diff --git a/.gitattributes b/.gitattributes index d0f0d3df..ded6cb71 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,17 +1,9 @@ # These files are text eol=lf and should be normalized (convert crlf => lf) -*.cs text eol=lf diff=csharp -*.xaml text eol=lf -*.csproj text eol=lf -*.sln text eol=lf -*.tt text eol=lf -*.ps1 text eol=lf -*.cmd text eol=lf -*.msbuild text eol=lf -*.md text eol=lf - +* text=auto eol=lf +*.{cmd,[cC][mM][dD]} text eol=crlf +*.{bat,[bB][aA][tT]} text eol=crlf # Images should be treated as binary # (binary is a macro for -text eol=lf -diff) *.png binary *.jepg binary - *.sdf binary diff --git a/.github/workflows/dotnet.yml b/.github/workflows/dotnet.yml new file mode 100644 index 00000000..fff48955 --- /dev/null +++ b/.github/workflows/dotnet.yml @@ -0,0 +1,27 @@ +name: dotnet + +on: + push: + branches: [ develop ] + pull_request: + branches: [ develop ] + +jobs: + build: + + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 # Required for Nerdbank.GitVersioning + - name: Setup .NET + uses: actions/setup-dotnet@v4 + with: + dotnet-version: '8.0.x' + - name: Restore dependencies + run: dotnet restore + - name: Build + run: dotnet build --no-restore + - name: Test + run: dotnet test --no-build --verbosity normal --filter "Category!=Network&Category!=Benchmark" diff --git a/.github/workflows/publish-nuget.yml b/.github/workflows/publish-nuget.yml new file mode 100644 index 00000000..16969201 --- /dev/null +++ b/.github/workflows/publish-nuget.yml @@ -0,0 +1,63 @@ +name: Publish NuGet Packages + +on: + push: + tags: + - 'v*' + +jobs: + publish: + runs-on: ubuntu-latest + + permissions: + packages: write + contents: read + + steps: + - name: Checkout (full history for Nerdbank.GitVersioning) + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Setup .NET + uses: actions/setup-dotnet@v4 + with: + dotnet-version: '8.0.x' + + - name: Add GitHub Packages source + run: | + dotnet nuget add source \ + "https://nuget.pkg.github.com/OpenSim-NGC/index.json" \ + --name "github" \ + --username "${{ github.actor }}" \ + --password "${{ secrets.GITHUB_TOKEN }}" \ + --store-password-in-clear-text + + - name: Restore dependencies + run: dotnet restore OpenMetaverse.sln + + - name: Build (Release) + run: dotnet build OpenMetaverse.sln -c Release --no-restore + + - name: Pack library projects + run: | + mkdir -p ./nupkgs + for proj in \ + OpenMetaverse.Types/OpenMetaverse.Types.csproj \ + OpenMetaverse.StructuredData/OpenMetaverse.StructuredData.csproj \ + OpenMetaverse/OpenMetaverse.csproj \ + OpenMetaverse.Rendering.Simple/OpenMetaverse.Rendering.Simple.csproj \ + OpenMetaverse.Rendering.Meshmerizer/OpenMetaverse.Rendering.Meshmerizer.csproj; do + dotnet pack "$proj" \ + -c Release \ + --no-build \ + --include-symbols \ + -o ./nupkgs + done + + - name: Publish packages to GitHub Packages + run: | + dotnet nuget push "./nupkgs/*.nupkg" \ + --api-key "${{ secrets.GITHUB_TOKEN }}" \ + --source "github" \ + --skip-duplicate diff --git a/.gitignore b/.gitignore index 9a7f6e27..52a02ba9 100644 --- a/.gitignore +++ b/.gitignore @@ -3,9 +3,12 @@ compile.bat *.userprefs *.suo *.cache - +*.csproj.lscache .vs/ [Oo]bj/ [Bb]in/ +[Bb]uild/ PublishProfiles/ - +build_log.txt +build_output.txt +build_status.txt \ No newline at end of file diff --git a/bin/Be.Windows.Forms.HexBox.dll b/AppData/Be.Windows.Forms.HexBox.dll similarity index 100% rename from bin/Be.Windows.Forms.HexBox.dll rename to AppData/Be.Windows.Forms.HexBox.dll diff --git a/bin/GlacialList.dll b/AppData/GlacialList.dll similarity index 100% rename from bin/GlacialList.dll rename to AppData/GlacialList.dll diff --git a/bin/GridImageUpload.exe.config b/AppData/GridImageUpload.exe.config similarity index 100% rename from bin/GridImageUpload.exe.config rename to AppData/GridImageUpload.exe.config diff --git a/AppData/ICSharpCode.SharpZipLib.dll b/AppData/ICSharpCode.SharpZipLib.dll new file mode 100755 index 00000000..3b268b7c Binary files /dev/null and b/AppData/ICSharpCode.SharpZipLib.dll differ diff --git a/bin/OpenMetaverse.Rendering.Linden.dll b/AppData/OpenMetaverse.Rendering.Linden.dll similarity index 100% rename from bin/OpenMetaverse.Rendering.Linden.dll rename to AppData/OpenMetaverse.Rendering.Linden.dll diff --git a/AppData/OpenMetaverse.dll.config b/AppData/OpenMetaverse.dll.config new file mode 100755 index 00000000..20b1df5e --- /dev/null +++ b/AppData/OpenMetaverse.dll.config @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/bin/SmartThreadPool.dll b/AppData/SmartThreadPool.dll similarity index 100% rename from bin/SmartThreadPool.dll rename to AppData/SmartThreadPool.dll diff --git a/bin/Tao.OpenGl.dll b/AppData/Tao.OpenGl.dll similarity index 100% rename from bin/Tao.OpenGl.dll rename to AppData/Tao.OpenGl.dll diff --git a/bin/Tao.OpenGl.dll.config b/AppData/Tao.OpenGl.dll.config similarity index 100% rename from bin/Tao.OpenGl.dll.config rename to AppData/Tao.OpenGl.dll.config diff --git a/bin/Tao.Platform.Windows.dll b/AppData/Tao.Platform.Windows.dll similarity index 100% rename from bin/Tao.Platform.Windows.dll rename to AppData/Tao.Platform.Windows.dll diff --git a/bin/WinGridProxy.exe.config b/AppData/WinGridProxy.exe.config similarity index 100% rename from bin/WinGridProxy.exe.config rename to AppData/WinGridProxy.exe.config diff --git a/AppData/XMLRPC.dll b/AppData/XMLRPC.dll new file mode 100755 index 00000000..e6fe0eb3 Binary files /dev/null and b/AppData/XMLRPC.dll differ diff --git a/bin/openmetaverse_data/avatar_lad.xml b/AppData/openmetaverse_data/avatar_lad.xml similarity index 69% rename from bin/openmetaverse_data/avatar_lad.xml rename to AppData/openmetaverse_data/avatar_lad.xml index 5d6b10c0..0c3fa9d4 100644 --- a/bin/openmetaverse_data/avatar_lad.xml +++ b/AppData/openmetaverse_data/avatar_lad.xml @@ -1,6 +1,6 @@ + version="2.0" wearable_definition_version="22"> @@ -21,6 +22,7 @@ pie_slice="2" name="Skull" joint="mHead" + location="ATTACH_HEAD" position="0 0 0.15" rotation="0 0 90" visible_in_first_person="false" /> @@ -28,9 +30,10 @@ @@ -38,18 +41,21 @@ @@ -78,9 +87,10 @@ @@ -91,6 +101,7 @@ pie_slice="7" name="Spine" joint="mChest" + location="ATTACH_BACK" position="-0.15 0 -0.1" rotation="0 -90 90" visible_in_first_person="true" /> @@ -101,6 +112,7 @@ pie_slice="6" name="Pelvis" joint="mPelvis" + location="ATTACH_PELVIS" position="0 0 -0.15" rotation="0 0 0" visible_in_first_person="true" /> @@ -111,6 +123,7 @@ pie_slice="6" name="Mouth" joint="mHead" + location="ATTACH_MOUTH" position="0.12 0 0.001" rotation="0 0 0" visible_in_first_person="false"/> @@ -121,6 +134,7 @@ pie_slice="7" name="Chin" joint="mHead" + location="ATTACH_CHIN" position="0.12 0 -0.04" rotation="0 0 0" visible_in_first_person="false" /> @@ -131,6 +145,7 @@ pie_slice="4" name="Left Ear" joint="mHead" + location="ATTACH_LEAR" position="0.015 0.08 0.017" rotation="0 0 0" visible_in_first_person="false" /> @@ -141,6 +156,7 @@ pie_slice="0" name="Right Ear" joint="mHead" + location="ATTACH_REAR" position="0.015 -0.08 0.017" rotation="0 0 0" visible_in_first_person="false" /> @@ -151,6 +167,7 @@ pie_slice="3" name="Left Eyeball" joint="mEyeLeft" + location="ATTACH_LEYE" position="0 0 0" rotation="0 0 0" visible_in_first_person="false"/> @@ -161,6 +178,7 @@ pie_slice="1" name="Right Eyeball" joint="mEyeRight" + location="ATTACH_REYE" position="0 0 0" rotation="0 0 0" visible_in_first_person="false" /> @@ -171,6 +189,7 @@ pie_slice="5" name="Nose" joint="mHead" + location="ATTACH_NOSE" position="0.1 0 0.05" rotation="0 0 0" visible_in_first_person="false"/> @@ -178,9 +197,10 @@ @@ -188,9 +208,10 @@ @@ -198,9 +219,10 @@ @@ -208,9 +230,10 @@ @@ -218,9 +241,10 @@ @@ -228,9 +252,10 @@ @@ -238,9 +263,10 @@ @@ -248,9 +274,10 @@ @@ -258,9 +285,10 @@ @@ -268,9 +296,10 @@ @@ -281,6 +310,7 @@ pie_slice="5" name="Stomach" joint="mPelvis" + location="ATTACH_BELLY" position="0.092 0.0 0.088" rotation="0 0 0" visible_in_first_person="true" /> @@ -291,6 +321,7 @@ pie_slice="3" name="Left Pec" joint="mTorso" + location="ATTACH_LEFT_PEC" position="0.104 0.082 0.247" rotation="0 0 0" visible_in_first_person="true" /> @@ -301,15 +332,17 @@ pie_slice="1" name="Right Pec" joint="mTorso" + location="ATTACH_RIGHT_PEC" position="0.104 -0.082 0.247" rotation="0 0 0" visible_in_first_person="true" /> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + name="mSpine3" + scale="0 0 .05" /> + + + + + + + + + + + + + + + + + @@ -514,8 +771,12 @@ scale="0 0 0.05" /> + name="mSpine3" + scale="0 0 0.05" /> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -586,10 +937,26 @@ name="mTorso" scale="0.1 0.1 0" /> + + + + + + + + @@ -605,6 +972,37 @@ + + + + + + + + + + + + + + + + + + + + + @@ -643,6 +1041,17 @@ + + + + + @@ -650,7 +1059,7 @@ id="37" group="0" name="Hip Width" - label="Hip Width" + label="Hip Width" wearable="shape" edit_group="shape_legs" edit_group_order="3" @@ -665,6 +1074,14 @@ name="mPelvis" scale="0 0.1 0" /> + + + + + + + + + + + + + + + @@ -693,7 +1129,19 @@ - + + + + + + + + + + + + + + + @@ -732,6 +1196,26 @@ + + + + + + + + + + @@ -755,10 +1239,82 @@ name="mEyeRight" scale="0 0 0" offset="0 -.009 0" /> - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -801,9 +1507,10 @@ name="mEyeRight" scale="0 0 0" offset=".016 0 0" /> + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -831,7 +1612,7 @@ id="655" group="1" name="Head Size" - label="Head Size" + label="Head Size" wearable="shape" edit_group="shape_head" label_min="Small Head" @@ -840,6 +1621,36 @@ value_min="-.25" value_max=".10"> + + + + + + + + + + + + + + - - - - - + + name="mFaceEyeAltLeft" + scale="1 1 1" + offset="0 0 -0.001" /> - - - - - + name="mFaceEyeAltRight" + scale="1 1 1" + offset="0 0 -0.001" /> + + name="mFaceForeheadLeft" + scale="1 1 1" + offset="0 0 0" /> - - + name="mFaceForeheadCenter" + scale="1 1 1" + offset="0 0 0" /> - - - - - - - - - - + name="mFaceEyebrowInnerLeft" + scale="1 1 1" + offset="0 0 0" /> + name="mFaceEyebrowOuterRight" + scale="1 1 1" + offset="0 0 0" /> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + id="197" + group="1" + wearable="shoes" + name="Shoe_Heels" + edit_group="shoes" + label_min="No Heels" + label_max="High Heels" + value_min="0" + value_max="1"> + name="mFootRight" + scale="0 0 0" + offset="0 0 -.08" /> + name="mFootLeft" + scale="0 0 0" + offset="0 0 -.08" /> + name="mHindLimb4Left" + scale="0 0 0" + offset="0 0 -.08" /> + name="mHindLimb4Right" + scale="0 0 0" + offset="0 0 -.08" /> + + + + + + + + + + + + + + + edit_group_order="10" + label_min="Small Hands" + label_max="Large Hands" + value_min="-.3" + value_max=".3" + camera_elevation=".1" + camera_distance="1.4" + camera_angle="0"> + name="mWristRight" + scale="1 1 1" + offset="0 0 0" /> + name="mWristLeft" + scale="1 1 1" + offset="0 0 0" /> - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + scale="1 1 0" + offset="0 0 0" /> - - - - - - - - - - - - + value_max="1"> + + + + + + + + + + + + + + + + + + + + + + + + - + camera_distance="2.5"> + + + + + + + + + + + + + + + + + - + value_default=".6" + camera_distance="1.5"> + + + + + + + + + - + value_default="0" + camera_elevation=".3" + camera_distance=".8" + camera_angle="15"> + + + - + - + value_default="0" + camera_distance="2.5"> + + + + + + + + + + + - + id="30004" + group="1" + name="Broad_Nostrils" + value_min="-.5" + value_max="1"> + + + + + + + + + + + + + - + id="30517" + group="1" + name="Wide_Nose" + value_min="-.5" + value_max="1"> + + + + + - - + id="30656" + group="1" + name="Crooked_Nose" + value_min="-2" + value_max="2"> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + name="Lip Width" + value_min="-0.9" + value_max="1.3" + value_default="0"> + + + + + + + + + + + + + + - - + name="Tall_Lips" + value_min="-1" + value_max="2"> + + + + + + + + + + + + + + + + + + + - - + value_max="0.7"> + + + + + + + + + + + + + + + + + + + + - - + value_max="1"> + + + + + + + + + + + + + + + + + + + + - + value_max="1.5"> + + + + + + + + + + + + + + + + + + + - + value_max="1.5"> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + value_max="1.4"> + + + + + + + + + + + + + + + + + - - + value_max="1.4"> + + + - - - + + + + + - - - + + + + + - - - + - - + + + + + + + + + + + + + + + + + + + + - - - + + + + + + - + value_max="2"> + + + + + + + + + + + + + + + + - - + value_max="2"> + + + + + + + + + + + + + + + + - + name="Big_Ears" + value_min="-1" + value_max="2"> + + + + - + - + name="Ears_Out" + value_min="-.5" + value_max="1.5"> + + + + + + + + + + + + - + - + id="30185" + group="1" + name="Deep_Chin" + value_min="-1" + value_max="1"> + + + + - - + + + + - + - + name="Jaw_Angle" + value_min="-1.2" + value_max="2" + value_default="0"> + + + - + + - - + name="Jaw_Jut" + value_min="-2" + value_max="2"> + - - - + + + + + + - + name="Bulbous_Nose_Tip" + value_min="-1" + value_max="1.5"> + + + + - + - + name="Weak_Chin" + value_min="-.5" + value_max=".5"> + + + + + + + + + + + + + + + + + - + + - - + - - - + - - - + + + - - - + + + - - - + - - + - + - - + name="Eyelid_Corner_Up" + value_min="-1.3" + value_max="1.2"> + + - - + + - + - - + name="Eyelid_Inner_Corner_Up" + value_min="-1.3" + value_max="1.2"> + + + + + + - + name="Puffy_Lower_Lids" + value_min="-.3" + value_max="2.5"> + + + + + + + + + + + - - + + + + + + + + + + - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - + - - + - - + + + + + + + + + + + - - + + - - + + - - + - - + + + + + + + + + + + + + + - - - - + value_max="2"> + + + + + + + + + + + + + + + + + + - + id="30011" + group="1" + name="Noble_Nose_Bridge" + value_min="-.5" + value_max="1.5"> + + + + + + + - + id="30758" + group="1" + name="Lower_Bridge_Nose" + value_min="-1.5" + value_max="1.5"> + + + + + + + + + + + + + + + - - + value_default="0.5"> + - - - + + + + + + - + id="30010" + group="1" + name="Sunken_Cheeks" + value_min="-1.5" + value_max="3"> + + + + + + - - + id="30017" + group="1" + name="Square_Jaw" + value_min="-0.5" + value_max="1"> + - - - + - - - + + + + + + + + + + + + + + + + + - - + value_max="2.5"> + - - - + + + + + + - + id="30021" + group="1" + name="Upper_Eyelid_Fold" + value_min="-0.2" + value_max="1.3"> + + + + + + + - - + value_max="1.5"> + - - + + + + + - - + value_max="1"> + - - - + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + value_default="0"> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + value_default="0.5"> + + + + + + + + + + + + + + + + - + id="30031" + group="1" + name="Arced_Eyebrows" + value_min="0" + value_max="2" + value_default=".5"> + + + + + + + + + + + + + + + + - + id="30757" + group="1" + name="Lower_Eyebrows" + value_min="-4" + value_max="2" + value_default="-1"> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + camera_distance=".5" + camera_angle="20"> + camera_distance=".5" + camera_angle="20"> + camera_distance=".5" + camera_angle="90"> + camera_distance=".5" + camera_angle="90"> + camera_distance=".7" + camera_angle="90"> + camera_distance=".5" + camera_angle="20"> + name="Hair_Part_Middle" + label="Middle Part" + wearable="hair" + edit_group="hair_style" + edit_group_order="17" + label_min="No Part" + label_max="Part" + value_min="0" + value_max="2" + camera_elevation=".1" + camera_distance=".5" + camera_angle="0"> + name="Hair_Part_Right" + label="Right Part" + wearable="hair" + edit_group="hair_style" + edit_group_order="18" + label_min="No Part" + label_max="Part" + value_min="0" + value_max="2" + camera_elevation=".1" + camera_distance=".5" + camera_angle="0"> + value_max="2" + camera_elevation=".1" + camera_distance=".5" + camera_angle="0"> + camera_distance=".5" + camera_angle="20"> + value_max="1" + camera_elevation=".1" + camera_distance=".5" + camera_angle="20"> + clothing_morph="true" + name="Bangs_Front_Down" + label="Front Bangs Down" + wearable="hair" + edit_group="hair_style" + label_min="Bangs" + label_max="Bangs Down" + value_min="0" + value_max="5" + camera_elevation=".1" + camera_distance=".5" + camera_angle="20"> + name="Bangs_Sides_Up" + label="Side Bangs Up" + wearable="hair" + edit_group="hair_style" + label_min="Side Bangs" + label_max="Side Bangs Up" + value_min="0" + value_max="1" + camera_elevation=".1" + camera_distance=".5" + camera_angle="20"> - + value_max="2" + camera_elevation=".1" + camera_distance=".5" + camera_angle="20"> - + edit_group="hair_style" + label_min="Back Bangs" + label_max="Back Bangs Up" + value_min="0" + value_max="1" + camera_elevation=".1" + camera_distance=".5" + camera_angle="150"> - - - - - - - - + camera_distance=".5" + camera_angle="150"> - - - + @@ -2589,12 +4802,14 @@ + name="Hair_Back_Down" + label="Back Hair Down" + clothing_morph="true" + wearable="hair" + edit_group="hair_style" + label_min="Back Hair" + label_max="Back Hair Down" + value_min="0" + value_max="3" + camera_elevation=".1" + camera_distance=".5" + camera_angle="150"> + value_max="1" + camera_elevation=".1" + camera_distance=".5" + camera_angle="150"> + wearable="hair" + clothing_morph="true" + edit_group="hair_style" + edit_group_order="14.5" + label_min="Smooth Hair" + label_max="Rumpled Hair" + value_min="0" + value_max="1" + camera_elevation=".1" + camera_distance=".5" + camera_angle="20"> - + camera_elevation=".1" + camera_distance=".5" + camera_angle="90"> + + value_max="1" + camera_elevation=".1" + camera_distance=".5" + camera_angle="90"> + value_max="1" + camera_elevation=".1" + camera_distance=".5" + camera_angle="0"> + id="191" + group="1" + name="Hair_Tilt_Left" + label="Hair Tilted Left" + wearable="hair" + edit_group="hair_style" + label_min="Hair" + label_max="Tilt Left" + value_min="0" + value_max="1" + camera_elevation=".1" + camera_distance=".5" + camera_angle="0"> + id="192" + group="0" + name="Bangs_Part_Middle" + label="Part Bangs" + wearable="hair" + edit_group="hair_style" + edit_group_order="20" + label_min="No Part" + label_max="Part Bangs" + value_min="0" + value_max="1" + camera_elevation=".1" + camera_distance=".5" + camera_angle="0"> - + id="640" + group="1" + name="Hair_Egg_Head" + wearable="hair" + edit_group="hair_style" + cross_wearable="true" + value_min="-1.3" + value_max="1"> + id="641" + group="1" + name="Hair_Squash_Stretch_Head" + wearable="hair" + edit_group="hair_style" + cross_wearable="true" + value_min="-.5" + value_max="1"> + value_max="1"> + value_max="1"> + value_max="1"> + value_max="1"> + value_max="2"> - - - + value_max="1"> + + value_default="-0.3" + camera_elevation=".1" + camera_distance=".5" + camera_angle="100"> + camera_distance=".5" + camera_angle="30"> - - - - - - - - + camera_angle="160"> + id="755" + group="0" + name="Hair_Taper_Front" + wearable="hair" + edit_group="hair_style" + edit_group_order="13" + label="Taper Front" + label_min="Wide Front" + label_max="Narrow Front" + value_min="-1.5" + value_max="1.5" + value_default="0.05" + camera_elevation=".1" + camera_distance=".5" + camera_angle="20"> - - + + + + + + + + + + + + + + + + + + + + + name="Big_Brow" + value_min="-.3" + value_max="2"> + name="Nose_Big_Out" + value_min="-0.8" + value_max="2.5"> + name="Bulbous_Nose" + value_min="-.5" + value_max="1.5"> - + + name="Crooked_Nose" + value_min="-2" + value_max="2"> - + + name="Tall_Lips" + value_min="-1" + value_max="2"> - + + name="Mouth_Height" + value_min="-2" + value_max="2"> - + - - + name="Lip_Cleft_Deep" + value_min="-.5" + value_max="1.2"> + + - + name="Wide_Lip_Cleft" + value_min="-.8" + value_max="1.5"> + - + + name="Shift_Mouth" + value_min="-2" + value_max="2" + value_default="0"> - + - + name="Big_Ears" + value_min="-1" + value_max="2"> + - + - + name="Ears_Out" + value_min="-.5" + value_max="1.5"> + - - - + + name="Pointy_Ears" + value_min="-.4" + value_max="3"> - + - - + + name="Jaw_Jut" + value_min="-2" + value_max="2"> - + + name="Wide_Eyes" + value_min="-1.5" + value_max="2"> - - + + name="Eyelid_Corner_Up" + value_min="-1.3" + value_max="1.2"> - + + name="Puffy_Lower_Lids" + value_min="-.3" + value_max="2.5"> + name="Low_Septum_Nose" + value_min="-1" + value_max="1.5" + value_default="0.5"> + id="5" + group="0" + name="Cleft_Chin" + label="Chin Cleft" + wearable="shape" + edit_group="shape_chin" + edit_group_order="6" + label_min="Round" + label_max="Cleft" + value_min="-.1" + value_max="1" + camera_elevation="0" + camera_distance=".28" + camera_angle="-20"> + name="Weak_Chin" + value_min="-.5" + value_max=".5"> + name="Double_Chin" + value_min="-.5" + value_max="1.5"> - - - - - - - - - - - - - - - - + name="Sunken_Cheeks" + value_min="-1.5" + value_max="3"> + name="Noble_Nose_Bridge" + value_min="-.5" + value_max="1.5"> + id="20758" + group="1" + name="Lower_Bridge_Nose" + value_min="-1.5" + value_max="1.5"> + camera_distance=".4" + camera_angle="0"> + edit_group="shape_chin" + edit_group_order="7" + label_min="Round" + label_max="Cleft" + value_min="0" + value_max="1.5" + camera_elevation="0" + camera_distance=".28" + camera_angle="-20"> + name="High_Cheek_Bones" + value_min="-.5" + value_max="1"> + + camera_distance=".3"> + name="Square_Jaw" + value_min="-.5" + value_max="1"> + id="20018" + group="1" + name="Puffy_Upper_Cheeks" + value_min="-1.5" + value_max="2.5"> + id="20019" + group="1" + name="Upturned_Nose_Tip" + value_min="-1.5" + value_max="1"> - - + + id="20021" + group="1" + name="Upper_Eyelid_Fold" + value_min="-0.2" + value_max="1.3"> + edit_group="shape_ears" + edit_group_order="3" + label_min="Unattached" + label_max="Attached" + value_min="0" + value_max="1" + camera_elevation=".1" + camera_distance=".3" + camera_angle="45"> + name="Baggy_Eyes" + value_min="-.5" + value_max="1.5"> - + value_max=".7"> + name="Wide_Nose_Bridge" + value_min="-1.3" + value_max="1.2"> + value_max="2"> + name="Wide_Upper_Lip" + wearable="shape" + edit_group="driven" + value_min="-.7" + value_max="1.3"> + name="Wide_Lower_Lip" + wearable="shape" + edit_group="driven" + value_min="-.7" + value_max="1.3"> + + + name="Lower_Eyebrows" + label="Eyebrow Height" + show_simple="true" + wearable="hair" + edit_group="hair_eyebrows" + edit_group_order="2.5" + label_min="Higher" + label_max="Lower" + value_min="-2" + value_max="2"> + name="Egg_Head" + label="Egg Head" + wearable="shape" + edit_group="shape_head" + label_min="Chin Heavy" + label_max="Forehead Heavy" + value_min="-1.3" + value_max="1" + camera_elevation=".1" + camera_distance=".5" + camera_angle="20"> - + name="Squash_Stretch_Head" + label="Squash/Stretch Head" + wearable="shape" + edit_group="shape_head" + label_min="Squash Head" + label_max="Stretch Head" + value_min="-.5" + value_max="1" + camera_elevation=".1" + camera_distance=".5" + camera_angle="20"> + + + + value_max=".7" + camera_elevation=".1" + camera_distance=".5" + camera_angle="20"> + value_max="1" + camera_elevation=".1" + camera_distance=".5" + camera_angle="20"> + name="Eye_Spread" + wearable="shape" + edit_group="shape_eyes" + label_min="Eyes Together" + label_max="Eyes Spread" + value_min="-2" + value_max="2"> + value_max="2"> - + value_max="1" + camera_elevation=".3"> + + id="20880" + group="1" + name="Eyelid_Inner_Corner_Up" + value_min="-1.3" + value_max="1.2"> - - + + value_max="1.4" + camera_distance=".3" + camera_elevation=".04"> - + value_max="1.2" + camera_distance=".3" + camera_elevation=".04"> + value_max="1.5" + camera_distance=".3" + camera_elevation=".04"> - - - - - - - + value_max="1.5" + camera_distance=".3" + camera_elevation=".04"> + + label="Shear Face" + edit_group="shape_head" + label_min="Shear Left" + label_max="Shear Right" + value_min="-2" + value_max="2" + value_default="0" + camera_distance=".5" + camera_elevation=".04"> - + value_default="0" + camera_distance=".5" + camera_elevation=".04"> + + + + id="664" + group="0" + name="Pop_Eye" + wearable="shape" + label="Eye Pop" + edit_group="shape_eyes" + edit_group_order="8" + label_min="Pop Right Eye" + label_max="Pop Left Eye" + value_min="-1.3" + value_max="1.3" + value_default="0" + camera_elevation=".1" + camera_distance=".35"> + + + + - - - - - - - - + label="Eye Size" + edit_group="shape_eyes" + label_min="Beady Eyes" + label_max="Anime Eyes" + show_simple="true" + value_min="-2" + value_max="2" + value_default="0"> + + + + + + + - - - - - - - - - - + value_max="1"> + - - - - - - - - - - + value_max="1"> + - - - - - - - - - - - - + value_max="1"> + - - - - + value_max="1"> + value_max="1"> - - - + name="Express_Shrug_Emote" + value_min="0" + value_max="1"> + + id="306" + group="1" + name="Express_Kiss" + value_min="0" + value_max="1"> - + + id="307" + group="1" + name="Express_Bored_Emote" + value_min="0" + value_max="1"> - - - - - - - - - - - - - + - + + + value_min="0" + value_max="1"> + name="Old" + value_min="0" + value_max="1"> + + name="Surprised_Eyebrows" + value_min="0" + value_max="1"> - + + + + + + + + + + + + + + + + + + + + + reference="avatar_head.llm"> + reference="avatar_head.llm"> + reference="avatar_head.llm"> + reference="avatar_head.llm"> - - + label="Shear Face" + edit_group="shape_head" + label_min="Shear Left" + label_max="Shear Right" + value_min="-2" + value_max="2" + value_default="0" + camera_distance=".5" + camera_elevation=".04"> - - - - + label="Shear Face" + edit_group="shape_head" + label_min="Flat Head" + label_max="Long Head" + value_min="-1" + value_max="1" + value_default="0" + camera_distance=".5" + camera_elevation=".04"> + - - - + label="Eye Pop" + edit_group="shape_eyes" + edit_group_order="8" + label_min="Pop Right Eye" + label_max="Pop Left Eye" + value_min="-2" + value_max="2" + value_default="0" + camera_distance=".5" + camera_elevation=".04" + camera_angle="-20"> + - - - - - - + edit_group="shape_head" + label_min="Chin Heavy" + label_max="Forehead Heavy" + value_min="-1.3" + value_max="1" + camera_elevation=".1" + camera_distance=".5" + camera_angle="20"> + - - - - - - + edit_group="shape_head" + label_min="Squash Head" + label_max="Stretch Head" + value_min="-.5" + value_max="1" + camera_elevation=".1" + camera_distance=".5" + camera_angle="20"> + + + + + - - - - - - + label="Eyelash Length" + edit_group="shape_eyes" + edit_group_order="7" + label_min="Short" + label_max="Long" + value_min="-.3" + value_max="1.5" + camera_elevation=".1" + camera_distance=".30" + camera_angle="-20"> + + name="Head_Eyes_Big" + wearable="shape" + label="Eye Size" + edit_group="shape_eyes" + label_min="Beady Eyes" + label_max="Anime Eyes" + value_min="-2" + value_max="2" + show_simple="true" + value_default="0"> + name="Bug_Eyed_Head" + wearable="shape" + label="Eye Depth" + edit_group="shape_eyes" + edit_group_order="4.5" + label_min="Sunken Eyes" + label_max="Bug Eyes" + value_min="-2" + value_max="2" + value_default="0"> + shared="1" + id="20021" + group="1" + name="Upper_Eyelid_Fold" + value_min="-0.2" + value_max="1.3"> + name="Wide_Eyes" + value_min="-1.5" + value_max="2"> + name="Eyelid_Corner_Up" + value_min="-1.3" + value_max="1.2"> + + + + + + value_max="1"> + value_max="1"> + value_max="1"> - - - - + shared="1" + id="304" + group="1" + name="Express_Embarrassed_Emote" + value_min="0" + value_max="1"> + + value_max="1"> + value_max="1"> + value_max="1"> + value_max="1"> - - - - - - - + - - - - + name="Express_Afraid_Emote" + value_min="0" + value_max="1"> + + shared="1" + id="312" + group="1" + name="Express_Cry_Emote" + value_min="0" + value_max="1"> - - - - - - - - - - - - - - - - - - - - - - - + name="Express_Toothsmile" + value_min="0" + value_max="1"> - - - - - - - + name="Express_Smile" + value_min="0" + value_max="1"> + + name="Old" + value_min="0" + value_max="1"> - - - - + + name="Blink_Left" + value_min="0" + value_max="1"> + name="Blink_Right" + value_min="0" + value_max="1"> + - + type="upperBodyMesh" + lod="0" + file_name="avatar_upper_body.llm" + min_pixel_width="320"> + - + edit_group="driven" + value_min="0" + value_max="1"> + + + + - - - - - - - + value_max="1" + camera_elevation=".1" + camera_distance="1" + camera_angle="15"> + + + + - + value_max="1" + camera_elevation="0" + camera_distance=".28"> + + + + - + value_max="1" + camera_elevation="0" + camera_distance=".28"> + + + + - + value_max="1.4" + camera_elevation=".3" + camera_distance="1.2"> + + + + + + + + - - - - - + value_max="1.4" + camera_elevation=".3" + camera_distance="1.2"> + + + + + + + + - + value_max="1.3" + camera_elevation=".3" + camera_distance="1.2"> + + + + + + + + + + + - - - - - + value_max="1.3" + camera_elevation=".3" + camera_distance="1.2"> + + + + + + + + + + + - + camera_elevation=".3"> + + + + + + + + + + + + + + + + + + + + + + + + + + - + id="840" + group="0" + name="Shirtsleeve_flair" + label="Sleeve Looseness" + show_simple="true" + wearable="shirt" + edit_group="shirt" + edit_group_order="6" + clothing_morph="true" + label_min="Tight Sleeves" + label_max="Loose Sleeves" + value_min="0" + value_max="1.5" + camera_distance="1.8" + camera_angle="30" + camera_elevation="-.3"> - - + value_max="2"> + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - + sex="female" + name="Breast_Female_Cleavage" + label="Breast Cleavage" + wearable="shape" + edit_group="shape_torso" + edit_group_order="8" + label_min="Separate" + label_max="Join" + value_default="0" + value_min="-.3" + value_max="1.3" + camera_elevation=".3" + camera_distance=".8"> + + + + - + - - - + sex="male" + name="Chest_Male_No_Pecs" + label="Pectorals" + wearable="shape" + edit_group="shape_torso" + edit_group_order="5" + label_min="Big Pectorals" + label_max="Sunken Chest" + value_default="0" + value_min="-0.5" + value_max="1.1" + camera_elevation=".3" + camera_distance="1.2"> + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + value_max="1"> + + + + + + + + + + + + + + + - - + value_max="1"> + + - - + + - - + value_max="1"> + + - - + + - - + value_max="1"> + + - + + + - + + + - + + + - + + + - + + + - + + + - - + + - - - - - - - - - - - - + value_max="1"> + + - - + + + + + + + - - + + + + + + - - + + + + + - - + + + + + + - - + - - + - - + + - - + + - - + + - - + + - - + + + + + + - - - - + + + + - - - - - + value_max="1"> + + + + - - - - - - - - - - + + + + + + + + - - - + + + + + + + + - - + + + + + + + + - - - + + + - - + + + - + + + - - - - + + + - - - + + + - - - + + + - - + + + - - - - - - - - + + + - - + + + + + + + + + - - - + + + + + + - - - - - - + + + - - - + + + + + + + + + - - - - + + + + - - + - - - + + + - - - - + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + - - + + + + + + - - - + + + + + - - - + - - - - + - - - - + + - + + - + + - + + - + + + + + + + - + + + + - + + + + + - + + + + - + + + + + + - - - + + + + - - - - + + + + + - - - - - + + + + - - - - + + + + - - - + + + - + + + - - - - - - - - - - - - - + + + - - - + + + - - - - + + + - - - - + + + - + + + - + + + - + + + - + + + - + + + + - + + + + - + - + + - + + - + + - + + - - - - - - - + + + + + - + - + - + + + - + + + + + - + + + - + - + - + - - - + - - - + - - - + - - - - + + + + - - - - + + + + + - + - + - + - + - + - + - + - + - + - + + + - + + + - + + + - + + + - + + + - + + + - + - + - + - + - + - + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + color="0, 0, 0, 255" /> + color="255, 0, 0, 255" /> - + value_default="1"> + + color="0, 0, 0, 255" /> + color="0, 255, 0, 255" /> - + value_default="1"> + + + + + + + + + + + + + + + name="head bump definition" + render_pass="bump"> + + + + + value_max="1"> + domain="0" /> + + + + + + + + + + + + + value_max="1"> + color="0, 0, 0, 0" /> - + color="0, 0, 0, 128" /> + + + - - + + - - - + + +color="255, 255, 255, 0" /> + - + color="255, 255, 255, 64" /> + + + + + - + + + color="198, 71, 71, 0" /> - + color="198, 71, 71, 255" /> + + + - + + + + + + color="220, 115, 115, 0" /> - + + name="wrinkles_shading" + render_pass="bump" + fixed_color="0,0,0,100"> + + + + + + + + + + + + + tga_file="eyebrows_alpha.tga" + domain="0.1" /> - - - - - - - - - - - - + color="255,255,255,0" /> + color="255,255,255,255" /> - - - - - - - - - + value_max="1" + value_default="0.5"> - - - - + color="255,255,255,0" /> + color="255,255,255,255" /> - - - - - - - - - - + name="lipstick"> + value_default=".25" + camera_distance=".25"> + color="245,161,177,200" /> - - + color="216,37,67,200" /> - - + color="178,48,76,200" /> - - + color="68,0,11,200" /> - - + color="252,207,184,200" /> - - + color="241,136,106,200" /> - + + - + - - - - - - + + + + value_max=".9" + value_default="0.0" + camera_distance=".25"> + tga_file="lipstick_alpha.tga" + skip_if_zero="true" + domain="0.05" /> - - - - - - - - - - + name="lipgloss" + fixed_color="255,255,255,190"> - - - - - + value_max="1" + camera_distance=".25"> + - + name="blush"> + + + + value_max="1" + value_default=".5" + camera_distance=".3" + camera_elevation=".07" + camera_angle="20"> + color="253,162,193,200" /> - - - + color="247,131,152,200" /> - - - + - - - - - + - - + - - + color="195,128,122,200" /> + color="148,103,100,200" /> + + - + value_default=".5" + camera_distance=".3" + camera_elevation=".07" + camera_angle="20"> + + color="255,255,255,0" /> + color="255,255,255,255" /> + + + camera_distance=".3" + camera_elevation=".14"> + color="252,247,246,255" /> - - + color="255,206,206,255" /> - + + - - + - - - + - - - + - - - + - - - - + - - + - - + color="223,227,213,255" /> - - + color="96,116,87,255" /> - - + color="88,143,107,255" /> - - + color="194,231,223,255" /> - - + color="207,227,234,255" /> - - + color="41,171,212,255" /> - - - + - - - + - - + + + + + + + + + + + + + + - + value_default=".6" + camera_distance=".3" + camera_elevation=".14"> + + + + + - - + value_max=".7" + camera_distance=".3" + camera_elevation=".14"> + domain="0.05" /> + + + camera_distance=".3" + camera_elevation=".14"> + color="252,247,246,255" /> + color="255,206,206,255" /> + color="233,135,149,255" /> + color="220,168,192,255" /> + color="228,203,232,255" /> + color="255,234,195,255" /> + color="230,157,101,255" /> + color="255,147,86,255" /> - - - + color="228,110,89,255" /> - - + - - - + - - - - + - - + - - + color="194,231,223,255" /> - - + color="207,227,234,255" /> - - + color="41,171,212,255" /> + color="180,137,130,255" /> + + + + + + + + + + + + + + + + - + value_default=".7" + camera_distance=".3" + camera_elevation=".14"> + + color="255,255,255,0" /> + color="255,255,255,255" /> + value_default="0" + camera_distance=".3" + camera_elevation=".14"> + tga_file="eyeshadow_inner_alpha.tga" + skip_if_zero="true" + domain="0.2" /> + + + value_default="0.0" + camera_distance=".3" + camera_elevation=".14"> + tga_file="eyeliner_alpha.tga" + skip_if_zero="true" + domain="0.1" /> - - - - + camera_distance=".3" + camera_elevation=".14"> + color="24,98,40,250" /> + + color="9,100,127,250" /> + + + + + + + + + + + + + + + + + + + + + + + + + + + + name="Sideburns bump" + value_min="0" + value_max="1"> + domain="0.05" /> + domain="0.1" /> + domain="0.03" /> + + + + + + + + + name="facialhair" + global_color="hair_color"> + + tga_file="head_hair.tga" + file_is_mask="false" /> + value_max="1"> + tga_file="facehair_sideburns_alpha.tga" + skip_if_zero="true" + domain="0.05" /> + tga_file="facehair_soulpatch_alpha.tga" + skip_if_zero="true" + domain="0.1" /> + tga_file="facehair_chincurtains_alpha.tga" + skip_if_zero="true" + domain="0.03" /> + + + + + + + + + name="head_bodypaint"> - + local_texture="head_bodypaint" /> + + + + + - + local_texture="head_alpha" /> + + + + value_default="1"> + color="0, 0, 0, 255" /> + color="255, 0, 0, 255" /> - - + value_max="1" + value_default="1"> + + - - + + - - + value_max="1" + value_default="1"> + + - - + + - + + name="head_universal_tattoo"> - + local_texture="head_universal_tattoo" /> @@ -7626,11 +10109,11 @@ render_pass="bump"> @@ -7644,11 +10127,11 @@ render_pass="bump"> @@ -7661,260 +10144,324 @@ render_pass="bump"> - - - + - - - + + + + + + + + + value_max="1"> + domain="0" /> + + + + + + + + + + + + - + value_max="1"> + + + + + + name="highlight"> + tga_file="upperbody_highlights_alpha.tga" + file_is_mask="TRUE" /> - + + + + + + + + + + + + tga_file="upperbodyfreckles_alpha.tga" + skip_if_zero="true" + domain="0.6" /> + + + + - + value_max="1" + value_default="1"> + + + + + - + value_max="1" + value_default="1"> + + + + + - + value_max="1" + value_default="1"> + + + + + - + + name="upper_universal_tattoo"> - - - - + local_texture="upper_universal_tattoo" /> + id="1232" + group="1" + edit_group="colorpicker_driven" + wearable="universal" + name="tattoo_upper_universal_red" + value_min="0" + value_max="1" + value_default="1"> + color="0, 0, 0, 255" /> + color="255, 0, 0, 255" /> - + value_max="1" + value_default="1"> + + + + + - + value_max="1" + value_default="1"> + + + + + + + + + + + + + + + value_max="1" + value_default=".8"> + value_max="1" + value_default=".8"> + domain="0.05" /> + value_max="1" + value_default=".8"> + domain="0.05" /> + name="upper_undershirt"> + local_texture="upper_undershirt" /> @@ -7928,11 +10475,11 @@ render_pass="bump"> @@ -7946,11 +10493,11 @@ render_pass="bump"> @@ -7964,320 +10511,185 @@ render_pass="bump"> + wearable="undershirt" + edit_group="driven" + name="Sleeve Length" + value_min=".01" + value_max="1" + value_default=".4"> + value_max="1" + value_default=".8"> + value_max="1" + value_default=".8"> + value_default=".8"> + domain="0.05" /> + + + value_default="0.0" + camera_distance="1.6" + camera_elevation="-.4" + camera_angle="70"> + tga_file="nailpolish_alpha.tga" + skip_if_zero="true" + domain="0.1" /> - - - - - - - - - - - - - - - - - - - - - - - - - - + value_max="1" + camera_distance="1.6" + camera_elevation="-.4" + camera_angle="70"> - - - - - - - - + color="255,187,200,255" /> - - + color="194,102,127,255" /> - - - - - - - - - - - - - - - - - - - - + color="227,34,99,255" /> - - + color="168,41,60,255" /> - - + color="97,28,59,255" /> - - + color="234,115,93,255" /> - - + color="142,58,47,255" /> - - + color="114,30,46,255" /> + color="14,14,14,255" /> - + value_default=".8"> + value_default="1"> + tga_file="gloves_fingers_alpha.tga" + multiply_blend="true" + domain="0.01" /> + name="upper_gloves"> + local_texture="upper_gloves" /> @@ -8291,11 +10703,11 @@ render_pass="bump"> @@ -8309,11 +10721,11 @@ render_pass="bump"> @@ -8327,168 +10739,282 @@ render_pass="bump"> + value_default=".8"> + value_default="1"> + tga_file="gloves_fingers_alpha.tga" + multiply_blend="true" + domain="0.01" /> + name="upper_clothes_shadow"> + local_texture="upper_shirt" /> - - - + value_default="0"> + + + + + + + + + + + + + + + + + + + + + + + + name="upper_shirt base bump" + render_pass="bump" + fixed_color="128,128,128,255"> + local_texture="upper_shirt" + local_texture_alpha_only="true" /> - - + value_max="0.85"> + + - - + + - - + value_max="1"> + + - - + + + + + + + + + value_default="0"> + color="255, 255, 255, 0" /> + color="255, 255, 255, 255" /> + value_max="0.85"> - - - + + + + value_max="1"> + multiply_blend="true" + tga_file="shirt_collar_alpha.tga" + domain="0.05" /> + + + + + name="upper_clothes"> + local_texture="upper_shirt" /> @@ -8502,11 +11028,11 @@ render_pass="bump"> @@ -8520,11 +11046,11 @@ render_pass="bump"> @@ -8538,127 +11064,166 @@ render_pass="bump"> + value_max="0.85" + value_default=".7"> - - - - - - - - - + value_default=".8"> + + name="Collar Front Height Cloth" + value_min="0" + value_max="1" + value_default=".8"> + multiply_blend="true" + tga_file="shirt_collar_alpha.tga" + domain="0.05" /> + name="Collar Back Height Cloth" + value_min="0" + value_max="1" + value_default=".8"> + multiply_blend="true" + tga_file="shirt_collar_back_alpha.tga" + domain="0.05" /> + + + + + + + + + + + + + tga_file="bump_shirt_wrinkles.tga" /> + + id="875" + group="1" + wearable="jacket" + name="jacket upper Wrinkles" + value_min="0" + value_max="1" + value_default="0"> @@ -8669,43 +11234,89 @@ render_pass="bump"> + + + + + + + + + + + + + name="upper_jacket"> + local_texture="upper_jacket" /> @@ -8719,11 +11330,11 @@ render_pass="bump"> @@ -8737,15 +11348,15 @@ render_pass="bump"> - + id="833" + group="1" + edit_group="colorpicker_driven" + wearable="jacket" + name="upper_jacket_blue" + value_min="0" + value_max="1" + value_default="1"> + @@ -8755,140 +11366,222 @@ render_pass="bump"> + + + + + value_max="1"> + value_max="1"> + multiply_blend="true" + tga_file="shirt_collar_back_alpha.tga" + domain="0.05" /> - - - - + value_max="1" + value_default=".8" + camera_distance="1.2" + camera_angle="30" + camera_elevation=".2"> + value_max="1" + value_default=".8" + camera_distance="1.2" + camera_angle="30" + camera_elevation=".2"> + + + + + + + + + + + tga_file="bump_lowerbody_base.tga" + file_is_mask="FALSE" /> + + + + + + - + tga_file="body_skingrain.tga" /> + + + + + value_max="1"> + color="0, 0, 0, 0" /> + color="0, 0, 0, 128" /> + + + + - + + + + + + + + + + + + + + + + tga_file="bodyfreckles_alpha.tga" + skip_if_zero="true" + domain="0.6" /> + name="lower_tattoo"> + local_texture="lower_tattoo" /> @@ -8902,11 +11595,11 @@ render_pass="bump"> @@ -8920,11 +11613,11 @@ render_pass="bump"> @@ -8937,101 +11630,114 @@ render_pass="bump"> + + + - - - - + + + + + + + + - + value_default="1"> + + + + + - - - - + + + - + + + - - - - - + name="lower_underpants bump" + render_pass="bump" + fixed_color="128,128,128,255"> - + local_texture="lower_underpants" + local_texture_alpha_only="true" /> - - - + + + - + + + + - - + name="lower_underpants"> + local_texture="lower_underpants" /> @@ -9045,11 +11751,11 @@ render_pass="bump"> @@ -9063,11 +11769,11 @@ render_pass="bump"> @@ -9079,123 +11785,2167 @@ render_pass="bump"> color="0, 0, 255, 255" /> - - + value_default=".3" + camera_distance="1.2" + camera_angle="30" + camera_elevation="-.3"> + tga_file="pants_length_alpha.tga" + domain="0.01" /> + value_default=".8"> + tga_file="pants_waist_alpha.tga" + domain="0.05" /> + + + + + value_default="0.35"> + tga_file="shoe_height_alpha.tga" + domain="0.01" /> + + + + - - + value_default="1"> + + + + + + + value_default="1"> + + + + + + + + + + + + + + + + + tga_file="shoe_height_alpha.tga" + domain="0.01" /> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + max1="1" max2="1" min2="1" /> + + + + @@ -9631,8 +14395,8 @@ render_pass="bump"> edit_group="shape_mouth" edit_group_order="3.2" name="Lip Ratio" - label="Lip Ratio" - show_simple="true" + label="Lip Ratio" + show_simple="true" label_min="More Upper Lip" label_max="More Lower Lip" value_min="0" @@ -9655,6 +14419,21 @@ render_pass="bump"> max1="1" max2="1" min2="1" /> + + + + + @@ -9680,6 +14459,10 @@ render_pass="bump"> + + + @@ -9890,6 +14673,10 @@ render_pass="bump"> max1="1" max2="1" min2="1" /> + + + @@ -10362,6 +15149,21 @@ render_pass="bump"> max1="1" max2="1" min2="1" /> + + + + + @@ -10388,6 +15190,14 @@ render_pass="bump"> + + + @@ -10414,6 +15224,10 @@ render_pass="bump"> + + + @@ -10444,7 +15258,7 @@ render_pass="bump"> min2=".5" /> min1=".5" max1="1" max2="1" + min2="1" /> + + + + + + + + + + + + @@ -10636,7 +15483,7 @@ render_pass="bump"> edit_group="shape_head" edit_group_order="1" name="Head Size" - label="Head Size" + label="Head Size" label_min="Small Head" label_max="Big Head" show_simple="true" @@ -10670,16 +15517,17 @@ render_pass="bump"> edit_group="shape_eyes" edit_group_order="1" name="Eye Size" - label="Eye Size" + label="Eye Size" label_min="Beady Eyes" label_max="Anime Eyes" value_min="0" value_max="1" value_default=".5" - show_simple="true" + show_simple="true" camera_elevation=".1" camera_distance=".35"> + @@ -10697,6 +15545,10 @@ render_pass="bump"> + + + @@ -10967,19 +15819,44 @@ render_pass="bump"> min2=".3" /> + id="151" + min1=".3" + max1="1" + max2="1" + min2="1" /> + + + + + + + + - - + + + + + @@ -11580,6 +16461,8 @@ render_pass="bump"> + @@ -11603,6 +16486,8 @@ render_pass="bump"> + @@ -11625,13 +16510,15 @@ render_pass="bump"> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/AppData/openmetaverse_data/avatar_skeleton.xml b/AppData/openmetaverse_data/avatar_skeleton.xml new file mode 100644 index 00000000..2241a125 --- /dev/null +++ b/AppData/openmetaverse_data/avatar_skeleton.xml @@ -0,0 +1,232 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/bin/openmetaverse_data/blush_alpha.tga b/AppData/openmetaverse_data/blush_alpha.tga similarity index 100% rename from bin/openmetaverse_data/blush_alpha.tga rename to AppData/openmetaverse_data/blush_alpha.tga diff --git a/bin/openmetaverse_data/body_skingrain.tga b/AppData/openmetaverse_data/body_skingrain.tga similarity index 100% rename from bin/openmetaverse_data/body_skingrain.tga rename to AppData/openmetaverse_data/body_skingrain.tga diff --git a/bin/openmetaverse_data/bodyfreckles_alpha.tga b/AppData/openmetaverse_data/bodyfreckles_alpha.tga similarity index 100% rename from bin/openmetaverse_data/bodyfreckles_alpha.tga rename to AppData/openmetaverse_data/bodyfreckles_alpha.tga diff --git a/bin/openmetaverse_data/bump_face_wrinkles.tga b/AppData/openmetaverse_data/bump_face_wrinkles.tga similarity index 100% rename from bin/openmetaverse_data/bump_face_wrinkles.tga rename to AppData/openmetaverse_data/bump_face_wrinkles.tga diff --git a/bin/openmetaverse_data/bump_head_base.tga b/AppData/openmetaverse_data/bump_head_base.tga similarity index 100% rename from bin/openmetaverse_data/bump_head_base.tga rename to AppData/openmetaverse_data/bump_head_base.tga diff --git a/bin/openmetaverse_data/bump_lowerbody_base.tga b/AppData/openmetaverse_data/bump_lowerbody_base.tga similarity index 100% rename from bin/openmetaverse_data/bump_lowerbody_base.tga rename to AppData/openmetaverse_data/bump_lowerbody_base.tga diff --git a/bin/openmetaverse_data/bump_pants_wrinkles.tga b/AppData/openmetaverse_data/bump_pants_wrinkles.tga similarity index 100% rename from bin/openmetaverse_data/bump_pants_wrinkles.tga rename to AppData/openmetaverse_data/bump_pants_wrinkles.tga diff --git a/bin/openmetaverse_data/bump_shirt_wrinkles.tga b/AppData/openmetaverse_data/bump_shirt_wrinkles.tga similarity index 100% rename from bin/openmetaverse_data/bump_shirt_wrinkles.tga rename to AppData/openmetaverse_data/bump_shirt_wrinkles.tga diff --git a/bin/openmetaverse_data/bump_upperbody_base.tga b/AppData/openmetaverse_data/bump_upperbody_base.tga similarity index 100% rename from bin/openmetaverse_data/bump_upperbody_base.tga rename to AppData/openmetaverse_data/bump_upperbody_base.tga diff --git a/bin/openmetaverse_data/eyebrows_alpha.tga b/AppData/openmetaverse_data/eyebrows_alpha.tga similarity index 100% rename from bin/openmetaverse_data/eyebrows_alpha.tga rename to AppData/openmetaverse_data/eyebrows_alpha.tga diff --git a/bin/openmetaverse_data/eyeliner_alpha.tga b/AppData/openmetaverse_data/eyeliner_alpha.tga similarity index 100% rename from bin/openmetaverse_data/eyeliner_alpha.tga rename to AppData/openmetaverse_data/eyeliner_alpha.tga diff --git a/bin/openmetaverse_data/eyeshadow_inner_alpha.tga b/AppData/openmetaverse_data/eyeshadow_inner_alpha.tga similarity index 100% rename from bin/openmetaverse_data/eyeshadow_inner_alpha.tga rename to AppData/openmetaverse_data/eyeshadow_inner_alpha.tga diff --git a/bin/openmetaverse_data/eyeshadow_outer_alpha.tga b/AppData/openmetaverse_data/eyeshadow_outer_alpha.tga similarity index 100% rename from bin/openmetaverse_data/eyeshadow_outer_alpha.tga rename to AppData/openmetaverse_data/eyeshadow_outer_alpha.tga diff --git a/bin/openmetaverse_data/eyewhite.tga b/AppData/openmetaverse_data/eyewhite.tga similarity index 100% rename from bin/openmetaverse_data/eyewhite.tga rename to AppData/openmetaverse_data/eyewhite.tga diff --git a/bin/openmetaverse_data/facehair_chincurtains_alpha.tga b/AppData/openmetaverse_data/facehair_chincurtains_alpha.tga similarity index 100% rename from bin/openmetaverse_data/facehair_chincurtains_alpha.tga rename to AppData/openmetaverse_data/facehair_chincurtains_alpha.tga diff --git a/bin/openmetaverse_data/facehair_moustache_alpha.tga b/AppData/openmetaverse_data/facehair_moustache_alpha.tga similarity index 100% rename from bin/openmetaverse_data/facehair_moustache_alpha.tga rename to AppData/openmetaverse_data/facehair_moustache_alpha.tga diff --git a/bin/openmetaverse_data/facehair_sideburns_alpha.tga b/AppData/openmetaverse_data/facehair_sideburns_alpha.tga similarity index 100% rename from bin/openmetaverse_data/facehair_sideburns_alpha.tga rename to AppData/openmetaverse_data/facehair_sideburns_alpha.tga diff --git a/bin/openmetaverse_data/facehair_soulpatch_alpha.tga b/AppData/openmetaverse_data/facehair_soulpatch_alpha.tga similarity index 100% rename from bin/openmetaverse_data/facehair_soulpatch_alpha.tga rename to AppData/openmetaverse_data/facehair_soulpatch_alpha.tga diff --git a/bin/openmetaverse_data/freckles_alpha.tga b/AppData/openmetaverse_data/freckles_alpha.tga similarity index 100% rename from bin/openmetaverse_data/freckles_alpha.tga rename to AppData/openmetaverse_data/freckles_alpha.tga diff --git a/bin/openmetaverse_data/glove_length_alpha.tga b/AppData/openmetaverse_data/glove_length_alpha.tga similarity index 100% rename from bin/openmetaverse_data/glove_length_alpha.tga rename to AppData/openmetaverse_data/glove_length_alpha.tga diff --git a/bin/openmetaverse_data/gloves_fingers_alpha.tga b/AppData/openmetaverse_data/gloves_fingers_alpha.tga similarity index 100% rename from bin/openmetaverse_data/gloves_fingers_alpha.tga rename to AppData/openmetaverse_data/gloves_fingers_alpha.tga diff --git a/bin/openmetaverse_data/head_alpha.tga b/AppData/openmetaverse_data/head_alpha.tga similarity index 100% rename from bin/openmetaverse_data/head_alpha.tga rename to AppData/openmetaverse_data/head_alpha.tga diff --git a/bin/openmetaverse_data/head_color.tga b/AppData/openmetaverse_data/head_color.tga similarity index 100% rename from bin/openmetaverse_data/head_color.tga rename to AppData/openmetaverse_data/head_color.tga diff --git a/bin/openmetaverse_data/head_hair.tga b/AppData/openmetaverse_data/head_hair.tga similarity index 100% rename from bin/openmetaverse_data/head_hair.tga rename to AppData/openmetaverse_data/head_hair.tga diff --git a/bin/openmetaverse_data/head_highlights_alpha.tga b/AppData/openmetaverse_data/head_highlights_alpha.tga similarity index 100% rename from bin/openmetaverse_data/head_highlights_alpha.tga rename to AppData/openmetaverse_data/head_highlights_alpha.tga diff --git a/bin/openmetaverse_data/head_shading_alpha.tga b/AppData/openmetaverse_data/head_shading_alpha.tga similarity index 100% rename from bin/openmetaverse_data/head_shading_alpha.tga rename to AppData/openmetaverse_data/head_shading_alpha.tga diff --git a/bin/openmetaverse_data/head_skingrain.tga b/AppData/openmetaverse_data/head_skingrain.tga similarity index 100% rename from bin/openmetaverse_data/head_skingrain.tga rename to AppData/openmetaverse_data/head_skingrain.tga diff --git a/bin/openmetaverse_data/jacket_length_lower_alpha.tga b/AppData/openmetaverse_data/jacket_length_lower_alpha.tga similarity index 100% rename from bin/openmetaverse_data/jacket_length_lower_alpha.tga rename to AppData/openmetaverse_data/jacket_length_lower_alpha.tga diff --git a/bin/openmetaverse_data/jacket_length_upper_alpha.tga b/AppData/openmetaverse_data/jacket_length_upper_alpha.tga similarity index 100% rename from bin/openmetaverse_data/jacket_length_upper_alpha.tga rename to AppData/openmetaverse_data/jacket_length_upper_alpha.tga diff --git a/bin/openmetaverse_data/jacket_open_lower_alpha.tga b/AppData/openmetaverse_data/jacket_open_lower_alpha.tga similarity index 100% rename from bin/openmetaverse_data/jacket_open_lower_alpha.tga rename to AppData/openmetaverse_data/jacket_open_lower_alpha.tga diff --git a/bin/openmetaverse_data/jacket_open_upper_alpha.tga b/AppData/openmetaverse_data/jacket_open_upper_alpha.tga similarity index 100% rename from bin/openmetaverse_data/jacket_open_upper_alpha.tga rename to AppData/openmetaverse_data/jacket_open_upper_alpha.tga diff --git a/bin/openmetaverse_data/lipgloss_alpha.tga b/AppData/openmetaverse_data/lipgloss_alpha.tga similarity index 100% rename from bin/openmetaverse_data/lipgloss_alpha.tga rename to AppData/openmetaverse_data/lipgloss_alpha.tga diff --git a/bin/openmetaverse_data/lips_mask.tga b/AppData/openmetaverse_data/lips_mask.tga similarity index 100% rename from bin/openmetaverse_data/lips_mask.tga rename to AppData/openmetaverse_data/lips_mask.tga diff --git a/bin/openmetaverse_data/lipstick_alpha.tga b/AppData/openmetaverse_data/lipstick_alpha.tga similarity index 100% rename from bin/openmetaverse_data/lipstick_alpha.tga rename to AppData/openmetaverse_data/lipstick_alpha.tga diff --git a/bin/openmetaverse_data/lowerbody_color.tga b/AppData/openmetaverse_data/lowerbody_color.tga similarity index 100% rename from bin/openmetaverse_data/lowerbody_color.tga rename to AppData/openmetaverse_data/lowerbody_color.tga diff --git a/bin/openmetaverse_data/lowerbody_highlights_alpha.tga b/AppData/openmetaverse_data/lowerbody_highlights_alpha.tga similarity index 100% rename from bin/openmetaverse_data/lowerbody_highlights_alpha.tga rename to AppData/openmetaverse_data/lowerbody_highlights_alpha.tga diff --git a/bin/openmetaverse_data/lowerbody_shading_alpha.tga b/AppData/openmetaverse_data/lowerbody_shading_alpha.tga similarity index 100% rename from bin/openmetaverse_data/lowerbody_shading_alpha.tga rename to AppData/openmetaverse_data/lowerbody_shading_alpha.tga diff --git a/bin/openmetaverse_data/nailpolish_alpha.tga b/AppData/openmetaverse_data/nailpolish_alpha.tga similarity index 100% rename from bin/openmetaverse_data/nailpolish_alpha.tga rename to AppData/openmetaverse_data/nailpolish_alpha.tga diff --git a/bin/openmetaverse_data/pants_length_alpha.tga b/AppData/openmetaverse_data/pants_length_alpha.tga similarity index 100% rename from bin/openmetaverse_data/pants_length_alpha.tga rename to AppData/openmetaverse_data/pants_length_alpha.tga diff --git a/bin/openmetaverse_data/pants_waist_alpha.tga b/AppData/openmetaverse_data/pants_waist_alpha.tga similarity index 100% rename from bin/openmetaverse_data/pants_waist_alpha.tga rename to AppData/openmetaverse_data/pants_waist_alpha.tga diff --git a/bin/openmetaverse_data/rosyface_alpha.tga b/AppData/openmetaverse_data/rosyface_alpha.tga similarity index 100% rename from bin/openmetaverse_data/rosyface_alpha.tga rename to AppData/openmetaverse_data/rosyface_alpha.tga diff --git a/bin/openmetaverse_data/rouge_alpha.tga b/AppData/openmetaverse_data/rouge_alpha.tga similarity index 100% rename from bin/openmetaverse_data/rouge_alpha.tga rename to AppData/openmetaverse_data/rouge_alpha.tga diff --git a/bin/openmetaverse_data/shirt_bottom_alpha.tga b/AppData/openmetaverse_data/shirt_bottom_alpha.tga similarity index 100% rename from bin/openmetaverse_data/shirt_bottom_alpha.tga rename to AppData/openmetaverse_data/shirt_bottom_alpha.tga diff --git a/bin/openmetaverse_data/shirt_collar_alpha.tga b/AppData/openmetaverse_data/shirt_collar_alpha.tga similarity index 100% rename from bin/openmetaverse_data/shirt_collar_alpha.tga rename to AppData/openmetaverse_data/shirt_collar_alpha.tga diff --git a/bin/openmetaverse_data/shirt_collar_back_alpha.tga b/AppData/openmetaverse_data/shirt_collar_back_alpha.tga similarity index 100% rename from bin/openmetaverse_data/shirt_collar_back_alpha.tga rename to AppData/openmetaverse_data/shirt_collar_back_alpha.tga diff --git a/bin/openmetaverse_data/shirt_sleeve_alpha.tga b/AppData/openmetaverse_data/shirt_sleeve_alpha.tga similarity index 100% rename from bin/openmetaverse_data/shirt_sleeve_alpha.tga rename to AppData/openmetaverse_data/shirt_sleeve_alpha.tga diff --git a/bin/openmetaverse_data/shoe_height_alpha.tga b/AppData/openmetaverse_data/shoe_height_alpha.tga similarity index 100% rename from bin/openmetaverse_data/shoe_height_alpha.tga rename to AppData/openmetaverse_data/shoe_height_alpha.tga diff --git a/bin/openmetaverse_data/skirt_length_alpha.tga b/AppData/openmetaverse_data/skirt_length_alpha.tga similarity index 100% rename from bin/openmetaverse_data/skirt_length_alpha.tga rename to AppData/openmetaverse_data/skirt_length_alpha.tga diff --git a/bin/openmetaverse_data/skirt_slit_back_alpha.tga b/AppData/openmetaverse_data/skirt_slit_back_alpha.tga similarity index 100% rename from bin/openmetaverse_data/skirt_slit_back_alpha.tga rename to AppData/openmetaverse_data/skirt_slit_back_alpha.tga diff --git a/bin/openmetaverse_data/skirt_slit_front_alpha.tga b/AppData/openmetaverse_data/skirt_slit_front_alpha.tga similarity index 100% rename from bin/openmetaverse_data/skirt_slit_front_alpha.tga rename to AppData/openmetaverse_data/skirt_slit_front_alpha.tga diff --git a/bin/openmetaverse_data/skirt_slit_left_alpha.tga b/AppData/openmetaverse_data/skirt_slit_left_alpha.tga similarity index 100% rename from bin/openmetaverse_data/skirt_slit_left_alpha.tga rename to AppData/openmetaverse_data/skirt_slit_left_alpha.tga diff --git a/bin/openmetaverse_data/skirt_slit_right_alpha.tga b/AppData/openmetaverse_data/skirt_slit_right_alpha.tga similarity index 100% rename from bin/openmetaverse_data/skirt_slit_right_alpha.tga rename to AppData/openmetaverse_data/skirt_slit_right_alpha.tga diff --git a/bin/openmetaverse_data/underpants_trial_female.tga b/AppData/openmetaverse_data/underpants_trial_female.tga similarity index 100% rename from bin/openmetaverse_data/underpants_trial_female.tga rename to AppData/openmetaverse_data/underpants_trial_female.tga diff --git a/bin/openmetaverse_data/underpants_trial_male.tga b/AppData/openmetaverse_data/underpants_trial_male.tga similarity index 100% rename from bin/openmetaverse_data/underpants_trial_male.tga rename to AppData/openmetaverse_data/underpants_trial_male.tga diff --git a/bin/openmetaverse_data/undershirt_trial_female.tga b/AppData/openmetaverse_data/undershirt_trial_female.tga similarity index 100% rename from bin/openmetaverse_data/undershirt_trial_female.tga rename to AppData/openmetaverse_data/undershirt_trial_female.tga diff --git a/bin/openmetaverse_data/upperbody_color.tga b/AppData/openmetaverse_data/upperbody_color.tga similarity index 100% rename from bin/openmetaverse_data/upperbody_color.tga rename to AppData/openmetaverse_data/upperbody_color.tga diff --git a/bin/openmetaverse_data/upperbody_highlights_alpha.tga b/AppData/openmetaverse_data/upperbody_highlights_alpha.tga similarity index 100% rename from bin/openmetaverse_data/upperbody_highlights_alpha.tga rename to AppData/openmetaverse_data/upperbody_highlights_alpha.tga diff --git a/bin/openmetaverse_data/upperbody_shading_alpha.tga b/AppData/openmetaverse_data/upperbody_shading_alpha.tga similarity index 100% rename from bin/openmetaverse_data/upperbody_shading_alpha.tga rename to AppData/openmetaverse_data/upperbody_shading_alpha.tga diff --git a/bin/openmetaverse_data/upperbodyfreckles_alpha.tga b/AppData/openmetaverse_data/upperbodyfreckles_alpha.tga similarity index 100% rename from bin/openmetaverse_data/upperbodyfreckles_alpha.tga rename to AppData/openmetaverse_data/upperbodyfreckles_alpha.tga diff --git a/CSJ2K/CSJ2K.csproj b/CSJ2K/CSJ2K.csproj deleted file mode 100644 index ee641e1f..00000000 --- a/CSJ2K/CSJ2K.csproj +++ /dev/null @@ -1,16 +0,0 @@ - - - Local - net48 - CSJ2K - CSJ2K - JPEG2000 decoding library - True - 1591,1574,0419,0618 - - true - - - - - \ No newline at end of file diff --git a/CSJ2K/Color/ChannelDefinitionMapper.cs b/CSJ2K/Color/ChannelDefinitionMapper.cs deleted file mode 100644 index 17f39081..00000000 --- a/CSJ2K/Color/ChannelDefinitionMapper.cs +++ /dev/null @@ -1,218 +0,0 @@ -/// ************************************************************************** -/// -/// $Id: ChannelDefinitionMapper.java,v 1.2 2002/08/08 14:06:53 grosbois Exp $ -/// -/// Copyright Eastman Kodak Company, 343 State Street, Rochester, NY 14650 -/// $Date $ -/// *************************************************************************** -/// -using CSJ2K.j2k.image; -namespace CSJ2K.Color -{ - - /// This class is responsible for the mapping between - /// requested components and image channels. - /// - /// - /// - /// - /// 1.0 - /// - /// Bruce A. Kern - /// - public class ChannelDefinitionMapper : ColorSpaceMapper - { - /// Factory method for creating instances of this class. - /// -- source of image data - /// - /// -- provides colorspace info - /// - /// ChannelDefinitionMapper instance - /// - /// - /// - public static new BlkImgDataSrc createInstance(BlkImgDataSrc src, ColorSpace csMap) - { - - return new ChannelDefinitionMapper(src, csMap); - } - - /// Ctor which creates an ICCProfile for the image and initializes - /// all data objects (input, working, and output). - /// - /// - /// -- Source of image data - /// - /// -- provides colorspace info - /// - protected internal ChannelDefinitionMapper(BlkImgDataSrc src, ColorSpace csMap) : base(src, csMap) - { - /* end ChannelDefinitionMapper ctor */ - } - - - /// Returns, in the blk argument, a block of image data containing the - /// specifed rectangular area, in the specified component. The data is - /// returned, as a copy of the internal data, therefore the returned data - /// can be modified "in place". - /// - ///

The rectangular area to return is specified by the 'ulx', 'uly', 'w' - /// and 'h' members of the 'blk' argument, relative to the current - /// tile. These members are not modified by this method. The 'offset' of - /// the returned data is 0, and the 'scanw' is the same as the block's - /// width. See the 'DataBlk' class. - /// - ///

If the data array in 'blk' is 'null', then a new one is created. If - /// the data array is not 'null' then it is reused, and it must be large - /// enough to contain the block's data. Otherwise an 'ArrayStoreException' - /// or an 'IndexOutOfBoundsException' is thrown by the Java system. - /// - ///

The returned data has its 'progressive' attribute set to that of the - /// input data. - /// - ///

- /// Its coordinates and dimensions specify the area to - /// return. If it contains a non-null data array, then it must have the - /// correct dimensions. If it contains a null data array a new one is - /// created. The fields in this object are modified to return the data. - /// - /// - /// The index of the component from which to get the data. Only 0 - /// and 3 are valid. - /// - /// - /// The requested DataBlk - /// - /// - /// - /// - /// - public override DataBlk getCompData(DataBlk out_Renamed, int c) - { - return src.getCompData(out_Renamed, csMap.getChannelDefinition(c)); - } - - /// Returns, in the blk argument, a block of image data containing the - /// specifed rectangular area, in the specified component. The data is - /// returned, as a copy of the internal data, therefore the returned data - /// can be modified "in place". - /// - ///

The rectangular area to return is specified by the 'ulx', 'uly', 'w' - /// and 'h' members of the 'blk' argument, relative to the current - /// tile. These members are not modified by this method. The 'offset' of - /// the returned data is 0, and the 'scanw' is the same as the block's - /// width. See the 'DataBlk' class. - /// - ///

This method, in general, is less efficient than the - /// 'getInternCompData()' method since, in general, it copies the - /// data. However if the array of returned data is to be modified by the - /// caller then this method is preferable. - /// - ///

If the data array in 'blk' is 'null', then a new one is created. If - /// the data array is not 'null' then it is reused, and it must be large - /// enough to contain the block's data. Otherwise an 'ArrayStoreException' - /// or an 'IndexOutOfBoundsException' is thrown by the Java system. - /// - ///

The returned data may have its 'progressive' attribute set. In this - /// case the returned data is only an approximation of the "final" data. - /// - ///

- /// Its coordinates and dimensions specify the area to return, - /// relative to the current tile. If it contains a non-null data array, - /// then it must be large enough. If it contains a null data array a new - /// one is created. Some fields in this object are modified to return the - /// data. - /// - /// - /// The index of the component from which to get the data. - /// - /// - /// - /// - /// - public override DataBlk getInternCompData(DataBlk out_Renamed, int c) - { - return src.getInternCompData(out_Renamed, csMap.getChannelDefinition(c)); - } - - /// Returns the number of bits, referred to as the "range bits", - /// corresponding to the nominal range of the data in the specified - /// component. If this number is b then for unsigned data the - /// nominal range is between 0 and 2^b-1, and for signed data it is between - /// -2^(b-1) and 2^(b-1)-1. For floating point data this value is not - /// applicable. - /// - /// - /// The index of the component. - /// - /// - /// The number of bits corresponding to the nominal range of the - /// data. Fro floating-point data this value is not applicable and the - /// return value is undefined. - /// - public override int getFixedPoint(int c) - { - return src.getFixedPoint(csMap.getChannelDefinition(c)); - } - - public override int getNomRangeBits(int c) - { - return src.getNomRangeBits(csMap.getChannelDefinition(c)); - } - - public override int getCompImgHeight(int c) - { - return src.getCompImgHeight(csMap.getChannelDefinition(c)); - } - - public override int getCompImgWidth(int c) - { - return src.getCompImgWidth(csMap.getChannelDefinition(c)); - } - - public override int getCompSubsX(int c) - { - return src.getCompSubsX(csMap.getChannelDefinition(c)); - } - - public override int getCompSubsY(int c) - { - return src.getCompSubsY(csMap.getChannelDefinition(c)); - } - - public override int getCompULX(int c) - { - return src.getCompULX(csMap.getChannelDefinition(c)); - } - - public override int getCompULY(int c) - { - return src.getCompULY(csMap.getChannelDefinition(c)); - } - - public override int getTileCompHeight(int t, int c) - { - return src.getTileCompHeight(t, csMap.getChannelDefinition(c)); - } - - public override int getTileCompWidth(int t, int c) - { - return src.getTileCompWidth(t, csMap.getChannelDefinition(c)); - } - - public override System.String ToString() - { - int i; - System.Text.StringBuilder rep = new System.Text.StringBuilder("[ChannelDefinitionMapper nchannels= ").Append(ncomps); - - for (i = 0; i < ncomps; ++i) - { - rep.Append(eol).Append(" component[").Append(i).Append("] mapped to channel[").Append(csMap.getChannelDefinition(i)).Append("]"); - } - - return rep.Append("]").ToString(); - } - - /* end class ChannelDefinitionMapper */ - } -} \ No newline at end of file diff --git a/CSJ2K/Color/ColorSpace.cs b/CSJ2K/Color/ColorSpace.cs deleted file mode 100644 index d3cbaeda..00000000 --- a/CSJ2K/Color/ColorSpace.cs +++ /dev/null @@ -1,409 +0,0 @@ -using ChannelDefinitionBox = CSJ2K.Color.Boxes.ChannelDefinitionBox; -using ColorSpecificationBox = CSJ2K.Color.Boxes.ColorSpecificationBox; -using ComponentMappingBox = CSJ2K.Color.Boxes.ComponentMappingBox; -using HeaderDecoder = CSJ2K.j2k.codestream.reader.HeaderDecoder; -using ImageHeaderBox = CSJ2K.Color.Boxes.ImageHeaderBox; -using PaletteBox = CSJ2K.Color.Boxes.PaletteBox; -/// ************************************************************************** -/// -/// $Id: ColorSpace.java,v 1.2 2002/07/25 16:31:11 grosbois Exp $ -/// -/// Copyright Eastman Kodak Company, 343 State Street, Rochester, NY 14650 -/// $Date $ -/// *************************************************************************** -/// -using ParameterList = CSJ2K.j2k.util.ParameterList; -using RandomAccessIO = CSJ2K.j2k.io.RandomAccessIO; -namespace CSJ2K.Color -{ - - /// This class analyzes the image to provide colorspace - /// information for the decoding chain. It does this by - /// examining the box structure of the JP2 image. - /// It also provides access to the parameter list information, - /// which is stored as a public final field. - /// - /// - /// - /// - /// 1.0 - /// - /// Bruce A. Kern - /// - public class ColorSpace - { - /// Retrieve the ICC profile from the images as - /// a byte array. - /// - /// the ICC Profile as a byte []. - /// - virtual public byte[] ICCProfile - { - get - { - return csbox.ICCProfile; - } - - } - /// Return the colorspace method (Profiled, enumerated, or palettized). - virtual public MethodEnum Method - { - get - { - return csbox.Method; - } - - } - /// Return number of channels in the palette. - virtual public PaletteBox PaletteBox - { - get - { - return pbox; - } - - } - /// Return number of channels in the palette. - virtual public int PaletteChannels - { - get - { - return pbox == null ? 0 : pbox.NumColumns; - } - - } - /// Is palettized predicate. - virtual public bool Palettized - { - get - { - return pbox != null; - } - - } - //UPGRADE_NOTE: Final was removed from the declaration of 'eol '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly System.String eol = System.Environment.NewLine; - - // Renamed for convenience: - internal const int GRAY = 0; - internal const int RED = 1; - internal const int GREEN = 2; - internal const int BLUE = 3; - - /// Parameter Specs - public ParameterList pl; - - /// Parameter Specs - public HeaderDecoder hd; - - /* Image box structure as pertains to colorspacees. */ - private PaletteBox pbox = null; - private ComponentMappingBox cmbox = null; - private ColorSpecificationBox csbox = null; - private ChannelDefinitionBox cdbox = null; - private ImageHeaderBox ihbox = null; - - /// Input image - private RandomAccessIO in_Renamed = null; - - /// Indent a String that contains newlines. - public static System.String indent(System.String ident, System.Text.StringBuilder instr) - { - return indent(ident, instr.ToString()); - } - - /// Indent a String that contains newlines. - public static System.String indent(System.String ident, System.String instr) - { - System.Text.StringBuilder tgt = new System.Text.StringBuilder(instr); - char eolChar = eol[0]; - int i = tgt.Length; - while (--i > 0) - { - if (tgt[i] == eolChar) - tgt.Insert(i + 1, ident); - } - return ident + tgt.ToString(); - } - - /// public constructor which takes in the image, parameterlist and the - /// image header decoder as args. - /// - /// input RandomAccess image file. - /// - /// provides information about the image header. - /// - /// provides parameters from the default and commandline lists. - /// - /// ColorSpaceException - /// - public ColorSpace(RandomAccessIO in_Renamed, HeaderDecoder hd, ParameterList pl) - { - this.pl = pl; - this.in_Renamed = in_Renamed; - this.hd = hd; - getBoxes(); - } - - /// Retrieve the various boxes from the JP2 file. - /// IOException - /// - protected internal void getBoxes() - { - //byte[] data; - int type; - long len = 0; - int boxStart = 0; - byte[] boxHeader = new byte[16]; - int i = 0; - - // Search the toplevel boxes for the header box - while (true) - { - in_Renamed.seek(boxStart); - in_Renamed.readFully(boxHeader, 0, 16); - // CONVERSION PROBLEM? - - len = (long)CSJ2K.Icc.ICCProfile.getInt(boxHeader, 0); - if (len == 1) - len = CSJ2K.Icc.ICCProfile.getLong(boxHeader, 8); // Extended - // length - type = CSJ2K.Icc.ICCProfile.getInt(boxHeader, 4); - - // Verify the contents of the file so far. - if (i == 0 && type != CSJ2K.j2k.fileformat.FileFormatBoxes.JP2_SIGNATURE_BOX) - { - throw new ColorSpaceException("first box in image not " + "signature"); - } - else if (i == 1 && type != CSJ2K.j2k.fileformat.FileFormatBoxes.FILE_TYPE_BOX) - { - throw new ColorSpaceException("second box in image not file"); - } - else if (type == CSJ2K.j2k.fileformat.FileFormatBoxes.CONTIGUOUS_CODESTREAM_BOX) - { - throw new ColorSpaceException("header box not found in image"); - } - else if (type == CSJ2K.j2k.fileformat.FileFormatBoxes.JP2_HEADER_BOX) - { - break; - } - - // Progress to the next box. - ++i; - boxStart = (int)(boxStart + len); - } - - // boxStart indexes the start of the JP2_HEADER_BOX, - // make headerBoxEnd index the end of the box. - long headerBoxEnd = boxStart + len; - - if (len == 1) - boxStart += 8; // Extended length header - - for (boxStart += 8; boxStart < headerBoxEnd; boxStart = (int)(boxStart + len)) - { - in_Renamed.seek(boxStart); - in_Renamed.readFully(boxHeader, 0, 16); - len = (long)CSJ2K.Icc.ICCProfile.getInt(boxHeader, 0); - if (len == 1) - throw new ColorSpaceException("Extended length boxes " + "not supported"); - type = (int)CSJ2K.Icc.ICCProfile.getInt(boxHeader, 4); - - switch (type) - { - - case CSJ2K.j2k.fileformat.FileFormatBoxes.IMAGE_HEADER_BOX: - ihbox = new ImageHeaderBox(in_Renamed, boxStart); - break; - - case CSJ2K.j2k.fileformat.FileFormatBoxes.COLOUR_SPECIFICATION_BOX: - csbox = new ColorSpecificationBox(in_Renamed, boxStart); - break; - - case CSJ2K.j2k.fileformat.FileFormatBoxes.CHANNEL_DEFINITION_BOX: - cdbox = new ChannelDefinitionBox(in_Renamed, boxStart); - break; - - case CSJ2K.j2k.fileformat.FileFormatBoxes.COMPONENT_MAPPING_BOX: - cmbox = new ComponentMappingBox(in_Renamed, boxStart); - break; - - case CSJ2K.j2k.fileformat.FileFormatBoxes.PALETTE_BOX: - pbox = new PaletteBox(in_Renamed, boxStart); - break; - - default: - break; - - } - } - - if (ihbox == null) - throw new ColorSpaceException("image header box not found"); - - if ((pbox == null && cmbox != null) || (pbox != null && cmbox == null)) - throw new ColorSpaceException("palette box and component " + "mapping box inconsistency"); - } - - - /// Return the channel definition of the input component. - public virtual int getChannelDefinition(int c) - { - if (cdbox == null) - return c; - else - return cdbox.getCn(c + 1); - } - - /// Return the colorspace (sYCC, sRGB, sGreyScale). - public virtual CSEnum getColorSpace() - { - return csbox.ColorSpace; - } - - /// Return bitdepth of the palette entries. - public virtual int getPaletteChannelBits(int c) - { - return pbox == null ? 0 : (int)pbox.getBitDepth(c); - } - - /// Return a palettized sample - /// requested - /// - /// of entry - /// - /// palettized sample - /// - public virtual int getPalettizedSample(int channel, int index) - { - return pbox == null ? 0 : pbox.getEntry(channel, index); - } - - /// Signed output predicate. - public virtual bool isOutputSigned(int channel) - { - return (pbox != null) ? pbox.isSigned(channel) : hd.isOriginalSigned(channel); - } - - /// Return a suitable String representation of the class instance. - public override System.String ToString() - { - System.Text.StringBuilder rep = new System.Text.StringBuilder("[ColorSpace is ").Append(csbox.MethodString).Append(Palettized ? " and palettized " : " ").Append(Method == MethodEnum.ENUMERATED ? csbox.ColorSpaceString : ""); - if (ihbox != null) - { - rep.Append(eol).Append(indent(" ", ihbox.ToString())); - } - if (cdbox != null) - { - rep.Append(eol).Append(indent(" ", cdbox.ToString())); - } - if (csbox != null) - { - rep.Append(eol).Append(indent(" ", csbox.ToString())); - } - if (pbox != null) - { - rep.Append(eol).Append(indent(" ", pbox.ToString())); - } - if (cmbox != null) - { - rep.Append(eol).Append(indent(" ", cmbox.ToString())); - } - return rep.Append("]").ToString(); - } - - /// Are profiling diagnostics turned on - /// yes or no - /// - public virtual bool debugging() - { - return pl.Get("colorspace_debug") != null && pl.Get("colorspace_debug").ToUpper().Equals("on".ToUpper()); - } - - - public enum MethodEnum - { - ICC_PROFILED, - ENUMERATED - } - public enum CSEnum - { - sRGB, - GreyScale, - sYCC, - esRGB, - Illegal, - Unknown - } - /* Enumeration Class */ - /* - /// method enumeration - //UPGRADE_NOTE: Final was removed from the declaration of 'ICC_PROFILED '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public const MethodEnum ICC_PROFILED = new MethodEnum("profiled"); - /// method enumeration - //UPGRADE_NOTE: Final was removed from the declaration of 'ENUMERATED '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public const MethodEnum ENUMERATED = new MethodEnum("enumerated"); - - /// colorspace enumeration - //UPGRADE_NOTE: Final was removed from the declaration of 'sRGB '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public const CSEnum sRGB = new CSEnum("sRGB"); - /// colorspace enumeration - //UPGRADE_NOTE: Final was removed from the declaration of 'GreyScale '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public const CSEnum GreyScale = new CSEnum("GreyScale"); - /// colorspace enumeration - //UPGRADE_NOTE: Final was removed from the declaration of 'sYCC '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public const CSEnum sYCC = new CSEnum("sYCC"); - /// colorspace enumeration - //UPGRADE_NOTE: Final was removed from the declaration of 'Illegal '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public const CSEnum Illegal = new CSEnum("Illegal"); - /// colorspace enumeration - //UPGRADE_NOTE: Final was removed from the declaration of 'Unknown '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public const CSEnum Unknown = new CSEnum("Unknown"); - - /// Typesafe enumeration class - /// 1.0 - /// - /// Bruce A Kern - /// - public class Enumeration - { - //UPGRADE_NOTE: Final was removed from the declaration of 'value '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public System.String value_Renamed; - public Enumeration(System.String value_Renamed) - { - this.value_Renamed = value_Renamed; - } - public override System.String ToString() - { - return value_Renamed; - } - } - - - /// Method enumeration class - /// 1.0 - /// - /// Bruce A Kern - /// - public class MethodEnum:Enumeration - { - public MethodEnum(System.String value_Renamed):base(value_Renamed) - { - } - } - - /// Colorspace enumeration class - /// 1.0 - /// - /// Bruce A Kern - /// - public class CSEnum:Enumeration - { - public CSEnum(System.String value_Renamed):base(value_Renamed) - { - } - } - */ - /* end class ColorSpace */ - } -} \ No newline at end of file diff --git a/CSJ2K/Color/ColorSpaceException.cs b/CSJ2K/Color/ColorSpaceException.cs deleted file mode 100644 index 2f01779f..00000000 --- a/CSJ2K/Color/ColorSpaceException.cs +++ /dev/null @@ -1,43 +0,0 @@ -/// ************************************************************************** -/// -/// $Id: ColorSpaceException.java,v 1.1 2002/07/25 14:52:00 grosbois Exp $ -/// -/// Copyright Eastman Kodak Company, 343 State Street, Rochester, NY 14650 -/// $Date $ -/// *************************************************************************** -/// -using System; -namespace CSJ2K.Color -{ - - /// This exception is thrown when the content of an - /// image contains an incorrect colorspace box - /// - /// - /// - /// - /// 1.0 - /// - /// Bruce A. Kern - /// - - [Serializable] - public class ColorSpaceException : System.Exception - { - - /// Contruct with message - /// returned by getMessage() - /// - public ColorSpaceException(System.String msg) : base(msg) - { - } - - - /// Empty constructor - public ColorSpaceException() - { - } - - /* end class ColorSpaceException */ - } -} \ No newline at end of file diff --git a/CSJ2K/Color/ColorSpaceMapper.cs b/CSJ2K/Color/ColorSpaceMapper.cs deleted file mode 100644 index ed9f53b4..00000000 --- a/CSJ2K/Color/ColorSpaceMapper.cs +++ /dev/null @@ -1,451 +0,0 @@ -using CSJ2K.Icc; -/// ************************************************************************** -/// -/// $Id: ColorSpaceMapper.java,v 1.2 2002/07/25 16:30:55 grosbois Exp $ -/// -/// Copyright Eastman Kodak Company, 343 State Street, Rochester, NY 14650 -/// $Date $ -/// *************************************************************************** -/// -using CSJ2K.j2k.image; -using CSJ2K.j2k.util; -namespace CSJ2K.Color -{ - - /// This is the base class for all modules in the colorspace and icc - /// profiling steps of the decoding chain. It is responsible for the - /// allocation and iniitialization of all working storage. It provides - /// several utilities which are of generic use in preparing DataBlks - /// for use and provides default implementations for the getCompData - /// and getInternCompData methods. - /// - /// - /// - /// - /// 1.0 - /// - /// Bruce A. Kern - /// - public abstract class ColorSpaceMapper : ImgDataAdapter, BlkImgDataSrc - { - private void InitBlock() - { - computed = new ComputedComponents(this); - } - /// Returns the parameters that are used in this class and implementing - /// classes. It returns a 2D String array. Each of the 1D arrays is for a - /// different option, and they have 3 elements. The first element is the - /// option name, the second one is the synopsis and the third one is a long - /// description of what the parameter is. The synopsis or description may - /// be 'null', in which case it is assumed that there is no synopsis or - /// description of the option, respectively. Null may be returned if no - /// options are supported. - /// - /// - /// the options name, their synopsis and their explanation, or null - /// if no options are supported. - /// - /// - public static System.String[][] ParameterInfo - { - get - { - return pinfo; - } - - } - /// Arrange for the input DataBlk to receive an - /// appropriately sized and typed data buffer - /// - /// input DataBlk - /// - /// - /// - protected internal static DataBlk InternalBuffer - { - set - { - switch (value.DataType) - { - - - case DataBlk.TYPE_INT: - if (value.Data == null || ((int[])value.Data).Length < value.w * value.h) - value.Data = new int[value.w * value.h]; - break; - - - case DataBlk.TYPE_FLOAT: - if (value.Data == null || ((float[])value.Data).Length < value.w * value.h) - { - value.Data = new float[value.w * value.h]; - } - break; - - - default: - throw new System.ArgumentException("Invalid output datablock" + " type"); - - } - } - - } - - /// The prefix for ICC Profiler options - public const char OPT_PREFIX = 'I'; - - /// Platform dependant end of line String. - //UPGRADE_NOTE: Final was removed from the declaration of 'eol '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - protected internal static readonly System.String eol = System.Environment.NewLine; - - // Temporary data buffers needed during profiling. - protected internal DataBlkInt[] inInt; // Integer input data. - protected internal DataBlkFloat[] inFloat; // Floating point input data. - protected internal DataBlkInt[] workInt; // Input data shifted to zero-offset - protected internal DataBlkFloat[] workFloat; // Input data shifted to zero-offset. - protected internal int[][] dataInt; // Points to input data. - protected internal float[][] dataFloat; // Points to input data. - protected internal float[][] workDataFloat; // References working data pixels. - protected internal int[][] workDataInt; // References working data pixels. - - - /* input data parameters by component */ - protected internal int[] shiftValueArray = null; - protected internal int[] maxValueArray = null; - protected internal int[] fixedPtBitsArray = null; - - /// The list of parameters that are accepted for ICC profiling. - //UPGRADE_NOTE: Final was removed from the declaration of 'pinfo'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly System.String[][] pinfo = new System.String[][] { new System.String[] { "IcolorSpacedebug", null, "Print debugging messages during colorspace mapping.", "off" } }; - - /// Parameter Specs - protected internal ParameterList pl = null; - - /// ColorSpace info - protected internal ColorSpace csMap = null; - - /// Number of image components - protected internal int ncomps = 0; - - /// The image source. - protected internal BlkImgDataSrc src = null; - - /// The image source data per component. - protected internal DataBlk[] srcBlk = null; - - - //UPGRADE_NOTE: Field 'EnclosingInstance' was added to class 'ComputedComponents' to access its enclosing instance. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1019'" - protected internal class ComputedComponents - { - private void InitBlock(ColorSpaceMapper enclosingInstance) - { - this.enclosingInstance = enclosingInstance; - } - private ColorSpaceMapper enclosingInstance; - public ColorSpaceMapper Enclosing_Instance - { - get - { - return enclosingInstance; - } - - } - //private int tIdx = - 1; - private int h = -1; - private int w = -1; - private int ulx = -1; - private int uly = -1; - private int offset = -1; - private int scanw = -1; - - public ComputedComponents(ColorSpaceMapper enclosingInstance) - { - InitBlock(enclosingInstance); - clear(); - } - - public ComputedComponents(ColorSpaceMapper enclosingInstance, DataBlk db) - { - InitBlock(enclosingInstance); - set_Renamed(db); - } - - public virtual void set_Renamed(DataBlk db) - { - h = db.h; - w = db.w; - ulx = db.ulx; - uly = db.uly; - offset = db.offset; - scanw = db.scanw; - } - - public virtual void clear() - { - h = w = ulx = uly = offset = scanw = -1; - } - - public bool Equals(ComputedComponents cc) - { - return (h == cc.h && w == cc.w && ulx == cc.ulx && uly == cc.uly && offset == cc.offset && scanw == cc.scanw); - } - - /* end class ComputedComponents */ - } - - //UPGRADE_NOTE: The initialization of 'computed' was moved to method 'InitBlock'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1005'" - protected internal ComputedComponents computed; - - /// Copy the DataBlk geometry from source to target - /// DataBlk and assure that the target has an appropriate - /// data buffer. - /// - /// has its geometry set. - /// - /// used to get the new geometric parameters. - /// - protected internal static void copyGeometry(DataBlk tgt, DataBlk src) - { - tgt.offset = 0; - tgt.h = src.h; - tgt.w = src.w; - tgt.ulx = src.ulx; - tgt.uly = src.uly; - tgt.scanw = src.w; - - // Create data array if necessary - - InternalBuffer = tgt; - } - - - /// Factory method for creating instances of this class. - /// -- source of image data - /// - /// -- provides colorspace info - /// - /// ColorSpaceMapper instance - /// - /// profile access exception - /// - public static BlkImgDataSrc createInstance(BlkImgDataSrc src, ColorSpace csMap) - { - - // Check parameters - csMap.pl.checkList(OPT_PREFIX, CSJ2K.j2k.util.ParameterList.toNameArray(pinfo)); - - // Perform ICCProfiling or ColorSpace tranfsormation. - if (csMap.Method == ColorSpace.MethodEnum.ICC_PROFILED) - { - return ICCProfiler.createInstance(src, csMap); - } - else - { - ColorSpace.CSEnum colorspace = csMap.getColorSpace(); - - if (colorspace == ColorSpace.CSEnum.sRGB) - { - return EnumeratedColorSpaceMapper.createInstance(src, csMap); - } - else if (colorspace == ColorSpace.CSEnum.GreyScale) - { - return EnumeratedColorSpaceMapper.createInstance(src, csMap); - } - else if (colorspace == ColorSpace.CSEnum.sYCC) - { - return SYccColorSpaceMapper.createInstance(src, csMap); - } - if (colorspace == ColorSpace.CSEnum.esRGB) - { - return EsRgbColorSpaceMapper.createInstance(src, csMap); - } - else if (colorspace == ColorSpace.CSEnum.Unknown) - { - return null; - } - else - { - throw new ColorSpaceException("Bad color space specification in image"); - } - } - } - - /// Ctor which creates an ICCProfile for the image and initializes - /// all data objects (input, working, and output). - /// - /// - /// -- Source of image data - /// - /// -- provides colorspace info - /// - /// - protected internal ColorSpaceMapper(BlkImgDataSrc src, ColorSpace csMap) : base(src) - { - InitBlock(); - this.src = src; - this.csMap = csMap; - initialize(); - /* end ColorSpaceMapper ctor */ - } - - /// General utility used by ctors - private void initialize() - { - - this.pl = csMap.pl; - this.ncomps = src.NumComps; - - shiftValueArray = new int[ncomps]; - maxValueArray = new int[ncomps]; - fixedPtBitsArray = new int[ncomps]; - - srcBlk = new DataBlk[ncomps]; - inInt = new DataBlkInt[ncomps]; - inFloat = new DataBlkFloat[ncomps]; - workInt = new DataBlkInt[ncomps]; - workFloat = new DataBlkFloat[ncomps]; - dataInt = new int[ncomps][]; - dataFloat = new float[ncomps][]; - workDataInt = new int[ncomps][]; - workDataFloat = new float[ncomps][]; - dataInt = new int[ncomps][]; - dataFloat = new float[ncomps][]; - - - /* For each component, get a reference to the pixel data and - * set up working DataBlks for both integer and float output. - */ - for (int i = 0; i < ncomps; ++i) - { - - shiftValueArray[i] = 1 << (src.getNomRangeBits(i) - 1); - maxValueArray[i] = (1 << src.getNomRangeBits(i)) - 1; - fixedPtBitsArray[i] = src.getFixedPoint(i); - - inInt[i] = new DataBlkInt(); - inFloat[i] = new DataBlkFloat(); - workInt[i] = new DataBlkInt(); - workInt[i].progressive = inInt[i].progressive; - workFloat[i] = new DataBlkFloat(); - workFloat[i].progressive = inFloat[i].progressive; - } - } - - /// Returns the number of bits, referred to as the "range bits", - /// corresponding to the nominal range of the data in the specified - /// component. If this number is b then for unsigned data the - /// nominal range is between 0 and 2^b-1, and for signed data it is between - /// -2^(b-1) and 2^(b-1)-1. For floating point data this value is not - /// applicable. - /// - /// - /// The index of the component. - /// - /// - /// The number of bits corresponding to the nominal range of the - /// data. Fro floating-point data this value is not applicable and the - /// return value is undefined. - /// - public virtual int getFixedPoint(int c) - { - return src.getFixedPoint(c); - } - - /// Returns, in the blk argument, a block of image data containing the - /// specifed rectangular area, in the specified component. The data is - /// returned, as a copy of the internal data, therefore the returned data - /// can be modified "in place". - /// - ///

The rectangular area to return is specified by the 'ulx', 'uly', 'w' - /// and 'h' members of the 'blk' argument, relative to the current - /// tile. These members are not modified by this method. The 'offset' of - /// the returned data is 0, and the 'scanw' is the same as the block's - /// width. See the 'DataBlk' class. - /// - ///

This method, in general, is less efficient than the - /// 'getInternCompData()' method since, in general, it copies the - /// data. However if the array of returned data is to be modified by the - /// caller then this method is preferable. - /// - ///

If the data array in 'blk' is 'null', then a new one is created. If - /// the data array is not 'null' then it is reused, and it must be large - /// enough to contain the block's data. Otherwise an 'ArrayStoreException' - /// or an 'IndexOutOfBoundsException' is thrown by the Java system. - /// - ///

The returned data may have its 'progressive' attribute set. In this - /// case the returned data is only an approximation of the "final" data. - /// - ///

- /// Its coordinates and dimensions specify the area to return, - /// relative to the current tile. If it contains a non-null data array, - /// then it must be large enough. If it contains a null data array a new - /// one is created. Some fields in this object are modified to return the - /// data. - /// - /// - /// The index of the component from which to get the data. - /// - /// - /// - /// - /// - public virtual DataBlk getCompData(DataBlk out_Renamed, int c) - { - return src.getCompData(out_Renamed, c); - } - - /// Returns, in the blk argument, a block of image data containing the - /// specifed rectangular area, in the specified component. The data is - /// returned, as a reference to the internal data, if any, instead of as a - /// copy, therefore the returned data should not be modified. - /// - ///

The rectangular area to return is specified by the 'ulx', 'uly', 'w' - /// and 'h' members of the 'blk' argument, relative to the current - /// tile. These members are not modified by this method. The 'offset' and - /// 'scanw' of the returned data can be arbitrary. See the 'DataBlk' class. - /// - ///

This method, in general, is more efficient than the 'getCompData()' - /// method since it may not copy the data. However if the array of returned - /// data is to be modified by the caller then the other method is probably - /// preferable. - /// - ///

If possible, the data in the returned 'DataBlk' should be the - /// internal data itself, instead of a copy, in order to increase the data - /// transfer efficiency. However, this depends on the particular - /// implementation (it may be more convenient to just return a copy of the - /// data). This is the reason why the returned data should not be modified. - /// - ///

If the data array in blk is null, then a new one - /// is created if necessary. The implementation of this interface may - /// choose to return the same array or a new one, depending on what is more - /// efficient. Therefore, the data array in blk prior to the - /// method call should not be considered to contain the returned data, a - /// new array may have been created. Instead, get the array from - /// blk after the method has returned. - /// - ///

The returned data may have its 'progressive' attribute set. In this - /// case the returned data is only an approximation of the "final" data. - /// - ///

- /// Its coordinates and dimensions specify the area to return, - /// relative to the current tile. Some fields in this object are modified - /// to return the data. - /// - /// - /// The index of the component from which to get the data. - /// - /// - /// The requested DataBlk - /// - /// - /// - /// - /// - public virtual DataBlk getInternCompData(DataBlk out_Renamed, int c) - { - return src.getInternCompData(out_Renamed, c); - } - - /* end class ColorSpaceMapper */ - } -} \ No newline at end of file diff --git a/CSJ2K/Color/EnumeratedColorSpaceMapper.cs b/CSJ2K/Color/EnumeratedColorSpaceMapper.cs deleted file mode 100644 index d9fd0943..00000000 --- a/CSJ2K/Color/EnumeratedColorSpaceMapper.cs +++ /dev/null @@ -1,185 +0,0 @@ -/// ************************************************************************** -/// -/// $Id: EnumeratedColorSpaceMapper.java,v 1.1 2002/07/25 14:52:01 grosbois Exp $ -/// -/// Copyright Eastman Kodak Company, 343 State Street, Rochester, NY 14650 -/// $Date $ -/// *************************************************************************** -/// -using BlkImgDataSrc = CSJ2K.j2k.image.BlkImgDataSrc; -using DataBlk = CSJ2K.j2k.image.DataBlk; -namespace CSJ2K.Color -{ - - /// This class provides Enumerated ColorSpace API for the jj2000.j2k imaging chain - /// by implementing the BlkImgDataSrc interface, in particular the getCompData - /// and getInternCompData methods. - /// - /// - /// - /// - /// 1.0 - /// - /// Bruce A. Kern - /// - public class EnumeratedColorSpaceMapper : ColorSpaceMapper - { - /// Factory method for creating instances of this class. - /// -- source of image data - /// - /// -- provides colorspace info - /// - /// EnumeratedColorSpaceMapper instance - /// - public static new BlkImgDataSrc createInstance(BlkImgDataSrc src, ColorSpace csMap) - { - return new EnumeratedColorSpaceMapper(src, csMap); - } - - /// Ctor which creates an ICCProfile for the image and initializes - /// all data objects (input, working, and output). - /// - /// - /// -- Source of image data - /// - /// -- provides colorspace info - /// - protected internal EnumeratedColorSpaceMapper(BlkImgDataSrc src, ColorSpace csMap) : base(src, csMap) - { - /* end EnumeratedColorSpaceMapper ctor */ - } - - - /// Returns, in the blk argument, a block of image data containing the - /// specifed rectangular area, in the specified component. The data is - /// returned, as a copy of the internal data, therefore the returned data - /// can be modified "in place". - /// - ///

The rectangular area to return is specified by the 'ulx', 'uly', 'w' - /// and 'h' members of the 'blk' argument, relative to the current - /// tile. These members are not modified by this method. The 'offset' of - /// the returned data is 0, and the 'scanw' is the same as the block's - /// width. See the 'DataBlk' class. - /// - ///

If the data array in 'blk' is 'null', then a new one is created. If - /// the data array is not 'null' then it is reused, and it must be large - /// enough to contain the block's data. Otherwise an 'ArrayStoreException' - /// or an 'IndexOutOfBoundsException' is thrown by the Java system. - /// - ///

The returned data has its 'progressive' attribute set to that of the - /// input data. - /// - ///

- /// Its coordinates and dimensions specify the area to - /// return. If it contains a non-null data array, then it must have the - /// correct dimensions. If it contains a null data array a new one is - /// created. The fields in this object are modified to return the data. - /// - /// - /// The index of the component from which to get the data. Only 0 - /// and 3 are valid. - /// - /// - /// The requested DataBlk - /// - /// - /// - /// - /// - public override DataBlk getCompData(DataBlk out_Renamed, int c) - { - return src.getCompData(out_Renamed, c); - } - - /// Returns, in the blk argument, a block of image data containing the - /// specifed rectangular area, in the specified component. The data is - /// returned, as a reference to the internal data, if any, instead of as a - /// copy, therefore the returned data should not be modified. - /// - ///

The rectangular area to return is specified by the 'ulx', 'uly', 'w' - /// and 'h' members of the 'blk' argument, relative to the current - /// tile. These members are not modified by this method. The 'offset' and - /// 'scanw' of the returned data can be arbitrary. See the 'DataBlk' class. - /// - ///

This method, in general, is more efficient than the 'getCompData()' - /// method since it may not copy the data. However if the array of returned - /// data is to be modified by the caller then the other method is probably - /// preferable. - /// - ///

If possible, the data in the returned 'DataBlk' should be the - /// internal data itself, instead of a copy, in order to increase the data - /// transfer efficiency. However, this depends on the particular - /// implementation (it may be more convenient to just return a copy of the - /// data). This is the reason why the returned data should not be modified. - /// - ///

If the data array in blk is null, then a new one - /// is created if necessary. The implementation of this interface may - /// choose to return the same array or a new one, depending on what is more - /// efficient. Therefore, the data array in blk prior to the - /// method call should not be considered to contain the returned data, a - /// new array may have been created. Instead, get the array from - /// blk after the method has returned. - /// - ///

The returned data may have its 'progressive' attribute set. In this - /// case the returned data is only an approximation of the "final" data. - /// - ///

- /// Its coordinates and dimensions specify the area to return, - /// relative to the current tile. Some fields in this object are modified - /// to return the data. - /// - /// - /// The index of the component from which to get the data. - /// - /// - /// The requested DataBlk - /// - /// - /// - /// - /// - public override DataBlk getInternCompData(DataBlk out_Renamed, int c) - { - return src.getInternCompData(out_Renamed, c); - } - - - - public override System.String ToString() - { - int i; - System.Text.StringBuilder rep_nComps = new System.Text.StringBuilder("ncomps= ").Append(System.Convert.ToString(ncomps)); - - System.Text.StringBuilder rep_fixedValue = new System.Text.StringBuilder("fixedPointBits= ("); - System.Text.StringBuilder rep_shiftValue = new System.Text.StringBuilder("shiftValue= ("); - System.Text.StringBuilder rep_maxValue = new System.Text.StringBuilder("maxValue= ("); - - for (i = 0; i < ncomps; ++i) - { - if (i != 0) - { - rep_shiftValue.Append(", "); - rep_maxValue.Append(", "); - rep_fixedValue.Append(", "); - } - rep_shiftValue.Append(System.Convert.ToString(shiftValueArray[i])); - rep_maxValue.Append(System.Convert.ToString(maxValueArray[i])); - rep_fixedValue.Append(System.Convert.ToString(fixedPtBitsArray[i])); - } - - rep_shiftValue.Append(")"); - rep_maxValue.Append(")"); - rep_fixedValue.Append(")"); - - System.Text.StringBuilder rep = new System.Text.StringBuilder("[EnumeratedColorSpaceMapper "); - rep.Append(rep_nComps); - rep.Append(eol).Append(" ").Append(rep_shiftValue); - rep.Append(eol).Append(" ").Append(rep_maxValue); - rep.Append(eol).Append(" ").Append(rep_fixedValue); - - return rep.Append("]").ToString(); - } - - /* end class EnumeratedColorSpaceMapper */ - } -} \ No newline at end of file diff --git a/CSJ2K/Color/EsRgbColorSpaceMapper.cs b/CSJ2K/Color/EsRgbColorSpaceMapper.cs deleted file mode 100644 index ffb2809a..00000000 --- a/CSJ2K/Color/EsRgbColorSpaceMapper.cs +++ /dev/null @@ -1,210 +0,0 @@ -/// ************************************************************************** -/// -/// $Id: SYccColorSpaceMapper.java,v 1.1 2002/07/25 14:52:01 grosbois Exp $ -/// -/// Copyright Eastman Kodak Company, 343 State Street, Rochester, NY 14650 -/// $Date $ -/// *************************************************************************** -/// -using System; -using BlkImgDataSrc = CSJ2K.j2k.image.BlkImgDataSrc; -using DataBlk = CSJ2K.j2k.image.DataBlk; -using DataBlkFloat = CSJ2K.j2k.image.DataBlkFloat; -using DataBlkInt = CSJ2K.j2k.image.DataBlkInt; -using FacilityManager = CSJ2K.j2k.util.FacilityManager; -namespace CSJ2K.Color -{ - - - /// This decodes maps which are defined in the e-sRGB - /// colorspace into the sRGB colorspace. - /// - /// - /// - /// - /// 1.0 - /// - /// Jason S. Clary - /// - public class EsRgbColorSpaceMapper : ColorSpaceMapper - { - - /// Factory method for creating instances of this class. - /// -- source of image data - /// - /// -- provides colorspace info - /// - /// SYccColorSpaceMapper instance - /// - public static new BlkImgDataSrc createInstance(BlkImgDataSrc src, ColorSpace csMap) - { - return new EsRgbColorSpaceMapper(src, csMap); - } - - /// Ctor which creates an ICCProfile for the image and initializes - /// all data objects (input, working, and output). - /// - /// - /// -- Source of image data - /// - /// -- provides colorspace info - /// - protected internal EsRgbColorSpaceMapper(BlkImgDataSrc src, ColorSpace csMap) : base(src, csMap) - { - initialize(); - } - - /// General utility used by ctors - private void initialize() - { - - if (ncomps != 1 && ncomps != 3) - { - System.String msg = "EsRgbColorSpaceMapper: e-sRGB transformation _not_ applied to " + ncomps + " component image"; - FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.ERROR, msg); - throw new ColorSpaceException(msg); - } - } - - - /// - /// Returns, in the blk argument, a block of image data containing the - /// specifed rectangular area, in the specified component. The data is - /// returned, as a copy of the internal data, therefore the returned data - /// can be modified "in place". - /// - /// The rectangular area to return is specified by the 'ulx', 'uly', 'w' - /// and 'h' members of the 'blk' argument, relative to the current - /// tile. These members are not modified by this method. The 'offset' of - /// the returned data is 0, and the 'scanw' is the same as the block's - /// width. See the 'DataBlk' class. - /// - /// If the data array in 'blk' is 'null', then a new one is created. If - /// the data array is not 'null' then it is reused, and it must be large - /// enough to contain the block's data. Otherwise an 'ArrayStoreException' - /// or an 'IndexOutOfBoundsException' is thrown by the Java system. - /// - /// The returned data has its 'progressive' attribute set to that of the - /// input data. - /// - /// - /// Its coordinates and dimensions specify the area to - /// return. If it contains a non-null data array, then it must have the - /// correct dimensions. If it contains a null data array a new one is - /// created. The fields in this object are modified to return the data. - /// - /// - /// The index of the component from which to get the data. Only 0 - /// and 3 are valid. - /// - /// - /// The requested DataBlk - /// - /// - /// - /// - public override DataBlk getCompData(DataBlk outblk, int c) - { - - int type = outblk.DataType; - double colors = Math.Pow(2, src.getNomRangeBits(c)); - double bitoff = colors * 0.375D; - if (type == DataBlk.TYPE_INT) - { - DataBlkInt intblk = (DataBlkInt)src.getInternCompData(outblk, c); - - for (int i = 0; i < intblk.data_array.Length; i++) - { - int tmp = intblk.data_array[i]; - - tmp += (int)(colors / 2); - tmp -= (int)bitoff; - tmp *= 2; - tmp -= (int)(colors / 2); - - intblk.data_array[i] = tmp; - } - outblk = intblk; - } - else if (type == DataBlk.TYPE_FLOAT) - { - FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.WARNING, "Unsupported e-sRGB DataType (float)"); - - DataBlkFloat fltblk = (DataBlkFloat)src.getInternCompData(outblk, c); - outblk = fltblk; - } - return outblk; - } - - /// Returns, in the blk argument, a block of image data containing the - /// specifed rectangular area, in the specified component. The data is - /// returned, as a reference to the internal data, if any, instead of as a - /// copy, therefore the returned data should not be modified. - /// - ///

The rectangular area to return is specified by the 'ulx', 'uly', 'w' - /// and 'h' members of the 'blk' argument, relative to the current - /// tile. These members are not modified by this method. The 'offset' and - /// 'scanw' of the returned data can be arbitrary. See the 'DataBlk' class. - /// - ///

This method, in general, is more efficient than the 'getCompData()' - /// method since it may not copy the data. However if the array of returned - /// data is to be modified by the caller then the other method is probably - /// preferable. - /// - ///

If possible, the data in the returned 'DataBlk' should be the - /// internal data itself, instead of a copy, in order to increase the data - /// transfer efficiency. However, this depends on the particular - /// implementation (it may be more convenient to just return a copy of the - /// data). This is the reason why the returned data should not be modified. - /// - ///

If the data array in blk is null, then a new one - /// is created if necessary. The implementation of this interface may - /// choose to return the same array or a new one, depending on what is more - /// efficient. Therefore, the data array in blk prior to the - /// method call should not be considered to contain the returned data, a - /// new array may have been created. Instead, get the array from - /// blk after the method has returned. - /// - ///

The returned data may have its 'progressive' attribute set. In this - /// case the returned data is only an approximation of the "final" data. - /// - ///

- /// Its coordinates and dimensions specify the area to return, - /// relative to the current tile. Some fields in this object are modified - /// to return the data. - /// - /// - /// The index of the component from which to get the data. - /// - /// - /// The requested DataBlk - /// - /// - /// - /// - public override DataBlk getInternCompData(DataBlk out_Renamed, int c) - { - return getCompData(out_Renamed, c); - } - - /// Return a suitable String representation of the class instance. - public override System.String ToString() - { - int i; - - System.Text.StringBuilder rep_nComps = new System.Text.StringBuilder("ncomps= ").Append(System.Convert.ToString(ncomps)); - System.Text.StringBuilder rep_comps = new System.Text.StringBuilder(); - - for (i = 0; i < ncomps; ++i) - { - rep_comps.Append(" ").Append("component[").Append(System.Convert.ToString(i)).Append("] height, width = (").Append(src.getCompImgHeight(i)).Append(", ").Append(src.getCompImgWidth(i)).Append(")").Append(eol); - } - - System.Text.StringBuilder rep = new System.Text.StringBuilder("[EsRGBColorSpaceMapper "); - rep.Append(rep_nComps).Append(eol); - rep.Append(rep_comps).Append(" "); - - return rep.Append("]").ToString(); - } - } -} \ No newline at end of file diff --git a/CSJ2K/Color/PalettizedColorSpaceMapper.cs b/CSJ2K/Color/PalettizedColorSpaceMapper.cs deleted file mode 100644 index 5a9eca11..00000000 --- a/CSJ2K/Color/PalettizedColorSpaceMapper.cs +++ /dev/null @@ -1,471 +0,0 @@ -using CSJ2K.Color.Boxes; -/// ************************************************************************** -/// -/// $Id: PalettizedColorSpaceMapper.java,v 1.2 2002/08/08 14:07:16 grosbois Exp $ -/// -/// Copyright Eastman Kodak Company, 343 State Street, Rochester, NY 14650 -/// $Date $ -/// *************************************************************************** -/// -using CSJ2K.j2k.image; -using CSJ2K.j2k.util; -namespace CSJ2K.Color -{ - - /// This class provides decoding of images with palettized colorspaces. - /// Here each sample in the input is treated as an index into a color - /// palette of triplet sRGB output values. - /// - /// - /// - /// - /// 1.0 - /// - /// Bruce A. Kern - /// - public class PalettizedColorSpaceMapper : ColorSpaceMapper - { - /// Returns the number of components in the image. - /// - /// - /// The number of components in the image. - /// - override public int NumComps - { - get - { - return pbox == null ? src.NumComps : pbox.NumColumns; - } - - } - internal int[] outShiftValueArray; - internal int srcChannel = 0; - - /// Access to the palette box information. - private PaletteBox pbox; - - /// Factory method for creating instances of this class. - /// -- source of image data - /// - /// -- provides colorspace info - /// - /// PalettizedColorSpaceMapper instance - /// - public static new BlkImgDataSrc createInstance(BlkImgDataSrc src, ColorSpace csMap) - { - return new PalettizedColorSpaceMapper(src, csMap); - } - - /// Ctor which creates an ICCProfile for the image and initializes - /// all data objects (input, working, and output). - /// - /// - /// -- Source of image data - /// - /// -- provides colorspace info - /// - protected internal PalettizedColorSpaceMapper(BlkImgDataSrc src, ColorSpace csMap) : base(src, csMap) - { - pbox = csMap.PaletteBox; - initialize(); - } - - /// General utility used by ctors - private void initialize() - { - if (ncomps != 1 && ncomps != 3) - throw new ColorSpaceException("wrong number of components (" + ncomps + ") for palettized image"); - - int outComps = NumComps; - outShiftValueArray = new int[outComps]; - - for (int i = 0; i < outComps; i++) - { - outShiftValueArray[i] = 1 << (getNomRangeBits(i) - 1); - } - } - - - /// Returns, in the blk argument, a block of image data containing the - /// specifed rectangular area, in the specified component. The data is - /// returned, as a copy of the internal data, therefore the returned data - /// can be modified "in place". - /// - ///

The rectangular area to return is specified by the 'ulx', 'uly', 'w' - /// and 'h' members of the 'blk' argument, relative to the current - /// tile. These members are not modified by this method. The 'offset' of - /// the returned data is 0, and the 'scanw' is the same as the block's - /// width. See the 'DataBlk' class. - /// - ///

If the data array in 'blk' is 'null', then a new one is created. If - /// the data array is not 'null' then it is reused, and it must be large - /// enough to contain the block's data. Otherwise an 'ArrayStoreException' - /// or an 'IndexOutOfBoundsException' is thrown by the Java system. - /// - ///

The returned data has its 'progressive' attribute set to that of the - /// input data. - /// - ///

- /// Its coordinates and dimensions specify the area to - /// return. If it contains a non-null data array, then it must have the - /// correct dimensions. If it contains a null data array a new one is - /// created. The fields in this object are modified to return the data. - /// - /// - /// The index of the component from which to get the data. Only 0 - /// and 3 are valid. - /// - /// - /// The requested DataBlk - /// - /// - /// - /// - /// - public override DataBlk getCompData(DataBlk out_Renamed, int c) - { - - if (pbox == null) - return src.getCompData(out_Renamed, c); - - if (ncomps != 1) - { - System.String msg = "PalettizedColorSpaceMapper: color palette " + "_not_ applied, incorrect number (" + System.Convert.ToString(ncomps) + ") of components"; - FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.WARNING, msg); - return src.getCompData(out_Renamed, c); - } - - // Initialize general input and output indexes - int leftedgeOut = -1; // offset to the start of the output scanline - int rightedgeOut = -1; // offset to the end of the output - // scanline + 1 - int leftedgeIn = -1; // offset to the start of the input scanline - int rightedgeIn = -1; // offset to the end of the input - // scanline + 1 - int kOut = -1; - int kIn = -1; - - // Assure a properly sized data buffer for output. - InternalBuffer = out_Renamed; - - switch (out_Renamed.DataType) - { - - // Int and Float data only - case DataBlk.TYPE_INT: - - copyGeometry(inInt[0], out_Renamed); - - // Request data from the source. - inInt[0] = (DataBlkInt)src.getInternCompData(inInt[0], 0); - dataInt[0] = (int[])inInt[0].Data; - int[] outdataInt = ((DataBlkInt)out_Renamed).DataInt; - - // The nitty-gritty. - - for (int row = 0; row < out_Renamed.h; ++row) - { - leftedgeIn = inInt[0].offset + row * inInt[0].scanw; - rightedgeIn = leftedgeIn + inInt[0].w; - leftedgeOut = out_Renamed.offset + row * out_Renamed.scanw; - rightedgeOut = leftedgeOut + out_Renamed.w; - - for (kOut = leftedgeOut, kIn = leftedgeIn; kIn < rightedgeIn; ++kIn, ++kOut) - { - outdataInt[kOut] = pbox.getEntry(c, dataInt[0][kIn] + shiftValueArray[0]) - outShiftValueArray[c]; - } - } - out_Renamed.progressive = inInt[0].progressive; - break; - - - case DataBlk.TYPE_FLOAT: - - copyGeometry(inFloat[0], out_Renamed); - - // Request data from the source. - inFloat[0] = (DataBlkFloat)src.getInternCompData(inFloat[0], 0); - dataFloat[0] = (float[])inFloat[0].Data; - float[] outdataFloat = ((DataBlkFloat)out_Renamed).DataFloat; - - // The nitty-gritty. - - for (int row = 0; row < out_Renamed.h; ++row) - { - leftedgeIn = inFloat[0].offset + row * inFloat[0].scanw; - rightedgeIn = leftedgeIn + inFloat[0].w; - leftedgeOut = out_Renamed.offset + row * out_Renamed.scanw; - rightedgeOut = leftedgeOut + out_Renamed.w; - - for (kOut = leftedgeOut, kIn = leftedgeIn; kIn < rightedgeIn; ++kIn, ++kOut) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - outdataFloat[kOut] = pbox.getEntry(c, (int)dataFloat[0][kIn] + shiftValueArray[0]) - outShiftValueArray[c]; - } - } - out_Renamed.progressive = inFloat[0].progressive; - break; - - - case DataBlk.TYPE_SHORT: - case DataBlk.TYPE_BYTE: - default: - // Unsupported output type. - throw new System.ArgumentException("invalid source datablock" + " type"); - } - - // Initialize the output block geometry and set the profiled - // data into the output block. - out_Renamed.offset = 0; - out_Renamed.scanw = out_Renamed.w; - return out_Renamed; - } - - - /// Return a suitable String representation of the class instance, e.g. - ///

- /// [PalettizedColorSpaceMapper - /// ncomps= 3, scomp= 1, nentries= 1024 - /// column=0, 7 bit signed entry - /// column=1, 7 bit unsigned entry - /// column=2, 7 bit signed entry] - ///

- /// - ///

- public override System.String ToString() - { - - int c; - System.Text.StringBuilder rep = new System.Text.StringBuilder("[PalettizedColorSpaceMapper "); - System.Text.StringBuilder body = new System.Text.StringBuilder(" " + eol); - - if (pbox != null) - { - body.Append("ncomps= ").Append(NumComps).Append(", scomp= ").Append(srcChannel); - for (c = 0; c < NumComps; ++c) - { - body.Append(eol).Append("column= ").Append(c).Append(", ").Append(pbox.getBitDepth(c)).Append(" bit ").Append(pbox.isSigned(c) ? "signed entry" : "unsigned entry"); - } - } - else - { - body.Append("image does not contain a palette box"); - } - - rep.Append(ColorSpace.indent(" ", body)); - return rep.Append("]").ToString(); - } - - - /// Returns, in the blk argument, a block of image data containing the - /// specifed rectangular area, in the specified component. The data is - /// returned, as a reference to the internal data, if any, instead of as a - /// copy, therefore the returned data should not be modified. - /// - ///

The rectangular area to return is specified by the 'ulx', 'uly', 'w' - /// and 'h' members of the 'blk' argument, relative to the current - /// tile. These members are not modified by this method. The 'offset' and - /// 'scanw' of the returned data can be arbitrary. See the 'DataBlk' class. - /// - ///

This method, in general, is more efficient than the 'getCompData()' - /// method since it may not copy the data. However if the array of returned - /// data is to be modified by the caller then the other method is probably - /// preferable. - /// - ///

If possible, the data in the returned 'DataBlk' should be the - /// internal data itself, instead of a copy, in order to increase the data - /// transfer efficiency. However, this depends on the particular - /// implementation (it may be more convenient to just return a copy of the - /// data). This is the reason why the returned data should not be modified. - /// - ///

If the data array in blk is null, then a new one - /// is created if necessary. The implementation of this interface may - /// choose to return the same array or a new one, depending on what is more - /// efficient. Therefore, the data array in blk prior to the - /// method call should not be considered to contain the returned data, a - /// new array may have been created. Instead, get the array from - /// blk after the method has returned. - /// - ///

The returned data may have its 'progressive' attribute set. In this - /// case the returned data is only an approximation of the "final" data. - /// - ///

- /// Its coordinates and dimensions specify the area to return, - /// relative to the current tile. Some fields in this object are modified - /// to return the data. - /// - /// - /// The index of the component from which to get the data. - /// - /// - /// The requested DataBlk - /// - /// - /// - /// - public override DataBlk getInternCompData(DataBlk out_Renamed, int c) - { - return getCompData(out_Renamed, c); - } - - /// Returns the number of bits, referred to as the "range bits", - /// corresponding to the nominal range of the image data in the specified - /// component. If this number is n then for unsigned data the - /// nominal range is between 0 and 2^b-1, and for signed data it is between - /// -2^(b-1) and 2^(b-1)-1. In the case of transformed data which is not in - /// the image domain (e.g., wavelet coefficients), this method returns the - /// "range bits" of the image data that generated the coefficients. - /// - /// - /// The index of the component. - /// - /// - /// The number of bits corresponding to the nominal range of the - /// image data (in the image domain). - /// - public override int getNomRangeBits(int c) - { - return pbox == null ? src.getNomRangeBits(c) : pbox.getBitDepth(c); - } - - - /// Returns the component subsampling factor in the horizontal direction, - /// for the specified component. This is, approximately, the ratio of - /// dimensions between the reference grid and the component itself, see the - /// 'ImgData' interface desription for details. - /// - /// - /// The index of the component (between 0 and N-1) - /// - /// - /// The horizontal subsampling factor of component 'c' - /// - /// - /// - /// - /// - public override int getCompSubsX(int c) - { - return imgdatasrc.getCompSubsX(srcChannel); - } - - /// Returns the component subsampling factor in the vertical direction, for - /// the specified component. This is, approximately, the ratio of - /// dimensions between the reference grid and the component itself, see the - /// 'ImgData' interface desription for details. - /// - /// - /// The index of the component (between 0 and N-1) - /// - /// - /// The vertical subsampling factor of component 'c' - /// - /// - /// - /// - /// - public override int getCompSubsY(int c) - { - return imgdatasrc.getCompSubsY(srcChannel); - } - - /// Returns the width in pixels of the specified tile-component - /// - /// - /// Tile index - /// - /// - /// The index of the component, from 0 to N-1. - /// - /// - /// The width in pixels of component c in tilet. - /// - /// - public override int getTileCompWidth(int t, int c) - { - return imgdatasrc.getTileCompWidth(t, srcChannel); - } - - /// Returns the height in pixels of the specified tile-component. - /// - /// - /// The tile index. - /// - /// - /// The index of the component, from 0 to N-1. - /// - /// - /// The height in pixels of component c in tile - /// t. - /// - /// - public override int getTileCompHeight(int t, int c) - { - return imgdatasrc.getTileCompHeight(t, srcChannel); - } - - /// Returns the width in pixels of the specified component in the overall - /// image. - /// - /// - /// The index of the component, from 0 to N-1. - /// - /// - /// The width in pixels of component c in the overall - /// image. - /// - /// - public override int getCompImgWidth(int c) - { - return imgdatasrc.getCompImgWidth(srcChannel); - } - - - /// Returns the number of bits, referred to as the "range bits", - /// corresponding to the nominal range of the image data in the specified - /// component. If this number is n then for unsigned data the - /// nominal range is between 0 and 2^b-1, and for signed data it is between - /// -2^(b-1) and 2^(b-1)-1. In the case of transformed data which is not in - /// the image domain (e.g., wavelet coefficients), this method returns the - /// "range bits" of the image data that generated the coefficients. - /// - /// - /// The index of the component. - /// - /// - /// The number of bits corresponding to the nominal range of the - /// image data (in the image domain). - /// - /// - public override int getCompImgHeight(int c) - { - return imgdatasrc.getCompImgHeight(srcChannel); - } - - /// Returns the horizontal coordinate of the upper-left corner of the - /// specified component in the current tile. - /// - /// - /// The index of the component. - /// - /// - public override int getCompULX(int c) - { - return imgdatasrc.getCompULX(srcChannel); - } - - /// Returns the vertical coordinate of the upper-left corner of the - /// specified component in the current tile. - /// - /// - /// The index of the component. - /// - /// - public override int getCompULY(int c) - { - return imgdatasrc.getCompULY(srcChannel); - } - - /* end class PalettizedColorSpaceMapper */ - } -} \ No newline at end of file diff --git a/CSJ2K/Color/Resampler.cs b/CSJ2K/Color/Resampler.cs deleted file mode 100644 index 2c0acf6f..00000000 --- a/CSJ2K/Color/Resampler.cs +++ /dev/null @@ -1,431 +0,0 @@ -/// ************************************************************************** -/// -/// $Id: Resampler.java,v 1.2 2002/08/08 14:07:31 grosbois Exp $ -/// -/// Copyright Eastman Kodak Company, 343 State Street, Rochester, NY 14650 -/// $Date $ -/// *************************************************************************** -/// -using CSJ2K.j2k.image; -namespace CSJ2K.Color -{ - - /// This class resamples the components of an image so that - /// all have the same number of samples. The current implementation - /// only handles the case of 2:1 upsampling. - /// - /// - /// - /// - /// 1.0 - /// - /// Bruce A. Kern - /// - public class Resampler : ColorSpaceMapper - { - //UPGRADE_NOTE: Final was removed from the declaration of 'minCompSubsX '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private int minCompSubsX; - //UPGRADE_NOTE: Final was removed from the declaration of 'minCompSubsY '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private int minCompSubsY; - //UPGRADE_NOTE: Final was removed from the declaration of 'maxCompSubsX '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private int maxCompSubsX; - //UPGRADE_NOTE: Final was removed from the declaration of 'maxCompSubsY '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private int maxCompSubsY; - - //UPGRADE_NOTE: Final was removed from the declaration of 'wspan '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - //UPGRADE_NOTE: Final was removed from the declaration of 'hspan '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - internal int wspan = 0; - internal int hspan = 0; - - /// Factory method for creating instances of this class. - /// -- source of image data - /// - /// -- provides colorspace info - /// - /// Resampler instance - /// - public static new BlkImgDataSrc createInstance(BlkImgDataSrc src, ColorSpace csMap) - { - return new Resampler(src, csMap); - } - - /// Ctor resamples a BlkImgDataSrc so that all components - /// have the same number of samples. - /// - /// Note the present implementation does only two to one - /// respampling in either direction (row, column). - /// - /// - /// -- Source of image data - /// - /// -- provides colorspace info - /// - protected internal Resampler(BlkImgDataSrc src, ColorSpace csMap) : base(src, csMap) - { - - int c; - - // Calculate the minimum and maximum subsampling factor - // across all channels. - - int minX = src.getCompSubsX(0); - int minY = src.getCompSubsY(0); - int maxX = minX; - int maxY = minY; - - for (c = 1; c < ncomps; ++c) - { - minX = System.Math.Min(minX, src.getCompSubsX(c)); - minY = System.Math.Min(minY, src.getCompSubsY(c)); - maxX = System.Math.Max(maxX, src.getCompSubsX(c)); - maxY = System.Math.Max(maxY, src.getCompSubsY(c)); - } - - // Throw an exception for other than 2:1 sampling. - if ((maxX != 1 && maxX != 2) || (maxY != 1 && maxY != 2)) - { - throw new ColorSpaceException("Upsampling by other than 2:1 not" + " supported"); - } - - minCompSubsX = minX; - minCompSubsY = minY; - maxCompSubsX = maxX; - maxCompSubsY = maxY; - - /* end Resampler ctor */ - } - - /// Return a DataBlk containing the requested component - /// upsampled by the scale factor applied to the particular - /// scaling direction - /// - /// Returns, in the blk argument, a block of image data containing the - /// specifed rectangular area, in the specified component. The data is - /// returned, as a copy of the internal data, therefore the returned data - /// can be modified "in place". - /// - ///

The rectangular area to return is specified by the 'ulx', 'uly', 'w' - /// and 'h' members of the 'blk' argument, relative to the current - /// tile. These members are not modified by this method. The 'offset' of - /// the returned data is 0, and the 'scanw' is the same as the block's - /// width. See the 'DataBlk' class. - /// - ///

If the data array in 'blk' is 'null', then a new one is created. If - /// the data array is not 'null' then it is reused, and it must be large - /// enough to contain the block's data. Otherwise an 'ArrayStoreException' - /// or an 'IndexOutOfBoundsException' is thrown by the Java system. - /// - ///

The returned data has its 'progressive' attribute set to that of the - /// input data. - /// - ///

- /// Its coordinates and dimensions specify the area to - /// return. If it contains a non-null data array, then it must have the - /// correct dimensions. If it contains a null data array a new one is - /// created. The fields in this object are modified to return the data. - /// - /// - /// The index of the component from which to get the data. Only 0 - /// and 3 are valid. - /// - /// - /// The requested DataBlk - /// - /// - /// - /// - public override DataBlk getInternCompData(DataBlk outblk, int c) - { - - // If the scaling factor of this channel is 1 in both - // directions, simply return the source DataBlk. - - if (src.getCompSubsX(c) == 1 && src.getCompSubsY(c) == 1) - return src.getInternCompData(outblk, c); - - int wfactor = src.getCompSubsX(c); - int hfactor = src.getCompSubsY(c); - if ((wfactor != 2 && wfactor != 1) || (hfactor != 2 && hfactor != 1)) - throw new System.ArgumentException("Upsampling by other than 2:1" + " not supported"); - - int leftedgeOut = -1; // offset to the start of the output scanline - int rightedgeOut = -1; // offset to the end of the output - // scanline + 1 - int leftedgeIn = -1; // offset to the start of the input scanline - int rightedgeIn = -1; // offset to the end of the input scanline + 1 - - - int y0In, y1In, y0Out, y1Out; - int x0In, x1In, x0Out, x1Out; - - y0Out = outblk.uly; - y1Out = y0Out + outblk.h - 1; - - x0Out = outblk.ulx; - x1Out = x0Out + outblk.w - 1; - - y0In = y0Out / hfactor; - y1In = y1Out / hfactor; - - x0In = x0Out / wfactor; - x1In = x1Out / wfactor; - - - // Calculate the requested height and width, requesting an extra - // row and or for upsampled channels. - int reqW = x1In - x0In + 1; - int reqH = y1In - y0In + 1; - - // Initialize general input and output indexes - int kOut = -1; - int kIn = -1; - int yIn; - - switch (outblk.DataType) - { - - - case DataBlk.TYPE_INT: - - DataBlkInt inblkInt = new DataBlkInt(x0In, y0In, reqW, reqH); - inblkInt = (DataBlkInt)src.getInternCompData(inblkInt, c); - dataInt[c] = inblkInt.DataInt; - - // Reference the working array - int[] outdataInt = (int[])outblk.Data; - - // Create data array if necessary - if (outdataInt == null || outdataInt.Length != outblk.w * outblk.h) - { - outdataInt = new int[outblk.h * outblk.w]; - outblk.Data = outdataInt; - } - - // The nitty-gritty. - - for (int yOut = y0Out; yOut <= y1Out; ++yOut) - { - - yIn = yOut / hfactor; - - - leftedgeIn = inblkInt.offset + (yIn - y0In) * inblkInt.scanw; - rightedgeIn = leftedgeIn + inblkInt.w; - leftedgeOut = outblk.offset + (yOut - y0Out) * outblk.scanw; - rightedgeOut = leftedgeOut + outblk.w; - - kIn = leftedgeIn; - kOut = leftedgeOut; - - if ((x0Out & 0x1) == 1) - { - // first is odd do the pixel once. - outdataInt[kOut++] = dataInt[c][kIn++]; - } - - if ((x1Out & 0x1) == 0) - { - // last is even adjust loop bounds - rightedgeOut--; - } - - while (kOut < rightedgeOut) - { - outdataInt[kOut++] = dataInt[c][kIn]; - outdataInt[kOut++] = dataInt[c][kIn++]; - } - - if ((x1Out & 0x1) == 0) - { - // last is even do the pixel once. - outdataInt[kOut++] = dataInt[c][kIn]; - } - } - - outblk.progressive = inblkInt.progressive; - break; - - - case DataBlk.TYPE_FLOAT: - - DataBlkFloat inblkFloat = new DataBlkFloat(x0In, y0In, reqW, reqH); - inblkFloat = (DataBlkFloat)src.getInternCompData(inblkFloat, c); - dataFloat[c] = inblkFloat.DataFloat; - - // Reference the working array - float[] outdataFloat = (float[])outblk.Data; - - // Create data array if necessary - if (outdataFloat == null || outdataFloat.Length != outblk.w * outblk.h) - { - outdataFloat = new float[outblk.h * outblk.w]; - outblk.Data = outdataFloat; - } - - // The nitty-gritty. - - for (int yOut = y0Out; yOut <= y1Out; ++yOut) - { - - yIn = yOut / hfactor; - - - leftedgeIn = inblkFloat.offset + (yIn - y0In) * inblkFloat.scanw; - rightedgeIn = leftedgeIn + inblkFloat.w; - leftedgeOut = outblk.offset + (yOut - y0Out) * outblk.scanw; - rightedgeOut = leftedgeOut + outblk.w; - - kIn = leftedgeIn; - kOut = leftedgeOut; - - if ((x0Out & 0x1) == 1) - { - // first is odd do the pixel once. - outdataFloat[kOut++] = dataFloat[c][kIn++]; - } - - if ((x1Out & 0x1) == 0) - { - // last is even adjust loop bounds - rightedgeOut--; - } - - while (kOut < rightedgeOut) - { - outdataFloat[kOut++] = dataFloat[c][kIn]; - outdataFloat[kOut++] = dataFloat[c][kIn++]; - } - - if ((x1Out & 0x1) == 0) - { - // last is even do the pixel once. - outdataFloat[kOut++] = dataFloat[c][kIn]; - } - } - - outblk.progressive = inblkFloat.progressive; - break; - - - case DataBlk.TYPE_SHORT: - case DataBlk.TYPE_BYTE: - default: - // Unsupported output type. - throw new System.ArgumentException("invalid source datablock " + "type"); - } - - return outblk; - } - - - /// Return an appropriate String representation of this Resampler instance. - public override System.String ToString() - { - System.Text.StringBuilder rep = new System.Text.StringBuilder("[Resampler: ncomps= " + ncomps); - System.Text.StringBuilder body = new System.Text.StringBuilder(" "); - for (int i = 0; i < ncomps; ++i) - { - body.Append(eol); - body.Append("comp["); - body.Append(i); - body.Append("] xscale= "); - body.Append(imgdatasrc.getCompSubsX(i)); - body.Append(", yscale= "); - body.Append(imgdatasrc.getCompSubsY(i)); - } - - rep.Append(ColorSpace.indent(" ", body)); - return rep.Append("]").ToString(); - } - - - - /// Returns, in the blk argument, a block of image data containing the - /// specifed rectangular area, in the specified component. The data is - /// returned, as a copy of the internal data, therefore the returned data - /// can be modified "in place". - /// - ///

The rectangular area to return is specified by the 'ulx', 'uly', 'w' - /// and 'h' members of the 'blk' argument, relative to the current - /// tile. These members are not modified by this method. The 'offset' of - /// the returned data is 0, and the 'scanw' is the same as the block's - /// width. See the 'DataBlk' class. - /// - ///

If the data array in 'blk' is 'null', then a new one is created. If - /// the data array is not 'null' then it is reused, and it must be large - /// enough to contain the block's data. Otherwise an 'ArrayStoreException' - /// or an 'IndexOutOfBoundsException' is thrown by the Java system. - /// - ///

The returned data has its 'progressive' attribute set to that of the - /// input data. - /// - ///

- /// Its coordinates and dimensions specify the area to - /// return. If it contains a non-null data array, then it must have the - /// correct dimensions. If it contains a null data array a new one is - /// created. The fields in this object are modified to return the data. - /// - /// - /// The index of the component from which to get the data. Only 0 - /// and 3 are valid. - /// - /// - /// The requested DataBlk - /// - /// - /// - /// - /// - public override DataBlk getCompData(DataBlk outblk, int c) - { - return getInternCompData(outblk, c); - } - - - /// Returns the height in pixels of the specified component in the - /// overall image. - /// - public override int getCompImgHeight(int c) - { - return src.getCompImgHeight(c) * src.getCompSubsY(c); - } - - /// Returns the width in pixels of the specified component in the - /// overall image. - /// - public override int getCompImgWidth(int c) - { - return src.getCompImgWidth(c) * src.getCompSubsX(c); - } - - /// Returns the component subsampling factor in the horizontal - /// direction, for the specified component. - /// - public override int getCompSubsX(int c) - { - return 1; - } - - /// Returns the component subsampling factor in the vertical - /// direction, for the specified component. - /// - public override int getCompSubsY(int c) - { - return 1; - } - - /// Returns the height in pixels of the specified tile-component. - public override int getTileCompHeight(int t, int c) - { - return src.getTileCompHeight(t, c) * src.getCompSubsY(c); - } - - /// Returns the width in pixels of the specified tile-component.. - public override int getTileCompWidth(int t, int c) - { - return src.getTileCompWidth(t, c) * src.getCompSubsX(c); - } - - /* end class Resampler */ - } -} \ No newline at end of file diff --git a/CSJ2K/Color/SYccColorSpaceMapper.cs b/CSJ2K/Color/SYccColorSpaceMapper.cs deleted file mode 100644 index b194a158..00000000 --- a/CSJ2K/Color/SYccColorSpaceMapper.cs +++ /dev/null @@ -1,344 +0,0 @@ -/// ************************************************************************** -/// -/// $Id: SYccColorSpaceMapper.java,v 1.1 2002/07/25 14:52:01 grosbois Exp $ -/// -/// Copyright Eastman Kodak Company, 343 State Street, Rochester, NY 14650 -/// $Date $ -/// *************************************************************************** -/// -using BlkImgDataSrc = CSJ2K.j2k.image.BlkImgDataSrc; -using DataBlk = CSJ2K.j2k.image.DataBlk; -using DataBlkFloat = CSJ2K.j2k.image.DataBlkFloat; -using DataBlkInt = CSJ2K.j2k.image.DataBlkInt; -using FacilityManager = CSJ2K.j2k.util.FacilityManager; -namespace CSJ2K.Color -{ - - - /// This decodes maps which are defined in the sYCC - /// colorspace into the sRGB colorspadce. - /// - /// - /// - /// - /// 1.0 - /// - /// Bruce A. Kern - /// - public class SYccColorSpaceMapper : ColorSpaceMapper - { - /// Matrix component for ycc transform. - /* sYCC colorspace matrix */ - - protected internal static float Matrix00 = 1; - /// Matrix component for ycc transform. - protected internal static float Matrix01 = 0; - /// Matrix component for ycc transform. - protected internal static float Matrix02 = (float)1.402; - /// Matrix component for ycc transform. - protected internal static float Matrix10 = 1; - /// Matrix component for ycc transform. - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - protected internal static float Matrix11 = (float)(-0.34413); - /// Matrix component for ycc transform. - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - protected internal static float Matrix12 = (float)(-0.71414); - /// Matrix component for ycc transform. - protected internal static float Matrix20 = 1; - /// Matrix component for ycc transform. - protected internal static float Matrix21 = (float)1.772; - /// Matrix component for ycc transform. - protected internal static float Matrix22 = 0; - - - /// Factory method for creating instances of this class. - /// -- source of image data - /// - /// -- provides colorspace info - /// - /// SYccColorSpaceMapper instance - /// - public static new BlkImgDataSrc createInstance(BlkImgDataSrc src, ColorSpace csMap) - { - return new SYccColorSpaceMapper(src, csMap); - } - - /// Ctor which creates an ICCProfile for the image and initializes - /// all data objects (input, working, and output). - /// - /// - /// -- Source of image data - /// - /// -- provides colorspace info - /// - protected internal SYccColorSpaceMapper(BlkImgDataSrc src, ColorSpace csMap) : base(src, csMap) - { - initialize(); - /* end SYccColorSpaceMapper ctor */ - } - - /// General utility used by ctors - private void initialize() - { - - if (ncomps != 1 && ncomps != 3) - { - System.String msg = "SYccColorSpaceMapper: ycc transformation _not_ applied to " + ncomps + " component image"; - FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.ERROR, msg); - throw new ColorSpaceException(msg); - } - } - - - /// Returns, in the blk argument, a block of image data containing the - /// specifed rectangular area, in the specified component. The data is - /// returned, as a copy of the internal data, therefore the returned data - /// can be modified "in place". - /// - ///

The rectangular area to return is specified by the 'ulx', 'uly', 'w' - /// and 'h' members of the 'blk' argument, relative to the current - /// tile. These members are not modified by this method. The 'offset' of - /// the returned data is 0, and the 'scanw' is the same as the block's - /// width. See the 'DataBlk' class. - /// - ///

If the data array in 'blk' is 'null', then a new one is created. If - /// the data array is not 'null' then it is reused, and it must be large - /// enough to contain the block's data. Otherwise an 'ArrayStoreException' - /// or an 'IndexOutOfBoundsException' is thrown by the Java system. - /// - ///

The returned data has its 'progressive' attribute set to that of the - /// input data. - /// - ///

- /// Its coordinates and dimensions specify the area to - /// return. If it contains a non-null data array, then it must have the - /// correct dimensions. If it contains a null data array a new one is - /// created. The fields in this object are modified to return the data. - /// - /// - /// The index of the component from which to get the data. Only 0 - /// and 3 are valid. - /// - /// - /// The requested DataBlk - /// - /// - /// - /// - public override DataBlk getCompData(DataBlk outblk, int c) - { - - int type = outblk.DataType; - - int i; // j removed - - // Calculate all components: - for (i = 0; i < ncomps; ++i) - { - - // Set up the working DataBlk geometry. - copyGeometry(workInt[i], outblk); - copyGeometry(workFloat[i], outblk); - copyGeometry(inInt[i], outblk); - copyGeometry(inFloat[i], outblk); - - // Request data from the source. - inInt[i] = (DataBlkInt)src.getInternCompData(inInt[i], i); - } - - if (type == DataBlk.TYPE_INT) - { - if (ncomps == 1) - workInt[c] = inInt[c]; - else - workInt = mult(inInt); - outblk.progressive = inInt[c].progressive; - outblk.Data = workInt[c].Data; - } - - if (type == DataBlk.TYPE_FLOAT) - { - if (ncomps == 1) - workFloat[c] = inFloat[c]; - else - workFloat = mult(inFloat); - outblk.progressive = inFloat[c].progressive; - outblk.Data = workFloat[c].Data; - } - - - // Initialize the output block geometry and set the profiled - // data into the output block. - outblk.offset = 0; - outblk.scanw = outblk.w; - - return outblk; - } - - /// Returns, in the blk argument, a block of image data containing the - /// specifed rectangular area, in the specified component. The data is - /// returned, as a reference to the internal data, if any, instead of as a - /// copy, therefore the returned data should not be modified. - /// - ///

The rectangular area to return is specified by the 'ulx', 'uly', 'w' - /// and 'h' members of the 'blk' argument, relative to the current - /// tile. These members are not modified by this method. The 'offset' and - /// 'scanw' of the returned data can be arbitrary. See the 'DataBlk' class. - /// - ///

This method, in general, is more efficient than the 'getCompData()' - /// method since it may not copy the data. However if the array of returned - /// data is to be modified by the caller then the other method is probably - /// preferable. - /// - ///

If possible, the data in the returned 'DataBlk' should be the - /// internal data itself, instead of a copy, in order to increase the data - /// transfer efficiency. However, this depends on the particular - /// implementation (it may be more convenient to just return a copy of the - /// data). This is the reason why the returned data should not be modified. - /// - ///

If the data array in blk is null, then a new one - /// is created if necessary. The implementation of this interface may - /// choose to return the same array or a new one, depending on what is more - /// efficient. Therefore, the data array in blk prior to the - /// method call should not be considered to contain the returned data, a - /// new array may have been created. Instead, get the array from - /// blk after the method has returned. - /// - ///

The returned data may have its 'progressive' attribute set. In this - /// case the returned data is only an approximation of the "final" data. - /// - ///

- /// Its coordinates and dimensions specify the area to return, - /// relative to the current tile. Some fields in this object are modified - /// to return the data. - /// - /// - /// The index of the component from which to get the data. - /// - /// - /// The requested DataBlk - /// - /// - /// - /// - public override DataBlk getInternCompData(DataBlk out_Renamed, int c) - { - return getCompData(out_Renamed, c); - } - - - /// Output a DataBlkFloat array where each sample in each component - /// is the product of the YCC matrix * the vector of samples across - /// the input components. - /// - /// input DataBlkFloat array - /// - /// output DataBlkFloat array - /// - private static DataBlkFloat[] mult(DataBlkFloat[] inblk) - { - - if (inblk.Length != 3) - throw new System.ArgumentException("bad input array size"); - - int i, j; - int length = inblk[0].h * inblk[0].w; - DataBlkFloat[] outblk = new DataBlkFloat[3]; - float[][] out_Renamed = new float[3][]; - float[][] in_Renamed = new float[3][]; - - for (i = 0; i < 3; ++i) - { - in_Renamed[i] = inblk[i].DataFloat; - outblk[i] = new DataBlkFloat(); - copyGeometry(outblk[i], inblk[i]); - outblk[i].offset = inblk[i].offset; - out_Renamed[i] = new float[length]; - outblk[i].Data = out_Renamed[i]; - } - - for (j = 0; j < length; ++j) - { - out_Renamed[0][j] = (Matrix00 * in_Renamed[0][inblk[0].offset + j] + Matrix01 * in_Renamed[1][inblk[1].offset + j] + Matrix02 * in_Renamed[2][inblk[2].offset + j]); - - out_Renamed[1][j] = (Matrix10 * in_Renamed[0][inblk[0].offset + j] + Matrix11 * in_Renamed[1][inblk[1].offset + j] + Matrix12 * in_Renamed[2][inblk[2].offset + j]); - - out_Renamed[2][j] = (Matrix20 * in_Renamed[0][inblk[0].offset + j] + Matrix21 * in_Renamed[1][inblk[1].offset + j] + Matrix22 * in_Renamed[2][inblk[2].offset + j]); - } - - return outblk; - } - - - - /// Output a DataBlkInt array where each sample in each component - /// is the product of the YCC matrix * the vector of samples across - /// the input components. - /// - /// input DataBlkInt array - /// - /// output DataBlkInt array - /// - private static DataBlkInt[] mult(DataBlkInt[] inblk) - { - - if (inblk.Length != 3) - throw new System.ArgumentException("bad input array size"); - - - int i, j; - int length = inblk[0].h * inblk[0].w; - DataBlkInt[] outblk = new DataBlkInt[3]; - int[][] out_Renamed = new int[3][]; - int[][] in_Renamed = new int[3][]; - - for (i = 0; i < 3; ++i) - { - in_Renamed[i] = inblk[i].DataInt; - outblk[i] = new DataBlkInt(); - copyGeometry(outblk[i], inblk[i]); - outblk[i].offset = inblk[i].offset; - out_Renamed[i] = new int[length]; - outblk[i].Data = out_Renamed[i]; - } - - for (j = 0; j < length; ++j) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - out_Renamed[0][j] = (int)(Matrix00 * in_Renamed[0][inblk[0].offset + j] + Matrix01 * in_Renamed[1][inblk[1].offset + j] + Matrix02 * in_Renamed[2][inblk[2].offset + j]); - - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - out_Renamed[1][j] = (int)(Matrix10 * in_Renamed[0][inblk[0].offset + j] + Matrix11 * in_Renamed[1][inblk[1].offset + j] + Matrix12 * in_Renamed[2][inblk[2].offset + j]); - - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - out_Renamed[2][j] = (int)(Matrix20 * in_Renamed[0][inblk[0].offset + j] + Matrix21 * in_Renamed[1][inblk[1].offset + j] + Matrix22 * in_Renamed[2][inblk[2].offset + j]); - } - - return outblk; - } - - - /// Return a suitable String representation of the class instance. - public override System.String ToString() - { - int i; - - System.Text.StringBuilder rep_nComps = new System.Text.StringBuilder("ncomps= ").Append(System.Convert.ToString(ncomps)); - System.Text.StringBuilder rep_comps = new System.Text.StringBuilder(); - - for (i = 0; i < ncomps; ++i) - { - rep_comps.Append(" ").Append("component[").Append(System.Convert.ToString(i)).Append("] height, width = (").Append(src.getCompImgHeight(i)).Append(", ").Append(src.getCompImgWidth(i)).Append(")").Append(eol); - } - - System.Text.StringBuilder rep = new System.Text.StringBuilder("[SYccColorSpaceMapper "); - rep.Append(rep_nComps).Append(eol); - rep.Append(rep_comps).Append(" "); - - return rep.Append("]").ToString(); - } - - - /* end class SYccColorSpaceMapper */ - } -} \ No newline at end of file diff --git a/CSJ2K/Color/boxes/ChannelDefinitionBox.cs b/CSJ2K/Color/boxes/ChannelDefinitionBox.cs deleted file mode 100644 index edb51b12..00000000 --- a/CSJ2K/Color/boxes/ChannelDefinitionBox.cs +++ /dev/null @@ -1,165 +0,0 @@ -/// ************************************************************************** -/// -/// $Id: ChannelDefinitionBox.java,v 1.1 2002/07/25 14:50:46 grosbois Exp $ -/// -/// Copyright Eastman Kodak Company, 343 State Street, Rochester, NY 14650 -/// $Date $ -/// *************************************************************************** -/// -using ICCProfile = CSJ2K.Icc.ICCProfile; -using RandomAccessIO = CSJ2K.j2k.io.RandomAccessIO; -namespace CSJ2K.Color.Boxes -{ - - /// This class maps the components in the codestream - /// to channels in the image. It models the Component - /// Mapping box in the JP2 header. - /// - /// - /// 1.0 - /// - /// Bruce A. Kern - /// - public sealed class ChannelDefinitionBox : JP2Box - { - public int NDefs - { - /* Return the number of channel definitions. */ - - get - { - return ndefs; - } - - } - - private int ndefs; - private System.Collections.Hashtable definitions = System.Collections.Hashtable.Synchronized(new System.Collections.Hashtable()); - - /// Construct a ChannelDefinitionBox from an input image. - /// RandomAccessIO jp2 image - /// - /// offset to the start of the box in the image - /// - /// ColorSpaceException - /// - public ChannelDefinitionBox(RandomAccessIO in_Renamed, int boxStart) : base(in_Renamed, boxStart) - { - readBox(); - } - - /// Analyze the box content. - private void readBox() - { - - byte[] bfr = new byte[8]; - - in_Renamed.seek(dataStart); - in_Renamed.readFully(bfr, 0, 2); - ndefs = ICCProfile.getShort(bfr, 0) & 0x0000ffff; - - int offset = dataStart + 2; - in_Renamed.seek(offset); - for (int i = 0; i < ndefs; ++i) - { - in_Renamed.readFully(bfr, 0, 6); - int channel = ICCProfile.getShort(bfr, 0); - int[] channel_def = new int[3]; - channel_def[0] = getCn(bfr); - channel_def[1] = getTyp(bfr); - channel_def[2] = getAsoc(bfr); - definitions[(System.Int32)channel_def[0]] = channel_def; - } - } - - /* Return the channel association. */ - public int getCn(int asoc) - { - System.Collections.IEnumerator keys = definitions.Keys.GetEnumerator(); - //UPGRADE_TODO: Method 'java.util.Enumeration.hasMoreElements' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationhasMoreElements'" - while (keys.MoveNext()) - { - //UPGRADE_TODO: Method 'java.util.Enumeration.nextElement' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationnextElement'" - int[] bfr = (int[])definitions[keys.Current]; - if (asoc == getAsoc(bfr)) - return getCn(bfr); - } - return asoc; - } - - /* Return the channel type. */ - public int getTyp(int channel) - { - int[] bfr = (int[])definitions[(System.Int32)channel]; - return getTyp(bfr); - } - - /* Return the associated channel of the association. */ - public int getAsoc(int channel) - { - int[] bfr = (int[])definitions[(System.Int32)channel]; - return getAsoc(bfr); - } - - - /// Return a suitable String representation of the class instance. - public override System.String ToString() - { - System.Text.StringBuilder rep = new System.Text.StringBuilder("[ChannelDefinitionBox ").Append(eol).Append(" "); - rep.Append("ndefs= ").Append(System.Convert.ToString(ndefs)); - - System.Collections.IEnumerator keys = definitions.Keys.GetEnumerator(); - //UPGRADE_TODO: Method 'java.util.Enumeration.hasMoreElements' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationhasMoreElements'" - while (keys.MoveNext()) - { - //UPGRADE_TODO: Method 'java.util.Enumeration.nextElement' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationnextElement'" - int[] bfr = (int[])definitions[keys.Current]; - rep.Append(eol).Append(" ").Append("Cn= ").Append(System.Convert.ToString(getCn(bfr))).Append(", ").Append("Typ= ").Append(System.Convert.ToString(getTyp(bfr))).Append(", ").Append("Asoc= ").Append(System.Convert.ToString(getAsoc(bfr))); - } - - rep.Append("]"); - return rep.ToString(); - } - - /// Return the channel from the record. - private int getCn(byte[] bfr) - { - return ICCProfile.getShort(bfr, 0); - } - - /// Return the channel type from the record. - private int getTyp(byte[] bfr) - { - return ICCProfile.getShort(bfr, 2); - } - - /// Return the associated channel from the record. - private int getAsoc(byte[] bfr) - { - return ICCProfile.getShort(bfr, 4); - } - - private int getCn(int[] bfr) - { - return bfr[0]; - } - - private int getTyp(int[] bfr) - { - return bfr[1]; - } - - private int getAsoc(int[] bfr) - { - return bfr[2]; - } - - /* end class ChannelDefinitionBox */ - static ChannelDefinitionBox() - { - { - type = 0x63646566; - } - } - } -} \ No newline at end of file diff --git a/CSJ2K/Color/boxes/ColorSpecificationBox.cs b/CSJ2K/Color/boxes/ColorSpecificationBox.cs deleted file mode 100644 index 647e23f2..00000000 --- a/CSJ2K/Color/boxes/ColorSpecificationBox.cs +++ /dev/null @@ -1,217 +0,0 @@ -using CSJ2K.j2k.io; -/// ************************************************************************** -/// -/// $Id: ColorSpecificationBox.java,v 1.3 2002/08/08 14:07:53 grosbois Exp $ -/// -/// Copyright Eastman Kodak Company, 343 State Street, Rochester, NY 14650 -/// $Date $ -/// *************************************************************************** -/// -using CSJ2K.j2k.util; -namespace CSJ2K.Color.Boxes -{ - - /// This class models the Color Specification Box in a JP2 image. - /// - /// - /// 1.0 - /// - /// Bruce A. Kern - /// - public sealed class ColorSpecificationBox : JP2Box - { - - public ColorSpace.MethodEnum Method - { - // Return an enumeration for the colorspace method. - - get - { - return method; - } - - } - public ColorSpace.CSEnum ColorSpace - { - // Return an enumeration for the colorspace. - - get - { - return colorSpace; - } - - } - - public System.String ColorSpaceString - { - // Return a String representation of the colorspace. - - get - { - return colorSpace.ToString(); - } - - } - public System.String MethodString - { - // Return a String representation of the colorspace method. - - get - { - return method.ToString(); - } - - } - - public byte[] ICCProfile - { - /* Retrieve the ICC Profile from the image as a byte []. */ - - get - { - return iccProfile; - } - - } - - private ColorSpace.MethodEnum method; - private ColorSpace.CSEnum colorSpace; - private byte[] iccProfile = null; - - /// Construct a ColorSpecificationBox from an input image. - /// RandomAccessIO jp2 image - /// - /// offset to the start of the box in the image - /// - /// ColorSpaceException - /// - /// - public ColorSpecificationBox(RandomAccessIO in_Renamed, int boxStart) : base(in_Renamed, boxStart) - { - readBox(); - } - - /// Analyze the box content. - private void readBox() - { - byte[] boxHeader = new byte[256]; - in_Renamed.seek(dataStart); - in_Renamed.readFully(boxHeader, 0, 11); - switch (boxHeader[0]) - { - - case 1: - method = CSJ2K.Color.ColorSpace.MethodEnum.ENUMERATED; - int cs = CSJ2K.Icc.ICCProfile.getInt(boxHeader, 3); - switch (cs) - { - case 16: - colorSpace = CSJ2K.Color.ColorSpace.CSEnum.sRGB; - break; // from switch (cs)... - - case 17: - colorSpace = CSJ2K.Color.ColorSpace.CSEnum.GreyScale; - break; // from switch (cs)... - - case 18: - colorSpace = CSJ2K.Color.ColorSpace.CSEnum.sYCC; - break; // from switch (cs)... - case 20: - colorSpace = CSJ2K.Color.ColorSpace.CSEnum.esRGB; - break; - - #region Known but unsupported colorspaces - case 3: - FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.WARNING, "Unsupported enumerated colorspace YCbCr(2) in color specification box"); - colorSpace = CSJ2K.Color.ColorSpace.CSEnum.Unknown; - break; - case 4: - FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.WARNING, "Unsupported enumerated colorspace YCbCr(3) in color specification box"); - colorSpace = CSJ2K.Color.ColorSpace.CSEnum.Unknown; - break; - case 9: - FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.WARNING, "Unsupported enumerated colorspace PhotoYCC in color specification box"); - colorSpace = CSJ2K.Color.ColorSpace.CSEnum.Unknown; - break; - case 11: - FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.WARNING, "Unsupported enumerated colorspace CMY in color specification box"); - colorSpace = CSJ2K.Color.ColorSpace.CSEnum.Unknown; - break; - case 12: - FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.WARNING, "Unsupported enumerated colorspace CMYK in color specification box"); - colorSpace = CSJ2K.Color.ColorSpace.CSEnum.Unknown; - break; - case 13: - FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.WARNING, "Unsupported enumerated colorspace YCCK in color specification box"); - colorSpace = CSJ2K.Color.ColorSpace.CSEnum.Unknown; - break; - case 14: - FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.WARNING, "Unsupported enumerated colorspace CIELab in color specification box"); - colorSpace = CSJ2K.Color.ColorSpace.CSEnum.Unknown; - break; - case 15: - FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.WARNING, "Unsupported enumerated colorspace Bi-Level(2) in color specification box"); - colorSpace = CSJ2K.Color.ColorSpace.CSEnum.Unknown; - break; - case 19: - FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.WARNING, "Unsupported enumerated colorspace CIEJab in color specification box"); - colorSpace = CSJ2K.Color.ColorSpace.CSEnum.Unknown; - break; - case 21: - FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.WARNING, "Unsupported enumerated colorspace ROMM-RGB in color specification box"); - colorSpace = CSJ2K.Color.ColorSpace.CSEnum.Unknown; - break; - case 22: - FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.WARNING, "Unsupported enumerated colorspace YPbPr(1125/60) in color specification box"); - colorSpace = CSJ2K.Color.ColorSpace.CSEnum.Unknown; - break; - case 23: - FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.WARNING, "Unsupported enumerated colorspace YPbPr(1250/50) in color specification box"); - colorSpace = CSJ2K.Color.ColorSpace.CSEnum.Unknown; - break; - case 24: - FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.WARNING, "Unsupported enumerated colorspace e-sYCC in color specification box"); - colorSpace = CSJ2K.Color.ColorSpace.CSEnum.Unknown; - break; - #endregion - - default: - FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.WARNING, "Unknown enumerated colorspace (" + cs + ") in color specification box"); - colorSpace = CSJ2K.Color.ColorSpace.CSEnum.Unknown; - break; - - } - break; // from switch (boxHeader[0])... - - case 2: - method = CSJ2K.Color.ColorSpace.MethodEnum.ICC_PROFILED; - int size = CSJ2K.Icc.ICCProfile.getInt(boxHeader, 3); - iccProfile = new byte[size]; - in_Renamed.seek(dataStart + 3); - in_Renamed.readFully(iccProfile, 0, size); - break; // from switch (boxHeader[0])... - - default: - throw new ColorSpaceException("Bad specification method (" + boxHeader[0] + ") in " + this); - - } - } - - /// Return a suitable String representation of the class instance. - public override System.String ToString() - { - System.Text.StringBuilder rep = new System.Text.StringBuilder("[ColorSpecificationBox "); - rep.Append("method= ").Append(System.Convert.ToString(method)).Append(", "); - rep.Append("colorspace= ").Append(System.Convert.ToString(colorSpace)).Append("]"); - return rep.ToString(); - } - - /* end class ColorSpecificationBox */ - static ColorSpecificationBox() - { - { - type = 0x636f6c72; - } - } - } -} \ No newline at end of file diff --git a/CSJ2K/Color/boxes/ComponentMappingBox.cs b/CSJ2K/Color/boxes/ComponentMappingBox.cs deleted file mode 100644 index 560d76bb..00000000 --- a/CSJ2K/Color/boxes/ComponentMappingBox.cs +++ /dev/null @@ -1,127 +0,0 @@ -/// ************************************************************************** -/// -/// $Id: ComponentMappingBox.java,v 1.1 2002/07/25 14:50:46 grosbois Exp $ -/// -/// Copyright Eastman Kodak Company, 343 State Street, Rochester, NY 14650 -/// $Date $ -/// *************************************************************************** -/// -using ICCProfile = CSJ2K.Icc.ICCProfile; -using RandomAccessIO = CSJ2K.j2k.io.RandomAccessIO; -namespace CSJ2K.Color.Boxes -{ - - /// This class maps the components in the codestream - /// to channels in the image. It models the Component - /// Mapping box in the JP2 header. - /// - /// - /// 1.0 - /// - /// Bruce A. Kern - /// - public sealed class ComponentMappingBox : JP2Box - { - public int NChannels - { - /* Return the number of mapped channels. */ - - get - { - return nChannels; - } - - } - - private int nChannels; - private System.Collections.ArrayList map = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); - - /// Construct a ComponentMappingBox from an input image. - /// RandomAccessIO jp2 image - /// - /// offset to the start of the box in the image - /// - /// ColorSpaceException - /// - public ComponentMappingBox(RandomAccessIO in_Renamed, int boxStart) : base(in_Renamed, boxStart) - { - readBox(); - } - - /// Analyze the box content. - internal void readBox() - { - nChannels = (boxEnd - dataStart) / 4; - in_Renamed.seek(dataStart); - for (int offset = dataStart; offset < boxEnd; offset += 4) - { - byte[] mapping = new byte[4]; - in_Renamed.readFully(mapping, 0, 4); - map.Add(mapping); - } - } - - /* Return the component mapped to the channel. */ - public int getCMP(int channel) - { - byte[] mapping = (byte[])map[channel]; - return ICCProfile.getShort(mapping, 0) & 0x0000ffff; - } - - /// Return the channel type. - public short getMTYP(int channel) - { - byte[] mapping = (byte[])map[channel]; - return (short)(mapping[2] & 0x00ff); - } - - /// Return the palette index for the channel. - public short getPCOL(int channel) - { - byte[] mapping = (byte[])map[channel]; - return (short)(mapping[3] & 0x000ff); - } - - /// Return a suitable String representation of the class instance. - public override System.String ToString() - { - System.Text.StringBuilder rep = new System.Text.StringBuilder("[ComponentMappingBox ").Append(" "); - rep.Append("nChannels= ").Append(System.Convert.ToString(nChannels)); - System.Collections.IEnumerator Enum = map.GetEnumerator(); - //UPGRADE_TODO: Method 'java.util.Enumeration.hasMoreElements' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationhasMoreElements'" - while (Enum.MoveNext()) - { - //UPGRADE_TODO: Method 'java.util.Enumeration.nextElement' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationnextElement'" - byte[] bfr = (byte[])Enum.Current; - rep.Append(eol).Append(" ").Append("CMP= ").Append(System.Convert.ToString(getCMP(bfr))).Append(", "); - rep.Append("MTYP= ").Append(System.Convert.ToString(getMTYP(bfr))).Append(", "); - rep.Append("PCOL= ").Append(System.Convert.ToString(getPCOL(bfr))); - } - rep.Append("]"); - return rep.ToString(); - } - - private int getCMP(byte[] mapping) - { - return ICCProfile.getShort(mapping, 0) & 0x0000ffff; - } - - private short getMTYP(byte[] mapping) - { - return (short)(mapping[2] & 0x00ff); - } - - private short getPCOL(byte[] mapping) - { - return (short)(mapping[3] & 0x000ff); - } - - /* end class ComponentMappingBox */ - static ComponentMappingBox() - { - { - type = 0x636d6170; - } - } - } -} \ No newline at end of file diff --git a/CSJ2K/Color/boxes/ImageHeaderBox.cs b/CSJ2K/Color/boxes/ImageHeaderBox.cs deleted file mode 100644 index f79d41f4..00000000 --- a/CSJ2K/Color/boxes/ImageHeaderBox.cs +++ /dev/null @@ -1,88 +0,0 @@ -using ICCProfile = CSJ2K.Icc.ICCProfile; -/// ************************************************************************** -/// -/// $Id: ImageHeaderBox.java,v 1.1 2002/07/25 14:50:47 grosbois Exp $ -/// -/// Copyright Eastman Kodak Company, 343 State Street, Rochester, NY 14650 -/// $Date $ -/// *************************************************************************** -/// -using RandomAccessIO = CSJ2K.j2k.io.RandomAccessIO; -namespace CSJ2K.Color.Boxes -{ - - /// This class models the Image Header box contained in a JP2 - /// image. It is a stub class here since for colormapping the - /// knowlege of the existance of the box in the image is sufficient. - /// - /// - /// 1.0 - /// - /// Bruce A. Kern - /// - public sealed class ImageHeaderBox : JP2Box - { - - internal long height; - internal long width; - internal int nc; - internal short bpc; - internal short c; - internal bool unk; - internal bool ipr; - - - /// Construct an ImageHeaderBox from an input image. - /// RandomAccessIO jp2 image - /// - /// offset to the start of the box in the image - /// - /// ColorSpaceException - /// - public ImageHeaderBox(RandomAccessIO in_Renamed, int boxStart) : base(in_Renamed, boxStart) - { - readBox(); - } - - /// Return a suitable String representation of the class instance. - public override System.String ToString() - { - System.Text.StringBuilder rep = new System.Text.StringBuilder("[ImageHeaderBox ").Append(eol).Append(" "); - rep.Append("height= ").Append(System.Convert.ToString(height)).Append(", "); - rep.Append("width= ").Append(System.Convert.ToString(width)).Append(eol).Append(" "); - - rep.Append("nc= ").Append(System.Convert.ToString(nc)).Append(", "); - rep.Append("bpc= ").Append(System.Convert.ToString(bpc)).Append(", "); - rep.Append("c= ").Append(System.Convert.ToString(c)).Append(eol).Append(" "); - - rep.Append("image colorspace is ").Append(new System.Text.StringBuilder(unk == true ? "known" : "unknown").ToString()); - rep.Append(", the image ").Append(new System.Text.StringBuilder(ipr == true ? "contains " : "does not contain ").ToString()).Append("intellectual property").Append("]"); - - return rep.ToString(); - } - - /// Analyze the box content. - internal void readBox() - { - byte[] bfr = new byte[14]; - in_Renamed.seek(dataStart); - in_Renamed.readFully(bfr, 0, 14); - - height = ICCProfile.getInt(bfr, 0); - width = ICCProfile.getInt(bfr, 4); - nc = ICCProfile.getShort(bfr, 8); - bpc = (short)(bfr[10] & 0x00ff); - c = (short)(bfr[11] & 0x00ff); - unk = bfr[12] == 0 ? true : false; - ipr = bfr[13] == 1 ? true : false; - } - - /* end class ImageHeaderBox */ - static ImageHeaderBox() - { - { - type = 69686472; - } - } - } -} \ No newline at end of file diff --git a/CSJ2K/Color/boxes/JP2Box.cs b/CSJ2K/Color/boxes/JP2Box.cs deleted file mode 100644 index 719300ef..00000000 --- a/CSJ2K/Color/boxes/JP2Box.cs +++ /dev/null @@ -1,138 +0,0 @@ -/// ************************************************************************** -/// -/// $Id: JP2Box.java,v 1.1 2002/07/25 14:50:47 grosbois Exp $ -/// -/// Copyright Eastman Kodak Company, 343 State Street, Rochester, NY 14650 -/// $Date $ -/// *************************************************************************** -/// -using System; -using ICCProfile = CSJ2K.Icc.ICCProfile; -using RandomAccessIO = CSJ2K.j2k.io.RandomAccessIO; -namespace CSJ2K.Color.Boxes -{ - - /// The abstract super class modeling the aspects of - /// a JP2 box common to all such boxes. - /// - /// - /// 1.0 - /// - /// Bruce A. Kern - /// - public abstract class JP2Box - { - /// Platform dependant line terminator - //UPGRADE_NOTE: Final was removed from the declaration of 'eol '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly System.String eol = System.Environment.NewLine; - /// Box type - public static int type; - - /// Return a String representation of the Box type. - public static System.String getTypeString(int t) - { - return BoxType.get_Renamed(t); - } - - /// Length of the box. - public int length; - /// input file - protected internal RandomAccessIO in_Renamed; - /// offset to start of box - protected internal int boxStart; - /// offset to end of box - protected internal int boxEnd; - /// offset to start of data in box - protected internal int dataStart; - - public JP2Box() - { - try - { - throw new ColorSpaceException("JP2Box empty ctor called!!"); - } - catch (ColorSpaceException e) - { - SupportClass.WriteStackTrace(e, Console.Error); throw e; - } - } - - /// Construct a JP2Box from an input image. - /// RandomAccessIO jp2 image - /// - /// offset to the start of the box in the image - /// - /// ColorSpaceException - /// - public JP2Box(RandomAccessIO in_Renamed, int boxStart) - { - byte[] boxHeader = new byte[16]; - - this.in_Renamed = in_Renamed; - this.boxStart = boxStart; - - this.in_Renamed.seek(this.boxStart); - this.in_Renamed.readFully(boxHeader, 0, 8); - - this.dataStart = boxStart + 8; - this.length = ICCProfile.getInt(boxHeader, 0); - this.boxEnd = boxStart + length; - if (length == 1) - throw new ColorSpaceException("extended length boxes not supported"); - } - - - /// Return the box type as a String. - public virtual System.String getTypeString() - { - return BoxType.get_Renamed(JP2Box.type); - } - - - /// JP2 Box structure analysis help - [Serializable] - protected internal class BoxType : System.Collections.Hashtable - { - - private static System.Collections.Hashtable map = System.Collections.Hashtable.Synchronized(new System.Collections.Hashtable()); - - private static void put(int type, System.String desc) - { - map[(System.Int32)type] = desc; - } - - public static System.String get_Renamed(int type) - { - return (System.String)map[(System.Int32)type]; - } - - /* end class BoxType */ - static BoxType() - { - { - put(CSJ2K.j2k.fileformat.FileFormatBoxes.BITS_PER_COMPONENT_BOX, "BITS_PER_COMPONENT_BOX"); - put(CSJ2K.j2k.fileformat.FileFormatBoxes.CAPTURE_RESOLUTION_BOX, "CAPTURE_RESOLUTION_BOX"); - put(CSJ2K.j2k.fileformat.FileFormatBoxes.CHANNEL_DEFINITION_BOX, "CHANNEL_DEFINITION_BOX"); - put(CSJ2K.j2k.fileformat.FileFormatBoxes.COLOUR_SPECIFICATION_BOX, "COLOUR_SPECIFICATION_BOX"); - put(CSJ2K.j2k.fileformat.FileFormatBoxes.COMPONENT_MAPPING_BOX, "COMPONENT_MAPPING_BOX"); - put(CSJ2K.j2k.fileformat.FileFormatBoxes.CONTIGUOUS_CODESTREAM_BOX, "CONTIGUOUS_CODESTREAM_BOX"); - put(CSJ2K.j2k.fileformat.FileFormatBoxes.DEFAULT_DISPLAY_RESOLUTION_BOX, "DEFAULT_DISPLAY_RESOLUTION_BOX"); - put(CSJ2K.j2k.fileformat.FileFormatBoxes.FILE_TYPE_BOX, "FILE_TYPE_BOX"); - put(CSJ2K.j2k.fileformat.FileFormatBoxes.IMAGE_HEADER_BOX, "IMAGE_HEADER_BOX"); - put(CSJ2K.j2k.fileformat.FileFormatBoxes.INTELLECTUAL_PROPERTY_BOX, "INTELLECTUAL_PROPERTY_BOX"); - put(CSJ2K.j2k.fileformat.FileFormatBoxes.JP2_HEADER_BOX, "JP2_HEADER_BOX"); - put(CSJ2K.j2k.fileformat.FileFormatBoxes.JP2_SIGNATURE_BOX, "JP2_SIGNATURE_BOX"); - put(CSJ2K.j2k.fileformat.FileFormatBoxes.PALETTE_BOX, "PALETTE_BOX"); - put(CSJ2K.j2k.fileformat.FileFormatBoxes.RESOLUTION_BOX, "RESOLUTION_BOX"); - put(CSJ2K.j2k.fileformat.FileFormatBoxes.URL_BOX, "URL_BOX"); - put(CSJ2K.j2k.fileformat.FileFormatBoxes.UUID_BOX, "UUID_BOX"); - put(CSJ2K.j2k.fileformat.FileFormatBoxes.UUID_INFO_BOX, "UUID_INFO_BOX"); - put(CSJ2K.j2k.fileformat.FileFormatBoxes.UUID_LIST_BOX, "UUID_LIST_BOX"); - put(CSJ2K.j2k.fileformat.FileFormatBoxes.XML_BOX, "XML_BOX"); - } - } - } - - /* end class JP2Box */ - } -} \ No newline at end of file diff --git a/CSJ2K/Color/boxes/PaletteBox.cs b/CSJ2K/Color/boxes/PaletteBox.cs deleted file mode 100644 index e7005f8f..00000000 --- a/CSJ2K/Color/boxes/PaletteBox.cs +++ /dev/null @@ -1,189 +0,0 @@ -/// ************************************************************************** -/// -/// $Id: PaletteBox.java,v 1.1 2002/07/25 14:50:47 grosbois Exp $ -/// -/// Copyright Eastman Kodak Company, 343 State Street, Rochester, NY 14650 -/// $Date $ -/// *************************************************************************** -/// -using ICCProfile = CSJ2K.Icc.ICCProfile; -using RandomAccessIO = CSJ2K.j2k.io.RandomAccessIO; -namespace CSJ2K.Color.Boxes -{ - - /// This class models the palette box contained in a JP2 - /// image. - /// - /// - /// 1.0 - /// - /// Bruce A. Kern - /// - public sealed class PaletteBox : JP2Box - { - /// Return the number of palette entries. - public int NumEntries - { - get - { - return nentries; - } - - } - /// Return the number of palette columns. - public int NumColumns - { - get - { - return ncolumns; - } - - } - - private int nentries; - private int ncolumns; - private short[] bitdepth; - private int[][] entries; - - /// Construct a PaletteBox from an input image. - /// RandomAccessIO jp2 image - /// - /// offset to the start of the box in the image - /// - /// ColorSpaceException - /// - public PaletteBox(RandomAccessIO in_Renamed, int boxStart) : base(in_Renamed, boxStart) - { - readBox(); - } - - /// Analyze the box content. - internal void readBox() - { - byte[] bfr = new byte[4]; - int i, j, b, m; - //int entry; - - // Read the number of palette entries and columns per entry. - in_Renamed.seek((int)dataStart); - in_Renamed.readFully(bfr, 0, 3); - nentries = ICCProfile.getShort(bfr, 0) & 0x0000ffff; - ncolumns = bfr[2] & 0x0000ffff; - - // Read the bitdepths for each column - bitdepth = new short[ncolumns]; - bfr = new byte[ncolumns]; - in_Renamed.readFully(bfr, 0, ncolumns); - for (i = 0; i < ncolumns; ++i) - { - bitdepth[i] = (short)(bfr[i] & 0x00fff); - } - - entries = new int[nentries * ncolumns][]; - - bfr = new byte[2]; - for (i = 0; i < nentries; ++i) - { - entries[i] = new int[ncolumns]; - - for (j = 0; j < ncolumns; ++j) - { - - int bd = getBitDepth(j); - bool signed = isSigned(j); - - switch (getEntrySize(j)) - { - - case 1: // 8 bit entries - in_Renamed.readFully(bfr, 0, 1); - b = bfr[0]; - break; - - - case 2: // 16 bits - in_Renamed.readFully(bfr, 0, 2); - b = ICCProfile.getShort(bfr, 0); - break; - - - default: - throw new ColorSpaceException("palettes greater than 16 bits deep not supported"); - - } - - if (signed) - { - // Do sign extension if high bit is set. - if ((b & (1 << (bd - 1))) == 0) - { - // high bit not set. - m = (1 << bd) - 1; - entries[i][j] = m & b; - } - else - { - // high bit set. - // CONVERSION PROBLEM? - m = unchecked((int)(0xffffffff << bd)); - entries[i][j] = m | b; - } - } - else - { - // Clear all high bits. - m = (1 << bd) - 1; - entries[i][j] = m & b; - } - } - } - } - - /// Are entries signed predicate. - public bool isSigned(int column) - { - return (bitdepth[column] & 0x80) == 1; - } - - /// Are entries unsigned predicate. - public bool isUnSigned(int column) - { - return !isSigned(column); - } - - /// Return the bitdepth of palette entries. - public short getBitDepth(int column) - { - return (short)((bitdepth[column] & 0x7f) + 1); - } - - /// Return an entry for a given index and column. - public int getEntry(int column, int entry) - { - return entries[entry][column]; - } - - /// Return a suitable String representation of the class instance. - public override System.String ToString() - { - System.Text.StringBuilder rep = new System.Text.StringBuilder("[PaletteBox ").Append("nentries= ").Append(System.Convert.ToString(nentries)).Append(", ncolumns= ").Append(System.Convert.ToString(ncolumns)).Append(", bitdepth per column= ("); - for (int i = 0; i < ncolumns; ++i) - rep.Append(getBitDepth(i)).Append(isSigned(i) ? "S" : "U").Append(i < ncolumns - 1 ? ", " : ""); - return rep.Append(")]").ToString(); - } - - private int getEntrySize(int column) - { - int bd = getBitDepth(column); - return bd / 8 + (bd % 8) == 0 ? 0 : 1; - } - - /* end class PaletteBox */ - static PaletteBox() - { - { - type = 0x70636c72; - } - } - } -} \ No newline at end of file diff --git a/CSJ2K/Icc/ICCMatrixBasedInputProfile.cs b/CSJ2K/Icc/ICCMatrixBasedInputProfile.cs deleted file mode 100644 index fd32bbeb..00000000 --- a/CSJ2K/Icc/ICCMatrixBasedInputProfile.cs +++ /dev/null @@ -1,56 +0,0 @@ -/// ************************************************************************** -/// -/// $Id: ICCMatrixBasedInputProfile.java,v 1.1 2002/07/25 14:56:54 grosbois Exp $ -/// -/// Copyright Eastman Kodak Company, 343 State Street, Rochester, NY 14650 -/// $Date $ -/// *************************************************************************** -/// -using ColorSpace = CSJ2K.Color.ColorSpace; -using ColorSpaceException = CSJ2K.Color.ColorSpaceException; -namespace CSJ2K.Icc -{ - - /// This class enables an application to construct an 3 component ICCProfile - /// - /// - /// 1.0 - /// - /// Bruce A. Kern - /// - - public class ICCMatrixBasedInputProfile : ICCProfile - { - - /// Factory method to create ICCMatrixBasedInputProfile based on a - /// suppled profile file. - /// - /// contains a disk based ICCProfile. - /// - /// the ICCMatrixBasedInputProfile - /// - /// - /// - /// - /// - public static ICCMatrixBasedInputProfile createInstance(ColorSpace csm) - { - return new ICCMatrixBasedInputProfile(csm); - } - - /// Construct an ICCMatrixBasedInputProfile based on a - /// suppled profile file. - /// - /// contains a disk based ICCProfile. - /// - /// - /// - /// - /// - protected internal ICCMatrixBasedInputProfile(ColorSpace csm) : base(csm) - { - } - - /* end class ICCMatrixBasedInputProfile */ - } -} \ No newline at end of file diff --git a/CSJ2K/Icc/ICCMonochromeInputProfile.cs b/CSJ2K/Icc/ICCMonochromeInputProfile.cs deleted file mode 100644 index 0e6d40d6..00000000 --- a/CSJ2K/Icc/ICCMonochromeInputProfile.cs +++ /dev/null @@ -1,53 +0,0 @@ -/// ************************************************************************** -/// -/// $Id: ICCMonochromeInputProfile.java,v 1.1 2002/07/25 14:56:54 grosbois Exp $ -/// -/// Copyright Eastman Kodak Company, 343 State Street, Rochester, NY 14650 -/// $Date $ -/// *************************************************************************** -/// -using ColorSpace = CSJ2K.Color.ColorSpace; -using ColorSpaceException = CSJ2K.Color.ColorSpaceException; -namespace CSJ2K.Icc -{ - - /// The monochrome ICCProfile. - /// - /// - /// 1.0 - /// - /// Bruce A. Kern - /// - public class ICCMonochromeInputProfile : ICCProfile - { - - /// Return the ICCProfile embedded in the input image - /// jp2 image with embedded profile - /// - /// ICCMonochromeInputProfile - /// - /// - /// - /// - /// - public static ICCMonochromeInputProfile createInstance(ColorSpace csm) - { - return new ICCMonochromeInputProfile(csm); - } - - /// Construct a ICCMonochromeInputProfile corresponding to the profile file - /// disk based ICCMonochromeInputProfile - /// - /// theICCMonochromeInputProfile - /// - /// - /// - /// - /// - protected internal ICCMonochromeInputProfile(ColorSpace csm) : base(csm) - { - } - - /* end class ICCMonochromeInputProfile */ - } -} \ No newline at end of file diff --git a/CSJ2K/Icc/ICCProfile.cs b/CSJ2K/Icc/ICCProfile.cs deleted file mode 100644 index 14010b4c..00000000 --- a/CSJ2K/Icc/ICCProfile.cs +++ /dev/null @@ -1,973 +0,0 @@ -/// ************************************************************************** -/// -/// $Id: ICCProfile.java,v 1.1 2002/07/25 14:56:55 grosbois Exp $ -/// -/// Copyright Eastman Kodak Company, 343 State Street, Rochester, NY 14650 -/// $Date $ -/// *************************************************************************** -/// -using System; -using System.Text; -using ColorSpace = CSJ2K.Color.ColorSpace; -using FacilityManager = CSJ2K.j2k.util.FacilityManager; -using ICCCurveType = CSJ2K.Icc.Tags.ICCCurveType; -using ICCDateTime = CSJ2K.Icc.Types.ICCDateTime; -using ICCProfileHeader = CSJ2K.Icc.Types.ICCProfileHeader; -using ICCProfileVersion = CSJ2K.Icc.Types.ICCProfileVersion; -using ICCTagTable = CSJ2K.Icc.Tags.ICCTagTable; -using ICCXYZType = CSJ2K.Icc.Tags.ICCXYZType; -using ParameterList = CSJ2K.j2k.util.ParameterList; -using XYZNumber = CSJ2K.Icc.Types.XYZNumber; -namespace CSJ2K.Icc -{ - - /// This class models the ICCProfile file. This file is a binary file which is divided - /// into two parts, an ICCProfileHeader followed by an ICCTagTable. The header is a - /// straightforward list of descriptive parameters such as profile size, version, date and various - /// more esoteric parameters. The tag table is a structured list of more complexly aggragated data - /// describing things such as ICC curves, copyright information, descriptive text blocks, etc. - /// - /// Classes exist to model the header and tag table and their various constituent parts the developer - /// is refered to these for further information on the structure and contents of the header and tag table. - /// - /// - /// - /// - /// - /// - /// 1.0 - /// - /// Bruce A. Kern - /// - - public abstract class ICCProfile - { - private int ProfileSize - { - get - { - return header.dwProfileSize; - } - - set - { - header.dwProfileSize = value; - } - - } - private int CMMTypeSignature - { - get - { - return header.dwCMMTypeSignature; - } - - set - { - header.dwCMMTypeSignature = value; - } - - } - private int ProfileClass - { - get - { - return header.dwProfileClass; - } - - set - { - header.dwProfileClass = value; - } - - } - private int ColorSpaceType - { - get - { - return header.dwColorSpaceType; - } - - set - { - header.dwColorSpaceType = value; - } - - } - private int PCSType - { - get - { - return header.dwPCSType; - } - - set - { - header.dwPCSType = value; - } - - } - private int ProfileSignature - { - get - { - return header.dwProfileSignature; - } - - set - { - header.dwProfileSignature = value; - } - - } - private int PlatformSignature - { - get - { - return header.dwPlatformSignature; - } - - set - { - header.dwPlatformSignature = value; - } - - } - private int CMMFlags - { - get - { - return header.dwCMMFlags; - } - - set - { - header.dwCMMFlags = value; - } - - } - private int DeviceManufacturer - { - get - { - return header.dwDeviceManufacturer; - } - - set - { - header.dwDeviceManufacturer = value; - } - - } - private int DeviceModel - { - get - { - return header.dwDeviceModel; - } - - set - { - header.dwDeviceModel = value; - } - - } - private int DeviceAttributes1 - { - get - { - return header.dwDeviceAttributes1; - } - - set - { - header.dwDeviceAttributes1 = value; - } - - } - private int DeviceAttributesReserved - { - get - { - return header.dwDeviceAttributesReserved; - } - - set - { - header.dwDeviceAttributesReserved = value; - } - - } - private int RenderingIntent - { - get - { - return header.dwRenderingIntent; - } - - set - { - header.dwRenderingIntent = value; - } - - } - private int CreatorSig - { - get - { - return header.dwCreatorSig; - } - - set - { - header.dwCreatorSig = value; - } - - } - private ICCProfileVersion ProfileVersion - { - get - { - return header.profileVersion; - } - - set - { - header.profileVersion = value; - } - - } - private XYZNumber PCSIlluminant - { - set - { - header.PCSIlluminant = value; - } - - } - private ICCDateTime DateTime - { - set - { - header.dateTime = value; - } - - } - /// Access the profile header - /// ICCProfileHeader - /// - virtual public ICCProfileHeader Header - { - get - { - return header; - } - - } - /// Access the profile tag table - /// ICCTagTable - /// - virtual public ICCTagTable TagTable - { - get - { - return tags; - } - - } - - //UPGRADE_NOTE: Final was removed from the declaration of 'eol '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly System.String eol = System.Environment.NewLine; - - /// Gray index. - // Renamed for convenience: - public const int GRAY = 0; - /// RGB index. - public const int RED = 0; - /// RGB index. - public const int GREEN = 1; - /// RGB index. - public const int BLUE = 2; - - /// Size of native type - public const int boolean_size = 1; - /// Size of native type - public const int byte_size = 1; - /// Size of native type - public const int char_size = 2; - /// Size of native type - public const int short_size = 2; - /// Size of native type - public const int int_size = 4; - /// Size of native type - public const int float_size = 4; - /// Size of native type - public const int long_size = 8; - /// Size of native type - public const int double_size = 8; - - /* Bit twiddling constant for integral types. */ - public const int BITS_PER_BYTE = 8; - /* Bit twiddling constant for integral types. */ - public const int BITS_PER_SHORT = 16; - /* Bit twiddling constant for integral types. */ - public const int BITS_PER_INT = 32; - /* Bit twiddling constant for integral types. */ - public const int BITS_PER_LONG = 64; - /* Bit twiddling constant for integral types. */ - public const int BYTES_PER_SHORT = 2; - /* Bit twiddling constant for integral types. */ - public const int BYTES_PER_INT = 4; - /* Bit twiddling constant for integral types. */ - public const int BYTES_PER_LONG = 8; - - /* JP2 Box structure analysis help */ - - [Serializable] - private class BoxType : System.Collections.Hashtable - { - - private static System.Collections.Hashtable map = System.Collections.Hashtable.Synchronized(new System.Collections.Hashtable()); - - public static void put(int type, System.String desc) - { - map[(System.Int32)type] = desc; - } - - public static System.String get_Renamed(int type) - { - return (System.String)map[(System.Int32)type]; - } - - public static System.String colorSpecMethod(int meth) - { - switch (meth) - { - - case 2: return "Restricted ICC Profile"; - - case 1: return "Enumerated Color Space"; - - default: return "Undefined Color Spec Method"; - - } - } - static BoxType() - { - { - put(CSJ2K.j2k.fileformat.FileFormatBoxes.BITS_PER_COMPONENT_BOX, "BITS_PER_COMPONENT_BOX"); - put(CSJ2K.j2k.fileformat.FileFormatBoxes.CAPTURE_RESOLUTION_BOX, "CAPTURE_RESOLUTION_BOX"); - put(CSJ2K.j2k.fileformat.FileFormatBoxes.CHANNEL_DEFINITION_BOX, "CHANNEL_DEFINITION_BOX"); - put(CSJ2K.j2k.fileformat.FileFormatBoxes.COLOUR_SPECIFICATION_BOX, "COLOUR_SPECIFICATION_BOX"); - put(CSJ2K.j2k.fileformat.FileFormatBoxes.COMPONENT_MAPPING_BOX, "COMPONENT_MAPPING_BOX"); - put(CSJ2K.j2k.fileformat.FileFormatBoxes.CONTIGUOUS_CODESTREAM_BOX, "CONTIGUOUS_CODESTREAM_BOX"); - put(CSJ2K.j2k.fileformat.FileFormatBoxes.DEFAULT_DISPLAY_RESOLUTION_BOX, "DEFAULT_DISPLAY_RESOLUTION_BOX"); - put(CSJ2K.j2k.fileformat.FileFormatBoxes.FILE_TYPE_BOX, "FILE_TYPE_BOX"); - put(CSJ2K.j2k.fileformat.FileFormatBoxes.IMAGE_HEADER_BOX, "IMAGE_HEADER_BOX"); - put(CSJ2K.j2k.fileformat.FileFormatBoxes.INTELLECTUAL_PROPERTY_BOX, "INTELLECTUAL_PROPERTY_BOX"); - put(CSJ2K.j2k.fileformat.FileFormatBoxes.JP2_HEADER_BOX, "JP2_HEADER_BOX"); - put(CSJ2K.j2k.fileformat.FileFormatBoxes.JP2_SIGNATURE_BOX, "JP2_SIGNATURE_BOX"); - put(CSJ2K.j2k.fileformat.FileFormatBoxes.PALETTE_BOX, "PALETTE_BOX"); - put(CSJ2K.j2k.fileformat.FileFormatBoxes.RESOLUTION_BOX, "RESOLUTION_BOX"); - put(CSJ2K.j2k.fileformat.FileFormatBoxes.URL_BOX, "URL_BOX"); - put(CSJ2K.j2k.fileformat.FileFormatBoxes.UUID_BOX, "UUID_BOX"); - put(CSJ2K.j2k.fileformat.FileFormatBoxes.UUID_INFO_BOX, "UUID_INFO_BOX"); - put(CSJ2K.j2k.fileformat.FileFormatBoxes.UUID_LIST_BOX, "UUID_LIST_BOX"); - put(CSJ2K.j2k.fileformat.FileFormatBoxes.XML_BOX, "XML_BOX"); - } - } - } - - - /// Creates an int from a 4 character String - /// string representation of an integer - /// - /// the integer which is denoted by the input String. - /// - public static int getIntFromString(System.String fourChar) - { - byte[] bytes = SupportClass.ToByteArray(fourChar); - return getInt(bytes, 0); - } - /// Create an XYZNumber from byte [] input - /// array containing the XYZNumber representation - /// - /// start of the rep in the array - /// - /// the created XYZNumber - /// - public static XYZNumber getXYZNumber(byte[] data, int offset) - { - int x, y, z; - x = ICCProfile.getInt(data, offset); - y = ICCProfile.getInt(data, offset + int_size); - z = ICCProfile.getInt(data, offset + 2 * int_size); - return new XYZNumber(x, y, z); - } - - /// Create an ICCProfileVersion from byte [] input - /// array containing the ICCProfileVersion representation - /// - /// start of the rep in the array - /// - /// the created ICCProfileVersion - /// - public static ICCProfileVersion getICCProfileVersion(byte[] data, int offset) - { - byte major = data[offset]; - byte minor = data[offset + byte_size]; - byte resv1 = data[offset + 2 * byte_size]; - byte resv2 = data[offset + 3 * byte_size]; - return new ICCProfileVersion(major, minor, resv1, resv2); - } - - /// Create an ICCDateTime from byte [] input - /// array containing the ICCProfileVersion representation - /// - /// start of the rep in the array - /// - /// the created ICCProfileVersion - /// - public static ICCDateTime getICCDateTime(byte[] data, int offset) - { - short wYear = ICCProfile.getShort(data, offset); // Number of the actual year (i.e. 1994) - short wMonth = ICCProfile.getShort(data, offset + ICCProfile.short_size); // Number of the month (1-12) - short wDay = ICCProfile.getShort(data, offset + 2 * ICCProfile.short_size); // Number of the day - short wHours = ICCProfile.getShort(data, offset + 3 * ICCProfile.short_size); // Number of hours (0-23) - short wMinutes = ICCProfile.getShort(data, offset + 4 * ICCProfile.short_size); // Number of minutes (0-59) - short wSeconds = ICCProfile.getShort(data, offset + 5 * ICCProfile.short_size); // Number of seconds (0-59) - return new ICCDateTime(wYear, wMonth, wDay, wHours, wMinutes, wSeconds); - } - - - /// Create a String from a byte []. Optionally swap adjacent byte - /// pairs. Intended to be used to create integer String representations - /// allowing for endian translations. - /// - /// data array - /// - /// start of data in array - /// - /// length of data in array - /// - /// swap adjacent bytes? - /// - /// String rep of data - /// - public static System.String getString(byte[] bfr, int offset, int length, bool swap) - { - - byte[] result = new byte[length]; - int incr = swap ? -1 : 1; - int start = swap ? offset + length - 1 : offset; - for (int i = 0, j = start; i < length; ++i) - { - result[i] = bfr[j]; - j += incr; - } - return new System.String(SupportClass.ToCharArray(result)); - } - - /// Create a short from a two byte [], with optional byte swapping. - /// data array - /// - /// start of data in array - /// - /// swap bytes? - /// - /// native type from representation. - /// - public static short getShort(byte[] bfr, int off, bool swap) - { - - int tmp0 = bfr[off] & 0xff; // Clear the sign extended bits in the int. - int tmp1 = bfr[off + 1] & 0xff; - - - return (short)(swap ? (tmp1 << BITS_PER_BYTE | tmp0) : (tmp0 << BITS_PER_BYTE | tmp1)); - } - - /// Create a short from a two byte []. - /// data array - /// - /// start of data in array - /// - /// native type from representation. - /// - public static short getShort(byte[] bfr, int off) - { - int tmp0 = bfr[off] & 0xff; // Clear the sign extended bits in the int. - int tmp1 = bfr[off + 1] & 0xff; - return (short)(tmp0 << BITS_PER_BYTE | tmp1); - } - - /// Separate bytes in an int into a byte array lsb to msb order. - /// integer to separate - /// - /// byte [] containing separated int. - /// - public static byte[] setInt(int d) - { - return setInt(d, new byte[BYTES_PER_INT]); - } - - /// Separate bytes in an int into a byte array lsb to msb order. - /// Return the result in the provided array - /// - /// integer to separate - /// - /// return output here. - /// - /// reference to output. - /// - public static byte[] setInt(int d, byte[] b) - { - if (b == null) - b = new byte[BYTES_PER_INT]; - for (int i = 0; i < BYTES_PER_INT; ++i) - { - b[i] = (byte)(d & 0x0ff); - d = d >> BITS_PER_BYTE; - } - return b; - } - - /// Separate bytes in a long into a byte array lsb to msb order. - /// long to separate - /// - /// byte [] containing separated int. - /// - public static byte[] setLong(long d) - { - return setLong(d, new byte[BYTES_PER_INT]); - } - - /// Separate bytes in a long into a byte array lsb to msb order. - /// Return the result in the provided array - /// - /// long to separate - /// - /// return output here. - /// - /// reference to output. - /// - public static byte[] setLong(long d, byte[] b) - { - if (b == null) - b = new byte[BYTES_PER_LONG]; - for (int i = 0; i < BYTES_PER_LONG; ++i) - { - b[i] = (byte)(d & 0x0ff); - d = d >> BITS_PER_BYTE; - } - return b; - } - - - /// Create an int from a byte [4], with optional byte swapping. - /// data array - /// - /// start of data in array - /// - /// swap bytes? - /// - /// native type from representation. - /// - public static int getInt(byte[] bfr, int off, bool swap) - { - - int tmp0 = getShort(bfr, off, swap) & 0xffff; // Clear the sign extended bits in the int. - int tmp1 = getShort(bfr, off + 2, swap) & 0xffff; - - return (int)(swap ? (tmp1 << BITS_PER_SHORT | tmp0) : (tmp0 << BITS_PER_SHORT | tmp1)); - } - - /// Create an int from a byte [4]. - /// data array - /// - /// start of data in array - /// - /// native type from representation. - /// - public static int getInt(byte[] bfr, int off) - { - - int tmp0 = getShort(bfr, off) & 0xffff; // Clear the sign extended bits in the int. - int tmp1 = getShort(bfr, off + 2) & 0xffff; - - return (int)(tmp0 << BITS_PER_SHORT | tmp1); - } - - /// Create an long from a byte [8]. - /// data array - /// - /// start of data in array - /// - /// native type from representation. - /// - public static long getLong(byte[] bfr, int off) - { - - long tmp0 = getInt(bfr, off) & unchecked((int)0xffffffff); // Clear the sign extended bits in the int. - long tmp1 = getInt(bfr, off + 4) & unchecked((int)0xffffffff); - - return (long)(tmp0 << BITS_PER_INT | tmp1); - } - - - /// signature - // Define the set of standard signature and type values - // Because of the endian issues and byte swapping, the profile codes must - // be stored in memory and be addressed by address. As such, only those - // codes required for Restricted ICC use are defined here - - //UPGRADE_NOTE: Final was removed from the declaration of 'kdwProfileSignature '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly int kdwProfileSignature; - /// signature - //UPGRADE_NOTE: Final was removed from the declaration of 'kdwProfileSigReverse '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly int kdwProfileSigReverse; - /// profile type - //UPGRADE_NOTE: Final was removed from the declaration of 'kdwInputProfile '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly int kdwInputProfile; - /// tag type - //UPGRADE_NOTE: Final was removed from the declaration of 'kdwDisplayProfile '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly int kdwDisplayProfile; - /// tag type - //UPGRADE_NOTE: Final was removed from the declaration of 'kdwRGBData '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly int kdwRGBData; - /// tag type - //UPGRADE_NOTE: Final was removed from the declaration of 'kdwGrayData '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly int kdwGrayData; - /// tag type - //UPGRADE_NOTE: Final was removed from the declaration of 'kdwXYZData '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly int kdwXYZData; - /// input type - public const int kMonochromeInput = 0; - /// input type - public const int kThreeCompInput = 1; - - /// tag signature - //UPGRADE_NOTE: Final was removed from the declaration of 'kdwGrayTRCTag '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly int kdwGrayTRCTag; - /// tag signature - //UPGRADE_NOTE: Final was removed from the declaration of 'kdwRedColorantTag '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly int kdwRedColorantTag; - /// tag signature - //UPGRADE_NOTE: Final was removed from the declaration of 'kdwGreenColorantTag '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly int kdwGreenColorantTag; - /// tag signature - //UPGRADE_NOTE: Final was removed from the declaration of 'kdwBlueColorantTag '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly int kdwBlueColorantTag; - /// tag signature - //UPGRADE_NOTE: Final was removed from the declaration of 'kdwRedTRCTag '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly int kdwRedTRCTag; - /// tag signature - //UPGRADE_NOTE: Final was removed from the declaration of 'kdwGreenTRCTag '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly int kdwGreenTRCTag; - /// tag signature - //UPGRADE_NOTE: Final was removed from the declaration of 'kdwBlueTRCTag '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly int kdwBlueTRCTag; - /// tag signature - //UPGRADE_NOTE: Final was removed from the declaration of 'kdwCopyrightTag '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly int kdwCopyrightTag; - /// tag signature - //UPGRADE_NOTE: Final was removed from the declaration of 'kdwMediaWhiteTag '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly int kdwMediaWhiteTag; - /// tag signature - //UPGRADE_NOTE: Final was removed from the declaration of 'kdwProfileDescTag '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly int kdwProfileDescTag; - - - private ICCProfileHeader header = null; - private ICCTagTable tags = null; - private byte[] profile = null; - - //private byte[] data = null; - private ParameterList pl = null; - - private ICCProfile() - { - throw new ICCProfileException("illegal to invoke empty constructor"); - } - - /// ParameterList constructor - /// provides colorspace information - /// - protected internal ICCProfile(ColorSpace csm) - { - this.pl = csm.pl; - profile = csm.ICCProfile; - initProfile(profile); - } - - /// Read the header and tags into memory and verify - /// that the correct type of profile is being used. for encoding. - /// - /// ICCProfile - /// - /// for bad signature and class and bad type - /// - private void initProfile(byte[] data) - { - header = new ICCProfileHeader(data); - tags = ICCTagTable.createInstance(data); - - - // Verify that the data pointed to by icc is indeed a valid profile - // and that it is possibly of one of the Restricted ICC types. The simplest way to check - // this is to verify that the profile signature is correct, that it is an input profile, - // and that the PCS used is XYX. - - // However, a common error in profiles will be to create Monitor profiles rather - // than input profiles. If this is the only error found, it's still useful to let this - // go through with an error written to stderr. - - if (ProfileClass == kdwDisplayProfile) - { - System.String message = "NOTE!! Technically, this profile is a Display profile, not an" + " Input Profile, and thus is not a valid Restricted ICC profile." + " However, it is quite possible that this profile is usable as" + " a Restricted ICC profile, so this code will ignore this state" + " and proceed with processing."; - - FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.WARNING, message); - } - - if ((ProfileSignature != kdwProfileSignature) || ((ProfileClass != kdwInputProfile) && (ProfileClass != kdwDisplayProfile)) || (PCSType != kdwXYZData)) - { - throw new ICCProfileInvalidException(); - } - } - - - /// Provide a suitable string representation for the class - public override System.String ToString() - { - System.Text.StringBuilder rep = new System.Text.StringBuilder("[ICCProfile:"); - System.Text.StringBuilder body = new System.Text.StringBuilder(); - body.Append(eol).Append(header); - body.Append(eol).Append(eol).Append(tags); - rep.Append(ColorSpace.indent(" ", body)); - return rep.Append("]").ToString(); - } - - - /// Create a two character hex representation of a byte - /// byte to represent - /// - /// representation - /// - public static System.String toHexString(byte i) - { - System.String rep = (i >= 0 && i < 16 ? "0" : "") + System.Convert.ToString((int)i, 16); - if (rep.Length > 2) - rep = rep.Substring(rep.Length - 2); - return rep; - } - - /// Create a 4 character hex representation of a short - /// short to represent - /// - /// representation - /// - public static System.String toHexString(short i) - { - System.String rep; - - if (i >= 0 && i < 0x10) - rep = "000" + System.Convert.ToString((int)i, 16); - else if (i >= 0 && i < 0x100) - rep = "00" + System.Convert.ToString((int)i, 16); - else if (i >= 0 && i < 0x1000) - rep = "0" + System.Convert.ToString((int)i, 16); - else - rep = "" + System.Convert.ToString((int)i, 16); - - if (rep.Length > 4) - rep = rep.Substring(rep.Length - 4); - return rep; - } - - - /// Create a 8 character hex representation of a int - /// int to represent - /// - /// representation - /// - public static System.String toHexString(int i) - { - System.String rep; - - if (i >= 0 && i < 0x10) - rep = "0000000" + System.Convert.ToString((int)i, 16); - else if (i >= 0 && i < 0x100) - rep = "000000" + System.Convert.ToString((int)i, 16); - else if (i >= 0 && i < 0x1000) - rep = "00000" + System.Convert.ToString((int)i, 16); - else if (i >= 0 && i < 0x10000) - rep = "0000" + System.Convert.ToString((int)i, 16); - else if (i >= 0 && i < 0x100000) - rep = "000" + System.Convert.ToString((int)i, 16); - else if (i >= 0 && i < 0x1000000) - rep = "00" + System.Convert.ToString((int)i, 16); - else if (i >= 0 && i < 0x10000000) - rep = "0" + System.Convert.ToString((int)i, 16); - else - rep = "" + System.Convert.ToString((int)i, 16); - - if (rep.Length > 8) - rep = rep.Substring(rep.Length - 8); - return rep; - } - - public static System.String ToString(byte[] data) - { - - int i, row, col, rem, rows, cols; - - System.Text.StringBuilder rep = new System.Text.StringBuilder(); - System.Text.StringBuilder rep0 = null; - System.Text.StringBuilder rep1 = null; - System.Text.StringBuilder rep2 = null; - - cols = 16; - rows = data.Length / cols; - rem = data.Length % cols; - - byte[] lbytes = new byte[8]; - for (row = 0, i = 0; row < rows; ++row) - { - rep1 = new System.Text.StringBuilder(); - rep2 = new System.Text.StringBuilder(); - - for (i = 0; i < 8; ++i) - lbytes[i] = 0; - byte[] tbytes = System.Text.ASCIIEncoding.ASCII.GetBytes(System.Convert.ToString(row * 16, 16)); - for (int t = 0, l = lbytes.Length - tbytes.Length; t < tbytes.Length; ++l, ++t) - lbytes[l] = tbytes[t]; - - rep0 = new System.Text.StringBuilder(new System.String(SupportClass.ToCharArray(lbytes))); - - for (col = 0; col < cols; ++col) - { - byte b = data[i++]; - rep1.Append(toHexString(b)).Append(i % 2 == 0 ? " " : ""); - if ((System.Char.IsLetter((char)b) || ((char)b).CompareTo('$') == 0 || ((char)b).CompareTo('_') == 0)) - rep2.Append((char)b); - else - rep2.Append("."); - } - rep.Append(rep0).Append(" : ").Append(rep1).Append(": ").Append(rep2).Append(eol); - } - - rep1 = new System.Text.StringBuilder(); - rep2 = new System.Text.StringBuilder(); - - for (i = 0; i < 8; ++i) - lbytes[i] = 0; - byte[] tbytes2 = System.Text.ASCIIEncoding.ASCII.GetBytes(System.Convert.ToString(row * 16, 16)); - for (int t = 0, l = lbytes.Length - tbytes2.Length; t < tbytes2.Length; ++l, ++t) - lbytes[l] = tbytes2[t]; - - rep0 = new System.Text.StringBuilder(System.Text.ASCIIEncoding.ASCII.GetString(lbytes)); - - for (col = 0; col < rem; ++col) - { - byte b = data[i++]; - rep1.Append(toHexString(b)).Append(i % 2 == 0 ? " " : ""); - if ((System.Char.IsLetter((char)b) || ((char)b).CompareTo('$') == 0 || ((char)b).CompareTo('_') == 0)) - rep2.Append((char)b); - else - rep2.Append("."); - } - for (col = rem; col < 16; ++col) - rep1.Append(" ").Append(col % 2 == 0 ? " " : ""); - - rep.Append(rep0).Append(" : ").Append(rep1).Append(": ").Append(rep2).Append(eol); - - return rep.ToString(); - } - - /// Parse this ICCProfile into a RestrictedICCProfile - /// which is appropriate to the data in this profile. - /// Either a MonochromeInputRestrictedProfile or - /// MatrixBasedRestrictedProfile is returned - /// - /// RestrictedICCProfile - /// - /// no curve data - /// - public virtual RestrictedICCProfile parse() - { - - // The next step is to determine which Restricted ICC type is used by this profile. - // Unfortunately, the only way to do this is to look through the tag table for - // the tags required by the two types. - - // First look for the gray TRC tag. If the profile is indeed an input profile, and this - // tag exists, then the profile is a Monochrome Input profile - - ICCCurveType grayTag = (ICCCurveType)tags[(System.Int32)kdwGrayTRCTag]; - if (grayTag != null) - { - return RestrictedICCProfile.createInstance(grayTag); - } - - // If it wasn't a Monochrome Input profile, look for the Red Colorant tag. If that - // tag is found and the profile is indeed an input profile, then this profile is - // a Three-Component Matrix-Based Input profile - - ICCCurveType rTRCTag = (ICCCurveType)tags[(System.Int32)kdwRedTRCTag]; - - - if (rTRCTag != null) - { - ICCCurveType gTRCTag = (ICCCurveType)tags[(System.Int32)kdwGreenTRCTag]; - ICCCurveType bTRCTag = (ICCCurveType)tags[(System.Int32)kdwBlueTRCTag]; - ICCXYZType rColorantTag = (ICCXYZType)tags[(System.Int32)kdwRedColorantTag]; - ICCXYZType gColorantTag = (ICCXYZType)tags[(System.Int32)kdwGreenColorantTag]; - ICCXYZType bColorantTag = (ICCXYZType)tags[(System.Int32)kdwBlueColorantTag]; - return RestrictedICCProfile.createInstance(rTRCTag, gTRCTag, bTRCTag, rColorantTag, gColorantTag, bColorantTag); - } - - throw new ICCProfileInvalidException("curve data not found in profile"); - } - - /// Output this ICCProfile to a RandomAccessFile - /// output file - /// - //UPGRADE_TODO: Class 'java.io.RandomAccessFile' was converted to 'System.IO.FileStream' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioRandomAccessFile'" - public virtual void write(System.IO.FileStream os) - { - Header.write(os); - TagTable.write(os); - } - - - /* end class ICCProfile */ - static ICCProfile() - { - kdwProfileSignature = GetTagInt("acsp"); - kdwProfileSigReverse = GetTagInt("psca"); - kdwInputProfile = GetTagInt("scnr"); - kdwDisplayProfile = GetTagInt("mntr"); - kdwRGBData = GetTagInt("RGB "); - kdwGrayData = GetTagInt("GRAY"); - kdwXYZData = GetTagInt("XYZ "); - - kdwGrayTRCTag = GetTagInt("kTRC"); - kdwRedColorantTag = GetTagInt("rXYZ"); - kdwGreenColorantTag = GetTagInt("gXYZ"); - kdwBlueColorantTag = GetTagInt("bXYZ"); - kdwRedTRCTag = GetTagInt("rTRC"); - kdwGreenTRCTag = GetTagInt("gTRC"); - kdwBlueTRCTag = GetTagInt("bTRC"); - kdwCopyrightTag = GetTagInt("cprt"); - kdwMediaWhiteTag = GetTagInt("wtpt"); - kdwProfileDescTag = GetTagInt("desc"); - } - static int GetTagInt(string tag) - { - byte[] tagBytes = ASCIIEncoding.ASCII.GetBytes(tag); - Array.Reverse(tagBytes); - return BitConverter.ToInt32(tagBytes, 0); - } - - } -} \ No newline at end of file diff --git a/CSJ2K/Icc/ICCProfileException.cs b/CSJ2K/Icc/ICCProfileException.cs deleted file mode 100644 index b02422fc..00000000 --- a/CSJ2K/Icc/ICCProfileException.cs +++ /dev/null @@ -1,40 +0,0 @@ -/// ************************************************************************** -/// -/// $Id: ICCProfileException.java,v 1.2 2002/08/08 14:08:13 grosbois Exp $ -/// -/// Copyright Eastman Kodak Company, 343 State Street, Rochester, NY 14650 -/// $Date $ -/// *************************************************************************** -/// -using System; -namespace CSJ2K.Icc -{ - - /// This exception is thrown when the content of a profile - /// is incorrect. - /// - /// - /// - /// - /// 1.0 - /// - /// Bruce A. Kern - /// - [Serializable] - public class ICCProfileException : System.Exception - { - - /// Contruct with message - /// returned by getMessage() - /// - public ICCProfileException(System.String msg) : base(msg) - { - } - - - /// Empty constructor - public ICCProfileException() - { - } - } -} \ No newline at end of file diff --git a/CSJ2K/Icc/ICCProfileInvalidException.cs b/CSJ2K/Icc/ICCProfileInvalidException.cs deleted file mode 100644 index 08fc0785..00000000 --- a/CSJ2K/Icc/ICCProfileInvalidException.cs +++ /dev/null @@ -1,43 +0,0 @@ -/// ************************************************************************** -/// -/// $Id: ICCProfileInvalidException.java,v 1.1 2002/07/25 14:56:55 grosbois Exp $ -/// -/// Copyright Eastman Kodak Company, 343 State Street, Rochester, NY 14650 -/// $Date $ -/// *************************************************************************** -/// -using System; -namespace CSJ2K.Icc -{ - - /// This exception is thrown when the content of an an icc profile - /// is in someway incorrect. - /// - /// - /// - /// - /// 1.0 - /// - /// Bruce A. Kern - /// - - [Serializable] - public class ICCProfileInvalidException : ICCProfileException - { - - /// Contruct with message - /// returned by getMessage() - /// - internal ICCProfileInvalidException(System.String msg) : base(msg) - { - } - - - /// Empty constructor - internal ICCProfileInvalidException() : base("icc profile is invalid") - { - } - - /* end class ICCProfileInvalidException */ - } -} \ No newline at end of file diff --git a/CSJ2K/Icc/ICCProfileNotFoundException.cs b/CSJ2K/Icc/ICCProfileNotFoundException.cs deleted file mode 100644 index 328ab26b..00000000 --- a/CSJ2K/Icc/ICCProfileNotFoundException.cs +++ /dev/null @@ -1,43 +0,0 @@ -/// ************************************************************************** -/// -/// $Id: ICCProfileNotFoundException.java,v 1.1 2002/07/25 14:56:55 grosbois Exp $ -/// -/// Copyright Eastman Kodak Company, 343 State Street, Rochester, NY 14650 -/// $Date $ -/// *************************************************************************** -/// -using System; -namespace CSJ2K.Icc -{ - - /// This exception is thrown when an image contains no icc profile. - /// is incorrect. - /// - /// - /// - /// - /// 1.0 - /// - /// Bruce A. Kern - /// - - [Serializable] - public class ICCProfileNotFoundException : ICCProfileException - { - - /// Contruct with message - /// returned by getMessage() - /// - internal ICCProfileNotFoundException(System.String msg) : base(msg) - { - } - - - /// Empty constructor - internal ICCProfileNotFoundException() : base("no icc profile in image") - { - } - - /* end class ICCProfileNotFoundException */ - } -} \ No newline at end of file diff --git a/CSJ2K/Icc/ICCProfiler.cs b/CSJ2K/Icc/ICCProfiler.cs deleted file mode 100644 index b095525a..00000000 --- a/CSJ2K/Icc/ICCProfiler.cs +++ /dev/null @@ -1,479 +0,0 @@ -using CSJ2K.Color; -using CSJ2K.Icc.Lut; -using CSJ2K.j2k.image; -using CSJ2K.j2k.util; -/// ************************************************************************** -/// -/// $Id: ICCProfiler.java,v 1.2 2002/08/08 14:08:27 grosbois Exp $ -/// -/// Copyright Eastman Kodak Company, 343 State Street, Rochester, NY 14650 -/// $Date $ -/// *************************************************************************** -/// -using System; -namespace CSJ2K.Icc -{ - - /// This class provides ICC Profiling API for the jj2000.j2k imaging chain - /// by implementing the BlkImgDataSrc interface, in particular the getCompData - /// and getInternCompData methods. - /// - /// - /// - /// - /// 1.0 - /// - /// Bruce A. Kern - /// - public class ICCProfiler : ColorSpaceMapper - { - - /// The prefix for ICC Profiler options - new public const char OPT_PREFIX = 'I'; - - /// Platform dependant end of line String. - //UPGRADE_NOTE: Final was removed from the declaration of 'eol '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - new protected internal static readonly System.String eol = System.Environment.NewLine; - - // Renamed for convenience: - //UPGRADE_NOTE: Final was removed from the declaration of 'GRAY '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - //UPGRADE_NOTE: The initialization of 'GRAY' was moved to static method 'icc.ICCProfiler'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1005'" - private static readonly int GRAY; - //UPGRADE_NOTE: Final was removed from the declaration of 'RED '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - //UPGRADE_NOTE: The initialization of 'RED' was moved to static method 'icc.ICCProfiler'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1005'" - private static readonly int RED; - //UPGRADE_NOTE: Final was removed from the declaration of 'GREEN '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - //UPGRADE_NOTE: The initialization of 'GREEN' was moved to static method 'icc.ICCProfiler'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1005'" - private static readonly int GREEN; - //UPGRADE_NOTE: Final was removed from the declaration of 'BLUE '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - //UPGRADE_NOTE: The initialization of 'BLUE' was moved to static method 'icc.ICCProfiler'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1005'" - private static readonly int BLUE; - - // ICCProfiles. - internal RestrictedICCProfile ricc = null; - internal ICCProfile icc = null; - - // Temporary variables needed during profiling. - private DataBlkInt[] tempInt; // Holds the results of the transform. - private DataBlkFloat[] tempFloat; // Holds the results of the transform. - - private System.Object xform = null; - - /// The image's ICC profile. - private RestrictedICCProfile iccp = null; - - /// Factory method for creating instances of this class. - /// -- source of image data - /// - /// -- provides colorspace info - /// - /// ICCProfiler instance - /// - /// profile access exception - /// - /// profile content exception - /// - public static new BlkImgDataSrc createInstance(BlkImgDataSrc src, CSJ2K.Color.ColorSpace csMap) - { - return new ICCProfiler(src, csMap); - } - - /// Ctor which creates an ICCProfile for the image and initializes - /// all data objects (input, working, output). - /// - /// - /// -- Source of image data - /// - /// -- provides colorspace info - /// - /// - /// - /// - /// - /// - /// - /// - protected internal ICCProfiler(BlkImgDataSrc src, CSJ2K.Color.ColorSpace csMap) : base(src, csMap) - { - initialize(); - - iccp = getICCProfile(csMap); - if (ncomps == 1) - { - xform = new MonochromeTransformTosRGB(iccp, maxValueArray[0], shiftValueArray[0]); - } - else - { - xform = new MatrixBasedTransformTosRGB(iccp, maxValueArray, shiftValueArray); - } - - /* end ICCProfiler ctor */ - } - - /// General utility used by ctors - private void initialize() - { - - tempInt = new DataBlkInt[ncomps]; - tempFloat = new DataBlkFloat[ncomps]; - - /* For each component, get the maximum data value, a reference - * to the pixel data and set up working and temporary DataBlks - * for both integer and float output. - */ - for (int i = 0; i < ncomps; ++i) - { - tempInt[i] = new DataBlkInt(); - tempFloat[i] = new DataBlkFloat(); - } - } - - /// Get the ICCProfile information JP2 ColorSpace - /// provides all necessary info about the colorspace - /// - /// ICCMatrixBasedInputProfile for 3 component input and - /// ICCMonochromeInputProfile for a 1 component source. Returns - /// null if exceptions were encountered. - /// - /// - /// - /// - /// - /// - /// - private RestrictedICCProfile getICCProfile(CSJ2K.Color.ColorSpace csm) - { - - switch (ncomps) - { - - case 1: - icc = ICCMonochromeInputProfile.createInstance(csm); - ricc = icc.parse(); - if (ricc.Type != RestrictedICCProfile.kMonochromeInput) - throw new System.ArgumentException("wrong ICCProfile type" + " for image"); - break; - - case 3: - icc = ICCMatrixBasedInputProfile.createInstance(csm); - ricc = icc.parse(); - if (ricc.Type != RestrictedICCProfile.kThreeCompInput) - throw new System.ArgumentException("wrong ICCProfile type" + " for image"); - break; - - default: - throw new System.ArgumentException("illegal number of " + "components (" + ncomps + ") in image"); - - } - return ricc; - } - - /// Returns, in the blk argument, a block of image data containing the - /// specifed rectangular area, in the specified component. The data is - /// returned, as a copy of the internal data, therefore the returned data - /// can be modified "in place". - /// - ///

The rectangular area to return is specified by the 'ulx', 'uly', 'w' - /// and 'h' members of the 'blk' argument, relative to the current - /// tile. These members are not modified by this method. The 'offset' of - /// the returned data is 0, and the 'scanw' is the same as the block's - /// width. See the 'DataBlk' class. - /// - ///

If the data array in 'blk' is 'null', then a new one is created. If - /// the data array is not 'null' then it is reused, and it must be large - /// enough to contain the block's data. Otherwise an 'ArrayStoreException' - /// or an 'IndexOutOfBoundsException' is thrown by the Java system. - /// - ///

The returned data has its 'progressive' attribute set to that of the - /// input data. - /// - ///

- /// Its coordinates and dimensions specify the area to - /// return. If it contains a non-null data array, then it must have the - /// correct dimensions. If it contains a null data array a new one is - /// created. The fields in this object are modified to return the data. - /// - /// - /// The index of the component from which to get the data. Only 0 - /// and 3 are valid. - /// - /// - /// The requested DataBlk - /// - /// - /// - /// - /// - public override DataBlk getCompData(DataBlk outblk, int c) - { - - try - { - if (ncomps != 1 && ncomps != 3) - { - System.String msg = "ICCProfiler: icc profile _not_ applied to " + ncomps + " component image"; - FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.WARNING, msg); - return src.getCompData(outblk, c); - } - - int type = outblk.DataType; - - int leftedgeOut = -1; // offset to the start of the output scanline - int rightedgeOut = -1; // offset to the end of the output - // scanline + 1 - int leftedgeIn = -1; // offset to the start of the input scanline - int rightedgeIn = -1; // offset to the end of the input - // scanline + 1 - - // Calculate all components: - for (int i = 0; i < ncomps; ++i) - { - - int fixedPtBits = src.getFixedPoint(i); - int shiftVal = shiftValueArray[i]; - int maxVal = maxValueArray[i]; - - // Initialize general input and output indexes - int kOut = -1; - int kIn = -1; - - switch (type) - { - - // Int and Float data only - case DataBlk.TYPE_INT: - - // Set up the DataBlk geometry - copyGeometry(workInt[i], outblk); - copyGeometry(tempInt[i], outblk); - copyGeometry(inInt[i], outblk); - InternalBuffer = outblk; - - // Reference the output array - workDataInt[i] = (int[])workInt[i].Data; - - // Request data from the source. - inInt[i] = (DataBlkInt)src.getInternCompData(inInt[i], i); - dataInt[i] = inInt[i].DataInt; - - // The nitty-gritty. - - for (int row = 0; row < outblk.h; ++row) - { - leftedgeIn = inInt[i].offset + row * inInt[i].scanw; - rightedgeIn = leftedgeIn + inInt[i].w; - leftedgeOut = outblk.offset + row * outblk.scanw; - rightedgeOut = leftedgeOut + outblk.w; - - for (kOut = leftedgeOut, kIn = leftedgeIn; kIn < rightedgeIn; ++kIn, ++kOut) - { - int tmpInt = (dataInt[i][kIn] >> fixedPtBits) + shiftVal; - workDataInt[i][kOut] = ((tmpInt < 0) ? 0 : ((tmpInt > maxVal) ? maxVal : tmpInt)); - } - } - break; - - - case DataBlk.TYPE_FLOAT: - - // Set up the DataBlk geometry - copyGeometry(workFloat[i], outblk); - copyGeometry(tempFloat[i], outblk); - copyGeometry(inFloat[i], outblk); - InternalBuffer = outblk; - - // Reference the output array - workDataFloat[i] = (float[])workFloat[i].Data; - - // Request data from the source. - inFloat[i] = (DataBlkFloat)src.getInternCompData(inFloat[i], i); - dataFloat[i] = inFloat[i].DataFloat; - - // The nitty-gritty. - - for (int row = 0; row < outblk.h; ++row) - { - leftedgeIn = inFloat[i].offset + row * inFloat[i].scanw; - rightedgeIn = leftedgeIn + inFloat[i].w; - leftedgeOut = outblk.offset + row * outblk.scanw; - rightedgeOut = leftedgeOut + outblk.w; - - for (kOut = leftedgeOut, kIn = leftedgeIn; kIn < rightedgeIn; ++kIn, ++kOut) - { - float tmpFloat = dataFloat[i][kIn] / (1 << fixedPtBits) + shiftVal; - workDataFloat[i][kOut] = ((tmpFloat < 0) ? 0 : ((tmpFloat > maxVal) ? maxVal : tmpFloat)); - } - } - break; - - - case DataBlk.TYPE_SHORT: - case DataBlk.TYPE_BYTE: - default: - // Unsupported output type. - throw new System.ArgumentException("Invalid source " + "datablock type"); - } - } - - switch (type) - { - - // Int and Float data only - case DataBlk.TYPE_INT: - - if (ncomps == 1) - { - ((MonochromeTransformTosRGB)xform).apply(workInt[c], tempInt[c]); - } - else - { - // ncomps == 3 - ((MatrixBasedTransformTosRGB)xform).apply(workInt, tempInt); - } - - outblk.progressive = inInt[c].progressive; - outblk.Data = tempInt[c].Data; - break; - - - case DataBlk.TYPE_FLOAT: - - if (ncomps == 1) - { - ((MonochromeTransformTosRGB)xform).apply(workFloat[c], tempFloat[c]); - } - else - { - // ncomps == 3 - ((MatrixBasedTransformTosRGB)xform).apply(workFloat, tempFloat); - } - - outblk.progressive = inFloat[c].progressive; - outblk.Data = tempFloat[c].Data; - break; - - - case DataBlk.TYPE_SHORT: - case DataBlk.TYPE_BYTE: - default: - // Unsupported output type. - throw new System.ArgumentException("invalid source datablock" + " type"); - } - - // Initialize the output block geometry and set the profiled - // data into the output block. - outblk.offset = 0; - outblk.scanw = outblk.w; - } - catch (MatrixBasedTransformException e) - { - //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Throwable.getMessage' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" - FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.ERROR, "matrix transform problem:\n" + e.Message); - if (pl.getParameter("debug").Equals("on")) - { - SupportClass.WriteStackTrace(e, Console.Error); - } - else - { - FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.ERROR, "Use '-debug' option for more details"); - } - return null; - } - catch (MonochromeTransformException e) - { - //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Throwable.getMessage' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" - FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.ERROR, "monochrome transform problem:\n" + e.Message); - if (pl.getParameter("debug").Equals("on")) - { - SupportClass.WriteStackTrace(e, Console.Error); - } - else - { - FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.ERROR, "Use '-debug' option for more details"); - } - return null; - } - - return outblk; - } - - /// Returns, in the blk argument, a block of image data containing the - /// specifed rectangular area, in the specified component. The data is - /// returned, as a reference to the internal data, if any, instead of as a - /// copy, therefore the returned data should not be modified. - /// - ///

The rectangular area to return is specified by the 'ulx', 'uly', 'w' - /// and 'h' members of the 'blk' argument, relative to the current - /// tile. These members are not modified by this method. The 'offset' and - /// 'scanw' of the returned data can be arbitrary. See the 'DataBlk' class. - /// - ///

This method, in general, is more efficient than the 'getCompData()' - /// method since it may not copy the data. However if the array of returned - /// data is to be modified by the caller then the other method is probably - /// preferable. - /// - ///

If possible, the data in the returned 'DataBlk' should be the - /// internal data itself, instead of a copy, in order to increase the data - /// transfer efficiency. However, this depends on the particular - /// implementation (it may be more convenient to just return a copy of the - /// data). This is the reason why the returned data should not be modified. - /// - ///

If the data array in blk is null, then a new one - /// is created if necessary. The implementation of this interface may - /// choose to return the same array or a new one, depending on what is more - /// efficient. Therefore, the data array in blk prior to the - /// method call should not be considered to contain the returned data, a - /// new array may have been created. Instead, get the array from - /// blk after the method has returned. - /// - ///

The returned data may have its 'progressive' attribute set. In this - /// case the returned data is only an approximation of the "final" data. - /// - ///

- /// Its coordinates and dimensions specify the area to return, - /// relative to the current tile. Some fields in this object are modified - /// to return the data. - /// - /// - /// The index of the component from which to get the data. - /// - /// - /// The requested DataBlk - /// - /// - /// - /// - /// - public override DataBlk getInternCompData(DataBlk out_Renamed, int c) - { - return getCompData(out_Renamed, c); - } - - /// Return a suitable String representation of the class instance. - public override System.String ToString() - { - System.Text.StringBuilder rep = new System.Text.StringBuilder("[ICCProfiler:"); - System.Text.StringBuilder body = new System.Text.StringBuilder(); - if (icc != null) - { - body.Append(eol).Append(CSJ2K.Color.ColorSpace.indent(" ", icc.ToString())); - } - if (xform != null) - { - //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Object.toString' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" - body.Append(eol).Append(CSJ2K.Color.ColorSpace.indent(" ", xform.ToString())); - } - rep.Append(CSJ2K.Color.ColorSpace.indent(" ", body)); - return rep.Append("]").ToString(); - } - - /* end class ICCProfiler */ - static ICCProfiler() - { - GRAY = RestrictedICCProfile.GRAY; - RED = RestrictedICCProfile.RED; - GREEN = RestrictedICCProfile.GREEN; - BLUE = RestrictedICCProfile.BLUE; - } - } -} \ No newline at end of file diff --git a/CSJ2K/Icc/Lut/LookUpTable.cs b/CSJ2K/Icc/Lut/LookUpTable.cs deleted file mode 100644 index 018990b0..00000000 --- a/CSJ2K/Icc/Lut/LookUpTable.cs +++ /dev/null @@ -1,47 +0,0 @@ -/// ************************************************************************** -/// -/// $Id: LookUpTable.java,v 1.1 2002/07/25 14:56:49 grosbois Exp $ -/// -/// Copyright Eastman Kodak Company, 343 State Street, Rochester, NY 14650 -/// $Date $ -/// *************************************************************************** -/// -using ICCCurveType = CSJ2K.Icc.Tags.ICCCurveType; -namespace CSJ2K.Icc.Lut -{ - - - /// Toplevel class for a lut. All lookup tables must - /// extend this class. - /// - /// - /// 1.0 - /// - /// Bruce A. Kern - /// - public abstract class LookUpTable - { - - /// End of line string. - //UPGRADE_NOTE: Final was removed from the declaration of 'eol '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - protected internal static readonly System.String eol = System.Environment.NewLine; - /// The curve data - protected internal ICCCurveType curve = null; - /// Number of values in created lut - protected internal int dwNumInput = 0; - - - /// For subclass usage. - /// The curve data - /// - /// Number of values in created lut - /// - protected internal LookUpTable(ICCCurveType curve, int dwNumInput) - { - this.curve = curve; - this.dwNumInput = dwNumInput; - } - - /* end class LookUpTable */ - } -} \ No newline at end of file diff --git a/CSJ2K/Icc/Lut/LookUpTable16.cs b/CSJ2K/Icc/Lut/LookUpTable16.cs deleted file mode 100644 index b893fd3f..00000000 --- a/CSJ2K/Icc/Lut/LookUpTable16.cs +++ /dev/null @@ -1,122 +0,0 @@ -/// ************************************************************************** -/// -/// $Id: LookUpTable16.java,v 1.1 2002/07/25 14:56:47 grosbois Exp $ -/// -/// Copyright Eastman Kodak Company, 343 State Street, Rochester, NY 14650 -/// $Date $ -/// *************************************************************************** -/// -using ICCCurveType = CSJ2K.Icc.Tags.ICCCurveType; -namespace CSJ2K.Icc.Lut -{ - - /// Toplevel class for a short [] lut. - /// - /// - /// 1.0 - /// - /// Bruce A. Kern - /// - public abstract class LookUpTable16 : LookUpTable - { - - /// Maximum output value of the LUT - //UPGRADE_NOTE: Final was removed from the declaration of 'dwMaxOutput '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - protected internal int dwMaxOutput; - /// The lut values. - //UPGRADE_NOTE: Final was removed from the declaration of 'lut '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - protected internal short[] lut; - - /// Create an abbreviated string representation of a 16 bit lut. - /// the lut as a String - /// - public override System.String ToString() - { - System.Text.StringBuilder rep = new System.Text.StringBuilder("[LookUpTable16 "); - //int row, col; - rep.Append("max= " + dwMaxOutput); - rep.Append(", nentries= " + dwMaxOutput); - return rep.Append("]").ToString(); - } - - /// Create a full string representation of a 16 bit lut. - /// the lut as a String - /// - public virtual System.String toStringWholeLut() - { - System.Text.StringBuilder rep = new System.Text.StringBuilder("[LookUpTable16" + eol); - int row, col; - - rep.Append("max output = " + dwMaxOutput + eol); - for (row = 0; row < dwNumInput / 10; ++row) - { - rep.Append("lut[" + 10 * row + "] : "); - for (col = 0; col < 10; ++col) - { - rep.Append(lut[10 * row + col]).Append(" "); - } - rep.Append(eol); - } - // Partial row. - rep.Append("lut[" + 10 * row + "] : "); - for (col = 0; col < dwNumInput % 10; ++col) - rep.Append(lut[10 * row + col] + " "); - rep.Append(eol + eol); - return rep.ToString(); - } - - /// Factory method for getting a 16 bit lut from a given curve. - /// the data - /// - /// the size of the lut - /// - /// max output value of the lut - /// - /// the lookup table - /// - public static LookUpTable16 createInstance(ICCCurveType curve, int dwNumInput, int dwMaxOutput) - { - - if (curve.count == 1) - return new LookUpTable16Gamma(curve, dwNumInput, dwMaxOutput); - else - return new LookUpTable16Interp(curve, dwNumInput, dwMaxOutput); - } - - /// Construct an empty 16 bit lut - /// the size of the lut t lut. - /// - /// max output value of the lut - /// - protected internal LookUpTable16(int dwNumInput, int dwMaxOutput) : base(null, dwNumInput) - { - lut = new short[dwNumInput]; - this.dwMaxOutput = dwMaxOutput; - } - - /// Construct a 16 bit lut from a given curve. - /// the data - /// - /// the size of the lut t lut. - /// - /// max output value of the lut - /// - protected internal LookUpTable16(ICCCurveType curve, int dwNumInput, int dwMaxOutput) : base(curve, dwNumInput) - { - this.dwMaxOutput = dwMaxOutput; - lut = new short[dwNumInput]; - } - - /// lut accessor - /// of the element - /// - /// the lut [index] - /// - public short elementAt(int index) - { - return lut[index]; - } - - /* end class LookUpTable16 */ - } -} \ No newline at end of file diff --git a/CSJ2K/Icc/Lut/LookUpTable16Gamma.cs b/CSJ2K/Icc/Lut/LookUpTable16Gamma.cs deleted file mode 100644 index 91ed72c4..00000000 --- a/CSJ2K/Icc/Lut/LookUpTable16Gamma.cs +++ /dev/null @@ -1,42 +0,0 @@ -/// ************************************************************************** -/// -/// $Id: LookUpTable16Gamma.java,v 1.1 2002/07/25 14:56:46 grosbois Exp $ -/// -/// Copyright Eastman Kodak Company, 343 State Street, Rochester, NY 14650 -/// $Date $ -/// *************************************************************************** -/// -using ICCCurveType = CSJ2K.Icc.Tags.ICCCurveType; -namespace CSJ2K.Icc.Lut -{ - - /// A Gamma based 16 bit lut. - /// - /// - /// - /// - /// 1.0 - /// - /// Bruce A. Kern - /// - public class LookUpTable16Gamma : LookUpTable16 - { - - /* Construct the lut - * @param curve data - * @param dwNumInput size of lut - * @param dwMaxOutput max value of lut - */ - public LookUpTable16Gamma(ICCCurveType curve, int dwNumInput, int dwMaxOutput) : base(curve, dwNumInput, dwMaxOutput) - { - double dfE = ICCCurveType.CurveGammaToDouble(curve.entry(0)); // Gamma exponent for inverse transformation - for (int i = 0; i < dwNumInput; i++) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - lut[i] = (short)System.Math.Floor(System.Math.Pow((double)i / (dwNumInput - 1), dfE) * dwMaxOutput + 0.5); - } - } - - /* end class LookUpTable16Gamma */ - } -} \ No newline at end of file diff --git a/CSJ2K/Icc/Lut/LookUpTable16Interp.cs b/CSJ2K/Icc/Lut/LookUpTable16Interp.cs deleted file mode 100644 index 8dfb7d25..00000000 --- a/CSJ2K/Icc/Lut/LookUpTable16Interp.cs +++ /dev/null @@ -1,65 +0,0 @@ -/// ************************************************************************** -/// -/// $Id: LookUpTable16Interp.java,v 1.1 2002/07/25 14:56:46 grosbois Exp $ -/// -/// Copyright Eastman Kodak Company, 343 State Street, Rochester, NY 14650 -/// $Date $ -/// *************************************************************************** -/// -using ICCCurveType = CSJ2K.Icc.Tags.ICCCurveType; -namespace CSJ2K.Icc.Lut -{ - - /// An interpolated 16 bit lut - /// - /// - /// 1.0 - /// - /// Bruce A.Kern - /// - public class LookUpTable16Interp : LookUpTable16 - { - - /// Construct the lut from the curve data - /// curve the data - /// dwNumInput the lut size - /// dwMaxOutput the lut max value - public LookUpTable16Interp(ICCCurveType curve, int dwNumInput, int dwMaxOutput) : base(curve, dwNumInput, dwMaxOutput) - { - - int dwLowIndex, dwHighIndex; // Indices of interpolation points - double dfLowIndex, dfHighIndex; // FP indices of interpolation points - double dfTargetIndex; // Target index into interpolation table - double dfRatio; // Ratio of LUT input points to curve values - double dfLow, dfHigh; // Interpolation values - double dfOut; // Output LUT value - - dfRatio = (double)(curve.count - 1) / (double)(dwNumInput - 1); - - for (int i = 0; i < dwNumInput; i++) - { - dfTargetIndex = (double)i * dfRatio; - dfLowIndex = System.Math.Floor(dfTargetIndex); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - dwLowIndex = (int)dfLowIndex; - dfHighIndex = System.Math.Ceiling(dfTargetIndex); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - dwHighIndex = (int)dfHighIndex; - - if (dwLowIndex == dwHighIndex) - dfOut = ICCCurveType.CurveToDouble(curve.entry(dwLowIndex)); - else - { - dfLow = ICCCurveType.CurveToDouble(curve.entry(dwLowIndex)); - dfHigh = ICCCurveType.CurveToDouble(curve.entry(dwHighIndex)); - dfOut = dfLow + (dfHigh - dfLow) * (dfTargetIndex - dfLowIndex); - } - - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - lut[i] = (short)System.Math.Floor(dfOut * dwMaxOutput + 0.5); - } - } - - /* end class LookUpTable16Interp */ - } -} \ No newline at end of file diff --git a/CSJ2K/Icc/Lut/LookUpTable16LinearSRGBtoSRGB.cs b/CSJ2K/Icc/Lut/LookUpTable16LinearSRGBtoSRGB.cs deleted file mode 100644 index e4b67d10..00000000 --- a/CSJ2K/Icc/Lut/LookUpTable16LinearSRGBtoSRGB.cs +++ /dev/null @@ -1,79 +0,0 @@ -/// ************************************************************************** -/// -/// $Id: LookUpTable16LinearSRGBtoSRGB.java,v 1.1 2002/07/25 14:56:47 grosbois Exp $ -/// -/// Copyright Eastman Kodak Company, 343 State Street, Rochester, NY 14650 -/// $Date $ -/// *************************************************************************** -/// -namespace CSJ2K.Icc.Lut -{ - - /// A Linear 16 bit SRGB to SRGB lut - /// - /// - /// 1.0 - /// - /// Bruce A. Kern - /// - public class LookUpTable16LinearSRGBtoSRGB : LookUpTable16 - { - - /// Factory method for creating the lut. - /// size of shadow region - /// - /// shadow region parameter - /// - /// size of lut - /// - /// post shadow region parameter - /// - /// post shadow region parameter - /// - /// post shadow region parameter - /// - /// the lut - /// - public static LookUpTable16LinearSRGBtoSRGB createInstance(int wShadowCutoff, double dfShadowSlope, int ksRGBLinearMaxValue, double ksRGB8ScaleAfterExp, double ksRGBExponent, double ksRGB8ReduceAfterEx) - { - return new LookUpTable16LinearSRGBtoSRGB(wShadowCutoff, dfShadowSlope, ksRGBLinearMaxValue, ksRGB8ScaleAfterExp, ksRGBExponent, ksRGB8ReduceAfterEx); - } - - /// Construct the lut - /// size of shadow region - /// - /// shadow region parameter - /// - /// size of lut - /// - /// post shadow region parameter - /// - /// post shadow region parameter - /// - /// post shadow region parameter - /// - protected internal LookUpTable16LinearSRGBtoSRGB(int wShadowCutoff, double dfShadowSlope, int ksRGBLinearMaxValue, double ksRGB8ScaleAfterExp, double ksRGBExponent, double ksRGB8ReduceAfterExp) : base(ksRGBLinearMaxValue + 1, (short)0) - { - - int i = -1; - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - double dfNormalize = 1.0 / (float)ksRGBLinearMaxValue; - - // Generate the final linear-sRGB to non-linear sRGB LUT - for (i = 0; i <= wShadowCutoff; i++) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - lut[i] = (byte)System.Math.Floor(dfShadowSlope * (double)i + 0.5); - } - - // Now calculate the rest - for (; i <= ksRGBLinearMaxValue; i++) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - lut[i] = (byte)System.Math.Floor(ksRGB8ScaleAfterExp * System.Math.Pow((double)i * dfNormalize, ksRGBExponent) - ksRGB8ReduceAfterExp + 0.5); - } - } - - /* end class LookUpTable16LinearSRGBtoSRGB */ - } -} \ No newline at end of file diff --git a/CSJ2K/Icc/Lut/LookUpTable32.cs b/CSJ2K/Icc/Lut/LookUpTable32.cs deleted file mode 100644 index c139871c..00000000 --- a/CSJ2K/Icc/Lut/LookUpTable32.cs +++ /dev/null @@ -1,121 +0,0 @@ -/// ************************************************************************** -/// -/// $Id: LookUpTable32.java,v 1.1 2002/07/25 14:56:47 grosbois Exp $ -/// -/// Copyright Eastman Kodak Company, 343 State Street, Rochester, NY 14650 -/// $Date $ -/// *************************************************************************** -/// -using ICCCurveType = CSJ2K.Icc.Tags.ICCCurveType; -namespace CSJ2K.Icc.Lut -{ - - /// Toplevel class for a int [] lut. - /// - /// - /// 1.0 - /// - /// Bruce A. Kern - /// - //UPGRADE_NOTE: The access modifier for this class or class field has been changed in order to prevent compilation errors due to the visibility level. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1296'" - abstract public class LookUpTable32 : LookUpTable - { - - /// Maximum output value of the LUT - //UPGRADE_NOTE: Final was removed from the declaration of 'dwMaxOutput '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - protected internal int dwMaxOutput; - /// the lut values. - //UPGRADE_NOTE: Final was removed from the declaration of 'lut '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public int[] lut; - - /// Create an abbreviated string representation of a 16 bit lut. - /// the lut as a String - /// - public override System.String ToString() - { - System.Text.StringBuilder rep = new System.Text.StringBuilder("[LookUpTable32 "); - //int row, col; - rep.Append("max= " + dwMaxOutput); - rep.Append(", nentries= " + dwNumInput); - return rep.Append("]").ToString(); - } - - /// Create the string representation of a 32 bit lut. - /// the lut as a String - /// - public virtual System.String toStringWholeLut() - { - System.Text.StringBuilder rep = new System.Text.StringBuilder("[LookUpTable32" + eol); - int row, col; - rep.Append("max output = " + dwMaxOutput + eol); - for (row = 0; row < dwNumInput / 10; ++row) - { - rep.Append("lut[" + 10 * row + "] : "); - for (col = 0; col < 10; ++col) - { - rep.Append(lut[10 * row + col] + " "); - } - rep.Append(eol); - } - // Partial row. - rep.Append("lut[" + 10 * row + "] : "); - for (col = 0; col < dwNumInput % 10; ++col) - rep.Append(lut[10 * row + col] + " "); - rep.Append(eol + eol); - return rep.ToString(); - } - - /// Factory method for getting a 32 bit lut from a given curve. - /// the data - /// - /// the size of the lut - /// - /// max output value of the lut - /// - /// the lookup table - /// - public static LookUpTable32 createInstance(ICCCurveType curve, int dwNumInput, int dwMaxOutput) - { - if (curve.count == 1) - return new LookUpTable32Gamma(curve, dwNumInput, dwMaxOutput); - else - return new LookUpTable32Interp(curve, dwNumInput, dwMaxOutput); - } - - /// Construct an empty 32 bit - /// the size of the lut t lut. - /// - /// max output value of the lut - /// - protected internal LookUpTable32(int dwNumInput, int dwMaxOutput) : base(null, dwNumInput) - { - lut = new int[dwNumInput]; - this.dwMaxOutput = dwMaxOutput; - } - - /// Construct a 16 bit lut from a given curve. - /// the data - /// - /// the size of the lut t lut. - /// - /// max output value of the lut - /// - protected internal LookUpTable32(ICCCurveType curve, int dwNumInput, int dwMaxOutput) : base(curve, dwNumInput) - { - this.dwMaxOutput = dwMaxOutput; - lut = new int[dwNumInput]; - } - - /// lut accessor - /// of the element - /// - /// the lut [index] - /// - public int elementAt(int index) - { - return lut[index]; - } - - /* end class LookUpTable32 */ - } -} \ No newline at end of file diff --git a/CSJ2K/Icc/Lut/LookUpTable32Gamma.cs b/CSJ2K/Icc/Lut/LookUpTable32Gamma.cs deleted file mode 100644 index 8ec3a6f3..00000000 --- a/CSJ2K/Icc/Lut/LookUpTable32Gamma.cs +++ /dev/null @@ -1,44 +0,0 @@ -/// ************************************************************************** -/// -/// $Id: LookUpTable32Gamma.java,v 1.1 2002/07/25 14:56:47 grosbois Exp $ -/// -/// Copyright Eastman Kodak Company, 343 State Street, Rochester, NY 14650 -/// $Date $ -/// *************************************************************************** -/// -using ICCCurveType = CSJ2K.Icc.Tags.ICCCurveType; -namespace CSJ2K.Icc.Lut -{ - - /// A Gamma based 32 bit lut. - /// - /// - /// - /// - /// 1.0 - /// - /// Bruce A. Kern - /// - - public class LookUpTable32Gamma : LookUpTable32 - { - - - /* Construct the lut - * @param curve data - * @param dwNumInput size of lut - * @param dwMaxOutput max value of lut - */ - public LookUpTable32Gamma(ICCCurveType curve, int dwNumInput, int dwMaxOutput) : base(curve, dwNumInput, dwMaxOutput) - { - double dfE = ICCCurveType.CurveGammaToDouble(curve.entry(0)); // Gamma exponent for inverse transformation - for (int i = 0; i < dwNumInput; i++) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - lut[i] = (int)System.Math.Floor(System.Math.Pow((double)i / (dwNumInput - 1), dfE) * dwMaxOutput + 0.5); - } - } - - /* end class LookUpTable32Gamma */ - } -} \ No newline at end of file diff --git a/CSJ2K/Icc/Lut/LookUpTable32Interp.cs b/CSJ2K/Icc/Lut/LookUpTable32Interp.cs deleted file mode 100644 index 5626e145..00000000 --- a/CSJ2K/Icc/Lut/LookUpTable32Interp.cs +++ /dev/null @@ -1,66 +0,0 @@ -/// ************************************************************************** -/// -/// $Id: LookUpTable32Interp.java,v 1.1 2002/07/25 14:56:47 grosbois Exp $ -/// -/// Copyright Eastman Kodak Company, 343 State Street, Rochester, NY 14650 -/// $Date $ -/// *************************************************************************** -/// -using ICCCurveType = CSJ2K.Icc.Tags.ICCCurveType; -namespace CSJ2K.Icc.Lut -{ - - /// An interpolated 32 bit lut - /// - /// - /// 1.0 - /// - /// Bruce A.Kern - /// - - public class LookUpTable32Interp : LookUpTable32 - { - - /// Construct the lut from the curve data - /// curve the data - /// dwNumInput the lut size - /// dwMaxOutput the lut max value - public LookUpTable32Interp(ICCCurveType curve, int dwNumInput, int dwMaxOutput) : base(curve, dwNumInput, dwMaxOutput) - { - - int dwLowIndex, dwHighIndex; // Indices of interpolation points - double dfLowIndex, dfHighIndex; // FP indices of interpolation points - double dfTargetIndex; // Target index into interpolation table - double dfRatio; // Ratio of LUT input points to curve values - double dfLow, dfHigh; // Interpolation values - double dfOut; // Output LUT value - - dfRatio = (double)(curve.count - 1) / (double)(dwNumInput - 1); - - for (int i = 0; i < dwNumInput; i++) - { - dfTargetIndex = (double)i * dfRatio; - dfLowIndex = System.Math.Floor(dfTargetIndex); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - dwLowIndex = (int)dfLowIndex; - dfHighIndex = System.Math.Ceiling(dfTargetIndex); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - dwHighIndex = (int)dfHighIndex; - - if (dwLowIndex == dwHighIndex) - dfOut = ICCCurveType.CurveToDouble(curve.entry(dwLowIndex)); - else - { - dfLow = ICCCurveType.CurveToDouble(curve.entry(dwLowIndex)); - dfHigh = ICCCurveType.CurveToDouble(curve.entry(dwHighIndex)); - dfOut = dfLow + (dfHigh - dfLow) * (dfTargetIndex - dfLowIndex); - } - - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - lut[i] = (int)System.Math.Floor(dfOut * dwMaxOutput + 0.5); - } - } - - /* end class LookUpTable32Interp */ - } -} \ No newline at end of file diff --git a/CSJ2K/Icc/Lut/LookUpTable32LinearSRGBtoSRGB.cs b/CSJ2K/Icc/Lut/LookUpTable32LinearSRGBtoSRGB.cs deleted file mode 100644 index 09b1df6d..00000000 --- a/CSJ2K/Icc/Lut/LookUpTable32LinearSRGBtoSRGB.cs +++ /dev/null @@ -1,100 +0,0 @@ -/// ************************************************************************** -/// -/// $Id: LookUpTable32LinearSRGBtoSRGB.java,v 1.1 2002/07/25 14:56:47 grosbois Exp $ -/// -/// Copyright Eastman Kodak Company, 343 State Street, Rochester, NY 14650 -/// $Date $ -/// *************************************************************************** -/// -namespace CSJ2K.Icc.Lut -{ - - /// A Linear 32 bit SRGB to SRGB lut - /// - /// - /// 1.0 - /// - /// Bruce A. Kern - /// - public class LookUpTable32LinearSRGBtoSRGB : LookUpTable32 - { - - /// Factory method for creating the lut. - /// size of shadow region - /// - /// shadow region parameter - /// - /// size of lut - /// - /// post shadow region parameter - /// - /// post shadow region parameter - /// - /// post shadow region parameter - /// - /// the lut - /// - public static LookUpTable32LinearSRGBtoSRGB createInstance(int inMax, int outMax, double shadowCutoff, double shadowSlope, double scaleAfterExp, double exponent, double reduceAfterExp) - { - return new LookUpTable32LinearSRGBtoSRGB(inMax, outMax, shadowCutoff, shadowSlope, scaleAfterExp, exponent, reduceAfterExp); - } - - /// Construct the lut - /// size of shadow region - /// - /// shadow region parameter - /// - /// size of lut - /// - /// post shadow region parameter - /// - /// post shadow region parameter - /// - /// post shadow region parameter - /// - protected internal LookUpTable32LinearSRGBtoSRGB(int inMax, int outMax, double shadowCutoff, double shadowSlope, double scaleAfterExp, double exponent, double reduceAfterExp) : base(inMax + 1, outMax) - { - - int i = -1; - // Normalization factor for i. - double normalize = 1.0 / (double)inMax; - - // Generate the final linear-sRGB to non-linear sRGB LUT - - // calculate where shadow portion of lut ends. - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - int cutOff = (int)System.Math.Floor(shadowCutoff * inMax); - - // Scale to account for output - shadowSlope *= outMax; - - // Our output needs to be centered on zero so we shift it down. - int shift = (outMax + 1) / 2; - - for (i = 0; i <= cutOff; i++) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - lut[i] = (int)(System.Math.Floor(shadowSlope * (i * normalize) + 0.5) - shift); - } - - // Scale values for output. - scaleAfterExp *= outMax; - reduceAfterExp *= outMax; - - // Now calculate the rest - for (; i <= inMax; i++) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - lut[i] = (int)(System.Math.Floor(scaleAfterExp * System.Math.Pow(i * normalize, exponent) - reduceAfterExp + 0.5) - shift); - } - } - - public override System.String ToString() - { - System.Text.StringBuilder rep = new System.Text.StringBuilder("[LookUpTable32LinearSRGBtoSRGB:"); - return rep.Append("]").ToString(); - } - - /* end class LookUpTable32LinearSRGBtoSRGB */ - } -} \ No newline at end of file diff --git a/CSJ2K/Icc/Lut/LookUpTable8.cs b/CSJ2K/Icc/Lut/LookUpTable8.cs deleted file mode 100644 index 79773e70..00000000 --- a/CSJ2K/Icc/Lut/LookUpTable8.cs +++ /dev/null @@ -1,83 +0,0 @@ -/// ************************************************************************** -/// -/// $Id: LookUpTable8.java,v 1.1 2002/07/25 14:56:48 grosbois Exp $ -/// -/// Copyright Eastman Kodak Company, 343 State Street, Rochester, NY 14650 -/// $Date $ -/// *************************************************************************** -/// -using ICCCurveType = CSJ2K.Icc.Tags.ICCCurveType; -namespace CSJ2K.Icc.Lut -{ - - /// Toplevel class for a byte [] lut. - /// - /// - /// 1.0 - /// - /// Bruce A. Kern - /// - public abstract class LookUpTable8 : LookUpTable - { - - /// Maximum output value of the LUT - //UPGRADE_NOTE: Final was removed from the declaration of 'dwMaxOutput '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - protected internal byte dwMaxOutput; - /// The lut values. - // Maximum output value of the LUT - //UPGRADE_NOTE: Final was removed from the declaration of 'lut '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - protected internal byte[] lut; - - - /// Create an abbreviated string representation of a 16 bit lut. - /// the lut as a String - /// - public override System.String ToString() - { - System.Text.StringBuilder rep = new System.Text.StringBuilder("[LookUpTable8 "); - //int row, col; - rep.Append("max= " + dwMaxOutput); - rep.Append(", nentries= " + dwMaxOutput); - return rep.Append("]").ToString(); - } - - - - public virtual System.String toStringWholeLut() - { - System.Text.StringBuilder rep = new System.Text.StringBuilder("LookUpTable8" + eol); - rep.Append("maxOutput = " + dwMaxOutput + eol); - for (int i = 0; i < dwNumInput; ++i) - rep.Append("lut[" + i + "] = " + lut[i] + eol); - return rep.Append("]").ToString(); - } - - protected internal LookUpTable8(int dwNumInput, byte dwMaxOutput) : base(null, dwNumInput) - { - lut = new byte[dwNumInput]; - this.dwMaxOutput = dwMaxOutput; - } - - - /// Create the string representation of a 16 bit lut. - /// the lut as a String - /// - protected internal LookUpTable8(ICCCurveType curve, int dwNumInput, byte dwMaxOutput) : base(curve, dwNumInput) - { - this.dwMaxOutput = dwMaxOutput; - lut = new byte[dwNumInput]; - } - - /// lut accessor - /// of the element - /// - /// the lut [index] - /// - public byte elementAt(int index) - { - return lut[index]; - } - - /* end class LookUpTable8 */ - } -} \ No newline at end of file diff --git a/CSJ2K/Icc/Lut/LookUpTable8Gamma.cs b/CSJ2K/Icc/Lut/LookUpTable8Gamma.cs deleted file mode 100644 index 9dd22264..00000000 --- a/CSJ2K/Icc/Lut/LookUpTable8Gamma.cs +++ /dev/null @@ -1,42 +0,0 @@ -/// ************************************************************************** -/// -/// $Id: LookUpTable8Gamma.java,v 1.1 2002/07/25 14:56:48 grosbois Exp $ -/// -/// Copyright Eastman Kodak Company, 343 State Street, Rochester, NY 14650 -/// $Date $ -/// *************************************************************************** -/// -using ICCCurveType = CSJ2K.Icc.Tags.ICCCurveType; -namespace CSJ2K.Icc.Lut -{ - - /// A Gamma based 16 bit lut. - /// - /// - /// - /// - /// 1.0 - /// - /// Bruce A. Kern - /// - public class LookUpTable8Gamma : LookUpTable8 - { - - /* Construct the lut - * @param curve data - * @param dwNumInput size of lut - * @param dwMaxOutput max value of lut - */ - public LookUpTable8Gamma(ICCCurveType curve, int dwNumInput, byte dwMaxOutput) : base(curve, dwNumInput, dwMaxOutput) - { - double dfE = ICCCurveType.CurveGammaToDouble(curve.entry(0)); // Gamma exponent for inverse transformation - for (int i = 0; i < dwNumInput; i++) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - lut[i] = (byte)System.Math.Floor(System.Math.Pow((double)i / (dwNumInput - 1), dfE) * dwMaxOutput + 0.5); - } - } - - /* end class LookUpTable8Gamma */ - } -} \ No newline at end of file diff --git a/CSJ2K/Icc/Lut/LookUpTable8Interp.cs b/CSJ2K/Icc/Lut/LookUpTable8Interp.cs deleted file mode 100644 index 98619ad3..00000000 --- a/CSJ2K/Icc/Lut/LookUpTable8Interp.cs +++ /dev/null @@ -1,66 +0,0 @@ -/// ************************************************************************** -/// -/// $Id: LookUpTable8Interp.java,v 1.1 2002/07/25 14:56:48 grosbois Exp $ -/// -/// Copyright Eastman Kodak Company, 343 State Street, Rochester, NY 14650 -/// $Date $ -/// *************************************************************************** -/// -using ICCCurveType = CSJ2K.Icc.Tags.ICCCurveType; -namespace CSJ2K.Icc.Lut -{ - - - /// An interpolated 8 bit lut - /// - /// - /// 1.0 - /// - /// Bruce A.Kern - /// - public class LookUpTable8Interp : LookUpTable8 - { - - /// Construct the lut from the curve data - /// curve the data - /// dwNumInput the lut size - /// dwMaxOutput the lut max value - public LookUpTable8Interp(ICCCurveType curve, int dwNumInput, byte dwMaxOutput) : base(curve, dwNumInput, dwMaxOutput) - { - - int dwLowIndex, dwHighIndex; // Indices of interpolation points - double dfLowIndex, dfHighIndex; // FP indices of interpolation points - double dfTargetIndex; // Target index into interpolation table - double dfRatio; // Ratio of LUT input points to curve values - double dfLow, dfHigh; // Interpolation values - double dfOut; // Output LUT value - - dfRatio = (double)(curve.count - 1) / (double)(dwNumInput - 1); - - for (int i = 0; i < dwNumInput; i++) - { - dfTargetIndex = (double)i * dfRatio; - dfLowIndex = System.Math.Floor(dfTargetIndex); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - dwLowIndex = (int)dfLowIndex; - dfHighIndex = System.Math.Ceiling(dfTargetIndex); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - dwHighIndex = (int)dfHighIndex; - - if (dwLowIndex == dwHighIndex) - dfOut = ICCCurveType.CurveToDouble(curve.entry(dwLowIndex)); - else - { - dfLow = ICCCurveType.CurveToDouble(curve.entry(dwLowIndex)); - dfHigh = ICCCurveType.CurveToDouble(curve.entry(dwHighIndex)); - dfOut = dfLow + (dfHigh - dfLow) * (dfTargetIndex - dfLowIndex); - } - - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - lut[i] = (byte)System.Math.Floor(dfOut * dwMaxOutput + 0.5); - } - } - - /* end class LookUpTable8Interp */ - } -} \ No newline at end of file diff --git a/CSJ2K/Icc/Lut/LookUpTableFP.cs b/CSJ2K/Icc/Lut/LookUpTableFP.cs deleted file mode 100644 index 06fba55b..00000000 --- a/CSJ2K/Icc/Lut/LookUpTableFP.cs +++ /dev/null @@ -1,66 +0,0 @@ -/// ************************************************************************** -/// -/// $Id: LookUpTableFP.java,v 1.1 2002/07/25 14:56:49 grosbois Exp $ -/// -/// Copyright Eastman Kodak Company, 343 State Street, Rochester, NY 14650 -/// $Date $ -/// *************************************************************************** -/// -using ICCCurveType = CSJ2K.Icc.Tags.ICCCurveType; -namespace CSJ2K.Icc.Lut -{ - - /// Toplevel class for a float [] lut. - /// - /// - /// 1.0 - /// - /// Bruce A. Kern - /// - public abstract class LookUpTableFP : LookUpTable - { - - /// The lut values. - //UPGRADE_NOTE: Final was removed from the declaration of 'lut '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public float[] lut; - - /// Factory method for getting a lut from a given curve. - /// the data - /// - /// the size of the lut - /// - /// the lookup table - /// - - public static LookUpTableFP createInstance(ICCCurveType curve, int dwNumInput) - { - - if (curve.nEntries == 1) - return new LookUpTableFPGamma(curve, dwNumInput); - else - return new LookUpTableFPInterp(curve, dwNumInput); - } - - /// Construct an empty lut - /// the size of the lut t lut. - /// - /// max output value of the lut - /// - protected internal LookUpTableFP(ICCCurveType curve, int dwNumInput) : base(curve, dwNumInput) - { - lut = new float[dwNumInput]; - } - - /// lut accessor - /// of the element - /// - /// the lut [index] - /// - public float elementAt(int index) - { - return lut[index]; - } - - /* end class LookUpTableFP */ - } -} \ No newline at end of file diff --git a/CSJ2K/Icc/Lut/LookUpTableFPGamma.cs b/CSJ2K/Icc/Lut/LookUpTableFPGamma.cs deleted file mode 100644 index 012b034f..00000000 --- a/CSJ2K/Icc/Lut/LookUpTableFPGamma.cs +++ /dev/null @@ -1,55 +0,0 @@ -/// ************************************************************************** -/// -/// $Id: LookUpTableFPGamma.java,v 1.1 2002/07/25 14:56:48 grosbois Exp $ -/// -/// Copyright Eastman Kodak Company, 343 State Street, Rochester, NY 14650 -/// $Date $ -/// *************************************************************************** -/// -using ICCCurveType = CSJ2K.Icc.Tags.ICCCurveType; -namespace CSJ2K.Icc.Lut -{ - - /// Class Description - /// - /// - /// 1.0 - /// - /// Bruce A. Kern - /// - - public class LookUpTableFPGamma : LookUpTableFP - { - - internal double dfE = -1; - //UPGRADE_NOTE: Final was removed from the declaration of 'eol '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - new private static readonly System.String eol = System.Environment.NewLine; - - public LookUpTableFPGamma(ICCCurveType curve, int dwNumInput) : base(curve, dwNumInput) - { - - // Gamma exponent for inverse transformation - dfE = ICCCurveType.CurveGammaToDouble(curve.entry(0)); - for (int i = 0; i < dwNumInput; i++) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - lut[i] = (float)System.Math.Pow((double)i / (dwNumInput - 1), dfE); - } - } - - /// Create an abbreviated string representation of a 16 bit lut. - /// the lut as a String - /// - public override System.String ToString() - { - System.Text.StringBuilder rep = new System.Text.StringBuilder("[LookUpTableGamma "); - //int row, col; - rep.Append("dfe= " + dfE); - rep.Append(", nentries= " + lut.Length); - return rep.Append("]").ToString(); - } - - - /* end class LookUpTableFPGamma */ - } -} \ No newline at end of file diff --git a/CSJ2K/Icc/Lut/LookUpTableFPInterp.cs b/CSJ2K/Icc/Lut/LookUpTableFPInterp.cs deleted file mode 100644 index c3c7f654..00000000 --- a/CSJ2K/Icc/Lut/LookUpTableFPInterp.cs +++ /dev/null @@ -1,72 +0,0 @@ -/// ************************************************************************** -/// -/// $Id: LookUpTableFPInterp.java,v 1.1 2002/07/25 14:56:48 grosbois Exp $ -/// -/// Copyright Eastman Kodak Company, 343 State Street, Rochester, NY 14650 -/// $Date $ -/// *************************************************************************** -/// -using ICCCurveType = CSJ2K.Icc.Tags.ICCCurveType; -namespace CSJ2K.Icc.Lut -{ - - /// An interpolated floating point lut - /// - /// - /// 1.0 - /// - /// Bruce A.Kern - /// - public class LookUpTableFPInterp : LookUpTableFP - { - - /// Create an abbreviated string representation of a 16 bit lut. - /// the lut as a String - /// - public override System.String ToString() - { - System.Text.StringBuilder rep = new System.Text.StringBuilder("[LookUpTable32 ").Append(" nentries= " + lut.Length); - return rep.Append("]").ToString(); - } - - /// Construct the lut from the curve data - /// curve the data - /// dwNumInput the lut size - public LookUpTableFPInterp(ICCCurveType curve, int dwNumInput) : base(curve, dwNumInput) - { - - int dwLowIndex, dwHighIndex; // Indices of interpolation points - double dfLowIndex, dfHighIndex; // FP indices of interpolation points - double dfTargetIndex; // Target index into interpolation table - double dfRatio; // Ratio of LUT input points to curve values - double dfLow, dfHigh; // Interpolation values - - dfRatio = (double)(curve.nEntries - 1) / (double)(dwNumInput - 1); - - for (int i = 0; i < dwNumInput; i++) - { - dfTargetIndex = (double)i * dfRatio; - dfLowIndex = System.Math.Floor(dfTargetIndex); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - dwLowIndex = (int)dfLowIndex; - dfHighIndex = System.Math.Ceiling(dfTargetIndex); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - dwHighIndex = (int)dfHighIndex; - if (dwLowIndex == dwHighIndex) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - lut[i] = (float)ICCCurveType.CurveToDouble(curve.entry(dwLowIndex)); - } - else - { - dfLow = ICCCurveType.CurveToDouble(curve.entry(dwLowIndex)); - dfHigh = ICCCurveType.CurveToDouble(curve.entry(dwHighIndex)); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - lut[i] = (float)(dfLow + (dfHigh - dfLow) * (dfTargetIndex - dfLowIndex)); - } - } - } - - /* end class LookUpTableFPInterp */ - } -} \ No newline at end of file diff --git a/CSJ2K/Icc/Lut/MatrixBasedTransformException.cs b/CSJ2K/Icc/Lut/MatrixBasedTransformException.cs deleted file mode 100644 index fd86fc4b..00000000 --- a/CSJ2K/Icc/Lut/MatrixBasedTransformException.cs +++ /dev/null @@ -1,42 +0,0 @@ -/// ************************************************************************** -/// -/// $Id: MatrixBasedTransformException.java,v 1.1 2002/07/25 14:56:49 grosbois Exp $ -/// -/// Copyright Eastman Kodak Company, 343 State Street, Rochester, NY 14650 -/// $Date $ -/// *************************************************************************** -/// -using System; -namespace CSJ2K.Icc.Lut -{ - - /// Thrown by MatrixBasedTransformTosRGB - /// - /// - /// - /// - /// 1.0 - /// - /// Bruce A. Kern - /// - - [Serializable] - public class MatrixBasedTransformException : System.Exception - { - - /// Contruct with message - /// returned by getMessage() - /// - internal MatrixBasedTransformException(System.String msg) : base(msg) - { - } - - - /// Empty constructor - internal MatrixBasedTransformException() - { - } - - /* end class MatrixBasedTransformException */ - } -} \ No newline at end of file diff --git a/CSJ2K/Icc/Lut/MatrixBasedTransformTosRGB.cs b/CSJ2K/Icc/Lut/MatrixBasedTransformTosRGB.cs deleted file mode 100644 index d3c78704..00000000 --- a/CSJ2K/Icc/Lut/MatrixBasedTransformTosRGB.cs +++ /dev/null @@ -1,472 +0,0 @@ -/// ************************************************************************** -/// -/// $Id: MatrixBasedTransformTosRGB.java,v 1.1 2002/07/25 14:56:49 grosbois Exp $ -/// -/// Copyright Eastman Kodak Company, 343 State Street, Rochester, NY 14650 -/// $Date $ -/// *************************************************************************** -/// -using ColorSpace = CSJ2K.Color.ColorSpace; -using DataBlkFloat = CSJ2K.j2k.image.DataBlkFloat; -using DataBlkInt = CSJ2K.j2k.image.DataBlkInt; -using ICCXYZType = CSJ2K.Icc.Tags.ICCXYZType; -namespace CSJ2K.Icc.Lut -{ - - /// Transform for applying ICCProfiling to an input DataBlk - /// - /// - /// - /// - /// - /// - /// 1.0 - /// - /// Bruce A. Kern - /// - public class MatrixBasedTransformTosRGB - { - - //UPGRADE_NOTE: Final was removed from the declaration of 'eol '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly System.String eol = System.Environment.NewLine; - - // Start of contant definitions: - - //UPGRADE_NOTE: Final was removed from the declaration of 'RED '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - //UPGRADE_NOTE: The initialization of 'RED' was moved to static method 'icc.lut.MatrixBasedTransformTosRGB'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1005'" - //UPGRADE_NOTE: Final was removed from the declaration of 'GREEN '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - //UPGRADE_NOTE: The initialization of 'GREEN' was moved to static method 'icc.lut.MatrixBasedTransformTosRGB'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1005'" - //UPGRADE_NOTE: Final was removed from the declaration of 'BLUE '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - //UPGRADE_NOTE: The initialization of 'BLUE' was moved to static method 'icc.lut.MatrixBasedTransformTosRGB'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1005'" - private static readonly int RED; - private static readonly int GREEN; - private static readonly int BLUE; - - private const double SRGB00 = 3.1337; - private const double SRGB01 = -1.6173; - private const double SRGB02 = -0.4907; - private const double SRGB10 = -0.9785; - private const double SRGB11 = 1.9162; - private const double SRGB12 = 0.0334; - private const double SRGB20 = 0.0720; - private const double SRGB21 = -0.2290; - private const double SRGB22 = 1.4056; - - // Define constants representing the indices into the matrix array - private const int M00 = 0; - private const int M01 = 1; - private const int M02 = 2; - private const int M10 = 3; - private const int M11 = 4; - private const int M12 = 5; - private const int M20 = 6; - private const int M21 = 7; - private const int M22 = 8; - - private const double ksRGBExponent = (1.0 / 2.4); - private const double ksRGBScaleAfterExp = 1.055; - private const double ksRGBReduceAfterExp = 0.055; - private const double ksRGBShadowCutoff = 0.0031308; - private const double ksRGBShadowSlope = 12.92; - - // End of contant definitions: - - //UPGRADE_NOTE: Final was removed from the declaration of 'matrix '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private double[] matrix; // Matrix coefficients - - private LookUpTableFP[] fLut = new LookUpTableFP[3]; - private LookUpTable32LinearSRGBtoSRGB lut; // Linear sRGB to sRGB LUT - - //UPGRADE_NOTE: Final was removed from the declaration of 'dwMaxValue '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private int[] dwMaxValue; - //UPGRADE_NOTE: Final was removed from the declaration of 'dwShiftValue '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private int[] dwShiftValue; - - //private int dwMaxCols = 0; // Maximum number of columns that can be processed - //private int dwMaxRows = 0; // Maximum number of rows that can be processed - - private float[][] fBuf = null; // Intermediate output of the first LUT operation. - - /// String representation of class - /// suitable representation for class - /// - public override System.String ToString() - { - int i, j; - - System.Text.StringBuilder rep = new System.Text.StringBuilder("[MatrixBasedTransformTosRGB: "); - - System.Text.StringBuilder body = new System.Text.StringBuilder(" "); - body.Append(eol).Append("ksRGBExponent= ").Append(System.Convert.ToString(ksRGBExponent)); - body.Append(eol).Append("ksRGBScaleAfterExp= ").Append(System.Convert.ToString(ksRGBScaleAfterExp)); - body.Append(eol).Append("ksRGBReduceAfterExp= ").Append(System.Convert.ToString(ksRGBReduceAfterExp)); - - - body.Append(eol).Append("dwMaxValues= ").Append(System.Convert.ToString(dwMaxValue[0])).Append(", ").Append(System.Convert.ToString(dwMaxValue[1])).Append(", ").Append(System.Convert.ToString(dwMaxValue[2])); - - body.Append(eol).Append("dwShiftValues= ").Append(System.Convert.ToString(dwShiftValue[0])).Append(", ").Append(System.Convert.ToString(dwShiftValue[1])).Append(", ").Append(System.Convert.ToString(dwShiftValue[2])); - - //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Object.toString' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" - body.Append(eol).Append(eol).Append("fLut= ").Append(eol).Append(ColorSpace.indent(" ", "fLut[RED]= " + fLut[0].ToString())).Append(eol).Append(ColorSpace.indent(" ", "fLut[GRN]= " + fLut[1].ToString())).Append(eol).Append(ColorSpace.indent(" ", "fLut[BLU]= " + fLut[2].ToString())); - - // Print the matrix - body.Append(eol).Append(eol).Append("[matrix "); - for (i = 0; i < 3; ++i) - { - body.Append(eol).Append(" "); - for (j = 0; j < 3; ++j) - { - body.Append(matrix[3 * i + j] + " "); - } - } - body.Append("]"); - - - // Print the LinearSRGBtoSRGB lut. - body.Append(eol).Append(eol).Append(lut.ToString()); - - rep.Append(ColorSpace.indent(" ", body)).Append("]"); - return rep.Append("]").ToString(); - } - - - /// Construct a 3 component transform based on an input RestricedICCProfile - /// This transform will pass the input throught a floating point lut (LookUpTableFP), - /// apply a matrix to the output and finally pass the intermediate buffer through - /// a 8-bit lut (LookUpTable8). This operation will be designated (LFP*M*L8) * Data - /// The operators (LFP*M*L8) are constructed here. Although the data for - /// only one component is returned, the transformation must be done for all - /// components, because the matrix application involves a linear combination of - /// component input to produce the output. - /// - /// input profile - /// - /// clipping value for output. - /// - /// number of columns to transform - /// - /// number of rows to transform - /// - public MatrixBasedTransformTosRGB(RestrictedICCProfile ricc, int[] dwMaxValue, int[] dwShiftValue) - { - - // Assure the proper type profile for this xform. - if (ricc.Type != RestrictedICCProfile.kThreeCompInput) - throw new System.ArgumentException("MatrixBasedTransformTosRGB: wrong type ICCProfile supplied"); - - int c; // component index. - this.dwMaxValue = dwMaxValue; - this.dwShiftValue = dwShiftValue; - - // Create the LUTFP from the input profile. - for (c = 0; c < 3; ++c) - { - fLut[c] = LookUpTableFP.createInstance(ricc.trc[c], dwMaxValue[c] + 1); - } - - // Create the Input linear to PCS matrix - matrix = createMatrix(ricc, dwMaxValue); // Create and matrix from the ICC profile. - - // Create the final LUT32 - lut = LookUpTable32LinearSRGBtoSRGB.createInstance(dwMaxValue[0], dwMaxValue[0], ksRGBShadowCutoff, ksRGBShadowSlope, ksRGBScaleAfterExp, ksRGBExponent, ksRGBReduceAfterExp); - } - - - private double[] createMatrix(RestrictedICCProfile ricc, int[] maxValues) - { - - // Coefficients from the input linear to PCS matrix - double dfPCS00 = ICCXYZType.XYZToDouble(ricc.colorant[RED].x); - double dfPCS01 = ICCXYZType.XYZToDouble(ricc.colorant[GREEN].x); - double dfPCS02 = ICCXYZType.XYZToDouble(ricc.colorant[BLUE].x); - double dfPCS10 = ICCXYZType.XYZToDouble(ricc.colorant[RED].y); - double dfPCS11 = ICCXYZType.XYZToDouble(ricc.colorant[GREEN].y); - double dfPCS12 = ICCXYZType.XYZToDouble(ricc.colorant[BLUE].y); - double dfPCS20 = ICCXYZType.XYZToDouble(ricc.colorant[RED].z); - double dfPCS21 = ICCXYZType.XYZToDouble(ricc.colorant[GREEN].z); - double dfPCS22 = ICCXYZType.XYZToDouble(ricc.colorant[BLUE].z); - - double[] matrix = new double[9]; - matrix[M00] = maxValues[0] * (SRGB00 * dfPCS00 + SRGB01 * dfPCS10 + SRGB02 * dfPCS20); - matrix[M01] = maxValues[0] * (SRGB00 * dfPCS01 + SRGB01 * dfPCS11 + SRGB02 * dfPCS21); - matrix[M02] = maxValues[0] * (SRGB00 * dfPCS02 + SRGB01 * dfPCS12 + SRGB02 * dfPCS22); - matrix[M10] = maxValues[1] * (SRGB10 * dfPCS00 + SRGB11 * dfPCS10 + SRGB12 * dfPCS20); - matrix[M11] = maxValues[1] * (SRGB10 * dfPCS01 + SRGB11 * dfPCS11 + SRGB12 * dfPCS21); - matrix[M12] = maxValues[1] * (SRGB10 * dfPCS02 + SRGB11 * dfPCS12 + SRGB12 * dfPCS22); - matrix[M20] = maxValues[2] * (SRGB20 * dfPCS00 + SRGB21 * dfPCS10 + SRGB22 * dfPCS20); - matrix[M21] = maxValues[2] * (SRGB20 * dfPCS01 + SRGB21 * dfPCS11 + SRGB22 * dfPCS21); - matrix[M22] = maxValues[2] * (SRGB20 * dfPCS02 + SRGB21 * dfPCS12 + SRGB22 * dfPCS22); - - return matrix; - } - - - /// Performs the transform. Pass the input throught the LookUpTableFP, apply the - /// matrix to the output and finally pass the intermediate buffer through the - /// LookUpTable8. This operation is designated (LFP*M*L8) * Data are already - /// constructed. Although the data for only one component is returned, the - /// transformation must be done for all components, because the matrix application - /// involves a linear combination of component input to produce the output. - /// - /// number of columns in the input - /// - /// number of rows in the input - /// - /// input data block - /// - /// output data block - /// - /// - /// - public virtual void apply(DataBlkInt[] inb, DataBlkInt[] outb) - { - int[][] in_Renamed = new int[3][], out_Renamed = new int[3][]; // data references. - - int nrows = inb[0].h, ncols = inb[0].w; - - if ((fBuf == null) || (fBuf[0].Length < ncols * nrows)) - { - float[][] tmpArray = new float[3][]; - for (int i = 0; i < 3; i++) - { - tmpArray[i] = new float[ncols * nrows]; - } - fBuf = tmpArray; - } - - // for each component (rgb) - for (int c = 0; c < 3; ++c) - { - - // Reference the input and output samples. - in_Renamed[c] = (int[])inb[c].Data; - out_Renamed[c] = (int[])outb[c].Data; - - // Assure a properly sized output buffer. - if (out_Renamed[c] == null || out_Renamed[c].Length < in_Renamed[c].Length) - { - out_Renamed[c] = new int[in_Renamed[c].Length]; - outb[c].Data = out_Renamed[c]; - } - - // The first thing to do is to process the input into a standard form - // and through the first input LUT, producing floating point output values - standardizeMatrixLineThroughLut(inb[c], fBuf[c], dwMaxValue[c], fLut[c]); - } - - // For each row and column - float[] ra = fBuf[RED]; - float[] ga = fBuf[GREEN]; - float[] ba = fBuf[BLUE]; - - int[] ro = out_Renamed[RED]; - int[] go = out_Renamed[GREEN]; - int[] bo = out_Renamed[BLUE]; - int[] lut32 = lut.lut; - - double r, g, b; - int val, index = 0; - for (int y = 0; y < inb[0].h; ++y) - { - int end = index + inb[0].w; - while (index < end) - { - // Calculate the rgb pixel indices for this row / column - r = ra[index]; - g = ga[index]; - b = ba[index]; - - // Apply the matrix to the intermediate floating point data in order to index the - // final LUT. - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - val = (int)(matrix[M00] * r + matrix[M01] * g + matrix[M02] * b + 0.5); - // Clip the calculated value if necessary.. - if (val < 0) - ro[index] = lut32[0]; - else if (val >= lut32.Length) - ro[index] = lut32[lut32.Length - 1]; - else - ro[index] = lut32[val]; - - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - val = (int)(matrix[M10] * r + matrix[M11] * g + matrix[M12] * b + 0.5); - // Clip the calculated value if necessary.. - if (val < 0) - go[index] = lut32[0]; - else if (val >= lut32.Length) - go[index] = lut32[lut32.Length - 1]; - else - go[index] = lut32[val]; - - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - val = (int)(matrix[M20] * r + matrix[M21] * g + matrix[M22] * b + 0.5); - // Clip the calculated value if necessary.. - if (val < 0) - bo[index] = lut32[0]; - else if (val >= lut32.Length) - bo[index] = lut32[lut32.Length - 1]; - else - bo[index] = lut32[val]; - - index++; - } - } - } - - /// Performs the transform. Pass the input throught the LookUpTableFP, apply the - /// matrix to the output and finally pass the intermediate buffer through the - /// LookUpTable8. This operation is designated (LFP*M*L8) * Data are already - /// constructed. Although the data for only one component is returned, the - /// transformation must be done for all components, because the matrix application - /// involves a linear combination of component input to produce the output. - /// - /// number of columns in the input - /// - /// number of rows in the input - /// - /// input data block - /// - /// output data block - /// - /// - /// - public virtual void apply(DataBlkFloat[] inb, DataBlkFloat[] outb) - { - - float[][] in_Renamed = new float[3][], out_Renamed = new float[3][]; // data references. - - int nrows = inb[0].h, ncols = inb[0].w; - - if ((fBuf == null) || (fBuf[0].Length < ncols * nrows)) - { - float[][] tmpArray = new float[3][]; - for (int i = 0; i < 3; i++) - { - tmpArray[i] = new float[ncols * nrows]; - } - fBuf = tmpArray; - } - - // for each component (rgb) - for (int c = 0; c < 3; ++c) - { - - // Reference the input and output pixels. - in_Renamed[c] = (float[])inb[c].Data; - out_Renamed[c] = (float[])outb[c].Data; - - // Assure a properly sized output buffer. - if (out_Renamed[c] == null || out_Renamed[c].Length < in_Renamed[c].Length) - { - out_Renamed[c] = new float[in_Renamed[c].Length]; - outb[c].Data = out_Renamed[c]; - } - - // The first thing to do is to process the input into a standard form - // and through the first input LUT, producing floating point output values - standardizeMatrixLineThroughLut(inb[c], fBuf[c], dwMaxValue[c], fLut[c]); - } - - int[] lut32 = lut.lut; - - // For each row and column - int index = 0, val; - for (int y = 0; y < inb[0].h; ++y) - { - int end = index + inb[0].w; - while (index < end) - { - // Calculate the rgb pixel indices for this row / column - - // Apply the matrix to the intermediate floating point data inorder to index the - // final LUT. - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - val = (int)(matrix[M00] * fBuf[RED][index] + matrix[M01] * fBuf[GREEN][index] + matrix[M02] * fBuf[BLUE][index] + 0.5); - // Clip the calculated value if necessary.. - if (val < 0) - out_Renamed[0][index] = lut32[0]; - else if (val >= lut32.Length) - out_Renamed[0][index] = lut32[lut32.Length - 1]; - else - out_Renamed[0][index] = lut32[val]; - - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - val = (int)(matrix[M10] * fBuf[RED][index] + matrix[M11] * fBuf[GREEN][index] + matrix[M12] * fBuf[BLUE][index] + 0.5); - // Clip the calculated value if necessary.. - if (val < 0) - out_Renamed[1][index] = lut32[0]; - else if (val >= lut32.Length) - out_Renamed[1][index] = lut32[lut32.Length - 1]; - else - out_Renamed[1][index] = lut32[val]; - - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - val = (int)(matrix[M20] * fBuf[RED][index] + matrix[M21] * fBuf[GREEN][index] + matrix[M22] * fBuf[BLUE][index] + 0.5); - // Clip the calculated value if necessary.. - if (val < 0) - out_Renamed[2][index] = lut32[0]; - else if (val >= lut32.Length) - out_Renamed[2][index] = lut32[lut32.Length - 1]; - else - out_Renamed[2][index] = lut32[val]; - - index++; - } - } - } - - private static void standardizeMatrixLineThroughLut(DataBlkInt inb, float[] out_Renamed, int dwInputMaxValue, LookUpTableFP lut) - { - int wTemp, j = 0; - int[] in_Renamed = (int[])inb.Data; // input pixel reference - float[] lutFP = lut.lut; - for (int y = inb.uly; y < inb.uly + inb.h; ++y) - { - for (int x = inb.ulx; x < inb.ulx + inb.w; ++x) - { - int i = inb.offset + (y - inb.uly) * inb.scanw + (x - inb.ulx); // pixel index. - if (in_Renamed[i] > dwInputMaxValue) - wTemp = dwInputMaxValue; - else if (in_Renamed[i] < 0) - wTemp = 0; - else - wTemp = in_Renamed[i]; - out_Renamed[j++] = lutFP[wTemp]; - } - } - } - - - private static void standardizeMatrixLineThroughLut(DataBlkFloat inb, float[] out_Renamed, float dwInputMaxValue, LookUpTableFP lut) - { - int j = 0; - float wTemp; - float[] in_Renamed = (float[])inb.Data; // input pixel reference - float[] lutFP = lut.lut; - - for (int y = inb.uly; y < inb.uly + inb.h; ++y) - { - for (int x = inb.ulx; x < inb.ulx + inb.w; ++x) - { - int i = inb.offset + (y - inb.uly) * inb.scanw + (x - inb.ulx); // pixel index. - if (in_Renamed[i] > dwInputMaxValue) - wTemp = dwInputMaxValue; - else if (in_Renamed[i] < 0) - wTemp = 0; - else - wTemp = in_Renamed[i]; - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - out_Renamed[j++] = lutFP[(int)wTemp]; - } - } - } - - /* end class MatrixBasedTransformTosRGB */ - static MatrixBasedTransformTosRGB() - { - RED = ICCProfile.RED; - GREEN = ICCProfile.GREEN; - BLUE = ICCProfile.BLUE; - } - } -} \ No newline at end of file diff --git a/CSJ2K/Icc/Lut/MonochromeTransformException.cs b/CSJ2K/Icc/Lut/MonochromeTransformException.cs deleted file mode 100644 index 87493283..00000000 --- a/CSJ2K/Icc/Lut/MonochromeTransformException.cs +++ /dev/null @@ -1,41 +0,0 @@ -/// ************************************************************************** -/// -/// $Id: MonochromeTransformException.java,v 1.1 2002/07/25 14:56:49 grosbois Exp $ -/// -/// Copyright Eastman Kodak Company, 343 State Street, Rochester, NY 14650 -/// $Date $ -/// *************************************************************************** -/// -using System; -namespace CSJ2K.Icc.Lut -{ - - /// Exception thrown by MonochromeTransformTosRGB. - /// - /// - /// - /// - /// 1.0 - /// - /// Bruce A. Kern - /// - - [Serializable] - public class MonochromeTransformException : System.Exception - { - - /// Contruct with message - /// returned by getMessage() - /// - internal MonochromeTransformException(System.String msg) : base(msg) - { - } - - /// Empty constructor - internal MonochromeTransformException() - { - } - - /* end class MonochromeTransformException */ - } -} \ No newline at end of file diff --git a/CSJ2K/Icc/Lut/MonochromeTransformTosRGB.cs b/CSJ2K/Icc/Lut/MonochromeTransformTosRGB.cs deleted file mode 100644 index 5e3f16fa..00000000 --- a/CSJ2K/Icc/Lut/MonochromeTransformTosRGB.cs +++ /dev/null @@ -1,210 +0,0 @@ -/// ************************************************************************** -/// -/// $Id: MonochromeTransformTosRGB.java,v 1.1 2002/07/25 14:56:50 grosbois Exp $ -/// -/// Copyright Eastman Kodak Company, 343 State Street, Rochester, NY 14650 -/// $Date $ -/// *************************************************************************** -/// -using ColorSpace = CSJ2K.Color.ColorSpace; -using DataBlkFloat = CSJ2K.j2k.image.DataBlkFloat; -using DataBlkInt = CSJ2K.j2k.image.DataBlkInt; -namespace CSJ2K.Icc.Lut -{ - - /// - /// This class constructs a LookUpTableFP from a RestrictedICCProfile. - /// The values in this table are used to calculate a second lookup table (simply a short []). - /// table. When this transform is applied to an input DataBlk, an output data block is - /// constructed by using the input samples as indices into the lookup table, whose values - /// are used to populate the output DataBlk. - /// - /// - /// - /// - /// - /// - /// 1.0 - /// - /// Bruce A. Kern - /// - - public class MonochromeTransformTosRGB - { - - //UPGRADE_NOTE: Final was removed from the declaration of 'eol '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly System.String eol = System.Environment.NewLine; - - /// Transform parameter. - public const double ksRGBShadowCutoff = 0.0031308; - /// Transform parameter. - public const double ksRGBShadowSlope = 12.92; - /// Transform parameter. - //UPGRADE_NOTE: Final was removed from the declaration of 'ksRGB8ShadowSlope '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly double ksRGB8ShadowSlope = (255 * ksRGBShadowSlope); - /// Transform parameter. - public const double ksRGBExponent = (1.0 / 2.4); - /// Transform parameter. - public const double ksRGB8ScaleAfterExp = 269.025; - /// Transform parameter. - public const double ksRGB8ReduceAfterExp = 14.025; - - private short[] lut = null; - private int dwInputMaxValue = 0; - private LookUpTableFP fLut = null; - - - /// String representation of class - /// suitable representation for class - /// - public override System.String ToString() - { - System.Text.StringBuilder rep = new System.Text.StringBuilder("[MonochromeTransformTosRGB "); - System.Text.StringBuilder body = new System.Text.StringBuilder(" "); - - // Print the parameters: - body.Append(eol).Append("ksRGBShadowSlope= ").Append(System.Convert.ToString(ksRGBShadowSlope)); - body.Append(eol).Append("ksRGBShadowCutoff= ").Append(System.Convert.ToString(ksRGBShadowCutoff)); - body.Append(eol).Append("ksRGBShadowSlope= ").Append(System.Convert.ToString(ksRGBShadowSlope)); - body.Append(eol).Append("ksRGB8ShadowSlope= ").Append(System.Convert.ToString(ksRGB8ShadowSlope)); - body.Append(eol).Append("ksRGBExponent= ").Append(System.Convert.ToString(ksRGBExponent)); - body.Append(eol).Append("ksRGB8ScaleAfterExp= ").Append(System.Convert.ToString(ksRGB8ScaleAfterExp)); - body.Append(eol).Append("ksRGB8ReduceAfterExp= ").Append(System.Convert.ToString((ksRGB8ReduceAfterExp))); - body.Append(eol).Append("dwInputMaxValue= ").Append(System.Convert.ToString(dwInputMaxValue)); - - // Print the LinearSRGBtoSRGB lut. - body.Append(eol).Append("[lut = [short[" + lut.Length + "]]]"); - - // Print the FP luts. - //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Object.toString' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" - body.Append(eol).Append("fLut= " + fLut.ToString()); - - rep.Append(ColorSpace.indent(" ", body)); - return rep.Append("]").ToString(); - } - - /// Construct the lut from the RestrictedICCProfile. - /// - /// - /// input RestrictedICCProfile - /// - /// size of the output lut. - /// - /// value used to shift samples to positive - /// - public MonochromeTransformTosRGB(RestrictedICCProfile ricc, int dwInputMaxValue, int dwInputShiftValue) - { - - if (ricc.Type != RestrictedICCProfile.kMonochromeInput) - throw new System.ArgumentException("MonochromeTransformTosRGB: wrong type ICCProfile supplied"); - - this.dwInputMaxValue = dwInputMaxValue; - lut = new short[dwInputMaxValue + 1]; - fLut = LookUpTableFP.createInstance(ricc.trc[ICCProfile.GRAY], dwInputMaxValue + 1); - - // First calculate the value for the shadow region - int i; - for (i = 0; ((i <= dwInputMaxValue) && (fLut.lut[i] <= ksRGBShadowCutoff)); i++) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - lut[i] = (short)(System.Math.Floor(ksRGB8ShadowSlope * (double)fLut.lut[i] + 0.5) - dwInputShiftValue); - } - - // Now calculate the rest - for (; i <= dwInputMaxValue; i++) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - lut[i] = (short)(System.Math.Floor(ksRGB8ScaleAfterExp * System.Math.Pow((double)fLut.lut[i], ksRGBExponent) - ksRGB8ReduceAfterExp + 0.5) - dwInputShiftValue); - } - } - - /// Populate the output block by looking up the values in the lut, using the input - /// as lut indices. - /// - /// input samples - /// - /// output samples. - /// - /// - /// - public virtual void apply(DataBlkInt inb, DataBlkInt outb) - { - - int i, j, o; // x, y removed - - int[] in_Renamed = (int[])inb.Data; - int[] out_Renamed = (int[])outb.Data; - - if (out_Renamed == null || out_Renamed.Length < in_Renamed.Length) - { - out_Renamed = new int[in_Renamed.Length]; - outb.Data = out_Renamed; - } - - outb.uly = inb.uly; - outb.ulx = inb.ulx; - outb.h = inb.h; - outb.w = inb.w; - outb.offset = inb.offset; - outb.scanw = inb.scanw; - - o = inb.offset; - for (i = 0; i < inb.h * inb.w; ++i) - { - j = in_Renamed[i]; - if (j < 0) - j = 0; - else if (j > dwInputMaxValue) - j = dwInputMaxValue; - out_Renamed[i] = lut[j]; - } - } - - /// Populate the output block by looking up the values in the lut, using the input - /// as lut indices. - /// - /// input samples - /// - /// output samples. - /// - /// - /// - public virtual void apply(DataBlkFloat inb, DataBlkFloat outb) - { - - int i, j, o; // x, y removed - - float[] in_Renamed = (float[])inb.Data; - float[] out_Renamed = (float[])outb.Data; - - - if (out_Renamed == null || out_Renamed.Length < in_Renamed.Length) - { - out_Renamed = new float[in_Renamed.Length]; - outb.Data = out_Renamed; - - outb.uly = inb.uly; - outb.ulx = inb.ulx; - outb.h = inb.h; - outb.w = inb.w; - outb.offset = inb.offset; - outb.scanw = inb.scanw; - } - - o = inb.offset; - for (i = 0; i < inb.h * inb.w; ++i) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - j = (int)in_Renamed[i]; - if (j < 0) - j = 0; - else if (j > dwInputMaxValue) - j = dwInputMaxValue; - out_Renamed[i] = lut[j]; - } - } - - - /* end class MonochromeTransformTosRGB */ - } -} \ No newline at end of file diff --git a/CSJ2K/Icc/MatrixBasedRestrictedProfile.cs b/CSJ2K/Icc/MatrixBasedRestrictedProfile.cs deleted file mode 100644 index 8b16bdc7..00000000 --- a/CSJ2K/Icc/MatrixBasedRestrictedProfile.cs +++ /dev/null @@ -1,91 +0,0 @@ -/// ************************************************************************** -/// -/// $Id: MatrixBasedRestrictedProfile.java,v 1.1 2002/07/25 14:56:56 grosbois Exp $ -/// -/// Copyright Eastman Kodak Company, 343 State Street, Rochester, NY 14650 -/// $Date $ -/// *************************************************************************** -/// -using ICCCurveType = CSJ2K.Icc.Tags.ICCCurveType; -using ICCXYZType = CSJ2K.Icc.Tags.ICCXYZType; -namespace CSJ2K.Icc -{ - - /// This class is a 3 component RestrictedICCProfile - /// - /// - /// 1.0 - /// - /// Bruce A Kern - /// - public class MatrixBasedRestrictedProfile : RestrictedICCProfile - { - /// Get the type of RestrictedICCProfile for this object - /// kThreeCompInput - /// - override public int Type - { - get - { - return kThreeCompInput; - } - - } - - /// Factory method which returns a 3 component RestrictedICCProfile - /// Red TRC curve - /// - /// Green TRC curve - /// - /// Blue TRC curve - /// - /// Red colorant - /// - /// Green colorant - /// - /// Blue colorant - /// - /// the RestrictedICCProfile - /// - public static new RestrictedICCProfile createInstance(ICCCurveType rcurve, ICCCurveType gcurve, ICCCurveType bcurve, ICCXYZType rcolorant, ICCXYZType gcolorant, ICCXYZType bcolorant) - { - return new MatrixBasedRestrictedProfile(rcurve, gcurve, bcurve, rcolorant, gcolorant, bcolorant); - } - - /// Construct a 3 component RestrictedICCProfile - /// Red TRC curve - /// - /// Green TRC curve - /// - /// Blue TRC curve - /// - /// Red colorant - /// - /// Green colorant - /// - /// Blue colorant - /// - protected internal MatrixBasedRestrictedProfile(ICCCurveType rcurve, ICCCurveType gcurve, ICCCurveType bcurve, ICCXYZType rcolorant, ICCXYZType gcolorant, ICCXYZType bcolorant) : base(rcurve, gcurve, bcurve, rcolorant, gcolorant, bcolorant) - { - } - - /// String representation of a MatrixBasedRestrictedProfile - /// - public override System.String ToString() - { - System.Text.StringBuilder rep = new System.Text.StringBuilder("[Matrix-Based Input Restricted ICC profile").Append(eol); - - rep.Append("trc[RED]:").Append(eol).Append(trc[RED]).Append(eol); - rep.Append("trc[RED]:").Append(eol).Append(trc[GREEN]).Append(eol); - rep.Append("trc[RED]:").Append(eol).Append(trc[BLUE]).Append(eol); - - rep.Append("Red colorant: ").Append(colorant[RED]).Append(eol); - rep.Append("Red colorant: ").Append(colorant[GREEN]).Append(eol); - rep.Append("Red colorant: ").Append(colorant[BLUE]).Append(eol); - - return rep.Append("]").ToString(); - } - - /* end class MatrixBasedRestrictedProfile */ - } -} \ No newline at end of file diff --git a/CSJ2K/Icc/MonochromeInputRestrictedProfile.cs b/CSJ2K/Icc/MonochromeInputRestrictedProfile.cs deleted file mode 100644 index fd071e29..00000000 --- a/CSJ2K/Icc/MonochromeInputRestrictedProfile.cs +++ /dev/null @@ -1,64 +0,0 @@ -/// ************************************************************************** -/// -/// $Id: MonochromeInputRestrictedProfile.java,v 1.1 2002/07/25 14:56:56 grosbois Exp $ -/// -/// Copyright Eastman Kodak Company, 343 State Street, Rochester, NY 14650 -/// $Date $ -/// *************************************************************************** -/// -using ICCCurveType = CSJ2K.Icc.Tags.ICCCurveType; -namespace CSJ2K.Icc -{ - - /// This class is a 1 component RestrictedICCProfile - /// - /// - /// 1.0 - /// - /// Bruce A Kern - /// - public class MonochromeInputRestrictedProfile : RestrictedICCProfile - { - /// Get the type of RestrictedICCProfile for this object - /// kMonochromeInput - /// - override public int Type - { - get - { - return kMonochromeInput; - } - - } - - /// Factory method which returns a 1 component RestrictedICCProfile - /// Gray TRC curve - /// - /// the RestrictedICCProfile - /// - public static new RestrictedICCProfile createInstance(ICCCurveType c) - { - return new MonochromeInputRestrictedProfile(c); - } - - /// Construct a 1 component RestrictedICCProfile - /// Gray TRC curve - /// - private MonochromeInputRestrictedProfile(ICCCurveType c) : base(c) - { - } - - /// String representation of a MonochromeInputRestrictedProfile - /// - public override System.String ToString() - { - System.Text.StringBuilder rep = new System.Text.StringBuilder("Monochrome Input Restricted ICC profile" + eol); - - rep.Append("trc[GRAY]:" + eol).Append(trc[GRAY]).Append(eol); - - return rep.ToString(); - } - - /* end class MonochromeInputRestrictedProfile */ - } -} \ No newline at end of file diff --git a/CSJ2K/Icc/RestrictedICCProfile.cs b/CSJ2K/Icc/RestrictedICCProfile.cs deleted file mode 100644 index d5c20193..00000000 --- a/CSJ2K/Icc/RestrictedICCProfile.cs +++ /dev/null @@ -1,141 +0,0 @@ -/// ************************************************************************** -/// -/// $Id: RestrictedICCProfile.java,v 1.1 2002/07/25 14:56:56 grosbois Exp $ -/// -/// Copyright Eastman Kodak Company, 343 State Street, Rochester, NY 14650 -/// $Date $ -/// *************************************************************************** -/// -using ICCCurveType = CSJ2K.Icc.Tags.ICCCurveType; -using ICCXYZType = CSJ2K.Icc.Tags.ICCXYZType; -namespace CSJ2K.Icc -{ - - /// This profile is constructed by parsing an ICCProfile and - /// is the profile actually applied to the image. - /// - /// - /// - /// - /// 1.0 - /// - /// Bruce A. Kern - /// - public abstract class RestrictedICCProfile - { - /// Returns the appropriate input type enum. - public abstract int Type { get; } - - //UPGRADE_NOTE: Final was removed from the declaration of 'eol '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - protected internal static readonly System.String eol = System.Environment.NewLine; - - /// Factory method for creating a RestrictedICCProfile from - /// 3 component curve and colorant data. - /// - /// red curve - /// - /// green curve - /// - /// blue curve - /// - /// red colorant - /// - /// green colorant - /// - /// blue colorant - /// - /// MatrixBasedRestrictedProfile - /// - public static RestrictedICCProfile createInstance(ICCCurveType rcurve, ICCCurveType gcurve, ICCCurveType bcurve, ICCXYZType rcolorant, ICCXYZType gcolorant, ICCXYZType bcolorant) - { - - return MatrixBasedRestrictedProfile.createInstance(rcurve, gcurve, bcurve, rcolorant, gcolorant, bcolorant); - } - - /// Factory method for creating a RestrictedICCProfile from - /// gray curve data. - /// - /// gray curve - /// - /// MonochromeInputRestrictedProfile - /// - public static RestrictedICCProfile createInstance(ICCCurveType gcurve) - { - return MonochromeInputRestrictedProfile.createInstance(gcurve); - } - - /// Component index - //UPGRADE_NOTE: Final was removed from the declaration of 'GRAY '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - //UPGRADE_NOTE: The initialization of 'GRAY' was moved to static method 'icc.RestrictedICCProfile'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1005'" - protected internal static readonly int GRAY; - /// Component index - //UPGRADE_NOTE: Final was removed from the declaration of 'RED '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - //UPGRADE_NOTE: The initialization of 'RED' was moved to static method 'icc.RestrictedICCProfile'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1005'" - protected internal static readonly int RED; - /// Component index - //UPGRADE_NOTE: Final was removed from the declaration of 'GREEN '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - //UPGRADE_NOTE: The initialization of 'GREEN' was moved to static method 'icc.RestrictedICCProfile'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1005'" - protected internal static readonly int GREEN; - /// Component index - //UPGRADE_NOTE: Final was removed from the declaration of 'BLUE '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - //UPGRADE_NOTE: The initialization of 'BLUE' was moved to static method 'icc.RestrictedICCProfile'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1005'" - protected internal static readonly int BLUE; - /// input type enumerator - public const int kMonochromeInput = 0; - /// input type enumerator - public const int kThreeCompInput = 1; - - /// Curve data - public ICCCurveType[] trc; - /// Colorant data - public ICCXYZType[] colorant; - - /// Construct the common state of all gray RestrictedICCProfiles - /// curve data - /// - protected internal RestrictedICCProfile(ICCCurveType gcurve) - { - trc = new ICCCurveType[1]; - colorant = null; - trc[GRAY] = gcurve; - } - - /// Construct the common state of all 3 component RestrictedICCProfiles - /// - /// - /// red curve - /// - /// green curve - /// - /// blue curve - /// - /// red colorant - /// - /// green colorant - /// - /// blue colorant - /// - protected internal RestrictedICCProfile(ICCCurveType rcurve, ICCCurveType gcurve, ICCCurveType bcurve, ICCXYZType rcolorant, ICCXYZType gcolorant, ICCXYZType bcolorant) - { - trc = new ICCCurveType[3]; - colorant = new ICCXYZType[3]; - - trc[RED] = rcurve; - trc[GREEN] = gcurve; - trc[BLUE] = bcurve; - - colorant[RED] = rcolorant; - colorant[GREEN] = gcolorant; - colorant[BLUE] = bcolorant; - } - - /* end class RestrictedICCProfile */ - static RestrictedICCProfile() - { - GRAY = ICCProfile.GRAY; - RED = ICCProfile.RED; - GREEN = ICCProfile.GREEN; - BLUE = ICCProfile.BLUE; - } - } -} \ No newline at end of file diff --git a/CSJ2K/Icc/Tags/ICCCurveType.cs b/CSJ2K/Icc/Tags/ICCCurveType.cs deleted file mode 100644 index 9e8aab6e..00000000 --- a/CSJ2K/Icc/Tags/ICCCurveType.cs +++ /dev/null @@ -1,92 +0,0 @@ -/// ************************************************************************** -/// -/// $Id: ICCCurveType.java,v 1.1 2002/07/25 14:56:36 grosbois Exp $ -/// -/// Copyright Eastman Kodak Company, 343 State Street, Rochester, NY 14650 -/// $Date $ -/// *************************************************************************** -/// -namespace CSJ2K.Icc.Tags -{ - - /// The ICCCurve tag - /// - /// - /// 1.0 - /// - /// Bruce A. Kern - /// - public class ICCCurveType : ICCTag - { - - //UPGRADE_NOTE: Final was removed from the declaration of 'eol '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly System.String eol = System.Environment.NewLine; - /// Tag fields - //UPGRADE_NOTE: Final was removed from the declaration of 'type '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - new public int type; - /// Tag fields - //UPGRADE_NOTE: Final was removed from the declaration of 'reserved '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public int reserved; - /// Tag fields - //UPGRADE_NOTE: Final was removed from the declaration of 'nEntries '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public int nEntries; - /// Tag fields - //UPGRADE_NOTE: Final was removed from the declaration of 'entry '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public int[] entry_Renamed_Field; - - /// Return the string rep of this tag. - public override System.String ToString() - { - System.Text.StringBuilder rep = new System.Text.StringBuilder("[").Append(base.ToString()).Append(" nentries = ").Append(System.Convert.ToString(nEntries)).Append(", length = " + System.Convert.ToString(entry_Renamed_Field.Length) + " ... "); - return rep.Append("]").ToString(); - } - - /// Normalization utility - public static double CurveToDouble(int entry) - { - return (double)entry / 65535.0; - } - - /// Normalization utility - public static short DoubleToCurve(double entry) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - return (short)System.Math.Floor(entry * 65535.0 + 0.5); - } - - /// Normalization utility - public static double CurveGammaToDouble(int entry) - { - return (double)entry / 256.0; - } - - - /// Construct this tag from its constituant parts - /// tag id - /// - /// array of bytes - /// - /// to data in the data array - /// - /// of data in the data array - /// - protected internal ICCCurveType(int signature, byte[] data, int offset, int length) : base(signature, data, offset, offset + 2 * ICCProfile.int_size) - { - type = ICCProfile.getInt(data, offset); - reserved = ICCProfile.getInt(data, offset + ICCProfile.int_size); - nEntries = ICCProfile.getInt(data, offset + 2 * ICCProfile.int_size); - entry_Renamed_Field = new int[nEntries]; - for (int i = 0; i < nEntries; ++i) - entry_Renamed_Field[i] = ICCProfile.getShort(data, offset + 3 * ICCProfile.int_size + i * ICCProfile.short_size) & 0xFFFF; - } - - - /// Accessor for curve entry at index. - public int entry(int i) - { - return entry_Renamed_Field[i]; - } - - /* end class ICCCurveType */ - } -} \ No newline at end of file diff --git a/CSJ2K/Icc/Tags/ICCCurveTypeReverse.cs b/CSJ2K/Icc/Tags/ICCCurveTypeReverse.cs deleted file mode 100644 index d39d6b1c..00000000 --- a/CSJ2K/Icc/Tags/ICCCurveTypeReverse.cs +++ /dev/null @@ -1,96 +0,0 @@ -/// ************************************************************************** -/// -/// $Id: ICCCurveTypeReverse.java,v 1.1 2002/07/25 14:56:36 grosbois Exp $ -/// -/// Copyright Eastman Kodak Company, 343 State Street, Rochester, NY 14650 -/// $Date $ -/// *************************************************************************** -/// -namespace CSJ2K.Icc.Tags -{ - - /// The ICCCurveReverse tag - /// - /// - /// 1.0 - /// - /// Bruce A. Kern - /// - public class ICCCurveTypeReverse : ICCTag - { - - //UPGRADE_NOTE: Final was removed from the declaration of 'eol '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly System.String eol = System.Environment.NewLine; - /// Tag fields - //UPGRADE_NOTE: Final was removed from the declaration of 'type '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - new public int type; - /// Tag fields - //UPGRADE_NOTE: Final was removed from the declaration of 'reserved '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public int reserved; - /// Tag fields - //UPGRADE_NOTE: Final was removed from the declaration of 'nEntries '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public int nEntries; - /// Tag fields - //UPGRADE_NOTE: Final was removed from the declaration of 'entry '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public int[] entry_Renamed_Field; - - - /// Return the string rep of this tag. - public override System.String ToString() - { - System.Text.StringBuilder rep = new System.Text.StringBuilder("[").Append(base.ToString()).Append(eol); - rep.Append("num entries = " + System.Convert.ToString(nEntries) + eol); - rep.Append("data length = " + System.Convert.ToString(entry_Renamed_Field.Length) + eol); - for (int i = 0; i < nEntries; ++i) - rep.Append(ICCProfile.toHexString(entry_Renamed_Field[i]) + eol); - return rep.Append("]").ToString(); - } - - /// Normalization utility - public static double CurveToDouble(int entry) - { - return ICCCurveType.CurveToDouble(entry); - } - - /// Normalization utility - public static short DoubleToCurve(int entry) - { - return ICCCurveType.DoubleToCurve(entry); - } - - /// Normalization utility - public static double CurveGammaToDouble(int entry) - { - return ICCCurveType.CurveGammaToDouble(entry); - } - - - /// Construct this tag from its constituant parts - /// tag id - /// - /// array of bytes - /// - /// to data in the data array - /// - /// of data in the data array - /// - protected internal ICCCurveTypeReverse(int signature, byte[] data, int offset, int length) : base(signature, data, offset, offset + 2 * ICCProfile.int_size) - { - type = ICCProfile.getInt(data, offset); - reserved = ICCProfile.getInt(data, offset + ICCProfile.int_size); - nEntries = ICCProfile.getInt(data, offset + 2 * ICCProfile.int_size); - entry_Renamed_Field = new int[nEntries]; - for (int i = 0; i < nEntries; ++i) - // Reverse the storage order. - entry_Renamed_Field[nEntries - 1 + i] = ICCProfile.getShort(data, offset + 3 * ICCProfile.int_size + i * ICCProfile.short_size) & 0xFFFF; - } - - /// Accessor for curve entry at index. - public int entry(int i) - { - return entry_Renamed_Field[i]; - } - - /* end class ICCCurveTypeReverse */ - } -} \ No newline at end of file diff --git a/CSJ2K/Icc/Tags/ICCDataType.cs b/CSJ2K/Icc/Tags/ICCDataType.cs deleted file mode 100644 index 68dc0bb3..00000000 --- a/CSJ2K/Icc/Tags/ICCDataType.cs +++ /dev/null @@ -1,24 +0,0 @@ -namespace CSJ2K.Icc.Tags -{ - public class ICCDataType : ICCTag - { - new public int type; - public int reserved; - public int dataFlag; - //byte[] Data; - - /// Construct this tag from its constituant parts - /// tag id - /// array of bytes - /// to data in the data array - /// of data in the data array - protected internal ICCDataType(int signature, byte[] data, int offset, int length) - : base(signature, data, offset, offset + 2 * ICCProfile.int_size) - { - type = ICCProfile.getInt(data, offset); - reserved = ICCProfile.getInt(data, offset + ICCProfile.int_size); - dataFlag = ICCProfile.getInt(data, offset + ICCProfile.int_size); - //Data = ICCProfile.getString(data, offset + ICCProfile.int_size, length, true); - } - } -} \ No newline at end of file diff --git a/CSJ2K/Icc/Tags/ICCMeasurementType.cs b/CSJ2K/Icc/Tags/ICCMeasurementType.cs deleted file mode 100644 index d2317173..00000000 --- a/CSJ2K/Icc/Tags/ICCMeasurementType.cs +++ /dev/null @@ -1,32 +0,0 @@ -using CSJ2K.Icc.Types; - -namespace CSJ2K.Icc.Tags -{ - public class ICCMeasurementType : ICCTag - { - new public int type; - public int reserved; - public int observer; - public XYZNumber backing; - public int geometry; - public int flare; - public int illuminant; - - /// Construct this tag from its constituant parts - /// tag id - /// array of bytes - /// to data in the data array - /// of data in the data array - protected internal ICCMeasurementType(int signature, byte[] data, int offset, int length) - : base(signature, data, offset, offset + 2 * ICCProfile.int_size) - { - type = ICCProfile.getInt(data, offset); - reserved = ICCProfile.getInt(data, offset + ICCProfile.int_size); - observer = ICCProfile.getInt(data, offset + ICCProfile.int_size); - backing = ICCProfile.getXYZNumber(data, offset + ICCProfile.int_size); - geometry = ICCProfile.getInt(data, offset + (ICCProfile.int_size * 3)); - flare = ICCProfile.getInt(data, offset + ICCProfile.int_size); - illuminant = ICCProfile.getInt(data, offset + ICCProfile.int_size); - } - } -} \ No newline at end of file diff --git a/CSJ2K/Icc/Tags/ICCSignatureType.cs b/CSJ2K/Icc/Tags/ICCSignatureType.cs deleted file mode 100644 index 180f0e7f..00000000 --- a/CSJ2K/Icc/Tags/ICCSignatureType.cs +++ /dev/null @@ -1,22 +0,0 @@ -namespace CSJ2K.Icc.Tags -{ - public class ICCSignatureType : ICCTag - { - new public int type; - public int reserved; - new public int signature; - - /// Construct this tag from its constituant parts - /// tag id - /// array of bytes - /// to data in the data array - /// of data in the data array - protected internal ICCSignatureType(int signature, byte[] data, int offset, int length) - : base(signature, data, offset, offset + 2 * ICCProfile.int_size) - { - type = ICCProfile.getInt(data, offset); - reserved = ICCProfile.getInt(data, offset + ICCProfile.int_size); - signature = ICCProfile.getInt(data, offset + ICCProfile.int_size); - } - } -} \ No newline at end of file diff --git a/CSJ2K/Icc/Tags/ICCTag.cs b/CSJ2K/Icc/Tags/ICCTag.cs deleted file mode 100644 index 2cb55e17..00000000 --- a/CSJ2K/Icc/Tags/ICCTag.cs +++ /dev/null @@ -1,276 +0,0 @@ -/// ************************************************************************** -/// -/// $Id: ICCTag.java,v 1.1 2002/07/25 14:56:37 grosbois Exp $ -/// -/// Copyright Eastman Kodak Company, 343 State Street, Rochester, NY 14650 -/// $Date $ -/// *************************************************************************** -/// -using System; -using System.Text; -namespace CSJ2K.Icc.Tags -{ - - /// An ICC profile contains a 128-byte header followed by a variable - /// number of tags contained in a tag table. Each tag is a structured - /// block of ints. The tags share a common format on disk starting with - /// a signature, an offset to the tag data, and a length of the tag data. - /// The tag data itself is found at the given offset in the file and - /// consists of a tag type int, followed by a reserved int, followed by - /// a data block, the structure of which is unique to the tag type. - ///

- /// This class is the abstract super class of all tags. It models that - /// part of the structure which is common among tags of all types.

- /// It also contains the definitions of the various tag types. - /// - /// - ///

- /// - /// - /// 1.0 - /// - /// Bruce A. Kern - /// - public abstract class ICCTag - { - - // Tag Signature Strings - private const System.String sdwCprtSignature = "cprt"; - private const System.String sdwDescSignature = "desc"; - private const System.String sdwWtPtSignature = "wtpt"; - private const System.String sdwBkPtSignature = "bkpt"; - private const System.String sdwRXYZSignature = "rXYZ"; - private const System.String sdwGXYZSignature = "gXYZ"; - private const System.String sdwBXYZSignature = "bXYZ"; - private const System.String sdwKXYZSignature = "kXYZ"; - private const System.String sdwRTRCSignature = "rTRC"; - private const System.String sdwGTRCSignature = "gTRC"; - private const System.String sdwBTRCSignature = "bTRC"; - private const System.String sdwKTRCSignature = "kTRC"; - private const System.String sdwDmndSignature = "dmnd"; - private const System.String sdwDmddSignature = "dmdd"; - - // Tag Signatures - private static readonly int kdwCprtSignature; - private static readonly int kdwDescSignature; - private static readonly int kdwWtPtSignature; - private static readonly int kdwBkPtSignature; - private static readonly int kdwRXYZSignature; - private static readonly int kdwGXYZSignature; - private static readonly int kdwBXYZSignature; - private static readonly int kdwKXYZSignature; - private static readonly int kdwRTRCSignature; - private static readonly int kdwGTRCSignature; - private static readonly int kdwBTRCSignature; - private static readonly int kdwKTRCSignature; - private static readonly int kdwDmndSignature; - private static readonly int kdwDmddSignature; - - // Tag Type Strings - private const string sdwTextDescType = "desc"; - private const string sdwTextType = "text"; - private const string sdwCurveType = "curv"; - private const string sdwCurveTypeReverse = "vruc"; - private const string sdwXYZType = "XYZ "; - private const string sdwXYZTypeReverse = " ZYX"; - private const string sdwMeasurementType = "meas"; - private const string sdwSignatureType = "sig "; - private const string sdwViewType = "view"; - private const string sdwDataType = "data"; - - // Tag Types - private static readonly int kdwTextDescType; - private static readonly int kdwTextType; - private static readonly int kdwCurveType; - private static readonly int kdwCurveTypeReverse; - private static readonly int kdwXYZType; - private static readonly int kdwXYZTypeReverse; - private static readonly int kdwMeasurementType; - private static readonly int kdwSignatureType; - private static readonly int kdwViewType; - private static readonly int kdwDataType; - - /// Tag id - public int signature; - /// Tag type - // Tag signature - public int type; - /// Tag data - public byte[] data; - /// offset to tag data in the array - // Tag type - public int offset; - /// size of the tag data in the array - public int count; - - /// Create a string representation of the tag type - /// input - /// - /// String representation of the type - /// - public static System.String typeString(int type) - { - if (type == kdwTextDescType) - return sdwTextDescType; - else if (type == kdwTextType) - return sdwTextDescType; - else if (type == kdwCurveType) - return sdwCurveType; - else if (type == kdwCurveTypeReverse) - return sdwCurveTypeReverse; - else if (type == kdwXYZType) - return sdwXYZType; - else if (type == kdwXYZTypeReverse) - return sdwXYZTypeReverse; - else if (type == kdwMeasurementType) - return sdwMeasurementType; - else if (type == kdwSignatureType) - return sdwSignatureType; - else if (type == kdwViewType) - return sdwViewType; - else if (type == kdwDataType) - return sdwDataType; - else - return "bad tag type"; - } - - - /// Create a string representation of the signature - /// input - /// - /// String representation of the signature - /// - public static System.String signatureString(int signature) - { - - if (signature == kdwCprtSignature) - return sdwCprtSignature; - else if (signature == kdwDescSignature) - return sdwDescSignature; - else if (signature == kdwWtPtSignature) - return sdwWtPtSignature; - else if (signature == kdwBkPtSignature) - return sdwBkPtSignature; - else if (signature == kdwRXYZSignature) - return sdwRXYZSignature; - else if (signature == kdwGXYZSignature) - return sdwGXYZSignature; - else if (signature == kdwBXYZSignature) - return sdwBXYZSignature; - else if (signature == kdwRTRCSignature) - return sdwRTRCSignature; - else if (signature == kdwGTRCSignature) - return sdwGTRCSignature; - else if (signature == kdwBTRCSignature) - return sdwBTRCSignature; - else if (signature == kdwKTRCSignature) - return sdwKTRCSignature; - else if (signature == kdwDmndSignature) - return sdwDmndSignature; - else if (signature == kdwDmddSignature) - return sdwDmddSignature; - else - return "bad tag signature"; - } - - - /// Factory method for creating a tag of a specific type. - /// tag to create - /// - /// byte array containg embedded tag data - /// - /// to tag data in the array - /// - /// size of tag data in bytes - /// - /// specified ICCTag - /// - public static ICCTag createInstance(int signature, byte[] data, int offset, int count) - { - - int type = ICCProfile.getInt(data, offset); - - if (type == kdwTextDescType) - return new ICCTextDescriptionType(signature, data, offset, count); - else if (type == kdwTextType) - return new ICCTextType(signature, data, offset, count); - else if (type == kdwXYZType) - return new ICCXYZType(signature, data, offset, count); - else if (type == kdwXYZTypeReverse) - return new ICCXYZTypeReverse(signature, data, offset, count); - else if (type == kdwCurveType) - return new ICCCurveType(signature, data, offset, count); - else if (type == kdwCurveTypeReverse) - return new ICCCurveTypeReverse(signature, data, offset, count); - else if (type == kdwMeasurementType) - return new ICCMeasurementType(signature, data, offset, count); - else if (type == kdwSignatureType) - return new ICCSignatureType(signature, data, offset, count); - else if (type == kdwViewType) - return new ICCViewType(signature, data, offset, count); - else if (type == kdwDataType) - return new ICCDataType(signature, data, offset, count); - else - throw new System.ArgumentException("bad tag type: " + System.Text.ASCIIEncoding.ASCII.GetString(BitConverter.GetBytes(type)) + "(" + type + ")"); - } - - - /// Ued by subclass initialization to store the state common to all tags - /// tag being created - /// - /// byte array containg embedded tag data - /// - /// to tag data in the array - /// - /// size of tag data in bytes - /// - protected internal ICCTag(int signature, byte[] data, int offset, int count) - { - this.signature = signature; - this.data = data; - this.offset = offset; - this.count = count; - this.type = ICCProfile.getInt(data, offset); - } - - public override System.String ToString() - { - return signatureString(signature) + ":" + typeString(type); - } - - /* end class ICCTag */ - static ICCTag() - { - kdwCprtSignature = GetTagInt(sdwCprtSignature); - kdwDescSignature = GetTagInt(sdwDescSignature); - kdwWtPtSignature = GetTagInt(sdwWtPtSignature); - kdwBkPtSignature = GetTagInt(sdwBkPtSignature); - kdwRXYZSignature = GetTagInt(sdwRXYZSignature); - kdwGXYZSignature = GetTagInt(sdwGXYZSignature); - kdwBXYZSignature = GetTagInt(sdwBXYZSignature); - kdwKXYZSignature = GetTagInt(sdwKXYZSignature); - kdwRTRCSignature = GetTagInt(sdwRTRCSignature); - kdwGTRCSignature = GetTagInt(sdwGTRCSignature); - kdwBTRCSignature = GetTagInt(sdwBTRCSignature); - kdwKTRCSignature = GetTagInt(sdwKTRCSignature); - kdwDmndSignature = GetTagInt(sdwDmndSignature); - kdwDmddSignature = GetTagInt(sdwDmddSignature); - kdwTextDescType = GetTagInt(sdwTextDescType); - kdwTextType = GetTagInt(sdwTextType); - kdwCurveType = GetTagInt(sdwCurveType); - kdwCurveTypeReverse = GetTagInt(sdwCurveTypeReverse); - kdwXYZType = GetTagInt(sdwXYZType); - kdwXYZTypeReverse = GetTagInt(sdwXYZTypeReverse); - kdwMeasurementType = GetTagInt(sdwMeasurementType); - kdwSignatureType = GetTagInt(sdwSignatureType); - kdwViewType = GetTagInt(sdwViewType); - kdwDataType = GetTagInt(sdwDataType); - } - static int GetTagInt(string tag) - { - byte[] tagBytes = ASCIIEncoding.ASCII.GetBytes(tag); - Array.Reverse(tagBytes); - return BitConverter.ToInt32(tagBytes, 0); - } - } -} \ No newline at end of file diff --git a/CSJ2K/Icc/Tags/ICCTagTable.cs b/CSJ2K/Icc/Tags/ICCTagTable.cs deleted file mode 100644 index c0102c48..00000000 --- a/CSJ2K/Icc/Tags/ICCTagTable.cs +++ /dev/null @@ -1,200 +0,0 @@ -/// ************************************************************************** -/// -/// $Id: ICCTagTable.java,v 1.1 2002/07/25 14:56:37 grosbois Exp $ -/// -/// Copyright Eastman Kodak Company, 343 State Street, Rochester, NY 14650 -/// $Date $ -/// *************************************************************************** -/// -using System; -using ColorSpace = CSJ2K.Color.ColorSpace; -using ICCProfileHeader = CSJ2K.Icc.Types.ICCProfileHeader; -namespace CSJ2K.Icc.Tags -{ - - /// This class models an ICCTagTable as a HashTable which maps - /// ICCTag signatures (as Integers) to ICCTags. - /// - /// On disk the tag table exists as a byte array conventionally aggragted into a - /// structured sequence of types (bytes, shorts, ints, and floats. The first four bytes - /// are the integer count of tags in the table. This is followed by an array of triplets, - /// one for each tag. The triplets each contain three integers, which are the tag signature, - /// the offset of the tag in the byte array and the length of the tag in bytes. - /// The tag data follows. Each tag consists of an integer (4 bytes) tag type, a reserved integer - /// and the tag data, which varies depending on the tag. - /// - /// - /// - /// - /// 1.0 - /// - /// Bruce A. Kern - /// - [Serializable] - public class ICCTagTable : System.Collections.Hashtable - { - //UPGRADE_NOTE: Final was removed from the declaration of 'eol '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly System.String eol = System.Environment.NewLine; - //UPGRADE_NOTE: Final was removed from the declaration of 'offTagCount '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - //UPGRADE_NOTE: The initialization of 'offTagCount' was moved to static method 'icc.tags.ICCTagTable'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1005'" - private static readonly int offTagCount; - //UPGRADE_NOTE: Final was removed from the declaration of 'offTags '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - //UPGRADE_NOTE: The initialization of 'offTags' was moved to static method 'icc.tags.ICCTagTable'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1005'" - private static readonly int offTags; - - //UPGRADE_NOTE: Final was removed from the declaration of 'trios '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private System.Collections.ArrayList trios = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); - - private int tagCount; - - - private class Triplet - { - /// Tag identifier - internal int signature; - /// absolute offset of tag data - internal int offset; - /// length of tag data - internal int count; - /// size of an entry - //UPGRADE_NOTE: Final was removed from the declaration of 'size '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - //UPGRADE_NOTE: The initialization of 'size' was moved to static method 'icc.tags.ICCTagTable.Triplet'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1005'" - public static readonly int size; - - - internal Triplet(int signature, int offset, int count) - { - this.signature = signature; - this.offset = offset; - this.count = count; - } - static Triplet() - { - size = 3 * ICCProfile.int_size; - } - } - - /// Representation of a tag table - /// String - /// - //UPGRADE_NOTE: The equivalent of method 'java.util.Hashtable.toString' is not an override method. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1143'" - public override System.String ToString() - { - System.Text.StringBuilder rep = new System.Text.StringBuilder("[ICCTagTable containing " + tagCount + " tags:"); - System.Text.StringBuilder body = new System.Text.StringBuilder(" "); - System.Collections.IEnumerator keys = Keys.GetEnumerator(); - //UPGRADE_TODO: Method 'java.util.Enumeration.hasMoreElements' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationhasMoreElements'" - while (keys.MoveNext()) - { - //UPGRADE_TODO: Method 'java.util.Enumeration.nextElement' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationnextElement'" - System.Int32 key = (System.Int32)keys.Current; - ICCTag tag = (ICCTag)this[key]; - body.Append(eol).Append(tag.ToString()); - } - rep.Append(ColorSpace.indent(" ", body)); - return rep.Append("]").ToString(); - } - - - /// Factory method for creating a tag table from raw input. - /// array of unstructured data representing a tag - /// - /// ICCTagTable - /// - public static ICCTagTable createInstance(byte[] data) - { - ICCTagTable tags = new ICCTagTable(data); - return tags; - } - - - /// Ctor used by factory method. - /// raw tag data - /// - protected internal ICCTagTable(byte[] data) - { - tagCount = ICCProfile.getInt(data, offTagCount); - - int offset = offTags; - for (int i = 0; i < tagCount; ++i) - { - int signature = ICCProfile.getInt(data, offset); - int tagOffset = ICCProfile.getInt(data, offset + ICCProfile.int_size); - int length = ICCProfile.getInt(data, offset + 2 * ICCProfile.int_size); - trios.Add(new Triplet(signature, tagOffset, length)); - offset += 3 * ICCProfile.int_size; - } - - - System.Collections.IEnumerator Enum = trios.GetEnumerator(); - //UPGRADE_TODO: Method 'java.util.Enumeration.hasMoreElements' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationhasMoreElements'" - while (Enum.MoveNext()) - { - //UPGRADE_TODO: Method 'java.util.Enumeration.nextElement' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationnextElement'" - Triplet trio = (Triplet)Enum.Current; - ICCTag tag = ICCTag.createInstance(trio.signature, data, trio.offset, trio.count); - System.Object tempObject; - tempObject = this[(System.Int32)tag.signature]; - this[(System.Int32)tag.signature] = tag; - System.Object generatedAux2 = tempObject; - } - } - - - /// Output the table to a disk - /// RandomAccessFile which receives the table. - /// - /// - /// - //UPGRADE_TODO: Class 'java.io.RandomAccessFile' was converted to 'System.IO.FileStream' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioRandomAccessFile'" - public virtual void write(System.IO.FileStream raf) - { - - int ntags = trios.Count; - - int countOff = ICCProfileHeader.size; - int tagOff = countOff + ICCProfile.int_size; - int dataOff = tagOff + 3 * ntags * ICCProfile.int_size; - - raf.Seek(countOff, System.IO.SeekOrigin.Begin); - System.IO.BinaryWriter temp_BinaryWriter; - temp_BinaryWriter = new System.IO.BinaryWriter(raf); - temp_BinaryWriter.Write((System.Int32)ntags); - - int currentTagOff = tagOff; - int currentDataOff = dataOff; - - System.Collections.IEnumerator enum_Renamed = trios.GetEnumerator(); - //UPGRADE_TODO: Method 'java.util.Enumeration.hasMoreElements' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationhasMoreElements'" - while (enum_Renamed.MoveNext()) - { - //UPGRADE_TODO: Method 'java.util.Enumeration.nextElement' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationnextElement'" - Triplet trio = (Triplet)enum_Renamed.Current; - ICCTag tag = (ICCTag)this[(System.Int32)trio.signature]; - - raf.Seek(currentTagOff, System.IO.SeekOrigin.Begin); - System.IO.BinaryWriter temp_BinaryWriter2; - temp_BinaryWriter2 = new System.IO.BinaryWriter(raf); - temp_BinaryWriter2.Write((System.Int32)tag.signature); - System.IO.BinaryWriter temp_BinaryWriter3; - temp_BinaryWriter3 = new System.IO.BinaryWriter(raf); - temp_BinaryWriter3.Write((System.Int32)currentDataOff); - System.IO.BinaryWriter temp_BinaryWriter4; - temp_BinaryWriter4 = new System.IO.BinaryWriter(raf); - temp_BinaryWriter4.Write((System.Int32)tag.count); - currentTagOff += 3 * CSJ2K.Icc.Tags.ICCTagTable.Triplet.size; - - raf.Seek(currentDataOff, System.IO.SeekOrigin.Begin); - raf.Write(tag.data, tag.offset, tag.count); - currentDataOff += tag.count; - } - } - - /* end class ICCTagTable */ - static ICCTagTable() - { - offTagCount = ICCProfileHeader.size; - offTags = offTagCount + ICCProfile.int_size; - } - } -} \ No newline at end of file diff --git a/CSJ2K/Icc/Tags/ICCTextDescriptionType.cs b/CSJ2K/Icc/Tags/ICCTextDescriptionType.cs deleted file mode 100644 index 099c049c..00000000 --- a/CSJ2K/Icc/Tags/ICCTextDescriptionType.cs +++ /dev/null @@ -1,69 +0,0 @@ -/// ************************************************************************** -/// -/// $Id: ICCTextDescriptionType.java,v 1.1 2002/07/25 14:56:37 grosbois Exp $ -/// -/// Copyright Eastman Kodak Company, 343 State Street, Rochester, NY 14650 -/// $Date $ -/// *************************************************************************** -/// -using System; -namespace CSJ2K.Icc.Tags -{ - - /// A text based ICC tag - /// - /// - /// 1.0 - /// - /// Bruce A. Kern - /// - public class ICCTextDescriptionType : ICCTag - { - - /// Tag fields - //UPGRADE_NOTE: Final was removed from the declaration of 'type '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - new public int type; - /// Tag fields - //UPGRADE_NOTE: Final was removed from the declaration of 'reserved '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public int reserved; - /// Tag fields - //UPGRADE_NOTE: Final was removed from the declaration of 'size '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public int size; - /// Tag fields - //UPGRADE_NOTE: Final was removed from the declaration of 'ascii '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public byte[] ascii; - - /// Construct this tag from its constituant parts - /// tag id - /// - /// array of bytes - /// - /// to data in the data array - /// - /// of data in the data array - /// - protected internal ICCTextDescriptionType(int signature, byte[] data, int offset, int length) : base(signature, data, offset, length) - { - - type = ICCProfile.getInt(data, offset); - offset += ICCProfile.int_size; - - reserved = ICCProfile.getInt(data, offset); - offset += ICCProfile.int_size; - - size = ICCProfile.getInt(data, offset); - offset += ICCProfile.int_size; - - ascii = new byte[size - 1]; - Array.Copy(data, offset, ascii, 0, size - 1); - } - - /// Return the string rep of this tag. - public override System.String ToString() - { - return "[" + base.ToString() + " \"" + System.Text.ASCIIEncoding.ASCII.GetString(ascii) + "\"]"; - } - - /* end class ICCTextDescriptionType */ - } -} \ No newline at end of file diff --git a/CSJ2K/Icc/Tags/ICCTextType.cs b/CSJ2K/Icc/Tags/ICCTextType.cs deleted file mode 100644 index 2c11bc9c..00000000 --- a/CSJ2K/Icc/Tags/ICCTextType.cs +++ /dev/null @@ -1,63 +0,0 @@ -/// ************************************************************************** -/// -/// $Id: ICCTextType.java,v 1.1 2002/07/25 14:56:37 grosbois Exp $ -/// -/// Copyright Eastman Kodak Company, 343 State Street, Rochester, NY 14650 -/// $Date $ -/// *************************************************************************** -/// -using System; -namespace CSJ2K.Icc.Tags -{ - - /// A text based ICC tag - /// - /// - /// 1.0 - /// - /// Bruce A. Kern - /// - public class ICCTextType : ICCTag - { - - /// Tag fields - //UPGRADE_NOTE: Final was removed from the declaration of 'type '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - new public int type; - /// Tag fields - //UPGRADE_NOTE: Final was removed from the declaration of 'reserved '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public int reserved; - /// Tag fields - //UPGRADE_NOTE: Final was removed from the declaration of 'ascii '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public byte[] ascii; - - /// Construct this tag from its constituant parts - /// tag id - /// - /// array of bytes - /// - /// to data in the data array - /// - /// of data in the data array - /// - protected internal ICCTextType(int signature, byte[] data, int offset, int length) : base(signature, data, offset, length) - { - type = ICCProfile.getInt(data, offset); - offset += ICCProfile.int_size; - reserved = ICCProfile.getInt(data, offset); - offset += ICCProfile.int_size; - int size = 0; - while (data[offset + size] != 0) - ++size; - ascii = new byte[size]; - Array.Copy(data, offset, ascii, 0, size); - } - - /// Return the string rep of this tag. - public override System.String ToString() - { - return "[" + base.ToString() + " \"" + System.Text.ASCIIEncoding.ASCII.GetString(ascii, 0, ascii.Length) + "\"]"; - } - - /* end class ICCTextType */ - } -} \ No newline at end of file diff --git a/CSJ2K/Icc/Tags/ICCViewType.cs b/CSJ2K/Icc/Tags/ICCViewType.cs deleted file mode 100644 index 87925d8f..00000000 --- a/CSJ2K/Icc/Tags/ICCViewType.cs +++ /dev/null @@ -1,28 +0,0 @@ -using CSJ2K.Icc.Types; - -namespace CSJ2K.Icc.Tags -{ - public class ICCViewType : ICCTag - { - new public int type; - public int reserved; - public XYZNumber CIEilluminant; - public XYZNumber CIEsurround; - public int illuminant; - - /// Construct this tag from its constituant parts - /// tag id - /// array of bytes - /// to data in the data array - /// of data in the data array - protected internal ICCViewType(int signature, byte[] data, int offset, int length) - : base(signature, data, offset, offset + 2 * ICCProfile.int_size) - { - type = ICCProfile.getInt(data, offset); - reserved = ICCProfile.getInt(data, offset + ICCProfile.int_size); - CIEilluminant = ICCProfile.getXYZNumber(data, offset + ICCProfile.int_size); - CIEsurround = ICCProfile.getXYZNumber(data, offset + (ICCProfile.int_size * 3)); - illuminant = ICCProfile.getInt(data, offset + (ICCProfile.int_size * 3)); - } - } -} \ No newline at end of file diff --git a/CSJ2K/Icc/Tags/ICCXYZType.cs b/CSJ2K/Icc/Tags/ICCXYZType.cs deleted file mode 100644 index 242ce458..00000000 --- a/CSJ2K/Icc/Tags/ICCXYZType.cs +++ /dev/null @@ -1,90 +0,0 @@ -/// ************************************************************************** -/// -/// $Id: ICCXYZType.java,v 1.1 2002/07/25 14:56:37 grosbois Exp $ -/// -/// Copyright Eastman Kodak Company, 343 State Street, Rochester, NY 14650 -/// $Date $ -/// *************************************************************************** -/// -namespace CSJ2K.Icc.Tags -{ - - /// A tag containing a triplet. - /// - /// - /// - /// - /// - /// - /// 1.0 - /// - /// Bruce A. Kern - /// - public class ICCXYZType : ICCTag - { - - /// x component - //UPGRADE_NOTE: Final was removed from the declaration of 'x '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public long x; - /// y component - //UPGRADE_NOTE: Final was removed from the declaration of 'y '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public long y; - /// z component - //UPGRADE_NOTE: Final was removed from the declaration of 'z '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public long z; - - /// Normalization utility - public static long DoubleToXYZ(double x) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - return (long)System.Math.Floor(x * 65536.0 + 0.5); - } - - /// Normalization utility - public static double XYZToDouble(long x) - { - return x / 65536.0; - } - - /// Construct this tag from its constituant parts - /// tag id - /// - /// array of bytes - /// - /// to data in the data array - /// - /// of data in the data array - /// - protected internal ICCXYZType(int signature, byte[] data, int offset, int length) : base(signature, data, offset, length) - { - x = ICCProfile.getInt(data, offset + 2 * ICCProfile.int_size); - y = ICCProfile.getInt(data, offset + 3 * ICCProfile.int_size); - z = ICCProfile.getInt(data, offset + 4 * ICCProfile.int_size); - } - - - /// Return the string rep of this tag. - public override System.String ToString() - { - return "[" + base.ToString() + "(" + x + ", " + y + ", " + z + ")]"; - } - - - /// Write to a file. - //UPGRADE_TODO: Class 'java.io.RandomAccessFile' was converted to 'System.IO.FileStream' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioRandomAccessFile'" - public virtual void write(System.IO.FileStream raf) - { - byte[] xb = ICCProfile.setLong(x); - byte[] yb = ICCProfile.setLong(y); - byte[] zb = ICCProfile.setLong(z); - - // CONVERSION PROBLEM? - raf.Write(xb, ICCProfile.int_size, 0); - raf.Write(yb, ICCProfile.int_size, 0); - raf.Write(zb, ICCProfile.int_size, 0); - } - - - /* end class ICCXYZType */ - } -} \ No newline at end of file diff --git a/CSJ2K/Icc/Tags/ICCXYZTypeReverse.cs b/CSJ2K/Icc/Tags/ICCXYZTypeReverse.cs deleted file mode 100644 index 03463fbf..00000000 --- a/CSJ2K/Icc/Tags/ICCXYZTypeReverse.cs +++ /dev/null @@ -1,61 +0,0 @@ -/// ************************************************************************** -/// -/// $Id: ICCXYZTypeReverse.java,v 1.1 2002/07/25 14:56:38 grosbois Exp $ -/// -/// Copyright Eastman Kodak Company, 343 State Street, Rochester, NY 14650 -/// $Date $ -/// *************************************************************************** -/// -namespace CSJ2K.Icc.Tags -{ - - /// A tag containing a triplet. - /// - /// - /// - /// - /// - /// - /// 1.0 - /// - /// Bruce A. Kern - /// - public class ICCXYZTypeReverse : ICCXYZType - { - - /// x component - //UPGRADE_NOTE: Final was removed from the declaration of 'x '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - new public long x; - /// y component - //UPGRADE_NOTE: Final was removed from the declaration of 'y '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - new public long y; - /// z component - //UPGRADE_NOTE: Final was removed from the declaration of 'z '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - new public long z; - - /// Construct this tag from its constituant parts - /// tag id - /// - /// array of bytes - /// - /// to data in the data array - /// - /// of data in the data array - /// - protected internal ICCXYZTypeReverse(int signature, byte[] data, int offset, int length) : base(signature, data, offset, length) - { - z = ICCProfile.getInt(data, offset + 2 * ICCProfile.int_size); - y = ICCProfile.getInt(data, offset + 3 * ICCProfile.int_size); - x = ICCProfile.getInt(data, offset + 4 * ICCProfile.int_size); - } - - - /// Return the string rep of this tag. - public override System.String ToString() - { - return "[" + base.ToString() + "(" + x + ", " + y + ", " + z + ")]"; - } - - /* end class ICCXYZTypeReverse */ - } -} \ No newline at end of file diff --git a/CSJ2K/Icc/Types/ICCDateTime.cs b/CSJ2K/Icc/Types/ICCDateTime.cs deleted file mode 100644 index 4bc1c6c6..00000000 --- a/CSJ2K/Icc/Types/ICCDateTime.cs +++ /dev/null @@ -1,87 +0,0 @@ -/// ************************************************************************** -/// -/// $Id: ICCDateTime.java,v 1.1 2002/07/25 14:56:31 grosbois Exp $ -/// -/// Copyright Eastman Kodak Company, 343 State Street, Rochester, NY 14650 -/// $Date $ -/// *************************************************************************** -/// -namespace CSJ2K.Icc.Types -{ - - /// Date Time format for tags - /// - /// - /// 1.0 - /// - /// Bruce A. Kern - /// - public class ICCDateTime - { - //UPGRADE_NOTE: Final was removed from the declaration of 'size '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - //UPGRADE_NOTE: The initialization of 'size' was moved to static method 'icc.types.ICCDateTime'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1005'" - public static readonly int size; - - /// Year datum. - public short wYear; - /// Month datum. - // Number of the actual year (i.e. 1994) - public short wMonth; - /// Day datum. - // Number of the month (1-12) - public short wDay; - /// Hour datum. - // Number of the day - public short wHours; - /// Minute datum. - // Number of hours (0-23) - public short wMinutes; - /// Second datum. - // Number of minutes (0-59) - public short wSeconds; // Number of seconds (0-59) - - /// Construct an ICCDateTime from parts - public ICCDateTime(short year, short month, short day, short hour, short minute, short second) - { - wYear = year; wMonth = month; wDay = day; - wHours = hour; wMinutes = minute; wSeconds = second; - } - - /// Write an ICCDateTime to a file. - //UPGRADE_TODO: Class 'java.io.RandomAccessFile' was converted to 'System.IO.FileStream' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioRandomAccessFile'" - public virtual void write(System.IO.FileStream raf) - { - System.IO.BinaryWriter temp_BinaryWriter; - temp_BinaryWriter = new System.IO.BinaryWriter(raf); - temp_BinaryWriter.Write((System.Int16)wYear); - System.IO.BinaryWriter temp_BinaryWriter2; - temp_BinaryWriter2 = new System.IO.BinaryWriter(raf); - temp_BinaryWriter2.Write((System.Int16)wMonth); - System.IO.BinaryWriter temp_BinaryWriter3; - temp_BinaryWriter3 = new System.IO.BinaryWriter(raf); - temp_BinaryWriter3.Write((System.Int16)wDay); - System.IO.BinaryWriter temp_BinaryWriter4; - temp_BinaryWriter4 = new System.IO.BinaryWriter(raf); - temp_BinaryWriter4.Write((System.Int16)wHours); - System.IO.BinaryWriter temp_BinaryWriter5; - temp_BinaryWriter5 = new System.IO.BinaryWriter(raf); - temp_BinaryWriter5.Write((System.Int16)wMinutes); - System.IO.BinaryWriter temp_BinaryWriter6; - temp_BinaryWriter6 = new System.IO.BinaryWriter(raf); - temp_BinaryWriter6.Write((System.Int16)wSeconds); - } - - /// Return a ICCDateTime representation. - public override System.String ToString() - { - //System.String rep = ""; - return System.Convert.ToString(wYear) + "/" + System.Convert.ToString(wMonth) + "/" + System.Convert.ToString(wDay) + " " + System.Convert.ToString(wHours) + ":" + System.Convert.ToString(wMinutes) + ":" + System.Convert.ToString(wSeconds); - } - - /* end class ICCDateTime*/ - static ICCDateTime() - { - size = 6 * ICCProfile.short_size; - } - } -} \ No newline at end of file diff --git a/CSJ2K/Icc/Types/ICCProfileHeader.cs b/CSJ2K/Icc/Types/ICCProfileHeader.cs deleted file mode 100644 index c44f31e2..00000000 --- a/CSJ2K/Icc/Types/ICCProfileHeader.cs +++ /dev/null @@ -1,230 +0,0 @@ -/// ************************************************************************** -/// -/// $Id: ICCProfileHeader.java,v 1.1 2002/07/25 14:56:31 grosbois Exp $ -/// -/// Copyright Eastman Kodak Company, 343 State Street, Rochester, NY 14650 -/// $Date $ -/// *************************************************************************** -/// -namespace CSJ2K.Icc.Types -{ - - - /// An ICC profile contains a 128-byte header followed by a variable - /// number of tags contained in a tag table. This class models the header - /// portion of the profile. Most fields in the header are ints. Some, such - /// as data and version are aggregations of ints. This class provides an api to - /// those fields as well as the definition of standard constants which are used - /// in the header. - /// - /// - /// - /// - /// 1.0 - /// - /// Bruce A. Kern - /// - - public class ICCProfileHeader - { - //UPGRADE_NOTE: Final was removed from the declaration of 'eol '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly System.String eol = System.Environment.NewLine; - - /// ICCProfile header byte array. - //private byte[] header = null; - - - /* Define the set of standard signature and type values. Only - * those codes required for Restricted ICC use are defined here. - */ - /// Profile header signature - private static int kdwProfileSignature = ICCProfile.getInt(System.Text.ASCIIEncoding.ASCII.GetBytes("acsp"), 0); - - /// Profile header signature - public static int kdwProfileSigReverse = ICCProfile.getInt(System.Text.ASCIIEncoding.ASCII.GetBytes("psca"), 0); - - private const System.String kdwInputProfile = "scnr"; - private const System.String kdwDisplayProfile = "mntr"; - private const System.String kdwRGBData = "RGB "; - private const System.String kdwGrayData = "GRAY"; - private const System.String kdwXYZData = "XYZ "; - private const System.String kdwGrayTRCTag = "kTRC"; - private const System.String kdwRedColorantTag = "rXYZ"; - private const System.String kdwGreenColorantTag = "gXYZ"; - private const System.String kdwBlueColorantTag = "bXYZ"; - private const System.String kdwRedTRCTag = "rTRC"; - private const System.String kdwGreenTRCTag = "gTRC"; - private const System.String kdwBlueTRCTag = "bTRC"; - - /* Offsets into ICCProfile header byte array. */ - - private static int offProfileSize = 0; - private static int offCMMTypeSignature = offProfileSize + ICCProfile.int_size; - private static int offProfileVersion = offCMMTypeSignature + ICCProfile.int_size; - private static int offProfileClass = offProfileVersion + ICCProfileVersion.size; - private static int offColorSpaceType = offProfileClass + ICCProfile.int_size; - private static int offPCSType = offColorSpaceType + ICCProfile.int_size; - private static int offDateTime = offPCSType + ICCProfile.int_size; - private static int offProfileSignature = offDateTime + ICCDateTime.size; - private static int offPlatformSignature = offProfileSignature + ICCProfile.int_size; - private static int offCMMFlags = offPlatformSignature + ICCProfile.int_size; - private static int offDeviceManufacturer = offCMMFlags + ICCProfile.int_size; - private static int offDeviceModel = offDeviceManufacturer + ICCProfile.int_size; - private static int offDeviceAttributes1 = offDeviceModel + ICCProfile.int_size; - private static int offDeviceAttributesReserved = offDeviceAttributes1 + ICCProfile.int_size; - private static int offRenderingIntent = offDeviceAttributesReserved + ICCProfile.int_size; - private static int offPCSIlluminant = offRenderingIntent + ICCProfile.int_size; - private static int offCreatorSig = offPCSIlluminant + XYZNumber.size; - private static int offReserved = offCreatorSig + ICCProfile.int_size; - /// Size of the header - public static int size = offReserved + 44 * ICCProfile.byte_size; - - /// Header field - /* Header fields mapped to primitive types. */ - public int dwProfileSize; - /// Header field - // Size of the entire profile in bytes - public int dwCMMTypeSignature; - /// Header field - // The preferred CMM for this profile - public int dwProfileClass; - /// Header field - // Profile/Device class signature - public int dwColorSpaceType; - /// Header field - // Colorspace signature - public int dwPCSType; - /// Header field - // PCS type signature - public int dwProfileSignature; - /// Header field - // Must be 'acsp' (0x61637370) - public int dwPlatformSignature; - /// Header field - // Primary platform for which this profile was created - public int dwCMMFlags; - /// Header field - // Flags to indicate various hints for the CMM - public int dwDeviceManufacturer; - /// Header field - // Signature of device manufacturer - public int dwDeviceModel; - /// Header field - // Signature of device model - public int dwDeviceAttributes1; - /// Header field - // Attributes of the device - public int dwDeviceAttributesReserved; - /// Header field - public int dwRenderingIntent; - /// Header field - // Desired rendering intent for this profile - public int dwCreatorSig; - /// Header field - // Profile creator signature - - public byte[] reserved = new byte[44]; // - - /// Header field - /* Header fields mapped to ggregate types. */ - public ICCProfileVersion profileVersion; - /// Header field - // Version of the profile format on which - public ICCDateTime dateTime; - /// Header field - // Date and time of profile creation// this profile is based - public XYZNumber PCSIlluminant; // Illuminant used for this profile - - - /// Construct and empty header - public ICCProfileHeader() - { - } - - /// Construct a header from a complete ICCProfile - /// [] -- holds ICCProfile contents - /// - public ICCProfileHeader(byte[] data) - { - - dwProfileSize = ICCProfile.getInt(data, offProfileSize); - dwCMMTypeSignature = ICCProfile.getInt(data, offCMMTypeSignature); - dwProfileClass = ICCProfile.getInt(data, offProfileClass); - dwColorSpaceType = ICCProfile.getInt(data, offColorSpaceType); - dwPCSType = ICCProfile.getInt(data, offPCSType); - dwProfileSignature = ICCProfile.getInt(data, offProfileSignature); - dwPlatformSignature = ICCProfile.getInt(data, offPlatformSignature); - dwCMMFlags = ICCProfile.getInt(data, offCMMFlags); - dwDeviceManufacturer = ICCProfile.getInt(data, offDeviceManufacturer); - dwDeviceModel = ICCProfile.getInt(data, offDeviceModel); - dwDeviceAttributes1 = ICCProfile.getInt(data, offDeviceAttributesReserved); - dwDeviceAttributesReserved = ICCProfile.getInt(data, offDeviceAttributesReserved); - dwRenderingIntent = ICCProfile.getInt(data, offRenderingIntent); - dwCreatorSig = ICCProfile.getInt(data, offCreatorSig); - profileVersion = ICCProfile.getICCProfileVersion(data, offProfileVersion); - dateTime = ICCProfile.getICCDateTime(data, offDateTime); - PCSIlluminant = ICCProfile.getXYZNumber(data, offPCSIlluminant); - - for (int i = 0; i < reserved.Length; ++i) - reserved[i] = data[offReserved + i]; - } - - /// Write out this ICCProfile header to a RandomAccessFile - /// sink for data - /// - /// - /// - //UPGRADE_TODO: Class 'java.io.RandomAccessFile' was converted to 'System.IO.FileStream' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioRandomAccessFile'" - public virtual void write(System.IO.FileStream raf) - { - - raf.Seek(offProfileSize, System.IO.SeekOrigin.Begin); raf.WriteByte((System.Byte)dwProfileSize); - raf.Seek(offCMMTypeSignature, System.IO.SeekOrigin.Begin); raf.WriteByte((System.Byte)dwCMMTypeSignature); - raf.Seek(offProfileVersion, System.IO.SeekOrigin.Begin); profileVersion.write(raf); - raf.Seek(offProfileClass, System.IO.SeekOrigin.Begin); raf.WriteByte((System.Byte)dwProfileClass); - raf.Seek(offColorSpaceType, System.IO.SeekOrigin.Begin); raf.WriteByte((System.Byte)dwColorSpaceType); - raf.Seek(offPCSType, System.IO.SeekOrigin.Begin); raf.WriteByte((System.Byte)dwPCSType); - raf.Seek(offDateTime, System.IO.SeekOrigin.Begin); dateTime.write(raf); - raf.Seek(offProfileSignature, System.IO.SeekOrigin.Begin); raf.WriteByte((System.Byte)dwProfileSignature); - raf.Seek(offPlatformSignature, System.IO.SeekOrigin.Begin); raf.WriteByte((System.Byte)dwPlatformSignature); - raf.Seek(offCMMFlags, System.IO.SeekOrigin.Begin); raf.WriteByte((System.Byte)dwCMMFlags); - raf.Seek(offDeviceManufacturer, System.IO.SeekOrigin.Begin); raf.WriteByte((System.Byte)dwDeviceManufacturer); - raf.Seek(offDeviceModel, System.IO.SeekOrigin.Begin); raf.WriteByte((System.Byte)dwDeviceModel); - raf.Seek(offDeviceAttributes1, System.IO.SeekOrigin.Begin); raf.WriteByte((System.Byte)dwDeviceAttributes1); - raf.Seek(offDeviceAttributesReserved, System.IO.SeekOrigin.Begin); raf.WriteByte((System.Byte)dwDeviceAttributesReserved); - raf.Seek(offRenderingIntent, System.IO.SeekOrigin.Begin); raf.WriteByte((System.Byte)dwRenderingIntent); - raf.Seek(offPCSIlluminant, System.IO.SeekOrigin.Begin); PCSIlluminant.write(raf); - raf.Seek(offCreatorSig, System.IO.SeekOrigin.Begin); raf.WriteByte((System.Byte)dwCreatorSig); - raf.Seek(offReserved, System.IO.SeekOrigin.Begin); - raf.Write(reserved, 0, reserved.Length); - //SupportClass.RandomAccessFileSupport.WriteRandomFile(reserved, raf); - } - - - /// String representation of class - public override System.String ToString() - { - System.Text.StringBuilder rep = new System.Text.StringBuilder("[ICCProfileHeader: "); - - rep.Append(eol + " ProfileSize: " + System.Convert.ToString(dwProfileSize, 16)); - rep.Append(eol + " CMMTypeSignature: " + System.Convert.ToString(dwCMMTypeSignature, 16)); - rep.Append(eol + " ProfileClass: " + System.Convert.ToString(dwProfileClass, 16)); - rep.Append(eol + " ColorSpaceType: " + System.Convert.ToString(dwColorSpaceType, 16)); - rep.Append(eol + " dwPCSType: " + System.Convert.ToString(dwPCSType, 16)); - rep.Append(eol + " dwProfileSignature: " + System.Convert.ToString(dwProfileSignature, 16)); - rep.Append(eol + " dwPlatformSignature: " + System.Convert.ToString(dwPlatformSignature, 16)); - rep.Append(eol + " dwCMMFlags: " + System.Convert.ToString(dwCMMFlags, 16)); - rep.Append(eol + "dwDeviceManufacturer: " + System.Convert.ToString(dwDeviceManufacturer, 16)); - rep.Append(eol + " dwDeviceModel: " + System.Convert.ToString(dwDeviceModel, 16)); - rep.Append(eol + " dwDeviceAttributes1: " + System.Convert.ToString(dwDeviceAttributes1, 16)); - rep.Append(eol + " dwRenderingIntent: " + System.Convert.ToString(dwRenderingIntent, 16)); - rep.Append(eol + " dwCreatorSig: " + System.Convert.ToString(dwCreatorSig, 16)); - rep.Append(eol + " profileVersion: " + profileVersion); - rep.Append(eol + " dateTime: " + dateTime); - rep.Append(eol + " PCSIlluminant: " + PCSIlluminant); - return rep.Append("]").ToString(); - } - - /* end class ICCProfileHeader */ - } -} \ No newline at end of file diff --git a/CSJ2K/Icc/Types/ICCProfileVersion.cs b/CSJ2K/Icc/Types/ICCProfileVersion.cs deleted file mode 100644 index c1df9347..00000000 --- a/CSJ2K/Icc/Types/ICCProfileVersion.cs +++ /dev/null @@ -1,66 +0,0 @@ -/// ************************************************************************** -/// -/// $Id: ICCProfileVersion.java,v 1.1 2002/07/25 14:56:31 grosbois Exp $ -/// -/// Copyright Eastman Kodak Company, 343 State Street, Rochester, NY 14650 -/// $Date $ -/// *************************************************************************** -/// -namespace CSJ2K.Icc.Types -{ - - /// This class describes the ICCProfile Version as contained in - /// the header of the ICC Profile. - /// - /// - /// - /// - /// - /// - /// 1.0 - /// - /// Bruce A. Kern - /// - public class ICCProfileVersion - { - /// Field size - //UPGRADE_NOTE: Final was removed from the declaration of 'size '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - //UPGRADE_NOTE: The initialization of 'size' was moved to static method 'icc.types.ICCProfileVersion'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1005'" - public static readonly int size; - - /// Major revision number in binary coded decimal - public byte uMajor; - /// Minor revision in high nibble, bug fix revision - /// in low nibble, both in binary coded decimal - /// - public byte uMinor; - - private byte reserved1; - private byte reserved2; - - /// Construct from constituent parts. - public ICCProfileVersion(byte major, byte minor, byte res1, byte res2) - { - uMajor = major; uMinor = minor; reserved1 = res1; reserved2 = res2; - } - - /// Construct from file content. - //UPGRADE_TODO: Class 'java.io.RandomAccessFile' was converted to 'System.IO.FileStream' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioRandomAccessFile'" - public virtual void write(System.IO.FileStream raf) - { - raf.WriteByte(uMajor); raf.WriteByte(uMinor); raf.WriteByte(reserved1); raf.WriteByte(reserved2); - } - - /// String representation of class instance. - public override System.String ToString() - { - return "Version " + uMajor + "." + uMinor; - } - - /* end class ICCProfileVersion */ - static ICCProfileVersion() - { - size = 4 * ICCProfile.byte_size; - } - } -} \ No newline at end of file diff --git a/CSJ2K/Icc/Types/XYZNumber.cs b/CSJ2K/Icc/Types/XYZNumber.cs deleted file mode 100644 index 17e91501..00000000 --- a/CSJ2K/Icc/Types/XYZNumber.cs +++ /dev/null @@ -1,84 +0,0 @@ -/// ************************************************************************** -/// -/// $Id: XYZNumber.java,v 1.1 2002/07/25 14:56:31 grosbois Exp $ -/// -/// Copyright Eastman Kodak Company, 343 State Street, Rochester, NY 14650 -/// $Date $ -/// *************************************************************************** -/// -namespace CSJ2K.Icc.Types -{ - - /// A convientient representation for the contents of the - /// ICCXYZTypeTag class. - /// - /// - /// - /// - /// 1.0 - /// - /// Bruce A. Kern - /// - public class XYZNumber - { - //UPGRADE_NOTE: Final was removed from the declaration of 'size '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - //UPGRADE_NOTE: The initialization of 'size' was moved to static method 'icc.types.XYZNumber'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1005'" - public static readonly int size; - - /// x value - public int dwX; - /// y value - // X tristimulus value - public int dwY; - /// z value - // Y tristimulus value - public int dwZ; // Z tristimulus value - - /// Construct from constituent parts. - public XYZNumber(int x, int y, int z) - { - dwX = x; dwY = y; dwZ = z; - } - - /// Normalization utility - public static int DoubleToXYZ(double x) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - return (int)System.Math.Floor(x * 65536.0 + 0.5); - } - - /// Normalization utility - public static double XYZToDouble(int x) - { - return (double)x / 65536.0; - } - - /// Write to a file - //UPGRADE_TODO: Class 'java.io.RandomAccessFile' was converted to 'System.IO.FileStream' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioRandomAccessFile'" - public virtual void write(System.IO.FileStream raf) - { - System.IO.BinaryWriter temp_BinaryWriter; - temp_BinaryWriter = new System.IO.BinaryWriter(raf); - temp_BinaryWriter.Write((System.Int32)dwX); - System.IO.BinaryWriter temp_BinaryWriter2; - temp_BinaryWriter2 = new System.IO.BinaryWriter(raf); - temp_BinaryWriter2.Write((System.Int32)dwY); - System.IO.BinaryWriter temp_BinaryWriter3; - temp_BinaryWriter3 = new System.IO.BinaryWriter(raf); - temp_BinaryWriter3.Write((System.Int32)dwZ); - } - - /// String representation of class instance. - public override System.String ToString() - { - return "[" + dwX + ", " + dwY + ", " + dwZ + "]"; - } - - - /* end class XYZNumber */ - static XYZNumber() - { - size = 3 * ICCProfile.int_size; - } - } -} \ No newline at end of file diff --git a/CSJ2K/J2KEncoder.cs b/CSJ2K/J2KEncoder.cs deleted file mode 100644 index d47b69e1..00000000 --- a/CSJ2K/J2KEncoder.cs +++ /dev/null @@ -1,226 +0,0 @@ -#region Using Statements -using CSJ2K.j2k.codestream.writer; -using CSJ2K.j2k.encoder; -using CSJ2K.j2k.entropy.encoder; -using CSJ2K.j2k.image; -using CSJ2K.j2k.image.forwcomptransf; -using CSJ2K.j2k.image.input; -using CSJ2K.j2k.quantization.quantizer; -using CSJ2K.j2k.roi.encoder; -using CSJ2K.j2k.util; -using CSJ2K.j2k.wavelet.analysis; -using System; -using System.Collections.Generic; -using System.Drawing; -using System.IO; -#endregion - -namespace CSJ2K -{ - public static class J2KEncoder - { - #region Default Encoding Parameters - - private readonly static string[][] pinfo = { - new string[] { "debug", null, - "Print debugging messages when an error is encountered.","off"}, - new string[] { "disable_jp2_extension", "[on|off]", - "JJ2000 automatically adds .jp2 extension when using 'file_format'"+ - "option. This option disables it when on.", "off"}, - new string[] { "file_format", "[on|off]", - "Puts the JPEG 2000 codestream in a JP2 file format wrapper.","off"}, - new string[] { "pph_tile", "[on|off]", - "Packs the packet headers in the tile headers.","off"}, - new string[] { "pph_main", "[on|off]", - "Packs the packet headers in the main header.","off"}, - new string[] { "pfile", "", - "Loads the arguments from the specified file. Arguments that are "+ - "specified on the command line override the ones from the file.\n"+ - "The arguments file is a simple text file with one argument per "+ - "line of the following form:\n" + - " =\n"+ - "If the argument is of boolean type (i.e. its presence turns a "+ - "feature on), then the 'on' value turns it on, while the 'off' "+ - "value turns it off. The argument name does not include the '-' "+ - "or '+' character. Long lines can be broken into several lines "+ - "by terminating them with '\'. Lines starting with '#' are "+ - "considered as comments. This option is not recursive: any 'pfile' "+ - "argument appearing in the file is ignored.",null}, - new string[] { "tile_parts", "", - "This option specifies the maximum number of packets to have in "+ - "one tile-part. 0 means include all packets in first tile-part "+ - "of each tile","0"}, - new string[] { "tiles", " ", - "This option specifies the maximum tile dimensions to use. "+ - "If both dimensions are 0 then no tiling is used.","0 0"}, - new string[] { "ref", " ", - "Sets the origin of the image in the canvas system. It sets the "+ - "coordinate of the top-left corner of the image reference grid, "+ - "with respect to the canvas origin","0 0"}, - new string[] { "tref", " ", - "Sets the origin of the tile partitioning on the reference grid, "+ - "with respect to the canvas origin. The value of 'x' ('y') "+ - "specified can not be larger than the 'x' one specified in the ref "+ - "option.","0 0"}, - new string[] { "rate", "", - "This is the output bitrate of the codestream in bits per pixel."+ - " When equal to -1, no image information (beside quantization "+ - "effects) is discarded during compression.\n"+ - "Note: In the case where '-file_format' option is used, the "+ - "resulting file may have a larger bitrate.","-1"}, - new string[] { "lossless", "[on|off]", - "Specifies a lossless compression for the encoder. This options"+ - " is equivalent to use reversible quantization ('-Qtype "+ - "reversible')"+ - " and 5x3 wavelet filters pair ('-Ffilters w5x3'). Note that "+ - "this option cannot be used with '-rate'. When this option is "+ - "off, the quantization type and the filters pair is defined by "+ - "'-Qtype' and '-Ffilters' respectively.","off"}, - new string[] { "i", " [, [, ... ]]", - "Mandatory argument. This option specifies the name of the input "+ - "image files. If several image files are provided, they have to be"+ - " separated by commas in the command line. Supported formats are "+ - "PGM (raw), PPM (raw) and PGX, "+ - "which is a simple extension of the PGM file format for single "+ - "component data supporting arbitrary bitdepths. If the extension "+ - "is '.pgm', PGM-raw file format is assumed, if the extension is "+ - "'.ppm', PPM-raw file format is assumed, otherwise PGX file "+ - "format is assumed. PGM and PPM files are assumed to be 8 bits "+ - "deep. A multi-component image can be specified by either "+ - "specifying several PPM and/or PGX files, or by specifying one "+ - "PPM file.",null}, - new string[] { "o", "", - "Mandatory argument. This option specifies the name of the output "+ - "file to which the codestream will be written.",null}, - new string[] { "verbose", null, - "Prints information about the obtained bit stream.","on"}, - new string[] { "v", "[on|off]", - "Prints version and copyright information.","off"}, - new string[] { "u", "[on|off]", - "Prints usage information. "+ - "If specified all other arguments (except 'v') are ignored","off"}, - }; - - #endregion Default Encoding Parameters - - private readonly static ParameterList pl; - - static J2KEncoder() - { - pl = new ParameterList(); - string[][] parameters = GetAllParameters(); - for (int i = 0; i < parameters.Length; i++) - { - string[] param = parameters[i]; - pl.Set(param[0], param[3]); - } - - // Custom parameters - pl.Set("Aptype", "layer"); - pl.Set("Qguard_bits", "1"); - pl.Set("Alayers", "sl"); - //pl.Set("lossless", "on"); - } - - public static byte[] EncodeJPEG(Image jpgImage) - { - Tiler imgtiler; - ForwCompTransf fctransf; - ImgDataConverter converter; - EncoderSpecs encSpec; - ForwardWT dwt; - Quantizer quant; - ROIScaler rois; - EntropyCoder ecoder; - PostCompRateAllocator ralloc; - HeaderEncoder headenc; - CodestreamWriter bwriter; - - float rate = Single.MaxValue; - - ImgReaderGDI imgsrc = new ImgReaderGDI(jpgImage); - - imgtiler = new Tiler(imgsrc, 0, 0, 0, 0, jpgImage.Width, jpgImage.Height); - int ntiles = imgtiler.getNumTiles(); - - encSpec = new EncoderSpecs(ntiles, 3, imgsrc, pl); - - fctransf = new ForwCompTransf(imgtiler, encSpec); - converter = new ImgDataConverter(fctransf); - dwt = ForwardWT.createInstance(converter, pl, encSpec); - quant = Quantizer.createInstance(dwt, encSpec); - rois = ROIScaler.createInstance(quant, pl, encSpec); - ecoder = EntropyCoder.createInstance(rois, pl, encSpec.cblks, - encSpec.pss, encSpec.bms, - encSpec.mqrs, encSpec.rts, - encSpec.css, encSpec.sss, - encSpec.lcs, encSpec.tts); - - using (MemoryStream stream = new MemoryStream()) - { - bwriter = new FileCodestreamWriter(stream, Int32.MaxValue); - ralloc = PostCompRateAllocator.createInstance(ecoder, pl, rate, bwriter, encSpec); - - headenc = new HeaderEncoder(imgsrc, new bool[3], dwt, imgtiler, encSpec, rois, ralloc, pl); - ralloc.HeaderEncoder = headenc; - headenc.encodeMainHeader(); - ralloc.initialize(); - headenc.reset(); - headenc.encodeMainHeader(); - bwriter.commitBitstreamHeader(headenc); - - ralloc.runAndWrite(); - bwriter.close(); - - return stream.ToArray(); - } - } - - private static string[][] GetAllParameters() - { - List parameters = new List(); - - string[][] str = pinfo; - for (int i = 0; i < str.Length; i++) - parameters.Add(str[i]); - - str = ForwCompTransf.ParameterInfo; - for (int i = 0; i < str.Length; i++) - parameters.Add(str[i]); - - str = AnWTFilter.ParameterInfo; - for (int i = 0; i < str.Length; i++) - parameters.Add(str[i]); - - str = ForwardWT.ParameterInfo; - for (int i = 0; i < str.Length; i++) - parameters.Add(str[i]); - - str = Quantizer.ParameterInfo; - for (int i = 0; i < str.Length; i++) - parameters.Add(str[i]); - - str = ROIScaler.ParameterInfo; - for (int i = 0; i < str.Length; i++) - parameters.Add(str[i]); - - str = EntropyCoder.ParameterInfo; - for (int i = 0; i < str.Length; i++) - parameters.Add(str[i]); - - str = HeaderEncoder.ParameterInfo; - for (int i = 0; i < str.Length; i++) - parameters.Add(str[i]); - - str = PostCompRateAllocator.ParameterInfo; - for (int i = 0; i < str.Length; i++) - parameters.Add(str[i]); - - str = PktEncoder.ParameterInfo; - for (int i = 0; i < str.Length; i++) - parameters.Add(str[i]); - - return parameters.ToArray(); - } - } -} diff --git a/CSJ2K/J2kImage.cs b/CSJ2K/J2kImage.cs deleted file mode 100644 index d0cbd87a..00000000 --- a/CSJ2K/J2kImage.cs +++ /dev/null @@ -1,637 +0,0 @@ -#region Using Statements -using CSJ2K.Color; -using CSJ2K.Icc; -using CSJ2K.j2k.codestream; -using CSJ2K.j2k.codestream.reader; -using CSJ2K.j2k.decoder; -using CSJ2K.j2k.entropy.decoder; -using CSJ2K.j2k.fileformat.reader; -using CSJ2K.j2k.image; -using CSJ2K.j2k.image.invcomptransf; -using CSJ2K.j2k.io; -using CSJ2K.j2k.quantization.dequantizer; -using CSJ2K.j2k.roi; -using CSJ2K.j2k.util; -using CSJ2K.j2k.wavelet.synthesis; -using System; -using System.Collections.Generic; -using System.Drawing; -using System.Drawing.Imaging; -using System.IO; -#endregion - -namespace CSJ2K -{ - public class J2kImage - { - #region Static Decoder Methods - public static Image FromFile(string filename) - { - Stream stream = new FileStream(filename, FileMode.Open, FileAccess.Read); - Image img = FromStream(stream); - stream.Close(); - return (img); - } - - public static Image FromBytes(byte[] j2kdata) - { - return FromStream(new MemoryStream(j2kdata)); - } - - public static Image FromStream(Stream stream) - { - RandomAccessIO in_stream = new ISRandomAccessIO(stream); - - // Initialize default parameters - ParameterList defpl = GetDefaultParameterList(decoder_pinfo); - - // Create parameter list using defaults - ParameterList pl = new ParameterList(defpl); - - // **** File Format **** - // If the codestream is wrapped in the jp2 fileformat, Read the - // file format wrapper - FileFormatReader ff = new FileFormatReader(in_stream); - ff.readFileFormat(); - if (ff.JP2FFUsed) - { - in_stream.seek(ff.FirstCodeStreamPos); - } - - // +----------------------------+ - // | Instantiate decoding chain | - // +----------------------------+ - - // **** Header decoder **** - // Instantiate header decoder and read main header - HeaderInfo hi = new HeaderInfo(); - HeaderDecoder hd; - try - { - hd = new HeaderDecoder(in_stream, pl, hi); - } - catch (EndOfStreamException e) - { - throw new ApplicationException("Codestream too short or bad header, unable to decode.", e); - } - - int nCompCod = hd.NumComps; - int nTiles = hi.sizValue.NumTiles; - DecoderSpecs decSpec = hd.DecoderSpecs; - - // Get demixed bitdepths - int[] depth = new int[nCompCod]; - for (int i = 0; i < nCompCod; i++) - { - depth[i] = hd.getOriginalBitDepth(i); - } - - // **** Bit stream reader **** - BitstreamReaderAgent breader; - try - { - breader = BitstreamReaderAgent. - createInstance(in_stream, hd, pl, decSpec, - false, hi); - } - catch (IOException e) - { - throw new ApplicationException("Error while reading bit stream header or parsing packets.", e); - } - catch (ArgumentException e) - { - throw new ApplicationException("Cannot instantiate bit stream reader.", e); - } - - // **** Entropy decoder **** - EntropyDecoder entdec; - try - { - entdec = hd.createEntropyDecoder(breader, pl); - } - catch (ArgumentException e) - { - throw new ApplicationException("Cannot instantiate entropy decoder.", e); - } - - // **** ROI de-scaler **** - ROIDeScaler roids; - try - { - roids = hd.createROIDeScaler(entdec, pl, decSpec); - } - catch (ArgumentException e) - { - throw new ApplicationException("Cannot instantiate roi de-scaler.", e); - } - - // **** Dequantizer **** - Dequantizer deq; - try - { - deq = hd.createDequantizer(roids, depth, decSpec); - } - catch (ArgumentException e) - { - throw new ApplicationException("Cannot instantiate dequantizer.", e); - } - - // **** Inverse wavelet transform *** - InverseWT invWT; - try - { - // full page inverse wavelet transform - invWT = InverseWT.createInstance(deq, decSpec); - } - catch (ArgumentException e) - { - throw new ApplicationException("Cannot instantiate inverse wavelet transform.", e); - } - - int res = breader.ImgRes; - invWT.ImgResLevel = res; - - // **** Data converter **** (after inverse transform module) - ImgDataConverter converter = new ImgDataConverter(invWT, 0); - - // **** Inverse component transformation **** - InvCompTransf ictransf = new InvCompTransf(converter, decSpec, depth, pl); - - // **** Color space mapping **** - BlkImgDataSrc color; - if (ff.JP2FFUsed && pl.getParameter("nocolorspace").Equals("off")) - { - try - { - ColorSpace csMap = new ColorSpace(in_stream, hd, pl); - BlkImgDataSrc channels = hd.createChannelDefinitionMapper(ictransf, csMap); - BlkImgDataSrc resampled = hd.createResampler(channels, csMap); - BlkImgDataSrc palettized = hd.createPalettizedColorSpaceMapper(resampled, csMap); - color = hd.createColorSpaceMapper(palettized, csMap); - } - catch (ArgumentException e) - { - throw new ApplicationException("Could not instantiate ICC profiler.", e); - } - catch (ColorSpaceException e) - { - throw new ApplicationException("Error processing ColorSpace information.", e); - } - } - else - { // Skip colorspace mapping - color = ictransf; - } - - // This is the last image in the decoding chain and should be - // assigned by the last transformation: - BlkImgDataSrc decodedImage = color; - if (color == null) - { - decodedImage = ictransf; - } - int numComps = decodedImage.NumComps; - int bytesPerPixel = numComps; // Assuming 8-bit components - - // **** Copy to Bitmap **** - PixelFormat pixelFormat; - switch (numComps) - { - case 1: - pixelFormat = PixelFormat.Format24bppRgb; break; - case 3: - pixelFormat = PixelFormat.Format24bppRgb; break; - case 4: - case 5: - pixelFormat = PixelFormat.Format32bppArgb; break; - default: - throw new ApplicationException("Unsupported PixelFormat. " + numComps + " components."); - } - - Bitmap dst = new Bitmap(decodedImage.ImgWidth, decodedImage.ImgHeight, pixelFormat); - - Coord numTiles = decodedImage.getNumTiles(null); - - int tIdx = 0; - - for (int y = 0; y < numTiles.y; y++) - { - // Loop on horizontal tiles - for (int x = 0; x < numTiles.x; x++, tIdx++) - { - decodedImage.setTile(x, y); - - int height = decodedImage.getTileCompHeight(tIdx, 0); - int width = decodedImage.getTileCompWidth(tIdx, 0); - - int tOffx = decodedImage.getCompULX(0) - - (int)Math.Ceiling(decodedImage.ImgULX / - (double)decodedImage.getCompSubsX(0)); - - int tOffy = decodedImage.getCompULY(0) - - (int)Math.Ceiling(decodedImage.ImgULY / - (double)decodedImage.getCompSubsY(0)); - - DataBlkInt[] db = new DataBlkInt[numComps]; - int[] ls = new int[numComps]; - int[] mv = new int[numComps]; - int[] fb = new int[numComps]; - for (int i = 0; i < numComps; i++) - { - db[i] = new DataBlkInt(); - ls[i] = 1 << (decodedImage.getNomRangeBits(0) - 1); - mv[i] = (1 << decodedImage.getNomRangeBits(0)) - 1; - fb[i] = decodedImage.getFixedPoint(0); - } - for (int l = 0; l < height; l++) - { - for (int i = numComps - 1; i >= 0; i--) - { - db[i].ulx = 0; - db[i].uly = l; - db[i].w = width; - db[i].h = 1; - decodedImage.getInternCompData(db[i], i); - } - int[] k = new int[numComps]; - for (int i = numComps - 1; i >= 0; i--) k[i] = db[i].offset + width - 1; - - int outputBytesPerPixel = Math.Max(3, Math.Min(4, bytesPerPixel)); - byte[] rowvalues = new byte[width * outputBytesPerPixel]; - - for (int i = width - 1; i >= 0; i--) - { - int[] tmp = new int[numComps]; - for (int j = numComps - 1; j >= 0; j--) - { - tmp[j] = (db[j].data_array[k[j]--] >> fb[j]) + ls[j]; - tmp[j] = (tmp[j] < 0) ? 0 : ((tmp[j] > mv[j]) ? mv[j] : tmp[j]); - - if (decodedImage.getNomRangeBits(j) != 8) - tmp[j] = (int)Math.Round(((double)tmp[j] / Math.Pow(2D, (double)decodedImage.getNomRangeBits(j))) * 255D); - - } - int offset = i * outputBytesPerPixel; - switch (numComps) - { - case 1: - rowvalues[offset + 0] = (byte)tmp[0]; - rowvalues[offset + 1] = (byte)tmp[0]; - rowvalues[offset + 2] = (byte)tmp[0]; - break; - case 3: - rowvalues[offset + 0] = (byte)tmp[2]; - rowvalues[offset + 1] = (byte)tmp[1]; - rowvalues[offset + 2] = (byte)tmp[0]; - break; - case 4: - case 5: - rowvalues[offset + 0] = (byte)tmp[2]; - rowvalues[offset + 1] = (byte)tmp[1]; - rowvalues[offset + 2] = (byte)tmp[0]; - rowvalues[offset + 3] = (byte)tmp[3]; - break; - } - } - - BitmapData dstdata = dst.LockBits( - new System.Drawing.Rectangle(tOffx, tOffy + l, width, 1), - ImageLockMode.WriteOnly, pixelFormat); - - IntPtr ptr = dstdata.Scan0; - System.Runtime.InteropServices.Marshal.Copy(rowvalues, 0, ptr, rowvalues.Length); - dst.UnlockBits(dstdata); - } - } - } - return dst; - } - - public static List GetLayerBoundaries(Stream stream) - { - RandomAccessIO in_stream = new ISRandomAccessIO(stream); - - // Create parameter list using defaults - ParameterList pl = new ParameterList(GetDefaultParameterList(decoder_pinfo)); - - // **** File Format **** - // If the codestream is wrapped in the jp2 fileformat, Read the - // file format wrapper - FileFormatReader ff = new FileFormatReader(in_stream); - ff.readFileFormat(); - if (ff.JP2FFUsed) - { - in_stream.seek(ff.FirstCodeStreamPos); - } - - // +----------------------------+ - // | Instantiate decoding chain | - // +----------------------------+ - - // **** Header decoder **** - // Instantiate header decoder and read main header - HeaderInfo hi = new HeaderInfo(); - HeaderDecoder hd; - try - { - hd = new HeaderDecoder(in_stream, pl, hi); - } - catch (EndOfStreamException e) - { - throw new ArgumentException("Codestream too short or bad header, unable to decode.", e); - } - - int nCompCod = hd.NumComps; - int nTiles = hi.sizValue.NumTiles; - DecoderSpecs decSpec = hd.DecoderSpecs; - - // Get demixed bitdepths - int[] depth = new int[nCompCod]; - for (int i = 0; i < nCompCod; i++) - { - depth[i] = hd.getOriginalBitDepth(i); - } - - // **** Bit stream reader **** - BitstreamReaderAgent breader; - try - { - breader = BitstreamReaderAgent.createInstance(in_stream, hd, pl, decSpec, false, hi); - } - catch (IOException e) - { - throw new ArgumentException("Error while reading bit stream header or parsing packets.", e); - } - catch (ArgumentException e) - { - throw new ArgumentException("Cannot instantiate bit stream reader.", e); - } - - breader.setTile(0, 0); - - return ((FileBitstreamReaderAgent)breader).layerStarts; - } - - #endregion - - #region Static Encoder Methods - - public static void ToFile(Bitmap bitmap, string filename) - { - using (FileStream stream = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite)) - { - ToStream(bitmap, stream); - } - } - public static byte[] ToArray(Bitmap bitmap) - { - using (MemoryStream stream = new MemoryStream()) - { - ToStream(bitmap, stream); - return stream.ToArray(); - } - } - public static void ToStream(Bitmap bitmap, Stream stream) - { - throw new NotImplementedException(); - } - - #endregion - - #region Default Parameter Loader - public static ParameterList GetDefaultParameterList(string[][] pinfo) - { - ParameterList pl = new ParameterList(); - string[][] str; - - str = BitstreamReaderAgent.ParameterInfo; - if (str != null) for (int i = str.Length - 1; i >= 0; i--) - pl.Set(str[i][0], str[i][3]); - - str = EntropyDecoder.ParameterInfo; - if (str != null) for (int i = str.Length - 1; i >= 0; i--) - pl.Set(str[i][0], str[i][3]); - - str = ROIDeScaler.ParameterInfo; - if (str != null) for (int i = str.Length - 1; i >= 0; i--) - pl.Set(str[i][0], str[i][3]); - - str = Dequantizer.ParameterInfo; - if (str != null) for (int i = str.Length - 1; i >= 0; i--) - pl.Set(str[i][0], str[i][3]); - - str = InvCompTransf.ParameterInfo; - if (str != null) for (int i = str.Length - 1; i >= 0; i--) - pl.Set(str[i][0], str[i][3]); - - str = HeaderDecoder.ParameterInfo; - if (str != null) for (int i = str.Length - 1; i >= 0; i--) - pl.Set(str[i][0], str[i][3]); - - str = ICCProfiler.ParameterInfo; - if (str != null) for (int i = str.Length - 1; i >= 0; i--) - pl.Set(str[i][0], str[i][3]); - - str = pinfo; - if (str != null) for (int i = str.Length - 1; i >= 0; i--) - pl.Set(str[i][0], str[i][3]); - - return pl; - } - #endregion - - #region Decoder Parameters - private static String[][] decoder_pinfo = { - new string[] { "u", "[on|off]", - "Prints usage information. "+ - "If specified all other arguments (except 'v') are ignored","off"}, - new string[] { "v", "[on|off]", - "Prints version and copyright information","off"}, - new string[] { "verbose", "[on|off]", - "Prints information about the decoded codestream","on"}, - new string[] { "pfile", "", - "Loads the arguments from the specified file. Arguments that are "+ - "specified on the command line override the ones from the file.\n"+ - "The arguments file is a simple text file with one argument per "+ - "line of the following form:\n" + - " =\n"+ - "If the argument is of boolean type (i.e. its presence turns a "+ - "feature on), then the 'on' value turns it on, while the 'off' "+ - "value turns it off. The argument name does not include the '-' "+ - "or '+' character. Long lines can be broken into several lines "+ - "by terminating them with '\\'. Lines starting with '#' are "+ - "considered as comments. This option is not recursive: any 'pfile' "+ - "argument appearing in the file is ignored.",null}, - new string[] { "res", "", - "The resolution level at which to reconstruct the image "+ - " (0 means the lowest available resolution whereas the maximum "+ - "resolution level corresponds to the original image resolution). "+ - "If the given index"+ - " is greater than the number of available resolution levels of the "+ - "compressed image, the image is reconstructed at its highest "+ - "resolution (among all tile-components). Note that this option"+ - " affects only the inverse wavelet transform and not the number "+ - " of bytes read by the codestream parser: this number of bytes "+ - "depends only on options '-nbytes' or '-rate'.", null}, - new string[] { "i", "", - "The file containing the JPEG 2000 compressed data. This can be "+ - "either a JPEG 2000 codestream or a JP2 file containing a "+ - "JPEG 2000 "+ - "codestream. In the latter case the first codestream in the file "+ - "will be decoded. If an URL is specified (e.g., http://...) "+ - "the data will be downloaded and cached in memory before decoding. "+ - "This is intended for easy use in applets, but it is not a very "+ - "efficient way of decoding network served data.", null}, - new string[] { "o", "", - "This is the name of the file to which the decompressed image "+ - "is written. If no output filename is given, the image is "+ - "displayed on the screen. "+ - "Output file format is PGX by default. If the extension"+ - " is '.pgm' then a PGM file is written as output, however this is "+ - "only permitted if the component bitdepth does not exceed 8. If "+ - "the extension is '.ppm' then a PPM file is written, however this "+ - "is only permitted if there are 3 components and none of them has "+ - "a bitdepth of more than 8. If there is more than 1 component, "+ - "suffices '-1', '-2', '-3', ... are added to the file name, just "+ - "before the extension, except for PPM files where all three "+ - "components are written to the same file.",null}, - new string[] { "rate","", - "Specifies the decoding rate in bits per pixel (bpp) where the "+ - "number of pixels is related to the image's original size (Note:"+ - " this number is not affected by the '-res' option). If it is equal"+ - "to -1, the whole codestream is decoded. "+ - "The codestream is either parsed (default) or truncated depending "+ - "the command line option '-parsing'. To specify the decoding "+ - "rate in bytes, use '-nbytes' options instead.","-1"}, - new string[] { "nbytes","", - "Specifies the decoding rate in bytes. "+ - "The codestream is either parsed (default) or truncated depending "+ - "the command line option '-parsing'. To specify the decoding "+ - "rate in bits per pixel, use '-rate' options instead.","-1"}, - new string[] { "parsing", null, - "Enable or not the parsing mode when decoding rate is specified "+ - "('-nbytes' or '-rate' options). If it is false, the codestream "+ - "is decoded as if it were truncated to the given rate. If it is "+ - "true, the decoder creates, truncates and decodes a virtual layer"+ - " progressive codestream with the same truncation points in each "+ - "code-block.","on"}, - new string[] { "ncb_quit","", - "Use the ncb and lbody quit conditions. If state information is "+ - "found for more code blocks than is indicated with this option, "+ - "the decoder "+ - "will decode using only information found before that point. "+ - "Using this otion implies that the 'rate' or 'nbyte' parameter "+ - "is used to indicate the lbody parameter which is the number of "+ - "packet body bytes the decoder will decode.","-1"}, - new string[] { "l_quit","", - "Specifies the maximum number of layers to decode for any code-"+ - "block","-1"}, - new string[] { "m_quit","", - "Specifies the maximum number of bit planes to decode for any code"+ - "-block","-1"}, - new string[] { "poc_quit",null, - "Specifies the whether the decoder should only decode code-blocks "+ - "included in the first progression order.","off"}, - new string[] { "one_tp",null, - "Specifies whether the decoder should only decode the first "+ - "tile part of each tile.","off"}, - new string[] { "comp_transf",null, - "Specifies whether the component transform indicated in the "+ - "codestream should be used.","on"}, - new string[] { "debug", null, - "Print debugging messages when an error is encountered.","off"}, - new string[] { "cdstr_info", null, - "Display information about the codestream. This information is: "+ - "\n- Marker segments value in main and tile-part headers,"+ - "\n- Tile-part length and position within the code-stream.", "off"}, - new string[] { "nocolorspace",null, - "Ignore any colorspace information in the image.","off"}, - new string[] { "colorspace_debug", null, - "Print debugging messages when an error is encountered in the"+ - " colorspace module.","off"} - }; - #endregion - - #region Encoder Parameters - private static String[][] encoder_pinfo = { - new string[] { "debug", null, - "Print debugging messages when an error is encountered.","off"}, - new string[] { "disable_jp2_extension", "[on|off]", - "JJ2000 automatically adds .jp2 extension when using 'file_format'"+ - "option. This option disables it when on.", "off"}, - new string[] { "file_format", "[on|off]", - "Puts the JPEG 2000 codestream in a JP2 file format wrapper.","off"}, - new string[] { "pph_tile", "[on|off]", - "Packs the packet headers in the tile headers.","off"}, - new string[] { "pph_main", "[on|off]", - "Packs the packet headers in the main header.","off"}, - new string[] { "pfile", "", - "Loads the arguments from the specified file. Arguments that are "+ - "specified on the command line override the ones from the file.\n"+ - "The arguments file is a simple text file with one argument per "+ - "line of the following form:\n" + - " =\n"+ - "If the argument is of boolean type (i.e. its presence turns a "+ - "feature on), then the 'on' value turns it on, while the 'off' "+ - "value turns it off. The argument name does not include the '-' "+ - "or '+' character. Long lines can be broken into several lines "+ - "by terminating them with '\'. Lines starting with '#' are "+ - "considered as comments. This option is not recursive: any 'pfile' "+ - "argument appearing in the file is ignored.",null}, - new string[] { "tile_parts", "", - "This option specifies the maximum number of packets to have in "+ - "one tile-part. 0 means include all packets in first tile-part "+ - "of each tile","0"}, - new string[] { "tiles", " ", - "This option specifies the maximum tile dimensions to use. "+ - "If both dimensions are 0 then no tiling is used.","0 0"}, - new string[] { "ref", " ", - "Sets the origin of the image in the canvas system. It sets the "+ - "coordinate of the top-left corner of the image reference grid, "+ - "with respect to the canvas origin","0 0"}, - new string[] { "tref", " ", - "Sets the origin of the tile partitioning on the reference grid, "+ - "with respect to the canvas origin. The value of 'x' ('y') "+ - "specified can not be larger than the 'x' one specified in the ref "+ - "option.","0 0"}, - new string[] { "rate", "", - "This is the output bitrate of the codestream in bits per pixel."+ - " When equal to -1, no image information (beside quantization "+ - "effects) is discarded during compression.\n"+ - "Note: In the case where '-file_format' option is used, the "+ - "resulting file may have a larger bitrate.","-1"}, - new string[] { "lossless", "[on|off]", - "Specifies a lossless compression for the encoder. This options"+ - " is equivalent to use reversible quantization ('-Qtype "+ - "reversible')"+ - " and 5x3 wavelet filters pair ('-Ffilters w5x3'). Note that "+ - "this option cannot be used with '-rate'. When this option is "+ - "off, the quantization type and the filters pair is defined by "+ - "'-Qtype' and '-Ffilters' respectively.","off"}, - new string[] { "i", " [, [, ... ]]", - "Mandatory argument. This option specifies the name of the input "+ - "image files. If several image files are provided, they have to be"+ - " separated by commas in the command line. Supported formats are "+ - "PGM (raw), PPM (raw) and PGX, "+ - "which is a simple extension of the PGM file format for single "+ - "component data supporting arbitrary bitdepths. If the extension "+ - "is '.pgm', PGM-raw file format is assumed, if the extension is "+ - "'.ppm', PPM-raw file format is assumed, otherwise PGX file "+ - "format is assumed. PGM and PPM files are assumed to be 8 bits "+ - "deep. A multi-component image can be specified by either "+ - "specifying several PPM and/or PGX files, or by specifying one "+ - "PPM file.",null}, - new string[] { "o", "", - "Mandatory argument. This option specifies the name of the output "+ - "file to which the codestream will be written.",null}, - new string[] { "verbose", null, - "Prints information about the obtained bit stream.","on"}, - new string[] { "v", "[on|off]", - "Prints version and copyright information.","off"}, - new string[] { "u", "[on|off]", - "Prints usage information. "+ - "If specified all other arguments (except 'v') are ignored","off"}, - }; - #endregion - } -} diff --git a/CSJ2K/Util/EndianBinaryReader.cs b/CSJ2K/Util/EndianBinaryReader.cs deleted file mode 100644 index 5cb50237..00000000 --- a/CSJ2K/Util/EndianBinaryReader.cs +++ /dev/null @@ -1,625 +0,0 @@ -using System; -using System.IO; -using System.Text; - -namespace CSJ2K.Util -{ - internal class EndianBinaryReader : BinaryReader - { - private bool _bigEndian = false; - - // Summary: - // Initializes a new instance of the System.IO.BinaryReader class based on the - // supplied stream and using System.Text.UTF8Encoding. - // - // Parameters: - // input: - // A stream. - // - // Exceptions: - // System.ArgumentException: - // The stream does not support reading, the stream is null, or the stream is - // already closed. - public EndianBinaryReader(Stream input) : base(input) - { - - } - // - // Summary: - // Initializes a new instance of the System.IO.BinaryReader class based on the - // supplied stream and a specific character encoding. - // - // Parameters: - // encoding: - // The character encoding. - // - // input: - // The supplied stream. - // - // Exceptions: - // System.ArgumentNullException: - // encoding is null. - // - // System.ArgumentException: - // The stream does not support reading, the stream is null, or the stream is - // already closed. - public EndianBinaryReader(Stream input, Encoding encoding) : base(input, encoding) - { - - } - - public EndianBinaryReader(Stream input, Encoding encoding, bool bigEndian) - : base(input, encoding) - { - _bigEndian = bigEndian; - } - - public EndianBinaryReader(Stream input, bool bigEndian) : base(input, bigEndian ? Encoding.BigEndianUnicode : Encoding.ASCII) - { - _bigEndian = bigEndian; - } - - // Summary: - // Exposes access to the underlying stream of the System.IO.BinaryReader. - // - // Returns: - // The underlying stream associated with the BinaryReader. - //public virtual Stream BaseStream { get; } - - // Summary: - // Closes the current reader and the underlying stream. - //public virtual void Close(); - // - // Summary: - // Releases the unmanaged resources used by the System.IO.BinaryReader and optionally - // releases the managed resources. - // - // Parameters: - // disposing: - // true to release both managed and unmanaged resources; false to release only - // unmanaged resources. - //protected virtual void Dispose(bool disposing); - // - // Summary: - // Fills the internal buffer with the specified number of bytes read from the - // stream. - // - // Parameters: - // numBytes: - // The number of bytes to be read. - // - // Exceptions: - // System.IO.EndOfStreamException: - // The end of the stream is reached before numBytes could be read. - // - // System.IO.IOException: - // An I/O error occurs. - //protected virtual void FillBuffer(int numBytes); - // - // Summary: - // Returns the next available character and does not advance the byte or character - // position. - // - // Returns: - // The next available character, or -1 if no more characters are available or - // the stream does not support seeking. - // - // Exceptions: - // System.IO.IOException: - // An I/O error occurs. - //public virtual int PeekChar(); - // - // Summary: - // Reads characters from the underlying stream and advances the current position - // of the stream in accordance with the Encoding used and the specific character - // being read from the stream. - // - // Returns: - // The next character from the input stream, or -1 if no characters are currently - // available. - // - // Exceptions: - // System.ObjectDisposedException: - // The stream is closed. - // - // System.IO.IOException: - // An I/O error occurs. - //public virtual int Read(); - // - // Summary: - // Reads count bytes from the stream with index as the starting point in the - // byte array. - // - // Parameters: - // count: - // The number of characters to read. - // - // buffer: - // The buffer to read data into. - // - // index: - // The starting point in the buffer at which to begin reading into the buffer. - // - // Returns: - // The number of characters read into buffer. This might be less than the number - // of bytes requested if that many bytes are not available, or it might be zero - // if the end of the stream is reached. - // - // Exceptions: - // System.ArgumentNullException: - // buffer is null. - // - // System.IO.IOException: - // An I/O error occurs. - // - // System.ObjectDisposedException: - // The stream is closed. - // - // System.ArgumentOutOfRangeException: - // index or count is negative. - // - // System.ArgumentException: - // The buffer length minus index is less than count. - //public virtual int Read(byte[] buffer, int index, int count); - // - // Summary: - // Reads count characters from the stream with index as the starting point in - // the character array. - // - // Parameters: - // count: - // The number of characters to read. - // - // buffer: - // The buffer to read data into. - // - // index: - // The starting point in the buffer at which to begin reading into the buffer. - // - // Returns: - // The total number of characters read into the buffer. This might be less than - // the number of characters requested if that many characters are not currently - // available, or it might be zero if the end of the stream is reached. - // - // Exceptions: - // System.ArgumentNullException: - // buffer is null. - // - // System.IO.IOException: - // An I/O error occurs. - // - // System.ObjectDisposedException: - // The stream is closed. - // - // System.ArgumentOutOfRangeException: - // index or count is negative. - // - // System.ArgumentException: - // The buffer length minus index is less than count. - //public virtual int Read(char[] buffer, int index, int count); - // - // Summary: - // Reads in a 32-bit integer in compressed format. - // - // Returns: - // A 32-bit integer in compressed format. - // - // Exceptions: - // System.ObjectDisposedException: - // The stream is closed. - // - // System.IO.IOException: - // An I/O error occurs. - // - // System.FormatException: - // The stream is corrupted. - // - // System.IO.EndOfStreamException: - // The end of the stream is reached. - //protected internal int Read7BitEncodedInt(); - // - // Summary: - // Reads a Boolean value from the current stream and advances the current position - // of the stream by one byte. - // - // Returns: - // true if the byte is nonzero; otherwise, false. - // - // Exceptions: - // System.ObjectDisposedException: - // The stream is closed. - // - // System.IO.IOException: - // An I/O error occurs. - // - // System.IO.EndOfStreamException: - // The end of the stream is reached. - //public virtual bool ReadBoolean(); - // - // Summary: - // Reads the next byte from the current stream and advances the current position - // of the stream by one byte. - // - // Returns: - // The next byte read from the current stream. - // - // Exceptions: - // System.ObjectDisposedException: - // The stream is closed. - // - // System.IO.IOException: - // An I/O error occurs. - // - // System.IO.EndOfStreamException: - // The end of the stream is reached. - //public virtual byte ReadByte(); - // - // Summary: - // Reads count bytes from the current stream into a byte array and advances - // the current position by count bytes. - // - // Parameters: - // count: - // The number of bytes to read. - // - // Returns: - // A byte array containing data read from the underlying stream. This might - // be less than the number of bytes requested if the end of the stream is reached. - // - // Exceptions: - // System.ObjectDisposedException: - // The stream is closed. - // - // System.IO.IOException: - // An I/O error occurs. - // - // System.ArgumentOutOfRangeException: - // count is negative. - //public virtual byte[] ReadBytes(int count); - // - // Summary: - // Reads the next character from the current stream and advances the current - // position of the stream in accordance with the Encoding used and the specific - // character being read from the stream. - // - // Returns: - // A character read from the current stream. - // - // Exceptions: - // System.ObjectDisposedException: - // The stream is closed. - // - // System.IO.IOException: - // An I/O error occurs. - // - // System.IO.EndOfStreamException: - // The end of the stream is reached. - // - // System.ArgumentException: - // A surrogate character was read. - //public virtual char ReadChar(); - // - // Summary: - // Reads count characters from the current stream, returns the data in a character - // array, and advances the current position in accordance with the Encoding - // used and the specific character being read from the stream. - // - // Parameters: - // count: - // The number of characters to read. - // - // Returns: - // A character array containing data read from the underlying stream. This might - // be less than the number of characters requested if the end of the stream - // is reached. - // - // Exceptions: - // System.ObjectDisposedException: - // The stream is closed. - // - // System.IO.IOException: - // An I/O error occurs. - // - // System.IO.EndOfStreamException: - // The end of the stream is reached. - // - // System.ArgumentOutOfRangeException: - // count is negative. - //public virtual char[] ReadChars(int count); - // - // Summary: - // Reads a decimal value from the current stream and advances the current position - // of the stream by sixteen bytes. - // - // Returns: - // A decimal value read from the current stream. - // - // Exceptions: - // System.ObjectDisposedException: - // The stream is closed. - // - // System.IO.IOException: - // An I/O error occurs. - // - // System.IO.EndOfStreamException: - // The end of the stream is reached. - public override decimal ReadDecimal() - { - if (_bigEndian) - { - // TODO: Is the whole thing reversed or just the individual ints? - // Maybe we should just call ReadInt32 4 times? - byte[] buf = this.ReadBytes(16); - Array.Reverse(buf); - int[] decimalints = new int[4]; - decimalints[0] = BitConverter.ToInt32(buf, 0); - decimalints[1] = BitConverter.ToInt32(buf, 4); - decimalints[2] = BitConverter.ToInt32(buf, 8); - decimalints[3] = BitConverter.ToInt32(buf, 12); - return new decimal(decimalints); - } - else return base.ReadDecimal(); - } - // - // Summary: - // Reads an 8-byte floating point value from the current stream and advances - // the current position of the stream by eight bytes. - // - // Returns: - // An 8-byte floating point value read from the current stream. - // - // Exceptions: - // System.ObjectDisposedException: - // The stream is closed. - // - // System.IO.IOException: - // An I/O error occurs. - // - // System.IO.EndOfStreamException: - // The end of the stream is reached. - public override double ReadDouble() - { - if (_bigEndian) - { - byte[] buf = this.ReadBytes(8); - Array.Reverse(buf); - return BitConverter.ToDouble(buf, 0); - } - else - return base.ReadDouble(); - } - // - // Summary: - // Reads a 2-byte signed integer from the current stream and advances the current - // position of the stream by two bytes. - // - // Returns: - // A 2-byte signed integer read from the current stream. - // - // Exceptions: - // System.ObjectDisposedException: - // The stream is closed. - // - // System.IO.IOException: - // An I/O error occurs. - // - // System.IO.EndOfStreamException: - // The end of the stream is reached. - public override short ReadInt16() - { - if (_bigEndian) - { - byte[] buf = this.ReadBytes(2); - Array.Reverse(buf); - return BitConverter.ToInt16(buf, 0); - } - else - return base.ReadInt16(); - } - // - // Summary: - // Reads a 4-byte signed integer from the current stream and advances the current - // position of the stream by four bytes. - // - // Returns: - // A 4-byte signed integer read from the current stream. - // - // Exceptions: - // System.ObjectDisposedException: - // The stream is closed. - // - // System.IO.IOException: - // An I/O error occurs. - // - // System.IO.EndOfStreamException: - // The end of the stream is reached. - public override int ReadInt32() - { - if (_bigEndian) - { - byte[] buf = this.ReadBytes(4); - Array.Reverse(buf); - return BitConverter.ToInt32(buf, 0); - } - else - return base.ReadInt32(); - } - // - // Summary: - // Reads an 8-byte signed integer from the current stream and advances the current - // position of the stream by eight bytes. - // - // Returns: - // An 8-byte signed integer read from the current stream. - // - // Exceptions: - // System.ObjectDisposedException: - // The stream is closed. - // - // System.IO.IOException: - // An I/O error occurs. - // - // System.IO.EndOfStreamException: - // The end of the stream is reached. - public override long ReadInt64() - { - if (_bigEndian) - { - byte[] buf = this.ReadBytes(8); - Array.Reverse(buf); - return BitConverter.ToInt64(buf, 0); - } - else - return base.ReadInt64(); - } - // - // Summary: - // Reads a signed byte from this stream and advances the current position of - // the stream by one byte. - // - // Returns: - // A signed byte read from the current stream. - // - // Exceptions: - // System.ObjectDisposedException: - // The stream is closed. - // - // System.IO.IOException: - // An I/O error occurs. - // - // System.IO.EndOfStreamException: - // The end of the stream is reached. - //[CLSCompliant(false)] - //public virtual byte Readbyte(); - // - // Summary: - // Reads a 4-byte floating point value from the current stream and advances - // the current position of the stream by four bytes. - // - // Returns: - // A 4-byte floating point value read from the current stream. - // - // Exceptions: - // System.ObjectDisposedException: - // The stream is closed. - // - // System.IO.IOException: - // An I/O error occurs. - // - // System.IO.EndOfStreamException: - // The end of the stream is reached. - public override float ReadSingle() - { - if (_bigEndian) - { - byte[] buf = this.ReadBytes(4); - Array.Reverse(buf); - return BitConverter.ToSingle(buf, 0); - } - else - return base.ReadSingle(); - } - // - // Summary: - // Reads a string from the current stream. The string is prefixed with the length, - // encoded as an integer seven bits at a time. - // - // Returns: - // The string being read. - // - // Exceptions: - // System.ObjectDisposedException: - // The stream is closed. - // - // System.IO.IOException: - // An I/O error occurs. - // - // System.IO.EndOfStreamException: - // The end of the stream is reached. - //public virtual string ReadString(); - // - // Summary: - // Reads a 2-byte unsigned integer from the current stream using little-endian - // encoding and advances the position of the stream by two bytes. - // - // Returns: - // A 2-byte unsigned integer read from this stream. - // - // Exceptions: - // System.ObjectDisposedException: - // The stream is closed. - // - // System.IO.IOException: - // An I/O error occurs. - // - // System.IO.EndOfStreamException: - // The end of the stream is reached. - public override ushort ReadUInt16() - { - if (_bigEndian) - { - byte[] buf = this.ReadBytes(2); - Array.Reverse(buf); - return BitConverter.ToUInt16(buf, 0); - } - else - return base.ReadUInt16(); - } - // - // Summary: - // Reads a 4-byte unsigned integer from the current stream and advances the - // position of the stream by four bytes. - // - // Returns: - // A 4-byte unsigned integer read from this stream. - // - // Exceptions: - // System.ObjectDisposedException: - // The stream is closed. - // - // System.IO.IOException: - // An I/O error occurs. - // - // System.IO.EndOfStreamException: - // The end of the stream is reached. - public override uint ReadUInt32() - { - if (_bigEndian) - { - byte[] buf = this.ReadBytes(4); - Array.Reverse(buf); - return BitConverter.ToUInt32(buf, 0); - } - else - return base.ReadUInt32(); - } - // - // Summary: - // Reads an 8-byte unsigned integer from the current stream and advances the - // position of the stream by eight bytes. - // - // Returns: - // An 8-byte unsigned integer read from this stream. - // - // Exceptions: - // System.ObjectDisposedException: - // The stream is closed. - // - // System.IO.IOException: - // An I/O error occurs. - // - // System.IO.EndOfStreamException: - // The end of the stream is reached. - public override ulong ReadUInt64() - { - if (_bigEndian) - { - byte[] buf = this.ReadBytes(8); - Array.Reverse(buf); - return BitConverter.ToUInt64(buf, 0); - } - else - return base.ReadUInt64(); - } - } -} diff --git a/CSJ2K/Util/EndianBinaryWriter.cs b/CSJ2K/Util/EndianBinaryWriter.cs deleted file mode 100644 index b03581e2..00000000 --- a/CSJ2K/Util/EndianBinaryWriter.cs +++ /dev/null @@ -1,556 +0,0 @@ -using System; -using System.IO; -using System.Text; - -namespace CSJ2K.Util -{ - internal class EndianBinaryWriter : BinaryWriter - { - private bool _bigEndian = false; - - // - // Summary: - // Initializes a new instance of the System.IO.BinaryWriter class based on the - // supplied stream and using UTF-8 as the encoding for strings. - // - // Parameters: - // output: - // The output stream. - // - // Exceptions: - // System.ArgumentException: - // The stream does not support writing, or the stream is already closed. - // - // System.ArgumentNullException: - // output is null. - public EndianBinaryWriter(Stream input) : base(input) - { - } - // - // Summary: - // Initializes a new instance of the System.IO.BinaryWriter class based on the - // supplied stream and a specific character encoding. - // - // Parameters: - // encoding: - // The character encoding. - // - // output: - // The supplied stream. - // - // Exceptions: - // System.ArgumentNullException: - // output or encoding is null. - // - // System.ArgumentException: - // The stream does not support writing, or the stream is already closed. - public EndianBinaryWriter(Stream input, Encoding encoding) : base(input, encoding) - { - - } - public EndianBinaryWriter(Stream input, Encoding encoding, bool bigEndian) - : base(input, encoding) - { - _bigEndian = bigEndian; - } - - public EndianBinaryWriter(Stream input, bool bigEndian) : base(input, bigEndian ? Encoding.BigEndianUnicode : Encoding.ASCII) - { - _bigEndian = bigEndian; - } - - // Summary: - // Gets the underlying stream of the System.IO.BinaryWriter. - // - // Returns: - // The underlying stream associated with the BinaryWriter. - //public virtual Stream BaseStream { get; } - - // Summary: - // Closes the current System.IO.BinaryWriter and the underlying stream. - //public virtual void Close(); - // - // Summary: - // Releases the unmanaged resources used by the System.IO.BinaryWriter and optionally - // releases the managed resources. - // - // Parameters: - // disposing: - // true to release both managed and unmanaged resources; false to release only - // unmanaged resources. - //protected virtual void Dispose(bool disposing); - // - // Summary: - // Clears all buffers for the current writer and causes any buffered data to - // be written to the underlying device. - //public virtual void Flush(); - // - // Summary: - // Sets the position within the current stream. - // - // Parameters: - // offset: - // A byte offset relative to origin. - // - // origin: - // A field of System.IO.SeekOrigin indicating the reference point from which - // the new position is to be obtained. - // - // Returns: - // The position with the current stream. - // - // Exceptions: - // System.ArgumentException: - // The System.IO.SeekOrigin value is invalid. - // - // System.IO.IOException: - // The file pointer was moved to an invalid location. - //public virtual long Seek(int offset, SeekOrigin origin); - // - // Summary: - // Writes a one-byte Boolean value to the current stream, with 0 representing - // false and 1 representing true. - // - // Parameters: - // value: - // The Boolean value to write (0 or 1). - // - // Exceptions: - // System.ObjectDisposedException: - // The stream is closed. - // - // System.IO.IOException: - // An I/O error occurs. - //public virtual void Write(bool value); - // - // Summary: - // Writes an unsigned byte to the current stream and advances the stream position - // by one byte. - // - // Parameters: - // value: - // The unsigned byte to write. - // - // Exceptions: - // System.ObjectDisposedException: - // The stream is closed. - // - // System.IO.IOException: - // An I/O error occurs. - //public virtual void Write(byte value); - // - // Summary: - // Writes a byte array to the underlying stream. - // - // Parameters: - // buffer: - // A byte array containing the data to write. - // - // Exceptions: - // System.ArgumentNullException: - // buffer is null. - // - // System.ObjectDisposedException: - // The stream is closed. - // - // System.IO.IOException: - // An I/O error occurs. - //public virtual void Write(byte[] buffer); - // - // Summary: - // Writes a Unicode character to the current stream and advances the current - // position of the stream in accordance with the Encoding used and the specific - // characters being written to the stream. - // - // Parameters: - // ch: - // The non-surrogate, Unicode character to write. - // - // Exceptions: - // System.ObjectDisposedException: - // The stream is closed. - // - // System.ArgumentException: - // ch is a single surrogate character. - // - // System.IO.IOException: - // An I/O error occurs. - //public virtual void Write(char ch); - // - // Summary: - // Writes a character array to the current stream and advances the current position - // of the stream in accordance with the Encoding used and the specific characters - // being written to the stream. - // - // Parameters: - // chars: - // A character array containing the data to write. - // - // Exceptions: - // System.ObjectDisposedException: - // The stream is closed. - // - // System.IO.IOException: - // An I/O error occurs. - // - // System.ArgumentNullException: - // chars is null. - //public virtual void Write(char[] chars); - // - // Summary: - // Writes a decimal value to the current stream and advances the stream position - // by sixteen bytes. - // - // Parameters: - // value: - // The decimal value to write. - // - // Exceptions: - // System.ObjectDisposedException: - // The stream is closed. - // - // System.IO.IOException: - // An I/O error occurs. - public override void Write(decimal value) - { - if (_bigEndian) - { - throw new System.NotImplementedException(); - /* - int[] decimalints=decimal.GetBits(value); - - // TODO: Is the whole thing reversed or just the individual ints? - // Maybe we should just call ReadInt32 4 times? - //byte[] buf = this.ReadBytes(16); - //Array.Reverse(buf); - //int[] decimalints = new int[4]; - //decimalints[0] = BitConverter.ToInt32(buf, 0); - //decimalints[1] = BitConverter.ToInt32(buf, 4); - //decimalints[2] = BitConverter.ToInt32(buf, 8); - //decimalints[3] = BitConverter.ToInt32(buf, 12); - //return new decimal(decimalints); - */ - } - else base.Write(value); - } - // - // Summary: - // Writes an eight-byte floating-point value to the current stream and advances - // the stream position by eight bytes. - // - // Parameters: - // value: - // The eight-byte floating-point value to write. - // - // Exceptions: - // System.ObjectDisposedException: - // The stream is closed. - // - // System.IO.IOException: - // An I/O error occurs. - public override void Write(double value) - { - if (_bigEndian) - { - byte[] buf = BitConverter.GetBytes(value); - Array.Reverse(buf); - base.Write(buf); - } - else base.Write(value); - } - // - // Summary: - // Writes a four-byte floating-point value to the current stream and advances - // the stream position by four bytes. - // - // Parameters: - // value: - // The four-byte floating-point value to write. - // - // Exceptions: - // System.ObjectDisposedException: - // The stream is closed. - // - // System.IO.IOException: - // An I/O error occurs. - public override void Write(float value) - { - if (_bigEndian) - { - byte[] buf = BitConverter.GetBytes(value); - Array.Reverse(buf); - base.Write(buf); - } - else base.Write(value); - } - // - // Summary: - // Writes a four-byte signed integer to the current stream and advances the - // stream position by four bytes. - // - // Parameters: - // value: - // The four-byte signed integer to write. - // - // Exceptions: - // System.ObjectDisposedException: - // The stream is closed. - // - // System.IO.IOException: - // An I/O error occurs. - public override void Write(int value) - { - if (_bigEndian) - { - byte[] buf = BitConverter.GetBytes(value); - Array.Reverse(buf); - base.Write(buf); - } - else base.Write(value); - } - // - // Summary: - // Writes an eight-byte signed integer to the current stream and advances the - // stream position by eight bytes. - // - // Parameters: - // value: - // The eight-byte signed integer to write. - // - // Exceptions: - // System.ObjectDisposedException: - // The stream is closed. - // - // System.IO.IOException: - // An I/O error occurs. - public override void Write(long value) - { - if (_bigEndian) - { - byte[] buf = BitConverter.GetBytes(value); - Array.Reverse(buf); - base.Write(buf); - } - else base.Write(value); - } - // - // Summary: - // Writes a signed byte to the current stream and advances the stream position - // by one byte. - // - // Parameters: - // value: - // The signed byte to write. - // - // Exceptions: - // System.ObjectDisposedException: - // The stream is closed. - // - // System.IO.IOException: - // An I/O error occurs. - //[CLSCompliant(false)] - //public virtual void Write(sbyte value); - // - // Summary: - // Writes a two-byte signed integer to the current stream and advances the stream - // position by two bytes. - // - // Parameters: - // value: - // The two-byte signed integer to write. - // - // Exceptions: - // System.ObjectDisposedException: - // The stream is closed. - // - // System.IO.IOException: - // An I/O error occurs. - public override void Write(short value) - { - if (_bigEndian) - { - byte[] buf = BitConverter.GetBytes(value); - Array.Reverse(buf); - base.Write(buf); - } - else base.Write(value); - } - // - // Summary: - // Writes a length-prefixed string to this stream in the current encoding of - // the System.IO.BinaryWriter, and advances the current position of the stream - // in accordance with the encoding used and the specific characters being written - // to the stream. - // - // Parameters: - // value: - // The value to write. - // - // Exceptions: - // System.ObjectDisposedException: - // The stream is closed. - // - // System.IO.IOException: - // An I/O error occurs. - // - // System.ArgumentNullException: - // value is null. - //public virtual void Write(string value); - // - // Summary: - // Writes a four-byte unsigned integer to the current stream and advances the - // stream position by four bytes. - // - // Parameters: - // value: - // The four-byte unsigned integer to write. - // - // Exceptions: - // System.ObjectDisposedException: - // The stream is closed. - // - // System.IO.IOException: - // An I/O error occurs. - public override void Write(uint value) - { - if (_bigEndian) - { - byte[] buf = BitConverter.GetBytes(value); - Array.Reverse(buf); - base.Write(buf); - } - else base.Write(value); - } - // - // Summary: - // Writes an eight-byte unsigned integer to the current stream and advances - // the stream position by eight bytes. - // - // Parameters: - // value: - // The eight-byte unsigned integer to write. - // - // Exceptions: - // System.ObjectDisposedException: - // The stream is closed. - // - // System.IO.IOException: - // An I/O error occurs. - public override void Write(ulong value) - { - if (_bigEndian) - { - byte[] buf = BitConverter.GetBytes(value); - Array.Reverse(buf); - base.Write(buf); - } - else base.Write(value); - } - // - // Summary: - // Writes a two-byte unsigned integer to the current stream and advances the - // stream position by two bytes. - // - // Parameters: - // value: - // The two-byte unsigned integer to write. - // - // Exceptions: - // System.ObjectDisposedException: - // The stream is closed. - // - // System.IO.IOException: - // An I/O error occurs. - public override void Write(ushort value) - { - if (_bigEndian) - { - byte[] buf = BitConverter.GetBytes(value); - Array.Reverse(buf); - base.Write(buf); - } - else base.Write(value); - } - // - // Summary: - // Writes a region of a byte array to the current stream. - // - // Parameters: - // count: - // The number of bytes to write. - // - // buffer: - // A byte array containing the data to write. - // - // index: - // The starting point in buffer at which to begin writing. - // - // Exceptions: - // System.ArgumentNullException: - // buffer is null. - // - // System.IO.IOException: - // An I/O error occurs. - // - // System.ObjectDisposedException: - // The stream is closed. - // - // System.ArgumentOutOfRangeException: - // index or count is negative. - // - // System.ArgumentException: - // The buffer length minus index is less than count. - //public virtual void Write(byte[] buffer, int index, int count); - // - // Summary: - // Writes a section of a character array to the current stream, and advances - // the current position of the stream in accordance with the Encoding used and - // perhaps the specific characters being written to the stream. - // - // Parameters: - // chars: - // A character array containing the data to write. - // - // count: - // The number of characters to write. - // - // index: - // The starting point in buffer from which to begin writing. - // - // Exceptions: - // System.IO.IOException: - // An I/O error occurs. - // - // System.ObjectDisposedException: - // The stream is closed. - // - // System.ArgumentOutOfRangeException: - // index or count is negative. - // - // System.ArgumentException: - // The buffer length minus index is less than count. - // - // System.ArgumentNullException: - // chars is null. - //public virtual void Write(char[] chars, int index, int count); - // - // Summary: - // Writes a 32-bit integer in a compressed format. - // - // Parameters: - // value: - // The 32-bit integer to be written. - // - // Exceptions: - // System.ObjectDisposedException: - // The stream is closed. - // - // System.IO.EndOfStreamException: - // The end of the stream is reached. - // - // System.IO.IOException: - // The stream is closed. - //protected void Write7BitEncodedInt(int value) - - } -} diff --git a/CSJ2K/Util/SupportClass.cs b/CSJ2K/Util/SupportClass.cs deleted file mode 100644 index 6e19142e..00000000 --- a/CSJ2K/Util/SupportClass.cs +++ /dev/null @@ -1,1978 +0,0 @@ -// -// In order to convert some functionality to Visual C#, the Java Language Conversion Assistant -// creates "support classes" that duplicate the original functionality. -// -// Support classes replicate the functionality of the original code, but in some cases they are -// substantially different architecturally. Although every effort is made to preserve the -// original architecture of the application in the converted project, the user should be aware that -// the primary goal of these support classes is to replicate functionality, and that at times -// the architecture of the resulting solution may differ somewhat. -// - -using System; - -/// -/// This interface should be implemented by any class whose instances are intended -/// to be executed by a thread. -/// -public interface IThreadRunnable -{ - /// - /// This method has to be implemented in order that starting of the thread causes the object's - /// run method to be called in that separately executing thread. - /// - void Run(); -} - -/// -/// Contains conversion support elements such as classes, interfaces and static methods. -/// -internal class SupportClass -{ - /// - /// Converts an array of sbytes to an array of bytes - /// - /// The array of sbytes to be converted - /// The new array of bytes - public static byte[] ToByteArray(sbyte[] sbyteArray) - { - byte[] byteArray = null; - - if (sbyteArray != null) - { - byteArray = new byte[sbyteArray.Length]; - for (int index = 0; index < sbyteArray.Length; index++) - byteArray[index] = (byte)sbyteArray[index]; - } - return byteArray; - } - - /// - /// Converts a string to an array of bytes - /// - /// The string to be converted - /// The new array of bytes - public static byte[] ToByteArray(System.String sourceString) - { - return System.Text.UTF8Encoding.UTF8.GetBytes(sourceString); - } - - /// - /// Converts a array of object-type instances to a byte-type array. - /// - /// Array to convert. - /// An array of byte type elements. - public static byte[] ToByteArray(System.Object[] tempObjectArray) - { - byte[] byteArray = null; - if (tempObjectArray != null) - { - byteArray = new byte[tempObjectArray.Length]; - for (int index = 0; index < tempObjectArray.Length; index++) - byteArray[index] = (byte)tempObjectArray[index]; - } - return byteArray; - } - - /*******************************/ - /// - /// Writes the exception stack trace to the received stream - /// - /// Exception to obtain information from - /// Output sream used to write to - public static void WriteStackTrace(System.Exception throwable, System.IO.TextWriter stream) - { - stream.Write(throwable.StackTrace); - stream.Flush(); - } - - /*******************************/ - /// - /// Receives a byte array and returns it transformed in an sbyte array - /// - /// Byte array to process - /// The transformed array - public static sbyte[] ToSByteArray(byte[] byteArray) - { - sbyte[] sbyteArray = null; - if (byteArray != null) - { - sbyteArray = new sbyte[byteArray.Length]; - for (int index = 0; index < byteArray.Length; index++) - sbyteArray[index] = (sbyte)byteArray[index]; - } - return sbyteArray; - } - - /*******************************/ - /// - /// Converts an array of sbytes to an array of chars - /// - /// The array of sbytes to convert - /// The new array of chars - public static char[] ToCharArray(sbyte[] sByteArray) - { - return System.Text.UTF8Encoding.UTF8.GetChars(ToByteArray(sByteArray)); - } - - /// - /// Converts an array of bytes to an array of chars - /// - /// The array of bytes to convert - /// The new array of chars - public static char[] ToCharArray(byte[] byteArray) - { - return System.Text.UTF8Encoding.UTF8.GetChars(byteArray); - } - - /*******************************/ - /// - /// This method returns the literal value received - /// - /// The literal to return - /// The received value - public static long Identity(long literal) - { - return literal; - } - - /// - /// This method returns the literal value received - /// - /// The literal to return - /// The received value - public static ulong Identity(ulong literal) - { - return literal; - } - - /// - /// This method returns the literal value received - /// - /// The literal to return - /// The received value - public static float Identity(float literal) - { - return literal; - } - - /// - /// This method returns the literal value received - /// - /// The literal to return - /// The received value - public static double Identity(double literal) - { - return literal; - } - - /*******************************/ - /// - /// Provides support functions to create read-write random acces files and write functions - /// - public class RandomAccessFileSupport - { - /// - /// Creates a new random acces stream with read-write or read rights - /// - /// A relative or absolute path for the file to open - /// Mode to open the file in - /// The new System.IO.FileStream - public static System.IO.FileStream CreateRandomAccessFile(System.String fileName, System.String mode) - { - System.IO.FileStream newFile = null; - - if (mode.CompareTo("rw") == 0) - // newFile = new System.IO.FileStream(fileName, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite); - //else if (mode.CompareTo("rw+") == 0) - newFile = new System.IO.FileStream(fileName, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite); - else if (mode.CompareTo("r") == 0) - newFile = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read); - else - throw new System.ArgumentException(); - - return newFile; - } - - /// - /// Creates a new random acces stream with read-write or read rights - /// - /// File infomation for the file to open - /// Mode to open the file in - /// The new System.IO.FileStream - public static System.IO.FileStream CreateRandomAccessFile(System.IO.FileInfo fileName, System.String mode) - { - return CreateRandomAccessFile(fileName.FullName, mode); - } - - /// - /// Writes the data to the specified file stream - /// - /// Data to write - /// File to write to - public static void WriteBytes(System.String data, System.IO.FileStream fileStream) - { - int index = 0; - int length = data.Length; - - while (index < length) - fileStream.WriteByte((byte)data[index++]); - } - - /// - /// Writes the received string to the file stream - /// - /// String of information to write - /// File to write to - public static void WriteChars(System.String data, System.IO.FileStream fileStream) - { - WriteBytes(data, fileStream); - } - - /// - /// Writes the received data to the file stream - /// - /// Data to write - /// File to write to - public static void WriteRandomFile(sbyte[] sByteArray, System.IO.FileStream fileStream) - { - byte[] byteArray = ToByteArray(sByteArray); - fileStream.Write(byteArray, 0, byteArray.Length); - } - } - - /*******************************/ - /// - /// Performs an unsigned bitwise right shift with the specified number - /// - /// Number to operate on - /// Ammount of bits to shift - /// The resulting number from the shift operation - public static int URShift(int number, int bits) - { - if (number >= 0) - return number >> bits; - else - return (number >> bits) + (2 << ~bits); - } - - /// - /// Performs an unsigned bitwise right shift with the specified number - /// - /// Number to operate on - /// Ammount of bits to shift - /// The resulting number from the shift operation - public static int URShift(int number, long bits) - { - return URShift(number, (int)bits); - } - - /// - /// Performs an unsigned bitwise right shift with the specified number - /// - /// Number to operate on - /// Ammount of bits to shift - /// The resulting number from the shift operation - public static long URShift(long number, int bits) - { - if (number >= 0) - return number >> bits; - else - return (number >> bits) + (2L << ~bits); - } - - /// - /// Performs an unsigned bitwise right shift with the specified number - /// - /// Number to operate on - /// Ammount of bits to shift - /// The resulting number from the shift operation - public static long URShift(long number, long bits) - { - return URShift(number, (int)bits); - } - - /*******************************/ - /// Reads a number of characters from the current source Stream and writes the data to the target array at the specified index. - /// The source Stream to read from. - /// Contains the array of characteres read from the source Stream. - /// The starting index of the target array. - /// The maximum number of characters to read from the source Stream. - /// The number of characters read. The number will be less than or equal to count depending on the data available in the source Stream. Returns -1 if the end of the stream is reached. - public static System.Int32 ReadInput(System.IO.Stream sourceStream, sbyte[] target, int start, int count) - { - // Returns 0 bytes if not enough space in target - if (target.Length == 0) - return 0; - - byte[] receiver = new byte[target.Length]; - int bytesRead = sourceStream.Read(receiver, start, count); - - // Returns -1 if EOF - if (bytesRead == 0) - return -1; - - for (int i = start; i < start + bytesRead; i++) - target[i] = (sbyte)receiver[i]; - - return bytesRead; - } - - /// Reads a number of characters from the current source TextReader and writes the data to the target array at the specified index. - /// The source TextReader to read from - /// Contains the array of characteres read from the source TextReader. - /// The starting index of the target array. - /// The maximum number of characters to read from the source TextReader. - /// The number of characters read. The number will be less than or equal to count depending on the data available in the source TextReader. Returns -1 if the end of the stream is reached. - public static System.Int32 ReadInput(System.IO.TextReader sourceTextReader, sbyte[] target, int start, int count) - { - // Returns 0 bytes if not enough space in target - if (target.Length == 0) return 0; - - char[] charArray = new char[target.Length]; - int bytesRead = sourceTextReader.Read(charArray, start, count); - - // Returns -1 if EOF - if (bytesRead == 0) return -1; - - for (int index = start; index < start + bytesRead; index++) - target[index] = (sbyte)charArray[index]; - - return bytesRead; - } - - /*******************************/ - /// - /// The class performs token processing in strings - /// - public class Tokenizer : System.Collections.IEnumerator - { - /// Position over the string - private long currentPos = 0; - - /// Include demiliters in the results. - private bool includeDelims = false; - - /// Char representation of the String to tokenize. - private char[] chars = null; - - //The tokenizer uses the default delimiter set: the space character, the tab character, the newline character, and the carriage-return character and the form-feed character - private string delimiters = " \t\n\r\f"; - - /// - /// Initializes a new class instance with a specified string to process - /// - /// String to tokenize - public Tokenizer(System.String source) - { - this.chars = source.ToCharArray(); - } - - /// - /// Initializes a new class instance with a specified string to process - /// and the specified token delimiters to use - /// - /// String to tokenize - /// String containing the delimiters - public Tokenizer(System.String source, System.String delimiters) : this(source) - { - this.delimiters = delimiters; - } - - - /// - /// Initializes a new class instance with a specified string to process, the specified token - /// delimiters to use, and whether the delimiters must be included in the results. - /// - /// String to tokenize - /// String containing the delimiters - /// Determines if delimiters are included in the results. - public Tokenizer(System.String source, System.String delimiters, bool includeDelims) : this(source, delimiters) - { - this.includeDelims = includeDelims; - } - - - /// - /// Returns the next token from the token list - /// - /// The string value of the token - public System.String NextToken() - { - return NextToken(this.delimiters); - } - - /// - /// Returns the next token from the source string, using the provided - /// token delimiters - /// - /// String containing the delimiters to use - /// The string value of the token - public System.String NextToken(System.String delimiters) - { - //According to documentation, the usage of the received delimiters should be temporary (only for this call). - //However, it seems it is not true, so the following line is necessary. - this.delimiters = delimiters; - - //at the end - if (this.currentPos == this.chars.Length) - throw new System.ArgumentOutOfRangeException(); - //if over a delimiter and delimiters must be returned - else if ((System.Array.IndexOf(delimiters.ToCharArray(), chars[this.currentPos]) != -1) - && this.includeDelims) - return "" + this.chars[this.currentPos++]; - //need to get the token wo delimiters. - else - return nextToken(delimiters.ToCharArray()); - } - - //Returns the nextToken wo delimiters - private System.String nextToken(char[] delimiters) - { - string token = ""; - long pos = this.currentPos; - - //skip possible delimiters - while (System.Array.IndexOf(delimiters, this.chars[currentPos]) != -1) - //The last one is a delimiter (i.e there is no more tokens) - if (++this.currentPos == this.chars.Length) - { - this.currentPos = pos; - throw new System.ArgumentOutOfRangeException(); - } - - //getting the token - while (System.Array.IndexOf(delimiters, this.chars[this.currentPos]) == -1) - { - token += this.chars[this.currentPos]; - //the last one is not a delimiter - if (++this.currentPos == this.chars.Length) - break; - } - return token; - } - - - /// - /// Determines if there are more tokens to return from the source string - /// - /// True or false, depending if there are more tokens - public bool HasMoreTokens() - { - //keeping the current pos - long pos = this.currentPos; - - try - { - this.NextToken(); - } - catch (System.ArgumentOutOfRangeException) - { - return false; - } - finally - { - this.currentPos = pos; - } - return true; - } - - /// - /// Remaining tokens count - /// - public int Count - { - get - { - //keeping the current pos - long pos = this.currentPos; - int i = 0; - - try - { - while (true) - { - this.NextToken(); - i++; - } - } - catch (System.ArgumentOutOfRangeException) - { - this.currentPos = pos; - return i; - } - } - } - - /// - /// Performs the same action as NextToken. - /// - public System.Object Current - { - get - { - return (Object)this.NextToken(); - } - } - - /// - // Performs the same action as HasMoreTokens. - /// - /// True or false, depending if there are more tokens - public bool MoveNext() - { - return this.HasMoreTokens(); - } - - /// - /// Does nothing. - /// - public void Reset() - { - ; - } - } - /*******************************/ - /// - /// This class provides auxiliar functionality to read and unread characters from a string into a buffer. - /// - private class BackStringReader : System.IO.StringReader - { - private char[] buffer; - private int position = 1; - - /// - /// Constructor. Calls the base constructor. - /// - /// The buffer from which chars will be read. - /// The size of the Back buffer. - public BackStringReader(String s) : base(s) - { - this.buffer = new char[position]; - } - - - /// - /// Reads a character. - /// - /// The character read. - public override int Read() - { - if (this.position >= 0 && this.position < this.buffer.Length) - return (int)this.buffer[this.position++]; - return base.Read(); - } - - /// - /// Reads an amount of characters from the buffer and copies the values to the array passed. - /// - /// Array where the characters will be stored. - /// The beginning index to read. - /// The number of characters to read. - /// The number of characters read. - public override int Read(char[] array, int index, int count) - { - int readLimit = this.buffer.Length - this.position; - - if (count <= 0) - return 0; - - if (readLimit > 0) - { - if (count < readLimit) - readLimit = count; - System.Array.Copy(this.buffer, this.position, array, index, readLimit); - count -= readLimit; - index += readLimit; - this.position += readLimit; - } - - if (count > 0) - { - count = base.Read(array, index, count); - if (count == -1) - { - if (readLimit == 0) - return -1; - return readLimit; - } - return readLimit + count; - } - return readLimit; - } - - /// - /// Unreads a character. - /// - /// The character to be unread. - public void UnRead(int unReadChar) - { - this.position--; - this.buffer[this.position] = (char)unReadChar; - } - - /// - /// Unreads an amount of characters by moving these to the buffer. - /// - /// The character array to be unread. - /// The beginning index to unread. - /// The number of characters to unread. - public void UnRead(char[] array, int index, int count) - { - this.Move(array, index, count); - } - - /// - /// Unreads an amount of characters by moving these to the buffer. - /// - /// The character array to be unread. - public void UnRead(char[] array) - { - this.Move(array, 0, array.Length - 1); - } - - /// - /// Moves the array of characters to the buffer. - /// - /// Array of characters to move. - /// Offset of the beginning. - /// Amount of characters to move. - private void Move(char[] array, int index, int count) - { - for (int arrayPosition = index + count; arrayPosition >= index; arrayPosition--) - this.UnRead(array[arrayPosition]); - } - } - - /*******************************/ - - /// - /// The StreamTokenizerSupport class takes an input stream and parses it into "tokens". - /// The stream tokenizer can recognize identifiers, numbers, quoted strings, and various comment styles. - /// - public class StreamTokenizerSupport - { - - /// - /// Internal constants and fields - /// - - private const System.String TOKEN = "Token["; - private const System.String NOTHING = "NOTHING"; - private const System.String NUMBER = "number="; - private const System.String EOF = "EOF"; - private const System.String EOL = "EOL"; - private const System.String QUOTED = "quoted string="; - private const System.String LINE = "], Line "; - private const System.String DASH = "-."; - private const System.String DOT = "."; - - private const int TT_NOTHING = -4; - - private const sbyte ORDINARYCHAR = 0x00; - private const sbyte WORDCHAR = 0x01; - private const sbyte WHITESPACECHAR = 0x02; - private const sbyte COMMENTCHAR = 0x04; - private const sbyte QUOTECHAR = 0x08; - private const sbyte NUMBERCHAR = 0x10; - - private const int STATE_NEUTRAL = 0; - private const int STATE_WORD = 1; - private const int STATE_NUMBER1 = 2; - private const int STATE_NUMBER2 = 3; - private const int STATE_NUMBER3 = 4; - private const int STATE_NUMBER4 = 5; - private const int STATE_STRING = 6; - private const int STATE_LINECOMMENT = 7; - private const int STATE_DONE_ON_EOL = 8; - - private const int STATE_PROCEED_ON_EOL = 9; - private const int STATE_POSSIBLEC_COMMENT = 10; - private const int STATE_POSSIBLEC_COMMENT_END = 11; - private const int STATE_C_COMMENT = 12; - private const int STATE_STRING_ESCAPE_SEQ = 13; - private const int STATE_STRING_ESCAPE_SEQ_OCTAL = 14; - - private const int STATE_DONE = 100; - - private sbyte[] attribute = new sbyte[256]; - private bool eolIsSignificant = false; - private bool slashStarComments = false; - private bool slashSlashComments = false; - private bool lowerCaseMode = false; - private bool pushedback = false; - private int lineno = 1; - - private BackReader inReader; - private BackStringReader inStringReader; - private BackInputStream inStream; - private System.Text.StringBuilder buf; - - - /// - /// Indicates that the end of the stream has been read. - /// - public const int TT_EOF = -1; - - /// - /// Indicates that the end of the line has been read. - /// - public const int TT_EOL = '\n'; - - /// - /// Indicates that a number token has been read. - /// - public const int TT_NUMBER = -2; - - /// - /// Indicates that a word token has been read. - /// - public const int TT_WORD = -3; - - /// - /// If the current token is a number, this field contains the value of that number. - /// - public double nval; - - /// - /// If the current token is a word token, this field contains a string giving the characters of the word - /// token. - /// - public System.String sval; - - /// - /// After a call to the nextToken method, this field contains the type of the token just read. - /// - public int ttype; - - - /// - /// Internal methods - /// - - private int read() - { - if (this.inReader != null) - return this.inReader.Read(); - else if (this.inStream != null) - return this.inStream.Read(); - else - return this.inStringReader.Read(); - } - - private void unread(int ch) - { - if (this.inReader != null) - this.inReader.UnRead(ch); - else if (this.inStream != null) - this.inStream.UnRead(ch); - else - this.inStringReader.UnRead(ch); - } - - private void init() - { - this.buf = new System.Text.StringBuilder(); - this.ttype = StreamTokenizerSupport.TT_NOTHING; - - this.WordChars('A', 'Z'); - this.WordChars('a', 'z'); - this.WordChars(160, 255); - this.WhitespaceChars(0x00, 0x20); - this.CommentChar('/'); - this.QuoteChar('\''); - this.QuoteChar('\"'); - this.ParseNumbers(); - } - - private void setAttributes(int low, int hi, sbyte attrib) - { - int l = System.Math.Max(0, low); - int h = System.Math.Min(255, hi); - for (int i = l; i <= h; i++) - this.attribute[i] = attrib; - } - - private bool isWordChar(int data) - { - char ch = (char)data; - return (data != -1 && (ch > 255 || this.attribute[ch] == StreamTokenizerSupport.WORDCHAR || this.attribute[ch] == StreamTokenizerSupport.NUMBERCHAR)); - } - - /// - /// Creates a StreamToknizerSupport that parses the given string. - /// - /// The System.IO.StringReader that contains the String to be parsed. - public StreamTokenizerSupport(System.IO.StringReader reader) - { - string s = ""; - for (int i = reader.Read(); i != -1; i = reader.Read()) - { - s += (char)i; - } - reader.Close(); - this.inStringReader = new BackStringReader(s); - this.init(); - } - - /// - /// Creates a StreamTokenizerSupport that parses the given stream. - /// - /// Reader to be parsed. - public StreamTokenizerSupport(System.IO.StreamReader reader) - { - this.inReader = new BackReader(new System.IO.StreamReader(reader.BaseStream, reader.CurrentEncoding).BaseStream, 2, reader.CurrentEncoding); - this.init(); - } - - /// - /// Creates a StreamTokenizerSupport that parses the given stream. - /// - /// Stream to be parsed. - public StreamTokenizerSupport(System.IO.Stream stream) - { - this.inStream = new BackInputStream(new System.IO.BufferedStream(stream), 2); - this.init(); - } - - /// - /// Specified that the character argument starts a single-line comment. - /// - /// The character. - public virtual void CommentChar(int ch) - { - if (ch >= 0 && ch <= 255) - this.attribute[ch] = StreamTokenizerSupport.COMMENTCHAR; - } - - /// - /// Determines whether or not ends of line are treated as tokens. - /// - /// True indicates that end-of-line characters are separate tokens; False indicates - /// that end-of-line characters are white space. - public virtual void EOLIsSignificant(bool flag) - { - this.eolIsSignificant = flag; - } - - /// - /// Return the current line number. - /// - /// Current line number - public virtual int Lineno() - { - return this.lineno; - } - - /// - /// Determines whether or not word token are automatically lowercased. - /// - /// True indicates that all word tokens should be lowercased. - public virtual void LowerCaseMode(bool flag) - { - this.lowerCaseMode = flag; - } - - /// - /// Parses the next token from the input stream of this tokenizer. - /// - /// The value of the ttype field. - public virtual int NextToken() - { - char prevChar = (char)(0); - char ch = (char)(0); - char qChar = (char)(0); - int octalNumber = 0; - int state; - - if (this.pushedback) - { - this.pushedback = false; - return this.ttype; - } - - this.ttype = StreamTokenizerSupport.TT_NOTHING; - state = StreamTokenizerSupport.STATE_NEUTRAL; - this.nval = 0.0; - this.sval = null; - this.buf.Length = 0; - - do - { - int data = this.read(); - prevChar = ch; - ch = (char)data; - - switch (state) - { - case StreamTokenizerSupport.STATE_NEUTRAL: - { - if (data == -1) - { - this.ttype = TT_EOF; - state = StreamTokenizerSupport.STATE_DONE; - } - else if (ch > 255) - { - this.buf.Append(ch); - this.ttype = StreamTokenizerSupport.TT_WORD; - state = StreamTokenizerSupport.STATE_WORD; - } - else if (this.attribute[ch] == StreamTokenizerSupport.COMMENTCHAR) - { - state = StreamTokenizerSupport.STATE_LINECOMMENT; - } - else if (this.attribute[ch] == StreamTokenizerSupport.WORDCHAR) - { - this.buf.Append(ch); - this.ttype = StreamTokenizerSupport.TT_WORD; - state = StreamTokenizerSupport.STATE_WORD; - } - else if (this.attribute[ch] == StreamTokenizerSupport.NUMBERCHAR) - { - this.ttype = StreamTokenizerSupport.TT_NUMBER; - this.buf.Append(ch); - if (ch == '-') - state = StreamTokenizerSupport.STATE_NUMBER1; - else if (ch == '.') - state = StreamTokenizerSupport.STATE_NUMBER3; - else - state = StreamTokenizerSupport.STATE_NUMBER2; - } - else if (this.attribute[ch] == StreamTokenizerSupport.QUOTECHAR) - { - qChar = ch; - this.ttype = ch; - state = StreamTokenizerSupport.STATE_STRING; - } - else if ((this.slashSlashComments || this.slashStarComments) && ch == '/') - state = StreamTokenizerSupport.STATE_POSSIBLEC_COMMENT; - else if (this.attribute[ch] == StreamTokenizerSupport.ORDINARYCHAR) - { - this.ttype = ch; - state = StreamTokenizerSupport.STATE_DONE; - } - else if (ch == '\n' || ch == '\r') - { - this.lineno++; - if (this.eolIsSignificant) - { - this.ttype = StreamTokenizerSupport.TT_EOL; - if (ch == '\n') - state = StreamTokenizerSupport.STATE_DONE; - else if (ch == '\r') - state = StreamTokenizerSupport.STATE_DONE_ON_EOL; - } - else if (ch == '\r') - state = StreamTokenizerSupport.STATE_PROCEED_ON_EOL; - } - break; - } - case StreamTokenizerSupport.STATE_WORD: - { - if (this.isWordChar(data)) - this.buf.Append(ch); - else - { - if (data != -1) - this.unread(ch); - this.sval = this.buf.ToString(); - state = StreamTokenizerSupport.STATE_DONE; - } - break; - } - case StreamTokenizerSupport.STATE_NUMBER1: - { - if (data == -1 || this.attribute[ch] != StreamTokenizerSupport.NUMBERCHAR || ch == '-') - { - if (this.attribute[ch] == StreamTokenizerSupport.COMMENTCHAR && System.Char.IsNumber(ch)) - { - this.buf.Append(ch); - state = StreamTokenizerSupport.STATE_NUMBER2; - } - else - { - if (data != -1) - this.unread(ch); - this.ttype = '-'; - state = StreamTokenizerSupport.STATE_DONE; - } - } - else - { - this.buf.Append(ch); - if (ch == '.') - state = StreamTokenizerSupport.STATE_NUMBER3; - else - state = StreamTokenizerSupport.STATE_NUMBER2; - } - break; - } - case StreamTokenizerSupport.STATE_NUMBER2: - { - if (data == -1 || this.attribute[ch] != StreamTokenizerSupport.NUMBERCHAR || ch == '-') - { - if (System.Char.IsNumber(ch) && this.attribute[ch] == StreamTokenizerSupport.WORDCHAR) - { - this.buf.Append(ch); - } - else if (ch == '.' && this.attribute[ch] == StreamTokenizerSupport.WHITESPACECHAR) - { - this.buf.Append(ch); - } - - else if ((data != -1) && (this.attribute[ch] == StreamTokenizerSupport.COMMENTCHAR && System.Char.IsNumber(ch))) - { - this.buf.Append(ch); - } - else - { - if (data != -1) - this.unread(ch); - try - { - this.nval = System.Double.Parse(this.buf.ToString()); - } - catch (System.FormatException) { } - state = StreamTokenizerSupport.STATE_DONE; - } - } - else - { - this.buf.Append(ch); - if (ch == '.') - state = StreamTokenizerSupport.STATE_NUMBER3; - } - break; - } - case StreamTokenizerSupport.STATE_NUMBER3: - { - if (data == -1 || this.attribute[ch] != StreamTokenizerSupport.NUMBERCHAR || ch == '-' || ch == '.') - { - if (this.attribute[ch] == StreamTokenizerSupport.COMMENTCHAR && System.Char.IsNumber(ch)) - { - this.buf.Append(ch); - } - else - { - if (data != -1) - this.unread(ch); - System.String str = this.buf.ToString(); - if (str.Equals(StreamTokenizerSupport.DASH)) - { - this.unread('.'); - this.ttype = '-'; - } - else if (str.Equals(StreamTokenizerSupport.DOT) && !(StreamTokenizerSupport.WORDCHAR != this.attribute[prevChar])) - this.ttype = '.'; - else - { - try - { - this.nval = System.Double.Parse(str); - } - catch (System.FormatException) { } - } - state = StreamTokenizerSupport.STATE_DONE; - } - } - else - { - this.buf.Append(ch); - state = StreamTokenizerSupport.STATE_NUMBER4; - } - break; - } - case StreamTokenizerSupport.STATE_NUMBER4: - { - if (data == -1 || this.attribute[ch] != StreamTokenizerSupport.NUMBERCHAR || ch == '-' || ch == '.') - { - if (data != -1) - this.unread(ch); - try - { - this.nval = System.Double.Parse(this.buf.ToString()); - } - catch (System.FormatException) { } - state = StreamTokenizerSupport.STATE_DONE; - } - else - this.buf.Append(ch); - break; - } - case StreamTokenizerSupport.STATE_LINECOMMENT: - { - if (data == -1) - { - this.ttype = StreamTokenizerSupport.TT_EOF; - state = StreamTokenizerSupport.STATE_DONE; - } - else if (ch == '\n' || ch == '\r') - { - this.unread(ch); - state = StreamTokenizerSupport.STATE_NEUTRAL; - } - break; - } - case StreamTokenizerSupport.STATE_DONE_ON_EOL: - { - if (ch != '\n' && data != -1) - this.unread(ch); - state = StreamTokenizerSupport.STATE_DONE; - break; - } - case StreamTokenizerSupport.STATE_PROCEED_ON_EOL: - { - if (ch != '\n' && data != -1) - this.unread(ch); - state = StreamTokenizerSupport.STATE_NEUTRAL; - break; - } - case StreamTokenizerSupport.STATE_STRING: - { - if (data == -1 || ch == qChar || ch == '\r' || ch == '\n') - { - this.sval = this.buf.ToString(); - if (ch == '\r' || ch == '\n') - this.unread(ch); - state = StreamTokenizerSupport.STATE_DONE; - } - else if (ch == '\\') - state = StreamTokenizerSupport.STATE_STRING_ESCAPE_SEQ; - else - this.buf.Append(ch); - break; - } - case StreamTokenizerSupport.STATE_STRING_ESCAPE_SEQ: - { - if (data == -1) - { - this.sval = this.buf.ToString(); - state = StreamTokenizerSupport.STATE_DONE; - break; - } - - state = StreamTokenizerSupport.STATE_STRING; - if (ch == 'a') - this.buf.Append(0x7); - else if (ch == 'b') - this.buf.Append('\b'); - else if (ch == 'f') - this.buf.Append(0xC); - else if (ch == 'n') - this.buf.Append('\n'); - else if (ch == 'r') - this.buf.Append('\r'); - else if (ch == 't') - this.buf.Append('\t'); - else if (ch == 'v') - this.buf.Append(0xB); - else if (ch >= '0' && ch <= '7') - { - octalNumber = ch - '0'; - state = StreamTokenizerSupport.STATE_STRING_ESCAPE_SEQ_OCTAL; - } - else - this.buf.Append(ch); - break; - } - case StreamTokenizerSupport.STATE_STRING_ESCAPE_SEQ_OCTAL: - { - if (data == -1 || ch < '0' || ch > '7') - { - this.buf.Append((char)octalNumber); - if (data == -1) - { - this.sval = buf.ToString(); - state = StreamTokenizerSupport.STATE_DONE; - } - else - { - this.unread(ch); - state = StreamTokenizerSupport.STATE_STRING; - } - } - else - { - int temp = octalNumber * 8 + (ch - '0'); - if (temp < 256) - octalNumber = temp; - else - { - buf.Append((char)octalNumber); - buf.Append(ch); - state = StreamTokenizerSupport.STATE_STRING; - } - } - break; - } - case StreamTokenizerSupport.STATE_POSSIBLEC_COMMENT: - { - if (ch == '*') - state = StreamTokenizerSupport.STATE_C_COMMENT; - else if (ch == '/') - state = StreamTokenizerSupport.STATE_LINECOMMENT; - else - { - if (data != -1) - this.unread(ch); - this.ttype = '/'; - state = StreamTokenizerSupport.STATE_DONE; - } - break; - } - case StreamTokenizerSupport.STATE_C_COMMENT: - { - if (ch == '*') - state = StreamTokenizerSupport.STATE_POSSIBLEC_COMMENT_END; - if (ch == '\n') - this.lineno++; - else if (data == -1) - { - this.ttype = StreamTokenizerSupport.TT_EOF; - state = StreamTokenizerSupport.STATE_DONE; - } - break; - } - case StreamTokenizerSupport.STATE_POSSIBLEC_COMMENT_END: - { - if (data == -1) - { - this.ttype = StreamTokenizerSupport.TT_EOF; - state = StreamTokenizerSupport.STATE_DONE; - } - else if (ch == '/') - state = StreamTokenizerSupport.STATE_NEUTRAL; - else if (ch != '*') - state = StreamTokenizerSupport.STATE_C_COMMENT; - break; - } - } - } - while (state != StreamTokenizerSupport.STATE_DONE); - - if (this.ttype == StreamTokenizerSupport.TT_WORD && this.lowerCaseMode) - this.sval = this.sval.ToLower(); - - return this.ttype; - } - - /// - /// Specifies that the character argument is "ordinary" in this tokenizer. - /// - /// The character. - public virtual void OrdinaryChar(int ch) - { - if (ch >= 0 && ch <= 255) - this.attribute[ch] = StreamTokenizerSupport.ORDINARYCHAR; - } - - /// - /// Specifies that all characters c in the range low less-equal c less-equal high are "ordinary" in this - /// tokenizer. - /// - /// Low end of the range. - /// High end of the range. - public virtual void OrdinaryChars(int low, int hi) - { - this.setAttributes(low, hi, StreamTokenizerSupport.ORDINARYCHAR); - } - - /// - /// Specifies that numbers should be parsed by this tokenizer. - /// - public virtual void ParseNumbers() - { - for (int i = '0'; i <= '9'; i++) - this.attribute[i] = StreamTokenizerSupport.NUMBERCHAR; - this.attribute['.'] = StreamTokenizerSupport.NUMBERCHAR; - this.attribute['-'] = StreamTokenizerSupport.NUMBERCHAR; - } - - /// - /// Causes the next call to the nextToken method of this tokenizer to return the current value in the - /// ttype field, and not to modify the value in the nval or sval field. - /// - public virtual void PushBack() - { - if (this.ttype != StreamTokenizerSupport.TT_NOTHING) - this.pushedback = true; - } - - /// - /// Specifies that matching pairs of this character delimit string constants in this tokenizer. - /// - /// The character. - public virtual void QuoteChar(int ch) - { - if (ch >= 0 && ch <= 255) - this.attribute[ch] = QUOTECHAR; - } - - /// - /// Resets this tokenizer's syntax table so that all characters are "ordinary." See the ordinaryChar - /// method for more information on a character being ordinary. - /// - public virtual void ResetSyntax() - { - this.OrdinaryChars(0x00, 0xff); - } - - /// - /// Determines whether or not the tokenizer recognizes C++-style comments. - /// - /// True indicates to recognize and ignore C++-style comments. - public virtual void SlashSlashComments(bool flag) - { - this.slashSlashComments = flag; - } - - /// - /// Determines whether or not the tokenizer recognizes C-style comments. - /// - /// True indicates to recognize and ignore C-style comments. - public virtual void SlashStarComments(bool flag) - { - this.slashStarComments = flag; - } - - /// - /// Returns the string representation of the current stream token. - /// - /// A String representation of the current stream token. - public override System.String ToString() - { - System.Text.StringBuilder buffer = new System.Text.StringBuilder(StreamTokenizerSupport.TOKEN); - - switch (this.ttype) - { - case StreamTokenizerSupport.TT_NOTHING: - { - buffer.Append(StreamTokenizerSupport.NOTHING); - break; - } - case StreamTokenizerSupport.TT_WORD: - { - buffer.Append(this.sval); - break; - } - case StreamTokenizerSupport.TT_NUMBER: - { - buffer.Append(StreamTokenizerSupport.NUMBER); - buffer.Append(this.nval); - break; - } - case StreamTokenizerSupport.TT_EOF: - { - buffer.Append(StreamTokenizerSupport.EOF); - break; - } - case StreamTokenizerSupport.TT_EOL: - { - buffer.Append(StreamTokenizerSupport.EOL); - break; - } - } - - if (this.ttype > 0) - { - if (this.attribute[this.ttype] == StreamTokenizerSupport.QUOTECHAR) - { - buffer.Append(StreamTokenizerSupport.QUOTED); - buffer.Append(this.sval); - } - else - { - buffer.Append('\''); - buffer.Append((char)this.ttype); - buffer.Append('\''); - } - } - - buffer.Append(StreamTokenizerSupport.LINE); - buffer.Append(this.lineno); - return buffer.ToString(); - } - - /// - /// Specifies that all characters c in the range low less-equal c less-equal high are white space - /// characters. - /// - /// The low end of the range. - /// The high end of the range. - public virtual void WhitespaceChars(int low, int hi) - { - this.setAttributes(low, hi, StreamTokenizerSupport.WHITESPACECHAR); - } - - /// - /// Specifies that all characters c in the range low less-equal c less-equal high are word constituents. - /// - /// The low end of the range. - /// The high end of the range. - public virtual void WordChars(int low, int hi) - { - this.setAttributes(low, hi, StreamTokenizerSupport.WORDCHAR); - } - } - - - /*******************************/ - /// - /// This class provides functionality to reads and unread characters into a buffer. - /// - public class BackReader : System.IO.StreamReader - { - private char[] buffer; - private int position = 1; - //private int markedPosition; - - /// - /// Constructor. Calls the base constructor. - /// - /// The buffer from which chars will be read. - /// The size of the Back buffer. - public BackReader(System.IO.Stream streamReader, int size, System.Text.Encoding encoding) : base(streamReader, encoding) - { - this.buffer = new char[size]; - this.position = size; - } - - /// - /// Constructor. Calls the base constructor. - /// - /// The buffer from which chars will be read. - public BackReader(System.IO.Stream streamReader, System.Text.Encoding encoding) : base(streamReader, encoding) - { - this.buffer = new char[this.position]; - } - - /// - /// Checks if this stream support mark and reset methods. - /// - /// - /// This method isn't supported. - /// - /// Always false. - public bool MarkSupported() - { - return false; - } - - /// - /// Marks the element at the corresponding position. - /// - /// - /// This method isn't supported. - /// - public void Mark(int position) - { - throw new System.IO.IOException("Mark operations are not allowed"); - } - - /// - /// Resets the current stream. - /// - /// - /// This method isn't supported. - /// - public void Reset() - { - throw new System.IO.IOException("Mark operations are not allowed"); - } - - /// - /// Reads a character. - /// - /// The character read. - public override int Read() - { - if (this.position >= 0 && this.position < this.buffer.Length) - return (int)this.buffer[this.position++]; - return base.Read(); - } - - /// - /// Reads an amount of characters from the buffer and copies the values to the array passed. - /// - /// Array where the characters will be stored. - /// The beginning index to read. - /// The number of characters to read. - /// The number of characters read. - public override int Read(char[] array, int index, int count) - { - int readLimit = this.buffer.Length - this.position; - - if (count <= 0) - return 0; - - if (readLimit > 0) - { - if (count < readLimit) - readLimit = count; - System.Array.Copy(this.buffer, this.position, array, index, readLimit); - count -= readLimit; - index += readLimit; - this.position += readLimit; - } - - if (count > 0) - { - count = base.Read(array, index, count); - if (count == -1) - { - if (readLimit == 0) - return -1; - return readLimit; - } - return readLimit + count; - } - return readLimit; - } - - /// - /// Checks if this buffer is ready to be read. - /// - /// True if the position is less than the length, otherwise false. - public bool IsReady() - { - return (this.position >= this.buffer.Length || this.BaseStream.Position >= this.BaseStream.Length); - } - - /// - /// Unreads a character. - /// - /// The character to be unread. - public void UnRead(int unReadChar) - { - this.position--; - this.buffer[this.position] = (char)unReadChar; - } - - /// - /// Unreads an amount of characters by moving these to the buffer. - /// - /// The character array to be unread. - /// The beginning index to unread. - /// The number of characters to unread. - public void UnRead(char[] array, int index, int count) - { - this.Move(array, index, count); - } - - /// - /// Unreads an amount of characters by moving these to the buffer. - /// - /// The character array to be unread. - public void UnRead(char[] array) - { - this.Move(array, 0, array.Length - 1); - } - - /// - /// Moves the array of characters to the buffer. - /// - /// Array of characters to move. - /// Offset of the beginning. - /// Amount of characters to move. - private void Move(char[] array, int index, int count) - { - for (int arrayPosition = index + count; arrayPosition >= index; arrayPosition--) - this.UnRead(array[arrayPosition]); - } - } - - - /*******************************/ - /// - /// Provides functionality to read and unread from a Stream. - /// - public class BackInputStream : System.IO.BinaryReader - { - private byte[] buffer; - private int position = 1; - - /// - /// Creates a BackInputStream with the specified stream and size for the buffer. - /// - /// The stream to use. - /// The specific size of the buffer. - public BackInputStream(System.IO.Stream streamReader, System.Int32 size) : base(streamReader) - { - this.buffer = new byte[size]; - this.position = size; - } - - /// - /// Creates a BackInputStream with the specified stream. - /// - /// The stream to use. - public BackInputStream(System.IO.Stream streamReader) : base(streamReader) - { - this.buffer = new byte[this.position]; - } - - /// - /// Checks if this stream support mark and reset methods. - /// - /// Always false, these methods aren't supported. - public bool MarkSupported() - { - return false; - } - - /// - /// Reads the next bytes in the stream. - /// - /// The next byte readed - public override int Read() - { - if (position >= 0 && position < buffer.Length) - return (int)this.buffer[position++]; - return base.Read(); - } - - /// - /// Reads the amount of bytes specified from the stream. - /// - /// The buffer to read data into. - /// The beginning point to read. - /// The number of characters to read. - /// The number of characters read into buffer. - public virtual int Read(sbyte[] array, int index, int count) - { - int byteCount = 0; - int readLimit = count + index; - byte[] aux = ToByteArray(array); - - for (byteCount = 0; position < buffer.Length && index < readLimit; byteCount++) - aux[index++] = buffer[position++]; - - if (index < readLimit) - byteCount += base.Read(aux, index, readLimit - index); - - for (int i = 0; i < aux.Length; i++) - array[i] = (sbyte)aux[i]; - - return byteCount; - } - - /// - /// Unreads a byte from the stream. - /// - /// The value to be unread. - public void UnRead(int element) - { - this.position--; - if (position >= 0) - this.buffer[this.position] = (byte)element; - } - - /// - /// Unreads an amount of bytes from the stream. - /// - /// The byte array to be unread. - /// The beginning index to unread. - /// The number of bytes to be unread. - public void UnRead(byte[] array, int index, int count) - { - this.Move(array, index, count); - } - - /// - /// Unreads an array of bytes from the stream. - /// - /// The byte array to be unread. - public void UnRead(byte[] array) - { - this.Move(array, 0, array.Length - 1); - } - - /// - /// Skips the specified number of bytes from the underlying stream. - /// - /// The number of bytes to be skipped. - /// The number of bytes actually skipped - public long Skip(long numberOfBytes) - { - return this.BaseStream.Seek(numberOfBytes, System.IO.SeekOrigin.Current) - this.BaseStream.Position; - } - - /// - /// Moves data from the array to the buffer field. - /// - /// The array of bytes to be unread. - /// The beginning index to unread. - /// The amount of bytes to be unread. - private void Move(byte[] array, int index, int count) - { - for (int arrayPosition = index + count; arrayPosition >= index; arrayPosition--) - this.UnRead(array[arrayPosition]); - } - } - - - /*******************************/ - /// - /// Support class used to handle threads - /// - public class ThreadClass : IThreadRunnable - { - /// - /// The instance of System.Threading.Thread - /// - private System.Threading.Thread threadField; - - /// - /// Initializes a new instance of the ThreadClass class - /// - public ThreadClass() - { - threadField = new System.Threading.Thread(new System.Threading.ThreadStart(Run)); - } - - /// - /// Initializes a new instance of the Thread class. - /// - /// The name of the thread - public ThreadClass(System.String Name) - { - threadField = new System.Threading.Thread(new System.Threading.ThreadStart(Run)); - this.Name = Name; - } - - /// - /// Initializes a new instance of the Thread class. - /// - /// A ThreadStart delegate that references the methods to be invoked when this thread begins executing - public ThreadClass(System.Threading.ThreadStart Start) - { - threadField = new System.Threading.Thread(Start); - } - - /// - /// Initializes a new instance of the Thread class. - /// - /// A ThreadStart delegate that references the methods to be invoked when this thread begins executing - /// The name of the thread - public ThreadClass(System.Threading.ThreadStart Start, System.String Name) - { - threadField = new System.Threading.Thread(Start); - this.Name = Name; - } - - /// - /// This method has no functionality unless the method is overridden - /// - public virtual void Run() - { - } - - /// - /// Causes the operating system to change the state of the current thread instance to ThreadState.Running - /// - public virtual void Start() - { - threadField.Start(); - } - - /// - /// Interrupts a thread that is in the WaitSleepJoin thread state - /// - public virtual void Interrupt() - { - threadField.Interrupt(); - } - - /// - /// Gets the current thread instance - /// - public System.Threading.Thread Instance - { - get - { - return threadField; - } - set - { - threadField = value; - } - } - - /// - /// Gets or sets the name of the thread - /// - public System.String Name - { - get - { - return threadField.Name; - } - set - { - if (threadField.Name == null) - threadField.Name = value; - } - } - - /// - /// Gets or sets a value indicating the scheduling priority of a thread - /// - public System.Threading.ThreadPriority Priority - { - get - { - return threadField.Priority; - } - set - { - threadField.Priority = value; - } - } - - /// - /// Gets a value indicating the execution status of the current thread - /// - public bool IsAlive - { - get - { - return threadField.IsAlive; - } - } - - /// - /// Gets or sets a value indicating whether or not a thread is a background thread. - /// - public bool IsBackground - { - get - { - return threadField.IsBackground; - } - set - { - threadField.IsBackground = value; - } - } - - /// - /// Blocks the calling thread until a thread terminates - /// - public void Join() - { - threadField.Join(); - } - - /// - /// Blocks the calling thread until a thread terminates or the specified time elapses - /// - /// Time of wait in milliseconds - public void Join(long MiliSeconds) - { - lock (this) - { - threadField.Join(new System.TimeSpan(MiliSeconds * 10000)); - } - } - - /// - /// Blocks the calling thread until a thread terminates or the specified time elapses - /// - /// Time of wait in milliseconds - /// Time of wait in nanoseconds - public void Join(long MiliSeconds, int NanoSeconds) - { - lock (this) - { - threadField.Join(new System.TimeSpan(MiliSeconds * 10000 + NanoSeconds * 100)); - } - } - /* - /// - /// Resumes a thread that has been suspended - /// - public void Resume() - { - threadField.Resume(); - } - - /// - /// Raises a ThreadAbortException in the thread on which it is invoked, - /// to begin the process of terminating the thread. Calling this method - /// usually terminates the thread - /// - public void Abort() - { - threadField.Abort(); - } - - - /// - /// Raises a ThreadAbortException in the thread on which it is invoked, - /// to begin the process of terminating the thread while also providing - /// exception information about the thread termination. - /// Calling this method usually terminates the thread. - /// - /// An object that contains application-specific information, such as state, which can be used by the thread being aborted - public void Abort(System.Object stateInfo) - { - lock(this) - { - threadField.Abort(stateInfo); - } - } - - /// - /// Suspends the thread, if the thread is already suspended it has no effect - /// - public void Suspend() - { - threadField.Suspend(); - } - */ - - /// - /// Obtain a String that represents the current Object - /// - /// A String that represents the current Object - public override System.String ToString() - { - return "Thread[" + Name + "," + Priority.ToString() + "," + "" + "]"; - } - - /// - /// Gets the currently running thread - /// - /// The currently running thread - public static ThreadClass Current() - { - ThreadClass CurrentThread = new ThreadClass(); - CurrentThread.Instance = System.Threading.Thread.CurrentThread; - return CurrentThread; - } - } - - - /*******************************/ - /// - /// SupportClass for the Stack class. - /// - public class StackSupport - { - /// - /// Removes the element at the top of the stack and returns it. - /// - /// The stack where the element at the top will be returned and removed. - /// The element at the top of the stack. - public static System.Object Pop(System.Collections.ArrayList stack) - { - System.Object obj = stack[stack.Count - 1]; - stack.RemoveAt(stack.Count - 1); - - return obj; - } - } - - -} diff --git a/CSJ2K/j2k/IntegerSpec.cs b/CSJ2K/j2k/IntegerSpec.cs deleted file mode 100644 index c9c180d9..00000000 --- a/CSJ2K/j2k/IntegerSpec.cs +++ /dev/null @@ -1,427 +0,0 @@ -/* -* CVS identifier: -* -* $Id: IntegerSpec.java,v 1.14 2001/09/20 12:31:08 grosbois Exp $ -* -* Class: IntegerSpec -* -* Description: Holds specs corresponding to an Integer -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.util; -namespace CSJ2K.j2k -{ - - /// This class extends ModuleSpec and is responsible of Integer specifications - /// for each tile-component. - /// - /// - /// - /// - /// - public class IntegerSpec : ModuleSpec - { - /// Gets the maximum value of all tile-components. - /// - /// - /// The maximum value - /// - /// - virtual public int Max - { - get - { - int max = ((System.Int32)def); - int tmp; - - for (int t = 0; t < nTiles; t++) - { - for (int c = 0; c < nComp; c++) - { - tmp = ((System.Int32)getSpec(t, c)); - if (max < tmp) - max = tmp; - } - } - - return max; - } - - } - /// Get the minimum value of all tile-components. - /// - /// - /// The minimum value - /// - /// - virtual public int Min - { - get - { - int min = ((System.Int32)def); - int tmp; - - for (int t = 0; t < nTiles; t++) - { - for (int c = 0; c < nComp; c++) - { - tmp = ((System.Int32)getSpec(t, c)); - if (min > tmp) - min = tmp; - } - } - - return min; - } - - } - - - /// The largest value of type int - protected internal static int MAX_INT = System.Int32.MaxValue; - - /// Constructs a new 'IntegerSpec' for the specified number of tiles and - /// components and with allowed type of specifications. This constructor is - /// normally called at decoder side. - /// - /// - /// The number of tiles - /// - /// - /// The number of components - /// - /// - /// The type of allowed specifications - /// - /// - public IntegerSpec(int nt, int nc, byte type) : base(nt, nc, type) - { - } - - /// Constructs a new 'IntegerSpec' for the specified number of tiles and - /// components, the allowed specifications type and the ParameterList - /// instance. This constructor is normally called at encoder side and parse - /// arguments of specified option. - /// - /// - /// The number of tiles - /// - /// - /// The number of components - /// - /// - /// The allowed specifications type - /// - /// - /// The ParameterList instance - /// - /// - /// The name of the option to process - /// - /// - public IntegerSpec(int nt, int nc, byte type, ParameterList pl, System.String optName) : base(nt, nc, type) - { - - System.Int32 value_Renamed; - System.String param = pl.getParameter(optName); - - if (param == null) - { - // No parameter specified - param = pl.DefaultParameterList.getParameter(optName); - try - { - setDefault((System.Object)System.Int32.Parse(param)); - } - catch (System.FormatException) - { - throw new System.ArgumentException("Non recognized value" + " for option -" + optName + ": " + param); - } - return; - } - - // Parse argument - SupportClass.Tokenizer stk = new SupportClass.Tokenizer(param); - System.String word; // current word - byte curSpecType = SPEC_DEF; // Specification type of the - // current parameter - bool[] tileSpec = null; // Tiles concerned by the specification - bool[] compSpec = null; // Components concerned by the specification - - while (stk.HasMoreTokens()) - { - word = stk.NextToken(); - - switch (word[0]) - { - - case 't': // Tiles specification - tileSpec = parseIdx(word, nTiles); - if (curSpecType == SPEC_COMP_DEF) - { - curSpecType = SPEC_TILE_COMP; - } - else - { - curSpecType = SPEC_TILE_DEF; - } - break; - - case 'c': // Components specification - compSpec = parseIdx(word, nComp); - if (curSpecType == SPEC_TILE_DEF) - { - curSpecType = SPEC_TILE_COMP; - } - else - { - curSpecType = SPEC_COMP_DEF; - } - break; - - default: - try - { - value_Renamed = System.Int32.Parse(word); - } - catch (System.FormatException) - { - throw new System.ArgumentException("Non recognized value" + " for option -" + optName + ": " + word); - } - - if (curSpecType == SPEC_DEF) - { - setDefault((System.Object)value_Renamed); - } - else if (curSpecType == SPEC_TILE_DEF) - { - for (int i = tileSpec.Length - 1; i >= 0; i--) - if (tileSpec[i]) - { - setTileDef(i, (System.Object)value_Renamed); - } - } - else if (curSpecType == SPEC_COMP_DEF) - { - for (int i = compSpec.Length - 1; i >= 0; i--) - if (compSpec[i]) - { - setCompDef(i, (System.Object)value_Renamed); - } - } - else - { - for (int i = tileSpec.Length - 1; i >= 0; i--) - { - for (int j = compSpec.Length - 1; j >= 0; j--) - { - if (tileSpec[i] && compSpec[j]) - { - setTileCompVal(i, j, (System.Object)value_Renamed); - } - } - } - } - - // Re-initialize - curSpecType = SPEC_DEF; - tileSpec = null; - compSpec = null; - break; - - } - } - - // Check that default value has been specified - if (getDefault() == null) - { - int ndefspec = 0; - for (int t = nt - 1; t >= 0; t--) - { - for (int c = nc - 1; c >= 0; c--) - { - if (specValType[t][c] == SPEC_DEF) - { - ndefspec++; - } - } - } - - // If some tile-component have received no specification, it takes - // the default value defined in ParameterList - if (ndefspec != 0) - { - param = pl.DefaultParameterList.getParameter(optName); - try - { - setDefault((System.Object)System.Int32.Parse(param)); - } - catch (System.FormatException) - { - throw new System.ArgumentException("Non recognized value" + " for option -" + optName + ": " + param); - } - } - else - { - // All tile-component have been specified, takes the first - // tile-component value as default. - setDefault(getTileCompVal(0, 0)); - switch (specValType[0][0]) - { - - case SPEC_TILE_DEF: - for (int c = nc - 1; c >= 0; c--) - { - if (specValType[0][c] == SPEC_TILE_DEF) - specValType[0][c] = SPEC_DEF; - } - tileDef[0] = null; - break; - - case SPEC_COMP_DEF: - for (int t = nt - 1; t >= 0; t--) - { - if (specValType[t][0] == SPEC_COMP_DEF) - specValType[t][0] = SPEC_DEF; - } - compDef[0] = null; - break; - - case SPEC_TILE_COMP: - specValType[0][0] = SPEC_DEF; - tileCompVal["t0c0"] = null; - break; - } - } - } - } - - /// Gets the maximum value of each tile for specified component - /// - /// - /// The component index - /// - /// - /// The maximum value - /// - /// - public virtual int getMaxInComp(int c) - { - int max = 0; - int tmp; - - for (int t = 0; t < nTiles; t++) - { - tmp = ((System.Int32)getSpec(t, c)); - if (max < tmp) - max = tmp; - } - - return max; - } - - /// Gets the minimum value of all tiles for the specified component. - /// - /// - /// The component index - /// - /// - /// The minimum value - /// - /// - public virtual int getMinInComp(int c) - { - int min = MAX_INT; // Big value - int tmp; - - for (int t = 0; t < nTiles; t++) - { - tmp = ((System.Int32)getSpec(t, c)); - if (min > tmp) - min = tmp; - } - - return min; - } - - /// Gets the maximum value of all components in the specified tile. - /// - /// - /// The tile index - /// - /// - /// The maximum value - /// - /// - public virtual int getMaxInTile(int t) - { - int max = 0; - int tmp; - - for (int c = 0; c < nComp; c++) - { - tmp = ((System.Int32)getSpec(t, c)); - if (max < tmp) - max = tmp; - } - - return max; - } - - /// Gets the minimum value of each component in specified tile - /// - /// - /// The tile index - /// - /// - /// The minimum value - /// - /// - public virtual int getMinInTile(int t) - { - int min = MAX_INT; // Big value - int tmp; - - for (int c = 0; c < nComp; c++) - { - tmp = ((System.Int32)getSpec(t, c)); - if (min > tmp) - min = tmp; - } - - return min; - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/JJ2KExceptionHandler.cs b/CSJ2K/j2k/JJ2KExceptionHandler.cs deleted file mode 100644 index 3f05c6b1..00000000 --- a/CSJ2K/j2k/JJ2KExceptionHandler.cs +++ /dev/null @@ -1,93 +0,0 @@ -/* -* CVS identifier: -* -* $Id: JJ2KExceptionHandler.java,v 1.6 2000/09/05 09:22:08 grosbois Exp $ -* -* Class: JJ2KExceptionHandler -* -* Description: A class to handle exceptions -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* -* -* -*/ -namespace CSJ2K.j2k -{ - - /// This class handles exceptions. It should be used in places where it - /// is not known how to handle the exception, and the exception can not - /// be thrown higher in the stack. - /// - ///

Different options can be registered for each Thread and - /// ThreadGroup. This feature is not implemented yet - /// - ///

- public class JJ2KExceptionHandler - { - - /// Handles the exception. If no special action is registered for - /// the current thread, then the Exception's stack trace and a - /// descriptive message are printed to standard error and the - /// current thread is stopped. - /// - ///

Registration of special actions is not implemented yet. - /// - ///

- /// The exception to handle - /// - /// - /// - /// - //UPGRADE_NOTE: Exception 'java.lang.Throwable' was converted to 'System.Exception' which has different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1100'" - public static void handleException(System.Exception e) - { - // Test if there is an special action (not implemented yet) - - // If no special action - - // Print the Exception message and stack to standard error - // including this method in the stack. - //UPGRADE_ISSUE: Method 'java.lang.Throwable.fillInStackTrace' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javalangThrowablefillInStackTrace'" - //e.fillInStackTrace(); - //SupportClass.WriteStackTrace(e, Console.Error); - // Print an explicative message - System.Console.Error.WriteLine("The Thread is being terminated bacause an " + "Exception (shown above)\n" + "has been thrown and no special action was " + "defined for this Thread."); - // Stop the thread (do not use stop, since it's deprecated in - // Java 1.2) - //UPGRADE_NOTE: Exception 'java.lang.ThreadDeath' was converted to 'System.ApplicationException' which has different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1100'" - throw e; - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/JJ2KInfo.cs b/CSJ2K/j2k/JJ2KInfo.cs deleted file mode 100644 index 0938da7e..00000000 --- a/CSJ2K/j2k/JJ2KInfo.cs +++ /dev/null @@ -1,66 +0,0 @@ -/* -* CVS identifier: -* -* $Id: JJ2KInfo.java,v 1.28 2002/07/30 10:12:38 grosbois Exp $ -* -* Class: JJ2KInfo -* -* Description: Holds general JJ2000 informartion (version, -* copyright, etc.) -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -namespace CSJ2K.j2k -{ - - /// This class holds general JJ2000 information, such as the version number, - /// copyright, contact address, etc. - /// - /// - public class JJ2KInfo - { - - /// The version number (such as 2.0, 2.1.1, etc.) - public const System.String version = "5.1"; - - /// The copyright message string. Double newlines separate paragraphs. - /// Newlines should be respected when displaying the message. - /// - /// - public const System.String copyright = "This software module was originally developed by Rapha\u00ebl " + "Grosbois " + "and Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); " + "Joel Askel\u00f6f (Ericsson Radio Systems AB); and Bertrand " + "Berthelot, " + "David Bouchard, F\u00e9lix Henry, Gerard Mozelle and Patrice Onno " + "(Canon" + " Research Centre " + "France S.A) in the course of development of the JPEG 2000 standard " + "as " + "specified by ISO/IEC 15444 (JPEG 2000 Standard). This software " + "module is an implementation of a part of the JPEG 2000 Standard. " + "Swiss Federal Institute of Technology-EPFL, Ericsson Radio Systems " + "AB and Canon Research Centre France S.A (collectively JJ2000 " + "Partners) agree not to assert against ISO/IEC and users of the JPEG " + "2000 Standard (Users) any of their rights under the copyright, not " + "including other intellectual property rights, for this software " + "module with respect to the usage by ISO/IEC and Users of this " + "software module or modifications thereof for use in hardware or " + "software products claiming conformance to the JPEG 2000 Standard. " + "Those intending to use this software module in hardware or software " + "products are advised that their use may infringe existing patents. " + "The original developers of this software module, JJ2000 Partners " + "and " + "ISO/IEC assume no liability for use of this software module or " + "modifications thereof. No license or right to this software module " + "is granted for non JPEG 2000 Standard conforming products. JJ2000 " + "Partners have full right to use this software module for his/her " + "own purpose, assign or donate this software module to any third " + "party and to inhibit third parties from using this software module " + "for non JPEG 2000 Standard conforming products. This copyright " + "notice must be included in all copies or derivative works of this " + "software module.\n\nCopyright (c) 1999/2000 JJ2000 Partners."; - - /// The bug reporting e-mail address - public const System.String bugaddr = "jj2000-bugs@ltssg3.epfl.ch"; - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/ModuleSpec.cs b/CSJ2K/j2k/ModuleSpec.cs deleted file mode 100644 index cccb9bdf..00000000 --- a/CSJ2K/j2k/ModuleSpec.cs +++ /dev/null @@ -1,715 +0,0 @@ -/* -* CVS identifier: -* -* $Id: ModuleSpec.java,v 1.24 2001/10/26 16:30:11 grosbois Exp $ -* -* Class: ModuleSpec -* -* Description: Generic class for storing module specs -* -* from WTFilterSpec (Diego Santa Cruz) -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.image; -namespace CSJ2K.j2k -{ - - /// This generic class is used to handle values to be used by a module for each - /// tile and component. It uses attribute to determine which value to use. It - /// should be extended by each module needing this feature. - /// - /// This class might be used for values that are only tile specific or - /// component specific but not both. - /// - ///

The attributes to use are defined by a hierarchy. The hierarchy is: - /// - ///

    - ///
  • Tile and component specific attribute
  • - ///
  • Tile specific default attribute
  • - ///
  • Component main default attribute
  • - ///
  • Main default attribute
  • - ///

- /// - ///
- public class ModuleSpec : System.ICloneable - { - virtual public ModuleSpec Copy - { - get - { - return (ModuleSpec)this.Clone(); - } - - } - - /// The identifier for a specification module that applies only to - /// components - /// - public const byte SPEC_TYPE_COMP = 0; - - /// The identifier for a specification module that applies only to tiles - public const byte SPEC_TYPE_TILE = 1; - - /// The identifier for a specification module that applies both to tiles - /// and components - /// - public const byte SPEC_TYPE_TILE_COMP = 2; - - /// The identifier for default specification - public const byte SPEC_DEF = 0; - - /// The identifier for "component default" specification - public const byte SPEC_COMP_DEF = 1; - - /// The identifier for "tile default" specification - public const byte SPEC_TILE_DEF = 2; - - /// The identifier for a "tile-component" specification - public const byte SPEC_TILE_COMP = 3; - - /// The type of the specification module - protected internal int specType; - - /// The number of tiles - protected internal int nTiles = 0; - - /// The number of components - protected internal int nComp = 0; - - /// The spec type for each tile-component. The first index is the tile - /// index, the second is the component index. - /// - protected internal byte[][] specValType; - - /// Default value for each tile-component - protected internal System.Object def = null; - - /// The default value for each component. Null if no component - /// specific value is defined - /// - protected internal System.Object[] compDef = null; - - /// The default value for each tile. Null if no tile specific value is - /// defined - /// - protected internal System.Object[] tileDef = null; - - /// The specific value for each tile-component. Value of tile 16 component - /// 3 is accessible through the hash value "t16c3". Null if no - /// tile-component specific value is defined - /// - protected internal System.Collections.Hashtable tileCompVal; - - public virtual System.Object Clone() - { - ModuleSpec ms; - try - { - ms = (ModuleSpec)base.MemberwiseClone(); - } - //UPGRADE_NOTE: Exception 'java.lang.CloneNotSupportedException' was converted to 'System.Exception' which has different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1100'" - catch (System.Exception) - { - throw new System.ApplicationException("Error when cloning ModuleSpec instance"); - } - // Create a copy of the specValType array - ms.specValType = new byte[nTiles][]; - for (int i = 0; i < nTiles; i++) - { - ms.specValType[i] = new byte[nComp]; - } - for (int t = 0; t < nTiles; t++) - { - for (int c = 0; c < nComp; c++) - { - ms.specValType[t][c] = specValType[t][c]; - } - } - // Create a copy of tileDef - if (tileDef != null) - { - ms.tileDef = new System.Object[nTiles]; - for (int t = 0; t < nTiles; t++) - { - ms.tileDef[t] = tileDef[t]; - } - } - // Create a copy of tileCompVal - if (tileCompVal != null) - { - ms.tileCompVal = System.Collections.Hashtable.Synchronized(new System.Collections.Hashtable()); - System.String tmpKey; - System.Object tmpVal; - //UPGRADE_TODO: Method 'java.util.Enumeration.hasMoreElements' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationhasMoreElements'" - for (System.Collections.IEnumerator e = tileCompVal.Keys.GetEnumerator(); e.MoveNext();) - { - //UPGRADE_TODO: Method 'java.util.Enumeration.nextElement' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationnextElement'" - tmpKey = ((System.String)e.Current); - tmpVal = tileCompVal[tmpKey]; - ms.tileCompVal[tmpKey] = tmpVal; - } - } - return ms; - } - - /// Rotate the ModuleSpec instance by 90 degrees (this modifies only tile - /// and tile-component specifications). - /// - /// - /// Number of tiles along horizontal and vertical axis after - /// rotation. - /// - /// - public virtual void rotate90(Coord anT) - { - // Rotate specValType - byte[][] tmpsvt = new byte[nTiles][]; - int ax, ay; - Coord bnT = new Coord(anT.y, anT.x); - for (int by = 0; by < bnT.y; by++) - { - for (int bx = 0; bx < bnT.x; bx++) - { - ay = bx; - ax = bnT.y - by - 1; - tmpsvt[ay * anT.x + ax] = specValType[by * bnT.x + bx]; - } - } - specValType = tmpsvt; - - // Rotate tileDef - if (tileDef != null) - { - System.Object[] tmptd = new System.Object[nTiles]; - for (int by = 0; by < bnT.y; by++) - { - for (int bx = 0; bx < bnT.x; bx++) - { - ay = bx; - ax = bnT.y - by - 1; - tmptd[ay * anT.x + ax] = tileDef[by * bnT.x + bx]; - } - } - tileDef = tmptd; - } - - // Rotate tileCompVal - if (tileCompVal != null && tileCompVal.Count > 0) - { - System.Collections.Hashtable tmptcv = System.Collections.Hashtable.Synchronized(new System.Collections.Hashtable()); - System.String tmpKey; - System.Object tmpVal; - int btIdx, atIdx; - int i1, i2; - int bx, by; - //UPGRADE_TODO: Method 'java.util.Enumeration.hasMoreElements' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationhasMoreElements'" - for (System.Collections.IEnumerator e = tileCompVal.Keys.GetEnumerator(); e.MoveNext();) - { - //UPGRADE_TODO: Method 'java.util.Enumeration.nextElement' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationnextElement'" - tmpKey = ((System.String)e.Current); - tmpVal = tileCompVal[tmpKey]; - i1 = tmpKey.IndexOf('t'); - i2 = tmpKey.IndexOf('c'); - btIdx = (System.Int32.Parse(tmpKey.Substring(i1 + 1, (i2) - (i1 + 1)))); - bx = btIdx % bnT.x; - by = btIdx / bnT.x; - ay = bx; - ax = bnT.y - by - 1; - atIdx = ax + ay * anT.x; - tmptcv["t" + atIdx + tmpKey.Substring(i2)] = tmpVal; - } - tileCompVal = tmptcv; - } - } - - /// Constructs a 'ModuleSpec' object, initializing all the components and - /// tiles to the 'SPEC_DEF' spec val type, for the specified number of - /// components and tiles. - /// - /// - /// The number of tiles - /// - /// - /// The number of components - /// - /// - /// the type of the specification module i.e. tile specific, - /// component specific or both. - /// - /// - public ModuleSpec(int nt, int nc, byte type) - { - nTiles = nt; - nComp = nc; - specValType = new byte[nt][]; - for (int i = 0; i < nt; i++) - { - specValType[i] = new byte[nc]; - } - switch (type) - { - - case SPEC_TYPE_TILE: - specType = SPEC_TYPE_TILE; - break; - - case SPEC_TYPE_COMP: - specType = SPEC_TYPE_COMP; - break; - - case SPEC_TYPE_TILE_COMP: - specType = SPEC_TYPE_TILE_COMP; - break; - } - } - - /// Sets default value for this module - /// - /// - public virtual void setDefault(System.Object value_Renamed) - { - def = value_Renamed; - } - - /// Gets default value for this module. - /// - /// - /// The default value (Must be casted before use) - /// - /// - public virtual System.Object getDefault() - { - return def; - } - - /// Sets default value for specified component and specValType tag if - /// allowed by its priority. - /// - /// - /// Component index - /// - /// - public virtual void setCompDef(int c, System.Object value_Renamed) - { - if (specType == SPEC_TYPE_TILE) - { - //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Object.toString' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" - System.String errMsg = "Option whose value is '" + value_Renamed + "' cannot be " + "specified for components as it is a 'tile only' specific " + "option"; - throw new System.ApplicationException(errMsg); - } - if (compDef == null) - { - compDef = new System.Object[nComp]; - } - for (int i = 0; i < nTiles; i++) - { - if (specValType[i][c] < SPEC_COMP_DEF) - { - specValType[i][c] = SPEC_COMP_DEF; - } - } - compDef[c] = value_Renamed; - } - - /// Gets default value of the specified component. If no specification have - /// been entered for this component, returns default value. - /// - /// - /// Component index - /// - /// - /// The default value for this component (Must be casted before - /// use) - /// - /// - /// - /// - /// - public virtual System.Object getCompDef(int c) - { - if (specType == SPEC_TYPE_TILE) - { - throw new System.ApplicationException("Illegal use of ModuleSpec class"); - } - if (compDef == null || compDef[c] == null) - { - return getDefault(); - } - else - { - return compDef[c]; - } - } - - /// Sets default value for specified tile and specValType tag if allowed by - /// its priority. - /// - /// - /// Tile index. - /// - /// - public virtual void setTileDef(int t, System.Object value_Renamed) - { - if (specType == SPEC_TYPE_COMP) - { - //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Object.toString' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" - System.String errMsg = "Option whose value is '" + value_Renamed + "' cannot be " + "specified for tiles as it is a 'component only' specific " + "option"; - throw new System.ApplicationException(errMsg); - } - if (tileDef == null) - { - tileDef = new System.Object[nTiles]; - } - for (int i = 0; i < nComp; i++) - { - if (specValType[t][i] < SPEC_TILE_DEF) - { - specValType[t][i] = SPEC_TILE_DEF; - } - } - tileDef[t] = value_Renamed; - } - - /// Gets default value of the specified tile. If no specification has been - /// entered, it returns the default value. - /// - /// - /// Tile index - /// - /// - /// The default value for this tile (Must be casted before use) - /// - /// - /// - /// - /// - public virtual System.Object getTileDef(int t) - { - if (specType == SPEC_TYPE_COMP) - { - throw new System.ApplicationException("Illegal use of ModuleSpec class"); - } - if (tileDef == null || tileDef[t] == null) - { - return getDefault(); - } - else - { - return tileDef[t]; - } - } - - /// Sets value for specified tile-component. - /// - /// - /// Tie index - /// - /// - /// Component index - /// - /// - public virtual void setTileCompVal(int t, int c, System.Object value_Renamed) - { - if (specType != SPEC_TYPE_TILE_COMP) - { - //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Object.toString' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" - System.String errMsg = "Option whose value is '" + value_Renamed + "' cannot be " + "specified for "; - switch (specType) - { - - case SPEC_TYPE_TILE: - errMsg += "components as it is a 'tile only' specific option"; - break; - - case SPEC_TYPE_COMP: - errMsg += "tiles as it is a 'component only' specific option"; - break; - } - throw new System.ApplicationException(errMsg); - } - if (tileCompVal == null) - tileCompVal = System.Collections.Hashtable.Synchronized(new System.Collections.Hashtable()); - specValType[t][c] = SPEC_TILE_COMP; - tileCompVal["t" + t + "c" + c] = value_Renamed; - } - - /// Gets value of specified tile-component. This method calls getSpec but - /// has a public access. - /// - /// - /// Tile index - /// - /// - /// Component index - /// - /// - /// The value of this tile-component (Must be casted before use) - /// - /// - /// - /// - /// - /// - /// - /// - public virtual System.Object getTileCompVal(int t, int c) - { - if (specType != SPEC_TYPE_TILE_COMP) - { - throw new System.ApplicationException("Illegal use of ModuleSpec class"); - } - return getSpec(t, c); - } - - /// Gets value of specified tile-component without knowing if a specific - /// tile-component value has been previously entered. It first check if a - /// tile-component specific value has been entered, then if a tile specific - /// value exist, then if a component specific value exist. If not the - /// default value is returned. - /// - /// - /// Tile index - /// - /// - /// Component index - /// - /// - /// Value for this tile component. - /// - /// - protected internal virtual System.Object getSpec(int t, int c) - { - switch (specValType[t][c]) - { - - case SPEC_DEF: - return getDefault(); - - case SPEC_COMP_DEF: - return getCompDef(c); - - case SPEC_TILE_DEF: - return getTileDef(t); - - case SPEC_TILE_COMP: - return tileCompVal["t" + t + "c" + c]; - - default: - throw new System.ArgumentException("Not recognized spec type"); - - } - } - - /// Return the spec type of the given tile-component. - /// - /// - /// Tile index - /// - /// - /// Component index - /// - /// - public virtual byte getSpecValType(int t, int c) - { - return specValType[t][c]; - } - - /// Whether or not specifications have been entered for the given - /// component. - /// - /// - /// Index of the component - /// - /// - /// True if component specification has been defined - /// - /// - public virtual bool isCompSpecified(int c) - { - if (compDef == null || compDef[c] == null) - { - return false; - } - else - { - return true; - } - } - - /// Whether or not specifications have been entered for the given tile. - /// - /// - /// Index of the tile - /// - /// - /// True if tile specification has been entered - /// - /// - public virtual bool isTileSpecified(int t) - { - if (tileDef == null || tileDef[t] == null) - { - return false; - } - else - { - return true; - } - } - - /// Whether or not a tile-component specification has been defined - /// - /// - /// Tile index - /// - /// - /// Component index - /// - /// - /// True if a tile-component specification has been defined. - /// - /// - public virtual bool isTileCompSpecified(int t, int c) - { - if (tileCompVal == null || tileCompVal["t" + t + "c" + c] == null) - { - return false; - } - else - { - return true; - } - } - - /// This method is responsible of parsing tile indexes set and component - /// indexes set for an option. Such an argument must follow the following - /// policy:
- /// - /// t<indexes set> or c<indexes set> where - /// tile or component indexes are separated by commas or a dashes. - /// - ///

Example:
- ///

  • t0,3,4 means tiles with indexes 0, 3 and 4.
    - ///
  • t2-4 means tiles with indexes 2,3 and 4.
    - /// - /// It returns a boolean array skteching which tile or component are - /// concerned by the next parameters. - /// - ///
  • - /// The word to parse. - /// - /// - /// Maximum authorized index - /// - /// - /// Indexes concerned by this parameter. - /// - /// - public static bool[] parseIdx(System.String word, int maxIdx) - { - int nChar = word.Length; // Number of characters - char c = word[0]; // current character - int idx = -1; // Current (tile or component) index - int lastIdx = -1; // Last (tile or component) index - bool isDash = false; // Whether or not last separator was a dash - - bool[] idxSet = new bool[maxIdx]; - int i = 1; // index of the current character - - while (i < nChar) - { - c = word[i]; - if (System.Char.IsDigit(c)) - { - if (idx == -1) - { - idx = 0; - } - idx = idx * 10 + (c - '0'); - } - else - { - if (idx == -1 || (c != ',' && c != '-')) - { - throw new System.ArgumentException("Bad construction for " + "parameter: " + word); - } - if (idx < 0 || idx >= maxIdx) - { - throw new System.ArgumentException("Out of range index " + "in " + "parameter `" + word + "' : " + idx); - } - - // Found a comma - if (c == ',') - { - if (isDash) - { - // Previously found a dash, fill idxSet - for (int j = lastIdx + 1; j < idx; j++) - { - idxSet[j] = true; - } - } - isDash = false; - } - else - { - // Found a dash - isDash = true; - } - - // Udate idxSet - idxSet[idx] = true; - lastIdx = idx; - idx = -1; - } - i++; - } - - // Process last found index - if (idx < 0 || idx >= maxIdx) - { - throw new System.ArgumentException("Out of range index in " + "parameter `" + word + "' : " + idx); - } - if (isDash) - { - for (int j = lastIdx + 1; j < idx; j++) - { - idxSet[j] = true; - } - } - idxSet[idx] = true; - - return idxSet; - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/NoNextElementException.cs b/CSJ2K/j2k/NoNextElementException.cs deleted file mode 100644 index 1b2b1fa5..00000000 --- a/CSJ2K/j2k/NoNextElementException.cs +++ /dev/null @@ -1,80 +0,0 @@ -/* -* CVS identifier: -* -* $Id: NoNextElementException.java,v 1.9 2000/09/05 09:22:12 grosbois Exp $ -* -* Class: NoNextElementException -* -* Description: Exception to indicate that there is no next -* element. -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* -* -* -*/ -using System; -namespace CSJ2K.j2k -{ - - /// This exception is thrown whenever a next???? method is called and - /// there is no next element to return. - /// - /// - [Serializable] - public class NoNextElementException : System.SystemException - { - - /// Constructs a new NoNextElementException exception with no - /// detail message. - /// - /// - /// - public NoNextElementException() : base() - { - } - - /// Constructs a new NoNextElementException exception with - /// the specified detail message. - /// - /// - /// The detail message. - /// - /// - /// - public NoNextElementException(System.String s) : base(s) - { - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/StringSpec.cs b/CSJ2K/j2k/StringSpec.cs deleted file mode 100644 index 311c20d5..00000000 --- a/CSJ2K/j2k/StringSpec.cs +++ /dev/null @@ -1,276 +0,0 @@ -/* -* CVS identifier: -* -* $Id: StringSpec.java,v 1.17 2000/11/30 13:14:07 grosbois Exp $ -* -* Class: StringSpec -* -* Description: String specification for an option -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.util; -namespace CSJ2K.j2k -{ - - /// This class extends ModuleSpec class in order to hold tile-component - /// specifications using Strings. - /// - /// - /// - /// - /// - public class StringSpec : ModuleSpec - { - - /// Constructs an empty 'StringSpec' with specified number of - /// tile and components. This constructor is called by the decoder. - /// - /// - /// Number of tiles - /// - /// - /// Number of components - /// - /// - /// the type of the specification module i.e. tile specific, - /// component specific or both. - /// - /// - public StringSpec(int nt, int nc, byte type) : base(nt, nc, type) - { - } - - /// Constructs a new 'StringSpec' for the specified number of - /// components:tiles and the arguments of optName - /// option. This constructor is called by the encoder. It also - /// checks that the arguments belongs to the recognized arguments - /// list. - /// - ///

    Note: The arguments must not start with 't' or 'c' - /// since it is reserved for respectively tile and components - /// indexes specification. - /// - ///

    - /// The number of tiles - /// - /// - /// The number of components - /// - /// - /// the type of the specification module i.e. tile specific, - /// component specific or both. - /// - /// - /// of the option using boolean spec. - /// - /// - /// The list of all recognized argument in a String array - /// - /// - /// The ParameterList - /// - /// - public StringSpec(int nt, int nc, byte type, System.String optName, System.String[] list, ParameterList pl) : base(nt, nc, type) - { - - System.String param = pl.getParameter(optName); - bool recognized = false; - - if (param == null) - { - param = pl.DefaultParameterList.getParameter(optName); - for (int i = list.Length - 1; i >= 0; i--) - if (param.ToUpper().Equals(list[i].ToUpper())) - recognized = true; - if (!recognized) - throw new System.ArgumentException("Default parameter of " + "option -" + optName + " not" + " recognized: " + param); - setDefault(param); - return; - } - - // Parse argument - SupportClass.Tokenizer stk = new SupportClass.Tokenizer(param); - System.String word; // current word - byte curSpecType = SPEC_DEF; // Specification type of the - // current parameter - bool[] tileSpec = null; // Tiles concerned by the - // specification - bool[] compSpec = null; // Components concerned by the specification - //System.Boolean value_Renamed; - - while (stk.HasMoreTokens()) - { - word = stk.NextToken(); - - switch (word[0]) - { - - case 't': // Tiles specification - tileSpec = parseIdx(word, nTiles); - if (curSpecType == SPEC_COMP_DEF) - { - curSpecType = SPEC_TILE_COMP; - } - else - { - curSpecType = SPEC_TILE_DEF; - } - break; - - case 'c': // Components specification - compSpec = parseIdx(word, nComp); - if (curSpecType == SPEC_TILE_DEF) - { - curSpecType = SPEC_TILE_COMP; - } - else - curSpecType = SPEC_COMP_DEF; - break; - - default: - recognized = false; - - for (int i = list.Length - 1; i >= 0; i--) - if (word.ToUpper().Equals(list[i].ToUpper())) - recognized = true; - if (!recognized) - throw new System.ArgumentException("Default parameter of " + "option -" + optName + " not" + " recognized: " + word); - - if (curSpecType == SPEC_DEF) - { - setDefault(word); - } - else if (curSpecType == SPEC_TILE_DEF) - { - for (int i = tileSpec.Length - 1; i >= 0; i--) - if (tileSpec[i]) - { - setTileDef(i, word); - } - } - else if (curSpecType == SPEC_COMP_DEF) - { - for (int i = compSpec.Length - 1; i >= 0; i--) - if (compSpec[i]) - { - setCompDef(i, word); - } - } - else - { - for (int i = tileSpec.Length - 1; i >= 0; i--) - { - for (int j = compSpec.Length - 1; j >= 0; j--) - { - if (tileSpec[i] && compSpec[j]) - { - setTileCompVal(i, j, word); - } - } - } - } - - // Re-initialize - curSpecType = SPEC_DEF; - tileSpec = null; - compSpec = null; - break; - - } - } - - // Check that default value has been specified - if (getDefault() == null) - { - int ndefspec = 0; - for (int t = nt - 1; t >= 0; t--) - { - for (int c = nc - 1; c >= 0; c--) - { - if (specValType[t][c] == SPEC_DEF) - { - ndefspec++; - } - } - } - - // If some tile-component have received no specification, it takes - // the default value defined in ParameterList - if (ndefspec != 0) - { - param = pl.DefaultParameterList.getParameter(optName); - for (int i = list.Length - 1; i >= 0; i--) - if (param.ToUpper().Equals(list[i].ToUpper())) - recognized = true; - if (!recognized) - throw new System.ArgumentException("Default parameter of " + "option -" + optName + " not" + " recognized: " + param); - setDefault(param); - } - else - { - // All tile-component have been specified, takes the first - // tile-component value as default. - setDefault(getSpec(0, 0)); - switch (specValType[0][0]) - { - - case SPEC_TILE_DEF: - for (int c = nc - 1; c >= 0; c--) - { - if (specValType[0][c] == SPEC_TILE_DEF) - specValType[0][c] = SPEC_DEF; - } - tileDef[0] = null; - break; - - case SPEC_COMP_DEF: - for (int t = nt - 1; t >= 0; t--) - { - if (specValType[t][0] == SPEC_COMP_DEF) - specValType[t][0] = SPEC_DEF; - } - compDef[0] = null; - break; - - case SPEC_TILE_COMP: - specValType[0][0] = SPEC_DEF; - tileCompVal["t0c0"] = null; - break; - } - } - } - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/codestream/CBlkCoordInfo.cs b/CSJ2K/j2k/codestream/CBlkCoordInfo.cs deleted file mode 100644 index bb16675d..00000000 --- a/CSJ2K/j2k/codestream/CBlkCoordInfo.cs +++ /dev/null @@ -1,90 +0,0 @@ -/* -* CVS identifier: -* -* $Id: CBlkCoordInfo.java,v 1.9 2001/09/14 09:32:53 grosbois Exp $ -* -* Class: CBlkCoordInfo -* -* Description: Used to store the code-blocks coordinates. -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.image; -namespace CSJ2K.j2k.codestream -{ - - /// This class is used to store the coordinates of code-blocks. - /// - /// - public class CBlkCoordInfo : CoordInfo - { - - /// The code-block horizontal and vertical indexes - public Coord idx; - - /// Constructor. Creates a CBlkCoordInfo object. - /// - /// - public CBlkCoordInfo() - { - this.idx = new Coord(); - } - - /// Constructor. Creates a CBlkCoordInfo object width specified code-block - /// vertical and horizontal indexes. - /// - /// - /// Code-block vertical index. - /// - /// - /// Code-block horizontal index. - /// - /// - public CBlkCoordInfo(int m, int n) - { - this.idx = new Coord(n, m); - } - - /// Returns code-block's information in a String - /// - /// - /// String with code-block's information - /// - /// - public override System.String ToString() - { - return base.ToString() + ",idx=" + idx; - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/codestream/CoordInfo.cs b/CSJ2K/j2k/codestream/CoordInfo.cs deleted file mode 100644 index 43aaf6ef..00000000 --- a/CSJ2K/j2k/codestream/CoordInfo.cs +++ /dev/null @@ -1,114 +0,0 @@ -/* -* CVS identifier: -* -* $Id: CoordInfo.java,v 1.10 2001/09/14 09:32:11 grosbois Exp $ -* -* Class: CoordInfo -* -* Description: Used to store the coordinates of code-blocks/packets -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -namespace CSJ2K.j2k.codestream -{ - - /// This class is used to store the coordinates of objects such as code-blocks - /// or precincts. As this is an abstract class, it cannot be used directly but - /// derived classes have been created for code-blocks and packets - /// (CBlkCoordInfo and PrecCoordInfo). - /// - /// - /// - /// - /// - /// - /// - public abstract class CoordInfo - { - - /// Horizontal upper left coordinate in the subband - public int ulx; - - /// Vertical upper left coordinate in the subband - public int uly; - - /// Object's width - public int w; - - /// Object's height - public int h; - - /// Constructor. Creates a CoordInfo object. - /// - /// - /// The horizontal upper left coordinate in the subband - /// - /// - /// The vertical upper left coordinate in the subband - /// - /// - /// The width - /// - /// - /// The height - /// - /// - /// The object's index - /// - /// - public CoordInfo(int ulx, int uly, int w, int h) - { - this.ulx = ulx; - this.uly = uly; - this.w = w; - this.h = h; - } - - /// Empty contructor - public CoordInfo() - { - } - - /// Returns object's information in a String - /// - /// - /// String with object's information - /// - /// - public override System.String ToString() - { - return "ulx=" + ulx + ",uly=" + uly + ",w=" + w + ",h=" + h; - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/codestream/CorruptedCodestreamException.cs b/CSJ2K/j2k/codestream/CorruptedCodestreamException.cs deleted file mode 100644 index f2cd0593..00000000 --- a/CSJ2K/j2k/codestream/CorruptedCodestreamException.cs +++ /dev/null @@ -1,77 +0,0 @@ -/* -* CVS identifier: -* -* $Id: CorruptedCodestreamException.java,v 1.6 2000/09/05 09:22:33 grosbois -* Exp $ -* -* Class: CorruptedCodestreamException -* -* Description: Exception thrown when illegal bit stream -* values are decoded. -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using System; -namespace CSJ2K.j2k.codestream -{ - - /// This exception is thrown whenever an illegal value is read from a bit - /// stream. The cause can be either a corrupted bit stream, or a a bit stream - /// which is illegal. - /// - /// - [Serializable] - public class CorruptedCodestreamException : System.IO.IOException - { - - /// Constructs a new CorruptedCodestreamException exception with - /// no detail message. - /// - /// - public CorruptedCodestreamException() : base() - { - } - - /// Constructs a new CorruptedCodestreamException exception with - /// the specified detail message. - /// - /// - /// The detail message. - /// - /// - public CorruptedCodestreamException(System.String s) : base(s) - { - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/codestream/HeaderInfo.cs b/CSJ2K/j2k/codestream/HeaderInfo.cs deleted file mode 100644 index 917ca577..00000000 --- a/CSJ2K/j2k/codestream/HeaderInfo.cs +++ /dev/null @@ -1,1368 +0,0 @@ -/* -* CVS identifier: -* -* $Id: HeaderInfo.java,v 1.3 2001/10/26 16:30:33 grosbois Exp $ -* -* Class: HeaderInfo -* -* Description: Holds information found in main and tile-part -* headers -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.wavelet; -namespace CSJ2K.j2k.codestream -{ - - /// Classe that holds information found in the marker segments of the main and - /// tile-part headers. There is one inner-class per marker segment type found - /// in these headers. - /// - /// - public class HeaderInfo : FilterTypes, System.ICloneable - { - /// Returns a new instance of SIZ - virtual public SIZ NewSIZ - { - get - { - return new SIZ(this); - } - - } - /// Returns a new instance of SOT - virtual public SOT NewSOT - { - get - { - return new SOT(this); - } - - } - /// Returns a new instance of COD - virtual public COD NewCOD - { - get - { - return new COD(this); - } - - } - /// Returns a new instance of COC - virtual public COC NewCOC - { - get - { - return new COC(this); - } - - } - /// Returns a new instance of RGN - virtual public RGN NewRGN - { - get - { - return new RGN(this); - } - - } - /// Returns a new instance of QCD - virtual public QCD NewQCD - { - get - { - return new QCD(this); - } - - } - /// Returns a new instance of QCC - virtual public QCC NewQCC - { - get - { - return new QCC(this); - } - - } - /// Returns a new instance of POC - virtual public POC NewPOC - { - get - { - return new POC(this); - } - - } - /// Returns a new instance of CRG - virtual public CRG NewCRG - { - get - { - return new CRG(this); - } - - } - /// Returns a new instance of COM - virtual public COM NewCOM - { - get - { - ncom++; return new COM(this); - } - - } - /// Returns the number of found COM marker segments - virtual public int NumCOM - { - get - { - return ncom; - } - - } - - //UPGRADE_NOTE: Field 'EnclosingInstance' was added to class 'SIZ' to access its enclosing instance. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1019'" - /// Internal class holding information found in the SIZ marker segment - public class SIZ : System.ICloneable - { - public SIZ(HeaderInfo enclosingInstance) - { - InitBlock(enclosingInstance); - } - private void InitBlock(HeaderInfo enclosingInstance) - { - this.enclosingInstance = enclosingInstance; - } - private HeaderInfo enclosingInstance; - virtual public int MaxCompWidth - { - get - { - if (compWidth == null) - { - compWidth = new int[csiz]; - for (int cc = 0; cc < csiz; cc++) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - compWidth[cc] = (int)(System.Math.Ceiling((xsiz) / (double)xrsiz[cc]) - System.Math.Ceiling(x0siz / (double)xrsiz[cc])); - } - } - if (maxCompWidth == -1) - { - for (int c = 0; c < csiz; c++) - { - if (compWidth[c] > maxCompWidth) - { - maxCompWidth = compWidth[c]; - } - } - } - return maxCompWidth; - } - - } - virtual public int MaxCompHeight - { - get - { - if (compHeight == null) - { - compHeight = new int[csiz]; - for (int cc = 0; cc < csiz; cc++) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - compHeight[cc] = (int)(System.Math.Ceiling((ysiz) / (double)yrsiz[cc]) - System.Math.Ceiling(y0siz / (double)yrsiz[cc])); - } - } - if (maxCompHeight == -1) - { - for (int c = 0; c < csiz; c++) - { - if (compHeight[c] != maxCompHeight) - { - maxCompHeight = compHeight[c]; - } - } - } - return maxCompHeight; - } - - } - virtual public int NumTiles - { - get - { - if (numTiles == -1) - { - numTiles = ((xsiz - xt0siz + xtsiz - 1) / xtsiz) * ((ysiz - yt0siz + ytsiz - 1) / ytsiz); - } - return numTiles; - } - - } - virtual public SIZ Copy - { - get - { - SIZ ms = null; - try - { - ms = (SIZ)this.Clone(); - } - //UPGRADE_NOTE: Exception 'java.lang.CloneNotSupportedException' was converted to 'System.Exception' which has different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1100'" - catch (System.Exception) - { - throw new System.ApplicationException("Cannot clone SIZ marker segment"); - } - return ms; - } - - } - public HeaderInfo Enclosing_Instance - { - get - { - return enclosingInstance; - } - - } - public int lsiz; - public int rsiz; - public int xsiz; - public int ysiz; - public int x0siz; - public int y0siz; - public int xtsiz; - public int ytsiz; - public int xt0siz; - public int yt0siz; - public int csiz; - public int[] ssiz; - public int[] xrsiz; - public int[] yrsiz; - - /// Component widths - private int[] compWidth = null; - /// Maximum width among all components - private int maxCompWidth = -1; - /// Component heights - private int[] compHeight = null; - /// Maximum height among all components - private int maxCompHeight = -1; - /// Width of the specified tile-component - /// - /// - /// Tile index - /// - /// - /// Component index - /// - /// - public virtual int getCompImgWidth(int c) - { - if (compWidth == null) - { - compWidth = new int[csiz]; - for (int cc = 0; cc < csiz; cc++) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - compWidth[cc] = (int)(System.Math.Ceiling((xsiz) / (double)xrsiz[cc]) - System.Math.Ceiling(x0siz / (double)xrsiz[cc])); - } - } - return compWidth[c]; - } - public virtual int getCompImgHeight(int c) - { - if (compHeight == null) - { - compHeight = new int[csiz]; - for (int cc = 0; cc < csiz; cc++) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - compHeight[cc] = (int)(System.Math.Ceiling((ysiz) / (double)yrsiz[cc]) - System.Math.Ceiling(y0siz / (double)yrsiz[cc])); - } - } - return compHeight[c]; - } - private int numTiles = -1; - private bool[] origSigned = null; - public virtual bool isOrigSigned(int c) - { - if (origSigned == null) - { - origSigned = new bool[csiz]; - for (int cc = 0; cc < csiz; cc++) - { - origSigned[cc] = ((SupportClass.URShift(ssiz[cc], CSJ2K.j2k.codestream.Markers.SSIZ_DEPTH_BITS)) == 1); - } - } - return origSigned[c]; - } - private int[] origBitDepth = null; - public virtual int getOrigBitDepth(int c) - { - if (origBitDepth == null) - { - origBitDepth = new int[csiz]; - for (int cc = 0; cc < csiz; cc++) - { - origBitDepth[cc] = (ssiz[cc] & ((1 << CSJ2K.j2k.codestream.Markers.SSIZ_DEPTH_BITS) - 1)) + 1; - } - } - return origBitDepth[c]; - } - - /// Display information found in SIZ marker segment - public override System.String ToString() - { - System.String str = "\n --- SIZ (" + lsiz + " bytes) ---\n"; - str += (" Capabilities : " + rsiz + "\n"); - str += (" Image dim. : " + (xsiz - x0siz) + "x" + (ysiz - y0siz) + ", (off=" + x0siz + "," + y0siz + ")\n"); - str += (" Tile dim. : " + xtsiz + "x" + ytsiz + ", (off=" + xt0siz + "," + yt0siz + ")\n"); - str += (" Component(s) : " + csiz + "\n"); - str += " Orig. depth : "; - for (int i = 0; i < csiz; i++) - { - str += (getOrigBitDepth(i) + " "); - } - str += "\n"; - str += " Orig. signed : "; - for (int i = 0; i < csiz; i++) - { - str += (isOrigSigned(i) + " "); - } - str += "\n"; - str += " Subs. factor : "; - for (int i = 0; i < csiz; i++) - { - str += (xrsiz[i] + "," + yrsiz[i] + " "); - } - str += "\n"; - return str; - } - //UPGRADE_TODO: The following method was automatically generated and it must be implemented in order to preserve the class logic. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1232'" - virtual public System.Object Clone() - { - return null; - } - } - - //UPGRADE_NOTE: Field 'EnclosingInstance' was added to class 'SOT' to access its enclosing instance. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1019'" - /// Internal class holding information found in the SOt marker segments - public class SOT - { - public SOT(HeaderInfo enclosingInstance) - { - InitBlock(enclosingInstance); - } - private void InitBlock(HeaderInfo enclosingInstance) - { - this.enclosingInstance = enclosingInstance; - } - private HeaderInfo enclosingInstance; - public HeaderInfo Enclosing_Instance - { - get - { - return enclosingInstance; - } - - } - public int lsot; - public int isot; - public int psot; - public int tpsot; - public int tnsot; - - /// Display information found in this SOT marker segment - public override System.String ToString() - { - System.String str = "\n --- SOT (" + lsot + " bytes) ---\n"; - str += ("Tile index : " + isot + "\n"); - str += ("Tile-part length : " + psot + " bytes\n"); - str += ("Tile-part index : " + tpsot + "\n"); - str += ("Num. of tile-parts : " + tnsot + "\n"); - str += "\n"; - return str; - } - } - - //UPGRADE_NOTE: Field 'EnclosingInstance' was added to class 'COD' to access its enclosing instance. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1019'" - /// Internal class holding information found in the COD marker segments - public class COD : System.ICloneable - { - public COD(HeaderInfo enclosingInstance) - { - InitBlock(enclosingInstance); - } - private void InitBlock(HeaderInfo enclosingInstance) - { - this.enclosingInstance = enclosingInstance; - } - private HeaderInfo enclosingInstance; - virtual public COD Copy - { - get - { - COD ms = null; - try - { - ms = (COD)this.Clone(); - } - //UPGRADE_NOTE: Exception 'java.lang.CloneNotSupportedException' was converted to 'System.Exception' which has different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1100'" - catch (System.Exception) - { - throw new System.ApplicationException("Cannot clone SIZ marker segment"); - } - return ms; - } - - } - public HeaderInfo Enclosing_Instance - { - get - { - return enclosingInstance; - } - - } - public int lcod; - public int scod; - public int sgcod_po; // Progression order - public int sgcod_nl; // Number of layers - public int sgcod_mct; // Multiple component transformation - public int spcod_ndl; // Number of decomposition levels - public int spcod_cw; // Code-blocks width - public int spcod_ch; // Code-blocks height - public int spcod_cs; // Code-blocks style - public int[] spcod_t = new int[1]; // Transformation - public int[] spcod_ps; // Precinct size - /// Display information found in this COD marker segment - public override System.String ToString() - { - System.String str = "\n --- COD (" + lcod + " bytes) ---\n"; - str += " Coding style : "; - if (scod == 0) - { - str += "Default"; - } - else - { - if ((scod & CSJ2K.j2k.codestream.Markers.SCOX_PRECINCT_PARTITION) != 0) - str += "Precints "; - if ((scod & CSJ2K.j2k.codestream.Markers.SCOX_USE_SOP) != 0) - str += "SOP "; - if ((scod & CSJ2K.j2k.codestream.Markers.SCOX_USE_EPH) != 0) - str += "EPH "; - int cb0x = ((scod & CSJ2K.j2k.codestream.Markers.SCOX_HOR_CB_PART) != 0) ? 1 : 0; - int cb0y = ((scod & CSJ2K.j2k.codestream.Markers.SCOX_VER_CB_PART) != 0) ? 1 : 0; - if (cb0x != 0 || cb0y != 0) - { - str += "Code-blocks offset"; - str += ("\n Cblk partition : " + cb0x + "," + cb0y); - } - } - str += "\n"; - str += " Cblk style : "; - if (spcod_cs == 0) - { - str += "Default"; - } - else - { - if ((spcod_cs & 0x1) != 0) - str += "Bypass "; - if ((spcod_cs & 0x2) != 0) - str += "Reset "; - if ((spcod_cs & 0x4) != 0) - str += "Terminate "; - if ((spcod_cs & 0x8) != 0) - str += "Vert_causal "; - if ((spcod_cs & 0x10) != 0) - str += "Predict "; - if ((spcod_cs & 0x20) != 0) - str += "Seg_symb "; - } - str += "\n"; - str += (" Num. of levels : " + spcod_ndl + "\n"); - switch (sgcod_po) - { - - case CSJ2K.j2k.codestream.ProgressionType.LY_RES_COMP_POS_PROG: - str += " Progress. type : LY_RES_COMP_POS_PROG\n"; - break; - - case CSJ2K.j2k.codestream.ProgressionType.RES_LY_COMP_POS_PROG: - str += " Progress. type : RES_LY_COMP_POS_PROG\n"; - break; - - case CSJ2K.j2k.codestream.ProgressionType.RES_POS_COMP_LY_PROG: - str += " Progress. type : RES_POS_COMP_LY_PROG\n"; - break; - - case CSJ2K.j2k.codestream.ProgressionType.POS_COMP_RES_LY_PROG: - str += " Progress. type : POS_COMP_RES_LY_PROG\n"; - break; - - case CSJ2K.j2k.codestream.ProgressionType.COMP_POS_RES_LY_PROG: - str += " Progress. type : COMP_POS_RES_LY_PROG\n"; - break; - } - str += (" Num. of layers : " + sgcod_nl + "\n"); - str += (" Cblk dimension : " + (1 << (spcod_cw + 2)) + "x" + (1 << (spcod_ch + 2)) + "\n"); - switch (spcod_t[0]) - { - - case CSJ2K.j2k.wavelet.FilterTypes_Fields.W9X7: - str += " Filter : 9-7 irreversible\n"; - break; - - case CSJ2K.j2k.wavelet.FilterTypes_Fields.W5X3: - str += " Filter : 5-3 reversible\n"; - break; - } - str += (" Multi comp tr. : " + (sgcod_mct == 1) + "\n"); - if (spcod_ps != null) - { - str += " Precincts : "; - for (int i = 0; i < spcod_ps.Length; i++) - { - str += ((1 << (spcod_ps[i] & 0x000F)) + "x" + (1 << (((spcod_ps[i] & 0x00F0) >> 4))) + " "); - } - } - str += "\n"; - return str; - } - //UPGRADE_TODO: The following method was automatically generated and it must be implemented in order to preserve the class logic. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1232'" - virtual public System.Object Clone() - { - return null; - } - } - - //UPGRADE_NOTE: Field 'EnclosingInstance' was added to class 'COC' to access its enclosing instance. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1019'" - /// Internal class holding information found in the COC marker segments - public class COC - { - public COC(HeaderInfo enclosingInstance) - { - InitBlock(enclosingInstance); - } - private void InitBlock(HeaderInfo enclosingInstance) - { - this.enclosingInstance = enclosingInstance; - } - private HeaderInfo enclosingInstance; - public HeaderInfo Enclosing_Instance - { - get - { - return enclosingInstance; - } - - } - public int lcoc; - public int ccoc; - public int scoc; - public int spcoc_ndl; // Number of decomposition levels - public int spcoc_cw; - public int spcoc_ch; - public int spcoc_cs; - public int[] spcoc_t = new int[1]; - public int[] spcoc_ps; - /// Display information found in this COC marker segment - public override System.String ToString() - { - System.String str = "\n --- COC (" + lcoc + " bytes) ---\n"; - str += (" Component : " + ccoc + "\n"); - str += " Coding style : "; - if (scoc == 0) - { - str += "Default"; - } - else - { - if ((scoc & 0x1) != 0) - str += "Precints "; - if ((scoc & 0x2) != 0) - str += "SOP "; - if ((scoc & 0x4) != 0) - str += "EPH "; - } - str += "\n"; - str += " Cblk style : "; - if (spcoc_cs == 0) - { - str += "Default"; - } - else - { - if ((spcoc_cs & 0x1) != 0) - str += "Bypass "; - if ((spcoc_cs & 0x2) != 0) - str += "Reset "; - if ((spcoc_cs & 0x4) != 0) - str += "Terminate "; - if ((spcoc_cs & 0x8) != 0) - str += "Vert_causal "; - if ((spcoc_cs & 0x10) != 0) - str += "Predict "; - if ((spcoc_cs & 0x20) != 0) - str += "Seg_symb "; - } - str += "\n"; - str += (" Num. of levels : " + spcoc_ndl + "\n"); - str += (" Cblk dimension : " + (1 << (spcoc_cw + 2)) + "x" + (1 << (spcoc_ch + 2)) + "\n"); - switch (spcoc_t[0]) - { - - case CSJ2K.j2k.wavelet.FilterTypes_Fields.W9X7: - str += " Filter : 9-7 irreversible\n"; - break; - - case CSJ2K.j2k.wavelet.FilterTypes_Fields.W5X3: - str += " Filter : 5-3 reversible\n"; - break; - } - if (spcoc_ps != null) - { - str += " Precincts : "; - for (int i = 0; i < spcoc_ps.Length; i++) - { - str += ((1 << (spcoc_ps[i] & 0x000F)) + "x" + (1 << (((spcoc_ps[i] & 0x00F0) >> 4))) + " "); - } - } - str += "\n"; - return str; - } - } - - //UPGRADE_NOTE: Field 'EnclosingInstance' was added to class 'RGN' to access its enclosing instance. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1019'" - /// Internal class holding information found in the RGN marker segments - public class RGN - { - public RGN(HeaderInfo enclosingInstance) - { - InitBlock(enclosingInstance); - } - private void InitBlock(HeaderInfo enclosingInstance) - { - this.enclosingInstance = enclosingInstance; - } - private HeaderInfo enclosingInstance; - public HeaderInfo Enclosing_Instance - { - get - { - return enclosingInstance; - } - - } - public int lrgn; - public int crgn; - public int srgn; - public int sprgn; - /// Display information found in this RGN marker segment - public override System.String ToString() - { - System.String str = "\n --- RGN (" + lrgn + " bytes) ---\n"; - str += (" Component : " + crgn + "\n"); - if (srgn == 0) - { - str += " ROI style : Implicit\n"; - } - else - { - str += " ROI style : Unsupported\n"; - } - str += (" ROI shift : " + sprgn + "\n"); - str += "\n"; - return str; - } - } - - //UPGRADE_NOTE: Field 'EnclosingInstance' was added to class 'QCD' to access its enclosing instance. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1019'" - /// Internal class holding information found in the QCD marker segments - public class QCD - { - public QCD(HeaderInfo enclosingInstance) - { - InitBlock(enclosingInstance); - } - private void InitBlock(HeaderInfo enclosingInstance) - { - this.enclosingInstance = enclosingInstance; - } - private HeaderInfo enclosingInstance; - virtual public int QuantType - { - get - { - if (qType == -1) - { - qType = sqcd & ~(CSJ2K.j2k.codestream.Markers.SQCX_GB_MSK << CSJ2K.j2k.codestream.Markers.SQCX_GB_SHIFT); - } - return qType; - } - - } - virtual public int NumGuardBits - { - get - { - if (gb == -1) - { - gb = (sqcd >> CSJ2K.j2k.codestream.Markers.SQCX_GB_SHIFT) & CSJ2K.j2k.codestream.Markers.SQCX_GB_MSK; - } - return gb; - } - - } - public HeaderInfo Enclosing_Instance - { - get - { - return enclosingInstance; - } - - } - public int lqcd; - public int sqcd; - public int[][] spqcd; - - private int qType = -1; - private int gb = -1; - - /// Display information found in this QCD marker segment - public override System.String ToString() - { - System.String str = "\n --- QCD (" + lqcd + " bytes) ---\n"; - str += " Quant. type : "; - int qt = QuantType; - if (qt == CSJ2K.j2k.codestream.Markers.SQCX_NO_QUANTIZATION) - str += "No quantization \n"; - else if (qt == CSJ2K.j2k.codestream.Markers.SQCX_SCALAR_DERIVED) - str += "Scalar derived\n"; - else if (qt == CSJ2K.j2k.codestream.Markers.SQCX_SCALAR_EXPOUNDED) - str += "Scalar expounded\n"; - str += (" Guard bits : " + NumGuardBits + "\n"); - if (qt == CSJ2K.j2k.codestream.Markers.SQCX_NO_QUANTIZATION) - { - str += " Exponents :\n"; - int exp; - for (int i = 0; i < spqcd.Length; i++) - { - for (int j = 0; j < spqcd[i].Length; j++) - { - if (i == 0 && j == 0) - { - exp = (spqcd[0][0] >> CSJ2K.j2k.codestream.Markers.SQCX_EXP_SHIFT) & CSJ2K.j2k.codestream.Markers.SQCX_EXP_MASK; - str += ("\tr=0 : " + exp + "\n"); - } - else if (i != 0 && j > 0) - { - exp = (spqcd[i][j] >> CSJ2K.j2k.codestream.Markers.SQCX_EXP_SHIFT) & CSJ2K.j2k.codestream.Markers.SQCX_EXP_MASK; - str += ("\tr=" + i + ",s=" + j + " : " + exp + "\n"); - } - } - } - } - else - { - str += " Exp / Mantissa : \n"; - int exp; - double mantissa; - for (int i = 0; i < spqcd.Length; i++) - { - for (int j = 0; j < spqcd[i].Length; j++) - { - if (i == 0 && j == 0) - { - exp = (spqcd[0][0] >> 11) & 0x1f; - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - mantissa = (-1f - ((float)(spqcd[0][0] & 0x07ff)) / (1 << 11)) / (-1 << exp); - str += ("\tr=0 : " + exp + " / " + mantissa + "\n"); - } - else if (i != 0 && j > 0) - { - exp = (spqcd[i][j] >> 11) & 0x1f; - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - mantissa = (-1f - ((float)(spqcd[i][j] & 0x07ff)) / (1 << 11)) / (-1 << exp); - str += ("\tr=" + i + ",s=" + j + " : " + exp + " / " + mantissa + "\n"); - } - } - } - } - str += "\n"; - return str; - } - } - - //UPGRADE_NOTE: Field 'EnclosingInstance' was added to class 'QCC' to access its enclosing instance. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1019'" - /// Internal class holding information found in the QCC marker segments - public class QCC - { - public QCC(HeaderInfo enclosingInstance) - { - InitBlock(enclosingInstance); - } - private void InitBlock(HeaderInfo enclosingInstance) - { - this.enclosingInstance = enclosingInstance; - } - private HeaderInfo enclosingInstance; - virtual public int QuantType - { - get - { - if (qType == -1) - { - qType = sqcc & ~(CSJ2K.j2k.codestream.Markers.SQCX_GB_MSK << CSJ2K.j2k.codestream.Markers.SQCX_GB_SHIFT); - } - return qType; - } - - } - virtual public int NumGuardBits - { - get - { - if (gb == -1) - { - gb = (sqcc >> CSJ2K.j2k.codestream.Markers.SQCX_GB_SHIFT) & CSJ2K.j2k.codestream.Markers.SQCX_GB_MSK; - } - return gb; - } - - } - public HeaderInfo Enclosing_Instance - { - get - { - return enclosingInstance; - } - - } - public int lqcc; - public int cqcc; - public int sqcc; - public int[][] spqcc; - - private int qType = -1; - private int gb = -1; - - /// Display information found in this QCC marker segment - public override System.String ToString() - { - System.String str = "\n --- QCC (" + lqcc + " bytes) ---\n"; - str += (" Component : " + cqcc + "\n"); - str += " Quant. type : "; - int qt = QuantType; - if (qt == CSJ2K.j2k.codestream.Markers.SQCX_NO_QUANTIZATION) - str += "No quantization \n"; - else if (qt == CSJ2K.j2k.codestream.Markers.SQCX_SCALAR_DERIVED) - str += "Scalar derived\n"; - else if (qt == CSJ2K.j2k.codestream.Markers.SQCX_SCALAR_EXPOUNDED) - str += "Scalar expounded\n"; - str += (" Guard bits : " + NumGuardBits + "\n"); - if (qt == CSJ2K.j2k.codestream.Markers.SQCX_NO_QUANTIZATION) - { - str += " Exponents :\n"; - int exp; - for (int i = 0; i < spqcc.Length; i++) - { - for (int j = 0; j < spqcc[i].Length; j++) - { - if (i == 0 && j == 0) - { - exp = (spqcc[0][0] >> CSJ2K.j2k.codestream.Markers.SQCX_EXP_SHIFT) & CSJ2K.j2k.codestream.Markers.SQCX_EXP_MASK; - str += ("\tr=0 : " + exp + "\n"); - } - else if (i != 0 && j > 0) - { - exp = (spqcc[i][j] >> CSJ2K.j2k.codestream.Markers.SQCX_EXP_SHIFT) & CSJ2K.j2k.codestream.Markers.SQCX_EXP_MASK; - str += ("\tr=" + i + ",s=" + j + " : " + exp + "\n"); - } - } - } - } - else - { - str += " Exp / Mantissa : \n"; - int exp; - double mantissa; - for (int i = 0; i < spqcc.Length; i++) - { - for (int j = 0; j < spqcc[i].Length; j++) - { - if (i == 0 && j == 0) - { - exp = (spqcc[0][0] >> 11) & 0x1f; - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - mantissa = (-1f - ((float)(spqcc[0][0] & 0x07ff)) / (1 << 11)) / (-1 << exp); - str += ("\tr=0 : " + exp + " / " + mantissa + "\n"); - } - else if (i != 0 && j > 0) - { - exp = (spqcc[i][j] >> 11) & 0x1f; - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - mantissa = (-1f - ((float)(spqcc[i][j] & 0x07ff)) / (1 << 11)) / (-1 << exp); - str += ("\tr=" + i + ",s=" + j + " : " + exp + " / " + mantissa + "\n"); - } - } - } - } - str += "\n"; - return str; - } - } - - //UPGRADE_NOTE: Field 'EnclosingInstance' was added to class 'POC' to access its enclosing instance. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1019'" - /// Internal class holding information found in the POC marker segments - public class POC - { - public POC(HeaderInfo enclosingInstance) - { - InitBlock(enclosingInstance); - } - private void InitBlock(HeaderInfo enclosingInstance) - { - this.enclosingInstance = enclosingInstance; - } - private HeaderInfo enclosingInstance; - public HeaderInfo Enclosing_Instance - { - get - { - return enclosingInstance; - } - - } - public int lpoc; - public int[] rspoc; - public int[] cspoc; - public int[] lyepoc; - public int[] repoc; - public int[] cepoc; - public int[] ppoc; - /// Display information found in this POC marker segment - public override System.String ToString() - { - System.String str = "\n --- POC (" + lpoc + " bytes) ---\n"; - str += " Chg_idx RSpoc CSpoc LYEpoc REpoc CEpoc Ppoc\n"; - for (int chg = 0; chg < rspoc.Length; chg++) - { - str += (" " + chg + " " + rspoc[chg] + " " + cspoc[chg] + " " + lyepoc[chg] + " " + repoc[chg] + " " + cepoc[chg]); - switch (ppoc[chg]) - { - - case CSJ2K.j2k.codestream.ProgressionType.LY_RES_COMP_POS_PROG: - str += " LY_RES_COMP_POS_PROG\n"; - break; - - case CSJ2K.j2k.codestream.ProgressionType.RES_LY_COMP_POS_PROG: - str += " RES_LY_COMP_POS_PROG\n"; - break; - - case CSJ2K.j2k.codestream.ProgressionType.RES_POS_COMP_LY_PROG: - str += " RES_POS_COMP_LY_PROG\n"; - break; - - case CSJ2K.j2k.codestream.ProgressionType.POS_COMP_RES_LY_PROG: - str += " POS_COMP_RES_LY_PROG\n"; - break; - - case CSJ2K.j2k.codestream.ProgressionType.COMP_POS_RES_LY_PROG: - str += " COMP_POS_RES_LY_PROG\n"; - break; - } - } - str += "\n"; - return str; - } - } - - //UPGRADE_NOTE: Field 'EnclosingInstance' was added to class 'CRG' to access its enclosing instance. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1019'" - /// Internal class holding information found in the CRG marker segment - public class CRG - { - public CRG(HeaderInfo enclosingInstance) - { - InitBlock(enclosingInstance); - } - private void InitBlock(HeaderInfo enclosingInstance) - { - this.enclosingInstance = enclosingInstance; - } - private HeaderInfo enclosingInstance; - public HeaderInfo Enclosing_Instance - { - get - { - return enclosingInstance; - } - - } - public int lcrg; - public int[] xcrg; - public int[] ycrg; - /// Display information found in the CRG marker segment - public override System.String ToString() - { - System.String str = "\n --- CRG (" + lcrg + " bytes) ---\n"; - for (int c = 0; c < xcrg.Length; c++) - { - str += (" Component " + c + " offset : " + xcrg[c] + "," + ycrg[c] + "\n"); - } - str += "\n"; - return str; - } - } - - //UPGRADE_NOTE: Field 'EnclosingInstance' was added to class 'COM' to access its enclosing instance. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1019'" - /// Internal class holding information found in the COM marker segments - public class COM - { - public COM(HeaderInfo enclosingInstance) - { - InitBlock(enclosingInstance); - } - private void InitBlock(HeaderInfo enclosingInstance) - { - this.enclosingInstance = enclosingInstance; - } - private HeaderInfo enclosingInstance; - public HeaderInfo Enclosing_Instance - { - get - { - return enclosingInstance; - } - - } - public int lcom; - public int rcom; - public byte[] ccom; - /// Display information found in the COM marker segment - public override System.String ToString() - { - System.String str = "\n --- COM (" + lcom + " bytes) ---\n"; - if (rcom == 0) - { - str += " Registration : General use (binary values)\n"; - } - else if (rcom == 1) - { - str += (" Registration : General use (IS 8859-15:1999 " + "(Latin) values)\n"); - str += (" Text : " + System.Text.ASCIIEncoding.ASCII.GetString(ccom) + "\n"); - } - else - { - str += " Registration : Unknown\n"; - } - str += "\n"; - return str; - } - } - - /// Reference to the SIZ marker segment found in main header - public SIZ sizValue; - - /// Reference to the SOT marker segments found in tile-part headers. The - /// kwy is given by "t"+tileIdx"_tp"+tilepartIndex. - /// - public System.Collections.Hashtable sotValue = System.Collections.Hashtable.Synchronized(new System.Collections.Hashtable()); - - /// Reference to the COD marker segments found in main and first tile-part - /// header. The key is either "main" or "t"+tileIdx. - /// - public System.Collections.Hashtable codValue = System.Collections.Hashtable.Synchronized(new System.Collections.Hashtable()); - - /// Reference to the COC marker segments found in main and first tile-part - /// header. The key is either "main_c"+componentIndex or - /// "t"+tileIdx+"_c"+component_index. - /// - public System.Collections.Hashtable cocValue = System.Collections.Hashtable.Synchronized(new System.Collections.Hashtable()); - - /// Reference to the RGN marker segments found in main and first tile-part - /// header. The key is either "main_c"+componentIndex or - /// "t"+tileIdx+"_c"+component_index. - /// - public System.Collections.Hashtable rgnValue = System.Collections.Hashtable.Synchronized(new System.Collections.Hashtable()); - - /// Reference to the QCD marker segments found in main and first tile-part - /// header. The key is either "main" or "t"+tileIdx. - /// - public System.Collections.Hashtable qcdValue = System.Collections.Hashtable.Synchronized(new System.Collections.Hashtable()); - - /// Reference to the QCC marker segments found in main and first tile-part - /// header. They key is either "main_c"+componentIndex or - /// "t"+tileIdx+"_c"+component_index. - /// - public System.Collections.Hashtable qccValue = System.Collections.Hashtable.Synchronized(new System.Collections.Hashtable()); - - /// Reference to the POC marker segments found in main and first tile-part - /// header. They key is either "main" or "t"+tileIdx. - /// - public System.Collections.Hashtable pocValue = System.Collections.Hashtable.Synchronized(new System.Collections.Hashtable()); - - /// Reference to the CRG marker segment found in main header - public CRG crgValue; - - /// Reference to the COM marker segments found in main and tile-part - /// headers. The key is either "main_"+comIdx or "t"+tileIdx+"_"+comIdx. - /// - public System.Collections.Hashtable comValue = System.Collections.Hashtable.Synchronized(new System.Collections.Hashtable()); - - /// Number of found COM marker segment - private int ncom = 0; - - /// Display information found in the different marker segments of the main - /// header - /// - public virtual System.String toStringMainHeader() - { - int nc = sizValue.csiz; - // SIZ - System.String str = "" + sizValue; - // COD - if (codValue["main"] != null) - { - str += ("" + ((COD)codValue["main"])); - } - // COCs - for (int c = 0; c < nc; c++) - { - if (cocValue["main_c" + c] != null) - { - str += ("" + ((COC)cocValue["main_c" + c])); - } - } - // QCD - if (qcdValue["main"] != null) - { - str += ("" + ((QCD)qcdValue["main"])); - } - // QCCs - for (int c = 0; c < nc; c++) - { - if (qccValue["main_c" + c] != null) - { - str += ("" + ((QCC)qccValue["main_c" + c])); - } - } - // RGN - for (int c = 0; c < nc; c++) - { - if (rgnValue["main_c" + c] != null) - { - str += ("" + ((RGN)rgnValue["main_c" + c])); - } - } - // POC - if (pocValue["main"] != null) - { - str += ("" + ((POC)pocValue["main"])); - } - // CRG - if (crgValue != null) - { - str += ("" + crgValue); - } - // COM - for (int i = 0; i < ncom; i++) - { - if (comValue["main_" + i] != null) - { - str += ("" + ((COM)comValue["main_" + i])); - } - } - return str; - } - - /// Returns information found in the tile-part headers of a given tile. - /// - /// - /// index of the tile - /// - /// - /// Number of tile-parts - /// - /// - public virtual System.String toStringTileHeader(int t, int ntp) - { - int nc = sizValue.csiz; - System.String str = ""; - // SOT - for (int i = 0; i < ntp; i++) - { - str += ("Tile-part " + i + ", tile " + t + ":\n"); - str += ("" + ((SOT)sotValue["t" + t + "_tp" + i])); - } - // COD - if (codValue["t" + t] != null) - { - str += ("" + ((COD)codValue["t" + t])); - } - // COCs - for (int c = 0; c < nc; c++) - { - if (cocValue["t" + t + "_c" + c] != null) - { - str += ("" + ((COC)cocValue["t" + t + "_c" + c])); - } - } - // QCD - if (qcdValue["t" + t] != null) - { - str += ("" + ((QCD)qcdValue["t" + t])); - } - // QCCs - for (int c = 0; c < nc; c++) - { - if (qccValue["t" + t + "_c" + c] != null) - { - str += ("" + ((QCC)qccValue["t" + t + "_c" + c])); - } - } - // RGN - for (int c = 0; c < nc; c++) - { - if (rgnValue["t" + t + "_c" + c] != null) - { - str += ("" + ((RGN)rgnValue["t" + t + "_c" + c])); - } - } - // POC - if (pocValue["t" + t] != null) - { - str += ("" + ((POC)pocValue["t" + t])); - } - return str; - } - - /// Returns information found in the tile-part headers of a given tile - /// exception the SOT marker segment. - /// - /// - /// index of the tile - /// - /// - /// Number of tile-parts - /// - /// - public virtual System.String toStringThNoSOT(int t, int ntp) - { - int nc = sizValue.csiz; - System.String str = ""; - // COD - if (codValue["t" + t] != null) - { - str += ("" + ((COD)codValue["t" + t])); - } - // COCs - for (int c = 0; c < nc; c++) - { - if (cocValue["t" + t + "_c" + c] != null) - { - str += ("" + ((COC)cocValue["t" + t + "_c" + c])); - } - } - // QCD - if (qcdValue["t" + t] != null) - { - str += ("" + ((QCD)qcdValue["t" + t])); - } - // QCCs - for (int c = 0; c < nc; c++) - { - if (qccValue["t" + t + "_c" + c] != null) - { - str += ("" + ((QCC)qccValue["t" + t + "_c" + c])); - } - } - // RGN - for (int c = 0; c < nc; c++) - { - if (rgnValue["t" + t + "_c" + c] != null) - { - str += ("" + ((RGN)rgnValue["t" + t + "_c" + c])); - } - } - // POC - if (pocValue["t" + t] != null) - { - str += ("" + ((POC)pocValue["t" + t])); - } - return str; - } - - /// Returns a copy of this object - public virtual HeaderInfo getCopy(int nt) - { - HeaderInfo nhi = null; - // SIZ - try - { - nhi = (HeaderInfo)Clone(); - } - //UPGRADE_NOTE: Exception 'java.lang.CloneNotSupportedException' was converted to 'System.Exception' which has different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1100'" - catch (System.Exception) - { - throw new System.ApplicationException("Cannot clone HeaderInfo instance"); - } - nhi.sizValue = sizValue.Copy; - // COD - if (codValue["main"] != null) - { - COD ms = (COD)codValue["main"]; - nhi.codValue["main"] = ms.Copy; - } - for (int t = 0; t < nt; t++) - { - if (codValue["t" + t] != null) - { - COD ms = (COD)codValue["t" + t]; - nhi.codValue["t" + t] = ms.Copy; - } - } - return nhi; - } - //UPGRADE_TODO: The following method was automatically generated and it must be implemented in order to preserve the class logic. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1232'" - virtual public System.Object Clone() - { - return null; - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/codestream/Markers.cs b/CSJ2K/j2k/codestream/Markers.cs deleted file mode 100644 index 522e5d19..00000000 --- a/CSJ2K/j2k/codestream/Markers.cs +++ /dev/null @@ -1,158 +0,0 @@ -/* -* CVS identifier: -* -* $Id: Markers.java,v 1.13 2001/09/14 09:31:40 grosbois Exp $ -* -* Class: Markers -* -* Description: Defines the values of the markers in JPEG 2000 codestream -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -namespace CSJ2K.j2k.codestream -{ - - /// This interface defines the values of the different markers in the JPEG 2000 - /// codestream. There are 16 bit values, always appearing in big-endian (most - /// significant byte first) and byte-aligned in the codestream. This interface - /// also defines some other constants such as bit-masks and bit-shifts. - /// - /// - public struct Markers - { - /// Start of codestream (SOC): 0xFF4F - public const short SOC = unchecked((short)0xff4f); - /// Start of tile-part (SOT): 0xFF90 - public const short SOT = unchecked((short)0xff90); - /// Start of data (SOD): 0xFF93 - public const short SOD = unchecked((short)0xff93); - /// End of codestream (EOC): 0xFFD9 - public const short EOC = unchecked((short)0xffd9); - /// SIZ marker (Image and tile size): 0xFF51 - public const short SIZ = unchecked((short)0xff51); - /// No special capabilities (baseline) in codestream, in Rsiz field of SIZ - /// marker: 0x00. All flag bits are turned off - /// - public const int RSIZ_BASELINE = 0x00; - /// Error resilience marker flag bit in Rsiz field in SIZ marker: 0x01 - public const int RSIZ_ER_FLAG = 0x01; - /// ROI present marker flag bit in Rsiz field in SIZ marker: 0x02 - public const int RSIZ_ROI = 0x02; - /// Component bitdepth bits in Ssiz field in SIZ marker: 7 - public const int SSIZ_DEPTH_BITS = 7; - /// The maximum number of component bitdepth - public const int MAX_COMP_BITDEPTH = 38; - /// Coding style default (COD): 0xFF52 - public const short COD = unchecked((short)0xff52); - /// Coding style component (COC): 0xFF53 - public const short COC = unchecked((short)0xff53); - /// Precinct used flag - public const int SCOX_PRECINCT_PARTITION = 1; - /// Use start of packet marker - public const int SCOX_USE_SOP = 2; - /// Use end of packet header marker - public const int SCOX_USE_EPH = 4; - /// Horizontal code-block partition origin is at x=1 - public const int SCOX_HOR_CB_PART = 8; - /// Vertical code-block partition origin is at y=1 - public const int SCOX_VER_CB_PART = 16; - /// The default size exponent of the precincts - public const int PRECINCT_PARTITION_DEF_SIZE = 0xffff; - // ** RGN marker segment ** - /// Region-of-interest (RGN): 0xFF5E - public const short RGN = unchecked((short)0xff5e); - /// Implicit (i.e. max-shift) ROI flag for Srgn field in RGN marker - /// segment: 0x00 - /// - public const int SRGN_IMPLICIT = 0x00; - /// Quantization default (QCD): 0xFF5C - public const short QCD = unchecked((short)0xff5c); - /// Quantization component (QCC): 0xFF5D - public const short QCC = unchecked((short)0xff5d); - /// Guard bits shift in SQCX field: 5 - public const int SQCX_GB_SHIFT = 5; - /// Guard bits mask in SQCX field: 7 - public const int SQCX_GB_MSK = 7; - /// No quantization (i.e. embedded reversible) flag for Sqcd or Sqcc - /// (Sqcx) fields: 0x00. - /// - public const int SQCX_NO_QUANTIZATION = 0x00; - /// Scalar derived (i.e. LL values only) quantization flag for Sqcd or - /// Sqcc (Sqcx) fields: 0x01. - /// - public const int SQCX_SCALAR_DERIVED = 0x01; - /// Scalar expounded (i.e. all values) quantization flag for Sqcd or Sqcc - /// (Sqcx) fields: 0x02. - /// - public const int SQCX_SCALAR_EXPOUNDED = 0x02; - /// Exponent shift in SPQCX when no quantization: 3 - public const int SQCX_EXP_SHIFT = 3; - /// Exponent bitmask in SPQCX when no quantization: 3 - public const int SQCX_EXP_MASK = (1 << 5) - 1; - /// The "SOP marker segments used" flag within Sers: 1 - public const int ERS_SOP = 1; - /// The "segmentation symbols used" flag within Sers: 2 - public const int ERS_SEG_SYMBOLS = 2; - // ** Progression order change ** - public const short POC = unchecked((short)0xff5f); - /// Tile-part lengths (TLM): 0xFF55 - public const short TLM = unchecked((short)0xff55); - /// Packet length, main header (PLM): 0xFF57 - public const short PLM = unchecked((short)0xff57); - /// Packet length, tile-part header (PLT): 0xFF58 - public const short PLT = unchecked((short)0xff58); - /// Packed packet headers, main header (PPM): 0xFF60 - public const short PPM = unchecked((short)0xff60); - /// Packed packet headers, tile-part header (PPT): 0xFF61 - public const short PPT = unchecked((short)0xff61); - /// Maximum length of PPT marker segment - public const int MAX_LPPT = 65535; - /// Maximum length of PPM marker segment - public const int MAX_LPPM = 65535; - /// Start pf packet (SOP): 0xFF91 - public const short SOP = unchecked((short)0xff91); - /// Length of SOP marker (in bytes) - public const short SOP_LENGTH = 6; - /// End of packet header (EPH): 0xFF92 - public const short EPH = unchecked((short)0xff92); - /// Length of EPH marker (in bytes) - public const short EPH_LENGTH = 2; - /// Component registration (CRG): 0xFF63 - public const short CRG = unchecked((short)0xff63); - /// Comment (COM): 0xFF64 - public const short COM = unchecked((short)0xff64); - /// General use registration value (binary) (COM): 0x0000 - public const short RCOM_BINARY = 0; - /// General use registration value (latin) (COM): 0x0001 - public const short RCOM_LATIN = 1; - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/codestream/PrecCoordInfo.cs b/CSJ2K/j2k/codestream/PrecCoordInfo.cs deleted file mode 100644 index 7b081c9b..00000000 --- a/CSJ2K/j2k/codestream/PrecCoordInfo.cs +++ /dev/null @@ -1,101 +0,0 @@ -/* -* CVS identifier: -* -* $Id: PrecCoordInfo.java,v 1.9 2001/09/14 09:33:22 grosbois Exp $ -* -* Class: PrecCoordInfo -* -* Description: Used to store the coordinates precincts. -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -namespace CSJ2K.j2k.codestream -{ - - /// This class is used to store the coordinates of precincts. - /// - /// - public class PrecCoordInfo : CoordInfo - { - - /// Horizontal upper left coordinate in the reference grid - public int xref; - - /// Vertical upper left coordinate on the reference grid - public int yref; - - /// Constructor. Creates a PrecCoordInfo object. - /// - /// - /// Horizontal upper left coordinate in the subband - /// - /// - /// Vertical upper left coordinate in the subband - /// - /// - /// Precinct's width - /// - /// - /// Precinct's height - /// - /// - /// The horizontal coordinate on the reference grid - /// - /// - /// The vertical coordinate on the reference grid - /// - /// - public PrecCoordInfo(int ulx, int uly, int w, int h, int xref, int yref) : base(ulx, uly, w, h) - { - this.xref = xref; - this.yref = yref; - } - - /// Empty Constructor. Creates an empty PrecCoordInfo object. - /// - /// - public PrecCoordInfo() : base() - { - } - - /// Returns precinct's information in a String - /// - /// - /// String with precinct's information - /// - /// - public override System.String ToString() - { - return base.ToString() + ", xref=" + xref + ", yref=" + yref; - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/codestream/PrecInfo.cs b/CSJ2K/j2k/codestream/PrecInfo.cs deleted file mode 100644 index b2cfe121..00000000 --- a/CSJ2K/j2k/codestream/PrecInfo.cs +++ /dev/null @@ -1,147 +0,0 @@ -/* -* CVS identifier: -* -* $Id: PrecInfo.java,v 1.2 2001/09/20 10:03:45 grosbois Exp $ -* -* Class: PrecInfo -* -* Description: Keeps information about a precinct -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -namespace CSJ2K.j2k.codestream -{ - - /// Class that holds precinct coordinates and references to contained - /// code-blocks in each subband. - /// - /// - public class PrecInfo - { - - /// Precinct horizontal upper-left coordinate in the reference grid - public int rgulx; - - /// Precinct vertical upper-left coordinate in the reference grid - public int rguly; - - /// Precinct width reported in the reference grid - public int rgw; - - /// Precinct height reported in the reference grid - public int rgh; - - /// Precinct horizontal upper-left coordinate in the corresponding - /// resolution level - /// - public int ulx; - - /// Precinct vertical upper-left coordinate in the corresponding - /// resolution level - /// - public int uly; - - /// Precinct width in the corresponding resolution level - public int w; - - /// Precinct height in the corresponding resolution level - public int h; - - /// Resolution level index - public int r; - - /// Code-blocks belonging to this precinct in each subbands of the - /// resolution level - /// - public CBlkCoordInfo[][][] cblk; - - /// Number of code-blocks in each subband belonging to this precinct - public int[] nblk; - - /// Class constructor. - /// - /// - /// Resolution level index. - /// - /// Precinct horizontal offset. - /// - /// Precinct vertical offset. - /// - /// Precinct width. - /// - /// Precinct height. - /// - /// Precinct horizontal offset in the image reference grid. - /// - /// Precinct horizontal offset in the image reference grid. - /// - /// Precinct width in the reference grid. - /// - /// Precinct height in the reference grid. - /// - /// - public PrecInfo(int r, int ulx, int uly, int w, int h, int rgulx, int rguly, int rgw, int rgh) - { - this.r = r; - this.ulx = ulx; - this.uly = uly; - this.w = w; - this.h = h; - this.rgulx = rgulx; - this.rguly = rguly; - this.rgw = rgw; - this.rgh = rgh; - - if (r == 0) - { - cblk = new CBlkCoordInfo[1][][]; - nblk = new int[1]; - } - else - { - cblk = new CBlkCoordInfo[4][][]; - nblk = new int[4]; - } - } - - /// Returns PrecInfo object information in a String - /// - /// - /// PrecInfo information - /// - /// - public override System.String ToString() - { - return "ulx=" + ulx + ",uly=" + uly + ",w=" + w + ",h=" + h + ",rgulx=" + rgulx + ",rguly=" + rguly + ",rgw=" + rgw + ",rgh=" + rgh; - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/codestream/ProgressionType.cs b/CSJ2K/j2k/codestream/ProgressionType.cs deleted file mode 100644 index 1a1f7655..00000000 --- a/CSJ2K/j2k/codestream/ProgressionType.cs +++ /dev/null @@ -1,85 +0,0 @@ -/* -* CVS identifier: -* -* $Id: ProgressionType.java,v 1.16 2001/07/25 16:21:06 grosbois Exp $ -* -* Class: ProgressionType -* -* Description: The definition of the different bit stream -* profiles. -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -namespace CSJ2K.j2k.codestream -{ - - /// This interface defines the identifiers for the different codestream - /// profiles and progression types. - /// - ///

    Each progressive type has a different number: 'LY_RES_COMP_POS_PROG', - /// 'RES_LY_COMP_POS_PROG', 'RES_POS_COMP_LY_PROG', 'POS_COMP_RES_LY_PROG' or - /// 'COMP_POS_RES_LY_PROG'. These are the same identifiers are used in the - /// codestream syntax. - /// - ///

    This interface defines the constants only. In order to use the constants - /// in any other class you can either use the fully qualified name (e.g., - /// ProgressionType.LY_RES_COMP_POS_PROG) or declare this interface in - /// the implements clause of the class and then access the identifier - /// directly.

    - /// - ///
    - public struct ProgressionType - { - /// The codestream is Layer/Resolution/Component/Position progressive : 0 - /// - /// - public const int LY_RES_COMP_POS_PROG = 0; - /// The codestream is Resolution/Layer/Component/Position progressive : 1 - /// - /// - public const int RES_LY_COMP_POS_PROG = 1; - /// The codestream is Resolution/Position/Component/Layer progressive : 2 - /// - /// - public const int RES_POS_COMP_LY_PROG = 2; - /// The codestream is Position/Component/Resolution/Layer progressive : 3 - /// - /// - public const int POS_COMP_RES_LY_PROG = 3; - /// The codestream is Component/Position/Resolution/Layer progressive : 4 - /// - /// - public const int COMP_POS_RES_LY_PROG = 4; - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/codestream/reader/BitstreamReaderAgent.cs b/CSJ2K/j2k/codestream/reader/BitstreamReaderAgent.cs deleted file mode 100644 index c4f51b9e..00000000 --- a/CSJ2K/j2k/codestream/reader/BitstreamReaderAgent.cs +++ /dev/null @@ -1,1272 +0,0 @@ -/* -* CVS identifier: -* -* $Id: BitstreamReaderAgent.java,v 1.27 2002/07/25 14:59:32 grosbois Exp $ -* -* Class: BitstreamReaderAgent -* -* Description: The generic interface for bit stream -* transport agents. -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.decoder; -using CSJ2K.j2k.entropy.decoder; -using CSJ2K.j2k.image; -using CSJ2K.j2k.io; -using CSJ2K.j2k.quantization.dequantizer; -using CSJ2K.j2k.util; -using CSJ2K.j2k.wavelet; -using CSJ2K.j2k.wavelet.synthesis; -namespace CSJ2K.j2k.codestream.reader -{ - - /// This is the generic interface for bit stream reader agents. A bit stream - /// reader agent is an entity that allows reading from a bit stream and - /// requesting compressed code-blocks. It can be a simple file reader, or a - /// network connection, or anything else. - /// - ///

    The bit stream reader agent allows to make request for compressed block - /// data in any order. The amount of data returned would normally depend on the - /// data available at the time of the request, be it from a file or from a - /// network connection.

    - /// - ///

    The bit stream reader agent has the notion of a current tile, and - /// coordinates are relative to the current tile, where applicable.

    - /// - ///

    Resolution level 0 is the lowest resolution level, i.e. the LL subband - /// alone.

    - /// - ///
    - public abstract class BitstreamReaderAgent : CodedCBlkDataSrcDec - { - /// Returns the horizontal code-block partition origin. Allowable values - /// are 0 and 1, nothing else. - /// - /// - virtual public int CbULX - { - get - { - return hd.CbULX; - } - - } - /// Returns the vertical code-block partition origin. Allowable values are - /// 0 and 1, nothing else. - /// - /// - virtual public int CbULY - { - get - { - return hd.CbULY; - } - - } - /// Returns the number of components in the image. - /// - /// - /// The number of components in the image. - /// - /// - virtual public int NumComps - { - get - { - return nc; - } - - } - /// Returns the index of the current tile, relative to a standard scan-line - /// order. - /// - /// - /// The current tile's index (starts at 0). - /// - /// - virtual public int TileIdx - { - get - { - return ctY * ntX + ctX; - } - - } - /// Returns the parameters that are used in this class and implementing - /// classes. It returns a 2D String array. Each of the 1D arrays is for a - /// different option, and they have 3 elements. The first element is the - /// option name, the second one is the synopsis and the third one is a long - /// description of what the parameter is. The synopsis or description may - /// be 'null', in which case it is assumed that there is no synopsis or - /// description of the option, respectively. Null may be returned if no - /// options are supported. - /// - /// - /// the options name, their synopsis and their explanation, or null - /// if no options are supported. - /// - /// - public static System.String[][] ParameterInfo - { - get - { - return pinfo; - } - - } - /// Returns the image resolution level to reconstruct from the - /// codestream. This value cannot be computed before every main and tile - /// headers are read. - /// - /// - /// The image resolution level - /// - /// - virtual public int ImgRes - { - get - { - return targetRes; - } - - } - /// Return the target decoding rate in bits per pixel. - /// - /// - /// Target decoding rate in bpp. - /// - /// - virtual public float TargetRate - { - get - { - return trate; - } - - } - /// Return the actual decoding rate in bits per pixel. - /// - /// - /// Actual decoding rate in bpp. - /// - /// - virtual public float ActualRate - { - get - { - arate = anbytes * 8f / hd.MaxCompImgWidth / hd.MaxCompImgHeight; - return arate; - } - - } - /// Return the target number of read bytes. - /// - /// - /// Target decoding rate in bytes. - /// - /// - virtual public int TargetNbytes - { - get - { - return tnbytes; - } - - } - /// Return the actual number of read bytes. - /// - /// - /// Actual decoding rate in bytes. - /// - /// - virtual public int ActualNbytes - { - get - { - return anbytes; - } - - } - /// Returns the horizontal offset of tile partition - virtual public int TilePartULX - { - get - { - return hd.getTilingOrigin(null).x; - } - - } - /// Returns the vertical offset of tile partition - virtual public int TilePartULY - { - get - { - return hd.getTilingOrigin(null).y; - } - - } - /// Returns the nominal tile width - virtual public int NomTileWidth - { - get - { - return hd.NomTileWidth; - } - - } - /// Returns the nominal tile height - virtual public int NomTileHeight - { - get - { - return hd.NomTileHeight; - } - - } - - /// The decoder specifications - protected internal DecoderSpecs decSpec; - - /// Whether or not the components in the current tile uses a derived - /// quantization step size (only relevant in non reversible quantization - /// mode). This field is actualized by the setTile method in - /// FileBitstreamReaderAgent. - /// - /// - /// - /// - /// - protected internal bool[] derived = null; - - /// Number of guard bits off all component in the current tile. This field - /// is actualized by the setTile method in FileBitstreamReaderAgent. - /// - /// - /// - /// - /// - protected internal int[] gb = null; - - /// Dequantization parameters of all subbands and all components in the - /// current tile. The value is actualized by the setTile method in - /// FileBitstreamReaderAgent. - /// - /// - /// - /// - /// - protected internal StdDequantizerParams[] params_Renamed = null; - - /// The prefix for bit stream reader options: 'B' - public const char OPT_PREFIX = 'B'; - - /// The list of parameters that is accepted by the bit stream - /// readers. They start with 'B'. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'pinfo'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly System.String[][] pinfo = null; - - /// The maximum number of decompostion levels for each component of the - /// current tile. It means that component c has mdl[c]+1 resolution levels - /// (indexed from 0 to mdl[c]) - /// - /// - protected internal int[] mdl; - - /// The number of components - //UPGRADE_NOTE: Final was removed from the declaration of 'nc '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - protected internal int nc; - - /// Image resolution level to generate - protected internal int targetRes; - - /// The subband trees for each component in the current tile. Each element - /// in the array is the root element of the subband tree for a - /// component. The number of magnitude bits in each subband (magBits member - /// variable) is not initialized. - /// - /// - protected internal SubbandSyn[] subbTrees; - - /// The image width on the hi-res reference grid - //UPGRADE_NOTE: Final was removed from the declaration of 'imgW '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - protected internal int imgW; - - /// The image width on the hi-res reference grid - //UPGRADE_NOTE: Final was removed from the declaration of 'imgH '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - protected internal int imgH; - - /// The horizontal coordinate of the image origin in the canvas system, on - /// the reference grid. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'ax '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - protected internal int ax; - - /// The vertical coordinate of the image origin in the canvas system, on - /// the reference grid. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'ay '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - protected internal int ay; - - /// The horizontal coordinate of the tiling origin in the canvas system, on - /// the reference grid. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'px '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - protected internal int px; - - /// The vertical coordinate of the tiling origin in the canvas system, on - /// the reference grid. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'py '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - protected internal int py; - - /// The horizontal offsets of the upper-left corner of the current tile - /// (not active tile) with respect to the canvas origin, in the component - /// hi-res grid, for each component. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'offX '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - protected internal int[] offX; - - /// The vertical offsets of the upper-left corner of the current tile (not - /// active tile) with respect to the canvas origin, in the component hi-res - /// grid, for each component. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'offY '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - protected internal int[] offY; - - /// The horizontal coordinates of the upper-left corner of the active - /// tile, with respect to the canvas origin, in the component hi-res grid, - /// for each component. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'culx '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - protected internal int[] culx; - - /// The vertical coordinates of the upper-left corner of the active tile, - /// with respect to the canvas origin, in the component hi-res grid, for - /// each component. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'culy '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - protected internal int[] culy; - - /// The nominal tile width, in the hi-res reference grid - //UPGRADE_NOTE: Final was removed from the declaration of 'ntW '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - protected internal int ntW; - - /// The nominal tile height, in the hi-res reference grid - //UPGRADE_NOTE: Final was removed from the declaration of 'ntH '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - protected internal int ntH; - - /// The number of tile in the horizontal direction - //UPGRADE_NOTE: Final was removed from the declaration of 'ntX '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - protected internal int ntX; - - /// The number of tiles in the vertical direction - //UPGRADE_NOTE: Final was removed from the declaration of 'ntY '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - protected internal int ntY; - - /// The total number of tiles - //UPGRADE_NOTE: Final was removed from the declaration of 'nt '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - protected internal int nt; - - /// The current tile horizontal index - protected internal int ctX; - - /// The current tile vertical index - protected internal int ctY; - - /// The decoded bit stream header - //UPGRADE_NOTE: Final was removed from the declaration of 'hd '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - protected internal HeaderDecoder hd; - - /// Number of bytes targeted to be read - protected internal int tnbytes; - - /// Actual number of read bytes - protected internal int anbytes; - - /// Target decoding rate in bpp - protected internal float trate; - - /// Actual decoding rate in bpp - protected internal float arate; - - /// Initializes members of this class. This constructor takes a - /// HeaderDecoder object. This object must be initialized by the - /// constructor of the implementing class from the header of the bit - /// stream. - /// - /// - /// The decoded header of the bit stream from where to initialize - /// the values. - /// - /// - /// The decoder specifications - /// - /// - protected internal BitstreamReaderAgent(HeaderDecoder hd, DecoderSpecs decSpec) - { - Coord co; - //int i, j, max; - - this.decSpec = decSpec; - this.hd = hd; - - // Number of components - nc = hd.NumComps; - offX = new int[nc]; - offY = new int[nc]; - culx = new int[nc]; - culy = new int[nc]; - - // Image size and origin - imgW = hd.ImgWidth; - imgH = hd.ImgHeight; - ax = hd.ImgULX; - ay = hd.ImgULY; - - // Tiles - co = hd.getTilingOrigin(null); - px = co.x; - py = co.y; - ntW = hd.NomTileWidth; - ntH = hd.NomTileHeight; - ntX = (ax + imgW - px + ntW - 1) / ntW; - ntY = (ay + imgH - py + ntH - 1) / ntH; - nt = ntX * ntY; - } - - /// Returns the component subsampling factor in the horizontal direction, - /// for the specified component. This is, approximately, the ratio of - /// dimensions between the reference grid and the component itself, see the - /// 'ImgData' interface desription for details. - /// - /// - /// The index of the component (between 0 and N-1) - /// - /// - /// The horizontal subsampling factor of component 'c' - /// - /// - /// - /// - /// - public int getCompSubsX(int c) - { - return hd.getCompSubsX(c); - } - - /// Returns the component subsampling factor in the vertical direction, for - /// the specified component. This is, approximately, the ratio of - /// dimensions between the reference grid and the component itself, see the - /// 'ImgData' interface desription for details. - /// - /// - /// The index of the component (between 0 and C-1) - /// - /// - /// The vertical subsampling factor of component 'c' - /// - /// - /// - /// - /// - public virtual int getCompSubsY(int c) - { - return hd.getCompSubsY(c); - } - - /// Returns the overall width of the current tile in pixels for the given - /// (tile) resolution level. This is the tile's width without accounting - /// for any component subsampling. - /// - ///

    Note: Tile resolution level indexes may be different from - /// tile-component resolution index. They are indeed indexed starting from - /// the lowest number of decomposition levels of each component of the - /// tile.

    - /// - ///

    For an image (1 tile) with 2 components (component 0 having 2 - /// decomposition levels and component 1 having 3 decomposition levels), - /// the first (tile-)component has 3 resolution levels and the second one - /// has 4 resolution levels, whereas the tile has only 3 resolution levels - /// available.

    - /// - ///
    - /// The (tile) resolution level. - /// - /// - /// The current tile's width in pixels. - /// - /// - public virtual int getTileWidth(int rl) - { - // The minumum number of decomposition levels between all the - // components - int mindl = decSpec.dls.getMinInTile(TileIdx); - if (rl > mindl) - { - throw new System.ArgumentException("Requested resolution level" + " is not available for, at " + "least, one component in " + "tile: " + ctX + "x" + ctY); - } - int ctulx, ntulx; - int dl = mindl - rl; // Number of decomposition to obtain this - // resolution - - // Calculate starting X of current tile at hi-res - ctulx = (ctX == 0) ? ax : px + ctX * ntW; - // Calculate starting X of next tile X-wise at hi-res - ntulx = (ctX < ntX - 1) ? px + (ctX + 1) * ntW : ax + imgW; - - // The difference at the rl resolution level is the width - return (ntulx + (1 << dl) - 1) / (1 << dl) - (ctulx + (1 << dl) - 1) / (1 << dl); - } - - /// Returns the overall height of the current tile in pixels, for the given - /// resolution level. This is the tile's height without accounting for any - /// component subsampling. - /// - ///

    Note: Tile resolution level indexes may be different from - /// tile-component resolution index. They are indeed indexed starting from - /// the lowest number of decomposition levels of each component of the - /// tile.

    - /// - ///

    For an image (1 tile) with 2 components (component 0 having 2 - /// decomposition levels and component 1 having 3 decomposition levels), - /// the first (tile-)component has 3 resolution levels and the second one - /// has 4 resolution levels, whereas the tile has only 3 resolution levels - /// available.

    - /// - ///
    - /// The (tile) resolution level. - /// - /// - /// The total current tile's height in pixels. - /// - /// - public virtual int getTileHeight(int rl) - { - // The minumum number of decomposition levels between all the - // components - int mindl = decSpec.dls.getMinInTile(TileIdx); - if (rl > mindl) - { - throw new System.ArgumentException("Requested resolution level" + " is not available for, at " + "least, one component in" + " tile: " + ctX + "x" + ctY); - } - - int ctuly, ntuly; - int dl = mindl - rl; // Number of decomposition to obtain this - // resolution - - // Calculate starting Y of current tile at hi-res - ctuly = (ctY == 0) ? ay : py + ctY * ntH; - // Calculate starting Y of next tile Y-wise at hi-res - ntuly = (ctY < ntY - 1) ? py + (ctY + 1) * ntH : ay + imgH; - // The difference at the rl level is the height - return (ntuly + (1 << dl) - 1) / (1 << dl) - (ctuly + (1 << dl) - 1) / (1 << dl); - } - - /// Returns the overall width of the image in pixels, for the given (image) - /// resolution level. This is the image's width without accounting for any - /// component subsampling or tiling. - /// - ///

    Note: Image resolution level indexes may differ from tile-component - /// resolution index. They are indeed indexed starting from the lowest - /// number of decomposition levels of each component of each tile.

    - /// - ///

    Example: For an image (1 tile) with 2 components (component 0 having - /// 2 decomposition levels and component 1 having 3 decomposition levels), - /// the first (tile-) component has 3 resolution levels and the second one - /// has 4 resolution levels, whereas the image has only 3 resolution levels - /// available.

    - /// - ///
    - /// The image resolution level. - /// - /// - /// The total image's width in pixels. - /// - /// - public virtual int getImgWidth(int rl) - { - // The minimum number of decomposition levels of each - // tile-component - int mindl = decSpec.dls.Min; - if (rl > mindl) - { - throw new System.ArgumentException("Requested resolution level" + " is not available for, at " + "least, one tile-component"); - } - // Retrieve number of decomposition levels corresponding to - // this resolution level - int dl = mindl - rl; - return (ax + imgW + (1 << dl) - 1) / (1 << dl) - (ax + (1 << dl) - 1) / (1 << dl); - } - - /// Returns the overall height of the image in pixels, for the given - /// resolution level. This is the image's height without accounting for any - /// component subsampling or tiling. - /// - ///

    Note: Image resolution level indexes may differ from tile-component - /// resolution index. They are indeed indexed starting from the lowest - /// number of decomposition levels of each component of each tile.

    - /// - ///

    Example: For an image (1 tile) with 2 components (component 0 having - /// 2 decomposition levels and component 1 having 3 decomposition levels), - /// the first (tile-) component has 3 resolution levels and the second one - /// has 4 resolution levels, whereas the image has only 3 resolution levels - /// available.

    - /// - ///
    - /// The image resolution level, from 0 to L. - /// - /// - /// The total image's height in pixels. - /// - /// - public virtual int getImgHeight(int rl) - { - int mindl = decSpec.dls.Min; - if (rl > mindl) - { - throw new System.ArgumentException("Requested resolution level" + " is not available for, at " + "least, one tile-component"); - } - // Retrieve number of decomposition levels corresponding to this - // resolution level - int dl = mindl - rl; - return (ay + imgH + (1 << dl) - 1) / (1 << dl) - (ay + (1 << dl) - 1) / (1 << dl); - } - - /// Returns the horizontal coordinate of the image origin, the top-left - /// corner, in the canvas system, on the reference grid at the specified - /// resolution level. - /// - ///

    Note: Image resolution level indexes may differ from tile-component - /// resolution index. They are indeed indexed starting from the lowest - /// number of decomposition levels of each component of each tile.

    - /// - ///

    Example: For an image (1 tile) with 2 components (component 0 having - /// 2 decomposition levels and component 1 having 3 decomposition levels), - /// the first (tile-) component has 3 resolution levels and the second one - /// has 4 resolution levels, whereas the image has only 3 resolution levels - /// available.

    - /// - ///
    - /// The resolution level, from 0 to L. - /// - /// - /// The horizontal coordinate of the image origin in the canvas - /// system, on the reference grid. - /// - /// - public virtual int getImgULX(int rl) - { - int mindl = decSpec.dls.Min; - if (rl > mindl) - { - throw new System.ArgumentException("Requested resolution level" + " is not available for, at " + "least, one tile-component"); - } - // Retrieve number of decomposition levels corresponding to this - // resolution level - int dl = mindl - rl; - return (ax + (1 << dl) - 1) / (1 << dl); - } - - /// Returns the vertical coordinate of the image origin, the top-left - /// corner, in the canvas system, on the reference grid at the specified - /// resolution level. - /// - ///

    Note: Image resolution level indexes may differ from tile-component - /// resolution index. They are indeed indexed starting from the lowest - /// number of decomposition levels of each component of each tile.

    - /// - ///

    Example: For an image (1 tile) with 2 components (component 0 having - /// 2 decomposition levels and component 1 having 3 decomposition levels), - /// the first (tile-) component has 3 resolution levels and the second one - /// has 4 resolution levels, whereas the image has only 3 resolution levels - /// available.

    - /// - ///
    - /// The resolution level, from 0 to L. - /// - /// - /// The vertical coordinate of the image origin in the canvas - /// system, on the reference grid. - /// - /// - public virtual int getImgULY(int rl) - { - int mindl = decSpec.dls.Min; - if (rl > mindl) - { - throw new System.ArgumentException("Requested resolution level" + " is not available for, at " + "least, one tile-component"); - } - // Retrieve number of decomposition levels corresponding to this - // resolution level - int dl = mindl - rl; - return (ay + (1 << dl) - 1) / (1 << dl); - } - - /// Returns the width in pixels of the specified tile-component for the - /// given (tile-component) resolution level. - /// - /// - /// The tile index - /// - /// - /// The index of the component, from 0 to N-1. - /// - /// - /// The resolution level, from 0 to L. - /// - /// - /// The width in pixels of component c in tile t - /// for resolution level rl. - /// - /// - public int getTileCompWidth(int t, int c, int rl) - { - int tIdx = TileIdx; - if (t != tIdx) - { - throw new System.ApplicationException("Asking the tile-component width of a tile " + "different from the current one."); - } - int ntulx; - int dl = mdl[c] - rl; - // Calculate starting X of next tile X-wise at reference grid hi-res - ntulx = (ctX < ntX - 1) ? px + (ctX + 1) * ntW : ax + imgW; - // Convert reference grid hi-res to component grid hi-res - ntulx = (ntulx + hd.getCompSubsX(c) - 1) / hd.getCompSubsX(c); - // Starting X of current tile at component grid hi-res is culx[c] - // The difference at the rl level is the width - return (ntulx + (1 << dl) - 1) / (1 << dl) - (culx[c] + (1 << dl) - 1) / (1 << dl); - } - - /// Returns the height in pixels of the specified tile-component for the - /// given (tile-component) resolution level. - /// - /// - /// The tile index. - /// - /// - /// The index of the component, from 0 to N-1. - /// - /// - /// The resolution level, from 0 to L. - /// - /// - /// The height in pixels of component c in the current - /// tile. - /// - /// - public int getTileCompHeight(int t, int c, int rl) - { - int tIdx = TileIdx; - if (t != tIdx) - { - throw new System.ApplicationException("Asking the tile-component width of a tile " + "different from the current one."); - } - int ntuly; - int dl = mdl[c] - rl; // Revert level indexation (0 is hi-res) - // Calculate starting Y of next tile Y-wise at reference grid hi-res - ntuly = (ctY < ntY - 1) ? py + (ctY + 1) * ntH : ay + imgH; - // Convert reference grid hi-res to component grid hi-res - ntuly = (ntuly + hd.getCompSubsY(c) - 1) / hd.getCompSubsY(c); - // Starting Y of current tile at component grid hi-res is culy[c] - // The difference at the rl level is the height - return (ntuly + (1 << dl) - 1) / (1 << dl) - (culy[c] + (1 << dl) - 1) / (1 << dl); - } - - /// Returns the width in pixels of the specified component in the overall - /// image, for the given (component) resolution level. - /// - ///

    Note: Component resolution level indexes may differ from - /// tile-component resolution index. They are indeed indexed starting from - /// the lowest number of decomposition levels of same component of each - /// tile.

    - /// - ///

    Example: For an image (2 tiles) with 1 component (tile 0 having 2 - /// decomposition levels and tile 1 having 3 decomposition levels), the - /// first tile(-component) has 3 resolution levels and the second one has 4 - /// resolution levels, whereas the component has only 3 resolution levels - /// available.

    - /// - ///
    - /// The index of the component, from 0 to N-1. - /// - /// - /// The resolution level, from 0 to L. - /// - /// - /// The width in pixels of component c in the overall - /// image. - /// - /// - public int getCompImgWidth(int c, int rl) - { - int sx, ex; - int dl = decSpec.dls.getMinInComp(c) - rl; - // indexation (0 is hi-res) - // Calculate image starting x at component hi-res grid - sx = (ax + hd.getCompSubsX(c) - 1) / hd.getCompSubsX(c); - // Calculate image ending (excluding) x at component hi-res grid - ex = (ax + imgW + hd.getCompSubsX(c) - 1) / hd.getCompSubsX(c); - // The difference at the rl level is the width - return (ex + (1 << dl) - 1) / (1 << dl) - (sx + (1 << dl) - 1) / (1 << dl); - } - - /// Returns the height in pixels of the specified component in the overall - /// image, for the given (component) resolution level. - /// - ///

    Note: Component resolution level indexes may differ from - /// tile-component resolution index. They are indeed indexed starting from - /// the lowest number of decomposition levels of same component of each - /// tile.

    - /// - ///

    Example: For an image (2 tiles) with 1 component (tile 0 having 2 - /// decomposition levels and tile 1 having 3 decomposition levels), the - /// first tile(-component) has 3 resolution levels and the second one has 4 - /// resolution levels, whereas the component has only 3 resolution levels - /// available.

    - /// - ///
    - /// The index of the component, from 0 to N-1. - /// - /// - /// The resolution level, from 0 to L. - /// - /// - /// The height in pixels of component c in the overall - /// image. - /// - /// - public int getCompImgHeight(int c, int rl) - { - int sy, ey; - int dl = decSpec.dls.getMinInComp(c) - rl; - // indexation (0 is hi-res) - // Calculate image starting x at component hi-res grid - sy = (ay + hd.getCompSubsY(c) - 1) / hd.getCompSubsY(c); - // Calculate image ending (excluding) x at component hi-res grid - ey = (ay + imgH + hd.getCompSubsY(c) - 1) / hd.getCompSubsY(c); - // The difference at the rl level is the width - return (ey + (1 << dl) - 1) / (1 << dl) - (sy + (1 << dl) - 1) / (1 << dl); - } - - /// Changes the current tile, given the new indexes. An - /// IllegalArgumentException is thrown if the indexes do not correspond to - /// a valid tile. - /// - /// - /// The horizontal indexes the tile. - /// - /// - /// The vertical indexes of the new tile. - /// - /// - public abstract void setTile(int x, int y); - - /// Advances to the next tile, in standard scan-line order (by rows then - /// columns). An NoNextElementException is thrown if the current tile is - /// the last one (i.e. there is no next tile). - /// - /// - public abstract void nextTile(); - - /// Returns the indexes of the current tile. These are the horizontal and - /// vertical indexes of the current tile. - /// - /// - /// If not null this object is used to return the information. If - /// null a new one is created and returned. - /// - /// - /// The current tile's indexes (vertical and horizontal indexes). - /// - /// - public Coord getTile(Coord co) - { - if (co != null) - { - co.x = ctX; - co.y = ctY; - return co; - } - else - { - return new Coord(ctX, ctY); - } - } - - /// Returns the horizontal coordinate of the upper-left corner of the - /// specified resolution in the given component of the current tile. - /// - /// - /// The component index. - /// - /// - /// The resolution level index. - /// - /// - public int getResULX(int c, int rl) - { - int dl = mdl[c] - rl; - if (dl < 0) - { - throw new System.ArgumentException("Requested resolution level" + " is not available for, at " + "least, one component in " + "tile: " + ctX + "x" + ctY); - } - int tx0 = (int)System.Math.Max(px + ctX * ntW, ax); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - int tcx0 = (int)System.Math.Ceiling(tx0 / (double)getCompSubsX(c)); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - return (int)System.Math.Ceiling(tcx0 / (double)(1 << dl)); - } - - /// Returns the vertical coordinate of the upper-left corner of the - /// specified component in the given component of the current tile. - /// - /// - /// The component index. - /// - /// - /// The resolution level index. - /// - /// - public int getResULY(int c, int rl) - { - int dl = mdl[c] - rl; - if (dl < 0) - { - throw new System.ArgumentException("Requested resolution level" + " is not available for, at " + "least, one component in " + "tile: " + ctX + "x" + ctY); - } - int ty0 = (int)System.Math.Max(py + ctY * ntH, ay); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - int tcy0 = (int)System.Math.Ceiling(ty0 / (double)getCompSubsY(c)); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - return (int)System.Math.Ceiling(tcy0 / (double)(1 << dl)); - } - - /// Returns the number of tiles in the horizontal and vertical directions. - /// - /// - /// If not null this object is used to return the information. If - /// null a new one is created and returned. - /// - /// - /// The number of tiles in the horizontal (Coord.x) and vertical - /// (Coord.y) directions. - /// - /// - public Coord getNumTiles(Coord co) - { - if (co != null) - { - co.x = ntX; - co.y = ntY; - return co; - } - else - { - return new Coord(ntX, ntY); - } - } - - /// Returns the total number of tiles in the image. - /// - /// - /// The total number of tiles in the image. - /// - /// - public int getNumTiles() - { - return ntX * ntY; - } - - /// Returns the subband tree, for the specified tile-component. This method - /// returns the root element of the subband tree structure, see Subband and - /// SubbandSyn. The tree comprises all the available resolution levels. - /// - ///

    Note: this method is not able to return subband tree for a tile - /// different than the current one.

    - /// - ///

    The number of magnitude bits ('magBits' member variable) for each - /// subband is not initialized.

    - /// - ///
    - /// The tile index - /// - /// - /// The index of the component, from 0 to C-1. - /// - /// - /// The root of the tree structure. - /// - /// - public SubbandSyn getSynSubbandTree(int t, int c) - { - if (t != TileIdx) - { - throw new System.ArgumentException("Can not request subband" + " tree of a different tile" + " than the current one"); - } - if (c < 0 || c >= nc) - { - throw new System.ArgumentException("Component index out of range"); - } - return subbTrees[c]; - } - - /// Creates a bit stream reader of the correct type that works on the - /// provided RandomAccessIO, with the special parameters from the parameter - /// list. - /// - /// - /// The RandomAccessIO source from which to read the bit stream. - /// - /// - /// Header of the codestream. - /// - /// - /// The parameter list containing parameters applicable to the - /// bit stream read (other parameters may also be present). - /// - /// - /// The decoder specifications - /// - /// - /// Whether or not to print information found in - /// codestream. - /// - /// - /// Reference to the HeaderInfo instance. - /// - /// - /// If an I/O error occurs while reading initial - /// data from the bit stream. - /// - /// If an unrecognised bit stream - /// reader option is present. - /// - /// - public static BitstreamReaderAgent createInstance(RandomAccessIO in_Renamed, HeaderDecoder hd, ParameterList pl, DecoderSpecs decSpec, bool cdstrInfo, HeaderInfo hi) - { - - // Check parameters - pl.checkList(BitstreamReaderAgent.OPT_PREFIX, CSJ2K.j2k.util.ParameterList.toNameArray(BitstreamReaderAgent.ParameterInfo)); - - return new FileBitstreamReaderAgent(hd, in_Renamed, decSpec, pl, cdstrInfo, hi); - } - - /// Returns the precinct partition width for the specified tile-component - /// and (tile-component) resolution level. - /// - /// - /// the tile index - /// - /// - /// The index of the component (between 0 and N-1) - /// - /// - /// The resolution level, from 0 to L. - /// - /// - /// the precinct partition width for the specified component, - /// resolution level and tile. - /// - /// - public int getPPX(int t, int c, int rl) - { - return decSpec.pss.getPPX(t, c, rl); - } - - /// Returns the precinct partition height for the specified tile-component - /// and (tile-component) resolution level. - /// - /// - /// The tile index - /// - /// - /// The index of the component (between 0 and N-1) - /// - /// - /// The resolution level, from 0 to L. - /// - /// - /// The precinct partition height in the specified component, for - /// the specified resolution level, for the current tile. - /// - /// - public int getPPY(int t, int c, int rl) - { - return decSpec.pss.getPPY(t, c, rl); - } - - /// Initialises subbands fields, such as number of code-blocks, code-blocks - /// dimension and number of magnitude bits, in the subband tree. The - /// nominal code-block width/height depends on the precincts dimensions if - /// used. The way the number of magnitude bits is computed depends on the - /// quantization type (reversible, derived, expounded). - /// - /// - /// The component index - /// - /// - /// The subband tree to be initialised. - /// - /// - protected internal virtual void initSubbandsFields(int c, SubbandSyn sb) - { - int t = TileIdx; - int rl = sb.resLvl; - int cbw, cbh; - - cbw = decSpec.cblks.getCBlkWidth(ModuleSpec.SPEC_TILE_COMP, t, c); - cbh = decSpec.cblks.getCBlkHeight(ModuleSpec.SPEC_TILE_COMP, t, c); - - if (!sb.isNode) - { - // Code-block dimensions - if (hd.precinctPartitionUsed()) - { - // The precinct partition is used - int ppxExp, ppyExp, cbwExp, cbhExp; - - // Get exponents - ppxExp = MathUtil.log2(getPPX(t, c, rl)); - ppyExp = MathUtil.log2(getPPY(t, c, rl)); - cbwExp = MathUtil.log2(cbw); - cbhExp = MathUtil.log2(cbh); - - switch (sb.resLvl) - { - - case 0: - sb.nomCBlkW = (cbwExp < ppxExp ? (1 << cbwExp) : (1 << ppxExp)); - sb.nomCBlkH = (cbhExp < ppyExp ? (1 << cbhExp) : (1 << ppyExp)); - break; - - - default: - sb.nomCBlkW = (cbwExp < ppxExp - 1 ? (1 << cbwExp) : (1 << (ppxExp - 1))); - sb.nomCBlkH = (cbhExp < ppyExp - 1 ? (1 << cbhExp) : (1 << (ppyExp - 1))); - break; - - } - } - else - { - sb.nomCBlkW = cbw; - sb.nomCBlkH = cbh; - } - - // Number of code-blocks - if (sb.numCb == null) - sb.numCb = new Coord(); - if (sb.w == 0 || sb.h == 0) - { - sb.numCb.x = 0; - sb.numCb.y = 0; - } - else - { - int cb0x = CbULX; - int cb0y = CbULY; - int tmp; - - // Projects code-block partition origin to subband. Since the - // origin is always 0 or 1, it projects to the low-pass side - // (throught the ceil operator) as itself (i.e. no change) and - // to the high-pass side (through the floor operator) as 0, - // always. - int acb0x = cb0x; - int acb0y = cb0y; - - switch (sb.sbandIdx) - { - - case Subband.WT_ORIENT_LL: - // No need to project since all low-pass => nothing to do - break; - - case Subband.WT_ORIENT_HL: - acb0x = 0; - break; - - case Subband.WT_ORIENT_LH: - acb0y = 0; - break; - - case Subband.WT_ORIENT_HH: - acb0x = 0; - acb0y = 0; - break; - - default: - throw new System.ApplicationException("Internal JJ2000 error"); - - } - if (sb.ulcx - acb0x < 0 || sb.ulcy - acb0y < 0) - { - throw new System.ArgumentException("Invalid code-blocks " + "partition origin or " + "image offset in the " + "reference grid."); - } - - // NOTE: when calculating "floor()" by integer division the - // dividend and divisor must be positive, we ensure that by - // adding the divisor to the dividend and then substracting 1 - // to the result of the division - - tmp = sb.ulcx - acb0x + sb.nomCBlkW; - sb.numCb.x = (tmp + sb.w - 1) / sb.nomCBlkW - (tmp / sb.nomCBlkW - 1); - - tmp = sb.ulcy - acb0y + sb.nomCBlkH; - sb.numCb.y = (tmp + sb.h - 1) / sb.nomCBlkH - (tmp / sb.nomCBlkH - 1); - } - - // Number of magnitude bits - if (derived[c]) - { - sb.magbits = gb[c] + (params_Renamed[c].exp[0][0] - (mdl[c] - sb.level)) - 1; - } - else - { - sb.magbits = gb[c] + params_Renamed[c].exp[sb.resLvl][sb.sbandIdx] - 1; - } - } - else - { - initSubbandsFields(c, (SubbandSyn)sb.LL); - initSubbandsFields(c, (SubbandSyn)sb.HL); - initSubbandsFields(c, (SubbandSyn)sb.LH); - initSubbandsFields(c, (SubbandSyn)sb.HH); - } - } - public abstract CSJ2K.j2k.entropy.decoder.DecLyrdCBlk getCodeBlock(int param1, int param2, int param3, CSJ2K.j2k.wavelet.synthesis.SubbandSyn param4, int param5, int param6, CSJ2K.j2k.entropy.decoder.DecLyrdCBlk param7); - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/codestream/reader/CBlkInfo.cs b/CSJ2K/j2k/codestream/reader/CBlkInfo.cs deleted file mode 100644 index 3d16ebf8..00000000 --- a/CSJ2K/j2k/codestream/reader/CBlkInfo.cs +++ /dev/null @@ -1,173 +0,0 @@ -/* -* CVS identifier: -* -* $Id: CBlkInfo.java,v 1.12 2001/09/14 08:32:15 grosbois Exp $ -* -* Class: CBlkInfo -* -* Description: Object containing code-block informations. -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -namespace CSJ2K.j2k.codestream.reader -{ - - /// This class contains location of code-blocks' piece of codewords (there is - /// one piece per layer) and some other information. - /// - /// - public class CBlkInfo - { - - /// Upper-left x-coordinate of the code-block (relative to the tile) - public int ulx; - - /// Upper-left y-coordinate of the code-block (relative to the tile) - public int uly; - - /// Width of the code-block - public int w; - - /// Height of the code-block - public int h; - - /// The number of most significant bits which are skipped for this - /// code-block (= Mb-1-bitDepth). - /// - public int msbSkipped; - - /// Length of each piece of code-block's codewords - public int[] len; - - /// Offset of each piece of code-block's codewords in the file - public int[] off; - - /// The number of truncation point for each layer - public int[] ntp; - - /// The cumulative number of truncation points - public int ctp; - - /// The length of each segment (used with regular termination or in - /// selective arithmetic bypass coding mode) - /// - public int[][] segLen; - - /// Index of the packet where each layer has been found - public int[] pktIdx; - - /// Constructs a new instance with specified number of layers and - /// code-block coordinates. The number corresponds to the maximum piece of - /// codeword for one code-block. - /// - /// - /// The uper-left x-coordinate - /// - /// - /// The uper-left y-coordinate - /// - /// - /// Width of the code-block - /// - /// - /// Height of the code-block - /// - /// - /// The number of layers - /// - /// - public CBlkInfo(int ulx, int uly, int w, int h, int nl) - { - this.ulx = ulx; - this.uly = uly; - this.w = w; - this.h = h; - off = new int[nl]; - len = new int[nl]; - ntp = new int[nl]; - segLen = new int[nl][]; - pktIdx = new int[nl]; - for (int i = nl - 1; i >= 0; i--) - { - pktIdx[i] = -1; - } - } - - /// Adds the number of new truncation for specified layer. - /// - /// - /// layer index - /// - /// - /// Number of new truncation points - /// - /// - public virtual void addNTP(int l, int newtp) - { - ntp[l] = newtp; - ctp = 0; - for (int lIdx = 0; lIdx <= l; lIdx++) - { - ctp += ntp[lIdx]; - } - } - - /// Object information in a string. - /// - /// - /// Object information - /// - /// - public override System.String ToString() - { - System.String string_Renamed = "(ulx,uly,w,h)= (" + ulx + "," + uly + "," + w + "," + h; - string_Renamed += (") " + msbSkipped + " MSB bit(s) skipped\n"); - if (len != null) - for (int i = 0; i < len.Length; i++) - { - string_Renamed += ("\tl:" + i + ", start:" + off[i] + ", len:" + len[i] + ", ntp:" + ntp[i] + ", pktIdx=" + pktIdx[i]); - if (segLen != null && segLen[i] != null) - { - string_Renamed += " { "; - for (int j = 0; j < segLen[i].Length; j++) - string_Renamed += (segLen[i][j] + " "); - string_Renamed += "}"; - } - string_Renamed += "\n"; - } - string_Renamed += ("\tctp=" + ctp); - return string_Renamed; - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/codestream/reader/FileBitstreamReaderAgent.cs b/CSJ2K/j2k/codestream/reader/FileBitstreamReaderAgent.cs deleted file mode 100644 index 33ff6031..00000000 --- a/CSJ2K/j2k/codestream/reader/FileBitstreamReaderAgent.cs +++ /dev/null @@ -1,2727 +0,0 @@ -/* -* CVS identifier: -* -* $Id: FileBitstreamReaderAgent.java,v 1.68 2002/07/19 12:34:38 grosbois Exp $ -* -* Class: FileBitstreamReaderAgent -* -* Description: Retrieve code-blocks codewords in the bit stream -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.decoder; -using CSJ2K.j2k.entropy.decoder; -using CSJ2K.j2k.image; -using CSJ2K.j2k.io; -using CSJ2K.j2k.quantization.dequantizer; -using CSJ2K.j2k.util; -using CSJ2K.j2k.wavelet.synthesis; -using System; -namespace CSJ2K.j2k.codestream.reader -{ - - /// This class reads the bit stream (with the help of HeaderDecoder for tile - /// headers and PktDecoder for packets header and body) and retrives location - /// of all code-block's codewords. - /// - ///

    Note: All tile-parts headers are read by the constructor whereas packets - /// are processed when decoding related tile (when setTile method is - /// called).

    - /// - ///

    In parsing mode, the reader simulates a virtual layer-resolution - /// progressive bit stream with the same truncation points in each code-block, - /// whereas in truncation mode, only the first bytes are taken into account (it - /// behaves like if it is a real truncated codestream).

    - /// - ///
    - /// - /// - /// - /// - /// - public class FileBitstreamReaderAgent : BitstreamReaderAgent - { - /// Gets the reference to the CBlkInfo array - virtual public CBlkInfo[][][][][] CBlkInfo - { - get - { - return cbI; - } - - } - - /// Whether or not the last read Psot value was zero. Only the Psot in the - /// last tile-part in the codestream can have such a value. - /// - private bool isPsotEqualsZero = true; - - /// Reference to the PktDecoder instance - public PktDecoder pktDec; - - /// Reference to the ParameterList instance - private ParameterList pl; - - /// The RandomAccessIO where to get data from - private RandomAccessIO in_Renamed; - - /// Offset of the first packet in each tile-part in each tile - private int[][] firstPackOff; - - /// Returns the number of tile-part found for a given tile - /// - /// - /// Tile index - /// - /// - /// - public virtual int getNumTileParts(int t) - { - if (firstPackOff == null || firstPackOff[t] == null) - { - throw new System.ApplicationException("Tile " + t + " not found in input codestream."); - } - return firstPackOff[t].Length; - } - - /// Number of bytes allocated to each tile. In parsing mode, this number - /// is related to the tile length in the codestream whereas in truncation - /// mode all the rate is affected to the first tiles. - /// - private int[] nBytes; - - /// Whether or not to print information found in codestream - private bool printInfo = false; - - /// Backup of the number of bytes allocated to each tile. This array is - /// used to restore the number of bytes to read in each tile when the - /// codestream is read several times (for instance when decoding an R,G,B - /// image to three output files) - /// - /// - private int[] baknBytes; - - /// Length of each tile-part (written in Psot) - private int[][] tilePartLen; - - /// Total length of each tile - private int[] totTileLen; - - /// Total length of tiles' header - private int[] totTileHeadLen; - - /// First tile part header length - private int firstTilePartHeadLen; - - /// Total length of all tile parts in all tiles - private double totAllTileLen; - - /// Length of main header - private int mainHeadLen; - - /// Length of main and tile-parts headers - private int headLen = 0; - - /// Length of all tile-part headers - private int[][] tilePartHeadLen; - - /// Length of each packet head found in the tile - private System.Collections.ArrayList pktHL; - - /// Layer starting positions - public System.Collections.Generic.List layerStarts; - - /// True if truncation mode is used. False if parsing mode - private bool isTruncMode; - - /// The number of tile-parts that remain to read - private int remainingTileParts; - - /// The number of tile-parts read so far for each tile - private int[] tilePartsRead; - - /// Thetotal number of tile-parts read so far - private int totTilePartsRead = 0; - - /// The number of found tile-parts in each tile. - private int[] tileParts; - - /// The current tile part being used - private int curTilePart; - - /// The number of the tile-parts found in the codestream after reading the - /// tp'th tile-part of tile t - /// - private int[][] tilePartNum; - - /// Whether or not a EOC marker has been found instead of a SOT - private bool isEOCFound = false; - - /// Reference to the HeaderInfo instance (used when reading SOT marker - /// segments) - /// - private HeaderInfo hi; - - /// Array containing information for all the code-blocks: - /// - ///
      - ///
    • 1st dim: component index.
    • - ///
    • 2nd dim: resolution level index.
    • - ///
    • 3rd dim: subband index.
    • - ///
    • 4th/5th dim: code-block index (vert. and horiz.).
    • - ///
    - ///
    - private CBlkInfo[][][][][] cbI; - - /// The maximum number of layers to decode for any code-block - private int lQuit; - - /// Whether or not to use only first progression order - private bool usePOCQuit = false; - - /// Reads all tiles headers and keep offset of their first - /// packet. Finally it calls the rate allocation method. - /// - /// - /// HeaderDecoder of the codestream. - /// - /// - /// The input stream where to read bit-stream. - /// - /// - /// The decoder specifications - /// - /// - /// The ParameterList instance created from the - /// command-line arguments. - /// - /// - /// Whether or not to print information found in - /// codestream. - /// - /// - /// - /// - /// - public FileBitstreamReaderAgent(HeaderDecoder hd, RandomAccessIO ehs, DecoderSpecs decSpec, ParameterList pl, bool cdstrInfo, HeaderInfo hi) : base(hd, decSpec) - { - - this.pl = pl; - this.printInfo = cdstrInfo; - this.hi = hi; - - // Check whether quit conditiosn used - usePOCQuit = pl.getBooleanParameter("poc_quit"); - - // Get decoding rate - bool rateInBytes; - bool parsing = pl.getBooleanParameter("parsing"); - try - { - trate = pl.getFloatParameter("rate"); - if (trate == -1) - { - trate = System.Single.MaxValue; - } - } - catch (System.FormatException) - { - throw new System.ApplicationException("Invalid value in 'rate' option: " + pl.getParameter("rate")); - } - catch (System.ArgumentException) - { - throw new System.ApplicationException("'rate' option is missing"); - } - - try - { - tnbytes = pl.getIntParameter("nbytes"); - } - catch (System.FormatException) - { - throw new System.ApplicationException("Invalid value in 'nbytes' option: " + pl.getParameter("nbytes")); - } - catch (System.ArgumentException) - { - throw new System.ApplicationException("'nbytes' option is missing"); - } - - // Check that '-rate' and '-nbytes' are not used at the same time - ParameterList defaults = pl.DefaultParameterList; - if (tnbytes != defaults.getFloatParameter("nbytes")) - { - rateInBytes = true; - } - else - { - rateInBytes = false; - } - - if (rateInBytes) - { - trate = tnbytes * 8f / hd.MaxCompImgWidth / hd.MaxCompImgHeight; - } - else - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - tnbytes = (int)(trate * hd.MaxCompImgWidth * hd.MaxCompImgHeight) / 8; - if (tnbytes < 0) tnbytes = int.MaxValue; - } - isTruncMode = !pl.getBooleanParameter("parsing"); - - // Check if quit conditions are being used - int ncbQuit; - try - { - ncbQuit = pl.getIntParameter("ncb_quit"); - } - catch (System.FormatException) - { - throw new System.ApplicationException("Invalid value in 'ncb_quit' option: " + pl.getParameter("ncb_quit")); - } - catch (System.ArgumentException) - { - throw new System.ApplicationException("'ncb_quit' option is missing"); - } - if (ncbQuit != -1 && !isTruncMode) - { - throw new System.ApplicationException("Cannot use -parsing and -ncb_quit condition at " + "the same time."); - } - - try - { - lQuit = pl.getIntParameter("l_quit"); - } - catch (System.FormatException) - { - throw new System.ApplicationException("Invalid value in 'l_quit' option: " + pl.getParameter("l_quit")); - } - catch (System.ArgumentException) - { - throw new System.ApplicationException("'l_quit' option is missing"); - } - - // initializations - in_Renamed = ehs; - pktDec = new PktDecoder(decSpec, hd, ehs, this, isTruncMode, ncbQuit); - - tileParts = new int[nt]; - totTileLen = new int[nt]; - tilePartLen = new int[nt][]; - tilePartNum = new int[nt][]; - firstPackOff = new int[nt][]; - tilePartsRead = new int[nt]; - totTileHeadLen = new int[nt]; - tilePartHeadLen = new int[nt][]; - nBytes = new int[nt]; - baknBytes = new int[nt]; - hd.nTileParts = new int[nt]; - - // CONVERSION PROBLEM? - //this.isTruncMode = isTruncMode; - int t = 0, pos, tp = 0, tptot = 0; - - // Keeps main header's length, takes file format overhead into account - int cdstreamStart = hd.mainHeadOff; // Codestream offset in the file - mainHeadLen = in_Renamed.Pos - cdstreamStart; - headLen = mainHeadLen; - - // If ncb and lbody quit conditions are used, headers are not counted - if (ncbQuit == -1) - { - anbytes = mainHeadLen; - } - else - { - anbytes = 0; - } - - // If cannot even read the first tile-part - if (anbytes > tnbytes) - { - throw new System.ApplicationException("Requested bitrate is too small."); - } - - // Read all tile-part headers from all tiles. - int tilePartStart; - bool rateReached = false; - int mdl; - //int numtp = 0; - totAllTileLen = 0; - remainingTileParts = nt; // at least as many tile-parts as tiles - int maxTP = nt; // If maximum 1 tile part per tile specified - - try - { - while (remainingTileParts != 0) - { - - tilePartStart = in_Renamed.Pos; - // Read tile-part header - try - { - t = readTilePartHeader(); - if (isEOCFound) - { - // Some tiles are missing but the - // codestream is OK - break; - } - tp = tilePartsRead[t]; - if (isPsotEqualsZero) - { - // Psot may equals zero for the - // last tile-part: it is assumed that this tile-part - // contain all data until EOC - tilePartLen[t][tp] = in_Renamed.length() - 2 - tilePartStart; - } - } - catch (System.IO.EndOfStreamException e) - { - firstPackOff[t][tp] = in_Renamed.length(); - throw e; - } - - pos = in_Renamed.Pos; - - // In truncation mode, if target decoding rate is reached in - // tile-part header, skips the tile-part and stop reading - // unless the ncb and lbody quit condition is in use - if (isTruncMode && ncbQuit == -1) - { - if ((pos - cdstreamStart) > tnbytes) - { - firstPackOff[t][tp] = in_Renamed.length(); - rateReached = true; - break; - } - } - - // Set tile part position and header length - firstPackOff[t][tp] = pos; - tilePartHeadLen[t][tp] = (pos - tilePartStart); - - // Update length counters - totTileLen[t] += tilePartLen[t][tp]; - totTileHeadLen[t] += tilePartHeadLen[t][tp]; - totAllTileLen += tilePartLen[t][tp]; - if (isTruncMode) - { - if (anbytes + tilePartLen[t][tp] > tnbytes) - { - anbytes += tilePartHeadLen[t][tp]; - headLen += tilePartHeadLen[t][tp]; - rateReached = true; - nBytes[t] += (tnbytes - anbytes); - break; - } - else - { - anbytes += tilePartHeadLen[t][tp]; - headLen += tilePartHeadLen[t][tp]; - nBytes[t] += (tilePartLen[t][tp] - tilePartHeadLen[t][tp]); - } - } - else - { - if (anbytes + tilePartHeadLen[t][tp] > tnbytes) - { - break; - } - else - { - anbytes += tilePartHeadLen[t][tp]; - headLen += tilePartHeadLen[t][tp]; - } - } - - // If this is first tile-part, remember header length - if (tptot == 0) - firstTilePartHeadLen = tilePartHeadLen[t][tp]; - - // Go to the beginning of next tile part - tilePartsRead[t]++; - in_Renamed.seek(tilePartStart + tilePartLen[t][tp]); - remainingTileParts--; - maxTP--; - tptot++; - - // If Psot of the current tile-part was equal to zero, it is - // assumed that it contains all data until the EOC marker - if (isPsotEqualsZero) - { - if (remainingTileParts != 0) - { - FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.WARNING, "Some tile-parts have not " + "been found. The codestream may be corrupted."); - } - break; - } - } - } - catch (System.IO.EndOfStreamException) - { - if (printInfo) - { - } - FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.WARNING, "Codestream truncated in tile " + t); - - // Set specified rate to end of file if valid - int fileLen = in_Renamed.length(); - if (fileLen < tnbytes) - { - tnbytes = fileLen; - trate = tnbytes * 8f / hd.MaxCompImgWidth / hd.MaxCompImgHeight; - } - - // Bit-rate allocation - if (!isTruncMode) - { - allocateRate(); - } - - // Update 'res' value once all tile-part headers are read - if (pl.getParameter("res") == null) - { - targetRes = decSpec.dls.Min; - } - else - { - try - { - targetRes = pl.getIntParameter("res"); - if (targetRes < 0) - { - throw new System.ArgumentException("Specified negative " + "resolution level " + "index: " + targetRes); - } - } - catch (System.FormatException) - { - throw new System.ArgumentException("Invalid resolution level " + "index ('-res' option) " + pl.getParameter("res")); - } - } - - // Verify reduction in resolution level - mdl = decSpec.dls.Min; - if (targetRes > mdl) - { - FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.WARNING, "Specified resolution level (" + targetRes + ") is larger" + " than the maximum value. Setting it to " + mdl + " (maximum value)"); - targetRes = mdl; - } - - // Backup nBytes - for (int tIdx = 0; tIdx < nt; tIdx++) - { - baknBytes[tIdx] = nBytes[tIdx]; - } - - return; - } - remainingTileParts = 0; - - // Update 'res' value once all tile-part headers are read - if (pl.getParameter("res") == null) - { - targetRes = decSpec.dls.Min; - } - else - { - try - { - targetRes = pl.getIntParameter("res"); - if (targetRes < 0) - { - throw new System.ArgumentException("Specified negative " + "resolution level index: " + targetRes); - } - } - catch (System.FormatException) - { - throw new System.ArgumentException("Invalid resolution level " + "index ('-res' option) " + pl.getParameter("res")); - } - } - - // Verify reduction in resolution level - mdl = decSpec.dls.Min; - if (targetRes > mdl) - { - FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.WARNING, "Specified resolution level (" + targetRes + ") is larger" + " than the maximum possible. Setting it to " + mdl + " (maximum possible)"); - targetRes = mdl; - } - - if (printInfo) - { - } - - // Check presence of EOC marker is decoding rate not reached or if - // this marker has not been found yet - if (!isEOCFound && !isPsotEqualsZero) - { - try - { - short eocCheck = 0; - if (in_Renamed.Pos + sizeof(short) <= in_Renamed.length()) - eocCheck = in_Renamed.readShort(); - - if (!rateReached && !isPsotEqualsZero && eocCheck != CSJ2K.j2k.codestream.Markers.EOC) - { - FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.WARNING, "EOC marker not found. " + "Codestream is corrupted."); - } - } - catch (System.IO.EndOfStreamException) - { - FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.WARNING, "EOC marker is missing"); - } - } - - // Bit-rate allocation - if (!isTruncMode) - { - allocateRate(); - } - else - { - // Take EOC into account if rate is not reached - if (in_Renamed.Pos >= tnbytes) - anbytes += 2; - } - - // Backup nBytes - for (int tIdx = 0; tIdx < nt; tIdx++) - { - baknBytes[tIdx] = nBytes[tIdx]; - if (printInfo) - { - FacilityManager.getMsgLogger().println("" + hi.toStringTileHeader(tIdx, tilePartLen[tIdx].Length), 2, 2); - } - } - } - - /// Allocates output bit-rate for each tile in parsing mode: The allocator - /// simulates the truncation of a virtual layer-resolution progressive - /// codestream. - /// - /// - private void allocateRate() - { - int stopOff = tnbytes; - - // In parsing mode, the bitrate is allocated related to each tile's - // length in the bit stream - - // EOC marker's length - anbytes += 2; - - // If there are too few bytes to read the tile part headers throw an - // error - if (anbytes > stopOff) - { - throw new System.ApplicationException("Requested bitrate is too small for parsing"); - } - - // Calculate bitrate for each tile - int rem = stopOff - anbytes; - int totnByte = rem; - for (int t = nt - 1; t > 0; t--) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - rem -= (nBytes[t] = (int)(totnByte * (totTileLen[t] / totAllTileLen))); - } - nBytes[0] = rem; - } - - /// Reads SOT marker segment of the tile-part header and calls related - /// methods of the HeaderDecoder to read other markers segments. The - /// tile-part header is entirely read when a SOD marker is encountered. - /// - /// - /// The tile number of the tile part that was read - /// - /// - private int readTilePartHeader() - { - HeaderInfo.SOT ms = hi.NewSOT; - - // SOT marker - short marker = in_Renamed.readShort(); - if (marker != CSJ2K.j2k.codestream.Markers.SOT) - { - if (marker == CSJ2K.j2k.codestream.Markers.EOC) - { - isEOCFound = true; - return -1; - } - else - { - throw new CorruptedCodestreamException("SOT tag not found " + "in tile-part start"); - } - } - isEOCFound = false; - - // Lsot (shall equals 10) - int lsot = in_Renamed.readUnsignedShort(); - ms.lsot = lsot; - if (lsot != 10) - throw new CorruptedCodestreamException("Wrong length for " + "SOT marker segment: " + lsot); - - // Isot - int tile = in_Renamed.readUnsignedShort(); - ms.isot = tile; - if (tile > 65534) - { - throw new CorruptedCodestreamException("Tile index too high in " + "tile-part."); - } - - // Psot - int psot = in_Renamed.readInt(); - ms.psot = psot; - isPsotEqualsZero = (psot != 0) ? false : true; - if (psot < 0) - { - throw new NotImplementedException("Tile length larger " + "than maximum supported"); - } - // TPsot - int tilePart = in_Renamed.read(); - ms.tpsot = tilePart; - if (tilePart != tilePartsRead[tile] || tilePart < 0 || tilePart > 254) - { - throw new CorruptedCodestreamException("Out of order tile-part"); - } - // TNsot - int nrOfTileParts = in_Renamed.read(); - ms.tnsot = nrOfTileParts; - hi.sotValue["t" + tile + "_tp" + tilePart] = ms; - if (nrOfTileParts == 0) - { - // The number of tile-part is not specified in - // this tile-part header. - - // Assumes that there will be another tile-part in the codestream - // that will indicate the number of tile-parts for this tile) - int nExtraTp; - if (tileParts[tile] == 0 || tileParts[tile] == tilePartLen.Length) - { - // Then there are two tile-parts (one is the current and the - // other will indicate the number of tile-part for this tile) - nExtraTp = 2; - remainingTileParts += 1; - } - else - { - // There is already one scheduled extra tile-part. In this - // case just add place for the current one - nExtraTp = 1; - } - - tileParts[tile] += nExtraTp; - nrOfTileParts = tileParts[tile]; - FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.WARNING, "Header of tile-part " + tilePart + " of tile " + tile + ", does not indicate the total" + " number of tile-parts. Assuming that there are " + nrOfTileParts + " tile-parts for this tile."); - - // Increase and re-copy tilePartLen array - int[] tmpA = tilePartLen[tile]; - tilePartLen[tile] = new int[nrOfTileParts]; - for (int i = 0; i < nrOfTileParts - nExtraTp; i++) - { - tilePartLen[tile][i] = tmpA[i]; - } - - // Increase and re-copy tilePartNum array - tmpA = tilePartNum[tile]; - tilePartNum[tile] = new int[nrOfTileParts]; - for (int i = 0; i < nrOfTileParts - nExtraTp; i++) - { - tilePartNum[tile][i] = tmpA[i]; - } - - // Increase and re-copy firsPackOff array - tmpA = firstPackOff[tile]; - firstPackOff[tile] = new int[nrOfTileParts]; - for (int i = 0; i < nrOfTileParts - nExtraTp; i++) - { - firstPackOff[tile][i] = tmpA[i]; - } - - // Increase and re-copy tilePartHeadLen array - tmpA = tilePartHeadLen[tile]; - tilePartHeadLen[tile] = new int[nrOfTileParts]; - for (int i = 0; i < nrOfTileParts - nExtraTp; i++) - { - tilePartHeadLen[tile][i] = tmpA[i]; - } - } - else - { - // The number of tile-parts is specified in the tile-part - // header - - // Check if it is consistant with what was found in previous - // tile-part headers - - if (tileParts[tile] == 0) - { - // First tile-part: OK - remainingTileParts += nrOfTileParts - 1; - tileParts[tile] = nrOfTileParts; - tilePartLen[tile] = new int[nrOfTileParts]; - tilePartNum[tile] = new int[nrOfTileParts]; - firstPackOff[tile] = new int[nrOfTileParts]; - tilePartHeadLen[tile] = new int[nrOfTileParts]; - } - else if (tileParts[tile] > nrOfTileParts) - { - // Already found more tile-parts than signaled here - throw new CorruptedCodestreamException("Invalid number " + "of tile-parts in" + " tile " + tile + ": " + nrOfTileParts); - } - else - { - // Signaled number of tile-part fits with number of - // previously found tile-parts - remainingTileParts += nrOfTileParts - tileParts[tile]; - - if (tileParts[tile] != nrOfTileParts) - { - - // Increase and re-copy tilePartLen array - int[] tmpA = tilePartLen[tile]; - tilePartLen[tile] = new int[nrOfTileParts]; - for (int i = 0; i < tileParts[tile] - 1; i++) - { - tilePartLen[tile][i] = tmpA[i]; - } - - // Increase and re-copy tilePartNum array - tmpA = tilePartNum[tile]; - tilePartNum[tile] = new int[nrOfTileParts]; - for (int i = 0; i < tileParts[tile] - 1; i++) - { - tilePartNum[tile][i] = tmpA[i]; - } - - // Increase and re-copy firstPackOff array - tmpA = firstPackOff[tile]; - firstPackOff[tile] = new int[nrOfTileParts]; - for (int i = 0; i < tileParts[tile] - 1; i++) - { - firstPackOff[tile][i] = tmpA[i]; - } - - // Increase and re-copy tilePartHeadLen array - tmpA = tilePartHeadLen[tile]; - tilePartHeadLen[tile] = new int[nrOfTileParts]; - for (int i = 0; i < tileParts[tile] - 1; i++) - { - tilePartHeadLen[tile][i] = tmpA[i]; - } - } - } - } - - // Other markers - hd.resetHeaderMarkers(); - hd.nTileParts[tile] = nrOfTileParts; - // Decode and store the tile-part header (i.e. until a SOD marker is - // found) - do - { - hd.extractTilePartMarkSeg(in_Renamed.readShort(), in_Renamed, tile, tilePart); - } - while ((hd.NumFoundMarkSeg & CSJ2K.j2k.codestream.reader.HeaderDecoder.SOD_FOUND) == 0); - - // Read each marker segment previously found - hd.readFoundTilePartMarkSeg(tile, tilePart); - - tilePartLen[tile][tilePart] = psot; - - tilePartNum[tile][tilePart] = totTilePartsRead; - totTilePartsRead++; - - // Add to list of which tile each successive tile-part belongs. - // This list is needed if there are PPM markers used - hd.TileOfTileParts = tile; - - return tile; - } - - /// Reads packets of the current tile according to the - /// layer-resolution-component-position progressiveness. - /// - /// - /// Index of the first layer for each component and resolution. - /// - /// - /// Index of the last layer. - /// - /// - /// Index of the first resolution level. - /// - /// - /// Index of the last resolution level. - /// - /// - /// Index of the first component. - /// - /// - /// Index of the last component. - /// - /// - /// True if rate has been reached. - /// - /// - private bool readLyResCompPos(int[][] lys, int lye, int ress, int rese, int comps, int compe) - { - - int minlys = 10000; - for (int c = comps; c < compe; c++) - { - //loop on components - // Check if this component exists - if (c >= mdl.Length) - continue; - - for (int r = ress; r < rese; r++) - { - //loop on resolution levels - if (lys[c] != null && r < lys[c].Length && lys[c][r] < minlys) - { - minlys = lys[c][r]; - } - } - } - - int t = TileIdx; - int start; - bool status = false; - int lastByte = firstPackOff[t][curTilePart] + tilePartLen[t][curTilePart] - 1 - tilePartHeadLen[t][curTilePart]; - int numLayers = ((System.Int32)decSpec.nls.getTileDef(t)); - int nPrec = 1; - int hlen, plen; - bool pph = false; - if (((System.Boolean)decSpec.pphs.getTileDef(t))) - { - pph = true; - } - for (int l = minlys; l < lye; l++) - { - // store the layer starting position - layerStarts.Add(in_Renamed.Pos); - - // loop on layers - for (int r = ress; r < rese; r++) - { - // loop on resolution levels - for (int c = comps; c < compe; c++) - { - // loop on components - // Checks if component exists - if (c >= mdl.Length) - continue; - // Checks if resolution level exists - if (r >= lys[c].Length) - continue; - if (r > mdl[c]) - continue; - // Checks if layer exists - if (l < lys[c][r] || l >= numLayers) - continue; - - nPrec = pktDec.getNumPrecinct(c, r); - for (int p = 0; p < nPrec; p++) - { - // loop on precincts - start = in_Renamed.Pos; - - // If packed packet headers are used, there is no need - // to check that there are bytes enough to read header - if (pph) - { - pktDec.readPktHead(l, r, c, p, cbI[c][r], nBytes); - } - - // If we are about to read outside of tile-part, - // skip to next tile-part - if (start > lastByte && curTilePart < firstPackOff[t].Length - 1) - { - curTilePart++; - in_Renamed.seek(firstPackOff[t][curTilePart]); - lastByte = in_Renamed.Pos + tilePartLen[t][curTilePart] - 1 - tilePartHeadLen[t][curTilePart]; - } - - // Read SOP marker segment if necessary - status = pktDec.readSOPMarker(nBytes, p, c, r); - - if (status) - { - if (printInfo) - { - } - return true; - } - - if (!pph) - { - status = pktDec.readPktHead(l, r, c, p, cbI[c][r], nBytes); - } - - if (status) - { - if (printInfo) - { - } - return true; - } - - // Store packet's head length - hlen = in_Renamed.Pos - start; - pktHL.Add((System.Int32)hlen); - - // Reads packet's body - status = pktDec.readPktBody(l, r, c, p, cbI[c][r], nBytes); - plen = in_Renamed.Pos - start; - - if (status) - { - if (printInfo) - { - } - return true; - } - } // end loop on precincts - } // end loop on components - } // end loop on resolution levels - } // end loop on layers - - if (printInfo) - { - } - return false; // Decoding rate was not reached - } - - /// Reads packets of the current tile according to the - /// resolution-layer-component-position progressiveness. - /// - /// - /// Index of the first layer for each component and resolution. - /// - /// - /// Index of the last layer. - /// - /// - /// Index of the first resolution level. - /// - /// - /// Index of the last resolution level. - /// - /// - /// Index of the first component. - /// - /// - /// Index of the last component. - /// - /// - /// True if rate has been reached. - /// - /// - private bool readResLyCompPos(int[][] lys, int lye, int ress, int rese, int comps, int compe) - { - - int t = TileIdx; // Current tile index - bool status = false; // True if decoding rate is reached when - int lastByte = firstPackOff[t][curTilePart] + tilePartLen[t][curTilePart] - 1 - tilePartHeadLen[t][curTilePart]; - int minlys = 10000; - for (int c = comps; c < compe; c++) - { - //loop on components - // Check if this component exists - if (c >= mdl.Length) - continue; - - for (int r = ress; r < rese; r++) - { - //loop on resolution levels - if (r > mdl[c]) - continue; - if (lys[c] != null && r < lys[c].Length && lys[c][r] < minlys) - { - minlys = lys[c][r]; - } - } - } - - int numLayers = ((System.Int32)decSpec.nls.getTileDef(t)); - bool pph = false; - if (((System.Boolean)decSpec.pphs.getTileDef(t))) - { - pph = true; - } - int nPrec = 1; - int start; - int hlen, plen; - for (int r = ress; r < rese; r++) - { - // loop on resolution levels - for (int l = minlys; l < lye; l++) - { - // loop on layers - for (int c = comps; c < compe; c++) - { - // loop on components - // Checks if component exists - if (c >= mdl.Length) - continue; - // Checks if resolution level exists - if (r > mdl[c]) - continue; - if (r >= lys[c].Length) - continue; - // Checks if layer exists - if (l < lys[c][r] || l >= numLayers) - continue; - - nPrec = pktDec.getNumPrecinct(c, r); - - for (int p = 0; p < nPrec; p++) - { - // loop on precincts - start = in_Renamed.Pos; - - // If packed packet headers are used, there is no need - // to check that there are bytes enough to read header - if (pph) - { - pktDec.readPktHead(l, r, c, p, cbI[c][r], nBytes); - } - - // If we are about to read outside of tile-part, - // skip to next tile-part - if (start > lastByte && curTilePart < firstPackOff[t].Length - 1) - { - curTilePart++; - in_Renamed.seek(firstPackOff[t][curTilePart]); - lastByte = in_Renamed.Pos + tilePartLen[t][curTilePart] - 1 - tilePartHeadLen[t][curTilePart]; - } - - // Read SOP marker segment if necessary - status = pktDec.readSOPMarker(nBytes, p, c, r); - - if (status) - { - if (printInfo) - { - } - return true; - } - - if (!pph) - { - status = pktDec.readPktHead(l, r, c, p, cbI[c][r], nBytes); - } - - if (status) - { - if (printInfo) - { - } - // Output rate of EOF reached - return true; - } - - // Store packet's head length - hlen = in_Renamed.Pos - start; - pktHL.Add((System.Int32)hlen); - - // Reads packet's body - status = pktDec.readPktBody(l, r, c, p, cbI[c][r], nBytes); - plen = in_Renamed.Pos - start; - - if (status) - { - if (printInfo) - { - } - // Output rate or EOF reached - return true; - } - } // end loop on precincts - } // end loop on components - } // end loop on layers - } // end loop on resolution levels - - if (printInfo) - { - } - return false; // Decoding rate was not reached - } - - /// Reads packets of the current tile according to the - /// resolution-position-component-layer progressiveness. - /// - /// - /// Index of the first layer for each component and resolution. - /// - /// - /// Index of the last layer. - /// - /// - /// Index of the first resolution level. - /// - /// - /// Index of the last resolution level. - /// - /// - /// Index of the first component. - /// - /// - /// Index of the last component. - /// - /// - /// True if rate has been reached. - /// - /// - private bool readResPosCompLy(int[][] lys, int lye, int ress, int rese, int comps, int compe) - { - // Computes current tile offset in the reference grid - - Coord nTiles = getNumTiles(null); - Coord tileI = getTile(null); - int x0siz = hd.ImgULX; - int y0siz = hd.ImgULY; - int xsiz = x0siz + hd.ImgWidth; - int ysiz = y0siz + hd.ImgHeight; - int xt0siz = TilePartULX; - int yt0siz = TilePartULY; - int xtsiz = NomTileWidth; - int ytsiz = NomTileHeight; - int tx0 = (tileI.x == 0) ? x0siz : xt0siz + tileI.x * xtsiz; - int ty0 = (tileI.y == 0) ? y0siz : yt0siz + tileI.y * ytsiz; - int tx1 = (tileI.x != nTiles.x - 1) ? xt0siz + (tileI.x + 1) * xtsiz : xsiz; - int ty1 = (tileI.y != nTiles.y - 1) ? yt0siz + (tileI.y + 1) * ytsiz : ysiz; - - // Get precinct information (number,distance between two consecutive - // precincts in the reference grid) in each component and resolution - // level - int t = TileIdx; // Current tile index - PrecInfo prec; // temporary variable - int p; // Current precinct index - int gcd_x = 0; // Horiz. distance between 2 precincts in the ref. grid - int gcd_y = 0; // Vert. distance between 2 precincts in the ref. grid - int nPrec = 0; // Total number of found precincts - int[][] nextPrec = new int[compe][]; // Next precinct index in each - // component and resolution level - int minlys = 100000; // minimum layer start index of each component - int minx = tx1; // Horiz. offset of the second precinct in the - // reference grid - int miny = ty1; // Vert. offset of the second precinct in the - // reference grid. - int maxx = tx0; // Max. horiz. offset of precincts in the ref. grid - int maxy = ty0; // Max. vert. offset of precincts in the ref. grid - //Coord numPrec; - for (int c = comps; c < compe; c++) - { - // components - for (int r = ress; r < rese; r++) - { - // resolution levels - if (c >= mdl.Length) - continue; - if (r > mdl[c]) - continue; - nextPrec[c] = new int[mdl[c] + 1]; - if (lys[c] != null && r < lys[c].Length && lys[c][r] < minlys) - { - minlys = lys[c][r]; - } - p = pktDec.getNumPrecinct(c, r) - 1; - for (; p >= 0; p--) - { - prec = pktDec.getPrecInfo(c, r, p); - if (prec.rgulx != tx0) - { - if (prec.rgulx < minx) - minx = prec.rgulx; - if (prec.rgulx > maxx) - maxx = prec.rgulx; - } - if (prec.rguly != ty0) - { - if (prec.rguly < miny) - miny = prec.rguly; - if (prec.rguly > maxy) - maxy = prec.rguly; - } - - if (nPrec == 0) - { - gcd_x = prec.rgw; - gcd_y = prec.rgh; - } - else - { - gcd_x = MathUtil.gcd(gcd_x, prec.rgw); - gcd_y = MathUtil.gcd(gcd_y, prec.rgh); - } - nPrec++; - } // precincts - } // resolution levels - } // components - - if (nPrec == 0) - { - throw new System.ApplicationException("Image cannot have no precinct"); - } - - int pyend = (maxy - miny) / gcd_y + 1; - int pxend = (maxx - minx) / gcd_x + 1; - int x, y; - int hlen, plen; - int start; - bool status = false; - int lastByte = firstPackOff[t][curTilePart] + tilePartLen[t][curTilePart] - 1 - tilePartHeadLen[t][curTilePart]; - int numLayers = ((System.Int32)decSpec.nls.getTileDef(t)); - bool pph = false; - if (((System.Boolean)decSpec.pphs.getTileDef(t))) - { - pph = true; - } - for (int r = ress; r < rese; r++) - { - // loop on resolution levels - y = ty0; - x = tx0; - for (int py = 0; py <= pyend; py++) - { - // Vertical precincts - for (int px = 0; px <= pxend; px++) - { - // Horiz. precincts - for (int c = comps; c < compe; c++) - { - // Components - if (c >= mdl.Length) - continue; - if (r > mdl[c]) - continue; - if (nextPrec[c][r] >= pktDec.getNumPrecinct(c, r)) - { - continue; - } - prec = pktDec.getPrecInfo(c, r, nextPrec[c][r]); - if ((prec.rgulx != x) || (prec.rguly != y)) - { - continue; - } - for (int l = minlys; l < lye; l++) - { - // layers - if (r >= lys[c].Length) - continue; - if (l < lys[c][r] || l >= numLayers) - continue; - - start = in_Renamed.Pos; - - // If packed packet headers are used, there is no - // need to check that there are bytes enough to - // read header - if (pph) - { - pktDec.readPktHead(l, r, c, nextPrec[c][r], cbI[c][r], nBytes); - } - - // If we are about to read outside of tile-part, - // skip to next tile-part - if (start > lastByte && curTilePart < firstPackOff[t].Length - 1) - { - curTilePart++; - in_Renamed.seek(firstPackOff[t][curTilePart]); - lastByte = in_Renamed.Pos + tilePartLen[t][curTilePart] - 1 - tilePartHeadLen[t][curTilePart]; - } - - // Read SOP marker segment if necessary - status = pktDec.readSOPMarker(nBytes, nextPrec[c][r], c, r); - - if (status) - { - if (printInfo) - { - } - return true; - } - - if (!pph) - { - status = pktDec.readPktHead(l, r, c, nextPrec[c][r], cbI[c][r], nBytes); - } - - if (status) - { - if (printInfo) - { - } - return true; - } - - // Store packet's head length - hlen = in_Renamed.Pos - start; - pktHL.Add((System.Int32)hlen); - - // Reads packet's body - status = pktDec.readPktBody(l, r, c, nextPrec[c][r], cbI[c][r], nBytes); - plen = in_Renamed.Pos - start; - - if (status) - { - if (printInfo) - { - } - return true; - } - } // layers - nextPrec[c][r]++; - } // Components - if (px != pxend) - { - x = minx + px * gcd_x; - } - else - { - x = tx0; - } - } // Horizontal precincts - if (py != pyend) - { - y = miny + py * gcd_y; - } - else - { - y = ty0; - } - } // Vertical precincts - } // end loop on resolution levels - - if (printInfo) - { - } - return false; // Decoding rate was not reached - } - - /// Reads packets of the current tile according to the - /// position-component-resolution-layer progressiveness. - /// - /// - /// Index of the first layer for each component and resolution. - /// - /// - /// Index of the last layer. - /// - /// - /// Index of the first resolution level. - /// - /// - /// Index of the last resolution level. - /// - /// - /// Index of the first component. - /// - /// - /// Index of the last component. - /// - /// - /// True if rate has been reached. - /// - /// - private bool readPosCompResLy(int[][] lys, int lye, int ress, int rese, int comps, int compe) - { - Coord nTiles = getNumTiles(null); - Coord tileI = getTile(null); - int x0siz = hd.ImgULX; - int y0siz = hd.ImgULY; - int xsiz = x0siz + hd.ImgWidth; - int ysiz = y0siz + hd.ImgHeight; - int xt0siz = TilePartULX; - int yt0siz = TilePartULY; - int xtsiz = NomTileWidth; - int ytsiz = NomTileHeight; - int tx0 = (tileI.x == 0) ? x0siz : xt0siz + tileI.x * xtsiz; - int ty0 = (tileI.y == 0) ? y0siz : yt0siz + tileI.y * ytsiz; - int tx1 = (tileI.x != nTiles.x - 1) ? xt0siz + (tileI.x + 1) * xtsiz : xsiz; - int ty1 = (tileI.y != nTiles.y - 1) ? yt0siz + (tileI.y + 1) * ytsiz : ysiz; - - // Get precinct information (number,distance between two consecutive - // precincts in the reference grid) in each component and resolution - // level - int t = TileIdx; // Current tile index - PrecInfo prec; // temporary variable - int p; // Current precinct index - int gcd_x = 0; // Horiz. distance between 2 precincts in the ref. grid - int gcd_y = 0; // Vert. distance between 2 precincts in the ref. grid - int nPrec = 0; // Total number of found precincts - int[][] nextPrec = new int[compe][]; // Next precinct index in each - // component and resolution level - int minlys = 100000; // minimum layer start index of each component - int minx = tx1; // Horiz. offset of the second precinct in the - // reference grid - int miny = ty1; // Vert. offset of the second precinct in the - // reference grid. - int maxx = tx0; // Max. horiz. offset of precincts in the ref. grid - int maxy = ty0; // Max. vert. offset of precincts in the ref. grid - //Coord numPrec; - for (int c = comps; c < compe; c++) - { - // components - for (int r = ress; r < rese; r++) - { - // resolution levels - if (c >= mdl.Length) - continue; - if (r > mdl[c]) - continue; - nextPrec[c] = new int[mdl[c] + 1]; - if (lys[c] != null && r < lys[c].Length && lys[c][r] < minlys) - { - minlys = lys[c][r]; - } - p = pktDec.getNumPrecinct(c, r) - 1; - for (; p >= 0; p--) - { - prec = pktDec.getPrecInfo(c, r, p); - if (prec.rgulx != tx0) - { - if (prec.rgulx < minx) - minx = prec.rgulx; - if (prec.rgulx > maxx) - maxx = prec.rgulx; - } - if (prec.rguly != ty0) - { - if (prec.rguly < miny) - miny = prec.rguly; - if (prec.rguly > maxy) - maxy = prec.rguly; - } - - if (nPrec == 0) - { - gcd_x = prec.rgw; - gcd_y = prec.rgh; - } - else - { - gcd_x = MathUtil.gcd(gcd_x, prec.rgw); - gcd_y = MathUtil.gcd(gcd_y, prec.rgh); - } - nPrec++; - } // precincts - } // resolution levels - } // components - - if (nPrec == 0) - { - throw new System.ApplicationException("Image cannot have no precinct"); - } - - int pyend = (maxy - miny) / gcd_y + 1; - int pxend = (maxx - minx) / gcd_x + 1; - int hlen, plen; - int start; - bool status = false; - int lastByte = firstPackOff[t][curTilePart] + tilePartLen[t][curTilePart] - 1 - tilePartHeadLen[t][curTilePart]; - int numLayers = ((System.Int32)decSpec.nls.getTileDef(t)); - bool pph = false; - if (((System.Boolean)decSpec.pphs.getTileDef(t))) - { - pph = true; - } - - int y = ty0; - int x = tx0; - for (int py = 0; py <= pyend; py++) - { - // Vertical precincts - for (int px = 0; px <= pxend; px++) - { - // Horiz. precincts - for (int c = comps; c < compe; c++) - { - // Components - if (c >= mdl.Length) - continue; - for (int r = ress; r < rese; r++) - { - // Resolution levels - if (r > mdl[c]) - continue; - if (nextPrec[c][r] >= pktDec.getNumPrecinct(c, r)) - { - continue; - } - prec = pktDec.getPrecInfo(c, r, nextPrec[c][r]); - if ((prec.rgulx != x) || (prec.rguly != y)) - { - continue; - } - for (int l = minlys; l < lye; l++) - { - // Layers - if (r >= lys[c].Length) - continue; - if (l < lys[c][r] || l >= numLayers) - continue; - - start = in_Renamed.Pos; - - // If packed packet headers are used, there is no - // need to check that there are bytes enough to - // read header - if (pph) - { - pktDec.readPktHead(l, r, c, nextPrec[c][r], cbI[c][r], nBytes); - } - - // If we are about to read outside of tile-part, - // skip to next tile-part - if (start > lastByte && curTilePart < firstPackOff[t].Length - 1) - { - curTilePart++; - in_Renamed.seek(firstPackOff[t][curTilePart]); - lastByte = in_Renamed.Pos + tilePartLen[t][curTilePart] - 1 - tilePartHeadLen[t][curTilePart]; - } - - // Read SOP marker segment if necessary - status = pktDec.readSOPMarker(nBytes, nextPrec[c][r], c, r); - - if (status) - { - if (printInfo) - { - } - return true; - } - - if (!pph) - { - status = pktDec.readPktHead(l, r, c, nextPrec[c][r], cbI[c][r], nBytes); - } - - if (status) - { - if (printInfo) - { - } - return true; - } - - // Store packet's head length - hlen = in_Renamed.Pos - start; - pktHL.Add((System.Int32)hlen); - - // Reads packet's body - status = pktDec.readPktBody(l, r, c, nextPrec[c][r], cbI[c][r], nBytes); - plen = in_Renamed.Pos - start; - - if (status) - { - if (printInfo) - { - } - return true; - } - } // layers - nextPrec[c][r]++; - } // Resolution levels - } // Components - if (px != pxend) - { - x = minx + px * gcd_x; - } - else - { - x = tx0; - } - } // Horizontal precincts - if (py != pyend) - { - y = miny + py * gcd_y; - } - else - { - y = ty0; - } - } // Vertical precincts - - if (printInfo) - { - } - return false; // Decoding rate was not reached - } - - /// Reads packets of the current tile according to the - /// component-position-resolution-layer progressiveness. - /// - /// - /// Index of the first layer for each component and resolution. - /// - /// - /// Index of the last layer. - /// - /// - /// Index of the first resolution level. - /// - /// - /// Index of the last resolution level. - /// - /// - /// Index of the first component. - /// - /// - /// Index of the last component. - /// - /// - /// True if rate has been reached. - /// - /// - private bool readCompPosResLy(int[][] lys, int lye, int ress, int rese, int comps, int compe) - { - Coord nTiles = getNumTiles(null); - Coord tileI = getTile(null); - int x0siz = hd.ImgULX; - int y0siz = hd.ImgULY; - int xsiz = x0siz + hd.ImgWidth; - int ysiz = y0siz + hd.ImgHeight; - int xt0siz = TilePartULX; - int yt0siz = TilePartULY; - int xtsiz = NomTileWidth; - int ytsiz = NomTileHeight; - int tx0 = (tileI.x == 0) ? x0siz : xt0siz + tileI.x * xtsiz; - int ty0 = (tileI.y == 0) ? y0siz : yt0siz + tileI.y * ytsiz; - int tx1 = (tileI.x != nTiles.x - 1) ? xt0siz + (tileI.x + 1) * xtsiz : xsiz; - int ty1 = (tileI.y != nTiles.y - 1) ? yt0siz + (tileI.y + 1) * ytsiz : ysiz; - - // Get precinct information (number,distance between two consecutive - // precincts in the reference grid) in each component and resolution - // level - int t = TileIdx; // Current tile index - PrecInfo prec; // temporary variable - int p; // Current precinct index - int gcd_x = 0; // Horiz. distance between 2 precincts in the ref. grid - int gcd_y = 0; // Vert. distance between 2 precincts in the ref. grid - int nPrec = 0; // Total number of found precincts - int[][] nextPrec = new int[compe][]; // Next precinct index in each - // component and resolution level - int minlys = 100000; // minimum layer start index of each component - int minx = tx1; // Horiz. offset of the second precinct in the - // reference grid - int miny = ty1; // Vert. offset of the second precinct in the - // reference grid. - int maxx = tx0; // Max. horiz. offset of precincts in the ref. grid - int maxy = ty0; // Max. vert. offset of precincts in the ref. grid - //Coord numPrec; - for (int c = comps; c < compe; c++) - { - // components - for (int r = ress; r < rese; r++) - { - // resolution levels - if (c >= mdl.Length) - continue; - if (r > mdl[c]) - continue; - nextPrec[c] = new int[mdl[c] + 1]; - if (lys[c] != null && r < lys[c].Length && lys[c][r] < minlys) - { - minlys = lys[c][r]; - } - p = pktDec.getNumPrecinct(c, r) - 1; - for (; p >= 0; p--) - { - prec = pktDec.getPrecInfo(c, r, p); - if (prec.rgulx != tx0) - { - if (prec.rgulx < minx) - minx = prec.rgulx; - if (prec.rgulx > maxx) - maxx = prec.rgulx; - } - if (prec.rguly != ty0) - { - if (prec.rguly < miny) - miny = prec.rguly; - if (prec.rguly > maxy) - maxy = prec.rguly; - } - - if (nPrec == 0) - { - gcd_x = prec.rgw; - gcd_y = prec.rgh; - } - else - { - gcd_x = MathUtil.gcd(gcd_x, prec.rgw); - gcd_y = MathUtil.gcd(gcd_y, prec.rgh); - } - nPrec++; - } // precincts - } // resolution levels - } // components - - if (nPrec == 0) - { - throw new System.ApplicationException("Image cannot have no precinct"); - } - - int pyend = (maxy - miny) / gcd_y + 1; - int pxend = (maxx - minx) / gcd_x + 1; - int hlen, plen; - int start; - bool status = false; - int lastByte = firstPackOff[t][curTilePart] + tilePartLen[t][curTilePart] - 1 - tilePartHeadLen[t][curTilePart]; - int numLayers = ((System.Int32)decSpec.nls.getTileDef(t)); - bool pph = false; - if (((System.Boolean)decSpec.pphs.getTileDef(t))) - { - pph = true; - } - - int x, y; - for (int c = comps; c < compe; c++) - { - // components - if (c >= mdl.Length) - continue; - y = ty0; - x = tx0; - for (int py = 0; py <= pyend; py++) - { - // Vertical precincts - for (int px = 0; px <= pxend; px++) - { - // Horiz. precincts - for (int r = ress; r < rese; r++) - { - // Resolution levels - if (r > mdl[c]) - continue; - if (nextPrec[c][r] >= pktDec.getNumPrecinct(c, r)) - { - continue; - } - prec = pktDec.getPrecInfo(c, r, nextPrec[c][r]); - if ((prec.rgulx != x) || (prec.rguly != y)) - { - continue; - } - - for (int l = minlys; l < lye; l++) - { - // Layers - if (r >= lys[c].Length) - continue; - if (l < lys[c][r]) - continue; - - start = in_Renamed.Pos; - - // If packed packet headers are used, there is no - // need to check that there are bytes enough to - // read header - if (pph) - { - pktDec.readPktHead(l, r, c, nextPrec[c][r], cbI[c][r], nBytes); - } - - // If we are about to read outside of tile-part, - // skip to next tile-part - if (start > lastByte && curTilePart < firstPackOff[t].Length - 1) - { - curTilePart++; - in_Renamed.seek(firstPackOff[t][curTilePart]); - lastByte = in_Renamed.Pos + tilePartLen[t][curTilePart] - 1 - tilePartHeadLen[t][curTilePart]; - } - - // Read SOP marker segment if necessary - status = pktDec.readSOPMarker(nBytes, nextPrec[c][r], c, r); - - if (status) - { - if (printInfo) - { - } - return true; - } - - if (!pph) - { - status = pktDec.readPktHead(l, r, c, nextPrec[c][r], cbI[c][r], nBytes); - } - - if (status) - { - if (printInfo) - { - } - return true; - } - - // Store packet's head length - hlen = in_Renamed.Pos - start; - pktHL.Add((System.Int32)hlen); - - // Reads packet's body - status = pktDec.readPktBody(l, r, c, nextPrec[c][r], cbI[c][r], nBytes); - plen = in_Renamed.Pos - start; - - if (status) - { - if (printInfo) - { - } - return true; - } - } // layers - nextPrec[c][r]++; - } // Resolution levels - if (px != pxend) - { - x = minx + px * gcd_x; - } - else - { - x = tx0; - } - } // Horizontal precincts - if (py != pyend) - { - y = miny + py * gcd_y; - } - else - { - y = ty0; - } - } // Vertical precincts - } // components - - if (printInfo) - { - } - return false; // Decoding rate was not reached - } - - /// Finish initialization of members for specified tile, reads packets head - /// of each tile and keeps location of each code-block's codewords. The - /// last 2 tasks are done by calling specific methods of PktDecoder. - /// - ///

    Then, if a parsing output rate is defined, it keeps information of - /// first layers only. This operation simulates a creation of a - /// layer-resolution-component progressive bit-stream which will be next - /// truncated and decoded.

    - /// - ///
    - /// Tile index - /// - /// - /// - /// - /// - private void readTilePkts(int t) - { - pktHL = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); - layerStarts = new System.Collections.Generic.List(5); - - // Number of layers - int nl = ((System.Int32)decSpec.nls.getTileDef(t)); - - // If packed packet headers was used, get the packet headers for this - // tile - if (((System.Boolean)decSpec.pphs.getTileDef(t))) - { - // Gets packed headers as separate input stream - System.IO.MemoryStream pphbais = hd.getPackedPktHead(t); - - // Restarts PktDecoder instance - cbI = pktDec.restart(this.nc, mdl, nl, cbI, true, pphbais); - } - else - { - // Restarts PktDecoder instance - cbI = pktDec.restart(this.nc, mdl, nl, cbI, false, null); - } - - // Reads packets of the tile according to the progression order - int[][] pocSpec = ((int[][])decSpec.pcs.getTileDef(t)); - int nChg = (pocSpec == null) ? 1 : pocSpec.Length; - - // Create an array containing information about changes (progression - // order type, layers index start, layer index end, resolution level - // start, resolution level end, component index start, component index - // end). There is one row per progresion order - int[][] change = new int[nChg][]; - for (int i = 0; i < nChg; i++) - { - change[i] = new int[6]; - } - int idx = 0; // Index of the current progression order - - change[0][1] = 0; // layer start - - if (pocSpec == null) - { - change[idx][0] = ((System.Int32)decSpec.pos.getTileDef(t)); - // Progression type found in COx marker segments - change[idx][1] = nl; // Layer index end - change[idx][2] = 0; // resolution level start - change[idx][3] = decSpec.dls.getMaxInTile(t) + 1; // res. level end - change[idx][4] = 0; // Component index start - change[idx][5] = this.nc; // Component index end - } - else - { - for (idx = 0; idx < nChg; idx++) - { - change[idx][0] = pocSpec[idx][5]; - change[idx][1] = pocSpec[idx][2]; // layer end - change[idx][2] = pocSpec[idx][0]; // res. lev. start - change[idx][3] = pocSpec[idx][3]; // res. lev. end - change[idx][4] = pocSpec[idx][1]; // Comp. index start - change[idx][5] = pocSpec[idx][4]; // Comp. index end - } - } - - // Seeks to the first packet of the first tile-part - try - { - // If in truncation mode, the first tile-part may be beyond the - // target decoding rate. In this case, the offset of the first - // packet is not defined. - if (isTruncMode && firstPackOff == null || firstPackOff[t] == null) - { - return; - } - in_Renamed.seek(firstPackOff[t][0]); - } - catch (System.IO.EndOfStreamException) - { - FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.WARNING, "Codestream truncated in tile " + t); - return; - } - - curTilePart = 0; - - // Start and end indexes for layers, resolution levels and components. - int lye, ress, rese, comps, compe; - bool status = false; - int nb = nBytes[t]; - int[][] lys = new int[this.nc][]; - for (int c = 0; c < this.nc; c++) - { - lys[c] = new int[((System.Int32)decSpec.dls.getTileCompVal(t, c)) + 1]; - } - - try - { - for (int chg = 0; chg < nChg; chg++) - { - - lye = change[chg][1]; - ress = change[chg][2]; - rese = change[chg][3]; - comps = change[chg][4]; - compe = change[chg][5]; - - switch (change[chg][0]) - { - - case CSJ2K.j2k.codestream.ProgressionType.LY_RES_COMP_POS_PROG: - status = readLyResCompPos(lys, lye, ress, rese, comps, compe); - break; - - case CSJ2K.j2k.codestream.ProgressionType.RES_LY_COMP_POS_PROG: - status = readResLyCompPos(lys, lye, ress, rese, comps, compe); - break; - - case CSJ2K.j2k.codestream.ProgressionType.RES_POS_COMP_LY_PROG: - status = readResPosCompLy(lys, lye, ress, rese, comps, compe); - break; - - case CSJ2K.j2k.codestream.ProgressionType.POS_COMP_RES_LY_PROG: - status = readPosCompResLy(lys, lye, ress, rese, comps, compe); - break; - - case CSJ2K.j2k.codestream.ProgressionType.COMP_POS_RES_LY_PROG: - status = readCompPosResLy(lys, lye, ress, rese, comps, compe); - break; - - default: - throw new System.ArgumentException("Not recognized " + "progression type"); - - } - - // Update next first layer index - for (int c = comps; c < compe; c++) - { - if (c >= lys.Length) - continue; - for (int r = ress; r < rese; r++) - { - if (r >= lys[c].Length) - continue; - lys[c][r] = lye; - } - } - - if (status || usePOCQuit) - { - break; - } - } - } - catch (System.IO.EndOfStreamException e) - { - // Should never happen. Truncated codestream are normally found by - // the class constructor - throw e; - } - - // In truncation mode, update the number of read bytes - if (isTruncMode) - { - anbytes += nb - nBytes[t]; - - // If truncation rate is reached - if (status) - { - nBytes[t] = 0; - } - } - else if (nBytes[t] < (totTileLen[t] - totTileHeadLen[t])) - { - // In parsing mode, if there is not enough rate to entirely read the - // tile. Then, parses the bit stream so as to create a virtual - // layer-resolution-component progressive bit stream that will be - // truncated and decoded afterwards. - CBlkInfo cb; - - // Systematicaly reject all remaining code-blocks if one - // code-block, at least, is refused. - bool reject; - // Stop reading any data from the bit stream - bool stopCount = false; - // Length of each packet's head (in an array) - int[] pktHeadLen = new int[pktHL.Count]; - for (int i = pktHL.Count - 1; i >= 0; i--) - { - pktHeadLen[i] = ((System.Int32)pktHL[i]); - } - - // Parse each code-block, layer per layer until nBytes[t] is - // reached - reject = false; - for (int l = 0; l < nl; l++) - { - // layers - if (cbI == null) - continue; - int nc = cbI.Length; - - int mres = 0; - for (int c = 0; c < nc; c++) - { - if (cbI[c] != null && cbI[c].Length > mres) - mres = cbI[c].Length; - } - for (int r = 0; r < mres; r++) - { - // resolutions - - int msub = 0; - for (int c = 0; c < nc; c++) - { - if (cbI[c] != null && cbI[c][r] != null && cbI[c][r].Length > msub) - msub = cbI[c][r].Length; - } - for (int s = 0; s < msub; s++) - { - // subbands - // Only LL subband resolution level 0 - if (r == 0 && s != 0) - { - continue; - } - else if (r != 0 && s == 0) - { - // No LL subband in resolution level > 0 - continue; - } - - int mnby = 0; - for (int c = 0; c < nc; c++) - { - if (cbI[c] != null && cbI[c][r] != null && cbI[c][r][s] != null && cbI[c][r][s].Length > mnby) - mnby = cbI[c][r][s].Length; - } - for (int m = 0; m < mnby; m++) - { - - int mnbx = 0; - for (int c = 0; c < nc; c++) - { - if (cbI[c] != null && cbI[c][r] != null && cbI[c][r][s] != null && cbI[c][r][s][m] != null && cbI[c][r][s][m].Length > mnbx) - mnbx = cbI[c][r][s][m].Length; - } - for (int n = 0; n < mnbx; n++) - { - - for (int c = 0; c < nc; c++) - { - - if (cbI[c] == null || cbI[c][r] == null || cbI[c][r][s] == null || cbI[c][r][s][m] == null || cbI[c][r][s][m][n] == null) - { - continue; - } - cb = cbI[c][r][s][m][n]; - - // If no code-block has been refused until - // now - if (!reject) - { - // Rate is to low to allow reading of - // packet's head - if (nBytes[t] < pktHeadLen[cb.pktIdx[l]]) - { - // Stop parsing - stopCount = true; - // Reject all next - // code-blocks - reject = true; - } - else - { - // Rate is enough to read packet's - // head - if (!stopCount) - { - //If parsing was not stopped - //Takes into account packet's - //head length - nBytes[t] -= pktHeadLen[cb.pktIdx[l]]; - anbytes += pktHeadLen[cb.pktIdx[l]]; - // Set packet's head length to - // 0, so that it won't be - // taken into account next - // time - pktHeadLen[cb.pktIdx[l]] = 0; - } - } - } - // Code-block has no data in this layer - if (cb.len[l] == 0) - { - continue; - } - - // Accepts code-block if length is enough, - // if this code-block was not refused in a - // previous layer and if no code-block was - // refused in current component - if (cb.len[l] < nBytes[t] && !reject) - { - nBytes[t] -= cb.len[l]; - anbytes += cb.len[l]; - } - else - { - // Refuses code-block - // Forgets code-block's data - cb.len[l] = cb.off[l] = cb.ntp[l] = 0; - // Refuses all other code-block in - // current and next component - reject = true; - } - } // End loop on components - } // End loop on horiz. code-blocks - } // End loop on vert. code-blocks - } // End loop on subbands - } // End loop on resolutions - } // End loop on layers - } - else - { - // No parsing for this tile, adds tile's body to the total - // number of read bytes. - anbytes += totTileLen[t] - totTileHeadLen[t]; - if (t < getNumTiles() - 1) - { - nBytes[t + 1] += nBytes[t] - (totTileLen[t] - totTileHeadLen[t]); - } - } - } - - - - /// Changes the current tile, given the new indexes. An - /// IllegalArgumentException is thrown if the indexes do not correspond to - /// a valid tile. - /// - /// - /// The horizontal indexes the tile. - /// - /// - /// The vertical indexes of the new tile. - /// - /// - public override void setTile(int x, int y) - { - - int i; // counter - // Check validity of tile indexes - if (x < 0 || y < 0 || x >= ntX || y >= ntY) - { - throw new System.ArgumentException(); - } - int t = (y * ntX + x); - - // Reset number of read bytes if needed - if (t == 0) - { - anbytes = headLen; - if (!isTruncMode) - { - anbytes += 2; - } - // Restore values of nBytes - for (int tIdx = 0; tIdx < nt; tIdx++) - { - nBytes[tIdx] = baknBytes[tIdx]; - } - } - - // Set the new current tile - ctX = x; - ctY = y; - // Calculate tile relative points - int ctox = (x == 0) ? ax : px + x * ntW; - int ctoy = (y == 0) ? ay : py + y * ntH; - for (i = nc - 1; i >= 0; i--) - { - culx[i] = (ctox + hd.getCompSubsX(i) - 1) / hd.getCompSubsX(i); - culy[i] = (ctoy + hd.getCompSubsY(i) - 1) / hd.getCompSubsY(i); - offX[i] = (px + x * ntW + hd.getCompSubsX(i) - 1) / hd.getCompSubsX(i); - offY[i] = (py + y * ntH + hd.getCompSubsY(i) - 1) / hd.getCompSubsY(i); - } - - // Initialize subband tree and number of resolution levels - subbTrees = new SubbandSyn[nc]; - mdl = new int[nc]; - derived = new bool[nc]; - params_Renamed = new StdDequantizerParams[nc]; - gb = new int[nc]; - - for (int c = 0; c < nc; c++) - { - derived[c] = decSpec.qts.isDerived(t, c); - params_Renamed[c] = (StdDequantizerParams)decSpec.qsss.getTileCompVal(t, c); - gb[c] = ((System.Int32)decSpec.gbs.getTileCompVal(t, c)); - mdl[c] = ((System.Int32)decSpec.dls.getTileCompVal(t, c)); - - subbTrees[c] = new SubbandSyn(getTileCompWidth(t, c, mdl[c]), getTileCompHeight(t, c, mdl[c]), getResULX(c, mdl[c]), getResULY(c, mdl[c]), mdl[c], decSpec.wfs.getHFilters(t, c), decSpec.wfs.getVFilters(t, c)); - initSubbandsFields(c, subbTrees[c]); - } - - // Read tile's packets - try - { - readTilePkts(t); - } - catch (System.IO.IOException e) - { - SupportClass.WriteStackTrace(e, Console.Error); - throw new System.ApplicationException("IO Error when reading tile " + x + " x " + y); - } - } - - /// Advances to the next tile, in standard scan-line order (by rows then - /// columns). A NoNextElementException is thrown if the current tile is the - /// last one (i.e. there is no next tile). - /// - /// - public override void nextTile() - { - if (ctX == ntX - 1 && ctY == ntY - 1) - { - // Already at last tile - throw new NoNextElementException(); - } - else if (ctX < ntX - 1) - { - // If not at end of current tile line - setTile(ctX + 1, ctY); - } - else - { - // Go to first tile at next line - setTile(0, ctY + 1); - } - } - - /// Returns the specified coded code-block, for the specified component, in - /// the current tile. The first layer to return is indicated by 'fl'. The - /// number of layers that is returned depends on 'nl' and the amount of - /// available data. - /// - ///

    The argument 'fl' is to be used by subsequent calls to this method - /// for the same code-block. In this way supplemental data can be retrieved - /// at a later time. The fact that data from more than one layer can be - /// returned means that several packets from the same code-block, of the - /// same component, and the same tile, have been concatenated.

    - /// - ///

    The returned compressed code-block can have its progressive - /// attribute set. If this attribute is set it means that more data can be - /// obtained by subsequent calls to this method (subject to transmission - /// delays, etc). If the progressive attribute is not set it means that the - /// returned data is all the data that can be obtained for the specified - /// code-block.

    - /// - ///

    The compressed code-block is uniquely specified by the current tile, - /// the component (identified by 'c'), the subband (indentified by 'sb') - /// and the code-block vertical and horizontal indexes 'n' and 'm'.

    - /// - ///

    The 'ulx' and 'uly' members of the returned 'DecLyrdCBlk' object - /// contain the coordinates of the top-left corner of the block, with - /// respect to the tile, not the subband.

    - /// - ///
    - /// The index of the component, from 0 to N-1. - /// - /// - /// The vertical index of the code-block to return, in the - /// specified subband. - /// - /// - /// The horizontal index of the code-block to return, in the - /// specified subband. - /// - /// - /// The subband in whic the requested code-block is. - /// - /// - /// The first layer to return. - /// - /// - /// The number of layers to return, if negative all available - /// layers are returned, starting at 'fl'. - /// - /// - /// If not null this object is used to return the compressed - /// code-block. If null a new object is created and returned. If the data - /// array in ccb is not null then it can be reused to return the compressed - /// data. - /// - /// - /// The compressed code-block, with a certain number of layers - /// determined by the available data and 'nl'. - /// - /// - public override DecLyrdCBlk getCodeBlock(int c, int m, int n, SubbandSyn sb, int fl, int nl, DecLyrdCBlk ccb) - { - - int t = TileIdx; - CBlkInfo rcb; // requested code-block - int r = sb.resLvl; // Resolution level - int s = sb.sbandIdx; // Subband index - int tpidx; - int passtype; - - // Number of layers - int numLayers = ((System.Int32)decSpec.nls.getTileDef(t)); - int options = ((System.Int32)decSpec.ecopts.getTileCompVal(t, c)); - if (nl < 0) - { - nl = numLayers - fl + 1; - } - - // If the l quit condition is used, Make sure that no layer - // after lquit is returned - if (lQuit != -1 && fl + nl > lQuit) - { - nl = lQuit - fl; - } - - // Check validity of resquested resolution level (according to the - // "-res" option). - int maxdl = getSynSubbandTree(t, c).resLvl; - if (r > targetRes + maxdl - decSpec.dls.Min) - { - throw new System.ApplicationException("JJ2000 error: requesting a code-block " + "disallowed by the '-res' option."); - } - - // Check validity of all the arguments - try - { - rcb = cbI[c][r][s][m][n]; - - if (fl < 1 || fl > numLayers || fl + nl - 1 > numLayers) - { - throw new System.ArgumentException(); - } - } - catch (System.IndexOutOfRangeException) - { - throw new System.ArgumentException("Code-block (t:" + t + ", c:" + c + ", r:" + r + ", s:" + s + ", " + m + "x" + (+n) + ") not found in codestream"); - } - catch (System.NullReferenceException) - { - throw new System.ArgumentException("Code-block (t:" + t + ", c:" + c + ", r:" + r + ", s:" + s + ", " + m + "x" + n + ") not found in bit stream"); - } - - // Create DecLyrdCBlk object if necessary - if (ccb == null) - { - ccb = new DecLyrdCBlk(); - } - ccb.m = m; - ccb.n = n; - ccb.nl = 0; - ccb.dl = 0; - ccb.nTrunc = 0; - - if (rcb == null) - { - // This code-block was skipped when reading. Returns no data - ccb.skipMSBP = 0; - ccb.prog = false; - ccb.w = ccb.h = ccb.ulx = ccb.uly = 0; - return ccb; - } - - // ccb initialization - ccb.skipMSBP = rcb.msbSkipped; - ccb.ulx = rcb.ulx; - ccb.uly = rcb.uly; - ccb.w = rcb.w; - ccb.h = rcb.h; - ccb.ftpIdx = 0; - - // Search for index of first truncation point (first layer where - // length of data is not zero) - int l = 0; - while ((l < rcb.len.Length) && (rcb.len[l] == 0)) - { - ccb.ftpIdx += rcb.ntp[l]; - l++; - } - - // Calculate total length, number of included layer and number of - // truncation points - for (l = fl - 1; l < fl + nl - 1; l++) - { - ccb.nl++; - ccb.dl += rcb.len[l]; - ccb.nTrunc += rcb.ntp[l]; - } - - // Calculate number of terminated segments - int nts; - if ((options & CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_TERM_PASS) != 0) - { - // Regular termination in use One segment per pass - // (i.e. truncation point) - nts = ccb.nTrunc - ccb.ftpIdx; - } - else if ((options & CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_BYPASS) != 0) - { - // Selective arithmetic coding bypass mode in use, but no regular - // termination: 1 segment upto the end of the last pass of the 4th - // most significant bit-plane, and, in each following bit-plane, - // one segment upto the end of the 2nd pass and one upto the end - // of the 3rd pass. - - if (ccb.nTrunc <= CSJ2K.j2k.entropy.StdEntropyCoderOptions.FIRST_BYPASS_PASS_IDX) - { - nts = 1; - } - else - { - nts = 1; - // Adds one for each terminated pass - for (tpidx = ccb.ftpIdx; tpidx < ccb.nTrunc; tpidx++) - { - if (tpidx >= CSJ2K.j2k.entropy.StdEntropyCoderOptions.FIRST_BYPASS_PASS_IDX - 1) - { - passtype = (tpidx + CSJ2K.j2k.entropy.StdEntropyCoderOptions.NUM_EMPTY_PASSES_IN_MS_BP) % CSJ2K.j2k.entropy.StdEntropyCoderOptions.NUM_PASSES; - if (passtype == 1 || passtype == 2) - { - // lazy pass just before MQ pass or MQ pass just - // before lazy pass => terminated - nts++; - } - } - } - } - } - else - { - // Nothing special in use, just one terminated segment - nts = 1; - } - - // ccb.data creation - if (ccb.data == null || ccb.data.Length < ccb.dl) - { - ccb.data = new byte[ccb.dl]; - } - - // ccb.tsLengths creation - if (nts > 1 && (ccb.tsLengths == null || ccb.tsLengths.Length < nts)) - { - ccb.tsLengths = new int[nts]; - } - else if (nts > 1 && (options & (CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_BYPASS | CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_TERM_PASS)) == CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_BYPASS) - { - ArrayUtil.intArraySet(ccb.tsLengths, 0); - } - - // Fill ccb with compressed data - int dataIdx = -1; - tpidx = ccb.ftpIdx; - int ctp = ccb.ftpIdx; // Cumulative number of truncation - // point for the current layer layer - int tsidx = 0; - int j; - - for (l = fl - 1; l < fl + nl - 1; l++) - { - ctp += rcb.ntp[l]; - // No data in this layer - if (rcb.len[l] == 0) - continue; - - // Read data - // NOTE: we should never get an EOFException here since all - // data is checked to be within the file. - try - { - in_Renamed.seek(rcb.off[l]); - in_Renamed.readFully(ccb.data, dataIdx + 1, rcb.len[l]); - dataIdx += rcb.len[l]; - } - catch (System.IO.IOException e) - { - JJ2KExceptionHandler.handleException(e); - } - - // Get the terminated segment lengths, if any - if (nts == 1) - continue; - if ((options & CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_TERM_PASS) != 0) - { - // Regular termination => each pass is terminated - for (j = 0; tpidx < ctp; j++, tpidx++) - { - if (rcb.segLen[l] != null) - { - ccb.tsLengths[tsidx++] = rcb.segLen[l][j]; - } - else - { - // Only one terminated segment in packet - ccb.tsLengths[tsidx++] = rcb.len[l]; - } - } - } - else - { - // Lazy coding without regular termination - for (j = 0; tpidx < ctp; tpidx++) - { - if (tpidx >= CSJ2K.j2k.entropy.StdEntropyCoderOptions.FIRST_BYPASS_PASS_IDX - 1) - { - passtype = (tpidx + CSJ2K.j2k.entropy.StdEntropyCoderOptions.NUM_EMPTY_PASSES_IN_MS_BP) % CSJ2K.j2k.entropy.StdEntropyCoderOptions.NUM_PASSES; - if (passtype != 0) - { - // lazy pass just before MQ pass or MQ - // pass just before lazy pass => - // terminated - if (rcb.segLen[l] != null) - { - ccb.tsLengths[tsidx++] += rcb.segLen[l][j++]; - rcb.len[l] -= rcb.segLen[l][j - 1]; - } - else - { - // Only one terminated segment in packet - ccb.tsLengths[tsidx++] += rcb.len[l]; - rcb.len[l] = 0; - } - } - } - } - - // Last length in packet always in (either terminated segment - // or contribution to terminated segment) - if (rcb.segLen[l] != null && j < rcb.segLen[l].Length) - { - ccb.tsLengths[tsidx] += rcb.segLen[l][j]; - rcb.len[l] -= rcb.segLen[l][j]; - } - else - { - // Only one terminated segment in packet - if (tsidx < nts) - { - ccb.tsLengths[tsidx] += rcb.len[l]; - rcb.len[l] = 0; - } - } - } - } - if (nts == 1 && ccb.tsLengths != null) - { - ccb.tsLengths[0] = ccb.dl; - } - - // Set the progressive flag - int lastlayer = fl + nl - 1; - if (lastlayer < numLayers - 1) - { - for (l = lastlayer + 1; l < numLayers; l++) - { - // It remains data for this code-block in the bit stream - if (rcb.len[l] != 0) - { - ccb.prog = true; - } - } - } - - return ccb; - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/codestream/reader/HeaderDecoder.cs b/CSJ2K/j2k/codestream/reader/HeaderDecoder.cs deleted file mode 100644 index 06b00db9..00000000 --- a/CSJ2K/j2k/codestream/reader/HeaderDecoder.cs +++ /dev/null @@ -1,3089 +0,0 @@ -/* -* CVS identifier: -* -* $Id: HeaderDecoder.java,v 1.61 2002/07/25 15:01:00 grosbois Exp $ -* -* Class: HeaderDecoder -* -* Description: Reads main and tile-part headers. -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.Color; -using CSJ2K.Icc; -using CSJ2K.j2k.decoder; -using CSJ2K.j2k.entropy.decoder; -using CSJ2K.j2k.image; -using CSJ2K.j2k.io; -using CSJ2K.j2k.quantization.dequantizer; -using CSJ2K.j2k.roi; -using CSJ2K.j2k.util; -using CSJ2K.j2k.wavelet.synthesis; -using System; -namespace CSJ2K.j2k.codestream.reader -{ - - /// This class reads main and tile-part headers from the codestream given a - /// RandomAccessIO instance located at the beginning of the codestream (i.e - /// just before the SOC marker) or at the beginning of a tile-part (i.e. just - /// before a SOT marker segment) respectively. - /// - ///

    A marker segment includes a marker and eventually marker segment - /// parameters. It is designed by the three letters code of the marker - /// associated with the marker segment. JPEG 2000 part 1 defines 6 types of - /// markers segments: - /// - ///

      - ///
    • Delimiting : SOC, SOT, SOD, EOC
    • - /// - ///
    • Fixed information: SIZ.
    • - /// - ///
    • Functional: COD, COC, RGN, QCD, QCC,POC.
    • - /// - ///
    • In bit-stream: SOP, EPH.
    • - /// - ///
    • Pointer: TLM, PLM, PLT, PPM, PPT.
    • - /// - ///
    • Informational: CRG, COM.
    • - ///

    - /// - ///

    The main header is read when the constructor is called whereas tile-part - /// headers are read when the FileBitstreamReaderAgent instance is created. The - /// reading is done in 2 passes: - /// - ///

      - ///
    1. All marker segments are buffered and their corresponding flag is - /// activated (extractMainMarkSeg and extractTilePartMarkSeg methods).
    2. - /// - ///
    3. Buffered marker segment are analyzed in a logical way and - /// specifications are stored in appropriate member of DecoderSpecs instance - /// (readFoundMainMarkSeg and readFoundTilePartMarkSeg methods).
    4. - ///

    - /// - ///

    Whenever a marker segment is not recognized a warning message is - /// displayed and its length parameter is used to skip it.

    - /// - ///

    The information found in this header is stored in HeaderInfo and - /// DecoderSpecs instances.

    - /// - ///
    - /// - /// - /// - /// - /// - /// - /// - /// - /// - public class HeaderDecoder - { - /// Return the maximum height among all components - /// - /// - /// Maximum component height - /// - /// - virtual public int MaxCompImgHeight - { - get - { - return hi.sizValue.MaxCompHeight; - } - - } - /// Return the maximum width among all components - /// - /// - /// Maximum component width - /// - /// - virtual public int MaxCompImgWidth - { - get - { - return hi.sizValue.MaxCompWidth; - } - - } - /// Returns the image width in the reference grid. - /// - /// - /// The image width in the reference grid - /// - /// - virtual public int ImgWidth - { - get - { - return hi.sizValue.xsiz - hi.sizValue.x0siz; - } - - } - /// Returns the image height in the reference grid. - /// - /// - /// The image height in the reference grid - /// - /// - virtual public int ImgHeight - { - get - { - return hi.sizValue.ysiz - hi.sizValue.y0siz; - } - - } - /// Return the horizontal upper-left coordinate of the image in the - /// reference grid. - /// - /// - /// The horizontal coordinate of the image origin. - /// - /// - virtual public int ImgULX - { - get - { - return hi.sizValue.x0siz; - } - - } - /// Return the vertical upper-left coordinate of the image in the reference - /// grid. - /// - /// - /// The vertical coordinate of the image origin. - /// - /// - virtual public int ImgULY - { - get - { - return hi.sizValue.y0siz; - } - - } - /// Returns the nominal width of the tiles in the reference grid. - /// - /// - /// The nominal tile width, in the reference grid. - /// - /// - virtual public int NomTileWidth - { - get - { - return hi.sizValue.xtsiz; - } - - } - /// Returns the nominal width of the tiles in the reference grid. - /// - /// - /// The nominal tile width, in the reference grid. - /// - /// - virtual public int NomTileHeight - { - get - { - return hi.sizValue.ytsiz; - } - - } - /// Returns the number of components in the image. - /// - /// - /// The number of components in the image. - /// - /// - virtual public int NumComps - { - get - { - return nComp; - } - - } - /// Returns the horizontal code-block partition origin.Allowable values are - /// 0 and 1, nothing else. - /// - /// - virtual public int CbULX - { - get - { - return cb0x; - } - - } - /// Returns the vertical code-block partition origin. Allowable values are - /// 0 and 1, nothing else. - /// - /// - virtual public int CbULY - { - get - { - return cb0y; - } - - } - /// Return the DecoderSpecs instance filled when reading the headers - /// - /// - /// The DecoderSpecs of the decoder - /// - /// - virtual public DecoderSpecs DecoderSpecs - { - get - { - return decSpec; - } - - } - /// Returns the parameters that are used in this class. It returns a 2D - /// String array. Each of the 1D arrays is for a different option, and they - /// have 3 elements. The first element is the option name, the second one - /// is the synopsis and the third one is a long description of what the - /// parameter is. The synopsis or description may be 'null', in which case - /// it is assumed that there is no synopsis or description of the option, - /// respectively. - /// - /// - /// the options name, their synopsis and their explanation. - /// - /// - public static System.String[][] ParameterInfo - { - get - { - return pinfo; - } - - } - /// Return the number of tiles in the image - /// - /// - /// The number of tiles - /// - /// - virtual public int NumTiles - { - get - { - return nTiles; - } - - } - /// Sets the tile of each tile part in order. This information is needed - /// for identifying which packet header belongs to which tile when using - /// the PPM marker. - /// - /// - /// The tile number that the present tile part belongs to. - /// - /// - virtual public int TileOfTileParts - { - set - { - if (nPPMMarkSeg != 0) - { - tileOfTileParts.Add((System.Int32)value); - } - } - - } - /// Returns the number of found marker segments in the current header. - /// - /// - /// The number of marker segments found in the current header. - /// - /// - virtual public int NumFoundMarkSeg - { - get - { - return nfMarkSeg; - } - - } - - /// The prefix for header decoder options: 'H' - public const char OPT_PREFIX = 'H'; - - /// The list of parameters that is accepted for quantization. Options - /// for quantization start with 'Q'. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'pinfo'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly System.String[][] pinfo = null; - - /// The reference to the HeaderInfo instance holding the information found - /// in headers - /// - private HeaderInfo hi; - - /// Whether or not to display general information - //private bool verbose; - - /// Current header information in a string - private System.String hdStr = ""; - - /// The number of tiles within the image - private int nTiles; - - /// The number of tile parts in each tile - public int[] nTileParts; - - /// Used to store which markers have been already read, by using flag - /// bits. The different markers are marked with XXX_FOUND flags, such as - /// SIZ_FOUND - /// - private int nfMarkSeg = 0; - - /// Counts number of COC markers found in the header - private int nCOCMarkSeg = 0; - - /// Counts number of QCC markers found in the header - private int nQCCMarkSeg = 0; - - /// Counts number of COM markers found in the header - private int nCOMMarkSeg = 0; - - /// Counts number of RGN markers found in the header - private int nRGNMarkSeg = 0; - - /// Counts number of PPM markers found in the header - private int nPPMMarkSeg = 0; - - /// Counts number of PPT markers found in the header - private int[][] nPPTMarkSeg = null; - - /// Flag bit for SIZ marker segment found - private const int SIZ_FOUND = 1; - - /// Flag bit for COD marker segment found - private const int COD_FOUND = 1 << 1; - - /// Flag bit for COC marker segment found - private const int COC_FOUND = 1 << 2; - - /// Flag bit for QCD marker segment found - private const int QCD_FOUND = 1 << 3; - - /// Flag bit for TLM marker segment found - private const int TLM_FOUND = 1 << 4; - - /// Flag bit for PLM marker segment found - private const int PLM_FOUND = 1 << 5; - - /// Flag bit for SOT marker segment found - private const int SOT_FOUND = 1 << 6; - - /// Flag bit for PLT marker segment found - private const int PLT_FOUND = 1 << 7; - - /// Flag bit for QCC marker segment found - private const int QCC_FOUND = 1 << 8; - - /// Flag bit for RGN marker segment found - private const int RGN_FOUND = 1 << 9; - - /// Flag bit for POC marker segment found - private const int POC_FOUND = 1 << 10; - - /// Flag bit for COM marker segment found - private const int COM_FOUND = 1 << 11; - - /// Flag bit for SOD marker segment found - public const int SOD_FOUND = 1 << 13; - - /// Flag bit for SOD marker segment found - public const int PPM_FOUND = 1 << 14; - - /// Flag bit for SOD marker segment found - public const int PPT_FOUND = 1 << 15; - - /// Flag bit for CRG marker segment found - public const int CRG_FOUND = 1 << 16; - - /// The reset mask for new tiles - //UPGRADE_NOTE: Final was removed from the declaration of 'TILE_RESET '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - //private static readonly int TILE_RESET = ~ (PLM_FOUND | SIZ_FOUND | RGN_FOUND); - - /// HashTable used to store temporary marker segment byte buffers - private System.Collections.Hashtable ht = null; - - /// The number of components in the image - private int nComp; - - /// The horizontal code-block partition origin - private int cb0x = -1; - - /// The vertical code-block partition origin - private int cb0y = -1; - - /// The decoder specifications - private DecoderSpecs decSpec; - - /// Is the precinct partition used - internal bool precinctPartitionIsUsed; - - /// The offset of the main header in the input stream - public int mainHeadOff; - - /// Vector containing info as to which tile each tilepart belong - private System.Collections.ArrayList tileOfTileParts; - - /// Array containing the Nppm and Ippm fields of the PPM marker segments - private byte[][] pPMMarkerData; - - /// Array containing the Ippm fields of the PPT marker segments - private byte[][][][] tilePartPkdPktHeaders; - - /// The packed packet headers if the PPM or PPT markers are used - private System.IO.MemoryStream[] pkdPktHeaders; - - /// Returns the tiling origin, referred to as '(Px,Py)' in the 'ImgData' - /// interface. - /// - /// - /// If not null this object is used to return the information. If - /// null a new one is created and returned. - /// - /// - /// The coordinate of the tiling origin, in the canvas system, on - /// the reference grid. - /// - /// - /// - /// - /// - public Coord getTilingOrigin(Coord co) - { - if (co != null) - { - co.x = hi.sizValue.xt0siz; - co.y = hi.sizValue.yt0siz; - return co; - } - else - { - return new Coord(hi.sizValue.xt0siz, hi.sizValue.yt0siz); - } - } - - /// Returns true if the original data of the specified component was - /// signed. If the data was not signed a level shift has to be applied at - /// the end of the decompression chain. - /// - /// - /// The index of the component - /// - /// - /// True if the original image component was signed. - /// - /// - public bool isOriginalSigned(int c) - { - return hi.sizValue.isOrigSigned(c); - } - - /// Returns the original bitdepth of the specified component. - /// - /// - /// The index of the component - /// - /// - /// The bitdepth of the component - /// - /// - public int getOriginalBitDepth(int c) - { - return hi.sizValue.getOrigBitDepth(c); - } - - /// Returns the component sub-sampling factor, with respect to the - /// reference grid, along the horizontal direction for the specified - /// component. - /// - /// - /// The index of the component - /// - /// - /// The component sub-sampling factor X-wise. - /// - /// - public int getCompSubsX(int c) - { - return hi.sizValue.xrsiz[c]; - } - - /// Returns the component sub-sampling factor, with respect to the - /// reference grid, along the vertical direction for the specified - /// component. - /// - /// - /// The index of the component - /// - /// - /// The component sub-sampling factor Y-wise. - /// - /// - public int getCompSubsY(int c) - { - return hi.sizValue.yrsiz[c]; - } - - /// Returns the dequantizer parameters. Dequantizer parameters normally are - /// the quantization step sizes, see DequantizerParams. - /// - /// - /// The source of data for the dequantizer. - /// - /// - /// The number of range bits for each component. Must be - /// the number of range bits of the mixed components. - /// - /// - /// The DecoderSpecs instance after any image manipulation. - /// - /// - /// The dequantizer - /// - /// - public Dequantizer createDequantizer(CBlkQuantDataSrcDec src, int[] rb, DecoderSpecs decSpec2) - { - return new StdDequantizer(src, rb, decSpec2); - } - - /// Returns the precinct partition width for the specified tile-component - /// and resolution level. - /// - /// - /// the component index - /// - /// - /// the tile index - /// - /// - /// the resolution level - /// - /// - /// The precinct partition width for the specified tile-component - /// and resolution level - /// - /// - public int getPPX(int t, int c, int rl) - { - return decSpec.pss.getPPX(t, c, rl); - } - - /// Returns the precinct partition height for the specified tile-component - /// and resolution level. - /// - /// - /// the component index - /// - /// - /// the tile index - /// - /// - /// the resolution level - /// - /// - /// The precinct partition height for the specified tile-component - /// and resolution level - /// - /// - public int getPPY(int t, int c, int rl) - { - return decSpec.pss.getPPY(t, c, rl); - } - - /// Returns the boolean used to know if the precinct partition is used - /// - /// - public bool precinctPartitionUsed() - { - return precinctPartitionIsUsed; - } - - /// Reads a wavelet filter from the codestream and returns the filter - /// object that implements it. - /// - /// - /// The encoded header stream from where to read the info - /// - /// - /// Int array of one element to return the type of the - /// wavelet filter. - /// - /// - //UPGRADE_TODO: Class 'java.io.DataInputStream' was converted to 'System.IO.BinaryReader' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioDataInputStream'" - private SynWTFilter readFilter(System.IO.BinaryReader ehs, int[] filtIdx) - { - int kid; // the filter id - - kid = filtIdx[0] = ehs.ReadByte(); - if (kid >= (1 << 7)) - { - throw new NotImplementedException("Custom filters not supported"); - } - // Return filter based on ID - switch (kid) - { - - case CSJ2K.j2k.wavelet.FilterTypes_Fields.W9X7: - return new SynWTFilterFloatLift9x7(); - - case CSJ2K.j2k.wavelet.FilterTypes_Fields.W5X3: - return new SynWTFilterIntLift5x3(); - - default: - throw new CorruptedCodestreamException("Specified wavelet filter " + "not" + " JPEG 2000 part I " + "compliant"); - - } - } - - /// Checks that the marker segment length is correct. - /// - /// - /// The encoded header stream - /// - /// - /// The string identifying the marker, such as "SIZ marker" - /// - /// - /// If an I/O error occurs - /// - /// - //UPGRADE_TODO: Class 'java.io.DataInputStream' was converted to 'System.IO.BinaryReader' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioDataInputStream'" - public virtual void checkMarkerLength(System.IO.BinaryReader ehs, System.String str) - { - long available; - available = ehs.BaseStream.Length - ehs.BaseStream.Position; - if ((int)available != 0) - { - FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.WARNING, str + " length was short, attempting to resync."); - } - } - - /// Reads the SIZ marker segment and realigns the codestream at the point - /// where the next marker segment should be found. - /// - ///

    SIZ is a fixed information marker segment containing informations - /// about image and tile sizes. It is required in the main header - /// immediately after SOC.

    - /// - ///
    - /// The encoded header stream - /// - /// - /// If an I/O error occurs while reading from the - /// encoded header stream - /// - /// - //UPGRADE_TODO: Class 'java.io.DataInputStream' was converted to 'System.IO.BinaryReader' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioDataInputStream'" - private void readSIZ(System.IO.BinaryReader ehs) - { - HeaderInfo.SIZ ms = hi.NewSIZ; - hi.sizValue = ms; - - // Read the length of SIZ marker segment (Lsiz) - ms.lsiz = ehs.ReadUInt16(); - - // Read the capability of the codestream (Rsiz) - ms.rsiz = ehs.ReadUInt16(); - if (ms.rsiz > 2) - { - throw new System.ApplicationException("Codestream capabiities not JPEG 2000 - Part I" + " compliant"); - } - - // Read image size - ms.xsiz = ehs.ReadInt32(); - ms.ysiz = ehs.ReadInt32(); - if (ms.xsiz <= 0 || ms.ysiz <= 0) - { - throw new System.IO.IOException("JJ2000 does not support images whose " + "width and/or height not in the " + "range: 1 -- (2^31)-1"); - } - - // Read image offset - ms.x0siz = ehs.ReadInt32(); - ms.y0siz = ehs.ReadInt32(); - if (ms.x0siz < 0 || ms.y0siz < 0) - { - throw new System.IO.IOException("JJ2000 does not support images offset " + "not in the range: 0 -- (2^31)-1"); - } - - // Read size of tile - ms.xtsiz = ehs.ReadInt32(); - ms.ytsiz = ehs.ReadInt32(); - if (ms.xtsiz <= 0 || ms.ytsiz <= 0) - { - throw new System.IO.IOException("JJ2000 does not support tiles whose " + "width and/or height are not in " + "the range: 1 -- (2^31)-1"); - } - - // Read upper-left tile offset - ms.xt0siz = ehs.ReadInt32(); - ms.yt0siz = ehs.ReadInt32(); - if (ms.xt0siz < 0 || ms.yt0siz < 0) - { - throw new System.IO.IOException("JJ2000 does not support tiles whose " + "offset is not in " + "the range: 0 -- (2^31)-1"); - } - - // Read number of components and initialize related arrays - nComp = ms.csiz = ehs.ReadUInt16(); - if (nComp < 1 || nComp > 16384) - { - throw new System.ArgumentException("Number of component out of " + "range 1--16384: " + nComp); - } - - ms.ssiz = new int[nComp]; - ms.xrsiz = new int[nComp]; - ms.yrsiz = new int[nComp]; - - // Read bit-depth and down-sampling factors of each component - for (int i = 0; i < nComp; i++) - { - ms.ssiz[i] = ehs.ReadByte(); - ms.xrsiz[i] = ehs.ReadByte(); - ms.yrsiz[i] = ehs.ReadByte(); - } - - // Check marker length - checkMarkerLength(ehs, "SIZ marker"); - - // Create needed ModuleSpec - nTiles = ms.NumTiles; - - // Finish initialization of decSpec - decSpec = new DecoderSpecs(nTiles, nComp); - } - - /// Reads a CRG marker segment and checks its length. CRG is an - /// informational marker segment that allows specific registration of - /// components with respect to each other. - /// - /// - /// The encoded header stream - /// - /// - //UPGRADE_TODO: Class 'java.io.DataInputStream' was converted to 'System.IO.BinaryReader' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioDataInputStream'" - private void readCRG(System.IO.BinaryReader ehs) - { - HeaderInfo.CRG ms = hi.NewCRG; - hi.crgValue = ms; - - ms.lcrg = ehs.ReadUInt16(); - ms.xcrg = new int[nComp]; - ms.ycrg = new int[nComp]; - - FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.WARNING, "Information in CRG marker segment " + "not taken into account. This may affect the display " + "of the decoded image."); - for (int c = 0; c < nComp; c++) - { - ms.xcrg[c] = ehs.ReadUInt16(); - ms.ycrg[c] = ehs.ReadUInt16(); - } - - // Check marker length - checkMarkerLength(ehs, "CRG marker"); - } - - /// Reads a COM marker segments and realigns the bit stream at the point - /// where the next marker segment should be found. COM is an informational - /// marker segment that allows to include unstructured data in the main and - /// tile-part headers. - /// - /// - /// The encoded header stream - /// - /// - /// Flag indicating whether or not this marker segment is read - /// from the main header. - /// - /// - /// The index of the current tile - /// - /// - /// Occurence of this COM marker in eith main or tile-part - /// header - /// - /// - /// If an I/O error occurs while reading from the - /// encoded header stream - /// - /// - //UPGRADE_TODO: Class 'java.io.DataInputStream' was converted to 'System.IO.BinaryReader' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioDataInputStream'" - private void readCOM(System.IO.BinaryReader ehs, bool mainh, int tileIdx, int comIdx) - { - HeaderInfo.COM ms = hi.NewCOM; - - // Read length of COM field - ms.lcom = ehs.ReadUInt16(); - - // Read the registration value of the COM marker segment - ms.rcom = ehs.ReadUInt16(); - switch (ms.rcom) - { - case CSJ2K.j2k.codestream.Markers.RCOM_BINARY: - case CSJ2K.j2k.codestream.Markers.RCOM_LATIN: - ms.ccom = new byte[ms.lcom - 4]; - for (int i = 0; i < ms.lcom - 4; i++) - { - ms.ccom[i] = ehs.ReadByte(); - } - break; - default: - // --- Unknown or unsupported markers --- - // (skip them and see if we can get way with it) - FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.WARNING, "COM marker registered as " + ms.rcom + " unknown, ignoring (this might crash the " + "decoder or decode a quality degraded or even " + "useless image)"); - System.IO.BinaryReader temp_BinaryReader; - System.Int64 temp_Int64; - temp_BinaryReader = ehs; - temp_Int64 = temp_BinaryReader.BaseStream.Position; - temp_Int64 = temp_BinaryReader.BaseStream.Seek(ms.lcom - 4, System.IO.SeekOrigin.Current) - temp_Int64; - // CONVERSION PROBLEM? - int generatedAux2 = (int)temp_Int64; //Ignore this field for the moment - break; - - } - - if (mainh) - { - hi.comValue["main_" + comIdx] = ms; - } - else - { - hi.comValue["t" + tileIdx + "_" + comIdx] = ms; - } - - // Check marker length - checkMarkerLength(ehs, "COM marker"); - } - - /// Reads a QCD marker segment and realigns the codestream at the point - /// where the next marker should be found. QCD is a functional marker - /// segment that describes the quantization default. - /// - /// - /// The encoded stream. - /// - /// - /// Flag indicating whether or not this marker segment is read - /// from the main header. - /// - /// - /// The index of the current tile - /// - /// - /// Tile-part index - /// - /// - /// If an I/O error occurs while reading from the - /// encoded header stream. - /// - /// - //UPGRADE_TODO: Class 'java.io.DataInputStream' was converted to 'System.IO.BinaryReader' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioDataInputStream'" - private void readQCD(System.IO.BinaryReader ehs, bool mainh, int tileIdx, int tpIdx) - { - StdDequantizerParams qParms; - int guardBits; - int[][] exp; - float[][] nStep = null; - HeaderInfo.QCD ms = hi.NewQCD; - - // Lqcd (length of QCD field) - ms.lqcd = ehs.ReadUInt16(); - - // Sqcd (quantization style) - ms.sqcd = ehs.ReadByte(); - - guardBits = ms.NumGuardBits; - int qType = ms.QuantType; - - if (mainh) - { - hi.qcdValue["main"] = ms; - // If the main header is being read set default value of - // dequantization spec - switch (qType) - { - - case CSJ2K.j2k.codestream.Markers.SQCX_NO_QUANTIZATION: - decSpec.qts.setDefault("reversible"); - break; - - case CSJ2K.j2k.codestream.Markers.SQCX_SCALAR_DERIVED: - decSpec.qts.setDefault("derived"); - break; - - case CSJ2K.j2k.codestream.Markers.SQCX_SCALAR_EXPOUNDED: - decSpec.qts.setDefault("expounded"); - break; - - default: - throw new CorruptedCodestreamException("Unknown or " + "unsupported " + "quantization style " + "in Sqcd field, QCD " + "marker main header"); - - } - } - else - { - hi.qcdValue["t" + tileIdx] = ms; - // If the tile header is being read set default value of - // dequantization spec for tile - switch (qType) - { - - case CSJ2K.j2k.codestream.Markers.SQCX_NO_QUANTIZATION: - decSpec.qts.setTileDef(tileIdx, "reversible"); - break; - - case CSJ2K.j2k.codestream.Markers.SQCX_SCALAR_DERIVED: - decSpec.qts.setTileDef(tileIdx, "derived"); - break; - - case CSJ2K.j2k.codestream.Markers.SQCX_SCALAR_EXPOUNDED: - decSpec.qts.setTileDef(tileIdx, "expounded"); - break; - - default: - throw new CorruptedCodestreamException("Unknown or " + "unsupported " + "quantization style " + "in Sqcd field, QCD " + "marker, tile header"); - - } - } - - qParms = new StdDequantizerParams(); - - if (qType == CSJ2K.j2k.codestream.Markers.SQCX_NO_QUANTIZATION) - { - int maxrl = (mainh ? ((System.Int32)decSpec.dls.getDefault()) : ((System.Int32)decSpec.dls.getTileDef(tileIdx))); - int j, rl; // i removed - int minb, maxb, hpd; - int tmp; - - exp = qParms.exp = new int[maxrl + 1][]; - int[][] tmpArray = new int[maxrl + 1][]; - for (int i2 = 0; i2 < maxrl + 1; i2++) - { - tmpArray[i2] = new int[4]; - } - ms.spqcd = tmpArray; - - for (rl = 0; rl <= maxrl; rl++) - { - // Loop on resolution levels - // Find the number of subbands in the resolution level - if (rl == 0) - { - // Only the LL subband - minb = 0; - maxb = 1; - } - else - { - // Dyadic decomposition - hpd = 1; - - // Adapt hpd to resolution level - if (hpd > maxrl - rl) - { - hpd -= (maxrl - rl); - } - else - { - hpd = 1; - } - // Determine max and min subband index - minb = 1 << ((hpd - 1) << 1); // minb = 4^(hpd-1) - maxb = 1 << (hpd << 1); // maxb = 4^hpd - } - // Allocate array for subbands in resolution level - exp[rl] = new int[maxb]; - - for (j = minb; j < maxb; j++) - { - tmp = ms.spqcd[rl][j] = ehs.ReadByte(); - exp[rl][j] = (tmp >> CSJ2K.j2k.codestream.Markers.SQCX_EXP_SHIFT) & CSJ2K.j2k.codestream.Markers.SQCX_EXP_MASK; - } - } // end for rl - } - else - { - int maxrl = (qType == CSJ2K.j2k.codestream.Markers.SQCX_SCALAR_DERIVED) ? 0 : (mainh ? ((System.Int32)decSpec.dls.getDefault()) : ((System.Int32)decSpec.dls.getTileDef(tileIdx))); - int j, rl; // i removed - int minb, maxb, hpd; - int tmp; - - exp = qParms.exp = new int[maxrl + 1][]; - nStep = qParms.nStep = new float[maxrl + 1][]; - int[][] tmpArray2 = new int[maxrl + 1][]; - for (int i3 = 0; i3 < maxrl + 1; i3++) - { - tmpArray2[i3] = new int[4]; - } - ms.spqcd = tmpArray2; - - for (rl = 0; rl <= maxrl; rl++) - { - // Loop on resolution levels - // Find the number of subbands in the resolution level - if (rl == 0) - { - // Only the LL subband - minb = 0; - maxb = 1; - } - else - { - // Dyadic decomposition - hpd = 1; - - // Adapt hpd to resolution level - if (hpd > maxrl - rl) - { - hpd -= (maxrl - rl); - } - else - { - hpd = 1; - } - // Determine max and min subband index - minb = 1 << ((hpd - 1) << 1); // minb = 4^(hpd-1) - maxb = 1 << (hpd << 1); // maxb = 4^hpd - } - // Allocate array for subbands in resolution level - exp[rl] = new int[maxb]; - nStep[rl] = new float[maxb]; - - for (j = minb; j < maxb; j++) - { - tmp = ms.spqcd[rl][j] = ehs.ReadUInt16(); - exp[rl][j] = (tmp >> 11) & 0x1f; - // NOTE: the formula below does not support more than 5 - // bits for the exponent, otherwise (-1< Reads a QCC marker segment and realigns the codestream at the point - /// where the next marker should be found. QCC is a functional marker - /// segment that describes the quantization of one component. - /// - /// - /// The encoded stream. - /// - /// - /// Flag indicating whether or not this marker segment is read - /// from the main header. - /// - /// - /// The index of the current tile - /// - /// - /// Tile-part index - /// - /// - /// If an I/O error occurs while reading from the - /// encoded header stream. - /// - /// - //UPGRADE_TODO: Class 'java.io.DataInputStream' was converted to 'System.IO.BinaryReader' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioDataInputStream'" - private void readQCC(System.IO.BinaryReader ehs, bool mainh, int tileIdx, int tpIdx) - { - int cComp; // current component - int tmp; - StdDequantizerParams qParms; - int[][] expC; - float[][] nStepC = null; - HeaderInfo.QCC ms = hi.NewQCC; - - // Lqcc (length of QCC field) - ms.lqcc = ehs.ReadUInt16(); - - // Cqcc - if (nComp < 257) - { - cComp = ms.cqcc = ehs.ReadByte(); - } - else - { - cComp = ms.cqcc = ehs.ReadUInt16(); - } - if (cComp >= nComp) - { - throw new CorruptedCodestreamException("Invalid component " + "index in QCC marker"); - } - - // Sqcc (quantization style) - ms.sqcc = ehs.ReadByte(); - int guardBits = ms.NumGuardBits; - int qType = ms.QuantType; - - if (mainh) - { - hi.qccValue["main_c" + cComp] = ms; - // If main header is being read, set default for component in all - // tiles - switch (qType) - { - - case CSJ2K.j2k.codestream.Markers.SQCX_NO_QUANTIZATION: - decSpec.qts.setCompDef(cComp, "reversible"); - break; - - case CSJ2K.j2k.codestream.Markers.SQCX_SCALAR_DERIVED: - decSpec.qts.setCompDef(cComp, "derived"); - break; - - case CSJ2K.j2k.codestream.Markers.SQCX_SCALAR_EXPOUNDED: - decSpec.qts.setCompDef(cComp, "expounded"); - break; - - default: - throw new CorruptedCodestreamException("Unknown or " + "unsupported " + "quantization style " + "in Sqcd field, QCD " + "marker, main header"); - - } - } - else - { - hi.qccValue["t" + tileIdx + "_c" + cComp] = ms; - // If tile header is being read, set value for component in - // this tiles - switch (qType) - { - - case CSJ2K.j2k.codestream.Markers.SQCX_NO_QUANTIZATION: - decSpec.qts.setTileCompVal(tileIdx, cComp, "reversible"); - break; - - case CSJ2K.j2k.codestream.Markers.SQCX_SCALAR_DERIVED: - decSpec.qts.setTileCompVal(tileIdx, cComp, "derived"); - break; - - case CSJ2K.j2k.codestream.Markers.SQCX_SCALAR_EXPOUNDED: - decSpec.qts.setTileCompVal(tileIdx, cComp, "expounded"); - break; - - default: - throw new CorruptedCodestreamException("Unknown or " + "unsupported " + "quantization style " + "in Sqcd field, QCD " + "marker, main header"); - - } - } - - // Decode all dequantizer params - qParms = new StdDequantizerParams(); - - if (qType == CSJ2K.j2k.codestream.Markers.SQCX_NO_QUANTIZATION) - { - int maxrl = (mainh ? ((System.Int32)decSpec.dls.getCompDef(cComp)) : ((System.Int32)decSpec.dls.getTileCompVal(tileIdx, cComp))); - int j, rl; // i removed - int minb, maxb, hpd; - - expC = qParms.exp = new int[maxrl + 1][]; - int[][] tmpArray = new int[maxrl + 1][]; - for (int i2 = 0; i2 < maxrl + 1; i2++) - { - tmpArray[i2] = new int[4]; - } - ms.spqcc = tmpArray; - - for (rl = 0; rl <= maxrl; rl++) - { - // Loop on resolution levels - // Find the number of subbands in the resolution level - if (rl == 0) - { - // Only the LL subband - minb = 0; - maxb = 1; - } - else - { - // Dyadic decomposition - hpd = 1; - - // Adapt hpd to resolution level - if (hpd > maxrl - rl) - { - hpd -= (maxrl - rl); - } - else - { - hpd = 1; - } - // Determine max and min subband index - minb = 1 << ((hpd - 1) << 1); // minb = 4^(hpd-1) - maxb = 1 << (hpd << 1); // maxb = 4^hpd - } - // Allocate array for subbands in resolution level - expC[rl] = new int[maxb]; - - for (j = minb; j < maxb; j++) - { - tmp = ms.spqcc[rl][j] = ehs.ReadByte(); - expC[rl][j] = (tmp >> CSJ2K.j2k.codestream.Markers.SQCX_EXP_SHIFT) & CSJ2K.j2k.codestream.Markers.SQCX_EXP_MASK; - } - } // end for rl - } - else - { - int maxrl = (qType == CSJ2K.j2k.codestream.Markers.SQCX_SCALAR_DERIVED) ? 0 : (mainh ? ((System.Int32)decSpec.dls.getCompDef(cComp)) : ((System.Int32)decSpec.dls.getTileCompVal(tileIdx, cComp))); - int j, rl; // i removed - int minb, maxb, hpd; - - nStepC = qParms.nStep = new float[maxrl + 1][]; - expC = qParms.exp = new int[maxrl + 1][]; - int[][] tmpArray2 = new int[maxrl + 1][]; - for (int i3 = 0; i3 < maxrl + 1; i3++) - { - tmpArray2[i3] = new int[4]; - } - ms.spqcc = tmpArray2; - - for (rl = 0; rl <= maxrl; rl++) - { - // Loop on resolution levels - // Find the number of subbands in the resolution level - if (rl == 0) - { - // Only the LL subband - minb = 0; - maxb = 1; - } - else - { - // Dyadic decomposition - hpd = 1; - - // Adapt hpd to resolution level - if (hpd > maxrl - rl) - { - hpd -= (maxrl - rl); - } - else - { - hpd = 1; - } - // Determine max and min subband index - minb = 1 << ((hpd - 1) << 1); // minb = 4^(hpd-1) - maxb = 1 << (hpd << 1); // maxb = 4^hpd - } - // Allocate array for subbands in resolution level - expC[rl] = new int[maxb]; - nStepC[rl] = new float[maxb]; - - for (j = minb; j < maxb; j++) - { - tmp = ms.spqcc[rl][j] = ehs.ReadUInt16(); - expC[rl][j] = (tmp >> 11) & 0x1f; - // NOTE: the formula below does not support more than 5 - // bits for the exponent, otherwise (-1< Reads a COD marker segment and realigns the codestream where the next - /// marker should be found. - /// - /// - /// The encoder header stream. - /// - /// - /// Flag indicating whether or not this marker segment is read - /// from the main header. - /// - /// - /// The index of the current tile - /// - /// - /// Tile-part index - /// - /// - /// If an I/O error occurs while reading from the - /// encoder header stream - /// - /// - //UPGRADE_TODO: Class 'java.io.DataInputStream' was converted to 'System.IO.BinaryReader' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioDataInputStream'" - private void readCOD(System.IO.BinaryReader ehs, bool mainh, int tileIdx, int tpIdx) - { - int cstyle; // The block style - SynWTFilter[] hfilters, vfilters; - //int l; - System.Int32[] cblk; - System.String errMsg; - //bool sopUsed = false; - //bool ephUsed = false; - HeaderInfo.COD ms = hi.NewCOD; - - // Lcod (marker length) - ms.lcod = ehs.ReadUInt16(); - - // Scod (block style) - // We only support wavelet transformed data - cstyle = ms.scod = ehs.ReadByte(); - - if ((cstyle & CSJ2K.j2k.codestream.Markers.SCOX_PRECINCT_PARTITION) != 0) - { - precinctPartitionIsUsed = true; - // Remove flag - cstyle &= ~(CSJ2K.j2k.codestream.Markers.SCOX_PRECINCT_PARTITION); - } - else - { - precinctPartitionIsUsed = false; - } - - // SOP markers - if (mainh) - { - hi.codValue["main"] = ms; - - if ((cstyle & CSJ2K.j2k.codestream.Markers.SCOX_USE_SOP) != 0) - { - // SOP markers are used - decSpec.sops.setDefault((System.Object)"true".ToUpper().Equals("TRUE")); - //sopUsed = true; - // Remove flag - cstyle &= ~(CSJ2K.j2k.codestream.Markers.SCOX_USE_SOP); - } - else - { - // SOP markers are not used - decSpec.sops.setDefault((System.Object)"false".ToUpper().Equals("TRUE")); - } - } - else - { - hi.codValue["t" + tileIdx] = ms; - - if ((cstyle & CSJ2K.j2k.codestream.Markers.SCOX_USE_SOP) != 0) - { - // SOP markers are used - decSpec.sops.setTileDef(tileIdx, (System.Object)"true".ToUpper().Equals("TRUE")); - //sopUsed = true; - // Remove flag - cstyle &= ~(CSJ2K.j2k.codestream.Markers.SCOX_USE_SOP); - } - else - { - // SOP markers are not used - decSpec.sops.setTileDef(tileIdx, (System.Object)"false".ToUpper().Equals("TRUE")); - } - } - - // EPH markers - if (mainh) - { - if ((cstyle & CSJ2K.j2k.codestream.Markers.SCOX_USE_EPH) != 0) - { - // EPH markers are used - decSpec.ephs.setDefault((System.Object)"true".ToUpper().Equals("TRUE")); - //ephUsed = true; - // Remove flag - cstyle &= ~(CSJ2K.j2k.codestream.Markers.SCOX_USE_EPH); - } - else - { - // EPH markers are not used - decSpec.ephs.setDefault((System.Object)"false".ToUpper().Equals("TRUE")); - } - } - else - { - if ((cstyle & CSJ2K.j2k.codestream.Markers.SCOX_USE_EPH) != 0) - { - // EPH markers are used - decSpec.ephs.setTileDef(tileIdx, (System.Object)"true".ToUpper().Equals("TRUE")); - //ephUsed = true; - // Remove flag - cstyle &= ~(CSJ2K.j2k.codestream.Markers.SCOX_USE_EPH); - } - else - { - // EPH markers are not used - decSpec.ephs.setTileDef(tileIdx, (System.Object)"false".ToUpper().Equals("TRUE")); - } - } - - // Code-block partition origin - if ((cstyle & (CSJ2K.j2k.codestream.Markers.SCOX_HOR_CB_PART | CSJ2K.j2k.codestream.Markers.SCOX_VER_CB_PART)) != 0) - { - FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.WARNING, "Code-block partition origin " + "different from (0,0). This is defined in JPEG 2000" + " part 2 and may not be supported by all JPEG " + "2000 decoders."); - } - if ((cstyle & CSJ2K.j2k.codestream.Markers.SCOX_HOR_CB_PART) != 0) - { - if (cb0x != -1 && cb0x == 0) - { - throw new System.ArgumentException("Code-block partition " + "origin redefined in new" + " COD marker segment. Not" + " supported by JJ2000"); - } - cb0x = 1; - cstyle &= ~(CSJ2K.j2k.codestream.Markers.SCOX_HOR_CB_PART); - } - else - { - if (cb0x != -1 && cb0x == 1) - { - throw new System.ArgumentException("Code-block partition " + "origin redefined in new" + " COD marker segment. Not" + " supported by JJ2000"); - } - cb0x = 0; - } - if ((cstyle & CSJ2K.j2k.codestream.Markers.SCOX_VER_CB_PART) != 0) - { - if (cb0y != -1 && cb0y == 0) - { - throw new System.ArgumentException("Code-block partition " + "origin redefined in new" + " COD marker segment. Not" + " supported by JJ2000"); - } - cb0y = 1; - cstyle &= ~(CSJ2K.j2k.codestream.Markers.SCOX_VER_CB_PART); - } - else - { - if (cb0y != -1 && cb0y == 1) - { - throw new System.ArgumentException("Code-block partition " + "origin redefined in new" + " COD marker segment. Not" + " supported by JJ2000"); - } - cb0y = 0; - } - - // SGcod - // Read the progressive order - ms.sgcod_po = ehs.ReadByte(); - - // Read the number of layers - ms.sgcod_nl = ehs.ReadUInt16(); - if (ms.sgcod_nl <= 0 || ms.sgcod_nl > 65535) - { - throw new CorruptedCodestreamException("Number of layers out of " + "range: 1--65535"); - } - - // Multiple component transform - ms.sgcod_mct = ehs.ReadByte(); - - // SPcod - // decomposition levels - int mrl = ms.spcod_ndl = ehs.ReadByte(); - if (mrl > 32) - { - throw new CorruptedCodestreamException("Number of decomposition " + "levels out of range: " + "0--32"); - } - - // Read the code-blocks dimensions - cblk = new System.Int32[2]; - ms.spcod_cw = ehs.ReadByte(); - cblk[0] = (System.Int32)(1 << (ms.spcod_cw + 2)); - if (cblk[0] < CSJ2K.j2k.entropy.StdEntropyCoderOptions.MIN_CB_DIM || cblk[0] > CSJ2K.j2k.entropy.StdEntropyCoderOptions.MAX_CB_DIM) - { - errMsg = "Non-valid code-block width in SPcod field, " + "COD marker"; - throw new CorruptedCodestreamException(errMsg); - } - ms.spcod_ch = ehs.ReadByte(); - cblk[1] = (System.Int32)(1 << (ms.spcod_ch + 2)); - if (cblk[1] < CSJ2K.j2k.entropy.StdEntropyCoderOptions.MIN_CB_DIM || cblk[1] > CSJ2K.j2k.entropy.StdEntropyCoderOptions.MAX_CB_DIM) - { - errMsg = "Non-valid code-block height in SPcod field, " + "COD marker"; - throw new CorruptedCodestreamException(errMsg); - } - if ((cblk[0] * cblk[1]) > CSJ2K.j2k.entropy.StdEntropyCoderOptions.MAX_CB_AREA) - { - errMsg = "Non-valid code-block area in SPcod field, " + "COD marker"; - throw new CorruptedCodestreamException(errMsg); - } - if (mainh) - { - decSpec.cblks.setDefault((System.Object)(cblk)); - } - else - { - decSpec.cblks.setTileDef(tileIdx, (System.Object)(cblk)); - } - - // Style of the code-block coding passes - int ecOptions = ms.spcod_cs = ehs.ReadByte(); - if ((ecOptions & ~(CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_BYPASS | CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_RESET_MQ | CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_TERM_PASS | CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_VERT_STR_CAUSAL | CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_PRED_TERM | CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_SEG_SYMBOLS)) != 0) - { - throw new CorruptedCodestreamException("Unknown \"code-block " + "style\" in SPcod field, " + "COD marker: 0x" + System.Convert.ToString(ecOptions, 16)); - } - - // Read wavelet filter for tile or image - hfilters = new SynWTFilter[1]; - vfilters = new SynWTFilter[1]; - hfilters[0] = readFilter(ehs, ms.spcod_t); - vfilters[0] = hfilters[0]; - - // Fill the filter spec - // If this is the main header, set the default value, if it is the - // tile header, set default for this tile - SynWTFilter[][] hvfilters = new SynWTFilter[2][]; - hvfilters[0] = hfilters; - hvfilters[1] = vfilters; - - // Get precinct partition sizes - System.Collections.ArrayList[] v = new System.Collections.ArrayList[2]; - v[0] = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); - v[1] = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); - int val = CSJ2K.j2k.codestream.Markers.PRECINCT_PARTITION_DEF_SIZE; - if (!precinctPartitionIsUsed) - { - System.Int32 w, h; - w = (System.Int32)(1 << (val & 0x000F)); - v[0].Add(w); - h = (System.Int32)(1 << (((val & 0x00F0) >> 4))); - v[1].Add(h); - } - else - { - ms.spcod_ps = new int[mrl + 1]; - for (int rl = mrl; rl >= 0; rl--) - { - System.Int32 w, h; - val = ms.spcod_ps[mrl - rl] = ehs.ReadByte(); - w = (System.Int32)(1 << (val & 0x000F)); - v[0].Insert(0, w); - h = (System.Int32)(1 << (((val & 0x00F0) >> 4))); - v[1].Insert(0, h); - } - } - if (mainh) - { - decSpec.pss.setDefault(v); - } - else - { - decSpec.pss.setTileDef(tileIdx, v); - } - precinctPartitionIsUsed = true; - - // Check marker length - checkMarkerLength(ehs, "COD marker"); - - // Store specifications in decSpec - if (mainh) - { - decSpec.wfs.setDefault(hvfilters); - decSpec.dls.setDefault((System.Object)mrl); - decSpec.ecopts.setDefault((System.Object)ecOptions); - decSpec.cts.setDefault((System.Object)ms.sgcod_mct); - decSpec.nls.setDefault((System.Object)ms.sgcod_nl); - decSpec.pos.setDefault((System.Object)ms.sgcod_po); - } - else - { - decSpec.wfs.setTileDef(tileIdx, hvfilters); - decSpec.dls.setTileDef(tileIdx, (System.Object)mrl); - decSpec.ecopts.setTileDef(tileIdx, (System.Object)ecOptions); - decSpec.cts.setTileDef(tileIdx, (System.Object)ms.sgcod_mct); - decSpec.nls.setTileDef(tileIdx, (System.Object)ms.sgcod_nl); - decSpec.pos.setTileDef(tileIdx, (System.Object)ms.sgcod_po); - } - } - - /// Reads the COC marker segment and realigns the codestream where the next - /// marker should be found. - /// - /// - /// The encoder header stream. - /// - /// - /// Flag indicating whether or not this marker segment is read - /// from the main header. - /// - /// - /// The index of the current tile - /// - /// - /// Tile-part index - /// - /// - /// If an I/O error occurs while reading from the - /// encoder header stream - /// - /// - //UPGRADE_TODO: Class 'java.io.DataInputStream' was converted to 'System.IO.BinaryReader' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioDataInputStream'" - private void readCOC(System.IO.BinaryReader ehs, bool mainh, int tileIdx, int tpIdx) - { - int cComp; // current component - SynWTFilter[] hfilters, vfilters; - //int tmp, l; - int ecOptions; - System.Int32[] cblk; - System.String errMsg; - HeaderInfo.COC ms = hi.NewCOC; - - // Lcoc (marker length) - ms.lcoc = ehs.ReadUInt16(); - - // Ccoc - if (nComp < 257) - { - cComp = ms.ccoc = ehs.ReadByte(); - } - else - { - cComp = ms.ccoc = ehs.ReadUInt16(); - } - if (cComp >= nComp) - { - throw new CorruptedCodestreamException("Invalid component index " + "in QCC marker"); - } - - // Scoc (block style) - int cstyle = ms.scoc = ehs.ReadByte(); - if ((cstyle & CSJ2K.j2k.codestream.Markers.SCOX_PRECINCT_PARTITION) != 0) - { - precinctPartitionIsUsed = true; - // Remove flag - cstyle &= ~(CSJ2K.j2k.codestream.Markers.SCOX_PRECINCT_PARTITION); - } - else - { - precinctPartitionIsUsed = false; - } - - // SPcoc - - // decomposition levels - int mrl = ms.spcoc_ndl = ehs.ReadByte(); - - // Read the code-blocks dimensions - cblk = new System.Int32[2]; - ms.spcoc_cw = ehs.ReadByte(); - cblk[0] = (System.Int32)(1 << (ms.spcoc_cw + 2)); - if (cblk[0] < CSJ2K.j2k.entropy.StdEntropyCoderOptions.MIN_CB_DIM || cblk[0] > CSJ2K.j2k.entropy.StdEntropyCoderOptions.MAX_CB_DIM) - { - errMsg = "Non-valid code-block width in SPcod field, " + "COC marker"; - throw new CorruptedCodestreamException(errMsg); - } - ms.spcoc_ch = ehs.ReadByte(); - cblk[1] = (System.Int32)(1 << (ms.spcoc_ch + 2)); - if (cblk[1] < CSJ2K.j2k.entropy.StdEntropyCoderOptions.MIN_CB_DIM || cblk[1] > CSJ2K.j2k.entropy.StdEntropyCoderOptions.MAX_CB_DIM) - { - errMsg = "Non-valid code-block height in SPcod field, " + "COC marker"; - throw new CorruptedCodestreamException(errMsg); - } - if ((cblk[0] * cblk[1]) > CSJ2K.j2k.entropy.StdEntropyCoderOptions.MAX_CB_AREA) - { - errMsg = "Non-valid code-block area in SPcod field, " + "COC marker"; - throw new CorruptedCodestreamException(errMsg); - } - if (mainh) - { - decSpec.cblks.setCompDef(cComp, (System.Object)(cblk)); - } - else - { - decSpec.cblks.setTileCompVal(tileIdx, cComp, (System.Object)(cblk)); - } - - // Read entropy block mode options - // NOTE: currently OPT_SEG_SYMBOLS is not included here - ecOptions = ms.spcoc_cs = ehs.ReadByte(); - if ((ecOptions & ~(CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_BYPASS | CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_RESET_MQ | CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_TERM_PASS | CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_VERT_STR_CAUSAL | CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_PRED_TERM | CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_SEG_SYMBOLS)) != 0) - { - throw new CorruptedCodestreamException("Unknown \"code-block " + "context\" in SPcoc field, " + "COC marker: 0x" + System.Convert.ToString(ecOptions, 16)); - } - - // Read wavelet filter for tile or image - hfilters = new SynWTFilter[1]; - vfilters = new SynWTFilter[1]; - hfilters[0] = readFilter(ehs, ms.spcoc_t); - vfilters[0] = hfilters[0]; - - // Fill the filter spec - // If this is the main header, set the default value, if it is the - // tile header, set default for this tile - SynWTFilter[][] hvfilters = new SynWTFilter[2][]; - hvfilters[0] = hfilters; - hvfilters[1] = vfilters; - - // Get precinct partition sizes - System.Collections.ArrayList[] v = new System.Collections.ArrayList[2]; - v[0] = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); - v[1] = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); - int val = CSJ2K.j2k.codestream.Markers.PRECINCT_PARTITION_DEF_SIZE; - if (!precinctPartitionIsUsed) - { - System.Int32 w, h; - w = (System.Int32)(1 << (val & 0x000F)); - v[0].Add(w); - h = (System.Int32)(1 << (((val & 0x00F0) >> 4))); - v[1].Add(h); - } - else - { - ms.spcoc_ps = new int[mrl + 1]; - for (int rl = mrl; rl >= 0; rl--) - { - System.Int32 w, h; - val = ms.spcoc_ps[rl] = ehs.ReadByte(); - w = (System.Int32)(1 << (val & 0x000F)); - v[0].Insert(0, w); - h = (System.Int32)(1 << (((val & 0x00F0) >> 4))); - v[1].Insert(0, h); - } - } - if (mainh) - { - decSpec.pss.setCompDef(cComp, v); - } - else - { - decSpec.pss.setTileCompVal(tileIdx, cComp, v); - } - precinctPartitionIsUsed = true; - - // Check marker length - checkMarkerLength(ehs, "COD marker"); - - if (mainh) - { - hi.cocValue["main_c" + cComp] = ms; - decSpec.wfs.setCompDef(cComp, hvfilters); - decSpec.dls.setCompDef(cComp, (System.Object)mrl); - decSpec.ecopts.setCompDef(cComp, (System.Object)ecOptions); - } - else - { - hi.cocValue["t" + tileIdx + "_c" + cComp] = ms; - decSpec.wfs.setTileCompVal(tileIdx, cComp, hvfilters); - decSpec.dls.setTileCompVal(tileIdx, cComp, (System.Object)mrl); - decSpec.ecopts.setTileCompVal(tileIdx, cComp, (System.Object)ecOptions); - } - } - - /// Reads the POC marker segment and realigns the codestream where the next - /// marker should be found. - /// - /// - /// The encoder header stream. - /// - /// - /// Flag indicating whether or not this marker segment is read - /// from the main header. - /// - /// - /// The index of the current tile - /// - /// - /// Tile-part index - /// - /// - /// If an I/O error occurs while reading from the - /// encoder header stream - /// - /// - //UPGRADE_TODO: Class 'java.io.DataInputStream' was converted to 'System.IO.BinaryReader' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioDataInputStream'" - private void readPOC(System.IO.BinaryReader ehs, bool mainh, int t, int tpIdx) - { - - bool useShort = (nComp >= 256) ? true : false; - int tmp; - int nOldChg = 0; - HeaderInfo.POC ms; - if (mainh || hi.pocValue["t" + t] == null) - { - ms = hi.NewPOC; - } - else - { - ms = (HeaderInfo.POC)hi.pocValue["t" + t]; - nOldChg = ms.rspoc.Length; - } - - // Lpoc - ms.lpoc = ehs.ReadUInt16(); - - // Compute the number of new progression changes - // newChg = (lpoc - Lpoc(2)) / (RSpoc(1) + CSpoc(2) + - // LYEpoc(2) + REpoc(1) + CEpoc(2) + Ppoc (1) ) - int newChg = (ms.lpoc - 2) / (5 + (useShort ? 4 : 2)); - int ntotChg = nOldChg + newChg; - - int[][] change; - if (nOldChg != 0) - { - // Creates new arrays - int[][] tmpArray = new int[ntotChg][]; - for (int i = 0; i < ntotChg; i++) - { - tmpArray[i] = new int[6]; - } - change = tmpArray; - int[] tmprspoc = new int[ntotChg]; - int[] tmpcspoc = new int[ntotChg]; - int[] tmplyepoc = new int[ntotChg]; - int[] tmprepoc = new int[ntotChg]; - int[] tmpcepoc = new int[ntotChg]; - int[] tmpppoc = new int[ntotChg]; - - // Copy old values - int[][] prevChg = (int[][])decSpec.pcs.getTileDef(t); - for (int chg = 0; chg < nOldChg; chg++) - { - change[chg] = prevChg[chg]; - tmprspoc[chg] = ms.rspoc[chg]; - tmpcspoc[chg] = ms.cspoc[chg]; - tmplyepoc[chg] = ms.lyepoc[chg]; - tmprepoc[chg] = ms.repoc[chg]; - tmpcepoc[chg] = ms.cepoc[chg]; - tmpppoc[chg] = ms.ppoc[chg]; - } - ms.rspoc = tmprspoc; - ms.cspoc = tmpcspoc; - ms.lyepoc = tmplyepoc; - ms.repoc = tmprepoc; - ms.cepoc = tmpcepoc; - ms.ppoc = tmpppoc; - } - else - { - int[][] tmpArray2 = new int[newChg][]; - for (int i2 = 0; i2 < newChg; i2++) - { - tmpArray2[i2] = new int[6]; - } - change = tmpArray2; - ms.rspoc = new int[newChg]; - ms.cspoc = new int[newChg]; - ms.lyepoc = new int[newChg]; - ms.repoc = new int[newChg]; - ms.cepoc = new int[newChg]; - ms.ppoc = new int[newChg]; - } - - for (int chg = nOldChg; chg < ntotChg; chg++) - { - // RSpoc - change[chg][0] = ms.rspoc[chg] = ehs.ReadByte(); - - // CSpoc - if (useShort) - { - change[chg][1] = ms.cspoc[chg] = ehs.ReadUInt16(); - } - else - { - change[chg][1] = ms.cspoc[chg] = ehs.ReadByte(); - } - - // LYEpoc - change[chg][2] = ms.lyepoc[chg] = ehs.ReadUInt16(); - if (change[chg][2] < 1) - { - throw new CorruptedCodestreamException("LYEpoc value must be greater than 1 in POC marker " + "segment of tile " + t + ", tile-part " + tpIdx); - } - - // REpoc - change[chg][3] = ms.repoc[chg] = ehs.ReadByte(); - if (change[chg][3] <= change[chg][0]) - { - throw new CorruptedCodestreamException("REpoc value must be greater than RSpoc in POC marker " + "segment of tile " + t + ", tile-part " + tpIdx); - } - - // CEpoc - if (useShort) - { - change[chg][4] = ms.cepoc[chg] = ehs.ReadUInt16(); - } - else - { - tmp = ms.cepoc[chg] = ehs.ReadByte(); - if (tmp == 0) - { - change[chg][4] = 0; - } - else - { - change[chg][4] = tmp; - } - } - if (change[chg][4] <= change[chg][1]) - { - throw new CorruptedCodestreamException("CEpoc value must be greater than CSpoc in POC marker " + "segment of tile " + t + ", tile-part " + tpIdx); - } - - // Ppoc - change[chg][5] = ms.ppoc[chg] = ehs.ReadByte(); - } - - // Check marker length - checkMarkerLength(ehs, "POC marker"); - - // Register specifications - if (mainh) - { - hi.pocValue["main"] = ms; - decSpec.pcs.setDefault(change); - } - else - { - hi.pocValue["t" + t] = ms; - decSpec.pcs.setTileDef(t, change); - } - } - - /// Reads TLM marker segment and realigns the codestream where the next - /// marker should be found. Informations stored in these fields are - /// currently NOT taken into account. - /// - /// - /// The encoder header stream. - /// - /// - /// If an I/O error occurs while reading from the - /// encoder header stream - /// - /// - //UPGRADE_TODO: Class 'java.io.DataInputStream' was converted to 'System.IO.BinaryReader' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioDataInputStream'" - private void readTLM(System.IO.BinaryReader ehs) - { - int length; - - length = ehs.ReadUInt16(); - //Ignore all informations contained - System.IO.BinaryReader temp_BinaryReader; - System.Int64 temp_Int64; - temp_BinaryReader = ehs; - temp_Int64 = temp_BinaryReader.BaseStream.Position; - temp_Int64 = temp_BinaryReader.BaseStream.Seek(length - 2, System.IO.SeekOrigin.Current) - temp_Int64; - // CONVERSION PROBLEM? - int generatedAux = (int)temp_Int64; - - FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.INFO, "Skipping unsupported TLM marker"); - } - - /// Reads PLM marker segment and realigns the codestream where the next - /// marker should be found. Informations stored in these fields are - /// currently not taken into account. - /// - /// - /// The encoder header stream. - /// - /// - /// If an I/O error occurs while reading from the - /// encoder header stream - /// - /// - //UPGRADE_TODO: Class 'java.io.DataInputStream' was converted to 'System.IO.BinaryReader' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioDataInputStream'" - private void readPLM(System.IO.BinaryReader ehs) - { - int length; - - length = ehs.ReadUInt16(); - //Ignore all informations contained - System.IO.BinaryReader temp_BinaryReader; - System.Int64 temp_Int64; - temp_BinaryReader = ehs; - temp_Int64 = temp_BinaryReader.BaseStream.Position; - temp_Int64 = temp_BinaryReader.BaseStream.Seek(length - 2, System.IO.SeekOrigin.Current) - temp_Int64; - // CONVERSION PROBLEM? - int generatedAux = (int)temp_Int64; - - FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.INFO, "Skipping unsupported PLM marker"); - } - - /// Reads the PLT fields and realigns the codestream where the next marker - /// should be found. Informations stored in these fields are currently NOT - /// taken into account. - /// - /// - /// The encoder header stream. - /// - /// - /// If an I/O error occurs while reading from the - /// encoder header stream - /// - /// - //UPGRADE_TODO: Class 'java.io.DataInputStream' was converted to 'System.IO.BinaryReader' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioDataInputStream'" - private void readPLTFields(System.IO.BinaryReader ehs) - { - int length; - - length = ehs.ReadUInt16(); - //Ignore all informations contained - System.IO.BinaryReader temp_BinaryReader; - System.Int64 temp_Int64; - temp_BinaryReader = ehs; - temp_Int64 = temp_BinaryReader.BaseStream.Position; - temp_Int64 = temp_BinaryReader.BaseStream.Seek(length - 2, System.IO.SeekOrigin.Current) - temp_Int64; - // CONVERSION PROBLEM? - int generatedAux = (int)temp_Int64; - - FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.INFO, "Skipping unsupported PLT marker"); - } - - /// Reads the RGN marker segment of the codestream header. - /// - ///

    May be used in tile or main header. If used in main header, it - /// refers to the maxshift value of a component in all tiles. When used in - /// tile header, only the particular tile-component is affected.

    - /// - ///
    - /// The encoder header stream. - /// - /// - /// Flag indicating whether or not this marker segment is read - /// from the main header. - /// - /// - /// The index of the current tile - /// - /// - /// Tile-part index - /// - /// - /// If an I/O error occurs while reading from the - /// encoder header stream - /// - /// - //UPGRADE_TODO: Class 'java.io.DataInputStream' was converted to 'System.IO.BinaryReader' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioDataInputStream'" - private void readRGN(System.IO.BinaryReader ehs, bool mainh, int tileIdx, int tpIdx) - { - int comp; // ROI component - //int i; // loop variable - //int tempComp; // Component for - HeaderInfo.RGN ms = hi.NewRGN; - - // Lrgn (marker length) - ms.lrgn = ehs.ReadUInt16(); - - // Read component - ms.crgn = comp = (nComp < 257) ? ehs.ReadByte() : ehs.ReadUInt16(); - if (comp >= nComp) - { - throw new CorruptedCodestreamException("Invalid component " + "index in RGN marker" + comp); - } - - // Read type of RGN.(Srgn) - ms.srgn = ehs.ReadByte(); - - // Check that we can handle it. - if (ms.srgn != CSJ2K.j2k.codestream.Markers.SRGN_IMPLICIT) - throw new CorruptedCodestreamException("Unknown or unsupported " + "Srgn parameter in ROI " + "marker"); - - if (decSpec.rois == null) - { - // No maxshift spec defined - // Create needed ModuleSpec - decSpec.rois = new MaxShiftSpec(nTiles, nComp, ModuleSpec.SPEC_TYPE_TILE_COMP); - } - - // SPrgn - ms.sprgn = ehs.ReadByte(); - - if (mainh) - { - hi.rgnValue["main_c" + comp] = ms; - decSpec.rois.setCompDef(comp, (System.Object)ms.sprgn); - } - else - { - hi.rgnValue["t" + tileIdx + "_c" + comp] = ms; - decSpec.rois.setTileCompVal(tileIdx, comp, (System.Object)ms.sprgn); - } - - // Check marker length - checkMarkerLength(ehs, "RGN marker"); - } - - /// Reads the PPM marker segment of the main header. - /// - /// - /// The encoder header stream. - /// - /// - /// If an I/O error occurs while reading from the - /// encoder header stream - /// - /// - //UPGRADE_TODO: Class 'java.io.DataInputStream' was converted to 'System.IO.BinaryReader' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioDataInputStream'" - private void readPPM(System.IO.BinaryReader ehs) - { - int curMarkSegLen; - int indx; // i, len, off removed - int remSegLen; - //byte[] b; - - // If first time readPPM method is called allocate arrays for packed - // packet data - if (pPMMarkerData == null) - { - pPMMarkerData = new byte[nPPMMarkSeg][]; - tileOfTileParts = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); - decSpec.pphs.setDefault((System.Object)true); - } - - // Lppm (marker length) - curMarkSegLen = ehs.ReadUInt16(); - remSegLen = curMarkSegLen - 3; - - // Zppm (index of PPM marker) - indx = ehs.ReadByte(); - - // Read Nppm and Ippm data - pPMMarkerData[indx] = new byte[remSegLen]; - ehs.BaseStream.Read(pPMMarkerData[indx], 0, remSegLen); //SupportClass.ReadInput(ehs.BaseStream, pPMMarkerData[indx], 0, remSegLen); - - // Check marker length - checkMarkerLength(ehs, "PPM marker"); - } - - /// Reads the PPT marker segment of the main header. - /// - /// - /// The encoder header stream. - /// - /// - /// The tile to which the current tile part belongs - /// - /// - /// Tile-part index - /// - /// - /// If an I/O error occurs while reading from the - /// encoder header stream - /// - /// - //UPGRADE_TODO: Class 'java.io.DataInputStream' was converted to 'System.IO.BinaryReader' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioDataInputStream'" - private void readPPT(System.IO.BinaryReader ehs, int tile, int tpIdx) - { - int curMarkSegLen; - int indx; // len = 0; removed - byte[] temp; - - if (tilePartPkdPktHeaders == null) - { - tilePartPkdPktHeaders = new byte[nTiles][][][]; - } - - if (tilePartPkdPktHeaders[tile] == null) - { - tilePartPkdPktHeaders[tile] = new byte[nTileParts[tile]][][]; - } - - if (tilePartPkdPktHeaders[tile][tpIdx] == null) - { - tilePartPkdPktHeaders[tile][tpIdx] = new byte[nPPTMarkSeg[tile][tpIdx]][]; - } - - // Lppt (marker length) - curMarkSegLen = ehs.ReadUInt16(); - - // Zppt (index of PPT marker) - indx = ehs.ReadByte(); - - // Ippt (packed packet headers) - temp = new byte[curMarkSegLen - 3]; - ehs.BaseStream.Read(temp, 0, temp.Length); //SupportClass.ReadInput(ehs.BaseStream, temp, 0, temp.Length); - tilePartPkdPktHeaders[tile][tpIdx][indx] = temp; - - // Check marker length - checkMarkerLength(ehs, "PPT marker"); - - decSpec.pphs.setTileDef(tile, (System.Object)true); - } - - /// This method extract a marker segment from the main header and stores it - /// into a byte buffer for the second pass. The marker segment is first - /// identified. Then its flag is activated. Finally, its content is - /// buffered into a byte array stored in an hashTable. - /// - ///

    If the marker is not recognized, it prints a warning and skips it - /// according to its length.

    - /// - ///

    SIZ marker segment shall be the first encountered marker segment.

    - /// - ///
    - /// The marker segment to process - /// - /// - /// The encoded header stream - /// - /// - private void extractMainMarkSeg(short marker, RandomAccessIO ehs) - { - if (nfMarkSeg == 0) - { - // First non-delimiting marker of the header - // JPEG 2000 part 1 specify that it must be SIZ - if (marker != CSJ2K.j2k.codestream.Markers.SIZ) - { - throw new CorruptedCodestreamException("First marker after " + "SOC " + "must be SIZ " + System.Convert.ToString(marker, 16)); - } - } - - System.String htKey = ""; // Name used as a key for the hash-table - if (ht == null) - { - ht = System.Collections.Hashtable.Synchronized(new System.Collections.Hashtable()); - } - - switch (marker) - { - - case CSJ2K.j2k.codestream.Markers.SIZ: - if ((nfMarkSeg & SIZ_FOUND) != 0) - { - throw new CorruptedCodestreamException("More than one SIZ marker " + "segment found in main " + "header"); - } - nfMarkSeg |= SIZ_FOUND; - htKey = "SIZ"; - break; - - case CSJ2K.j2k.codestream.Markers.SOD: - throw new CorruptedCodestreamException("SOD found in main header"); - - case CSJ2K.j2k.codestream.Markers.EOC: - throw new CorruptedCodestreamException("EOC found in main header"); - - case CSJ2K.j2k.codestream.Markers.SOT: - if ((nfMarkSeg & SOT_FOUND) != 0) - { - throw new CorruptedCodestreamException("More than one SOT " + "marker " + "found right after " + "main " + "or tile header"); - } - nfMarkSeg |= SOT_FOUND; - return; - - case CSJ2K.j2k.codestream.Markers.COD: - if ((nfMarkSeg & COD_FOUND) != 0) - { - throw new CorruptedCodestreamException("More than one COD " + "marker " + "found in main header"); - } - nfMarkSeg |= COD_FOUND; - htKey = "COD"; - break; - - case CSJ2K.j2k.codestream.Markers.COC: - nfMarkSeg |= COC_FOUND; - htKey = "COC" + (nCOCMarkSeg++); - break; - - case CSJ2K.j2k.codestream.Markers.QCD: - if ((nfMarkSeg & QCD_FOUND) != 0) - { - throw new CorruptedCodestreamException("More than one QCD " + "marker " + "found in main header"); - } - nfMarkSeg |= QCD_FOUND; - htKey = "QCD"; - break; - - case CSJ2K.j2k.codestream.Markers.QCC: - nfMarkSeg |= QCC_FOUND; - htKey = "QCC" + (nQCCMarkSeg++); - break; - - case CSJ2K.j2k.codestream.Markers.RGN: - nfMarkSeg |= RGN_FOUND; - htKey = "RGN" + (nRGNMarkSeg++); - break; - - case CSJ2K.j2k.codestream.Markers.COM: - nfMarkSeg |= COM_FOUND; - htKey = "COM" + (nCOMMarkSeg++); - break; - - case CSJ2K.j2k.codestream.Markers.CRG: - if ((nfMarkSeg & CRG_FOUND) != 0) - { - throw new CorruptedCodestreamException("More than one CRG " + "marker " + "found in main header"); - } - nfMarkSeg |= CRG_FOUND; - htKey = "CRG"; - break; - - case CSJ2K.j2k.codestream.Markers.PPM: - nfMarkSeg |= PPM_FOUND; - htKey = "PPM" + (nPPMMarkSeg++); - break; - - case CSJ2K.j2k.codestream.Markers.TLM: - if ((nfMarkSeg & TLM_FOUND) != 0) - { - throw new CorruptedCodestreamException("More than one TLM " + "marker " + "found in main header"); - } - nfMarkSeg |= TLM_FOUND; - break; - - case CSJ2K.j2k.codestream.Markers.PLM: - if ((nfMarkSeg & PLM_FOUND) != 0) - { - throw new CorruptedCodestreamException("More than one PLM " + "marker " + "found in main header"); - } - FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.WARNING, "PLM marker segment found but " + "not used by by JJ2000 decoder."); - nfMarkSeg |= PLM_FOUND; - htKey = "PLM"; - break; - - case CSJ2K.j2k.codestream.Markers.POC: - if ((nfMarkSeg & POC_FOUND) != 0) - { - throw new CorruptedCodestreamException("More than one POC " + "marker segment found " + "in main header"); - } - nfMarkSeg |= POC_FOUND; - htKey = "POC"; - break; - - case CSJ2K.j2k.codestream.Markers.PLT: - throw new CorruptedCodestreamException("PLT found in main header"); - - case CSJ2K.j2k.codestream.Markers.PPT: - throw new CorruptedCodestreamException("PPT found in main header"); - - default: - htKey = "UNKNOWN"; - FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.WARNING, "Non recognized marker segment (0x" + System.Convert.ToString(marker, 16) + ") in main header!"); - break; - - } - - if (marker < unchecked((short)0xffffff30) || marker > unchecked((short)0xffffff3f)) - { - // Read marker segment length and create corresponding byte buffer - int markSegLen = ehs.readUnsignedShort(); - byte[] buf = new byte[markSegLen]; - - // Copy data (after re-insertion of the marker segment length); - buf[0] = (byte)((markSegLen >> 8) & 0xFF); - buf[1] = (byte)(markSegLen & 0xFF); - ehs.readFully(buf, 2, markSegLen - 2); - - if (!htKey.Equals("UNKNOWN")) - { - // Store array in hashTable - ht[htKey] = buf; - } - } - } - - /// This method extracts a marker segment in a tile-part header and stores - /// it into a byte buffer for the second pass. The marker is first - /// recognized, then its flag is activated and, finally, its content is - /// buffered in an element of byte arrays accessible thanks to a hashTable. - /// If a marker segment is not recognized, it prints a warning and skip it - /// according to its length. - /// - /// - /// The marker to process - /// - /// - /// The encoded header stream - /// - /// - /// The index of the current tile - /// - /// - /// The index of the current tile part - /// - /// - public virtual void extractTilePartMarkSeg(short marker, RandomAccessIO ehs, int tileIdx, int tilePartIdx) - { - - System.String htKey = ""; // Name used as a hash-table key - if (ht == null) - { - ht = System.Collections.Hashtable.Synchronized(new System.Collections.Hashtable()); - } - - switch (marker) - { - - case CSJ2K.j2k.codestream.Markers.SOT: - throw new CorruptedCodestreamException("Second SOT marker " + "segment found in tile-" + "part header"); - - case CSJ2K.j2k.codestream.Markers.SIZ: - throw new CorruptedCodestreamException("SIZ found in tile-part" + " header"); - - case CSJ2K.j2k.codestream.Markers.EOC: - throw new CorruptedCodestreamException("EOC found in tile-part" + " header"); - - case CSJ2K.j2k.codestream.Markers.TLM: - throw new CorruptedCodestreamException("TLM found in tile-part" + " header"); - - case CSJ2K.j2k.codestream.Markers.PLM: - throw new CorruptedCodestreamException("PLM found in tile-part" + " header"); - - case CSJ2K.j2k.codestream.Markers.PPM: - throw new CorruptedCodestreamException("PPM found in tile-part" + " header"); - - case CSJ2K.j2k.codestream.Markers.COD: - if ((nfMarkSeg & COD_FOUND) != 0) - { - throw new CorruptedCodestreamException("More than one COD " + "marker " + "found in tile-part" + " header"); - } - nfMarkSeg |= COD_FOUND; - htKey = "COD"; - break; - - case CSJ2K.j2k.codestream.Markers.COC: - nfMarkSeg |= COC_FOUND; - htKey = "COC" + (nCOCMarkSeg++); - break; - - case CSJ2K.j2k.codestream.Markers.QCD: - if ((nfMarkSeg & QCD_FOUND) != 0) - { - throw new CorruptedCodestreamException("More than one QCD " + "marker " + "found in tile-part" + " header"); - } - nfMarkSeg |= QCD_FOUND; - htKey = "QCD"; - break; - - case CSJ2K.j2k.codestream.Markers.QCC: - nfMarkSeg |= QCC_FOUND; - htKey = "QCC" + (nQCCMarkSeg++); - break; - - case CSJ2K.j2k.codestream.Markers.RGN: - nfMarkSeg |= RGN_FOUND; - htKey = "RGN" + (nRGNMarkSeg++); - break; - - case CSJ2K.j2k.codestream.Markers.COM: - nfMarkSeg |= COM_FOUND; - htKey = "COM" + (nCOMMarkSeg++); - break; - - case CSJ2K.j2k.codestream.Markers.CRG: - throw new CorruptedCodestreamException("CRG marker found in " + "tile-part header"); - - case CSJ2K.j2k.codestream.Markers.PPT: - nfMarkSeg |= PPT_FOUND; - if (nPPTMarkSeg == null) - { - nPPTMarkSeg = new int[nTiles][]; - } - if (nPPTMarkSeg[tileIdx] == null) - { - nPPTMarkSeg[tileIdx] = new int[nTileParts[tileIdx]]; - } - htKey = "PPT" + (nPPTMarkSeg[tileIdx][tilePartIdx]++); - break; - - case CSJ2K.j2k.codestream.Markers.SOD: - nfMarkSeg |= SOD_FOUND; - return; - - case CSJ2K.j2k.codestream.Markers.POC: - if ((nfMarkSeg & POC_FOUND) != 0) - throw new CorruptedCodestreamException("More than one POC " + "marker segment found " + "in tile-part" + " header"); - nfMarkSeg |= POC_FOUND; - htKey = "POC"; - break; - - case CSJ2K.j2k.codestream.Markers.PLT: - if ((nfMarkSeg & PLM_FOUND) != 0) - { - throw new CorruptedCodestreamException("PLT marker found even" + "though PLM marker " + "found in main header"); - } - FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.WARNING, "PLT marker segment found but " + "not used by JJ2000 decoder."); - htKey = "UNKNOWN"; - break; - - default: - htKey = "UNKNOWN"; - FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.WARNING, "Non recognized marker segment (0x" + System.Convert.ToString(marker, 16) + ") in tile-part header" + " of tile " + tileIdx + " !"); - break; - - } - - // Read marker segment length and create corresponding byte buffer - int markSegLen = ehs.readUnsignedShort(); - byte[] buf = new byte[markSegLen]; - - // Copy data (after re-insertion of marker segment length); - buf[0] = (byte)((markSegLen >> 8) & 0xFF); - buf[1] = (byte)(markSegLen & 0xFF); - ehs.readFully(buf, 2, markSegLen - 2); - - if (!htKey.Equals("UNKNOWN")) - { - // Store array in hashTable - ht[htKey] = buf; - } - } - - /// Retrieves and reads all marker segments found in the main header during - /// the first pass. - /// - /// - private void readFoundMainMarkSeg() - { - //UPGRADE_TODO: Class 'java.io.DataInputStream' was converted to 'System.IO.BinaryReader' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioDataInputStream'" - //System.IO.BinaryReader dis; - System.IO.MemoryStream bais; - - // SIZ marker segment - if ((nfMarkSeg & SIZ_FOUND) != 0) - { - bais = new System.IO.MemoryStream((byte[])ht["SIZ"]); - readSIZ(new CSJ2K.Util.EndianBinaryReader(bais, true)); - bais.Dispose(); - } - - // COM marker segments - if ((nfMarkSeg & COM_FOUND) != 0) - { - for (int i = 0; i < nCOMMarkSeg; i++) - { - bais = new System.IO.MemoryStream((byte[])ht["COM" + i]); - readCOM(new CSJ2K.Util.EndianBinaryReader(bais, true), true, 0, i); - bais.Dispose(); - } - } - - // CRG marker segment - if ((nfMarkSeg & CRG_FOUND) != 0) - { - bais = new System.IO.MemoryStream((byte[])ht["CRG"]); - readCRG(new CSJ2K.Util.EndianBinaryReader(bais, true)); - bais.Dispose(); - } - - // COD marker segment - if ((nfMarkSeg & COD_FOUND) != 0) - { - bais = new System.IO.MemoryStream((byte[])ht["COD"]); - readCOD(new CSJ2K.Util.EndianBinaryReader(bais, true), true, 0, 0); - bais.Dispose(); - } - - // COC marker segments - if ((nfMarkSeg & COC_FOUND) != 0) - { - for (int i = 0; i < nCOCMarkSeg; i++) - { - bais = new System.IO.MemoryStream((byte[])ht["COC" + i]); - readCOC(new CSJ2K.Util.EndianBinaryReader(bais, true), true, 0, 0); - bais.Dispose(); - } - } - - // RGN marker segment - if ((nfMarkSeg & RGN_FOUND) != 0) - { - for (int i = 0; i < nRGNMarkSeg; i++) - { - bais = new System.IO.MemoryStream((byte[])ht["RGN" + i]); - readRGN(new CSJ2K.Util.EndianBinaryReader(bais, true), true, 0, 0); - bais.Dispose(); - } - } - - // QCD marker segment - if ((nfMarkSeg & QCD_FOUND) != 0) - { - bais = new System.IO.MemoryStream((byte[])ht["QCD"]); - readQCD(new CSJ2K.Util.EndianBinaryReader(bais, true), true, 0, 0); - bais.Dispose(); - } - - // QCC marker segments - if ((nfMarkSeg & QCC_FOUND) != 0) - { - for (int i = 0; i < nQCCMarkSeg; i++) - { - bais = new System.IO.MemoryStream((byte[])ht["QCC" + i]); - readQCC(new CSJ2K.Util.EndianBinaryReader(bais, true), true, 0, 0); - bais.Dispose(); - } - } - - // POC marker segment - if ((nfMarkSeg & POC_FOUND) != 0) - { - bais = new System.IO.MemoryStream((byte[])ht["POC"]); - readPOC(new CSJ2K.Util.EndianBinaryReader(bais, true), true, 0, 0); - bais.Dispose(); - } - - // PPM marker segments - if ((nfMarkSeg & PPM_FOUND) != 0) - { - for (int i = 0; i < nPPMMarkSeg; i++) - { - bais = new System.IO.MemoryStream((byte[])ht["PPM" + i]); - readPPM(new CSJ2K.Util.EndianBinaryReader(bais)); - bais.Dispose(); - } - } - - // Reset the hashtable - ht = null; - } - - /// Retrieves and reads all marker segments previously found in the - /// tile-part header. - /// - /// - /// The index of the current tile - /// - /// - /// Index of the current tile-part - /// - /// - public virtual void readFoundTilePartMarkSeg(int tileIdx, int tpIdx) - { - - //UPGRADE_TODO: Class 'java.io.DataInputStream' was converted to 'System.IO.BinaryReader' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioDataInputStream'" - //CSJ2K.EndianBinaryReader dis; - System.IO.MemoryStream bais; - - // COD marker segment - if ((nfMarkSeg & COD_FOUND) != 0) - { - bais = new System.IO.MemoryStream((byte[])ht["COD"]); - readCOD(new CSJ2K.Util.EndianBinaryReader(bais, true), false, tileIdx, tpIdx); - } - - // COC marker segments - if ((nfMarkSeg & COC_FOUND) != 0) - { - for (int i = 0; i < nCOCMarkSeg; i++) - { - bais = new System.IO.MemoryStream((byte[])ht["COC" + i]); - readCOC(new CSJ2K.Util.EndianBinaryReader(bais, true), false, tileIdx, tpIdx); - } - } - - // RGN marker segment - if ((nfMarkSeg & RGN_FOUND) != 0) - { - for (int i = 0; i < nRGNMarkSeg; i++) - { - bais = new System.IO.MemoryStream((byte[])ht["RGN" + i]); - readRGN(new CSJ2K.Util.EndianBinaryReader(bais, true), false, tileIdx, tpIdx); - } - } - - // QCD marker segment - if ((nfMarkSeg & QCD_FOUND) != 0) - { - bais = new System.IO.MemoryStream((byte[])ht["QCD"]); - readQCD(new CSJ2K.Util.EndianBinaryReader(bais, true), false, tileIdx, tpIdx); - } - - // QCC marker segments - if ((nfMarkSeg & QCC_FOUND) != 0) - { - for (int i = 0; i < nQCCMarkSeg; i++) - { - bais = new System.IO.MemoryStream((byte[])ht["QCC" + i]); - readQCC(new CSJ2K.Util.EndianBinaryReader(bais, true), false, tileIdx, tpIdx); - } - } - - // POC marker segment - if ((nfMarkSeg & POC_FOUND) != 0) - { - bais = new System.IO.MemoryStream((byte[])ht["POC"]); - readPOC(new CSJ2K.Util.EndianBinaryReader(bais, true), false, tileIdx, tpIdx); - } - - // COM marker segments - if ((nfMarkSeg & COM_FOUND) != 0) - { - for (int i = 0; i < nCOMMarkSeg; i++) - { - bais = new System.IO.MemoryStream((byte[])ht["COM" + i]); - readCOM(new CSJ2K.Util.EndianBinaryReader(bais, true), false, tileIdx, i); - } - } - - // PPT marker segments - if ((nfMarkSeg & PPT_FOUND) != 0) - { - for (int i = 0; i < nPPTMarkSeg[tileIdx][tpIdx]; i++) - { - bais = new System.IO.MemoryStream((byte[])ht["PPT" + i]); - readPPT(new CSJ2K.Util.EndianBinaryReader(bais, true), tileIdx, tpIdx); - } - } - - // Reset ht - ht = null; - } - - /// Creates a HeaderDecoder instance and read in two passes the main header - /// of the codestream. The first and last marker segments shall be - /// respectively SOC and SOT. - /// - /// - /// The encoded header stream where marker segments are - /// extracted. - /// - /// - /// The ParameterList object of the decoder - /// - /// - /// The HeaderInfo holding information found in marker segments - /// - /// - /// If an I/O error occurs while reading from the - /// encoded header stream. - /// - /// If the end of the encoded header stream is - /// reached before getting all the data. - /// - /// If invalid data is found in the - /// codestream main header. - /// - /// - public HeaderDecoder(RandomAccessIO ehs, ParameterList pl, HeaderInfo hi) - { - - this.hi = hi; - // CONVERSION PROBLEM? - //this.verbose = verbose; - - pl.checkList(OPT_PREFIX, ParameterList.toNameArray(pinfo)); - - mainHeadOff = ehs.Pos; - if (((short)ehs.readShort()) != CSJ2K.j2k.codestream.Markers.SOC) - { - throw new CorruptedCodestreamException("SOC marker segment not " + " found at the " + "beginning of the " + "codestream."); - } - - // First Pass: Decode and store main header information until the SOT - // marker segment is found - nfMarkSeg = 0; - do - { - extractMainMarkSeg(ehs.readShort(), ehs); - } - while ((nfMarkSeg & SOT_FOUND) == 0); //Stop when SOT is found - ehs.seek(ehs.Pos - 2); // Realign codestream on SOT marker - - // Second pass: Read each marker segment previously found - readFoundMainMarkSeg(); - } - - /// Creates and returns the entropy decoder corresponding to the - /// information read from the codestream header and with the special - /// additional parameters from the parameter list. - /// - /// - /// The bit stream reader agent where to get code-block data - /// from. - /// - /// - /// The parameter list containing parameters applicable to the - /// entropy decoder (other parameters can also be present). - /// - /// - /// The entropy decoder - /// - /// - public virtual EntropyDecoder createEntropyDecoder(CodedCBlkDataSrcDec src, ParameterList pl) - { - bool doer; - bool verber; - int mMax; - - // Check parameters - pl.checkList(EntropyDecoder.OPT_PREFIX, ParameterList.toNameArray(EntropyDecoder.ParameterInfo)); - // Get error detection option - doer = pl.getBooleanParameter("Cer"); - // Get verbose error detection option - verber = pl.getBooleanParameter("Cverber"); - - // Get maximum number of bit planes from m quit condition - mMax = pl.getIntParameter("m_quit"); - return new StdEntropyDecoder(src, decSpec, doer, verber, mMax); - } - - /// Creates and returns the EnumeratedColorSpaceMapper - /// corresponding to the information read from the JP2 image file - /// via the ColorSpace parameter. - /// - /// - /// The bit stream reader agent where to get code-block - /// data from. - /// - /// provides color space information from the image file - /// - /// - /// The color space mapping object - /// - /// image access exception - /// - /// if image contains a bad icc profile - /// - /// if image contains a bad colorspace box - /// - /// - public virtual BlkImgDataSrc createColorSpaceMapper(BlkImgDataSrc src, CSJ2K.Color.ColorSpace csMap) - { - return ColorSpaceMapper.createInstance(src, csMap); - } - - /// Creates and returns the ChannelDefinitonMapper which maps the - /// input channels to the channel definition for the appropriate - /// colorspace. - /// - /// - /// The bit stream reader agent where to get code-block - /// data from. - /// - /// provides color space information from the image file - /// - /// - /// The channel definition mapping object - /// - /// image access exception - /// - /// if image contains a bad colorspace box - /// - /// - public virtual BlkImgDataSrc createChannelDefinitionMapper(BlkImgDataSrc src, CSJ2K.Color.ColorSpace csMap) - { - return ChannelDefinitionMapper.createInstance(src, csMap); - } - - /// Creates and returns the PalettizedColorSpaceMapper which uses - /// the input samples as indicies into a sample palette to - /// construct the output. - /// - /// - /// The bit stream reader agent where to get code-block - /// data from. - /// - /// provides color space information from the image file - /// - /// - /// a PalettizedColorSpaceMapper instance - /// - /// image access exception - /// - /// if image contains a bad colorspace box - /// - /// - public virtual BlkImgDataSrc createPalettizedColorSpaceMapper(BlkImgDataSrc src, CSJ2K.Color.ColorSpace csMap) - { - return PalettizedColorSpaceMapper.createInstance(src, csMap); - } - - /// Creates and returns the Resampler which converts the input - /// source to one in which all channels have the same number of - /// samples. This is required for colorspace conversions. - /// - /// - /// The bit stream reader agent where to get code-block - /// data from. - /// - /// provides color space information from the image file - /// - /// - /// The resampled BlkImgDataSrc - /// - /// image access exception - /// - /// if image contains a bad colorspace box - /// - /// - public virtual BlkImgDataSrc createResampler(BlkImgDataSrc src, CSJ2K.Color.ColorSpace csMap) - { - return Resampler.createInstance(src, csMap); - } - - /// Creates and returns the ROIDeScaler corresponding to the information - /// read from the codestream header and with the special additional - /// parameters from the parameter list. - /// - /// - /// The bit stream reader agent where to get code-block data - /// from. - /// - /// - /// The parameter list containing parameters applicable to the - /// entropy decoder (other parameters can also be present). - /// - /// - /// The DecoderSpecs instance after any image manipulation. - /// - /// - /// The ROI descaler. - /// - /// - public virtual ROIDeScaler createROIDeScaler(CBlkQuantDataSrcDec src, ParameterList pl, DecoderSpecs decSpec2) - { - return ROIDeScaler.createInstance(src, pl, decSpec2); - } - - /// Method that resets members indicating which markers have already been - /// found - /// - /// - public virtual void resetHeaderMarkers() - { - // The found status of PLM remains since only PLM OR PLT allowed - // Same goes for PPM and PPT - nfMarkSeg = nfMarkSeg & (PLM_FOUND | PPM_FOUND); - nCOCMarkSeg = 0; - nQCCMarkSeg = 0; - nCOMMarkSeg = 0; - nRGNMarkSeg = 0; - } - - /// Print information about the current header. - /// - /// - /// Information in a String - /// - /// - public override System.String ToString() - { - return hdStr; - } - - /// Return the packed packet headers for a given tile. - /// - /// - /// An input stream containing the packed packet headers for a - /// particular tile - /// - /// - /// If an I/O error occurs while reading from the - /// encoder header stream - /// - /// - public virtual System.IO.MemoryStream getPackedPktHead(int tile) - { - - if (pkdPktHeaders == null) - { - int i, t; - pkdPktHeaders = new System.IO.MemoryStream[nTiles]; - for (i = nTiles - 1; i >= 0; i--) - { - pkdPktHeaders[i] = new System.IO.MemoryStream(); - } - if (nPPMMarkSeg != 0) - { - // If this is first time packed packet headers are requested, - // create packed packet headers from Nppm and Ippm fields - int nppm; - int nTileParts = tileOfTileParts.Count; - byte[] temp; - System.IO.MemoryStream pph; - System.IO.MemoryStream allNppmIppm = new System.IO.MemoryStream(); - - // Concatenate all Nppm and Ippm fields - for (i = 0; i < nPPMMarkSeg; i++) - { - byte[] temp_byteArray; - temp_byteArray = pPMMarkerData[i]; - allNppmIppm.Write(temp_byteArray, 0, temp_byteArray.Length); - } - pph = new System.IO.MemoryStream(allNppmIppm.ToArray()); - - // Read all packed packet headers and concatenate for each - // tile part - for (i = 0; i < nTileParts; i++) - { - t = ((System.Int32)tileOfTileParts[i]); - // get Nppm value - nppm = (pph.ReadByte() << 24) | (pph.ReadByte() << 16) | (pph.ReadByte() << 8) | (pph.ReadByte()); - - temp = new byte[nppm]; - // get ippm field - pph.Read(temp, 0, temp.Length); //SupportClass.ReadInput(pph, temp, 0, temp.Length); - byte[] temp_byteArray2; - temp_byteArray2 = temp; - pkdPktHeaders[t].Write(temp_byteArray2, 0, temp_byteArray2.Length); - } - } - else - { - int tp; - // Write all packed packet headers to pkdPktHeaders - for (t = nTiles - 1; t >= 0; t--) - { - for (tp = 0; tp < nTileParts[t]; tp++) - { - for (i = 0; i < nPPTMarkSeg[t][tp]; i++) - { - byte[] temp_byteArray3; - temp_byteArray3 = tilePartPkdPktHeaders[t][tp][i]; - pkdPktHeaders[t].Write(temp_byteArray3, 0, temp_byteArray3.Length); - } - } - } - } - } - - return new System.IO.MemoryStream(pkdPktHeaders[tile].ToArray()); - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/codestream/reader/PktDecoder.cs b/CSJ2K/j2k/codestream/reader/PktDecoder.cs deleted file mode 100644 index aab6bd6a..00000000 --- a/CSJ2K/j2k/codestream/reader/PktDecoder.cs +++ /dev/null @@ -1,1679 +0,0 @@ -using CSJ2K.j2k.decoder; -using CSJ2K.j2k.image; -using CSJ2K.j2k.io; -using CSJ2K.j2k.util; -/// CVS identifier: -/// -/// $Id: PktDecoder.java,v 1.46 2002/07/19 12:35:14 grosbois Exp $ -/// -/// Class: PktDecoder -/// -/// Description: Reads packets heads and keeps location of -/// code-blocks' codewords -/// -/// -/// -/// COPYRIGHT: -/// -/// This software module was originally developed by Raphaël Grosbois and -/// Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -/// Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -/// Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -/// Centre France S.A) in the course of development of the JPEG2000 -/// standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -/// software module is an implementation of a part of the JPEG 2000 -/// Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -/// Systems AB and Canon Research Centre France S.A (collectively JJ2000 -/// Partners) agree not to assert against ISO/IEC and users of the JPEG -/// 2000 Standard (Users) any of their rights under the copyright, not -/// including other intellectual property rights, for this software module -/// with respect to the usage by ISO/IEC and Users of this software module -/// or modifications thereof for use in hardware or software products -/// claiming conformance to the JPEG 2000 Standard. Those intending to use -/// this software module in hardware or software products are advised that -/// their use may infringe existing patents. The original developers of -/// this software module, JJ2000 Partners and ISO/IEC assume no liability -/// for use of this software module or modifications thereof. No license -/// or right to this software module is granted for non JPEG 2000 Standard -/// conforming products. JJ2000 Partners have full right to use this -/// software module for his/her own purpose, assign or donate this -/// software module to any third party and to inhibit third parties from -/// using this software module for non JPEG 2000 Standard conforming -/// products. This copyright notice must be included in all copies or -/// derivative works of this software module. -/// -/// Copyright (c) 1999/2000 JJ2000 Partners. -/// -/// -using CSJ2K.j2k.wavelet.synthesis; -namespace CSJ2K.j2k.codestream.reader -{ - - /// This class is used to read packet's head and body. All the members must be - /// re-initialized at the beginning of each tile thanks to the restart() - /// method. - /// - /// - public class PktDecoder - { - - /// Reference to the codestream reader agent - private BitstreamReaderAgent src; - - /// Flag indicating whether packed packet header was used for this tile - private bool pph = false; - - /// The packed packet header if it was used - private System.IO.MemoryStream pphbais; - - /// Reference to decoder specifications - private DecoderSpecs decSpec; - - /// Reference to the HeaderDecoder - private HeaderDecoder hd; - - /// Initial value of the state variable associated with code-block - /// length. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'INIT_LBLOCK '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private int INIT_LBLOCK = 3; - - /// The wrapper to read bits for the packet heads - private PktHeaderBitReader bin; - - /// Reference to the stream where to read from - private RandomAccessIO ehs; - - /// Maximum number of precincts : - /// - ///
      - ///
    • 1st dim: component index.
    • - ///
    • 2nd dim: resolution level index.
    • - ///
    - /// - ///
    - private Coord[][] numPrec; - - /// Index of the current tile - private int tIdx; - - /// Array containing the coordinates, width, height, indexes, ... of the - /// precincts in the current tile: - /// - ///
      - ///
    • 1st dim: component index.
    • - ///
    • 2nd dim: resolution level index.
    • - ///
    • 3rd dim: precinct index.
    • - ///
    - /// - ///
    - private PrecInfo[][][] ppinfo; - - /// Lblock value used to read code size information in each packet head: - /// - ///
      - ///
    • 1st dim: component index.
    • - ///
    • 2nd dim: resolution level index.
    • - ///
    • 3rd dim: subband index.
    • - ///
    • 4th/5th dim: code-block index (vert. and horiz.).
    • - ///
    - /// - ///
    - private int[][][][][] lblock; - - /// Tag tree used to read inclusion informations in packet's head: - /// - ///
      - ///
    • 1st dim: component index.
    • - ///
    • 2nd dim: resolution level index.
    • - ///
    • 3rd dim: precinct index.
    • - ///
    • 4th dim: subband index.
    • - /// - ///
    - private TagTreeDecoder[][][][] ttIncl; - - /// Tag tree used to read bit-depth information in packet's head: - /// - ///
      - ///
    • 1st dim: component index.
    • - ///
    • 2nd dim: resolution level index.
    • - ///
    • 3rd dim: precinct index.
    • - ///
    • 4th dim: subband index.
    • - ///
    - /// - ///
    - private TagTreeDecoder[][][][] ttMaxBP; - - /// Number of layers in t he current tile - private int nl = 0; - - /// The number of components - private int nc; - - /// Whether or not SOP marker segment are used - private bool sopUsed = false; - - /// Whether or not EPH marker are used - private bool ephUsed = false; - - /// Index of the current packet in the tile. Used with SOP marker segment - /// - /// - private int pktIdx; - - /// List of code-blocks found in last read packet head (one list - /// per subband) - /// - private System.Collections.ArrayList[] cblks; - - /// Number of codeblocks encountered. used for ncb quit condition - private int ncb; - - /// Maximum number of codeblocks to read before ncb quit condition is - /// reached - /// - private int maxCB; - - /// Flag indicating whether ncb quit condition has been reached - private bool ncbQuit; - - /// The tile in which the ncb quit condition was reached - private int tQuit; - - /// The component in which the ncb quit condition was reached - private int cQuit; - - /// The subband in which the ncb quit condition was reached - private int sQuit; - - /// The resolution in which the ncb quit condition was reached - private int rQuit; - - /// The x position of the last code block before ncb quit reached - private int xQuit; - - /// The y position of the last code block before ncb quit reached - private int yQuit; - - /// True if truncation mode is used. False if it is parsing mode - private bool isTruncMode; - - /// Creates an empty PktDecoder object associated with given decoder - /// specifications and HeaderDecoder. This object must be initialized - /// thanks to the restart method before being used. - /// - /// - /// The decoder specifications. - /// - /// - /// The HeaderDecoder instance. - /// - /// - /// The stream where to read data from. - /// - /// - /// The bit stream reader agent. - /// - /// - /// Whether or not truncation mode is required. - /// - /// - /// The maximum number of code-blocks to read before ncbquit - /// - /// - /// - public PktDecoder(DecoderSpecs decSpec, HeaderDecoder hd, RandomAccessIO ehs, BitstreamReaderAgent src, bool isTruncMode, int maxCB) - { - this.decSpec = decSpec; - this.hd = hd; - this.ehs = ehs; - this.isTruncMode = isTruncMode; - bin = new PktHeaderBitReader(ehs); - this.src = src; - ncb = 0; - ncbQuit = false; - this.maxCB = maxCB; - } - - - /// Re-initialize the PktDecoder instance at the beginning of a new tile. - /// - /// - /// The number of components in this tile - /// - /// - /// The maximum number of decomposition level in each component - /// of this tile - /// - /// - /// The number of layers in this tile - /// - /// - /// The code-blocks array - /// - /// - /// Flag indicating whether packed packet headers was used - /// - /// - /// Stream containing the packed packet headers - /// - /// - public virtual CBlkInfo[][][][][] restart(int nc, int[] mdl, int nl, CBlkInfo[][][][][] cbI, bool pph, System.IO.MemoryStream pphbais) - { - this.nc = nc; - this.nl = nl; - this.tIdx = src.TileIdx; - this.pph = pph; - this.pphbais = pphbais; - - sopUsed = ((System.Boolean)decSpec.sops.getTileDef(tIdx)); - pktIdx = 0; - ephUsed = ((System.Boolean)decSpec.ephs.getTileDef(tIdx)); - - cbI = new CBlkInfo[nc][][][][]; - lblock = new int[nc][][][][]; - ttIncl = new TagTreeDecoder[nc][][][]; - ttMaxBP = new TagTreeDecoder[nc][][][]; - numPrec = new Coord[nc][]; - ppinfo = new PrecInfo[nc][][]; - - // Used to compute the maximum number of precincts for each resolution - // level - int tcx0, tcy0, tcx1, tcy1; // Current tile position in the domain of - // the image component - int trx0, try0, trx1, try1; // Current tile position in the reduced - // resolution image domain - //int xrsiz, yrsiz; // Component sub-sampling factors - - SubbandSyn root, sb; - int mins, maxs; - Coord nBlk = null; - int cb0x = src.CbULX; - int cb0y = src.CbULY; - - for (int c = 0; c < nc; c++) - { - cbI[c] = new CBlkInfo[mdl[c] + 1][][][]; - lblock[c] = new int[mdl[c] + 1][][][]; - ttIncl[c] = new TagTreeDecoder[mdl[c] + 1][][]; - ttMaxBP[c] = new TagTreeDecoder[mdl[c] + 1][][]; - numPrec[c] = new Coord[mdl[c] + 1]; - ppinfo[c] = new PrecInfo[mdl[c] + 1][]; - - // Get the tile-component coordinates on the reference grid - tcx0 = src.getResULX(c, mdl[c]); - tcy0 = src.getResULY(c, mdl[c]); - tcx1 = tcx0 + src.getTileCompWidth(tIdx, c, mdl[c]); - tcy1 = tcy0 + src.getTileCompHeight(tIdx, c, mdl[c]); - - for (int r = 0; r <= mdl[c]; r++) - { - - // Tile's coordinates in the reduced resolution image domain - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - trx0 = (int)System.Math.Ceiling(tcx0 / (double)(1 << (mdl[c] - r))); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - try0 = (int)System.Math.Ceiling(tcy0 / (double)(1 << (mdl[c] - r))); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - trx1 = (int)System.Math.Ceiling(tcx1 / (double)(1 << (mdl[c] - r))); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - try1 = (int)System.Math.Ceiling(tcy1 / (double)(1 << (mdl[c] - r))); - - // Calculate the maximum number of precincts for each - // resolution level taking into account tile specific options. - double twoppx = (double)getPPX(tIdx, c, r); - double twoppy = (double)getPPY(tIdx, c, r); - numPrec[c][r] = new Coord(); - if (trx1 > trx0) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - numPrec[c][r].x = (int)System.Math.Ceiling((trx1 - cb0x) / twoppx) - (int)System.Math.Floor((trx0 - cb0x) / twoppx); - } - else - { - numPrec[c][r].x = 0; - } - if (try1 > try0) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - numPrec[c][r].y = (int)System.Math.Ceiling((try1 - cb0y) / twoppy) - (int)System.Math.Floor((try0 - cb0y) / twoppy); - } - else - { - numPrec[c][r].y = 0; - } - - // First and last subbands indexes - mins = (r == 0) ? 0 : 1; - maxs = (r == 0) ? 1 : 4; - - int maxPrec = numPrec[c][r].x * numPrec[c][r].y; - - ttIncl[c][r] = new TagTreeDecoder[maxPrec][]; - for (int i = 0; i < maxPrec; i++) - { - ttIncl[c][r][i] = new TagTreeDecoder[maxs + 1]; - } - ttMaxBP[c][r] = new TagTreeDecoder[maxPrec][]; - for (int i2 = 0; i2 < maxPrec; i2++) - { - ttMaxBP[c][r][i2] = new TagTreeDecoder[maxs + 1]; - } - cbI[c][r] = new CBlkInfo[maxs + 1][][]; - lblock[c][r] = new int[maxs + 1][][]; - - ppinfo[c][r] = new PrecInfo[maxPrec]; - fillPrecInfo(c, r, mdl[c]); - - root = (SubbandSyn)src.getSynSubbandTree(tIdx, c); - for (int s = mins; s < maxs; s++) - { - sb = (SubbandSyn)root.getSubbandByIdx(r, s); - nBlk = sb.numCb; - - cbI[c][r][s] = new CBlkInfo[nBlk.y][]; - for (int i3 = 0; i3 < nBlk.y; i3++) - { - cbI[c][r][s][i3] = new CBlkInfo[nBlk.x]; - } - lblock[c][r][s] = new int[nBlk.y][]; - for (int i4 = 0; i4 < nBlk.y; i4++) - { - lblock[c][r][s][i4] = new int[nBlk.x]; - } - - for (int i = nBlk.y - 1; i >= 0; i--) - { - ArrayUtil.intArraySet(lblock[c][r][s][i], INIT_LBLOCK); - } - } // loop on subbands - } // End loop on resolution levels - } // End loop on components - - return cbI; - } - - /// Retrives precincts and code-blocks coordinates in the given resolution, - /// level and component. Finishes TagTreeEncoder initialization as well. - /// - /// - /// Component index. - /// - /// - /// Resolution level index. - /// - /// - /// Number of decomposition level in component c. - /// - /// - private void fillPrecInfo(int c, int r, int mdl) - { - if (ppinfo[c][r].Length == 0) - return; // No precinct in this - // resolution level - - Coord tileI = src.getTile(null); - Coord nTiles = src.getNumTiles(null); - - int xsiz, ysiz, x0siz, y0siz; - int xt0siz, yt0siz; - int xtsiz, ytsiz; - - xt0siz = src.TilePartULX; - yt0siz = src.TilePartULY; - xtsiz = src.NomTileWidth; - ytsiz = src.NomTileHeight; - x0siz = hd.ImgULX; - y0siz = hd.ImgULY; - xsiz = hd.ImgWidth; - ysiz = hd.ImgHeight; - - int tx0 = (tileI.x == 0) ? x0siz : xt0siz + tileI.x * xtsiz; - int ty0 = (tileI.y == 0) ? y0siz : yt0siz + tileI.y * ytsiz; - int tx1 = (tileI.x != nTiles.x - 1) ? xt0siz + (tileI.x + 1) * xtsiz : xsiz; - int ty1 = (tileI.y != nTiles.y - 1) ? yt0siz + (tileI.y + 1) * ytsiz : ysiz; - - int xrsiz = hd.getCompSubsX(c); - int yrsiz = hd.getCompSubsY(c); - - int tcx0 = src.getResULX(c, mdl); - int tcy0 = src.getResULY(c, mdl); - int tcx1 = tcx0 + src.getTileCompWidth(tIdx, c, mdl); - int tcy1 = tcy0 + src.getTileCompHeight(tIdx, c, mdl); - - int ndl = mdl - r; - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - int trx0 = (int)System.Math.Ceiling(tcx0 / (double)(1 << ndl)); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - int try0 = (int)System.Math.Ceiling(tcy0 / (double)(1 << ndl)); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - int trx1 = (int)System.Math.Ceiling(tcx1 / (double)(1 << ndl)); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - int try1 = (int)System.Math.Ceiling(tcy1 / (double)(1 << ndl)); - - int cb0x = src.CbULX; - int cb0y = src.CbULY; - - double twoppx = (double)getPPX(tIdx, c, r); - double twoppy = (double)getPPY(tIdx, c, r); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - int twoppx2 = (int)(twoppx / 2); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - int twoppy2 = (int)(twoppy / 2); - - // Precincts are located at (cb0x+i*twoppx,cb0y+j*twoppy) - // Valid precincts are those which intersect with the current - // resolution level - int maxPrec = ppinfo[c][r].Length; - int nPrec = 0; - - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - int istart = (int)System.Math.Floor((try0 - cb0y) / twoppy); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - int iend = (int)System.Math.Floor((try1 - 1 - cb0y) / twoppy); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - int jstart = (int)System.Math.Floor((trx0 - cb0x) / twoppx); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - int jend = (int)System.Math.Floor((trx1 - 1 - cb0x) / twoppx); - - int acb0x, acb0y; - - SubbandSyn root = src.getSynSubbandTree(tIdx, c); - SubbandSyn sb = null; - - int p0x, p0y, p1x, p1y; // Precinct projection in subband - int s0x, s0y, s1x, s1y; // Active subband portion - int cw, ch; - int kstart, kend, lstart, lend, k0, l0; - int prg_ulx, prg_uly; - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - int prg_w = (int)twoppx << ndl; - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - int prg_h = (int)twoppy << ndl; - int tmp1, tmp2; - - CBlkCoordInfo cb; - - for (int i = istart; i <= iend; i++) - { - // Vertical precincts - for (int j = jstart; j <= jend; j++, nPrec++) - { - // Horizontal precincts - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - if (j == jstart && (trx0 - cb0x) % (xrsiz * ((int)twoppx)) != 0) - { - prg_ulx = tx0; - } - else - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - prg_ulx = cb0x + j * xrsiz * ((int)twoppx << ndl); - } - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - if (i == istart && (try0 - cb0y) % (yrsiz * ((int)twoppy)) != 0) - { - prg_uly = ty0; - } - else - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - prg_uly = cb0y + i * yrsiz * ((int)twoppy << ndl); - } - - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - ppinfo[c][r][nPrec] = new PrecInfo(r, (int)(cb0x + j * twoppx), (int)(cb0y + i * twoppy), (int)twoppx, (int)twoppy, prg_ulx, prg_uly, prg_w, prg_h); - - if (r == 0) - { - // LL subband - acb0x = cb0x; - acb0y = cb0y; - - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - p0x = acb0x + j * (int)twoppx; - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - p1x = p0x + (int)twoppx; - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - p0y = acb0y + i * (int)twoppy; - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - p1y = p0y + (int)twoppy; - - sb = (SubbandSyn)root.getSubbandByIdx(0, 0); - s0x = (p0x < sb.ulcx) ? sb.ulcx : p0x; - s1x = (p1x > sb.ulcx + sb.w) ? sb.ulcx + sb.w : p1x; - s0y = (p0y < sb.ulcy) ? sb.ulcy : p0y; - s1y = (p1y > sb.ulcy + sb.h) ? sb.ulcy + sb.h : p1y; - - // Code-blocks are located at (acb0x+k*cw,acb0y+l*ch) - cw = sb.nomCBlkW; - ch = sb.nomCBlkH; - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - k0 = (int)System.Math.Floor((sb.ulcy - acb0y) / (double)ch); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - kstart = (int)System.Math.Floor((s0y - acb0y) / (double)ch); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - kend = (int)System.Math.Floor((s1y - 1 - acb0y) / (double)ch); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - l0 = (int)System.Math.Floor((sb.ulcx - acb0x) / (double)cw); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - lstart = (int)System.Math.Floor((s0x - acb0x) / (double)cw); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - lend = (int)System.Math.Floor((s1x - 1 - acb0x) / (double)cw); - - if (s1x - s0x <= 0 || s1y - s0y <= 0) - { - ppinfo[c][r][nPrec].nblk[0] = 0; - ttIncl[c][r][nPrec][0] = new TagTreeDecoder(0, 0); - ttMaxBP[c][r][nPrec][0] = new TagTreeDecoder(0, 0); - } - else - { - ttIncl[c][r][nPrec][0] = new TagTreeDecoder(kend - kstart + 1, lend - lstart + 1); - ttMaxBP[c][r][nPrec][0] = new TagTreeDecoder(kend - kstart + 1, lend - lstart + 1); - CBlkCoordInfo[][] tmpArray = new CBlkCoordInfo[kend - kstart + 1][]; - for (int i2 = 0; i2 < kend - kstart + 1; i2++) - { - tmpArray[i2] = new CBlkCoordInfo[lend - lstart + 1]; - } - ppinfo[c][r][nPrec].cblk[0] = tmpArray; - ppinfo[c][r][nPrec].nblk[0] = (kend - kstart + 1) * (lend - lstart + 1); - - for (int k = kstart; k <= kend; k++) - { - // Vertical cblks - for (int l = lstart; l <= lend; l++) - { - // Horiz. cblks - cb = new CBlkCoordInfo(k - k0, l - l0); - if (l == l0) - { - cb.ulx = sb.ulx; - } - else - { - cb.ulx = sb.ulx + l * cw - (sb.ulcx - acb0x); - } - if (k == k0) - { - cb.uly = sb.uly; - } - else - { - cb.uly = sb.uly + k * ch - (sb.ulcy - acb0y); - } - tmp1 = acb0x + l * cw; - tmp1 = (tmp1 > sb.ulcx) ? tmp1 : sb.ulcx; - tmp2 = acb0x + (l + 1) * cw; - tmp2 = (tmp2 > sb.ulcx + sb.w) ? sb.ulcx + sb.w : tmp2; - cb.w = tmp2 - tmp1; - tmp1 = acb0y + k * ch; - tmp1 = (tmp1 > sb.ulcy) ? tmp1 : sb.ulcy; - tmp2 = acb0y + (k + 1) * ch; - tmp2 = (tmp2 > sb.ulcy + sb.h) ? sb.ulcy + sb.h : tmp2; - cb.h = tmp2 - tmp1; - ppinfo[c][r][nPrec].cblk[0][k - kstart][l - lstart] = cb; - } // Horizontal code-blocks - } // Vertical code-blocks - } - } - else - { - // HL, LH and HH subbands - // HL subband - acb0x = 0; - acb0y = cb0y; - - p0x = acb0x + j * twoppx2; - p1x = p0x + twoppx2; - p0y = acb0y + i * twoppy2; - p1y = p0y + twoppy2; - - sb = (SubbandSyn)root.getSubbandByIdx(r, 1); - s0x = (p0x < sb.ulcx) ? sb.ulcx : p0x; - s1x = (p1x > sb.ulcx + sb.w) ? sb.ulcx + sb.w : p1x; - s0y = (p0y < sb.ulcy) ? sb.ulcy : p0y; - s1y = (p1y > sb.ulcy + sb.h) ? sb.ulcy + sb.h : p1y; - - // Code-blocks are located at (acb0x+k*cw,acb0y+l*ch) - cw = sb.nomCBlkW; - ch = sb.nomCBlkH; - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - k0 = (int)System.Math.Floor((sb.ulcy - acb0y) / (double)ch); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - kstart = (int)System.Math.Floor((s0y - acb0y) / (double)ch); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - kend = (int)System.Math.Floor((s1y - 1 - acb0y) / (double)ch); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - l0 = (int)System.Math.Floor((sb.ulcx - acb0x) / (double)cw); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - lstart = (int)System.Math.Floor((s0x - acb0x) / (double)cw); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - lend = (int)System.Math.Floor((s1x - 1 - acb0x) / (double)cw); - - if (s1x - s0x <= 0 || s1y - s0y <= 0) - { - ppinfo[c][r][nPrec].nblk[1] = 0; - ttIncl[c][r][nPrec][1] = new TagTreeDecoder(0, 0); - ttMaxBP[c][r][nPrec][1] = new TagTreeDecoder(0, 0); - } - else - { - ttIncl[c][r][nPrec][1] = new TagTreeDecoder(kend - kstart + 1, lend - lstart + 1); - ttMaxBP[c][r][nPrec][1] = new TagTreeDecoder(kend - kstart + 1, lend - lstart + 1); - CBlkCoordInfo[][] tmpArray2 = new CBlkCoordInfo[kend - kstart + 1][]; - for (int i3 = 0; i3 < kend - kstart + 1; i3++) - { - tmpArray2[i3] = new CBlkCoordInfo[lend - lstart + 1]; - } - ppinfo[c][r][nPrec].cblk[1] = tmpArray2; - ppinfo[c][r][nPrec].nblk[1] = (kend - kstart + 1) * (lend - lstart + 1); - - for (int k = kstart; k <= kend; k++) - { - // Vertical cblks - for (int l = lstart; l <= lend; l++) - { - // Horiz. cblks - cb = new CBlkCoordInfo(k - k0, l - l0); - if (l == l0) - { - cb.ulx = sb.ulx; - } - else - { - cb.ulx = sb.ulx + l * cw - (sb.ulcx - acb0x); - } - if (k == k0) - { - cb.uly = sb.uly; - } - else - { - cb.uly = sb.uly + k * ch - (sb.ulcy - acb0y); - } - tmp1 = acb0x + l * cw; - tmp1 = (tmp1 > sb.ulcx) ? tmp1 : sb.ulcx; - tmp2 = acb0x + (l + 1) * cw; - tmp2 = (tmp2 > sb.ulcx + sb.w) ? sb.ulcx + sb.w : tmp2; - cb.w = tmp2 - tmp1; - tmp1 = acb0y + k * ch; - tmp1 = (tmp1 > sb.ulcy) ? tmp1 : sb.ulcy; - tmp2 = acb0y + (k + 1) * ch; - tmp2 = (tmp2 > sb.ulcy + sb.h) ? sb.ulcy + sb.h : tmp2; - cb.h = tmp2 - tmp1; - ppinfo[c][r][nPrec].cblk[1][k - kstart][l - lstart] = cb; - } // Horizontal code-blocks - } // Vertical code-blocks - } - - // LH subband - acb0x = cb0x; - acb0y = 0; - - p0x = acb0x + j * twoppx2; - p1x = p0x + twoppx2; - p0y = acb0y + i * twoppy2; - p1y = p0y + twoppy2; - - sb = (SubbandSyn)root.getSubbandByIdx(r, 2); - s0x = (p0x < sb.ulcx) ? sb.ulcx : p0x; - s1x = (p1x > sb.ulcx + sb.w) ? sb.ulcx + sb.w : p1x; - s0y = (p0y < sb.ulcy) ? sb.ulcy : p0y; - s1y = (p1y > sb.ulcy + sb.h) ? sb.ulcy + sb.h : p1y; - - // Code-blocks are located at (acb0x+k*cw,acb0y+l*ch) - cw = sb.nomCBlkW; - ch = sb.nomCBlkH; - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - k0 = (int)System.Math.Floor((sb.ulcy - acb0y) / (double)ch); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - kstart = (int)System.Math.Floor((s0y - acb0y) / (double)ch); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - kend = (int)System.Math.Floor((s1y - 1 - acb0y) / (double)ch); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - l0 = (int)System.Math.Floor((sb.ulcx - acb0x) / (double)cw); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - lstart = (int)System.Math.Floor((s0x - acb0x) / (double)cw); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - lend = (int)System.Math.Floor((s1x - 1 - acb0x) / (double)cw); - - if (s1x - s0x <= 0 || s1y - s0y <= 0) - { - ppinfo[c][r][nPrec].nblk[2] = 0; - ttIncl[c][r][nPrec][2] = new TagTreeDecoder(0, 0); - ttMaxBP[c][r][nPrec][2] = new TagTreeDecoder(0, 0); - } - else - { - ttIncl[c][r][nPrec][2] = new TagTreeDecoder(kend - kstart + 1, lend - lstart + 1); - ttMaxBP[c][r][nPrec][2] = new TagTreeDecoder(kend - kstart + 1, lend - lstart + 1); - CBlkCoordInfo[][] tmpArray3 = new CBlkCoordInfo[kend - kstart + 1][]; - for (int i4 = 0; i4 < kend - kstart + 1; i4++) - { - tmpArray3[i4] = new CBlkCoordInfo[lend - lstart + 1]; - } - ppinfo[c][r][nPrec].cblk[2] = tmpArray3; - ppinfo[c][r][nPrec].nblk[2] = (kend - kstart + 1) * (lend - lstart + 1); - - for (int k = kstart; k <= kend; k++) - { - // Vertical cblks - for (int l = lstart; l <= lend; l++) - { - // Horiz cblks - cb = new CBlkCoordInfo(k - k0, l - l0); - if (l == l0) - { - cb.ulx = sb.ulx; - } - else - { - cb.ulx = sb.ulx + l * cw - (sb.ulcx - acb0x); - } - if (k == k0) - { - cb.uly = sb.uly; - } - else - { - cb.uly = sb.uly + k * ch - (sb.ulcy - acb0y); - } - tmp1 = acb0x + l * cw; - tmp1 = (tmp1 > sb.ulcx) ? tmp1 : sb.ulcx; - tmp2 = acb0x + (l + 1) * cw; - tmp2 = (tmp2 > sb.ulcx + sb.w) ? sb.ulcx + sb.w : tmp2; - cb.w = tmp2 - tmp1; - tmp1 = acb0y + k * ch; - tmp1 = (tmp1 > sb.ulcy) ? tmp1 : sb.ulcy; - tmp2 = acb0y + (k + 1) * ch; - tmp2 = (tmp2 > sb.ulcy + sb.h) ? sb.ulcy + sb.h : tmp2; - cb.h = tmp2 - tmp1; - ppinfo[c][r][nPrec].cblk[2][k - kstart][l - lstart] = cb; - } // Horizontal code-blocks - } // Vertical code-blocks - } - - // HH subband - acb0x = 0; - acb0y = 0; - - p0x = acb0x + j * twoppx2; - p1x = p0x + twoppx2; - p0y = acb0y + i * twoppy2; - p1y = p0y + twoppy2; - - sb = (SubbandSyn)root.getSubbandByIdx(r, 3); - s0x = (p0x < sb.ulcx) ? sb.ulcx : p0x; - s1x = (p1x > sb.ulcx + sb.w) ? sb.ulcx + sb.w : p1x; - s0y = (p0y < sb.ulcy) ? sb.ulcy : p0y; - s1y = (p1y > sb.ulcy + sb.h) ? sb.ulcy + sb.h : p1y; - - // Code-blocks are located at (acb0x+k*cw,acb0y+l*ch) - cw = sb.nomCBlkW; - ch = sb.nomCBlkH; - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - k0 = (int)System.Math.Floor((sb.ulcy - acb0y) / (double)ch); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - kstart = (int)System.Math.Floor((s0y - acb0y) / (double)ch); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - kend = (int)System.Math.Floor((s1y - 1 - acb0y) / (double)ch); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - l0 = (int)System.Math.Floor((sb.ulcx - acb0x) / (double)cw); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - lstart = (int)System.Math.Floor((s0x - acb0x) / (double)cw); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - lend = (int)System.Math.Floor((s1x - 1 - acb0x) / (double)cw); - - if (s1x - s0x <= 0 || s1y - s0y <= 0) - { - ppinfo[c][r][nPrec].nblk[3] = 0; - ttIncl[c][r][nPrec][3] = new TagTreeDecoder(0, 0); - ttMaxBP[c][r][nPrec][3] = new TagTreeDecoder(0, 0); - } - else - { - ttIncl[c][r][nPrec][3] = new TagTreeDecoder(kend - kstart + 1, lend - lstart + 1); - ttMaxBP[c][r][nPrec][3] = new TagTreeDecoder(kend - kstart + 1, lend - lstart + 1); - CBlkCoordInfo[][] tmpArray4 = new CBlkCoordInfo[kend - kstart + 1][]; - for (int i5 = 0; i5 < kend - kstart + 1; i5++) - { - tmpArray4[i5] = new CBlkCoordInfo[lend - lstart + 1]; - } - ppinfo[c][r][nPrec].cblk[3] = tmpArray4; - ppinfo[c][r][nPrec].nblk[3] = (kend - kstart + 1) * (lend - lstart + 1); - - for (int k = kstart; k <= kend; k++) - { - // Vertical cblks - for (int l = lstart; l <= lend; l++) - { - // Horiz cblks - cb = new CBlkCoordInfo(k - k0, l - l0); - if (l == l0) - { - cb.ulx = sb.ulx; - } - else - { - cb.ulx = sb.ulx + l * cw - (sb.ulcx - acb0x); - } - if (k == k0) - { - cb.uly = sb.uly; - } - else - { - cb.uly = sb.uly + k * ch - (sb.ulcy - acb0y); - } - tmp1 = acb0x + l * cw; - tmp1 = (tmp1 > sb.ulcx) ? tmp1 : sb.ulcx; - tmp2 = acb0x + (l + 1) * cw; - tmp2 = (tmp2 > sb.ulcx + sb.w) ? sb.ulcx + sb.w : tmp2; - cb.w = tmp2 - tmp1; - tmp1 = acb0y + k * ch; - tmp1 = (tmp1 > sb.ulcy) ? tmp1 : sb.ulcy; - tmp2 = acb0y + (k + 1) * ch; - tmp2 = (tmp2 > sb.ulcy + sb.h) ? sb.ulcy + sb.h : tmp2; - cb.h = tmp2 - tmp1; - ppinfo[c][r][nPrec].cblk[3][k - kstart][l - lstart] = cb; - } // Horizontal code-blocks - } // Vertical code-blocks - } - } - } // Horizontal precincts - } // Vertical precincts - } - - /// Gets the number of precincts in a given component and resolution level. - /// - /// - /// Component index - /// - /// - /// Resolution index - /// - /// - public virtual int getNumPrecinct(int c, int r) - { - return numPrec[c][r].x * numPrec[c][r].y; - } - - /// Read specified packet head and found length of each code-block's piece - /// of codewords as well as number of skipped most significant bit-planes. - /// - /// - /// layer index - /// - /// - /// Resolution level index - /// - /// - /// Component index - /// - /// - /// Precinct index - /// - /// - /// CBlkInfo array of relevant component and resolution - /// level. - /// - /// - /// The number of bytes to read in each tile before reaching - /// output rate (used by truncation mode) - /// - /// - /// True if specified output rate or EOF is reached. - /// - /// - public virtual bool readPktHead(int l, int r, int c, int p, CBlkInfo[][][] cbI, int[] nb) - { - - CBlkInfo ccb; - int nSeg; // number of segment to read - int cbLen; // Length of cblk's code-words - int ltp; // last truncation point index - int passtype; // coding pass type - TagTreeDecoder tdIncl, tdBD; - int tmp, tmp2, totnewtp, lblockCur, tpidx; - int sumtotnewtp = 0; - Coord cbc; - int startPktHead = ehs.Pos; - if (startPktHead >= ehs.length()) - { - // EOF reached at the beginning of this packet head - return true; - } - int tIdx = src.TileIdx; - PktHeaderBitReader bin; - int mend, nend; - int b; - SubbandSyn sb; - SubbandSyn root = src.getSynSubbandTree(tIdx, c); - - // If packed packet headers was used, use separate stream for reading - // of packet headers - if (pph) - { - bin = new PktHeaderBitReader(pphbais); - } - else - { - bin = this.bin; - } - - int mins = (r == 0) ? 0 : 1; - int maxs = (r == 0) ? 1 : 4; - - bool precFound = false; - for (int s = mins; s < maxs; s++) - { - if (p < ppinfo[c][r].Length) - { - precFound = true; - } - } - if (!precFound) - { - return false; - } - - PrecInfo prec = ppinfo[c][r][p]; - - // Synchronize for bit reading - bin.sync(); - - // If packet is empty there is no info in it (i.e. no code-blocks) - if (bin.readBit() == 0) - { - // No code-block is included - cblks = new System.Collections.ArrayList[maxs + 1]; - for (int s = mins; s < maxs; s++) - { - cblks[s] = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); - } - pktIdx++; - - // If truncation mode, checks if output rate is reached - // unless ncb quit condition is used in which case headers - // are not counted - if (isTruncMode && maxCB == -1) - { - tmp = ehs.Pos - startPktHead; - if (tmp > nb[tIdx]) - { - nb[tIdx] = 0; - return true; - } - else - { - nb[tIdx] -= tmp; - } - } - - // Read EPH marker if needed - if (ephUsed) - { - readEPHMarker(bin); - } - return false; - } - - // Packet is not empty => decode info - // Loop on each subband in this resolution level - if (cblks == null || cblks.Length < maxs + 1) - { - cblks = new System.Collections.ArrayList[maxs + 1]; - } - - for (int s = mins; s < maxs; s++) - { - if (cblks[s] == null) - { - cblks[s] = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); - } - else - { - cblks[s].Clear(); - } - sb = (SubbandSyn)root.getSubbandByIdx(r, s); - // No code-block in this precinct - if (prec.nblk[s] == 0) - { - // Go to next subband - continue; - } - - tdIncl = ttIncl[c][r][p][s]; - tdBD = ttMaxBP[c][r][p][s]; - - mend = (prec.cblk[s] == null) ? 0 : prec.cblk[s].Length; - for (int m = 0; m < mend; m++) - { - // Vertical code-blocks - nend = (prec.cblk[s][m] == null) ? 0 : prec.cblk[s][m].Length; - for (int n = 0; n < nend; n++) - { - // Horizontal code-blocks - cbc = prec.cblk[s][m][n].idx; - b = cbc.x + cbc.y * sb.numCb.x; - - ccb = cbI[s][cbc.y][cbc.x]; - - try - { - // If code-block not included in previous layer(s) - if (ccb == null || ccb.ctp == 0) - { - if (ccb == null) - { - ccb = cbI[s][cbc.y][cbc.x] = new CBlkInfo(prec.cblk[s][m][n].ulx, prec.cblk[s][m][n].uly, prec.cblk[s][m][n].w, prec.cblk[s][m][n].h, nl); - } - ccb.pktIdx[l] = pktIdx; - - // Read inclusion using tag-tree - tmp = tdIncl.update(m, n, l + 1, bin); - if (tmp > l) - { - // Not included - continue; - } - - // Read bitdepth using tag-tree - tmp = 1; // initialization - for (tmp2 = 1; tmp >= tmp2; tmp2++) - { - tmp = tdBD.update(m, n, tmp2, bin); - } - ccb.msbSkipped = tmp2 - 2; - - // New code-block => at least one truncation point - totnewtp = 1; - ccb.addNTP(l, 0); - - // Check whether ncb quit condition is reached - ncb++; - - if (maxCB != -1 && !ncbQuit && ncb == maxCB) - { - // ncb quit contidion reached - ncbQuit = true; - tQuit = tIdx; - cQuit = c; - sQuit = s; - rQuit = r; - xQuit = cbc.x; - yQuit = cbc.y; - } - } - else - { - // If code-block already included in one of - // the previous layers. - - ccb.pktIdx[l] = pktIdx; - - // If not inclused - if (bin.readBit() != 1) - { - continue; - } - - // At least 1 more truncation point than - // prev. packet - totnewtp = 1; - } - - // Read new truncation points - if (bin.readBit() == 1) - { - // if bit is 1 - totnewtp++; - - // if next bit is 0 do nothing - if (bin.readBit() == 1) - { - //if is 1 - totnewtp++; - - tmp = bin.readBits(2); - totnewtp += tmp; - - // If next 2 bits are not 11 do nothing - if (tmp == 0x3) - { - //if 11 - tmp = bin.readBits(5); - totnewtp += tmp; - - // If next 5 bits are not 11111 do nothing - if (tmp == 0x1F) - { - //if 11111 - totnewtp += bin.readBits(7); - } - } - } - } - ccb.addNTP(l, totnewtp); - sumtotnewtp += totnewtp; - cblks[s].Add(prec.cblk[s][m][n]); - - // Code-block length - - // -- Compute the number of bit to read to obtain - // code-block length. - // numBits = betaLamda + log2(totnewtp); - - // The length is signalled for each segment in - // addition to the final one. The total length is the - // sum of all segment lengths. - - // If regular termination in use, then there is one - // segment per truncation point present. Otherwise, if - // selective arithmetic bypass coding mode is present, - // then there is one termination per bypass/MQ and - // MQ/bypass transition. Otherwise the only - // termination is at the end of the code-block. - int options = ((System.Int32)decSpec.ecopts.getTileCompVal(tIdx, c)); - - if ((options & CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_TERM_PASS) != 0) - { - // Regular termination in use, one segment per new - // pass (i.e. truncation point) - nSeg = totnewtp; - } - else if ((options & CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_BYPASS) != 0) - { - // Selective arithmetic coding bypass coding mode - // in use, but no regular termination 1 segment up - // to the end of the last pass of the 4th most - // significant bit-plane, and, in each following - // bit-plane, one segment upto the end of the 2nd - // pass and one upto the end of the 3rd pass. - - if (ccb.ctp <= CSJ2K.j2k.entropy.StdEntropyCoderOptions.FIRST_BYPASS_PASS_IDX) - { - nSeg = 1; - } - else - { - nSeg = 1; // One at least for last pass - // And one for each other terminated pass - for (tpidx = ccb.ctp - totnewtp; tpidx < ccb.ctp - 1; tpidx++) - { - if (tpidx >= CSJ2K.j2k.entropy.StdEntropyCoderOptions.FIRST_BYPASS_PASS_IDX - 1) - { - passtype = (tpidx + CSJ2K.j2k.entropy.StdEntropyCoderOptions.NUM_EMPTY_PASSES_IN_MS_BP) % CSJ2K.j2k.entropy.StdEntropyCoderOptions.NUM_PASSES; - if (passtype == 1 || passtype == 2) - { - // bypass coding just before MQ - // pass or MQ pass just before - // bypass coding => terminated - nSeg++; - } - } - } - } - } - else - { - // Nothing special in use, just one segment - nSeg = 1; - } - - // Reads lblock increment (common to all segments) - while (bin.readBit() != 0) - { - lblock[c][r][s][cbc.y][cbc.x]++; - } - - if (nSeg == 1) - { - // Only one segment in packet - cbLen = bin.readBits(lblock[c][r][s][cbc.y][cbc.x] + MathUtil.log2(totnewtp)); - } - else - { - // We must read one length per segment - ccb.segLen[l] = new int[nSeg]; - cbLen = 0; - int j; - if ((options & CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_TERM_PASS) != 0) - { - // Regular termination: each pass is terminated - for (tpidx = ccb.ctp - totnewtp, j = 0; tpidx < ccb.ctp; tpidx++, j++) - { - - lblockCur = lblock[c][r][s][cbc.y][cbc.x]; - - tmp = bin.readBits(lblockCur); - ccb.segLen[l][j] = tmp; - cbLen += tmp; - } - } - else - { - // Bypass coding: only some passes are - // terminated - ltp = ccb.ctp - totnewtp - 1; - for (tpidx = ccb.ctp - totnewtp, j = 0; tpidx < ccb.ctp - 1; tpidx++) - { - if (tpidx >= CSJ2K.j2k.entropy.StdEntropyCoderOptions.FIRST_BYPASS_PASS_IDX - 1) - { - passtype = (tpidx + CSJ2K.j2k.entropy.StdEntropyCoderOptions.NUM_EMPTY_PASSES_IN_MS_BP) % CSJ2K.j2k.entropy.StdEntropyCoderOptions.NUM_PASSES; - if (passtype == 0) - continue; - - lblockCur = lblock[c][r][s][cbc.y][cbc.x]; - tmp = bin.readBits(lblockCur + MathUtil.log2(tpidx - ltp)); - ccb.segLen[l][j] = tmp; - cbLen += tmp; - ltp = tpidx; - j++; - } - } - // Last pass has always the length sent - lblockCur = lblock[c][r][s][cbc.y][cbc.x]; - tmp = bin.readBits(lblockCur + MathUtil.log2(tpidx - ltp)); - cbLen += tmp; - ccb.segLen[l][j] = tmp; - } - } - ccb.len[l] = cbLen; - - // If truncation mode, checks if output rate is reached - // unless ncb and lbody quit contitions used. - if (isTruncMode && maxCB == -1) - { - tmp = ehs.Pos - startPktHead; - if (tmp > nb[tIdx]) - { - nb[tIdx] = 0; - // Remove found information in this code-block - if (l == 0) - { - cbI[s][cbc.y][cbc.x] = null; - } - else - { - ccb.off[l] = ccb.len[l] = 0; - ccb.ctp -= ccb.ntp[l]; - ccb.ntp[l] = 0; - ccb.pktIdx[l] = -1; - } - return true; - } - } - } - catch (System.IO.EndOfStreamException) - { - // Remove found information in this code-block - if (l == 0) - { - cbI[s][cbc.y][cbc.x] = null; - } - else - { - ccb.off[l] = ccb.len[l] = 0; - ccb.ctp -= ccb.ntp[l]; - ccb.ntp[l] = 0; - ccb.pktIdx[l] = -1; - } - // throw new EOFException(); - return true; - } - } // End loop on horizontal code-blocks - } // End loop on vertical code-blocks - } // End loop on subbands - - // Read EPH marker if needed - if (ephUsed) - { - readEPHMarker(bin); - } - - pktIdx++; - - // If truncation mode, checks if output rate is reached - if (isTruncMode && maxCB == -1) - { - tmp = ehs.Pos - startPktHead; - if (tmp > nb[tIdx]) - { - nb[tIdx] = 0; - return true; - } - else - { - nb[tIdx] -= tmp; - } - } - return false; - } - - /// Reads specificied packet body in order to find offset of each - /// code-block's piece of codeword. This use the list of found code-blocks - /// in previous red packet head. - /// - /// - /// layer index - /// - /// - /// Resolution level index - /// - /// - /// Component index - /// - /// - /// Precinct index - /// - /// - /// CBlkInfo array of relevant component and resolution - /// level. - /// - /// - /// The remainding number of bytes to read from the bit stream in - /// each tile before reaching the decoding rate (in truncation mode) - /// - /// - /// True if decoding rate is reached - /// - /// - public virtual bool readPktBody(int l, int r, int c, int p, CBlkInfo[][][] cbI, int[] nb) - { - int curOff = ehs.Pos; - //Coord curCB; - CBlkInfo ccb; - bool stopRead = false; - int tIdx = src.TileIdx; - Coord cbc; - - bool precFound = false; - int mins = (r == 0) ? 0 : 1; - int maxs = (r == 0) ? 1 : 4; - for (int s = mins; s < maxs; s++) - { - if (p < ppinfo[c][r].Length) - { - precFound = true; - } - } - if (!precFound) - { - return false; - } - - for (int s = mins; s < maxs; s++) - { - for (int numCB = 0; numCB < cblks[s].Count; numCB++) - { - cbc = ((CBlkCoordInfo)cblks[s][numCB]).idx; - ccb = cbI[s][cbc.y][cbc.x]; - ccb.off[l] = curOff; - curOff += ccb.len[l]; - try - { - ehs.seek(curOff); - } - catch (System.IO.EndOfStreamException) - { - if (l == 0) - { - cbI[s][cbc.y][cbc.x] = null; - } - else - { - ccb.off[l] = ccb.len[l] = 0; - ccb.ctp -= ccb.ntp[l]; - ccb.ntp[l] = 0; - ccb.pktIdx[l] = -1; - } - - // JH: If we try and seek past the end of the stream just stop the decoding - curOff = ehs.length() - 1; - ehs.seek(curOff); - stopRead = true; - return true; - //throw new System.IO.EndOfStreamException(); - } - - // If truncation mode - if (isTruncMode) - { - if (stopRead || ccb.len[l] > nb[tIdx]) - { - // Remove found information in this code-block - if (l == 0) - { - cbI[s][cbc.y][cbc.x] = null; - } - else - { - ccb.off[l] = ccb.len[l] = 0; - ccb.ctp -= ccb.ntp[l]; - ccb.ntp[l] = 0; - ccb.pktIdx[l] = -1; - } - stopRead = true; - } - if (!stopRead) - { - nb[tIdx] -= ccb.len[l]; - } - } - // If ncb quit condition reached - if (ncbQuit && r == rQuit && s == sQuit && cbc.x == xQuit && cbc.y == yQuit && tIdx == tQuit && c == cQuit) - { - cbI[s][cbc.y][cbc.x] = null; - stopRead = true; - } - } // Loop on code-blocks - } // End loop on subbands - - // Seek to the end of the packet - ehs.seek(curOff); - - if (stopRead) - { - return true; - } - else - { - return false; - } - } - - - /// Returns the precinct partition width for the specified component, - /// resolution level and tile. - /// - /// - /// the tile index - /// - /// - /// The index of the component (between 0 and C-1) - /// - /// - /// The resolution level, from 0 to L. - /// - /// - /// the precinct partition width for the specified component, - /// resolution level and tile. - /// - /// - public int getPPX(int t, int c, int r) - { - return decSpec.pss.getPPX(t, c, r); - } - - /// Returns the precinct partition height for the specified component, - /// resolution level and tile. - /// - /// - /// the tile index - /// - /// - /// The index of the component (between 0 and C-1) - /// - /// - /// The resolution level, from 0 to L. - /// - /// - /// the precinct partition height in the specified component, for - /// the specified resolution level, for the current tile. - /// - /// - public int getPPY(int t, int c, int rl) - { - return decSpec.pss.getPPY(t, c, rl); - } - - /// Try to read a SOP marker and check that its sequence number if not out - /// of sequence. If so, an error is thrown. - /// - /// - /// The number of bytes left to read from each tile - /// - /// - /// Precinct index - /// - /// - /// Resolution level index - /// - /// - /// Component index - /// - /// - public virtual bool readSOPMarker(int[] nBytes, int p, int c, int r) - { - int val; - byte[] sopArray = new byte[6]; - int tIdx = src.TileIdx; - int mins = (r == 0) ? 0 : 1; - int maxs = (r == 0) ? 1 : 4; - bool precFound = false; - for (int s = mins; s < maxs; s++) - { - if (p < ppinfo[c][r].Length) - { - precFound = true; - } - } - if (!precFound) - { - return false; - } - - // If SOP markers are not used, return - if (!sopUsed) - { - return false; - } - - // Check if SOP is used for this packet - int pos = ehs.Pos; - if ((short)((ehs.read() << 8) | ehs.read()) != CSJ2K.j2k.codestream.Markers.SOP) - { - ehs.seek(pos); - return false; - } - ehs.seek(pos); - - // If length of SOP marker greater than remaining bytes to read for - // this tile return true - if (nBytes[tIdx] < 6) - { - return true; - } - nBytes[tIdx] -= 6; - - // Read marker into array 'sopArray' - ehs.readFully(sopArray, 0, CSJ2K.j2k.codestream.Markers.SOP_LENGTH); - - // Check if this is the correct marker - val = sopArray[0]; - val <<= 8; - val |= sopArray[1]; - if (val != CSJ2K.j2k.codestream.Markers.SOP) - { - throw new System.ApplicationException("Corrupted Bitstream: Could not parse SOP " + "marker !"); - } - - // Check if length is correct - val = (sopArray[2] & 0xff); - val <<= 8; - val |= (sopArray[3] & 0xff); - if (val != 4) - { - throw new System.ApplicationException("Corrupted Bitstream: Corrupted SOP marker !"); - } - - // Check if sequence number if ok - val = (sopArray[4] & 0xff); - val <<= 8; - val |= (sopArray[5] & 0xff); - - if (!pph && val != pktIdx) - { - throw new System.ApplicationException("Corrupted Bitstream: SOP marker out of " + "sequence !"); - } - if (pph && val != pktIdx - 1) - { - // if packed packet headers are used, packet header was read - // before SOP marker segment - throw new System.ApplicationException("Corrupted Bitstream: SOP marker out of " + "sequence !"); - } - return false; - } - - /// Try to read an EPH marker. If it is not possible then an Error is - /// thrown. - /// - /// - /// The packet header reader to read the EPH marker from - /// - /// - public virtual void readEPHMarker(PktHeaderBitReader bin) - { - int val; - byte[] ephArray = new byte[2]; - - if (bin.usebais) - { - bin.bais.Read(ephArray, 0, CSJ2K.j2k.codestream.Markers.EPH_LENGTH); - } - else - { - bin.in_Renamed.readFully(ephArray, 0, CSJ2K.j2k.codestream.Markers.EPH_LENGTH); - } - - // Check if this is the correct marker - val = ephArray[0]; - val <<= 8; - val |= ephArray[1]; - if (val != CSJ2K.j2k.codestream.Markers.EPH) - { - throw new System.ApplicationException("Corrupted Bitstream: Could not parse EPH " + "marker ! "); - } - } - - /// Get PrecInfo instance of the specified resolution level, component and - /// precinct. - /// - /// - /// Component index. - /// - /// - /// Resolution level index. - /// - /// - /// Precinct index. - /// - /// - public virtual PrecInfo getPrecInfo(int c, int r, int p) - { - return ppinfo[c][r][p]; - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/codestream/reader/PktHeaderBitReader.cs b/CSJ2K/j2k/codestream/reader/PktHeaderBitReader.cs deleted file mode 100644 index 31846da8..00000000 --- a/CSJ2K/j2k/codestream/reader/PktHeaderBitReader.cs +++ /dev/null @@ -1,288 +0,0 @@ -/* -* CVS identifier: -* -* $Id: PktHeaderBitReader.java,v 1.10 2001/09/14 09:29:45 grosbois Exp $ -* -* Class: PktHeaderBitReader -* -* Description: Bit based reader for packet headers -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.io; -namespace CSJ2K.j2k.codestream.reader -{ - - /// This class provides a bit based reading facility from a byte based one, - /// applying the bit unstuffing procedure as required by the packet headers. - /// - /// - //UPGRADE_NOTE: The access modifier for this class or class field has been changed in order to prevent compilation errors due to the visibility level. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1296'" - public class PktHeaderBitReader - { - - /// The byte based source of data - internal RandomAccessIO in_Renamed; - - /// The byte array that is the source of data if the PktHeaderBitReader - /// is instantiated with a buffer instead of a RandomAccessIO - /// - internal System.IO.MemoryStream bais; - - /// Flag indicating whether the data should be read from the buffer - internal bool usebais; - - /// The current bit buffer - internal int bbuf; - - /// The position of the next bit to read in the bit buffer (0 means - /// empty, 8 full) - /// - internal int bpos; - - /// The next bit buffer, if bit stuffing occurred (i.e. current bit - /// buffer holds 0xFF) - /// - internal int nextbbuf; - - /// Instantiates a 'PktHeaderBitReader' that gets the byte data from the - /// given source. - /// - /// - /// The source of byte data - /// - /// - internal PktHeaderBitReader(RandomAccessIO in_Renamed) - { - this.in_Renamed = in_Renamed; - usebais = false; - } - - /// Instantiates a 'PktHeaderBitReader' that gets the byte data from the - /// given source. - /// - /// - /// The source of byte data - /// - /// - internal PktHeaderBitReader(System.IO.MemoryStream bais) - { - this.bais = bais; - usebais = true; - } - - /// Reads a single bit from the input. - /// - /// - /// The read bit (0 or 1) - /// - /// - /// If an I/O error occurred - /// - /// If teh end of file has been reached - /// - /// - internal int readBit() - { - if (bpos == 0) - { - // Is bit buffer empty? - if (bbuf != 0xFF) - { - // No bit stuffing - if (usebais) - { - bbuf = bais.ReadByte(); - } - else - { - bbuf = in_Renamed.read(); - } - bpos = 8; - if (bbuf == 0xFF) - { - // If new bit stuffing get next byte - if (usebais) - { - nextbbuf = bais.ReadByte(); - } - else - { - nextbbuf = in_Renamed.read(); - } - } - } - else - { - // We had bit stuffing, nextbuf can not be 0xFF - bbuf = nextbbuf; - bpos = 7; - } - } - return (bbuf >> --bpos) & 0x01; - } - - /// Reads a specified number of bits and returns them in a single - /// integer. The bits are returned in the 'n' least significant bits of the - /// returned integer. The maximum number of bits that can be read is 31. - /// - /// - /// The number of bits to read - /// - /// - /// The read bits, packed in the 'n' LSBs. - /// - /// - /// If an I/O error occurred - /// - /// If teh end of file has been reached - /// - /// - internal int readBits(int n) - { - int bits; // The read bits - - // Can we get all bits from the bit buffer? - if (n <= bpos) - { - return (bbuf >> (bpos -= n)) & ((1 << n) - 1); - } - else - { - // NOTE: The implementation need not be recursive but the not - // recursive one exploits a bug in the IBM x86 JIT and caused - // incorrect decoding (Diego Santa Cruz). - bits = 0; - do - { - // Get all the bits we can from the bit buffer - bits <<= bpos; - n -= bpos; - bits |= readBits(bpos); - // Get an extra bit to load next byte (here bpos is 0) - if (bbuf != 0xFF) - { - // No bit stuffing - if (usebais) - { - bbuf = bais.ReadByte(); - } - else - { - bbuf = in_Renamed.read(); - } - - bpos = 8; - if (bbuf == 0xFF) - { - // If new bit stuffing get next byte - if (usebais) - { - nextbbuf = bais.ReadByte(); - } - else - { - nextbbuf = in_Renamed.read(); - } - } - } - else - { - // We had bit stuffing, nextbuf can not be 0xFF - bbuf = nextbbuf; - bpos = 7; - } - } - while (n > bpos); - // Get the last bits, if any - bits <<= n; - bits |= (bbuf >> (bpos -= n)) & ((1 << n) - 1); - // Return result - return bits; - } - } - - /// Synchronizes this object with the underlying byte based input. It - /// discards and buffered bits and gets ready to read bits from the current - /// position in the underlying byte based input. - /// - ///

    This method should always be called when some data has been read - /// directly from the underlying byte based input since the last call to - /// 'readBits()' or 'readBit()' before a new call to any of those - /// methods.

    - /// - ///
    - internal virtual void sync() - { - bbuf = 0; - bpos = 0; - } - - /// Sets the underlying byte based input to the given object. This method - /// discards any currently buffered bits and gets ready to start reading - /// bits from 'in'. - /// - ///

    This method is equivalent to creating a new 'PktHeaderBitReader' - /// object.

    - /// - ///
    - /// The source of byte data - /// - /// - internal virtual void setInput(RandomAccessIO in_Renamed) - { - this.in_Renamed = in_Renamed; - bbuf = 0; - bpos = 0; - } - - /// Sets the underlying byte based input to the given object. This method - /// discards any currently buffered bits and gets ready to start reading - /// bits from 'in'. - /// - ///

    This method is equivalent to creating a new 'PktHeaderBitReader' - /// object.

    - /// - ///
    - /// The source of byte data - /// - /// - internal virtual void setInput(System.IO.MemoryStream bais) - { - this.bais = bais; - bbuf = 0; - bpos = 0; - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/codestream/reader/PktInfo.cs b/CSJ2K/j2k/codestream/reader/PktInfo.cs deleted file mode 100644 index b717e8f1..00000000 --- a/CSJ2K/j2k/codestream/reader/PktInfo.cs +++ /dev/null @@ -1,109 +0,0 @@ -/* -* CVS identifier: -* -* $Id: PktInfo.java,v 1.7 2001/02/14 10:54:49 grosbois Exp $ -* -* Class: PktInfo -* -* Description: Object containing packet informations. -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -namespace CSJ2K.j2k.codestream.reader -{ - - /// This class defines an object used to countain informations about a packet - /// to which the current code-block belongs. - /// - /// - /// - /// - /// - public class PktInfo - { - - /// Index of the packet - public int packetIdx; - - /// The layer associated with the current code-block in this packet. - public int layerIdx; - - /// The code-block offset in the codestream (for this packet) - public int cbOff = 0; - - /// The length of the code-block in this packet (in bytes) - public int cbLength; - - /// The length of each terminated segment in the packet. The total is the - /// same as 'cbLength'. It can be null if there is only one terminated - /// segment, in which case 'cbLength' holds the legth of that segment - /// - /// - public int[] segLengths; - - /// The number of truncation points that appear in this packet, and all - /// previous packets, for this code-block. This is the number of passes - /// that can be decoded with the information in this packet and all - /// previous ones. - /// - /// - public int numTruncPnts; - - /// Classe's constructor. - /// - /// - /// The layer index for the code-block in this packet - /// - /// - /// The packet index - /// - /// - public PktInfo(int lyIdx, int pckIdx) - { - layerIdx = lyIdx; - packetIdx = pckIdx; - } - - /// Object information in a string. - /// - /// - /// Object information - /// - /// - public override System.String ToString() - { - return "packet " + packetIdx + " (lay:" + layerIdx + ", off:" + cbOff + ", len:" + cbLength + ", numTruncPnts:" + numTruncPnts + ")\n"; - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/codestream/reader/TagTreeDecoder.cs b/CSJ2K/j2k/codestream/reader/TagTreeDecoder.cs deleted file mode 100644 index 1260f754..00000000 --- a/CSJ2K/j2k/codestream/reader/TagTreeDecoder.cs +++ /dev/null @@ -1,304 +0,0 @@ -/* -* CVS identifier: -* -* $Id: TagTreeDecoder.java,v 1.7 2001/08/23 08:04:48 grosbois Exp $ -* -* Class: TagTreeDecoder -* -* Description: Decoder of tag trees -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.util; -namespace CSJ2K.j2k.codestream.reader -{ - - /// This class implements the tag tree decoder. A tag tree codes a 2D matrix of - /// integer elements in an efficient way. The decoding procedure 'update()' - /// updates a value of the matrix from a stream of coded data, given a - /// threshold. This procedure decodes enough information to identify whether or - /// not the value is greater than or equal to the threshold, and updates the - /// value accordingly. - /// - ///

    In general the decoding procedure must follow the same sequence of - /// elements and thresholds as the encoding one. The encoder is implemented by - /// the TagTreeEncoder class.

    - /// - ///

    Tag trees that have one dimension, or both, as 0 are allowed for - /// convenience. Of course no values can be set or coded in such cases.

    - /// - ///
    - /// - /// - /// - public class TagTreeDecoder - { - /// Returns the number of leafs along the horizontal direction. - /// - /// - /// The number of leafs along the horizontal direction. - /// - /// - virtual public int Width - { - get - { - return w; - } - - } - /// Returns the number of leafs along the vertical direction. - /// - /// - /// The number of leafs along the vertical direction. - /// - /// - virtual public int Height - { - get - { - return h; - } - - } - - /// The horizontal dimension of the base level - protected internal int w; - - /// The vertical dimensions of the base level - protected internal int h; - - /// The number of levels in the tag tree - protected internal int lvls; - - /// The tag tree values. The first index is the level, starting at level 0 - /// (leafs). The second index is the element within the level, in - /// lexicographical order. - /// - protected internal int[][] treeV; - - /// The tag tree state. The first index is the level, starting at level 0 - /// (leafs). The second index is the element within the level, in - /// lexicographical order. - /// - protected internal int[][] treeS; - - /// Creates a tag tree decoder with 'w' elements along the horizontal - /// dimension and 'h' elements along the vertical direction. The total - /// number of elements is thus 'vdim' x 'hdim'. - /// - ///

    The values of all elements are initialized to Integer.MAX_VALUE - /// (i.e. no information decoded so far). The states are initialized all to - /// 0.

    - /// - ///
    - /// The number of elements along the vertical direction. - /// - /// - /// The number of elements along the horizontal direction. - /// - /// - public TagTreeDecoder(int h, int w) - { - int i; - - // Check arguments - if (w < 0 || h < 0) - { - throw new System.ArgumentException(); - } - // Initialize dimensions - this.w = w; - this.h = h; - // Calculate the number of levels - if (w == 0 || h == 0) - { - lvls = 0; // Empty tree - } - else - { - lvls = 1; - while (h != 1 || w != 1) - { - // Loop until we reach root - w = (w + 1) >> 1; - h = (h + 1) >> 1; - lvls++; - } - } - // Allocate tree values and states - treeV = new int[lvls][]; - treeS = new int[lvls][]; - w = this.w; - h = this.h; - for (i = 0; i < lvls; i++) - { - treeV[i] = new int[h * w]; - // Initialize to infinite value - ArrayUtil.intArraySet(treeV[i], System.Int32.MaxValue); - - // (no need to initialize to 0 since it's the default) - treeS[i] = new int[h * w]; - w = (w + 1) >> 1; - h = (h + 1) >> 1; - } - } - - /// Decodes information for the specified element of the tree, given the - /// threshold, and updates its value. The information that can be decoded - /// is whether or not the value of the element is greater than, or equal - /// to, the value of the threshold. - /// - /// - /// The vertical index of the element. - /// - /// - /// The horizontal index of the element. - /// - /// - /// The threshold to use in decoding. It must be non-negative. - /// - /// - /// The stream from where to read the coded information. - /// - /// - /// The updated value at position (m,n). - /// - /// - /// If an I/O error occurs while reading from 'in'. - /// - /// - /// If the ned of the 'in' stream is reached before - /// getting all the necessary data. - /// - /// - public virtual int update(int m, int n, int t, PktHeaderBitReader in_Renamed) - { - int k, tmin; - int idx, ts, tv; - - // Check arguments - if (m >= h || n >= w || t < 0) - { - throw new System.ArgumentException(); - } - - // Initialize - k = lvls - 1; - tmin = treeS[k][0]; - - // Loop on levels - idx = (m >> k) * ((w + (1 << k) - 1) >> k) + (n >> k); - while (true) - { - // Cache state and value - ts = treeS[k][idx]; - tv = treeV[k][idx]; - if (ts < tmin) - { - ts = tmin; - } - while (t > ts) - { - if (tv >= ts) - { - // We are not done yet - if (in_Renamed.readBit() == 0) - { - // '0' bit - // We know that 'value' > treeS[k][idx] - ts++; - } - else - { - // '1' bit - // We know that 'value' = treeS[k][idx] - tv = ts++; - } - // Increment of treeS[k][idx] done above - } - else - { - // We are done, we can set ts and get out - ts = t; - break; // get out of this while - } - } - // Update state and value - treeS[k][idx] = ts; - treeV[k][idx] = tv; - // Update tmin or terminate - if (k > 0) - { - tmin = ts < tv ? ts : tv; - k--; - // Index of element for next iteration - idx = (m >> k) * ((w + (1 << k) - 1) >> k) + (n >> k); - } - else - { - // Return the updated value - return tv; - } - } - } - - /// Returns the current value of the specified element in the tag - /// tree. This is the value as last updated by the update() method. - /// - /// - /// The vertical index of the element. - /// - /// - /// The horizontal index of the element. - /// - /// - /// The current value of the element. - /// - /// - /// - /// - /// - public virtual int getValue(int m, int n) - { - // Check arguments - if (m >= h || n >= w) - { - throw new System.ArgumentException(); - } - // Return value - return treeV[0][m * w + n]; - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/codestream/writer/BitOutputBuffer.cs b/CSJ2K/j2k/codestream/writer/BitOutputBuffer.cs deleted file mode 100644 index e3aff569..00000000 --- a/CSJ2K/j2k/codestream/writer/BitOutputBuffer.cs +++ /dev/null @@ -1,315 +0,0 @@ -/* -* CVS identifier: -* -* $Id: BitOutputBuffer.java,v 1.9 2002/07/19 12:40:05 grosbois Exp $ -* -* Class: BitOutputBuffer -* -* Description: -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.util; -using System; -namespace CSJ2K.j2k.codestream.writer -{ - - /// This class implements a buffer for writing bits, with the required bit - /// stuffing policy for the packet headers. The bits are stored in a byte array - /// in the order in which they are written. The byte array is automatically - /// reallocated and enlarged whenever necessary. A BitOutputBuffer object may - /// be reused by calling its 'reset()' method. - /// - ///

    NOTE: The methods implemented in this class are intended to be used only - /// in writing packet heads, since a special bit stuffing procedure is used, as - /// required for the packet heads. - /// - ///

    - public class BitOutputBuffer - { - /// Returns the current length of the buffer, in bytes. - /// - ///

    This method is declared final to increase performance. - /// - ///

    - /// The currebt length of the buffer in bytes. - /// - /// - virtual public int Length - { - get - { - if (avbits == 8) - { - // A integral number of bytes - return curbyte; - } - else - { - // Some bits in last byte - return curbyte + 1; - } - } - - } - /// Returns the byte buffer. This is the internal byte buffer so it should - /// not be modified. Only the first N elements have valid data, where N is - /// the value returned by 'getLength()' - /// - ///

    This method is declared final to increase performance. - /// - ///

    - /// The internal byte buffer. - /// - /// - virtual public byte[] Buffer - { - get - { - return buf; - } - - } - - /// The buffer where we store the data - internal byte[] buf; - - /// The position of the current byte to write - internal int curbyte; - - /// The number of available bits in the current byte - internal int avbits = 8; - - /// The increment size for the buffer, 16 bytes. This is the - /// number of bytes that are added to the buffer each time it is - /// needed to enlarge it. - /// - // This must be always 6 or larger. - public const int SZ_INCR = 16; - - /// The initial size for the buffer, 32 bytes. - public const int SZ_INIT = 32; - - /// Creates a new BitOutputBuffer width a buffer of length - /// 'SZ_INIT'. - /// - /// - public BitOutputBuffer() - { - buf = new byte[SZ_INIT]; - } - - /// Resets the buffer. This rewinds the current position to the start of - /// the buffer and sets all tha data to 0. Note that no new buffer is - /// allocated, so this will affect any data that was returned by the - /// 'getBuffer()' method. - /// - /// - public virtual void reset() - { - //int i; - // Reinit pointers - curbyte = 0; - avbits = 8; - ArrayUtil.byteArraySet(buf, (byte)0); - } - - /// Writes a bit to the buffer at the current position. The value 'bit' - /// must be either 0 or 1, otherwise it corrupts the bits that have been - /// already written. The buffer is enlarged, by 'SZ_INCR' bytes, if - /// necessary. - /// - ///

    This method is declared final to increase performance. - /// - ///

    - /// The bit to write, 0 or 1. - /// - /// - public void writeBit(int bit) - { - buf[curbyte] |= (byte)(bit << --avbits); - if (avbits > 0) - { - // There is still place in current byte for next bit - return; - } - else - { - // End of current byte => goto next - if (buf[curbyte] != (byte)SupportClass.Identity(0xFF)) - { - // We don't need bit stuffing - avbits = 8; - } - else - { - // We need to stuff a bit (next MSBit is 0) - avbits = 7; - } - curbyte++; - if (curbyte == buf.Length) - { - // We are at end of 'buf' => extend it - byte[] oldbuf = buf; - buf = new byte[oldbuf.Length + SZ_INCR]; - Array.Copy(oldbuf, 0, buf, 0, oldbuf.Length); - } - } - } - - /// Writes the n least significant bits of 'bits' to the buffer at the - /// current position. The least significant bit is written last. The 32-n - /// most significant bits of 'bits' must be 0, otherwise corruption of the - /// buffer will result. The buffer is enlarged, by 'SZ_INCR' bytes, if - /// necessary. - /// - ///

    This method is declared final to increase performance. - /// - ///

    - /// The bits to write. - /// - /// - /// The number of LSBs in 'bits' to write. - /// - /// - public void writeBits(int bits, int n) - { - // Check that we have enough place in 'buf' for n bits, and that we do - // not fill last byte, taking into account possibly stuffed bits (max - // 2) - if (((buf.Length - curbyte) << 3) - 8 + avbits <= n + 2) - { - // Not enough place, extend it - byte[] oldbuf = buf; - buf = new byte[oldbuf.Length + SZ_INCR]; - Array.Copy(oldbuf, 0, buf, 0, oldbuf.Length); - // SZ_INCR is always 6 or more, so it is enough to hold all the - // new bits plus the ones to come after - } - // Now write the bits - if (n >= avbits) - { - // Complete the current byte - n -= avbits; - buf[curbyte] |= (byte)(bits >> n); - if (buf[curbyte] != (byte)SupportClass.Identity(0xFF)) - { - // We don't need bit stuffing - avbits = 8; - } - else - { - // We need to stuff a bit (next MSBit is 0) - avbits = 7; - } - curbyte++; - // Write whole bytes - while (n >= avbits) - { - n -= avbits; - // CONVERSION PROBLEM? - buf[curbyte] |= (byte)((bits >> n) & (~(1 << avbits))); - if (buf[curbyte] != (byte)SupportClass.Identity(0xFF)) - { - // We don't need bit - // stuffing - avbits = 8; - } - else - { - // We need to stuff a bit (next MSBit is 0) - avbits = 7; - } - curbyte++; - } - } - // Finish last byte (we know that now n < avbits) - if (n > 0) - { - avbits -= n; - buf[curbyte] |= (byte)((bits & ((1 << n) - 1)) << avbits); - } - if (avbits == 0) - { - // Last byte is full - if (buf[curbyte] != (byte)SupportClass.Identity(0xFF)) - { - // We don't need bit stuffing - avbits = 8; - } - else - { - // We need to stuff a bit (next MSBit is 0) - avbits = 7; - } - curbyte++; // We already ensured that we have enough place - } - } - - /// Returns the byte buffer data in a new array. This is a copy of the - /// internal byte buffer. If 'data' is non-null it is used to return the - /// data. This array should be large enough to contain all the data, - /// otherwise a IndexOutOfBoundsException is thrown by the Java system. The - /// number of elements returned is what 'getLength()' returns. - /// - /// - /// If non-null this array is used to return the data, which - /// mus be large enough. Otherwise a new one is created and returned. - /// - /// - /// The byte buffer data. - /// - /// - public virtual byte[] toByteArray(byte[] data) - { - if (data == null) - { - data = new byte[(avbits == 8) ? curbyte : curbyte + 1]; - } - Array.Copy(buf, 0, data, 0, (avbits == 8) ? curbyte : curbyte + 1); - return data; - } - - /// Prints information about this object for debugging purposes - /// - /// - /// Information about the object. - /// - /// - public override System.String ToString() - { - return "bits written = " + (curbyte * 8 + (8 - avbits)) + ", curbyte = " + curbyte + ", avbits = " + avbits; - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/codestream/writer/CodestreamWriter.cs b/CSJ2K/j2k/codestream/writer/CodestreamWriter.cs deleted file mode 100644 index 107ff7d3..00000000 --- a/CSJ2K/j2k/codestream/writer/CodestreamWriter.cs +++ /dev/null @@ -1,231 +0,0 @@ -/* -* CVS identifier: -* -* $Id: CodestreamWriter.java,v 1.11 2001/07/24 17:03:30 grosbois Exp $ -* -* Class: CodestreamWriter -* -* Description: Interface for writing bit streams -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -namespace CSJ2K.j2k.codestream.writer -{ - - /// This is the abstract class for writing to a codestream. A codestream - /// corresponds to headers (main and tile-parts) and packets. Each packet has a - /// head and a body. The codestream always has a maximum number of bytes that - /// can be written to it. After that many number of bytes no more data is - /// written to the codestream but the number of bytes is counted so that the - /// value returned by getMaxAvailableBytes() is negative. If the number of - /// bytes is unlimited a ridicoulosly large value, such as Integer.MAX_VALUE, - /// is equivalent. - /// - ///

    Data writting to the codestream can be simulated. In this case, no byto - /// is effectively written to the codestream but the resulting number of bytes - /// is calculated and returned (although it is not accounted in the bit - /// stream). This can be used in rate control loops.

    - /// - ///

    Implementing classes should write the header of the bit stream before - /// writing any packets. The bit stream header can be written with the help of - /// the HeaderEncoder class.

    - /// - ///
    - /// - /// - /// - public abstract class CodestreamWriter - { - /// Returns the number of bytes remaining available in the codestream. This - /// is the maximum allowed number of bytes minus the number of bytes that - /// have already been written to the bit stream. If more bytes have been - /// written to the bit stream than the maximum number of allowed bytes, - /// then a negative value is returned. - /// - /// - /// The number of bytes remaining available in the bit stream. - /// - /// - public abstract int MaxAvailableBytes { get; } - /// Returns the current length of the entire codestream. - /// - /// - /// the current length of the codestream - /// - /// - public abstract int Length { get; } - /// Gives the offset of the end of last packet containing ROI information - /// - /// - /// End of last ROI packet - /// - /// - public abstract int OffLastROIPkt { get; } - - /// The number of bytes already written to the bit stream - protected internal int ndata = 0; - - /// The maximum number of bytes that can be written to the bit stream - protected internal int maxBytes; - - /// Allocates this object and initializes the maximum number of bytes. - /// - /// - /// The maximum number of bytes that can be written to the - /// codestream. - /// - /// - protected internal CodestreamWriter(int mb) - { - maxBytes = mb; - } - - /// Writes a packet head into the codestream and returns the number of - /// bytes used by this header. If in simulation mode then no data is - /// effectively written to the codestream but the number of bytes is - /// calculated. This can be used for iterative rate allocation. - /// - ///

    If the number of bytes that has to be written to the codestream is - /// more than the space left (as returned by getMaxAvailableBytes()), only - /// the data that does not exceed the allowed length is effectively written - /// and the rest is discarded. However the value returned by the method is - /// the total length of the packet, as if all of it was written to the bit - /// stream.

    - /// - ///

    If the codestream header has not been commited yet and if 'sim' is - /// false, then the bit stream header is automatically commited (see - /// commitBitstreamHeader() method) before writting the packet. - /// - ///

    - /// The packet head data. - /// - /// - /// The number of bytes in the packet head. - /// - /// - /// Simulation mode flag. If true nothing is written to the bit - /// stream, but the number of bytes that would be written is returned. - /// - /// - /// Start of packet header marker flag. This flag indicates - /// whether or not SOP markers should be written. If true, SOP markers - /// should be written, if false, they should not. - /// - /// - /// End of Packet Header marker flag. This flag indicates - /// whether or not EPH markers should be written. If true, EPH markers - /// should be written, if false, they should not. - /// - /// - /// The number of bytes spent by the packet head. - /// - /// - /// If an I/O error occurs while writing to the - /// output stream. - /// - /// - /// - /// - /// - public abstract int writePacketHead(byte[] head, int hlen, bool sim, bool sop, bool eph); - - /// Writes a packet body to the codestream and returns the number of bytes - /// used by this body. If in simulation mode then no data is written to the - /// bit stream but the number of bytes is calculated. This can be used for - /// iterative rate allocation. - /// - ///

    If the number of bytes that has to be written to the codestream is - /// more than the space left (as returned by getMaxAvailableBytes()), only - /// the data that does not exceed the allowed length is effectively written - /// and the rest is discarded. However the value returned by the method is - /// the total length of the packet, as if all of it was written to the bit - /// stream.

    - /// - ///
    - /// The packet body data. - /// - /// - /// The number of bytes in the packet body. - /// - /// - /// Simulation mode flag. If true nothing is written to the bit - /// stream, but the number of bytes that would be written is returned. - /// - /// - /// Whether or not there is ROI information in this packet - /// - /// - /// Number of byte to read in packet body to get all the ROI - /// information - /// - /// - /// The number of bytes spent by the packet body. - /// - /// - /// If an I/O error occurs while writing to the - /// output stream. - /// - /// - /// - /// - /// - public abstract int writePacketBody(byte[] body, int blen, bool sim, bool roiInPkt, int roiLen); - - - /// Closes the underlying resource (file, stream, network connection, - /// etc.). After a CodestreamWriter is closed no more data can be written - /// to it. - /// - /// - /// If an I/O error occurs while closing the - /// resource. - /// - /// - public abstract void close(); - - /// Writes the header data to the bit stream, if it has not been already - /// done. In some implementations this method can be called only once, and - /// an IllegalArgumentException is thrown if called more than once. - /// - /// - /// If an I/O error occurs while writing the data. - /// - /// - /// If this method has already been - /// called. - /// - /// - public abstract void commitBitstreamHeader(HeaderEncoder he); - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/codestream/writer/FileCodestreamWriter.cs b/CSJ2K/j2k/codestream/writer/FileCodestreamWriter.cs deleted file mode 100644 index 08834383..00000000 --- a/CSJ2K/j2k/codestream/writer/FileCodestreamWriter.cs +++ /dev/null @@ -1,461 +0,0 @@ -/* -* CVS identifier: -* -* $Id: FileCodestreamWriter.java,v 1.15 2001/09/14 09:29:22 grosbois Exp $ -* -* Class: FileCodestreamWriter -* -* Description: Implementation of the bit stream writer for streams. -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -namespace CSJ2K.j2k.codestream.writer -{ - - /// This class implements a CodestreamWriter for Java streams. The streams can - /// be files or network connections, or any other resource that presents itself - /// as a OutputStream. See the CodestreamWriter abstract class for more details - /// on the implementation of the CodestreamWriter abstract class. - /// - ///

    Before any packet data is written to the bit stream (even in simulation - /// mode) the complete header should be written otherwise incorrect estimates - /// are given by getMaxAvailableBytes() for rate allocation. - /// - ///

    - /// - /// - /// - public class FileCodestreamWriter : CodestreamWriter - { - /// Returns the number of bytes remaining available in the bit stream. This - /// is the maximum allowed number of bytes minus the number of bytes that - /// have already been written to the bit stream. If more bytes have been - /// written to the bit stream than the maximum number of allowed bytes, - /// then a negative value is returned. - /// - /// - /// The number of bytes remaining available in the bit stream. - /// - /// - override public int MaxAvailableBytes - { - get - { - return maxBytes - ndata; - } - - } - /// Returns the current length of the entire bit stream. - /// - /// - /// the current length of the bit stream - /// - /// - override public int Length - { - get - { - if (MaxAvailableBytes >= 0) - { - return ndata; - } - else - { - return maxBytes; - } - } - - } - /// Gives the offset of the end of last packet containing ROI information - /// - /// - /// End of last ROI packet - /// - /// - override public int OffLastROIPkt - { - get - { - return offLastROIPkt; - } - - } - - /// The upper limit for the value of the Nsop field of the SOP marker - private const int SOP_MARKER_LIMIT = 65535; - - /// Index of the current tile - //private int tileIdx = 0; - - /// The file to write - private System.IO.Stream out_Renamed; - - /// The number of bytes already written to the codestream, excluding the - /// header length, magic number and header length info. - /// - new internal int ndata = 0; - - /// The default buffer length, 1024 bytes - public static int DEF_BUF_LEN = 1024; - - /// Array used to store the SOP markers values - internal byte[] sopMarker; - - /// Array used to store the EPH markers values - internal byte[] ephMarker; - - /// The packet index (when start of packet markers i.e. SOP markers) are - /// used. - /// - internal int packetIdx = 0; - - /// Offset of end of last packet containing ROI information - private int offLastROIPkt = 0; - - /// Length of last packets containing no ROI information - private int lenLastNoROI = 0; - - /// Opens the file 'file' for writing the codestream. The magic number is - /// written to the bit stream. Normally, the header encoder must be empty - /// (i.e. no data has been written to it yet). A BufferedOutputStream is - /// used on top of the file to increase throughput, the length of the - /// buffer is DEF_BUF_LEN. - /// - /// - /// The file where to write the bit stream - /// - /// - /// The maximum number of bytes that can be written to the bit - /// stream. - /// - /// - /// If an error occurs while trying to open the file - /// for writing or while writing the magic number. - /// - /// - public FileCodestreamWriter(System.IO.FileInfo file, int mb) : base(mb) - { - //UPGRADE_TODO: Constructor 'java.io.FileOutputStream.FileOutputStream' was converted to 'System.IO.FileStream.FileStream' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioFileOutputStreamFileOutputStream_javaioFile'" - out_Renamed = new System.IO.BufferedStream(new System.IO.FileStream(file.FullName, System.IO.FileMode.Create), DEF_BUF_LEN); - initSOP_EPHArrays(); - } - - /// Opens the file named 'fname' for writing the bit stream, using the 'he' - /// header encoder. The magic number is written to the bit - /// stream. Normally, the header encoder must be empty (i.e. no data has - /// been written to it yet). A BufferedOutputStream is used on top of the - /// file to increase throughput, the length of the buffer is DEF_BUF_LEN. - /// - /// - /// The name of file where to write the bit stream - /// - /// - /// The maximum number of bytes that can be written to the bit - /// stream. - /// - /// - /// The encoder's specifications - /// - /// - /// If an error occurs while trying to open the file - /// for writing or while writing the magic number. - /// - /// - public FileCodestreamWriter(System.String fname, int mb) : base(mb) - { - //UPGRADE_TODO: Constructor 'java.io.FileOutputStream.FileOutputStream' was converted to 'System.IO.FileStream.FileStream' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioFileOutputStreamFileOutputStream_javalangString'" - out_Renamed = new System.IO.BufferedStream(new System.IO.FileStream(fname, System.IO.FileMode.Create), DEF_BUF_LEN); - initSOP_EPHArrays(); - } - - /// Uses the output stream 'os' for writing the bit stream, using the 'he' - /// header encoder. The magic number is written to the bit - /// stream. Normally, the header encoder must be empty (i.e. no data has - /// been written to it yet). No BufferedOutputStream is used on top of the - /// output stream 'os'. - /// - /// - /// The output stream where to write the bit stream. - /// - /// - /// The maximum number of bytes that can be written to the bit - /// stream. - /// - /// - /// If an error occurs while writing the magic - /// number to the 'os' output stream. - /// - /// - public FileCodestreamWriter(System.IO.Stream os, int mb) : base(mb) - { - out_Renamed = os; - initSOP_EPHArrays(); - } - - /// Writes a packet head to the bit stream and returns the number of bytes - /// used by this header. It returns the total number of bytes that the - /// packet head takes in the bit stream. If in simulation mode then no data - /// is written to the bit stream but the number of bytes is - /// calculated. This can be used for iterative rate allocation. - /// - ///

    If the length of the data that is to be written to the bit stream is - /// more than the space left (as returned by getMaxAvailableBytes()) only - /// the data that does not exceed the allowed length is written, the rest - /// is discarded. However the value returned by the method is the total - /// length of the packet, as if all of it was written to the bit stream. - /// - ///

    If the bit stream header has not been commited yet and 'sim' is - /// false, then the bit stream header is automatically commited (see - /// commitBitstreamHeader() method) before writting the packet. - /// - ///

    - /// The packet head data. - /// - /// - /// The number of bytes in the packet head. - /// - /// - /// Simulation mode flag. If true nothing is written to the bit - /// stream, but the number of bytes that would be written is returned. - /// - /// - /// Start of packet header marker flag. This flag indicates - /// whether or not SOP markers should be written. If true, SOP markers - /// should be written, if false, they should not. - /// - /// - /// End of Packet Header marker flag. This flag indicates - /// whether or not EPH markers should be written. If true, EPH markers - /// should be written, if false, they should not. - /// - /// - /// The number of bytes spent by the packet head. - /// - /// - /// If an I/O error occurs while writing to the - /// output stream. - /// - /// - /// - /// - /// - public override int writePacketHead(byte[] head, int hlen, bool sim, bool sop, bool eph) - { - // CONVERSION PROBLEM? - int len = hlen + (sop ? (int)CSJ2K.j2k.codestream.Markers.SOP_LENGTH : 0) + (eph ? (int)CSJ2K.j2k.codestream.Markers.EPH_LENGTH : 0); - - // If not in simulation mode write the data - if (!sim) - { - // Write the head bytes - if (MaxAvailableBytes < len) - { - len = MaxAvailableBytes; - } - - if (len > 0) - { - // Write Start Of Packet header markers if necessary - if (sop) - { - // The first 4 bytes of the array have been filled in the - // classe's constructor. - sopMarker[4] = (byte)(packetIdx >> 8); - sopMarker[5] = (byte)(packetIdx); - out_Renamed.Write(sopMarker, 0, CSJ2K.j2k.codestream.Markers.SOP_LENGTH); - packetIdx++; - if (packetIdx > SOP_MARKER_LIMIT) - { - // Reset SOP value as we have reached its upper limit - packetIdx = 0; - } - } - out_Renamed.Write(head, 0, hlen); - // Update data length - ndata += len; - - // Write End of Packet Header markers if necessary - if (eph) - { - out_Renamed.Write(ephMarker, 0, CSJ2K.j2k.codestream.Markers.EPH_LENGTH); - } - - // Deal with ROI Information - lenLastNoROI += len; - } - } - return len; - } - - /// Writes a packet body to the bit stream and returns the number of bytes - /// used by this body .If in simulation mode then no data is written to the - /// bit stream but the number of bytes is calculated. This can be used for - /// iterative rate allocation. - /// - ///

    If the length of the data that is to be written to the bit stream is - /// more than the space left (as returned by getMaxAvailableBytes()) only - /// the data that does not exceed the allowed length is written, the rest - /// is discarded. However the value returned by the method is the total - /// length of the packet body , as if all of it was written to the bit - /// stream. - /// - ///

    - /// The packet body data. - /// - /// - /// The number of bytes in the packet body. - /// - /// - /// Simulation mode flag. If true nothing is written to the bit - /// stream, but the number of bytes that would be written is returned. - /// - /// - /// Whether or not this packet contains ROI information - /// - /// - /// Number of byte to read in packet body to get all the ROI - /// information - /// - /// - /// The number of bytes spent by the packet body. - /// - /// - /// If an I/O error occurs while writing to the - /// output stream. - /// - /// - /// - /// - /// - public override int writePacketBody(byte[] body, int blen, bool sim, bool roiInPkt, int roiLen) - { - - int len = blen; - - // If not in simulation mode write the data - if (!sim) - { - // Write the body bytes - len = blen; - if (MaxAvailableBytes < len) - { - len = MaxAvailableBytes; - } - if (blen > 0) - { - out_Renamed.Write(body, 0, len); - } - // Update data length - ndata += len; - - // Deal with ROI information - if (roiInPkt) - { - offLastROIPkt += lenLastNoROI + roiLen; - lenLastNoROI = len - roiLen; - } - else - { - lenLastNoROI += len; - } - } - return len; - } - - /// Writes the EOC marker and closes the underlying stream. - /// - /// - /// If an error occurs while closing the underlying - /// stream. - /// - /// - public override void close() - { - - // Write the EOC marker and close the codestream. - // CONVERSION PROBLEM? - out_Renamed.WriteByte((byte)SupportClass.URShift(CSJ2K.j2k.codestream.Markers.EOC, 8)); - out_Renamed.WriteByte((byte)(CSJ2K.j2k.codestream.Markers.EOC & 0x00FF)); - - ndata += 2; // Add two to length of codestream for EOC marker - - out_Renamed.Close(); - } - - /// Writes the header data in the codestream and actualize ndata with the - /// header length. The header is either a MainHeaderEncoder or a - /// TileHeaderEncoder. - /// - /// - /// The current header encoder. - /// - /// - /// If an I/O error occurs while writing the data. - /// - /// - public override void commitBitstreamHeader(HeaderEncoder he) - { - // Actualize ndata - ndata += he.Length; - he.writeTo(out_Renamed); // Write the header - // Reset packet index used for SOP markers - packetIdx = 0; - - // Deal with ROI information - lenLastNoROI += he.Length; - } - - /// Performs the initialisation of the arrays that are used to store the - /// values used to write SOP and EPH markers - /// - /// - private void initSOP_EPHArrays() - { - - // Allocate and set first values of SOP marker as they will not be - // modified - sopMarker = new byte[CSJ2K.j2k.codestream.Markers.SOP_LENGTH]; - sopMarker[0] = unchecked((byte)(CSJ2K.j2k.codestream.Markers.SOP >> 8)); - sopMarker[1] = (byte)SupportClass.Identity(CSJ2K.j2k.codestream.Markers.SOP); - sopMarker[2] = (byte)0x00; - sopMarker[3] = (byte)0x04; - - // Allocate and set values of EPH marker as they will not be - // modified - ephMarker = new byte[CSJ2K.j2k.codestream.Markers.EPH_LENGTH]; - ephMarker[0] = unchecked((byte)(CSJ2K.j2k.codestream.Markers.EPH >> 8)); - ephMarker[1] = (byte)SupportClass.Identity(CSJ2K.j2k.codestream.Markers.EPH); - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/codestream/writer/HeaderEncoder.cs b/CSJ2K/j2k/codestream/writer/HeaderEncoder.cs deleted file mode 100644 index e6cc5267..00000000 --- a/CSJ2K/j2k/codestream/writer/HeaderEncoder.cs +++ /dev/null @@ -1,2074 +0,0 @@ -/* -* CVS identifier: -* -* $Id: HeaderEncoder.java,v 1.43 2001/10/12 09:02:14 grosbois Exp $ -* -* Class: HeaderEncoder -* -* Description: Write codestream headers. -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.encoder; -using CSJ2K.j2k.entropy; -using CSJ2K.j2k.entropy.encoder; -using CSJ2K.j2k.image; -using CSJ2K.j2k.io; -using CSJ2K.j2k.quantization.quantizer; -using CSJ2K.j2k.roi.encoder; -using CSJ2K.j2k.util; -using CSJ2K.j2k.wavelet.analysis; -namespace CSJ2K.j2k.codestream.writer -{ - - /// This class writes almost of the markers and marker segments in main header - /// and in tile-part headers. It is created by the run() method of the Encoder - /// instance. - /// - ///

    A marker segment includes a marker and eventually marker segment - /// parameters. It is designed by the three letter code of the marker - /// associated with the marker segment. JPEG 2000 part I defines 6 types of - /// markers: - ///

      - ///
    • Delimiting : SOC,SOT,SOD,EOC (written in FileCodestreamWriter).
    • - ///
    • Fixed information: SIZ.
    • - ///
    • Functional: COD,COC,RGN,QCD,QCC,POC.
    • - ///
    • In bit-stream: SOP,EPH.
    • - ///
    • Pointer: TLM,PLM,PLT,PPM,PPT.
    • - ///
    • Informational: CRG,COM.
    • - ///

    - /// - ///

    Main Header is written when Encoder instance calls encodeMainHeader - /// whereas tile-part headers are written when the EBCOTRateAllocator instance - /// calls encodeTilePartHeader.

    - /// - ///
    - /// - /// - /// - /// - /// - /// - /// - public class HeaderEncoder - { - /// Returns the parameters that are used in this class and implementing - /// classes. It returns a 2D String array. Each of the 1D arrays is for a - /// different option, and they have 3 elements. The first element is the - /// option name, the second one is the synopsis, the third one is a long - /// description of what the parameter is and the fourth is its default - /// value. The synopsis or description may be 'null', in which case it is - /// assumed that there is no synopsis or description of the option, - /// respectively. Null may be returned if no options are supported. - /// - /// - /// the options name, their synopsis and their explanation, or null - /// if no options are supported. - /// - /// - public static System.String[][] ParameterInfo - { - get - { - return pinfo; - } - - } - /// Returns the byte-buffer used to store the codestream header. - /// - /// - /// A byte array countaining codestream header - /// - /// - virtual protected internal byte[] Buffer - { - get - { - return baos.ToArray(); - } - - } - /// Returns the length of the header. - /// - /// - /// The length of the header in bytes - /// - /// - virtual public int Length - { - get - { - return (int)hbuf.BaseStream.Length; - } - - } - /// Returns the number of bytes used in the codestream header's buffer. - /// - /// - /// Header length in buffer (without any header overhead) - /// - /// - virtual protected internal int BufferLength - { - get - { - return (int)baos.Length; - } - - } - - /// The prefix for the header encoder options: 'H' - public const char OPT_PREFIX = 'H'; - - /// The list of parameters that are accepted for the header encoder - /// module. Options for this modules start with 'H'. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'pinfo'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly System.String[][] pinfo = new System.String[][] { new System.String[] { "Hjj2000_COM", null, "Writes or not the JJ2000 COM marker in the " + "codestream", "off" }, new System.String[] { "HCOM", "[#[#]]", "Adds COM marker segments in the codestream. Comments must be " + "separated with '#' and are written into distinct maker segments.", null } }; - - /// Nominal range bit of the component defining default values in QCD for - /// main header - /// - private int defimgn; - - /// Nominal range bit of the component defining default values in QCD for - /// tile headers - /// - private int deftilenr; - - /// The number of components in the image - private int nComp; - - /// Whether or not to write the JJ2000 COM marker segment - private bool enJJ2KMarkSeg = true; - - /// Other COM marker segments specified in the command line - private System.String otherCOMMarkSeg = null; - - /// The ByteArrayOutputStream to store header data. This handler is kept - /// in order to use methods not accessible from a general - /// DataOutputStream. For the other methods, it's better to use variable - /// hbuf. - /// - /// - /// - /// - protected internal System.IO.MemoryStream baos; - - /// The DataOutputStream to store header data. This kind of object is - /// useful to write short, int, .... It's constructor takes baos as - /// parameter. - /// - /// - /// - /// - /// - //UPGRADE_TODO: Class 'java.io.DataOutputStream' was converted to 'System.IO.BinaryWriter' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioDataOutputStream'" - protected internal System.IO.BinaryWriter hbuf; - - /// The image data reader. Source of original data info - protected internal ImgData origSrc; - - /// An array specifying, for each component,if the data was signed or not - /// - /// - protected internal bool[] isOrigSig; - - /// Reference to the rate allocator - protected internal PostCompRateAllocator ralloc; - - /// Reference to the DWT module - protected internal ForwardWT dwt; - - /// Reference to the tiler module - protected internal Tiler tiler; - - /// Reference to the ROI module - protected internal ROIScaler roiSc; - - /// The encoder specifications - protected internal EncoderSpecs encSpec; - - /// Initializes the header writer with the references to the coding chain. - /// - /// - /// The original image data (before any component mixing, - /// tiling, etc.) - /// - /// - /// An array specifying for each component if it was - /// originally signed or not. - /// - /// - /// The discrete wavelet transform module. - /// - /// - /// The tiler module. - /// - /// - /// The encoder specifications - /// - /// - /// The ROI scaler module. - /// - /// - /// The post compression rate allocator. - /// - /// - /// ParameterList instance. - /// - /// - public HeaderEncoder(ImgData origsrc, bool[] isorigsig, ForwardWT dwt, Tiler tiler, EncoderSpecs encSpec, ROIScaler roiSc, PostCompRateAllocator ralloc, ParameterList pl) - { - pl.checkList(OPT_PREFIX, CSJ2K.j2k.util.ParameterList.toNameArray(pinfo)); - if (origsrc.NumComps != isorigsig.Length) - { - throw new System.ArgumentException(); - } - this.origSrc = origsrc; - this.isOrigSig = isorigsig; - this.dwt = dwt; - this.tiler = tiler; - this.encSpec = encSpec; - this.roiSc = roiSc; - this.ralloc = ralloc; - - baos = new System.IO.MemoryStream(); - //UPGRADE_TODO: Class 'java.io.DataOutputStream' was converted to 'System.IO.BinaryWriter' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioDataOutputStream'" - hbuf = new CSJ2K.Util.EndianBinaryWriter(baos, true); - nComp = origsrc.NumComps; - enJJ2KMarkSeg = pl.getBooleanParameter("Hjj2000_COM"); - otherCOMMarkSeg = pl.getParameter("HCOM"); - } - - /// Resets the contents of this HeaderEncoder to its initial state. It - /// erases all the data in the header buffer and reactualizes the - /// headerLength field of the bit stream writer. - /// - /// - public virtual void reset() - { - //UPGRADE_ISSUE: Method 'java.io.ByteArrayOutputStream.reset' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javaioByteArrayOutputStreamreset'" - // CONVERSION PROBLEM? - //baos.reset(); - baos.SetLength(0); - //UPGRADE_TODO: Class 'java.io.DataOutputStream' was converted to 'System.IO.BinaryWriter' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioDataOutputStream'" - hbuf = new CSJ2K.Util.EndianBinaryWriter(baos, true); //new System.IO.BinaryWriter(baos); - } - - /// Writes the header to the specified BinaryDataOutput. - /// - /// - /// Where to write the header. - /// - /// - public virtual void writeTo(BinaryDataOutput out_Renamed) - { - int i, len; - byte[] buf; - - buf = Buffer; - len = Length; - - for (i = 0; i < len; i++) - { - out_Renamed.writeByte(buf[i]); - } - } - - /// Writes the header to the specified OutputStream. - /// - /// - /// Where to write the header. - /// - /// - public virtual void writeTo(System.IO.Stream out_Renamed) - { - out_Renamed.Write(Buffer, 0, BufferLength); - } - - /// Start Of Codestream marker (SOC) signalling the beginning of a - /// codestream. - /// - /// - private void writeSOC() - { - hbuf.Write((System.Int16)CSJ2K.j2k.codestream.Markers.SOC); - } - - /// Writes SIZ marker segment of the codestream header. It is a fixed - /// information marker segment containing informations about image and tile - /// sizes. It is required in the main header immediately after SOC marker - /// segment. - /// - /// - private void writeSIZ() - { - int tmp; - - // SIZ marker - hbuf.Write((System.Int16)CSJ2K.j2k.codestream.Markers.SIZ); - - // Lsiz (Marker length) corresponding to - // Lsiz(2 bytes)+Rsiz(2)+Xsiz(4)+Ysiz(4)+XOsiz(4)+YOsiz(4)+ - // XTsiz(4)+YTsiz(4)+XTOsiz(4)+YTOsiz(4)+Csiz(2)+ - // (Ssiz(1)+XRsiz(1)+YRsiz(1))*nComp - // markSegLen = 38 + 3*nComp; - int markSegLen = 38 + 3 * nComp; - hbuf.Write((System.Int16)markSegLen); - - // Rsiz (codestream capabilities) - hbuf.Write((System.Int16)0); // JPEG 2000 - Part I - - // Xsiz (original image width) - hbuf.Write(tiler.ImgWidth + tiler.ImgULX); - - // Ysiz (original image height) - hbuf.Write(tiler.ImgHeight + tiler.ImgULY); - - // XOsiz (horizontal offset from the origin of the reference - // grid to the left side of the image area) - hbuf.Write(tiler.ImgULX); - - // YOsiz (vertical offset from the origin of the reference - // grid to the top side of the image area) - hbuf.Write(tiler.ImgULY); - - // XTsiz (nominal tile width) - hbuf.Write(tiler.NomTileWidth); - - // YTsiz (nominal tile height) - hbuf.Write(tiler.NomTileHeight); - - Coord torig = tiler.getTilingOrigin(null); - // XTOsiz (Horizontal offset from the origin of the reference - // grid to the left side of the first tile) - hbuf.Write(torig.x); - - // YTOsiz (Vertical offset from the origin of the reference - // grid to the top side of the first tile) - hbuf.Write(torig.y); - - // Csiz (number of components) - hbuf.Write((System.Int16)nComp); - - // Bit-depth and downsampling factors. - for (int c = 0; c < nComp; c++) - { - // Loop on each component - - // Ssiz bit-depth before mixing - tmp = origSrc.getNomRangeBits(c) - 1; - - tmp |= ((isOrigSig[c] ? 1 : 0) << CSJ2K.j2k.codestream.Markers.SSIZ_DEPTH_BITS); - hbuf.Write((System.Byte)tmp); - - // XRsiz (component sub-sampling value x-wise) - hbuf.Write((System.Byte)tiler.getCompSubsX(c)); - - // YRsiz (component sub-sampling value y-wise) - hbuf.Write((System.Byte)tiler.getCompSubsY(c)); - } // End loop on each component - } - - /// Writes COD marker segment. COD is a functional marker segment - /// containing the code style default (coding style, decomposition, - /// layering) used for compressing all the components in an image. - /// - ///

    The values can be overriden for an individual component by a COC - /// marker in either the main or the tile header.

    - /// - ///
    - /// Flag indicating whether this marker belongs to the main - /// header - /// - /// - /// Tile index if the marker belongs to a tile-part header - /// - /// - /// - /// - /// - protected internal virtual void writeCOD(bool mh, int tileIdx) - { - AnWTFilter[][] filt; - bool precinctPartitionUsed; - int tmp; - int mrl = 0, a = 0; - int ppx = 0, ppy = 0; - Progression[] prog; - - if (mh) - { - mrl = ((System.Int32)encSpec.dls.getDefault()); - // get default precinct size - ppx = encSpec.pss.getPPX(-1, -1, mrl); - ppy = encSpec.pss.getPPY(-1, -1, mrl); - prog = (Progression[])(encSpec.pocs.getDefault()); - } - else - { - mrl = ((System.Int32)encSpec.dls.getTileDef(tileIdx)); - // get precinct size for specified tile - ppx = encSpec.pss.getPPX(tileIdx, -1, mrl); - ppy = encSpec.pss.getPPY(tileIdx, -1, mrl); - prog = (Progression[])(encSpec.pocs.getTileDef(tileIdx)); - } - - if (ppx != CSJ2K.j2k.codestream.Markers.PRECINCT_PARTITION_DEF_SIZE || ppy != CSJ2K.j2k.codestream.Markers.PRECINCT_PARTITION_DEF_SIZE) - { - precinctPartitionUsed = true; - } - else - { - precinctPartitionUsed = false; - } - - if (precinctPartitionUsed) - { - // If precinct partition is used we add one byte per resolution - // level i.e. mrl+1 (+1 for resolution 0). - a = mrl + 1; - } - - // Write COD marker - hbuf.Write((System.Int16)CSJ2K.j2k.codestream.Markers.COD); - - // Lcod (marker segment length (in bytes)) Basic : Lcod(2 - // bytes)+Scod(1)+SGcod(4)+SPcod(5+a) where: - // a=0 if no precinct partition is used - // a=mrl+1 if precinct partition used - int markSegLen = 12 + a; - hbuf.Write((System.Int16)markSegLen); - - // Scod (coding style parameter) - tmp = 0; - if (precinctPartitionUsed) - { - tmp = CSJ2K.j2k.codestream.Markers.SCOX_PRECINCT_PARTITION; - } - - // Are SOP markers used ? - if (mh) - { - //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Object.toString' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" - if (((System.String)encSpec.sops.getDefault().ToString()).ToUpper().Equals("on".ToUpper())) - { - tmp |= CSJ2K.j2k.codestream.Markers.SCOX_USE_SOP; - } - } - else - { - //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Object.toString' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" - if (((System.String)encSpec.sops.getTileDef(tileIdx).ToString()).ToUpper().Equals("on".ToUpper())) - { - tmp |= CSJ2K.j2k.codestream.Markers.SCOX_USE_SOP; - } - } - - // Are EPH markers used ? - if (mh) - { - //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Object.toString' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" - if (((System.String)encSpec.ephs.getDefault().ToString()).ToUpper().Equals("on".ToUpper())) - { - tmp |= CSJ2K.j2k.codestream.Markers.SCOX_USE_EPH; - } - } - else - { - //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Object.toString' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" - if (((System.String)encSpec.ephs.getTileDef(tileIdx).ToString()).ToUpper().Equals("on".ToUpper())) - { - tmp |= CSJ2K.j2k.codestream.Markers.SCOX_USE_EPH; - } - } - if (dwt.CbULX != 0) - tmp |= CSJ2K.j2k.codestream.Markers.SCOX_HOR_CB_PART; - if (dwt.CbULY != 0) - tmp |= CSJ2K.j2k.codestream.Markers.SCOX_VER_CB_PART; - hbuf.Write((System.Byte)tmp); - - // SGcod - // Progression order - hbuf.Write((System.Byte)prog[0].type); - - // Number of layers - hbuf.Write((System.Int16)ralloc.NumLayers); - - // Multiple component transform - // CSsiz (Color transform) - System.String str = null; - if (mh) - { - str = ((System.String)encSpec.cts.getDefault()); - } - else - { - str = ((System.String)encSpec.cts.getTileDef(tileIdx)); - } - - if (str.Equals("none")) - { - hbuf.Write((System.Byte)0); - } - else - { - hbuf.Write((System.Byte)1); - } - - // SPcod - // Number of decomposition levels - hbuf.Write((System.Byte)mrl); - - // Code-block width and height - if (mh) - { - // main header, get default values - tmp = encSpec.cblks.getCBlkWidth(ModuleSpec.SPEC_DEF, -1, -1); - hbuf.Write((System.Byte)(MathUtil.log2(tmp) - 2)); - tmp = encSpec.cblks.getCBlkHeight(ModuleSpec.SPEC_DEF, -1, -1); - hbuf.Write((System.Byte)(MathUtil.log2(tmp) - 2)); - } - else - { - // tile header, get tile default values - tmp = encSpec.cblks.getCBlkWidth(ModuleSpec.SPEC_TILE_DEF, tileIdx, -1); - hbuf.Write((System.Byte)(MathUtil.log2(tmp) - 2)); - tmp = encSpec.cblks.getCBlkHeight(ModuleSpec.SPEC_TILE_DEF, tileIdx, -1); - hbuf.Write((System.Byte)(MathUtil.log2(tmp) - 2)); - } - - // Style of the code-block coding passes - tmp = 0; - if (mh) - { - // Main header - // Selective arithmetic coding bypass ? - if (((System.String)encSpec.bms.getDefault()).Equals("on")) - { - tmp |= CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_BYPASS; - } - // MQ reset after each coding pass ? - if (((System.String)encSpec.mqrs.getDefault()).Equals("on")) - { - tmp |= CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_RESET_MQ; - } - // MQ termination after each arithmetically coded coding pass ? - if (((System.String)encSpec.rts.getDefault()).Equals("on")) - { - tmp |= CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_TERM_PASS; - } - // Vertically stripe-causal context mode ? - if (((System.String)encSpec.css.getDefault()).Equals("on")) - { - tmp |= CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_VERT_STR_CAUSAL; - } - // Predictable termination ? - if (((System.String)encSpec.tts.getDefault()).Equals("predict")) - { - tmp |= CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_PRED_TERM; - } - // Error resilience segmentation symbol insertion ? - if (((System.String)encSpec.sss.getDefault()).Equals("on")) - { - tmp |= CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_SEG_SYMBOLS; - } - } - else - { - // Tile header - // Selective arithmetic coding bypass ? - if (((System.String)encSpec.bms.getTileDef(tileIdx)).Equals("on")) - { - tmp |= CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_BYPASS; - } - // MQ reset after each coding pass ? - if (((System.String)encSpec.mqrs.getTileDef(tileIdx)).Equals("on")) - { - tmp |= CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_RESET_MQ; - } - // MQ termination after each arithmetically coded coding pass ? - if (((System.String)encSpec.rts.getTileDef(tileIdx)).Equals("on")) - { - tmp |= CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_TERM_PASS; - } - // Vertically stripe-causal context mode ? - if (((System.String)encSpec.css.getTileDef(tileIdx)).Equals("on")) - { - tmp |= CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_VERT_STR_CAUSAL; - } - // Predictable termination ? - if (((System.String)encSpec.tts.getTileDef(tileIdx)).Equals("predict")) - { - tmp |= CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_PRED_TERM; - } - // Error resilience segmentation symbol insertion ? - if (((System.String)encSpec.sss.getTileDef(tileIdx)).Equals("on")) - { - tmp |= CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_SEG_SYMBOLS; - } - } - hbuf.Write((System.Byte)tmp); - - // Wavelet transform - // Wavelet Filter - if (mh) - { - filt = ((AnWTFilter[][])encSpec.wfs.getDefault()); - hbuf.Write((System.Byte)filt[0][0].FilterType); - } - else - { - filt = ((AnWTFilter[][])encSpec.wfs.getTileDef(tileIdx)); - hbuf.Write((System.Byte)filt[0][0].FilterType); - } - - // Precinct partition - if (precinctPartitionUsed) - { - // Write the precinct size for each resolution level + 1 - // (resolution 0) if precinct partition is used. - System.Collections.ArrayList[] v = null; - if (mh) - { - v = (System.Collections.ArrayList[])encSpec.pss.getDefault(); - } - else - { - v = (System.Collections.ArrayList[])encSpec.pss.getTileDef(tileIdx); - } - for (int r = mrl; r >= 0; r--) - { - if (r >= v[1].Count) - { - tmp = ((System.Int32)v[1][v[1].Count - 1]); - } - else - { - tmp = ((System.Int32)v[1][r]); - } - int yExp = (MathUtil.log2(tmp) << 4) & 0x00F0; - - if (r >= v[0].Count) - { - tmp = ((System.Int32)v[0][v[0].Count - 1]); - } - else - { - tmp = ((System.Int32)v[0][r]); - } - int xExp = MathUtil.log2(tmp) & 0x000F; - hbuf.Write((System.Byte)(yExp | xExp)); - } - } - } - - /// Writes COC marker segment . It is a functional marker containing the - /// coding style for one component (coding style, decomposition, layering). - /// - ///

    Its values overrides any value previously set in COD in the main - /// header or in the tile header.

    - /// - ///
    - /// Flag indicating whether the main header is to be written. - /// - /// - /// Tile index. - /// - /// - /// index of the component which need use of the COC marker - /// segment. - /// - /// - /// - /// - /// - protected internal virtual void writeCOC(bool mh, int tileIdx, int compIdx) - { - AnWTFilter[][] filt; - bool precinctPartitionUsed; - int tmp; - int mrl = 0, a = 0; - int ppx = 0, ppy = 0; - Progression[] prog; - - if (mh) - { - mrl = ((System.Int32)encSpec.dls.getCompDef(compIdx)); - // Get precinct size for specified component - ppx = encSpec.pss.getPPX(-1, compIdx, mrl); - ppy = encSpec.pss.getPPY(-1, compIdx, mrl); - prog = (Progression[])(encSpec.pocs.getCompDef(compIdx)); - } - else - { - mrl = ((System.Int32)encSpec.dls.getTileCompVal(tileIdx, compIdx)); - // Get precinct size for specified component/tile - ppx = encSpec.pss.getPPX(tileIdx, compIdx, mrl); - ppy = encSpec.pss.getPPY(tileIdx, compIdx, mrl); - prog = (Progression[])(encSpec.pocs.getTileCompVal(tileIdx, compIdx)); - } - - if (ppx != CSJ2K.j2k.codestream.Markers.PRECINCT_PARTITION_DEF_SIZE || ppy != CSJ2K.j2k.codestream.Markers.PRECINCT_PARTITION_DEF_SIZE) - { - precinctPartitionUsed = true; - } - else - { - precinctPartitionUsed = false; - } - if (precinctPartitionUsed) - { - // If precinct partition is used we add one byte per resolution - // level i.e. mrl+1 (+1 for resolution 0). - a = mrl + 1; - } - - // COC marker - hbuf.Write((System.Int16)CSJ2K.j2k.codestream.Markers.COC); - - // Lcoc (marker segment length (in bytes)) - // Basic: Lcoc(2 bytes)+Scoc(1)+ Ccoc(1 or 2)+SPcod(5+a) - int markSegLen = 8 + ((nComp < 257) ? 1 : 2) + a; - - // Rounded to the nearest even value greater or equals - hbuf.Write((System.Int16)markSegLen); - - // Ccoc - if (nComp < 257) - { - hbuf.Write((System.Byte)compIdx); - } - else - { - hbuf.Write((System.Int16)compIdx); - } - - // Scod (coding style parameter) - tmp = 0; - if (precinctPartitionUsed) - { - tmp = CSJ2K.j2k.codestream.Markers.SCOX_PRECINCT_PARTITION; - } - hbuf.Write((System.Byte)tmp); - - - // SPcoc - - // Number of decomposition levels - hbuf.Write((System.Byte)mrl); - - // Code-block width and height - if (mh) - { - // main header, get component default values - tmp = encSpec.cblks.getCBlkWidth(ModuleSpec.SPEC_COMP_DEF, -1, compIdx); - hbuf.Write((System.Byte)(MathUtil.log2(tmp) - 2)); - tmp = encSpec.cblks.getCBlkHeight(ModuleSpec.SPEC_COMP_DEF, -1, compIdx); - hbuf.Write((System.Byte)(MathUtil.log2(tmp) - 2)); - } - else - { - // tile header, get tile component values - tmp = encSpec.cblks.getCBlkWidth(ModuleSpec.SPEC_TILE_COMP, tileIdx, compIdx); - hbuf.Write((System.Byte)(MathUtil.log2(tmp) - 2)); - tmp = encSpec.cblks.getCBlkHeight(ModuleSpec.SPEC_TILE_COMP, tileIdx, compIdx); - hbuf.Write((System.Byte)(MathUtil.log2(tmp) - 2)); - } - - // Entropy coding mode options - tmp = 0; - if (mh) - { - // Main header - // Lazy coding mode ? - if (((System.String)encSpec.bms.getCompDef(compIdx)).Equals("on")) - { - tmp |= CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_BYPASS; - } - // MQ reset after each coding pass ? - if (((System.String)encSpec.mqrs.getCompDef(compIdx)).ToUpper().Equals("on".ToUpper())) - { - tmp |= CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_RESET_MQ; - } - // MQ termination after each arithmetically coded coding pass ? - if (((System.String)encSpec.rts.getCompDef(compIdx)).Equals("on")) - { - tmp |= CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_TERM_PASS; - } - // Vertically stripe-causal context mode ? - if (((System.String)encSpec.css.getCompDef(compIdx)).Equals("on")) - { - tmp |= CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_VERT_STR_CAUSAL; - } - // Predictable termination ? - if (((System.String)encSpec.tts.getCompDef(compIdx)).Equals("predict")) - { - tmp |= CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_PRED_TERM; - } - // Error resilience segmentation symbol insertion ? - if (((System.String)encSpec.sss.getCompDef(compIdx)).Equals("on")) - { - tmp |= CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_SEG_SYMBOLS; - } - } - else - { - // Tile Header - if (((System.String)encSpec.bms.getTileCompVal(tileIdx, compIdx)).Equals("on")) - { - tmp |= CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_BYPASS; - } - // MQ reset after each coding pass ? - if (((System.String)encSpec.mqrs.getTileCompVal(tileIdx, compIdx)).Equals("on")) - { - tmp |= CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_RESET_MQ; - } - // MQ termination after each arithmetically coded coding pass ? - if (((System.String)encSpec.rts.getTileCompVal(tileIdx, compIdx)).Equals("on")) - { - tmp |= CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_TERM_PASS; - } - // Vertically stripe-causal context mode ? - if (((System.String)encSpec.css.getTileCompVal(tileIdx, compIdx)).Equals("on")) - { - tmp |= CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_VERT_STR_CAUSAL; - } - // Predictable termination ? - if (((System.String)encSpec.tts.getTileCompVal(tileIdx, compIdx)).Equals("predict")) - { - tmp |= CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_PRED_TERM; - } - // Error resilience segmentation symbol insertion ? - if (((System.String)encSpec.sss.getTileCompVal(tileIdx, compIdx)).Equals("on")) - { - tmp |= CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_SEG_SYMBOLS; - } - } - hbuf.Write((System.Byte)tmp); - - // Wavelet transform - // Wavelet Filter - if (mh) - { - filt = ((AnWTFilter[][])encSpec.wfs.getCompDef(compIdx)); - hbuf.Write((System.Byte)filt[0][0].FilterType); - } - else - { - filt = ((AnWTFilter[][])encSpec.wfs.getTileCompVal(tileIdx, compIdx)); - hbuf.Write((System.Byte)filt[0][0].FilterType); - } - - // Precinct partition - if (precinctPartitionUsed) - { - // Write the precinct size for each resolution level + 1 - // (resolution 0) if precinct partition is used. - System.Collections.ArrayList[] v = null; - if (mh) - { - v = (System.Collections.ArrayList[])encSpec.pss.getCompDef(compIdx); - } - else - { - v = (System.Collections.ArrayList[])encSpec.pss.getTileCompVal(tileIdx, compIdx); - } - for (int r = mrl; r >= 0; r--) - { - if (r >= v[1].Count) - { - tmp = ((System.Int32)v[1][v[1].Count - 1]); - } - else - { - tmp = ((System.Int32)v[1][r]); - } - int yExp = (MathUtil.log2(tmp) << 4) & 0x00F0; - - if (r >= v[0].Count) - { - tmp = ((System.Int32)v[0][v[0].Count - 1]); - } - else - { - tmp = ((System.Int32)v[0][r]); - } - int xExp = MathUtil.log2(tmp) & 0x000F; - hbuf.Write((System.Byte)(yExp | xExp)); - } - } - } - - /// Writes QCD marker segment in main header. QCD is a functional marker - /// segment countaining the quantization default used for compressing all - /// the components in an image. The values can be overriden for an - /// individual component by a QCC marker in either the main or the tile - /// header. - /// - /// - protected internal virtual void writeMainQCD() - { - int mrl; - int qstyle; - - float step; - - System.String qType = (System.String)encSpec.qts.getDefault(); - //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Float.floatValue' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" - float baseStep = (float)((System.Single)encSpec.qsss.getDefault()); - int gb = ((System.Int32)encSpec.gbs.getDefault()); - - bool isDerived = qType.Equals("derived"); - bool isReversible = qType.Equals("reversible"); - - mrl = ((System.Int32)encSpec.dls.getDefault()); - - int nt = dwt.getNumTiles(); - int nc = dwt.NumComps; - int tmpI; - int[] tcIdx = new int[2]; - System.String tmpStr; - bool notFound = true; - for (int t = 0; t < nt && notFound; t++) - { - for (int c = 0; c < nc && notFound; c++) - { - tmpI = ((System.Int32)encSpec.dls.getTileCompVal(t, c)); - tmpStr = ((System.String)encSpec.qts.getTileCompVal(t, c)); - if (tmpI == mrl && tmpStr.Equals(qType)) - { - tcIdx[0] = t; tcIdx[1] = c; - notFound = false; - } - } - } - if (notFound) - { - throw new System.ApplicationException("Default representative for quantization type " + " and number of decomposition levels not found " + " in main QCD marker segment. " + "You have found a JJ2000 bug."); - } - SubbandAn sb, csb, sbRoot = dwt.getAnSubbandTree(tcIdx[0], tcIdx[1]); - defimgn = dwt.getNomRangeBits(tcIdx[1]); - - int nqcd; // Number of quantization step-size to transmit - - // Get the quantization style - qstyle = (isReversible) ? CSJ2K.j2k.codestream.Markers.SQCX_NO_QUANTIZATION : ((isDerived) ? CSJ2K.j2k.codestream.Markers.SQCX_SCALAR_DERIVED : CSJ2K.j2k.codestream.Markers.SQCX_SCALAR_EXPOUNDED); - - // QCD marker - hbuf.Write((System.Int16)CSJ2K.j2k.codestream.Markers.QCD); - - // Compute the number of steps to send - switch (qstyle) - { - - case CSJ2K.j2k.codestream.Markers.SQCX_SCALAR_DERIVED: - nqcd = 1; // Just the LL value - break; - - case CSJ2K.j2k.codestream.Markers.SQCX_NO_QUANTIZATION: - case CSJ2K.j2k.codestream.Markers.SQCX_SCALAR_EXPOUNDED: - // One value per subband - nqcd = 0; - - sb = sbRoot; - - // Get the subband at first resolution level - sb = (SubbandAn)sb.getSubbandByIdx(0, 0); - - // Count total number of subbands - for (int j = 0; j <= mrl; j++) - { - csb = sb; - while (csb != null) - { - nqcd++; - csb = (SubbandAn)csb.nextSubband(); - } - // Go up one resolution level - sb = (SubbandAn)sb.NextResLevel; - } - break; - - default: - throw new System.ApplicationException("Internal JJ2000 error"); - - } - - // Lqcd (marker segment length (in bytes)) - // Lqcd(2 bytes)+Sqcd(1)+ SPqcd (2*Nqcd) - int markSegLen = 3 + ((isReversible) ? nqcd : 2 * nqcd); - - // Rounded to the nearest even value greater or equals - hbuf.Write((System.Int16)markSegLen); - - // Sqcd - hbuf.Write((System.Byte)(qstyle + (gb << CSJ2K.j2k.codestream.Markers.SQCX_GB_SHIFT))); - - // SPqcd - switch (qstyle) - { - - case CSJ2K.j2k.codestream.Markers.SQCX_NO_QUANTIZATION: - sb = sbRoot; - sb = (SubbandAn)sb.getSubbandByIdx(0, 0); - - // Output one exponent per subband - for (int j = 0; j <= mrl; j++) - { - csb = sb; - while (csb != null) - { - int tmp = (defimgn + csb.anGainExp); - hbuf.Write((System.Byte)(tmp << CSJ2K.j2k.codestream.Markers.SQCX_EXP_SHIFT)); - - csb = (SubbandAn)csb.nextSubband(); - // Go up one resolution level - } - sb = (SubbandAn)sb.NextResLevel; - } - break; - - case CSJ2K.j2k.codestream.Markers.SQCX_SCALAR_DERIVED: - sb = sbRoot; - sb = (SubbandAn)sb.getSubbandByIdx(0, 0); - - // Calculate subband step (normalized to unit - // dynamic range) - step = baseStep / (1 << sb.level); - - // Write exponent-mantissa, 16 bits - hbuf.Write((System.Int16)StdQuantizer.convertToExpMantissa(step)); - break; - - case CSJ2K.j2k.codestream.Markers.SQCX_SCALAR_EXPOUNDED: - sb = sbRoot; - sb = (SubbandAn)sb.getSubbandByIdx(0, 0); - - // Output one step per subband - for (int j = 0; j <= mrl; j++) - { - csb = sb; - while (csb != null) - { - // Calculate subband step (normalized to unit - // dynamic range) - step = baseStep / (csb.l2Norm * (1 << csb.anGainExp)); - - // Write exponent-mantissa, 16 bits - hbuf.Write((System.Int16)StdQuantizer.convertToExpMantissa(step)); - - csb = (SubbandAn)csb.nextSubband(); - } - // Go up one resolution level - sb = (SubbandAn)sb.NextResLevel; - } - break; - - default: - throw new System.ApplicationException("Internal JJ2000 error"); - - } - } - - /// Writes QCC marker segment in main header. It is a functional marker - /// segment countaining the quantization used for compressing the specified - /// component in an image. The values override for the specified component - /// what was defined by a QCC marker in either the main or the tile header. - /// - /// - /// Index of the component which needs QCC marker segment. - /// - /// - protected internal virtual void writeMainQCC(int compIdx) - { - - int mrl; - int qstyle; - int tIdx = 0; - float step; - - SubbandAn sb, sb2; - SubbandAn sbRoot; - - int imgnr = dwt.getNomRangeBits(compIdx); - System.String qType = (System.String)encSpec.qts.getCompDef(compIdx); - //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Float.floatValue' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" - float baseStep = (float)((System.Single)encSpec.qsss.getCompDef(compIdx)); - int gb = ((System.Int32)encSpec.gbs.getCompDef(compIdx)); - - bool isReversible = qType.Equals("reversible"); - bool isDerived = qType.Equals("derived"); - - mrl = ((System.Int32)encSpec.dls.getCompDef(compIdx)); - - int nt = dwt.getNumTiles(); - int nc = dwt.NumComps; - int tmpI; - System.String tmpStr; - bool notFound = true; - for (int t = 0; t < nt && notFound; t++) - { - for (int c = 0; c < nc && notFound; c++) - { - tmpI = ((System.Int32)encSpec.dls.getTileCompVal(t, c)); - tmpStr = ((System.String)encSpec.qts.getTileCompVal(t, c)); - if (tmpI == mrl && tmpStr.Equals(qType)) - { - tIdx = t; - notFound = false; - } - } - } - if (notFound) - { - throw new System.ApplicationException("Default representative for quantization type " + " and number of decomposition levels not found " + " in main QCC (c=" + compIdx + ") marker segment. " + "You have found a JJ2000 bug."); - } - sbRoot = dwt.getAnSubbandTree(tIdx, compIdx); - - int nqcc; // Number of quantization step-size to transmit - - // Get the quantization style - if (isReversible) - { - qstyle = CSJ2K.j2k.codestream.Markers.SQCX_NO_QUANTIZATION; - } - else if (isDerived) - { - qstyle = CSJ2K.j2k.codestream.Markers.SQCX_SCALAR_DERIVED; - } - else - { - qstyle = CSJ2K.j2k.codestream.Markers.SQCX_SCALAR_EXPOUNDED; - } - - // QCC marker - hbuf.Write((System.Int16)CSJ2K.j2k.codestream.Markers.QCC); - - // Compute the number of steps to send - switch (qstyle) - { - - case CSJ2K.j2k.codestream.Markers.SQCX_SCALAR_DERIVED: - nqcc = 1; // Just the LL value - break; - - case CSJ2K.j2k.codestream.Markers.SQCX_NO_QUANTIZATION: - case CSJ2K.j2k.codestream.Markers.SQCX_SCALAR_EXPOUNDED: - // One value per subband - nqcc = 0; - - sb = sbRoot; - mrl = sb.resLvl; - - // Get the subband at first resolution level - sb = (SubbandAn)sb.getSubbandByIdx(0, 0); - - // Find root element for LL subband - while (sb.resLvl != 0) - { - sb = sb.subb_LL; - } - - // Count total number of subbands - for (int j = 0; j <= mrl; j++) - { - sb2 = sb; - while (sb2 != null) - { - nqcc++; - sb2 = (SubbandAn)sb2.nextSubband(); - } - // Go up one resolution level - sb = (SubbandAn)sb.NextResLevel; - } - break; - - default: - throw new System.ApplicationException("Internal JJ2000 error"); - - } - - // Lqcc (marker segment length (in bytes)) - // Lqcc(2 bytes)+Cqcc(1 or 2)+Sqcc(1)+ SPqcc (2*Nqcc) - int markSegLen = 3 + ((nComp < 257) ? 1 : 2) + ((isReversible) ? nqcc : 2 * nqcc); - hbuf.Write((System.Int16)markSegLen); - - // Cqcc - if (nComp < 257) - { - hbuf.Write((System.Byte)compIdx); - } - else - { - hbuf.Write((System.Int16)compIdx); - } - - // Sqcc (quantization style) - hbuf.Write((System.Byte)(qstyle + (gb << CSJ2K.j2k.codestream.Markers.SQCX_GB_SHIFT))); - - // SPqcc - switch (qstyle) - { - - case CSJ2K.j2k.codestream.Markers.SQCX_NO_QUANTIZATION: - // Get resolution level 0 subband - sb = sbRoot; - sb = (SubbandAn)sb.getSubbandByIdx(0, 0); - - // Output one exponent per subband - for (int j = 0; j <= mrl; j++) - { - sb2 = sb; - while (sb2 != null) - { - int tmp = (imgnr + sb2.anGainExp); - hbuf.Write((System.Byte)(tmp << CSJ2K.j2k.codestream.Markers.SQCX_EXP_SHIFT)); - - sb2 = (SubbandAn)sb2.nextSubband(); - } - // Go up one resolution level - sb = (SubbandAn)sb.NextResLevel; - } - break; - - case CSJ2K.j2k.codestream.Markers.SQCX_SCALAR_DERIVED: - // Get resolution level 0 subband - sb = sbRoot; - sb = (SubbandAn)sb.getSubbandByIdx(0, 0); - - // Calculate subband step (normalized to unit - // dynamic range) - step = baseStep / (1 << sb.level); - - // Write exponent-mantissa, 16 bits - hbuf.Write((System.Int16)StdQuantizer.convertToExpMantissa(step)); - break; - - case CSJ2K.j2k.codestream.Markers.SQCX_SCALAR_EXPOUNDED: - // Get resolution level 0 subband - sb = sbRoot; - mrl = sb.resLvl; - - sb = (SubbandAn)sb.getSubbandByIdx(0, 0); - - for (int j = 0; j <= mrl; j++) - { - sb2 = sb; - while (sb2 != null) - { - // Calculate subband step (normalized to unit - // dynamic range) - step = baseStep / (sb2.l2Norm * (1 << sb2.anGainExp)); - - // Write exponent-mantissa, 16 bits - hbuf.Write((System.Int16)StdQuantizer.convertToExpMantissa(step)); - sb2 = (SubbandAn)sb2.nextSubband(); - } - // Go up one resolution level - sb = (SubbandAn)sb.NextResLevel; - } - break; - - default: - throw new System.ApplicationException("Internal JJ2000 error"); - - } - } - - /// Writes QCD marker segment in tile header. QCD is a functional marker - /// segment countaining the quantization default used for compressing all - /// the components in an image. The values can be overriden for an - /// individual component by a QCC marker in either the main or the tile - /// header. - /// - /// - /// Tile index - /// - /// - protected internal virtual void writeTileQCD(int tIdx) - { - int mrl; - int qstyle; - - float step; - SubbandAn sb, csb, sbRoot; - - System.String qType = (System.String)encSpec.qts.getTileDef(tIdx); - //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Float.floatValue' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" - float baseStep = (float)((System.Single)encSpec.qsss.getTileDef(tIdx)); - mrl = ((System.Int32)encSpec.dls.getTileDef(tIdx)); - - int nc = dwt.NumComps; - int tmpI; - System.String tmpStr; - bool notFound = true; - int compIdx = 0; - for (int c = 0; c < nc && notFound; c++) - { - tmpI = ((System.Int32)encSpec.dls.getTileCompVal(tIdx, c)); - tmpStr = ((System.String)encSpec.qts.getTileCompVal(tIdx, c)); - if (tmpI == mrl && tmpStr.Equals(qType)) - { - compIdx = c; - notFound = false; - } - } - if (notFound) - { - throw new System.ApplicationException("Default representative for quantization type " + " and number of decomposition levels not found " + " in tile QCD (t=" + tIdx + ") marker segment. " + "You have found a JJ2000 bug."); - } - - sbRoot = dwt.getAnSubbandTree(tIdx, compIdx); - deftilenr = dwt.getNomRangeBits(compIdx); - int gb = ((System.Int32)encSpec.gbs.getTileDef(tIdx)); - - bool isDerived = qType.Equals("derived"); - bool isReversible = qType.Equals("reversible"); - - int nqcd; // Number of quantization step-size to transmit - - // Get the quantization style - qstyle = (isReversible) ? CSJ2K.j2k.codestream.Markers.SQCX_NO_QUANTIZATION : ((isDerived) ? CSJ2K.j2k.codestream.Markers.SQCX_SCALAR_DERIVED : CSJ2K.j2k.codestream.Markers.SQCX_SCALAR_EXPOUNDED); - - // QCD marker - hbuf.Write((System.Int16)CSJ2K.j2k.codestream.Markers.QCD); - - // Compute the number of steps to send - switch (qstyle) - { - - case CSJ2K.j2k.codestream.Markers.SQCX_SCALAR_DERIVED: - nqcd = 1; // Just the LL value - break; - - case CSJ2K.j2k.codestream.Markers.SQCX_NO_QUANTIZATION: - case CSJ2K.j2k.codestream.Markers.SQCX_SCALAR_EXPOUNDED: - // One value per subband - nqcd = 0; - - sb = sbRoot; - - // Get the subband at first resolution level - sb = (SubbandAn)sb.getSubbandByIdx(0, 0); - - // Count total number of subbands - for (int j = 0; j <= mrl; j++) - { - csb = sb; - while (csb != null) - { - nqcd++; - csb = (SubbandAn)csb.nextSubband(); - } - // Go up one resolution level - sb = (SubbandAn)sb.NextResLevel; - } - break; - - default: - throw new System.ApplicationException("Internal JJ2000 error"); - - } - - // Lqcd (marker segment length (in bytes)) - // Lqcd(2 bytes)+Sqcd(1)+ SPqcd (2*Nqcd) - int markSegLen = 3 + ((isReversible) ? nqcd : 2 * nqcd); - - // Rounded to the nearest even value greater or equals - hbuf.Write((System.Int16)markSegLen); - - // Sqcd - hbuf.Write((System.Byte)(qstyle + (gb << CSJ2K.j2k.codestream.Markers.SQCX_GB_SHIFT))); - - // SPqcd - switch (qstyle) - { - - case CSJ2K.j2k.codestream.Markers.SQCX_NO_QUANTIZATION: - sb = sbRoot; - sb = (SubbandAn)sb.getSubbandByIdx(0, 0); - - // Output one exponent per subband - for (int j = 0; j <= mrl; j++) - { - csb = sb; - while (csb != null) - { - int tmp = (deftilenr + csb.anGainExp); - hbuf.Write((System.Byte)(tmp << CSJ2K.j2k.codestream.Markers.SQCX_EXP_SHIFT)); - - csb = (SubbandAn)csb.nextSubband(); - // Go up one resolution level - } - sb = (SubbandAn)sb.NextResLevel; - } - break; - - case CSJ2K.j2k.codestream.Markers.SQCX_SCALAR_DERIVED: - sb = sbRoot; - sb = (SubbandAn)sb.getSubbandByIdx(0, 0); - - // Calculate subband step (normalized to unit - // dynamic range) - step = baseStep / (1 << sb.level); - - // Write exponent-mantissa, 16 bits - hbuf.Write((System.Int16)StdQuantizer.convertToExpMantissa(step)); - break; - - case CSJ2K.j2k.codestream.Markers.SQCX_SCALAR_EXPOUNDED: - sb = sbRoot; - sb = (SubbandAn)sb.getSubbandByIdx(0, 0); - - // Output one step per subband - for (int j = 0; j <= mrl; j++) - { - csb = sb; - while (csb != null) - { - // Calculate subband step (normalized to unit - // dynamic range) - step = baseStep / (csb.l2Norm * (1 << csb.anGainExp)); - - // Write exponent-mantissa, 16 bits - hbuf.Write((System.Int16)StdQuantizer.convertToExpMantissa(step)); - - csb = (SubbandAn)csb.nextSubband(); - } - // Go up one resolution level - sb = (SubbandAn)sb.NextResLevel; - } - break; - - default: - throw new System.ApplicationException("Internal JJ2000 error"); - - } - } - - /// Writes QCC marker segment in tile header. It is a functional marker - /// segment countaining the quantization used for compressing the specified - /// component in an image. The values override for the specified component - /// what was defined by a QCC marker in either the main or the tile header. - /// - /// - /// Tile index - /// - /// - /// Index of the component which needs QCC marker segment. - /// - /// - protected internal virtual void writeTileQCC(int t, int compIdx) - { - - int mrl; - int qstyle; - float step; - - SubbandAn sb, sb2; - int nqcc; // Number of quantization step-size to transmit - - SubbandAn sbRoot = dwt.getAnSubbandTree(t, compIdx); - int imgnr = dwt.getNomRangeBits(compIdx); - System.String qType = (System.String)encSpec.qts.getTileCompVal(t, compIdx); - //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Float.floatValue' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" - float baseStep = (float)((System.Single)encSpec.qsss.getTileCompVal(t, compIdx)); - int gb = ((System.Int32)encSpec.gbs.getTileCompVal(t, compIdx)); - - bool isReversible = qType.Equals("reversible"); - bool isDerived = qType.Equals("derived"); - - mrl = ((System.Int32)encSpec.dls.getTileCompVal(t, compIdx)); - - // Get the quantization style - if (isReversible) - { - qstyle = CSJ2K.j2k.codestream.Markers.SQCX_NO_QUANTIZATION; - } - else if (isDerived) - { - qstyle = CSJ2K.j2k.codestream.Markers.SQCX_SCALAR_DERIVED; - } - else - { - qstyle = CSJ2K.j2k.codestream.Markers.SQCX_SCALAR_EXPOUNDED; - } - - // QCC marker - hbuf.Write((System.Int16)CSJ2K.j2k.codestream.Markers.QCC); - - // Compute the number of steps to send - switch (qstyle) - { - - case CSJ2K.j2k.codestream.Markers.SQCX_SCALAR_DERIVED: - nqcc = 1; // Just the LL value - break; - - case CSJ2K.j2k.codestream.Markers.SQCX_NO_QUANTIZATION: - case CSJ2K.j2k.codestream.Markers.SQCX_SCALAR_EXPOUNDED: - // One value per subband - nqcc = 0; - - sb = sbRoot; - mrl = sb.resLvl; - - // Get the subband at first resolution level - sb = (SubbandAn)sb.getSubbandByIdx(0, 0); - - // Find root element for LL subband - while (sb.resLvl != 0) - { - sb = sb.subb_LL; - } - - // Count total number of subbands - for (int j = 0; j <= mrl; j++) - { - sb2 = sb; - while (sb2 != null) - { - nqcc++; - sb2 = (SubbandAn)sb2.nextSubband(); - } - // Go up one resolution level - sb = (SubbandAn)sb.NextResLevel; - } - break; - - default: - throw new System.ApplicationException("Internal JJ2000 error"); - - } - - // Lqcc (marker segment length (in bytes)) - // Lqcc(2 bytes)+Cqcc(1 or 2)+Sqcc(1)+ SPqcc (2*Nqcc) - int markSegLen = 3 + ((nComp < 257) ? 1 : 2) + ((isReversible) ? nqcc : 2 * nqcc); - hbuf.Write((System.Int16)markSegLen); - - // Cqcc - if (nComp < 257) - { - hbuf.Write((System.Byte)compIdx); - } - else - { - hbuf.Write((System.Int16)compIdx); - } - - // Sqcc (quantization style) - hbuf.Write((System.Byte)(qstyle + (gb << CSJ2K.j2k.codestream.Markers.SQCX_GB_SHIFT))); - - // SPqcc - switch (qstyle) - { - - case CSJ2K.j2k.codestream.Markers.SQCX_NO_QUANTIZATION: - // Get resolution level 0 subband - sb = sbRoot; - sb = (SubbandAn)sb.getSubbandByIdx(0, 0); - - // Output one exponent per subband - for (int j = 0; j <= mrl; j++) - { - sb2 = sb; - while (sb2 != null) - { - int tmp = (imgnr + sb2.anGainExp); - hbuf.Write((System.Byte)(tmp << CSJ2K.j2k.codestream.Markers.SQCX_EXP_SHIFT)); - - sb2 = (SubbandAn)sb2.nextSubband(); - } - // Go up one resolution level - sb = (SubbandAn)sb.NextResLevel; - } - break; - - case CSJ2K.j2k.codestream.Markers.SQCX_SCALAR_DERIVED: - // Get resolution level 0 subband - sb = sbRoot; - sb = (SubbandAn)sb.getSubbandByIdx(0, 0); - - // Calculate subband step (normalized to unit - // dynamic range) - step = baseStep / (1 << sb.level); - - // Write exponent-mantissa, 16 bits - hbuf.Write((System.Int16)StdQuantizer.convertToExpMantissa(step)); - break; - - case CSJ2K.j2k.codestream.Markers.SQCX_SCALAR_EXPOUNDED: - // Get resolution level 0 subband - sb = sbRoot; - mrl = sb.resLvl; - - sb = (SubbandAn)sb.getSubbandByIdx(0, 0); - - for (int j = 0; j <= mrl; j++) - { - sb2 = sb; - while (sb2 != null) - { - // Calculate subband step (normalized to unit - // dynamic range) - step = baseStep / (sb2.l2Norm * (1 << sb2.anGainExp)); - - // Write exponent-mantissa, 16 bits - hbuf.Write((System.Int16)StdQuantizer.convertToExpMantissa(step)); - sb2 = (SubbandAn)sb2.nextSubband(); - } - // Go up one resolution level - sb = (SubbandAn)sb.NextResLevel; - } - break; - - default: - throw new System.ApplicationException("Internal JJ2000 error"); - - } - } - - /// Writes POC marker segment. POC is a functional marker segment - /// containing the bounds and progression order for any progression order - /// other than default in the codestream. - /// - /// - /// Flag indicating whether the main header is to be written - /// - /// - /// Tile index - /// - /// - protected internal virtual void writePOC(bool mh, int tileIdx) - { - int markSegLen = 0; // Segment marker length - int lenCompField; // Holds the size of any component field as - // this size depends on the number of - //components - Progression[] prog = null; // Holds the progression(s) - int npoc; // Number of progression order changes - - // Get the progression order changes, their number and checks - // if it is ok - if (mh) - { - prog = (Progression[])(encSpec.pocs.getDefault()); - } - else - { - prog = (Progression[])(encSpec.pocs.getTileDef(tileIdx)); - } - - // Calculate the length of a component field (depends on the number of - // components) - lenCompField = (nComp < 257 ? 1 : 2); - - // POC marker - hbuf.Write((System.Int16)CSJ2K.j2k.codestream.Markers.POC); - - // Lpoc (marker segment length (in bytes)) - // Basic: Lpoc(2 bytes) + npoc * [ RSpoc(1) + CSpoc(1 or 2) + - // LYEpoc(2) + REpoc(1) + CEpoc(1 or 2) + Ppoc(1) ] - npoc = prog.Length; - markSegLen = 2 + npoc * (1 + lenCompField + 2 + 1 + lenCompField + 1); - hbuf.Write((System.Int16)markSegLen); - - // Write each progression order change - for (int i = 0; i < npoc; i++) - { - // RSpoc(i) - hbuf.Write((System.Byte)prog[i].rs); - // CSpoc(i) - if (lenCompField == 2) - { - hbuf.Write((System.Int16)prog[i].cs); - } - else - { - hbuf.Write((System.Byte)prog[i].cs); - } - // LYEpoc(i) - hbuf.Write((System.Int16)prog[i].lye); - // REpoc(i) - hbuf.Write((System.Byte)prog[i].re); - // CEpoc(i) - if (lenCompField == 2) - { - hbuf.Write((System.Int16)prog[i].ce); - } - else - { - hbuf.Write((System.Byte)prog[i].ce); - } - // Ppoc(i) - hbuf.Write((System.Byte)prog[i].type); - } - } - - - /// Write main header. JJ2000 main header corresponds to the following - /// sequence of marker segments: - /// - ///
      - ///
    1. SOC
    2. - ///
    3. SIZ
    4. - ///
    5. COD
    6. - ///
    7. COC (if needed)
    8. - ///
    9. QCD
    10. - ///
    11. QCC (if needed)
    12. - ///
    13. POC (if needed)
    14. - ///
    - /// - ///
    - public virtual void encodeMainHeader() - { - int i; - - - // +---------------------------------+ - // | SOC marker segment | - // +---------------------------------+ - writeSOC(); - - // +---------------------------------+ - // | Image and tile SIZe (SIZ) | - // +---------------------------------+ - writeSIZ(); - - // +-------------------------------+ - // | COding style Default (COD) | - // +-------------------------------+ - bool isEresUsed = ((System.String)encSpec.tts.getDefault()).Equals("predict"); - writeCOD(true, 0); - - // +---------------------------------+ - // | COding style Component (COC) | - // +---------------------------------+ - for (i = 0; i < nComp; i++) - { - bool isEresUsedinComp = ((System.String)encSpec.tts.getCompDef(i)).Equals("predict"); - if (encSpec.wfs.isCompSpecified(i) || encSpec.dls.isCompSpecified(i) || encSpec.bms.isCompSpecified(i) || encSpec.mqrs.isCompSpecified(i) || encSpec.rts.isCompSpecified(i) || encSpec.sss.isCompSpecified(i) || encSpec.css.isCompSpecified(i) || encSpec.pss.isCompSpecified(i) || encSpec.cblks.isCompSpecified(i) || (isEresUsed != isEresUsedinComp)) - // Some component non-default stuff => need COC - writeCOC(true, 0, i); - } - - // +-------------------------------+ - // | Quantization Default (QCD) | - // +-------------------------------+ - writeMainQCD(); - - // +-------------------------------+ - // | Quantization Component (QCC) | - // +-------------------------------+ - // Write needed QCC markers - for (i = 0; i < nComp; i++) - { - if (dwt.getNomRangeBits(i) != defimgn || encSpec.qts.isCompSpecified(i) || encSpec.qsss.isCompSpecified(i) || encSpec.dls.isCompSpecified(i) || encSpec.gbs.isCompSpecified(i)) - { - writeMainQCC(i); - } - } - - // +--------------------------+ - // | POC maker segment | - // +--------------------------+ - Progression[] prog = (Progression[])(encSpec.pocs.getDefault()); - if (prog.Length > 1) - writePOC(true, 0); - - // +---------------------------+ - // | Comments (COM) | - // +---------------------------+ - writeCOM(); - } - - /// Write COM marker segment(s) to the codestream. - /// - ///

    This marker is currently written in main header and indicates the - /// JJ2000 encoder's version that has created the codestream.

    - /// - ///
    - private void writeCOM() - { - // JJ2000 COM marker segment - if (enJJ2KMarkSeg) - { - System.String str = "Created by: CSJ2K version " + JJ2KInfo.version; - int markSegLen; // the marker segment length - - // COM marker - hbuf.Write((System.Int16)CSJ2K.j2k.codestream.Markers.COM); - - // Calculate length: Lcom(2) + Rcom (2) + string's length; - markSegLen = 2 + 2 + str.Length; - hbuf.Write((System.Int16)markSegLen); - - // Rcom - hbuf.Write((System.Int16)1); // General use (IS 8859-15:1999(Latin) values) - - byte[] chars = System.Text.ASCIIEncoding.ASCII.GetBytes(str); - for (int i = 0; i < chars.Length; i++) - { - hbuf.Write((byte)chars[i]); - } - } - // other COM marker segments - if (otherCOMMarkSeg != null) - { - SupportClass.Tokenizer stk = new SupportClass.Tokenizer(otherCOMMarkSeg, "#"); - while (stk.HasMoreTokens()) - { - System.String str = stk.NextToken(); - int markSegLen; // the marker segment length - - // COM marker - hbuf.Write((System.Int16)CSJ2K.j2k.codestream.Markers.COM); - - // Calculate length: Lcom(2) + Rcom (2) + string's length; - markSegLen = 2 + 2 + str.Length; - hbuf.Write((System.Int16)markSegLen); - - // Rcom - hbuf.Write((System.Int16)1); // General use (IS 8859-15:1999(Latin) - // values) - - byte[] chars = System.Text.ASCIIEncoding.ASCII.GetBytes(str); - for (int i = 0; i < chars.Length; i++) - { - hbuf.Write((byte)chars[i]); - } - } - } - } - - /// Writes the RGN marker segment in the tile header. It describes the - /// scaling value in each tile component - /// - ///

    May be used in tile or main header. If used in main header, it - /// refers to a ROI of the whole image, regardless of tiling. When used in - /// tile header, only the particular tile is affected.

    - /// - ///
    - /// The tile index - /// - /// - /// If an I/O error occurs while reading from the - /// encoder header stream - /// - /// - private void writeRGN(int tIdx) - { - int i; - int markSegLen; // the marker length - - // Write one RGN marker per component - for (i = 0; i < nComp; i++) - { - // RGN marker - hbuf.Write((System.Int16)CSJ2K.j2k.codestream.Markers.RGN); - - // Calculate length (Lrgn) - // Basic: Lrgn (2) + Srgn (1) + SPrgn + one byte - // or two for component number - markSegLen = 4 + ((nComp < 257) ? 1 : 2); - hbuf.Write((System.Int16)markSegLen); - - // Write component (Crgn) - if (nComp < 257) - { - hbuf.Write((System.Byte)i); - } - else - { - hbuf.Write((System.Int16)i); - } - - // Write type of ROI (Srgn) - hbuf.Write((System.Byte)CSJ2K.j2k.codestream.Markers.SRGN_IMPLICIT); - - // Write ROI info (SPrgn) - hbuf.Write((System.Byte)((System.Int32)(encSpec.rois.getTileCompVal(tIdx, i)))); - } - } - /// Writes tile-part header. JJ2000 tile-part header corresponds to the - /// following sequence of marker segments: - /// - ///
      - ///
    1. SOT
    2. - ///
    3. COD (if needed)
    4. - ///
    5. COC (if needed)
    6. - ///
    7. QCD (if needed)
    8. - ///
    9. QCC (if needed)
    10. - ///
    11. RGN (if needed)
    12. - ///
    13. POC (if needed)
    14. - ///
    15. SOD
    16. - ///
    - /// - ///
    - /// The length of the current tile-part. - /// - /// - /// Index of the tile to write - /// - /// - public virtual void encodeTilePartHeader(int tileLength, int tileIdx) - { - - int tmp; - Coord numTiles = ralloc.getNumTiles(null); - ralloc.setTile(tileIdx % numTiles.x, tileIdx / numTiles.x); - - // +--------------------------+ - // | SOT maker segment | - // +--------------------------+ - // SOT marker - hbuf.Write((System.Byte)SupportClass.URShift(CSJ2K.j2k.codestream.Markers.SOT, 8)); - hbuf.Write((System.Byte)(CSJ2K.j2k.codestream.Markers.SOT & 0x00FF)); - - // Lsot (10 bytes) - hbuf.Write((System.Byte)0); - hbuf.Write((System.Byte)10); - - // Isot - if (tileIdx > 65534) - { - throw new System.ArgumentException("Trying to write a tile-part " + "header whose tile index is " + "too high"); - } - hbuf.Write((System.Byte)(tileIdx >> 8)); - hbuf.Write((System.Byte)tileIdx); - - // Psot - tmp = tileLength; - hbuf.Write((System.Byte)(tmp >> 24)); - hbuf.Write((System.Byte)(tmp >> 16)); - hbuf.Write((System.Byte)(tmp >> 8)); - hbuf.Write((System.Byte)tmp); - - // TPsot - hbuf.Write((System.Byte)0); // Only one tile-part currently supported ! - - // TNsot - hbuf.Write((System.Byte)1); // Only one tile-part currently supported ! - - // +--------------------------+ - // | COD maker segment | - // +--------------------------+ - bool isEresUsed = ((System.String)encSpec.tts.getDefault()).Equals("predict"); - bool isEresUsedInTile = ((System.String)encSpec.tts.getTileDef(tileIdx)).Equals("predict"); - bool tileCODwritten = false; - if (encSpec.wfs.isTileSpecified(tileIdx) || encSpec.cts.isTileSpecified(tileIdx) || encSpec.dls.isTileSpecified(tileIdx) || encSpec.bms.isTileSpecified(tileIdx) || encSpec.mqrs.isTileSpecified(tileIdx) || encSpec.rts.isTileSpecified(tileIdx) || encSpec.css.isTileSpecified(tileIdx) || encSpec.pss.isTileSpecified(tileIdx) || encSpec.sops.isTileSpecified(tileIdx) || encSpec.sss.isTileSpecified(tileIdx) || encSpec.pocs.isTileSpecified(tileIdx) || encSpec.ephs.isTileSpecified(tileIdx) || encSpec.cblks.isTileSpecified(tileIdx) || (isEresUsed != isEresUsedInTile)) - { - writeCOD(false, tileIdx); - tileCODwritten = true; - } - - // +--------------------------+ - // | COC maker segment | - // +--------------------------+ - for (int c = 0; c < nComp; c++) - { - bool isEresUsedInTileComp = ((System.String)encSpec.tts.getTileCompVal(tileIdx, c)).Equals("predict"); - - if (encSpec.wfs.isTileCompSpecified(tileIdx, c) || encSpec.dls.isTileCompSpecified(tileIdx, c) || encSpec.bms.isTileCompSpecified(tileIdx, c) || encSpec.mqrs.isTileCompSpecified(tileIdx, c) || encSpec.rts.isTileCompSpecified(tileIdx, c) || encSpec.css.isTileCompSpecified(tileIdx, c) || encSpec.pss.isTileCompSpecified(tileIdx, c) || encSpec.sss.isTileCompSpecified(tileIdx, c) || encSpec.cblks.isTileCompSpecified(tileIdx, c) || (isEresUsedInTileComp != isEresUsed)) - { - writeCOC(false, tileIdx, c); - } - else if (tileCODwritten) - { - if (encSpec.wfs.isCompSpecified(c) || encSpec.dls.isCompSpecified(c) || encSpec.bms.isCompSpecified(c) || encSpec.mqrs.isCompSpecified(c) || encSpec.rts.isCompSpecified(c) || encSpec.sss.isCompSpecified(c) || encSpec.css.isCompSpecified(c) || encSpec.pss.isCompSpecified(c) || encSpec.cblks.isCompSpecified(c) || (encSpec.tts.isCompSpecified(c) && ((System.String)encSpec.tts.getCompDef(c)).Equals("predict"))) - { - writeCOC(false, tileIdx, c); - } - } - } - - // +--------------------------+ - // | QCD maker segment | - // +--------------------------+ - bool tileQCDwritten = false; - if (encSpec.qts.isTileSpecified(tileIdx) || encSpec.qsss.isTileSpecified(tileIdx) || encSpec.dls.isTileSpecified(tileIdx) || encSpec.gbs.isTileSpecified(tileIdx)) - { - writeTileQCD(tileIdx); - tileQCDwritten = true; - } - else - { - deftilenr = defimgn; - } - - // +--------------------------+ - // | QCC maker segment | - // +--------------------------+ - for (int c = 0; c < nComp; c++) - { - if (dwt.getNomRangeBits(c) != deftilenr || encSpec.qts.isTileCompSpecified(tileIdx, c) || encSpec.qsss.isTileCompSpecified(tileIdx, c) || encSpec.dls.isTileCompSpecified(tileIdx, c) || encSpec.gbs.isTileCompSpecified(tileIdx, c)) - { - writeTileQCC(tileIdx, c); - } - else if (tileQCDwritten) - { - if (encSpec.qts.isCompSpecified(c) || encSpec.qsss.isCompSpecified(c) || encSpec.dls.isCompSpecified(c) || encSpec.gbs.isCompSpecified(c)) - { - writeTileQCC(tileIdx, c); - } - } - } - - // +--------------------------+ - // | RGN maker segment | - // +--------------------------+ - if (roiSc.useRoi() && (!roiSc.BlockAligned)) - writeRGN(tileIdx); - - // +--------------------------+ - // | POC maker segment | - // +--------------------------+ - Progression[] prog; - if (encSpec.pocs.isTileSpecified(tileIdx)) - { - prog = (Progression[])(encSpec.pocs.getTileDef(tileIdx)); - if (prog.Length > 1) - writePOC(false, tileIdx); - } - - // +--------------------------+ - // | SOD maker | - // +--------------------------+ - hbuf.Write((System.Byte)SupportClass.URShift(CSJ2K.j2k.codestream.Markers.SOD, 8)); - hbuf.Write((System.Byte)(CSJ2K.j2k.codestream.Markers.SOD & 0x00FF)); - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/codestream/writer/PktEncoder.cs b/CSJ2K/j2k/codestream/writer/PktEncoder.cs deleted file mode 100644 index eda2ca70..00000000 --- a/CSJ2K/j2k/codestream/writer/PktEncoder.cs +++ /dev/null @@ -1,1558 +0,0 @@ -/* -* CVS identifier: -* -* $Id: PktEncoder.java,v 1.29 2001/11/08 18:32:09 grosbois Exp $ -* -* Class: PktEncoder -* -* Description: Builds bit stream packets and keeps -* interpacket dependencies. -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.encoder; -using CSJ2K.j2k.entropy.encoder; -using CSJ2K.j2k.image; -using CSJ2K.j2k.util; -using CSJ2K.j2k.wavelet.analysis; -using System; -namespace CSJ2K.j2k.codestream.writer -{ - - /// This class builds packets and keeps the state information of packet - /// interdependencies. It also supports saving the state and reverting - /// (restoring) to the last saved state, with the save() and restore() methods. - /// - ///

    Each time the encodePacket() method is called a new packet is encoded, - /// the packet header is returned by the method, and the packet body can be - /// obtained with the getLastBodyBuf() and getLastBodyLen() methods.

    - /// - ///
    - public class PktEncoder - { - /// Returns the buffer of the body of the last encoded packet. The length - /// of the body can be retrieved with the getLastBodyLen() method. The - /// length of the array returned by this method may be larger than the - /// actual body length. - /// - /// - /// The buffer of body of the last encoded packet. - /// - /// - /// If no packet has been coded since - /// last reset(), last restore(), or object creation. - /// - /// - /// - /// - /// - virtual public byte[] LastBodyBuf - { - get - { - if (lbbuf == null) - { - throw new System.ArgumentException(); - } - return lbbuf; - } - - } - /// Returns the length of the body of the last encoded packet, in - /// bytes. The body itself can be retrieved with the getLastBodyBuf() - /// method. - /// - /// - /// The length of the body of last encoded packet, in bytes. - /// - /// - /// - /// - /// - virtual public int LastBodyLen - { - get - { - return lblen; - } - - } - /// Returns true if the current packet is writable i.e. should be written. - /// Returns false otherwise. - /// - /// - virtual public bool PacketWritable - { - get - { - return packetWritable; - } - - } - /// Tells if there was ROI information in the last written packet - /// - /// - virtual public bool ROIinPkt - { - get - { - return roiInPkt; - } - - } - /// Gives the length to read in current packet body to get all ROI - /// information - /// - virtual public int ROILen - { - get - { - return roiLen; - } - - } - /// Returns the parameters that are used in this class and implementing - /// classes. It returns a 2D String array. Each of the 1D arrays is for a - /// different option, and they have 3 elements. The first element is the - /// option name, the second one is the synopsis, the third one is a long - /// description of what the parameter is and the fourth is its default - /// value. The synopsis or description may be 'null', in which case it is - /// assumed that there is no synopsis or description of the option, - /// respectively. Null may be returned if no options are supported. - /// - /// - /// the options name, their synopsis and their explanation, - /// or null if no options are supported. - /// - /// - public static System.String[][] ParameterInfo - { - get - { - return pinfo; - } - - } - - /// The prefix for packet encoding options: 'P' - public const char OPT_PREFIX = 'P'; - - /// The list of parameters that is accepted for packet encoding. - //UPGRADE_NOTE: Final was removed from the declaration of 'pinfo'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly System.String[][] pinfo = new System.String[][] { new System.String[] { "Psop", "[] on|off" + "[ [] on|off ...]", "Specifies whether start of packet (SOP) markers should be used. " + "'on' enables, 'off' disables it.", "off" }, new System.String[] { "Peph", "[] on|off" + "[ [] on|off ...]", "Specifies whether end of packet header (EPH) markers should be " + " used. 'on' enables, 'off' disables it.", "off" } }; - - /// The initial value for the lblock - private const int INIT_LBLOCK = 3; - - /// The source object - private CodedCBlkDataSrcEnc infoSrc; - - /// The encoder specs - private EncoderSpecs encSpec; - - /// The tag tree for inclusion information. The indexes are outlined - /// below. Note that the layer indexes start at 1, therefore, the layer - /// index minus 1 is used. The subband indices are used as they are defined - /// in the Subband class. The tile indices start at 0 and follow a - /// lexicographical order. - /// - ///
      - ///
    • 1st index: tile index, in lexicographical order
    • - ///
    • 2nd index: component index
    • - ///
    • 3rd index: resolution level
    • - ///
    • 4th index: precinct index
    • - ///
    • 5th index: subband index
    • - ///
    - /// - ///
    - private TagTreeEncoder[][][][][] ttIncl; - - /// The tag tree for the maximum significant bit-plane. The indexes are - /// outlined below. Note that the layer indexes start at 1, therefore, the - /// layer index minus 1 is used. The subband indices are used as they are - /// defined in the Subband class. The tile indices start at 0 and follow a - /// lexicographical order. - /// - ///
      - ///
    • 1st index: tile index, in lexicographical order
    • - ///
    • 2nd index: component index
    • - ///
    • 3rd index: resolution level
    • - ///
    • 4th index: precinct index
    • - ///
    • 5th index: subband index
    • - ///
    - /// - ///
    - private TagTreeEncoder[][][][][] ttMaxBP; - - /// The base number of bits for sending code-block length information - /// (referred as Lblock in the JPEG 2000 standard). The indexes are - /// outlined below. Note that the layer indexes start at 1, therefore, the - /// layer index minus 1 is used. The subband indices are used as they are - /// defined in the Subband class. The tile indices start at 0 and follow a - /// lexicographical order. - /// - ///
      - ///
    • 1st index: tile index, in lexicographical order
    • - ///
    • 2nd index: component index
    • - ///
    • 3rd index: resolution level
    • - ///
    • 4th index: subband index
    • - ///
    • 5th index: code-block index, in lexicographical order
    • - ///
    - /// - ///
    - private int[][][][][] lblock; - - /// The last encoded truncation point for each code-block. A negative value - /// means that no information has been included for the block, yet. The - /// indexes are outlined below. The subband indices are used as they are - /// defined in the Subband class. The tile indices start at 0 and follow a - /// lexicographical order. The code-block indices follow a lexicographical - /// order within the subband tile. - /// - ///

    What is actually stored is the index of the element in - /// CBlkRateDistStats.truncIdxs that gives the real truncation point. - /// - ///

      - ///
    • 1st index: tile index, in lexicographical order
    • - ///
    • 2nd index: component index
    • - ///
    • 3rd index: resolution level
    • - ///
    • 4th index: subband index
    • - ///
    • 5th index: code-block index, in lexicographical order
    • - ///
    - /// - ///
    - private int[][][][][] prevtIdxs; - - /// The saved base number of bits for sending code-block length - /// information. It is used for restoring previous saved state by - /// restore(). The indexes are outlined below. Note that the layer indexes - /// start at 1, therefore, the layer index minus 1 is used. The subband - /// indices are used as they are defined in the Subband class. The tile - /// indices start at 0 and follow a lexicographical order. - /// - ///
      - ///
    • 1st index: tile index, in lexicographical order
    • - ///
    • 2nd index: component index
    • - ///
    • 3rd index: resolution level
    • - ///
    • 4th index: subband index
    • - ///
    • 5th index: code-block index, in lexicographical order
    • - ///
    - /// - ///
    - private int[][][][][] bak_lblock; - - /// The saved last encoded truncation point for each code-block. It is used - /// for restoring previous saved state by restore(). A negative value means - /// that no information has been included for the block, yet. The indexes - /// are outlined below. The subband indices are used as they are defined in - /// the Subband class. The tile indices start at 0 and follow a - /// lexicographical order. The code-block indices follow a lexicographical - /// order within the subband tile. - /// - ///
      - ///
    • 1st index: tile index, in lexicographical order
    • - ///
    • 2nd index: component index
    • - ///
    • 3rd index: resolution level
    • - ///
    • 4th index: subband index
    • - ///
    • 5th index: code-block index, in lexicographical order
    • - ///
    - /// - ///
    - private int[][][][][] bak_prevtIdxs; - - /// The body buffer of the last encoded packet - private byte[] lbbuf; - - /// The body length of the last encoded packet - private int lblen; - - /// The saved state - private bool saved; - - /// Whether or not there is ROI information in the last encoded Packet - private bool roiInPkt = false; - - /// Length to read in current packet body to get all the ROI information - private int roiLen = 0; - - /// Array containing the coordinates, width, height, indexes, ... of the - /// precincts. - /// - ///
      - ///
    • 1st dim: tile index.
    • - ///
    • 2nd dim: component index.
    • - ///
    • 3rd dim: resolution level index.
    • - ///
    • 4th dim: precinct index.
    • - ///
    - /// - ///
    - private PrecInfo[][][][] ppinfo; - - /// Whether or not the current packet is writable - private bool packetWritable; - - /// Creates a new packet encoder object, using the information from the - /// 'infoSrc' object. - /// - /// - /// The source of information to construct the object. - /// - /// - /// The encoding parameters. - /// - /// - /// Maximum number of precincts in each tile, component - /// and resolution level. - /// - /// - /// ParameterList instance that holds command line options - /// - /// - public PktEncoder(CodedCBlkDataSrcEnc infoSrc, EncoderSpecs encSpec, Coord[][][] numPrec, ParameterList pl) - { - this.infoSrc = infoSrc; - this.encSpec = encSpec; - - // Check parameters - pl.checkList(OPT_PREFIX, CSJ2K.j2k.util.ParameterList.toNameArray(pinfo)); - - // Get number of components and tiles - int nc = infoSrc.NumComps; - int nt = infoSrc.getNumTiles(); - - // Do initial allocation - ttIncl = new TagTreeEncoder[nt][][][][]; - for (int i = 0; i < nt; i++) - { - ttIncl[i] = new TagTreeEncoder[nc][][][]; - } - ttMaxBP = new TagTreeEncoder[nt][][][][]; - for (int i2 = 0; i2 < nt; i2++) - { - ttMaxBP[i2] = new TagTreeEncoder[nc][][][]; - } - lblock = new int[nt][][][][]; - for (int i3 = 0; i3 < nt; i3++) - { - lblock[i3] = new int[nc][][][]; - } - prevtIdxs = new int[nt][][][][]; - for (int i4 = 0; i4 < nt; i4++) - { - prevtIdxs[i4] = new int[nc][][][]; - } - ppinfo = new PrecInfo[nt][][][]; - for (int i5 = 0; i5 < nt; i5++) - { - ppinfo[i5] = new PrecInfo[nc][][]; - } - - // Finish allocation - SubbandAn root, sb; - int maxs, mins; - int mrl; - //Coord tmpCoord = null; - int numcb; // Number of code-blocks - //System.Collections.ArrayList cblks = null; - infoSrc.setTile(0, 0); - for (int t = 0; t < nt; t++) - { - // Loop on tiles - for (int c = 0; c < nc; c++) - { - // Loop on components - // Get number of resolution levels - root = infoSrc.getAnSubbandTree(t, c); - mrl = root.resLvl; - - lblock[t][c] = new int[mrl + 1][][]; - ttIncl[t][c] = new TagTreeEncoder[mrl + 1][][]; - ttMaxBP[t][c] = new TagTreeEncoder[mrl + 1][][]; - prevtIdxs[t][c] = new int[mrl + 1][][]; - ppinfo[t][c] = new PrecInfo[mrl + 1][]; - - for (int r = 0; r <= mrl; r++) - { - // Loop on resolution levels - mins = (r == 0) ? 0 : 1; - maxs = (r == 0) ? 1 : 4; - - int maxPrec = numPrec[t][c][r].x * numPrec[t][c][r].y; - - ttIncl[t][c][r] = new TagTreeEncoder[maxPrec][]; - for (int i6 = 0; i6 < maxPrec; i6++) - { - ttIncl[t][c][r][i6] = new TagTreeEncoder[maxs]; - } - ttMaxBP[t][c][r] = new TagTreeEncoder[maxPrec][]; - for (int i7 = 0; i7 < maxPrec; i7++) - { - ttMaxBP[t][c][r][i7] = new TagTreeEncoder[maxs]; - } - prevtIdxs[t][c][r] = new int[maxs][]; - lblock[t][c][r] = new int[maxs][]; - - // Precincts and code-blocks - ppinfo[t][c][r] = new PrecInfo[maxPrec]; - fillPrecInfo(t, c, r); - - for (int s = mins; s < maxs; s++) - { - // Loop on subbands - sb = (SubbandAn)root.getSubbandByIdx(r, s); - numcb = sb.numCb.x * sb.numCb.y; - - lblock[t][c][r][s] = new int[numcb]; - ArrayUtil.intArraySet(lblock[t][c][r][s], INIT_LBLOCK); - - prevtIdxs[t][c][r][s] = new int[numcb]; - ArrayUtil.intArraySet(prevtIdxs[t][c][r][s], -1); - } - } - } - if (t != nt - 1) - infoSrc.nextTile(); - } - } - - /// Retrives precincts and code-blocks coordinates in the given resolution, - /// component and tile. It terminates TagTreeEncoder initialization as - /// well. - /// - /// - /// Tile index. - /// - /// - /// Component index. - /// - /// - /// Resolution level index. - /// - /// - private void fillPrecInfo(int t, int c, int r) - { - if (ppinfo[t][c][r].Length == 0) - return; // No precinct in this - // resolution level - - Coord tileI = infoSrc.getTile(null); - Coord nTiles = infoSrc.getNumTiles(null); - - int x0siz = infoSrc.ImgULX; - int y0siz = infoSrc.ImgULY; - int xsiz = x0siz + infoSrc.ImgWidth; - int ysiz = y0siz + infoSrc.ImgHeight; - int xt0siz = infoSrc.TilePartULX; - int yt0siz = infoSrc.TilePartULY; - int xtsiz = infoSrc.NomTileWidth; - int ytsiz = infoSrc.NomTileHeight; - - int tx0 = (tileI.x == 0) ? x0siz : xt0siz + tileI.x * xtsiz; - int ty0 = (tileI.y == 0) ? y0siz : yt0siz + tileI.y * ytsiz; - int tx1 = (tileI.x != nTiles.x - 1) ? xt0siz + (tileI.x + 1) * xtsiz : xsiz; - int ty1 = (tileI.y != nTiles.y - 1) ? yt0siz + (tileI.y + 1) * ytsiz : ysiz; - - int xrsiz = infoSrc.getCompSubsX(c); - int yrsiz = infoSrc.getCompSubsY(c); - - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - int tcx0 = (int)System.Math.Ceiling(tx0 / (double)(xrsiz)); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - int tcy0 = (int)System.Math.Ceiling(ty0 / (double)(yrsiz)); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - int tcx1 = (int)System.Math.Ceiling(tx1 / (double)(xrsiz)); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - int tcy1 = (int)System.Math.Ceiling(ty1 / (double)(yrsiz)); - - int ndl = infoSrc.getAnSubbandTree(t, c).resLvl - r; - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - int trx0 = (int)System.Math.Ceiling(tcx0 / (double)(1 << ndl)); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - int try0 = (int)System.Math.Ceiling(tcy0 / (double)(1 << ndl)); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - int trx1 = (int)System.Math.Ceiling(tcx1 / (double)(1 << ndl)); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - int try1 = (int)System.Math.Ceiling(tcy1 / (double)(1 << ndl)); - - int cb0x = infoSrc.CbULX; - int cb0y = infoSrc.CbULY; - - double twoppx = (double)encSpec.pss.getPPX(t, c, r); - double twoppy = (double)encSpec.pss.getPPY(t, c, r); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - int twoppx2 = (int)(twoppx / 2); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - int twoppy2 = (int)(twoppy / 2); - - // Precincts are located at (cb0x+i*twoppx,cb0y+j*twoppy) - // Valid precincts are those which intersect with the current - // resolution level - int maxPrec = ppinfo[t][c][r].Length; - int nPrec = 0; - - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - int istart = (int)System.Math.Floor((try0 - cb0y) / twoppy); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - int iend = (int)System.Math.Floor((try1 - 1 - cb0y) / twoppy); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - int jstart = (int)System.Math.Floor((trx0 - cb0x) / twoppx); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - int jend = (int)System.Math.Floor((trx1 - 1 - cb0x) / twoppx); - - int acb0x, acb0y; - - SubbandAn root = infoSrc.getAnSubbandTree(t, c); - SubbandAn sb = null; - - int p0x, p0y, p1x, p1y; // Precinct projection in subband - int s0x, s0y, s1x, s1y; // Active subband portion - int cw, ch; - int kstart, kend, lstart, lend, k0, l0; - int prg_ulx, prg_uly; - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - int prg_w = (int)twoppx << ndl; - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - int prg_h = (int)twoppy << ndl; - - CBlkCoordInfo cb; - - for (int i = istart; i <= iend; i++) - { - // Vertical precincts - for (int j = jstart; j <= jend; j++, nPrec++) - { - // Horizontal precincts - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - if (j == jstart && (trx0 - cb0x) % (xrsiz * ((int)twoppx)) != 0) - { - prg_ulx = tx0; - } - else - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - prg_ulx = cb0x + j * xrsiz * ((int)twoppx << ndl); - } - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - if (i == istart && (try0 - cb0y) % (yrsiz * ((int)twoppy)) != 0) - { - prg_uly = ty0; - } - else - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - prg_uly = cb0y + i * yrsiz * ((int)twoppy << ndl); - } - - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - ppinfo[t][c][r][nPrec] = new PrecInfo(r, (int)(cb0x + j * twoppx), (int)(cb0y + i * twoppy), (int)twoppx, (int)twoppy, prg_ulx, prg_uly, prg_w, prg_h); - - if (r == 0) - { - // LL subband - acb0x = cb0x; - acb0y = cb0y; - - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - p0x = acb0x + j * (int)twoppx; - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - p1x = p0x + (int)twoppx; - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - p0y = acb0y + i * (int)twoppy; - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - p1y = p0y + (int)twoppy; - - sb = (SubbandAn)root.getSubbandByIdx(0, 0); - s0x = (p0x < sb.ulcx) ? sb.ulcx : p0x; - s1x = (p1x > sb.ulcx + sb.w) ? sb.ulcx + sb.w : p1x; - s0y = (p0y < sb.ulcy) ? sb.ulcy : p0y; - s1y = (p1y > sb.ulcy + sb.h) ? sb.ulcy + sb.h : p1y; - - // Code-blocks are located at (acb0x+k*cw,acb0y+l*ch) - cw = sb.nomCBlkW; - ch = sb.nomCBlkH; - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - k0 = (int)System.Math.Floor((sb.ulcy - acb0y) / (double)ch); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - kstart = (int)System.Math.Floor((s0y - acb0y) / (double)ch); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - kend = (int)System.Math.Floor((s1y - 1 - acb0y) / (double)ch); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - l0 = (int)System.Math.Floor((sb.ulcx - acb0x) / (double)cw); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - lstart = (int)System.Math.Floor((s0x - acb0x) / (double)cw); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - lend = (int)System.Math.Floor((s1x - 1 - acb0x) / (double)cw); - - if (s1x - s0x <= 0 || s1y - s0y <= 0) - { - ppinfo[t][c][r][nPrec].nblk[0] = 0; - ttIncl[t][c][r][nPrec][0] = new TagTreeEncoder(0, 0); - ttMaxBP[t][c][r][nPrec][0] = new TagTreeEncoder(0, 0); - } - else - { - ttIncl[t][c][r][nPrec][0] = new TagTreeEncoder(kend - kstart + 1, lend - lstart + 1); - ttMaxBP[t][c][r][nPrec][0] = new TagTreeEncoder(kend - kstart + 1, lend - lstart + 1); - CBlkCoordInfo[][] tmpArray = new CBlkCoordInfo[kend - kstart + 1][]; - for (int i2 = 0; i2 < kend - kstart + 1; i2++) - { - tmpArray[i2] = new CBlkCoordInfo[lend - lstart + 1]; - } - ppinfo[t][c][r][nPrec].cblk[0] = tmpArray; - ppinfo[t][c][r][nPrec].nblk[0] = (kend - kstart + 1) * (lend - lstart + 1); - - for (int k = kstart; k <= kend; k++) - { - // Vertical cblks - for (int l = lstart; l <= lend; l++) - { - // Horiz. cblks - - cb = new CBlkCoordInfo(k - k0, l - l0); - ppinfo[t][c][r][nPrec].cblk[0][k - kstart][l - lstart] = cb; - } // Horizontal code-blocks - } // Vertical code-blocks - } - } - else - { - // HL, LH and HH subbands - // HL subband - acb0x = 0; - acb0y = cb0y; - - p0x = acb0x + j * twoppx2; - p1x = p0x + twoppx2; - p0y = acb0y + i * twoppy2; - p1y = p0y + twoppy2; - - sb = (SubbandAn)root.getSubbandByIdx(r, 1); - s0x = (p0x < sb.ulcx) ? sb.ulcx : p0x; - s1x = (p1x > sb.ulcx + sb.w) ? sb.ulcx + sb.w : p1x; - s0y = (p0y < sb.ulcy) ? sb.ulcy : p0y; - s1y = (p1y > sb.ulcy + sb.h) ? sb.ulcy + sb.h : p1y; - - // Code-blocks are located at (acb0x+k*cw,acb0y+l*ch) - cw = sb.nomCBlkW; - ch = sb.nomCBlkH; - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - k0 = (int)System.Math.Floor((sb.ulcy - acb0y) / (double)ch); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - kstart = (int)System.Math.Floor((s0y - acb0y) / (double)ch); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - kend = (int)System.Math.Floor((s1y - 1 - acb0y) / (double)ch); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - l0 = (int)System.Math.Floor((sb.ulcx - acb0x) / (double)cw); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - lstart = (int)System.Math.Floor((s0x - acb0x) / (double)cw); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - lend = (int)System.Math.Floor((s1x - 1 - acb0x) / (double)cw); - - if (s1x - s0x <= 0 || s1y - s0y <= 0) - { - ppinfo[t][c][r][nPrec].nblk[1] = 0; - ttIncl[t][c][r][nPrec][1] = new TagTreeEncoder(0, 0); - ttMaxBP[t][c][r][nPrec][1] = new TagTreeEncoder(0, 0); - } - else - { - ttIncl[t][c][r][nPrec][1] = new TagTreeEncoder(kend - kstart + 1, lend - lstart + 1); - ttMaxBP[t][c][r][nPrec][1] = new TagTreeEncoder(kend - kstart + 1, lend - lstart + 1); - CBlkCoordInfo[][] tmpArray2 = new CBlkCoordInfo[kend - kstart + 1][]; - for (int i3 = 0; i3 < kend - kstart + 1; i3++) - { - tmpArray2[i3] = new CBlkCoordInfo[lend - lstart + 1]; - } - ppinfo[t][c][r][nPrec].cblk[1] = tmpArray2; - ppinfo[t][c][r][nPrec].nblk[1] = (kend - kstart + 1) * (lend - lstart + 1); - - for (int k = kstart; k <= kend; k++) - { - // Vertical cblks - for (int l = lstart; l <= lend; l++) - { - // Horiz. cblks - cb = new CBlkCoordInfo(k - k0, l - l0); - ppinfo[t][c][r][nPrec].cblk[1][k - kstart][l - lstart] = cb; - } // Horizontal code-blocks - } // Vertical code-blocks - } - - // LH subband - acb0x = cb0x; - acb0y = 0; - - p0x = acb0x + j * twoppx2; - p1x = p0x + twoppx2; - p0y = acb0y + i * twoppy2; - p1y = p0y + twoppy2; - - sb = (SubbandAn)root.getSubbandByIdx(r, 2); - s0x = (p0x < sb.ulcx) ? sb.ulcx : p0x; - s1x = (p1x > sb.ulcx + sb.w) ? sb.ulcx + sb.w : p1x; - s0y = (p0y < sb.ulcy) ? sb.ulcy : p0y; - s1y = (p1y > sb.ulcy + sb.h) ? sb.ulcy + sb.h : p1y; - - // Code-blocks are located at (acb0x+k*cw,acb0y+l*ch) - cw = sb.nomCBlkW; - ch = sb.nomCBlkH; - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - k0 = (int)System.Math.Floor((sb.ulcy - acb0y) / (double)ch); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - kstart = (int)System.Math.Floor((s0y - acb0y) / (double)ch); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - kend = (int)System.Math.Floor((s1y - 1 - acb0y) / (double)ch); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - l0 = (int)System.Math.Floor((sb.ulcx - acb0x) / (double)cw); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - lstart = (int)System.Math.Floor((s0x - acb0x) / (double)cw); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - lend = (int)System.Math.Floor((s1x - 1 - acb0x) / (double)cw); - - if (s1x - s0x <= 0 || s1y - s0y <= 0) - { - ppinfo[t][c][r][nPrec].nblk[2] = 0; - ttIncl[t][c][r][nPrec][2] = new TagTreeEncoder(0, 0); - ttMaxBP[t][c][r][nPrec][2] = new TagTreeEncoder(0, 0); - } - else - { - ttIncl[t][c][r][nPrec][2] = new TagTreeEncoder(kend - kstart + 1, lend - lstart + 1); - ttMaxBP[t][c][r][nPrec][2] = new TagTreeEncoder(kend - kstart + 1, lend - lstart + 1); - CBlkCoordInfo[][] tmpArray3 = new CBlkCoordInfo[kend - kstart + 1][]; - for (int i4 = 0; i4 < kend - kstart + 1; i4++) - { - tmpArray3[i4] = new CBlkCoordInfo[lend - lstart + 1]; - } - ppinfo[t][c][r][nPrec].cblk[2] = tmpArray3; - ppinfo[t][c][r][nPrec].nblk[2] = (kend - kstart + 1) * (lend - lstart + 1); - - for (int k = kstart; k <= kend; k++) - { - // Vertical cblks - for (int l = lstart; l <= lend; l++) - { - // Horiz cblks - cb = new CBlkCoordInfo(k - k0, l - l0); - ppinfo[t][c][r][nPrec].cblk[2][k - kstart][l - lstart] = cb; - } // Horizontal code-blocks - } // Vertical code-blocks - } - - // HH subband - acb0x = 0; - acb0y = 0; - - p0x = acb0x + j * twoppx2; - p1x = p0x + twoppx2; - p0y = acb0y + i * twoppy2; - p1y = p0y + twoppy2; - - sb = (SubbandAn)root.getSubbandByIdx(r, 3); - s0x = (p0x < sb.ulcx) ? sb.ulcx : p0x; - s1x = (p1x > sb.ulcx + sb.w) ? sb.ulcx + sb.w : p1x; - s0y = (p0y < sb.ulcy) ? sb.ulcy : p0y; - s1y = (p1y > sb.ulcy + sb.h) ? sb.ulcy + sb.h : p1y; - - // Code-blocks are located at (acb0x+k*cw,acb0y+l*ch) - cw = sb.nomCBlkW; - ch = sb.nomCBlkH; - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - k0 = (int)System.Math.Floor((sb.ulcy - acb0y) / (double)ch); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - kstart = (int)System.Math.Floor((s0y - acb0y) / (double)ch); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - kend = (int)System.Math.Floor((s1y - 1 - acb0y) / (double)ch); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - l0 = (int)System.Math.Floor((sb.ulcx - acb0x) / (double)cw); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - lstart = (int)System.Math.Floor((s0x - acb0x) / (double)cw); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - lend = (int)System.Math.Floor((s1x - 1 - acb0x) / (double)cw); - - if (s1x - s0x <= 0 || s1y - s0y <= 0) - { - ppinfo[t][c][r][nPrec].nblk[3] = 0; - ttIncl[t][c][r][nPrec][3] = new TagTreeEncoder(0, 0); - ttMaxBP[t][c][r][nPrec][3] = new TagTreeEncoder(0, 0); - } - else - { - ttIncl[t][c][r][nPrec][3] = new TagTreeEncoder(kend - kstart + 1, lend - lstart + 1); - ttMaxBP[t][c][r][nPrec][3] = new TagTreeEncoder(kend - kstart + 1, lend - lstart + 1); - CBlkCoordInfo[][] tmpArray4 = new CBlkCoordInfo[kend - kstart + 1][]; - for (int i5 = 0; i5 < kend - kstart + 1; i5++) - { - tmpArray4[i5] = new CBlkCoordInfo[lend - lstart + 1]; - } - ppinfo[t][c][r][nPrec].cblk[3] = tmpArray4; - ppinfo[t][c][r][nPrec].nblk[3] = (kend - kstart + 1) * (lend - lstart + 1); - - for (int k = kstart; k <= kend; k++) - { - // Vertical cblks - for (int l = lstart; l <= lend; l++) - { - // Horiz cblks - cb = new CBlkCoordInfo(k - k0, l - l0); - ppinfo[t][c][r][nPrec].cblk[3][k - kstart][l - lstart] = cb; - } // Horizontal code-blocks - } // Vertical code-blocks - } - } - } // Horizontal precincts - } // Vertical precincts - } - - /// Encodes a packet and returns the buffer containing the encoded packet - /// header. The code-blocks appear in a 3D array of CBlkRateDistStats, - /// 'cbs'. The first index is the tile index in lexicographical order, the - /// second index is the subband index (as defined in the Subband class), - /// and the third index is the code-block index (whithin the subband tile) - /// in lexicographical order as well. The indexes of the new truncation - /// points for each code-block are specified by the 3D array of int - /// 'tIndx'. The indices of this array are the same as for cbs. The - /// truncation point indices in 'tIndx' are the indices of the elements of - /// the 'truncIdxs' array, of the CBlkRateDistStats class, that give the - /// real truncation points. If a truncation point index is negative it - /// means that the code-block has not been included in any layer yet. If - /// the truncation point is less than or equal to the highest truncation - /// point used in previous layers then the code-block is not included in - /// the packet. Otherwise, if larger, the code-block is included in the - /// packet. The body of the packet can be obtained with the - /// getLastBodyBuf() and getLastBodyLen() methods. - /// - ///

    Layers must be coded in increasing order, in consecutive manner, for - /// each tile, component and resolution level (e.g., layer 1, then layer 2, - /// etc.). For different tile, component and/or resolution level no - /// particular order must be followed.

    - /// - ///
    - /// The layer index (starts at 1). - /// - /// - /// The component index. - /// - /// - /// The resolution level - /// - /// - /// Index of the current tile - /// - /// - /// The 3D array of coded code-blocks. - /// - /// - /// The truncation point indices for each code-block. - /// - /// - /// The header buffer. If null a new BitOutputBuffer is created - /// and returned. This buffer is reset before anything is written to it. - /// - /// - /// The body buffer. If null a new one is created. If not large - /// enough a new one is created. - /// - /// - /// The precinct index. - /// - /// - /// The buffer containing the packet header. - /// - /// - public virtual BitOutputBuffer encodePacket(int ly, int c, int r, int t, CBlkRateDistStats[][] cbs, int[][] tIndx, BitOutputBuffer hbuf, byte[] bbuf, int pIdx) - { - int b, i, maxi; - int ncb; - int thmax; - int newtp; - int cblen; - int prednbits, nbits; // deltabits removed - TagTreeEncoder cur_ttIncl, cur_ttMaxBP; // inclusion and bit-depth tag - // trees - int[] cur_prevtIdxs; // last encoded truncation points - CBlkRateDistStats[] cur_cbs; - int[] cur_tIndx; // truncation points to encode - int minsb = (r == 0) ? 0 : 1; - int maxsb = (r == 0) ? 1 : 4; - Coord cbCoord = null; - SubbandAn root = infoSrc.getAnSubbandTree(t, c); - SubbandAn sb; - roiInPkt = false; - roiLen = 0; - int mend, nend; - - // Checks if a precinct with such an index exists in this resolution - // level - if (pIdx >= ppinfo[t][c][r].Length) - { - packetWritable = false; - return hbuf; - } - PrecInfo prec = ppinfo[t][c][r][pIdx]; - - // First, we check if packet is empty (i.e precinct 'pIdx' has no - // code-block in any of the subbands) - bool isPrecVoid = true; - - for (int s = minsb; s < maxsb; s++) - { - if (prec.nblk[s] == 0) - { - // The precinct has no code-block in this subband. - continue; - } - else - { - // The precinct is not empty in at least one subband -> - // stop - isPrecVoid = false; - break; - } - } - - if (isPrecVoid) - { - packetWritable = true; - - if (hbuf == null) - { - hbuf = new BitOutputBuffer(); - } - else - { - hbuf.reset(); - } - if (bbuf == null) - { - lbbuf = bbuf = new byte[1]; - } - hbuf.writeBit(0); - lblen = 0; - - return hbuf; - } - - if (hbuf == null) - { - hbuf = new BitOutputBuffer(); - } - else - { - hbuf.reset(); - } - - // Invalidate last body buffer - lbbuf = null; - lblen = 0; - - // Signal that packet is present - hbuf.writeBit(1); - - for (int s = minsb; s < maxsb; s++) - { - // Loop on subbands - sb = (SubbandAn)root.getSubbandByIdx(r, s); - - // Go directly to next subband if the precinct has no code-block - // in the current one. - if (prec.nblk[s] == 0) - { - continue; - } - - cur_ttIncl = ttIncl[t][c][r][pIdx][s]; - cur_ttMaxBP = ttMaxBP[t][c][r][pIdx][s]; - cur_prevtIdxs = prevtIdxs[t][c][r][s]; - cur_cbs = cbs[s]; - cur_tIndx = tIndx[s]; - - // Set tag tree values for code-blocks in this precinct - mend = (prec.cblk[s] == null) ? 0 : prec.cblk[s].Length; - for (int m = 0; m < mend; m++) - { - nend = (prec.cblk[s][m] == null) ? 0 : prec.cblk[s][m].Length; - for (int n = 0; n < nend; n++) - { - cbCoord = prec.cblk[s][m][n].idx; - b = cbCoord.x + cbCoord.y * sb.numCb.x; - - if (cur_tIndx[b] > cur_prevtIdxs[b] && cur_prevtIdxs[b] < 0) - { - // First inclusion - cur_ttIncl.setValue(m, n, ly - 1); - } - if (ly == 1) - { - // First layer, need to set the skip of MSBP - cur_ttMaxBP.setValue(m, n, cur_cbs[b].skipMSBP); - } - } - } - - // Now encode the information - for (int m = 0; m < prec.cblk[s].Length; m++) - { - // Vertical code-blocks - for (int n = 0; n < prec.cblk[s][m].Length; n++) - { - // Horiz. cblks - cbCoord = prec.cblk[s][m][n].idx; - b = cbCoord.x + cbCoord.y * sb.numCb.x; - - // 1) Inclusion information - if (cur_tIndx[b] > cur_prevtIdxs[b]) - { - // Code-block included in this layer - if (cur_prevtIdxs[b] < 0) - { - // First inclusion - // Encode layer info - cur_ttIncl.encode(m, n, ly, hbuf); - - // 2) Max bitdepth info. Encode value - thmax = cur_cbs[b].skipMSBP + 1; - for (i = 1; i <= thmax; i++) - { - cur_ttMaxBP.encode(m, n, i, hbuf); - } - - // Count body size for packet - lblen += cur_cbs[b].truncRates[cur_cbs[b].truncIdxs[cur_tIndx[b]]]; - } - else - { - // Already in previous layer - // Send "1" bit - hbuf.writeBit(1); - // Count body size for packet - lblen += cur_cbs[b].truncRates[cur_cbs[b].truncIdxs[cur_tIndx[b]]] - cur_cbs[b].truncRates[cur_cbs[b].truncIdxs[cur_prevtIdxs[b]]]; - } - - // 3) Truncation point information - if (cur_prevtIdxs[b] < 0) - { - newtp = cur_cbs[b].truncIdxs[cur_tIndx[b]]; - } - else - { - newtp = cur_cbs[b].truncIdxs[cur_tIndx[b]] - cur_cbs[b].truncIdxs[cur_prevtIdxs[b]] - 1; - } - - // Mix of switch and if is faster - switch (newtp) - { - - case 0: - hbuf.writeBit(0); // Send one "0" bit - break; - - case 1: - hbuf.writeBits(2, 2); // Send one "1" and one "0" - break; - - case 2: - case 3: - case 4: - // Send two "1" bits followed by 2 bits - // representation of newtp-2 - hbuf.writeBits((3 << 2) | (newtp - 2), 4); - break; - - default: - if (newtp <= 35) - { - // Send four "1" bits followed by a five bits - // representation of newtp-5 - hbuf.writeBits((15 << 5) | (newtp - 5), 9); - } - else if (newtp <= 163) - { - // Send nine "1" bits followed by a seven bits - // representation of newtp-36 - hbuf.writeBits((511 << 7) | (newtp - 36), 16); - } - else - { - throw new System.ArithmeticException("Maximum number " + "of truncation " + "points exceeded"); - } - break; - - } - } - else - { - // Block not included in this layer - if (cur_prevtIdxs[b] >= 0) - { - // Already in previous layer. Send "0" bit - hbuf.writeBit(0); - } - else - { - // Not in any previous layers - cur_ttIncl.encode(m, n, ly, hbuf); - } - // Go to the next one. - continue; - } - - // Code-block length - - // We need to compute the maximum number of bits needed to - // signal the length of each terminated segment and the - // final truncation point. - newtp = 1; - maxi = cur_cbs[b].truncIdxs[cur_tIndx[b]]; - cblen = (cur_prevtIdxs[b] < 0) ? 0 : cur_cbs[b].truncRates[cur_cbs[b].truncIdxs[cur_prevtIdxs[b]]]; - - // Loop on truncation points - i = (cur_prevtIdxs[b] < 0) ? 0 : cur_cbs[b].truncIdxs[cur_prevtIdxs[b]] + 1; - int minbits = 0; - for (; i < maxi; i++, newtp++) - { - // If terminated truncation point calculate length - if (cur_cbs[b].isTermPass != null && cur_cbs[b].isTermPass[i]) - { - - // Calculate length - cblen = cur_cbs[b].truncRates[i] - cblen; - - // Calculate number of needed bits - prednbits = lblock[t][c][r][s][b] + MathUtil.log2(newtp); - minbits = ((cblen > 0) ? MathUtil.log2(cblen) : 0) + 1; - - // Update Lblock increment if needed - for (int j = prednbits; j < minbits; j++) - { - lblock[t][c][r][s][b]++; - hbuf.writeBit(1); - } - // Initialize for next length - newtp = 0; - cblen = cur_cbs[b].truncRates[i]; - } - } - - // Last truncation point length always sent - - // Calculate length - cblen = cur_cbs[b].truncRates[i] - cblen; - - // Calculate number of bits - prednbits = lblock[t][c][r][s][b] + MathUtil.log2(newtp); - minbits = ((cblen > 0) ? MathUtil.log2(cblen) : 0) + 1; - // Update Lblock increment if needed - for (int j = prednbits; j < minbits; j++) - { - lblock[t][c][r][s][b]++; - hbuf.writeBit(1); - } - - // End of comma-code increment - hbuf.writeBit(0); - - // There can be terminated several segments, send length - // info for all terminated truncation points in addition - // to final one - newtp = 1; - maxi = cur_cbs[b].truncIdxs[cur_tIndx[b]]; - cblen = (cur_prevtIdxs[b] < 0) ? 0 : cur_cbs[b].truncRates[cur_cbs[b].truncIdxs[cur_prevtIdxs[b]]]; - // Loop on truncation points and count the groups - i = (cur_prevtIdxs[b] < 0) ? 0 : cur_cbs[b].truncIdxs[cur_prevtIdxs[b]] + 1; - for (; i < maxi; i++, newtp++) - { - // If terminated truncation point, send length - if (cur_cbs[b].isTermPass != null && cur_cbs[b].isTermPass[i]) - { - - cblen = cur_cbs[b].truncRates[i] - cblen; - nbits = MathUtil.log2(newtp) + lblock[t][c][r][s][b]; - hbuf.writeBits(cblen, nbits); - - // Initialize for next length - newtp = 0; - cblen = cur_cbs[b].truncRates[i]; - } - } - // Last truncation point length is always signalled - // First calculate number of bits needed to signal - // Calculate length - cblen = cur_cbs[b].truncRates[i] - cblen; - nbits = MathUtil.log2(newtp) + lblock[t][c][r][s][b]; - hbuf.writeBits(cblen, nbits); - } // End loop on horizontal code-blocks - } // End loop on vertical code-blocks - } // End loop on subband - - // -> Copy the data to the body buffer - - // Ensure size for body data - if (bbuf == null || bbuf.Length < lblen) - { - bbuf = new byte[lblen]; - } - lbbuf = bbuf; - lblen = 0; - - for (int s = minsb; s < maxsb; s++) - { - // Loop on subbands - sb = (SubbandAn)root.getSubbandByIdx(r, s); - - cur_prevtIdxs = prevtIdxs[t][c][r][s]; - cur_cbs = cbs[s]; - cur_tIndx = tIndx[s]; - ncb = cur_prevtIdxs.Length; - - mend = (prec.cblk[s] == null) ? 0 : prec.cblk[s].Length; - for (int m = 0; m < mend; m++) - { - // Vertical code-blocks - nend = (prec.cblk[s][m] == null) ? 0 : prec.cblk[s][m].Length; - for (int n = 0; n < nend; n++) - { - // Horiz. cblks - cbCoord = prec.cblk[s][m][n].idx; - b = cbCoord.x + cbCoord.y * sb.numCb.x; - - if (cur_tIndx[b] > cur_prevtIdxs[b]) - { - - // Block included in this precinct -> Copy data to - // body buffer and get code-size - if (cur_prevtIdxs[b] < 0) - { - cblen = cur_cbs[b].truncRates[cur_cbs[b].truncIdxs[cur_tIndx[b]]]; - Array.Copy(cur_cbs[b].data, 0, lbbuf, lblen, cblen); - } - else - { - cblen = cur_cbs[b].truncRates[cur_cbs[b].truncIdxs[cur_tIndx[b]]] - cur_cbs[b].truncRates[cur_cbs[b].truncIdxs[cur_prevtIdxs[b]]]; - Array.Copy(cur_cbs[b].data, cur_cbs[b].truncRates[cur_cbs[b].truncIdxs[cur_prevtIdxs[b]]], lbbuf, lblen, cblen); - } - lblen += cblen; - - // Verifies if this code-block contains new ROI - // information - if (cur_cbs[b].nROIcoeff != 0 && (cur_prevtIdxs[b] == -1 || cur_cbs[b].truncIdxs[cur_prevtIdxs[b]] <= cur_cbs[b].nROIcp - 1)) - { - roiInPkt = true; - roiLen = lblen; - } - - // Update truncation point - cur_prevtIdxs[b] = cur_tIndx[b]; - } - } // End loop on horizontal code-blocks - } // End loop on vertical code-blocks - } // End loop on subbands - - packetWritable = true; - - // Must never happen - if (hbuf.Length == 0) - { - throw new System.ApplicationException("You have found a bug in PktEncoder, method:" + " encodePacket"); - } - - return hbuf; - } - - /// Saves the current state of this object. The last saved state - /// can be restored with the restore() method. - /// - /// - /// - /// - /// - public virtual void save() - { - int maxsbi, minsbi; - - // Have we done any save yet? - if (bak_lblock == null) - { - // Allocate backup buffers - bak_lblock = new int[ttIncl.Length][][][][]; - bak_prevtIdxs = new int[ttIncl.Length][][][][]; - for (int t = ttIncl.Length - 1; t >= 0; t--) - { - bak_lblock[t] = new int[ttIncl[t].Length][][][]; - bak_prevtIdxs[t] = new int[ttIncl[t].Length][][][]; - for (int c = ttIncl[t].Length - 1; c >= 0; c--) - { - bak_lblock[t][c] = new int[lblock[t][c].Length][][]; - bak_prevtIdxs[t][c] = new int[ttIncl[t][c].Length][][]; - for (int r = lblock[t][c].Length - 1; r >= 0; r--) - { - bak_lblock[t][c][r] = new int[lblock[t][c][r].Length][]; - bak_prevtIdxs[t][c][r] = new int[prevtIdxs[t][c][r].Length][]; - minsbi = (r == 0) ? 0 : 1; - maxsbi = (r == 0) ? 1 : 4; - for (int s = minsbi; s < maxsbi; s++) - { - bak_lblock[t][c][r][s] = new int[lblock[t][c][r][s].Length]; - bak_prevtIdxs[t][c][r][s] = new int[prevtIdxs[t][c][r][s].Length]; - } - } - } - } - } - - //-- Save the data - - // Use reference caches to minimize array access overhead - TagTreeEncoder[][][] ttIncl_t_c, ttMaxBP_t_c; - TagTreeEncoder[][] ttIncl_t_c_r, ttMaxBP_t_c_r; - int[][][] lblock_t_c, bak_lblock_t_c; - int[][] prevtIdxs_t_c_r, bak_prevtIdxs_t_c_r; - - // Loop on tiles - for (int t = ttIncl.Length - 1; t >= 0; t--) - { - // Loop on components - for (int c = ttIncl[t].Length - 1; c >= 0; c--) - { - // Initialize reference caches - lblock_t_c = lblock[t][c]; - bak_lblock_t_c = bak_lblock[t][c]; - ttIncl_t_c = ttIncl[t][c]; - ttMaxBP_t_c = ttMaxBP[t][c]; - // Loop on resolution levels - for (int r = lblock_t_c.Length - 1; r >= 0; r--) - { - // Initialize reference caches - ttIncl_t_c_r = ttIncl_t_c[r]; - ttMaxBP_t_c_r = ttMaxBP_t_c[r]; - prevtIdxs_t_c_r = prevtIdxs[t][c][r]; - bak_prevtIdxs_t_c_r = bak_prevtIdxs[t][c][r]; - - // Loop on subbands - minsbi = (r == 0) ? 0 : 1; - maxsbi = (r == 0) ? 1 : 4; - for (int s = minsbi; s < maxsbi; s++) - { - // Save 'lblock' - Array.Copy(lblock_t_c[r][s], 0, bak_lblock_t_c[r][s], 0, lblock_t_c[r][s].Length); - // Save 'prevtIdxs' - Array.Copy(prevtIdxs_t_c_r[s], 0, bak_prevtIdxs_t_c_r[s], 0, prevtIdxs_t_c_r[s].Length); - } // End loop on subbands - - // Loop on precincts - for (int p = ppinfo[t][c][r].Length - 1; p >= 0; p--) - { - if (p < ttIncl_t_c_r.Length) - { - // Loop on subbands - for (int s = minsbi; s < maxsbi; s++) - { - ttIncl_t_c_r[p][s].save(); - ttMaxBP_t_c_r[p][s].save(); - } // End loop on subbands - } - } // End loop on precincts - } // End loop on resolutions - } // End loop on components - } // End loop on tiles - - // Set the saved state - saved = true; - } - - /// Restores the last saved state of this object. An - /// IllegalArgumentException is thrown if no state has been saved. - /// - /// - /// - /// - /// - public virtual void restore() - { - int maxsbi, minsbi; - - if (!saved) - { - throw new System.ArgumentException(); - } - - // Invalidate last encoded body buffer - lbbuf = null; - - //-- Restore tha data - - // Use reference caches to minimize array access overhead - TagTreeEncoder[][][] ttIncl_t_c, ttMaxBP_t_c; - TagTreeEncoder[][] ttIncl_t_c_r, ttMaxBP_t_c_r; - int[][][] lblock_t_c, bak_lblock_t_c; - int[][] prevtIdxs_t_c_r, bak_prevtIdxs_t_c_r; - - // Loop on tiles - for (int t = ttIncl.Length - 1; t >= 0; t--) - { - // Loop on components - for (int c = ttIncl[t].Length - 1; c >= 0; c--) - { - // Initialize reference caches - lblock_t_c = lblock[t][c]; - bak_lblock_t_c = bak_lblock[t][c]; - ttIncl_t_c = ttIncl[t][c]; - ttMaxBP_t_c = ttMaxBP[t][c]; - // Loop on resolution levels - for (int r = lblock_t_c.Length - 1; r >= 0; r--) - { - // Initialize reference caches - ttIncl_t_c_r = ttIncl_t_c[r]; - ttMaxBP_t_c_r = ttMaxBP_t_c[r]; - prevtIdxs_t_c_r = prevtIdxs[t][c][r]; - bak_prevtIdxs_t_c_r = bak_prevtIdxs[t][c][r]; - - // Loop on subbands - minsbi = (r == 0) ? 0 : 1; - maxsbi = (r == 0) ? 1 : 4; - for (int s = minsbi; s < maxsbi; s++) - { - // Restore 'lblock' - Array.Copy(bak_lblock_t_c[r][s], 0, lblock_t_c[r][s], 0, lblock_t_c[r][s].Length); - // Restore 'prevtIdxs' - Array.Copy(bak_prevtIdxs_t_c_r[s], 0, prevtIdxs_t_c_r[s], 0, prevtIdxs_t_c_r[s].Length); - } // End loop on subbands - - // Loop on precincts - for (int p = ppinfo[t][c][r].Length - 1; p >= 0; p--) - { - if (p < ttIncl_t_c_r.Length) - { - // Loop on subbands - for (int s = minsbi; s < maxsbi; s++) - { - ttIncl_t_c_r[p][s].restore(); - ttMaxBP_t_c_r[p][s].restore(); - } // End loop on subbands - } - } // End loop on precincts - } // End loop on resolution levels - } // End loop on components - } // End loop on tiles - } - - /// Resets the state of the object to the initial state, as if the object - /// was just created. - /// - /// - public virtual void reset() - { - int maxsbi, minsbi; - - // Invalidate save - saved = false; - // Invalidate last encoded body buffer - lbbuf = null; - - // Reinitialize each element in the arrays - - // Use reference caches to minimize array access overhead - TagTreeEncoder[][][] ttIncl_t_c, ttMaxBP_t_c; - TagTreeEncoder[][] ttIncl_t_c_r, ttMaxBP_t_c_r; - int[][][] lblock_t_c; - int[][] prevtIdxs_t_c_r; - - // Loop on tiles - for (int t = ttIncl.Length - 1; t >= 0; t--) - { - // Loop on components - for (int c = ttIncl[t].Length - 1; c >= 0; c--) - { - // Initialize reference caches - lblock_t_c = lblock[t][c]; - ttIncl_t_c = ttIncl[t][c]; - ttMaxBP_t_c = ttMaxBP[t][c]; - // Loop on resolution levels - for (int r = lblock_t_c.Length - 1; r >= 0; r--) - { - // Initialize reference caches - ttIncl_t_c_r = ttIncl_t_c[r]; - ttMaxBP_t_c_r = ttMaxBP_t_c[r]; - prevtIdxs_t_c_r = prevtIdxs[t][c][r]; - - // Loop on subbands - minsbi = (r == 0) ? 0 : 1; - maxsbi = (r == 0) ? 1 : 4; - for (int s = minsbi; s < maxsbi; s++) - { - // Reset 'prevtIdxs' - ArrayUtil.intArraySet(prevtIdxs_t_c_r[s], -1); - // Reset 'lblock' - ArrayUtil.intArraySet(lblock_t_c[r][s], INIT_LBLOCK); - } // End loop on subbands - - // Loop on precincts - for (int p = ppinfo[t][c][r].Length - 1; p >= 0; p--) - { - if (p < ttIncl_t_c_r.Length) - { - // Loop on subbands - for (int s = minsbi; s < maxsbi; s++) - { - ttIncl_t_c_r[p][s].reset(); - ttMaxBP_t_c_r[p][s].reset(); - } // End loop on subbands - } - } // End loop on precincts - } // End loop on resolution levels - } // End loop on components - } // End loop on tiles - } - - /// Returns information about a given precinct - /// - /// - /// Tile index. - /// - /// - /// Component index. - /// - /// - /// Resolution level index. - /// - /// - /// Precinct index - /// - /// - public virtual PrecInfo getPrecInfo(int t, int c, int r, int p) - { - return ppinfo[t][c][r][p]; - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/codestream/writer/TagTreeEncoder.cs b/CSJ2K/j2k/codestream/writer/TagTreeEncoder.cs deleted file mode 100644 index 19009bce..00000000 --- a/CSJ2K/j2k/codestream/writer/TagTreeEncoder.cs +++ /dev/null @@ -1,595 +0,0 @@ -/* -* CVS identifier: -* -* $Id: TagTreeEncoder.java,v 1.10 2001/08/17 16:02:06 grosbois Exp $ -* -* Class: TagTreeEncoder -* -* Description: Encoder of tag trees -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.util; -using System; -namespace CSJ2K.j2k.codestream.writer -{ - - /// This class implements the tag tree encoder. A tag tree codes a 2D matrix of - /// integer elements in an efficient way. The encoding procedure 'encode()' - /// codes information about a value of the matrix, given a threshold. The - /// procedure encodes the sufficient information to identify whether or not the - /// value is greater than or equal to the threshold. - /// - ///

    The tag tree saves encoded information to a BitOutputBuffer.

    - /// - ///

    A particular and useful property of tag trees is that it is possible to - /// change a value of the matrix, provided both new and old values of the - /// element are both greater than or equal to the largest threshold which has - /// yet been supplied to the coding procedure 'encode()'. This property can be - /// exploited through the 'setValue()' method.

    - /// - ///

    This class allows saving the state of the tree at any point and - /// restoring it at a later time, by calling save() and restore().

    - /// - ///

    A tag tree can also be reused, or restarted, if one of the reset() - /// methods is called.

    - /// - ///

    The TagTreeDecoder class implements the tag tree decoder.

    - /// - ///

    Tag trees that have one dimension, or both, as 0 are allowed for - /// convenience. Of course no values can be set or coded in such cases.

    - /// - ///
    - /// - /// - /// - /// - /// - /// - public class TagTreeEncoder - { - /// Returns the number of leafs along the horizontal direction. - /// - /// - /// The number of leafs along the horizontal direction. - /// - /// - virtual public int Width - { - get - { - return w; - } - - } - /// Returns the number of leafs along the vertical direction. - /// - /// - /// The number of leafs along the vertical direction. - /// - /// - virtual public int Height - { - get - { - return h; - } - - } - /// Sets the values of the leafs to the new set of values and updates the - /// tag tree accordingly. No leaf can change its value if either the new or - /// old value is smaller than largest threshold which has yet been supplied - /// to 'encode()'. However such a leaf can keep its old value (i.e. new and - /// old value must be identical. - /// - ///

    This method is more efficient than the setValue() method if a large - /// proportion of the leafs change their value. Note that for leafs which - /// don't have their value defined yet the value should be - /// Integer.MAX_VALUE (which is the default initialization value).

    - /// - ///
    - /// The new values for the leafs, in lexicographical order. - /// - /// - /// - /// - /// - virtual public int[] Values - { - set - { - int i, maxt; - if (lvls == 0) - { - // Can't set values on empty tree - throw new System.ArgumentException(); - } - // Check the values - maxt = treeS[lvls - 1][0]; - for (i = w * h - 1; i >= 0; i--) - { - if ((treeV[0][i] < maxt || value[i] < maxt) && treeV[0][i] != value[i]) - { - throw new System.ArgumentException(); - } - // Update leaf value - treeV[0][i] = value[i]; - } - // Recalculate tree at other levels - recalcTreeV(); - } - - } - - /// The horizontal dimension of the base level - protected internal int w; - - /// The vertical dimensions of the base level - protected internal int h; - - /// The number of levels in the tag tree - protected internal int lvls; - - /// The tag tree values. The first index is the level, starting at level 0 - /// (leafs). The second index is the element within the level, in - /// lexicographical order. - /// - protected internal int[][] treeV; - - /// The tag tree state. The first index is the level, starting at level 0 - /// (leafs). The second index is the element within the level, in - /// lexicographical order. - /// - protected internal int[][] treeS; - - /// The saved tag tree values. The first index is the level, starting at - /// level 0 (leafs). The second index is the element within the level, in - /// lexicographical order. - /// - protected internal int[][] treeVbak; - - /// The saved tag tree state. The first index is the level, starting at - /// level 0 (leafs). The second index is the element within the level, in - /// lexicographical order. - /// - protected internal int[][] treeSbak; - - /// The saved state. If true the values and states of the tree have been - /// saved since the creation or last reset. - /// - protected internal bool saved; - - /// Creates a tag tree encoder with 'w' elements along the horizontal - /// dimension and 'h' elements along the vertical direction. The total - /// number of elements is thus 'vdim' x 'hdim'. - /// - ///

    The values of all elements are initialized to Integer.MAX_VALUE.

    - /// - ///
    - /// The number of elements along the horizontal direction. - /// - /// - /// The number of elements along the vertical direction. - /// - /// - public TagTreeEncoder(int h, int w) - { - int k; - // Check arguments - if (w < 0 || h < 0) - { - throw new System.ArgumentException(); - } - // Initialize elements - init(w, h); - // Set values to max - for (k = treeV.Length - 1; k >= 0; k--) - { - ArrayUtil.intArraySet(treeV[k], System.Int32.MaxValue); - } - } - - /// Creates a tag tree encoder with 'w' elements along the horizontal - /// dimension and 'h' elements along the vertical direction. The total - /// number of elements is thus 'vdim' x 'hdim'. The values of the leafs in - /// the tag tree are initialized to the values of the 'val' array. - /// - ///

    The values in the 'val' array are supposed to appear in - /// lexicographical order, starting at index 0.

    - /// - ///
    - /// The number of elements along the horizontal direction. - /// - /// - /// The number of elements along the vertical direction. - /// - /// - /// The values with which initialize the leafs of the tag tree. - /// - /// - public TagTreeEncoder(int h, int w, int[] val) - { - int k; - // Check arguments - if (w < 0 || h < 0 || val.Length < w * h) - { - throw new System.ArgumentException(); - } - // Initialize elements - init(w, h); - // Update leaf values - for (k = w * h - 1; k >= 0; k--) - { - treeV[0][k] = val[k]; - } - // Calculate values at other levels - recalcTreeV(); - } - - /// Initializes the variables of this class, given the dimensions at the - /// base level (leaf level). All the state ('treeS' array) and values - /// ('treeV' array) are intialized to 0. This method is called by the - /// constructors. - /// - /// - /// The number of elements along the vertical direction. - /// - /// - /// The number of elements along the horizontal direction. - /// - /// - private void init(int w, int h) - { - int i; - // Initialize dimensions - this.w = w; - this.h = h; - // Calculate the number of levels - if (w == 0 || h == 0) - { - lvls = 0; - } - else - { - lvls = 1; - while (h != 1 || w != 1) - { - // Loop until we reach root - w = (w + 1) >> 1; - h = (h + 1) >> 1; - lvls++; - } - } - // Allocate tree values and states (no need to initialize to 0 since - // it's the default) - treeV = new int[lvls][]; - treeS = new int[lvls][]; - w = this.w; - h = this.h; - for (i = 0; i < lvls; i++) - { - treeV[i] = new int[h * w]; - treeS[i] = new int[h * w]; - w = (w + 1) >> 1; - h = (h + 1) >> 1; - } - } - - /// Recalculates the values of the elements in the tag tree, in levels 1 - /// and up, based on the values of the leafs (level 0). - /// - /// - private void recalcTreeV() - { - int m, n, bi, lw, tm1, tm2, lh, k; - // Loop on all other levels, updating minimum - for (k = 0; k < lvls - 1; k++) - { - // Visit all elements in level - lw = (w + (1 << k) - 1) >> k; - lh = (h + (1 << k) - 1) >> k; - for (m = ((lh >> 1) << 1) - 2; m >= 0; m -= 2) - { - // All quads with 2 lines - for (n = ((lw >> 1) << 1) - 2; n >= 0; n -= 2) - { - // All quads with 2 columns - // Take minimum of 4 elements and put it in higher - // level - bi = m * lw + n; - tm1 = (treeV[k][bi] < treeV[k][bi + 1]) ? treeV[k][bi] : treeV[k][bi + 1]; - tm2 = (treeV[k][bi + lw] < treeV[k][bi + lw + 1]) ? treeV[k][bi + lw] : treeV[k][bi + lw + 1]; - treeV[k + 1][(m >> 1) * ((lw + 1) >> 1) + (n >> 1)] = tm1 < tm2 ? tm1 : tm2; - } - // Now we may have quad with 1 column, 2 lines - if (lw % 2 != 0) - { - n = ((lw >> 1) << 1); - // Take minimum of 2 elements and put it in higher - // level - bi = m * lw + n; - treeV[k + 1][(m >> 1) * ((lw + 1) >> 1) + (n >> 1)] = (treeV[k][bi] < treeV[k][bi + lw]) ? treeV[k][bi] : treeV[k][bi + lw]; - } - } - // Now we may have quads with 1 line, 2 or 1 columns - if (lh % 2 != 0) - { - m = ((lh >> 1) << 1); - for (n = ((lw >> 1) << 1) - 2; n >= 0; n -= 2) - { - // All quads with 2 columns - // Take minimum of 2 elements and put it in higher - // level - bi = m * lw + n; - treeV[k + 1][(m >> 1) * ((lw + 1) >> 1) + (n >> 1)] = (treeV[k][bi] < treeV[k][bi + 1]) ? treeV[k][bi] : treeV[k][bi + 1]; - } - // Now we may have quad with 1 column, 1 line - if (lw % 2 != 0) - { - // Just copy the value - n = ((lw >> 1) << 1); - treeV[k + 1][(m >> 1) * ((lw + 1) >> 1) + (n >> 1)] = treeV[k][m * lw + n]; - } - } - } - } - - /// Changes the value of a leaf in the tag tree. The new and old values of - /// the element must be not smaller than the largest threshold which has - /// yet been supplied to 'encode()'. - /// - /// - /// The vertical index of the element. - /// - /// - /// The horizontal index of the element. - /// - /// - /// The new value of the element. - /// - /// - public virtual void setValue(int m, int n, int v) - { - int k, idx; - // Check arguments - if (lvls == 0 || n < 0 || n >= w || v < treeS[lvls - 1][0] || treeV[0][m * w + n] < treeS[lvls - 1][0]) - { - throw new System.ArgumentException(); - } - // Update the leaf value - treeV[0][m * w + n] = v; - // Update all parents - for (k = 1; k < lvls; k++) - { - idx = (m >> k) * ((w + (1 << k) - 1) >> k) + (n >> k); - if (v < treeV[k][idx]) - { - // We need to update minimum and continue checking - // in higher levels - treeV[k][idx] = v; - } - else - { - // We are done: v is equal or less to minimum - // in this level, no other minimums to update. - break; - } - } - } - - /// Encodes information for the specified element of the tree, given the - /// threshold and sends it to the 'out' stream. The information that is - /// coded is whether or not the value of the element is greater than or - /// equal to the value of the threshold. - /// - /// - /// The vertical index of the element. - /// - /// - /// The horizontal index of the element. - /// - /// - /// The threshold to use for encoding. It must be non-negative. - /// - /// - /// The stream where to write the coded information. - /// - /// - public virtual void encode(int m, int n, int t, BitOutputBuffer out_Renamed) - { - int k, ts, idx, tmin; - - // Check arguments - if (m >= h || n >= w || t < 0) - { - throw new System.ArgumentException(); - } - - // Initialize - k = lvls - 1; - tmin = treeS[k][0]; - - // Loop on levels - while (true) - { - // Index of element in level 'k' - idx = (m >> k) * ((w + (1 << k) - 1) >> k) + (n >> k); - // Cache state - ts = treeS[k][idx]; - if (ts < tmin) - { - ts = tmin; - } - while (t > ts) - { - if (treeV[k][idx] > ts) - { - out_Renamed.writeBit(0); // Send '0' bit - } - else if (treeV[k][idx] == ts) - { - out_Renamed.writeBit(1); // Send '1' bit - } - else - { - // we are done: set ts and get out of this while - ts = t; - break; - } - // Increment of treeS[k][idx] - ts++; - } - // Update state - treeS[k][idx] = ts; - // Update tmin or terminate - if (k > 0) - { - tmin = ts < treeV[k][idx] ? ts : treeV[k][idx]; - k--; - } - else - { - // Terminate - return; - } - } - } - - /// Saves the current values and state of the tree. Calling restore() - /// restores the tag tree the saved state. - /// - /// - /// - /// - /// - public virtual void save() - { - int k; // i removed - - if (treeVbak == null) - { - // Nothing saved yet - // Allocate saved arrays - // treeV and treeS have the same dimensions - treeVbak = new int[lvls][]; - treeSbak = new int[lvls][]; - for (k = lvls - 1; k >= 0; k--) - { - treeVbak[k] = new int[treeV[k].Length]; - treeSbak[k] = new int[treeV[k].Length]; - } - } - - // Copy the arrays - for (k = treeV.Length - 1; k >= 0; k--) - { - Array.Copy(treeV[k], 0, treeVbak[k], 0, treeV[k].Length); - Array.Copy(treeS[k], 0, treeSbak[k], 0, treeS[k].Length); - } - - // Set saved state - saved = true; - } - - /// Restores the saved values and state of the tree. An - /// IllegalArgumentException is thrown if the tree values and state have - /// not been saved yet. - /// - /// - /// - /// - /// - public virtual void restore() - { - int k; // i removed - - if (!saved) - { - // Nothing saved yet - throw new System.ArgumentException(); - } - - // Copy the arrays - for (k = lvls - 1; k >= 0; k--) - { - Array.Copy(treeVbak[k], 0, treeV[k], 0, treeV[k].Length); - Array.Copy(treeSbak[k], 0, treeS[k], 0, treeS[k].Length); - } - } - - /// Resets the tree values and state. All the values are set to - /// Integer.MAX_VALUE and the states to 0. - /// - /// - public virtual void reset() - { - int k; - // Set all values to Integer.MAX_VALUE - // and states to 0 - for (k = lvls - 1; k >= 0; k--) - { - ArrayUtil.intArraySet(treeV[k], System.Int32.MaxValue); - ArrayUtil.intArraySet(treeS[k], 0); - } - // Invalidate saved tree - saved = false; - } - - /// Resets the tree values and state. The values are set to the values in - /// 'val'. The states are all set to 0. - /// - /// - /// The new values for the leafs, in lexicographical order. - /// - /// - public virtual void reset(int[] val) - { - int k; - // Set values for leaf level - for (k = w * h - 1; k >= 0; k--) - { - treeV[0][k] = val[k]; - } - // Calculate values at other levels - recalcTreeV(); - // Set all states to 0 - for (k = lvls - 1; k >= 0; k--) - { - ArrayUtil.intArraySet(treeS[k], 0); - } - // Invalidate saved tree - saved = false; - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/decoder/DecoderSpecs.cs b/CSJ2K/j2k/decoder/DecoderSpecs.cs deleted file mode 100644 index 62a32bd6..00000000 --- a/CSJ2K/j2k/decoder/DecoderSpecs.cs +++ /dev/null @@ -1,201 +0,0 @@ -/* -* CVS identifier: -* -* $Id: DecoderSpecs.java,v 1.25 2002/07/25 15:06:17 grosbois Exp $ -* -* Class: DecoderSpecs -* -* Description: Hold all decoder specifications -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.entropy; -using CSJ2K.j2k.image; -using CSJ2K.j2k.quantization; -using CSJ2K.j2k.roi; -using CSJ2K.j2k.wavelet.synthesis; -namespace CSJ2K.j2k.decoder -{ - - /// This class holds references to each module specifications used in the - /// decoding chain. This avoid big amount of arguments in method calls. A - /// specification contains values of each tile-component for one module. All - /// members must be instance of ModuleSpec class (or its children). - /// - /// - /// - /// - /// - public class DecoderSpecs : System.ICloneable - { - /// Returns a copy of the current object. - /// - /// - virtual public DecoderSpecs Copy - { - get - { - DecoderSpecs decSpec2; - try - { - decSpec2 = (DecoderSpecs)this.Clone(); - } - //UPGRADE_NOTE: Exception 'java.lang.CloneNotSupportedException' was converted to 'System.Exception' which has different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1100'" - catch (System.Exception) - { - throw new System.ApplicationException("Cannot clone the DecoderSpecs instance"); - } - // Quantization - decSpec2.qts = (QuantTypeSpec)qts.Copy; - decSpec2.qsss = (QuantStepSizeSpec)qsss.Copy; - decSpec2.gbs = (GuardBitsSpec)gbs.Copy; - // Wavelet transform - decSpec2.wfs = (SynWTFilterSpec)wfs.Copy; - decSpec2.dls = (IntegerSpec)dls.Copy; - // Component transformation - decSpec2.cts = (CompTransfSpec)cts.Copy; - // ROI - if (rois != null) - { - decSpec2.rois = (MaxShiftSpec)rois.Copy; - } - return decSpec2; - } - - } - - /// ICC Profiling specifications - public ModuleSpec iccs; - - /// ROI maxshift value specifications - public MaxShiftSpec rois; - - /// Quantization type specifications - public QuantTypeSpec qts; - - /// Quantization normalized base step size specifications - public QuantStepSizeSpec qsss; - - /// Number of guard bits specifications - public GuardBitsSpec gbs; - - /// Analysis wavelet filters specifications - public SynWTFilterSpec wfs; - - /// Number of decomposition levels specifications - public IntegerSpec dls; - - /// Number of layers specifications - public IntegerSpec nls; - - /// Progression order specifications - public IntegerSpec pos; - - /// The Entropy decoder options specifications - public ModuleSpec ecopts; - - /// The component transformation specifications - public CompTransfSpec cts; - - /// The progression changes specifications - public ModuleSpec pcs; - - /// The error resilience specifications concerning the entropy - /// decoder - /// - public ModuleSpec ers; - - /// Precinct partition specifications - public PrecinctSizeSpec pss; - - /// The Start Of Packet (SOP) markers specifications - public ModuleSpec sops; - - /// The End of Packet Headers (EPH) markers specifications - public ModuleSpec ephs; - - /// Code-blocks sizes specification - public CBlkSizeSpec cblks; - - /// Packed packet header specifications - public ModuleSpec pphs; - - /// Initialize all members with the given number of tiles and components. - /// - /// - /// Number of tiles - /// - /// - /// Number of components - /// - /// - public DecoderSpecs(int nt, int nc) - { - // Quantization - qts = new QuantTypeSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP); - qsss = new QuantStepSizeSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP); - gbs = new GuardBitsSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP); - - // Wavelet transform - wfs = new SynWTFilterSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP); - dls = new IntegerSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP); - - // Component transformation - cts = new CompTransfSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP); - - // Entropy decoder - ecopts = new ModuleSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP); - ers = new ModuleSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP); - cblks = new CBlkSizeSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP); - - // Precinct partition - pss = new PrecinctSizeSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP, dls); - - // Codestream - nls = new IntegerSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE); - pos = new IntegerSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE); - pcs = new ModuleSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE); - sops = new ModuleSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE); - ephs = new ModuleSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE); - pphs = new ModuleSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE); - iccs = new ModuleSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE); - pphs.setDefault((System.Object)false); - } - //UPGRADE_TODO: The following method was automatically generated and it must be implemented in order to preserve the class logic. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1232'" - virtual public System.Object Clone() - { - return null; - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/encoder/EncoderSpecs.cs b/CSJ2K/j2k/encoder/EncoderSpecs.cs deleted file mode 100644 index 28ead9b5..00000000 --- a/CSJ2K/j2k/encoder/EncoderSpecs.cs +++ /dev/null @@ -1,187 +0,0 @@ -/* -* CVS identifier: -* -* $Id: EncoderSpecs.java,v 1.35 2001/05/08 16:10:40 grosbois Exp $ -* -* Class: EncoderSpecs -* -* Description: Hold all encoder specifications -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.entropy; -using CSJ2K.j2k.image; -using CSJ2K.j2k.image.forwcomptransf; -using CSJ2K.j2k.quantization; -using CSJ2K.j2k.quantization.quantizer; -using CSJ2K.j2k.roi; -using CSJ2K.j2k.util; -using CSJ2K.j2k.wavelet.analysis; -namespace CSJ2K.j2k.encoder -{ - - /// This class holds references to each module specifications used in the - /// encoding chain. This avoid big amount of arguments in method calls. A - /// specification contains values of each tile-component for one module. All - /// members must be instance of ModuleSpec class (or its children). - /// - /// - /// - /// - /// - public class EncoderSpecs - { - - /// ROI maxshift value specifications - public MaxShiftSpec rois; - - /// Quantization type specifications - public QuantTypeSpec qts; - - /// Quantization normalized base step size specifications - public QuantStepSizeSpec qsss; - - /// Number of guard bits specifications - public GuardBitsSpec gbs; - - /// Analysis wavelet filters specifications - public AnWTFilterSpec wfs; - - /// Component transformation specifications - public CompTransfSpec cts; - - /// Number of decomposition levels specifications - public IntegerSpec dls; - - /// The length calculation specifications - public StringSpec lcs; - - /// The termination type specifications - public StringSpec tts; - - /// Error resilience segment symbol use specifications - public StringSpec sss; - - /// Causal stripes specifications - public StringSpec css; - - /// Regular termination specifications - public StringSpec rts; - - /// MQ reset specifications - public StringSpec mqrs; - - /// By-pass mode specifications - public StringSpec bms; - - /// Precinct partition specifications - public PrecinctSizeSpec pss; - - /// Start of packet (SOP) marker use specification - public StringSpec sops; - - /// End of packet header (EPH) marker use specification - public StringSpec ephs; - - /// Code-blocks sizes specification - public CBlkSizeSpec cblks; - - /// Progression/progression changes specification - public ProgressionSpec pocs; - - /// The number of tiles within the image - public int nTiles; - - /// The number of components within the image - public int nComp; - - /// Initialize all members with the given number of tiles and components - /// and the command-line arguments stored in a ParameterList instance - /// - /// - /// Number of tiles - /// - /// - /// Number of components - /// - /// - /// The image source (used to get the image size) - /// - /// - /// The ParameterList instance - /// - /// - public EncoderSpecs(int nt, int nc, BlkImgDataSrc imgsrc, ParameterList pl) - { - nTiles = nt; - nComp = nc; - - // ROI - rois = new MaxShiftSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP); - - // Quantization - pl.checkList(Quantizer.OPT_PREFIX, CSJ2K.j2k.util.ParameterList.toNameArray(Quantizer.ParameterInfo)); - qts = new QuantTypeSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP, pl); - qsss = new QuantStepSizeSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP, pl); - gbs = new GuardBitsSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP, pl); - - // Wavelet transform - wfs = new AnWTFilterSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP, qts, pl); - dls = new IntegerSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP, pl, "Wlev"); - - // Component transformation - cts = new ForwCompTransfSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE, wfs, pl); - - // Entropy coder - System.String[] strLcs = new System.String[] { "near_opt", "lazy_good", "lazy" }; - lcs = new StringSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP, "Clen_calc", strLcs, pl); - System.String[] strTerm = new System.String[] { "near_opt", "easy", "predict", "full" }; - tts = new StringSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP, "Cterm_type", strTerm, pl); - System.String[] strBoolean = new System.String[] { "on", "off" }; - sss = new StringSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP, "Cseg_symbol", strBoolean, pl); - css = new StringSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP, "Ccausal", strBoolean, pl); - rts = new StringSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP, "Cterminate", strBoolean, pl); - mqrs = new StringSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP, "CresetMQ", strBoolean, pl); - bms = new StringSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP, "Cbypass", strBoolean, pl); - cblks = new CBlkSizeSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP, pl); - - // Precinct partition - pss = new PrecinctSizeSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP, imgsrc, dls, pl); - - // Codestream - sops = new StringSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE, "Psop", strBoolean, pl); - ephs = new StringSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE, "Peph", strBoolean, pl); - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/entropy/CBlkSizeSpec.cs b/CSJ2K/j2k/entropy/CBlkSizeSpec.cs deleted file mode 100644 index 2f1a3e91..00000000 --- a/CSJ2K/j2k/entropy/CBlkSizeSpec.cs +++ /dev/null @@ -1,537 +0,0 @@ -/* -* CVS identifier: -* -* $Id: CBlkSizeSpec.java,v 1.11 2001/02/14 10:38:18 grosbois Exp $ -* -* Class: CBlkSizeSpec -* -* Description: Specification of the code-blocks size -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.util; -namespace CSJ2K.j2k.entropy -{ - - /// This class extends ModuleSpec class for code-blocks sizes holding purposes. - /// - ///

    It stores the size a of code-block. - /// - ///

    - public class CBlkSizeSpec : ModuleSpec - { - /// Returns the maximum code-block's width - /// - /// - virtual public int MaxCBlkWidth - { - get - { - return maxCBlkWidth; - } - - } - /// Returns the maximum code-block's height - /// - /// - virtual public int MaxCBlkHeight - { - get - { - return maxCBlkHeight; - } - - } - - /// Name of the option - private const System.String optName = "Cblksiz"; - - /// The maximum code-block width - private int maxCBlkWidth = 0; - - /// The maximum code-block height - private int maxCBlkHeight = 0; - - /// Creates a new CBlkSizeSpec object for the specified number of tiles and - /// components. - /// - /// - /// The number of tiles - /// - /// - /// The number of components - /// - /// - /// the type of the specification module i.e. tile specific, - /// component specific or both. - /// - /// - public CBlkSizeSpec(int nt, int nc, byte type) : base(nt, nc, type) - { - } - - /// Creates a new CBlkSizeSpec object for the specified number of tiles and - /// components and the ParameterList instance. - /// - /// - /// The number of tiles - /// - /// - /// The number of components - /// - /// - /// the type of the specification module i.e. tile specific, - /// component specific or both. - /// - /// - /// The image source (used to get the image size) - /// - /// - /// The ParameterList instance - /// - /// - public CBlkSizeSpec(int nt, int nc, byte type, ParameterList pl) : base(nt, nc, type) - { - - bool firstVal = true; - System.String param = pl.getParameter(optName); - - // Precinct partition is used : parse arguments - SupportClass.Tokenizer stk = new SupportClass.Tokenizer(param); - byte curSpecType = SPEC_DEF; // Specification type of the - // current parameter - bool[] tileSpec = null; // Tiles concerned by the specification - bool[] compSpec = null; // Components concerned by the specification - int ci, ti; // i, xIdx removed - System.String word = null; // current word - System.String errMsg = null; - - while (stk.HasMoreTokens()) - { - word = stk.NextToken(); - - switch (word[0]) - { - - - case 't': // Tiles specification - tileSpec = parseIdx(word, nTiles); - if (curSpecType == SPEC_COMP_DEF) - { - curSpecType = SPEC_TILE_COMP; - } - else - { - curSpecType = SPEC_TILE_DEF; - } - break; - - - case 'c': // Components specification - compSpec = parseIdx(word, nComp); - if (curSpecType == SPEC_TILE_DEF) - { - curSpecType = SPEC_TILE_COMP; - } - else - { - curSpecType = SPEC_COMP_DEF; - } - break; - - - default: - if (!System.Char.IsDigit(word[0])) - { - errMsg = "Bad construction for parameter: " + word; - throw new System.ArgumentException(errMsg); - } - System.Int32[] dim = new System.Int32[2]; - // Get code-block's width - try - { - dim[0] = System.Int32.Parse(word); - // Check that width is not > - // StdEntropyCoderOptions.MAX_CB_DIM - if (dim[0] > CSJ2K.j2k.entropy.StdEntropyCoderOptions.MAX_CB_DIM) - { - errMsg = "'" + optName + "' option : the code-block's " + "width cannot be greater than " + CSJ2K.j2k.entropy.StdEntropyCoderOptions.MAX_CB_DIM; - throw new System.ArgumentException(errMsg); - } - // Check that width is not < - // StdEntropyCoderOptions.MIN_CB_DIM - if (dim[0] < CSJ2K.j2k.entropy.StdEntropyCoderOptions.MIN_CB_DIM) - { - errMsg = "'" + optName + "' option : the code-block's " + "width cannot be less than " + CSJ2K.j2k.entropy.StdEntropyCoderOptions.MIN_CB_DIM; - throw new System.ArgumentException(errMsg); - } - // Check that width is a power of 2 - if (dim[0] != (1 << MathUtil.log2(dim[0]))) - { - errMsg = "'" + optName + "' option : the code-block's " + "width must be a power of 2"; - throw new System.ArgumentException(errMsg); - } - } - catch (System.FormatException) - { - errMsg = "'" + optName + "' option : the code-block's " + "width could not be parsed."; - throw new System.ArgumentException(errMsg); - } - // Get the next word in option - try - { - word = stk.NextToken(); - } - catch (System.ArgumentOutOfRangeException) - { - errMsg = "'" + optName + "' option : could not parse the " + "code-block's height"; - throw new System.ArgumentException(errMsg); - } - // Get the code-block's height - try - { - dim[1] = System.Int32.Parse(word); - // Check that height is not > - // StdEntropyCoderOptions.MAX_CB_DIM - if (dim[1] > CSJ2K.j2k.entropy.StdEntropyCoderOptions.MAX_CB_DIM) - { - errMsg = "'" + optName + "' option : the code-block's " + "height cannot be greater than " + CSJ2K.j2k.entropy.StdEntropyCoderOptions.MAX_CB_DIM; - throw new System.ArgumentException(errMsg); - } - // Check that height is not < - // StdEntropyCoderOptions.MIN_CB_DIM - if (dim[1] < CSJ2K.j2k.entropy.StdEntropyCoderOptions.MIN_CB_DIM) - { - errMsg = "'" + optName + "' option : the code-block's " + "height cannot be less than " + CSJ2K.j2k.entropy.StdEntropyCoderOptions.MIN_CB_DIM; - throw new System.ArgumentException(errMsg); - } - // Check that height is a power of 2 - if (dim[1] != (1 << MathUtil.log2(dim[1]))) - { - errMsg = "'" + optName + "' option : the code-block's " + "height must be a power of 2"; - throw new System.ArgumentException(errMsg); - } - // Check that the code-block 'area' (i.e. width*height) is - // not greater than StdEntropyCoderOptions.MAX_CB_AREA - if (dim[0] * dim[1] > CSJ2K.j2k.entropy.StdEntropyCoderOptions.MAX_CB_AREA) - { - errMsg = "'" + optName + "' option : The " + "code-block's area (i.e. width*height) " + "cannot be greater than " + CSJ2K.j2k.entropy.StdEntropyCoderOptions.MAX_CB_AREA; - throw new System.ArgumentException(errMsg); - } - } - catch (System.FormatException) - { - errMsg = "'" + optName + "' option : the code-block's height " + "could not be parsed."; - throw new System.ArgumentException(errMsg); - } - - // Store the maximum dimensions if necessary - if (dim[0] > maxCBlkWidth) - { - maxCBlkWidth = dim[0]; - } - - if (dim[1] > maxCBlkHeight) - { - maxCBlkHeight = dim[1]; - } - - if (firstVal) - { - // This is the first time a value is given so we set it as - // the default one - setDefault((System.Object)(dim)); - firstVal = false; - } - - switch (curSpecType) - { - - case SPEC_DEF: - setDefault((System.Object)(dim)); - break; - - case SPEC_TILE_DEF: - for (ti = tileSpec.Length - 1; ti >= 0; ti--) - { - if (tileSpec[ti]) - { - setTileDef(ti, (System.Object)(dim)); - } - } - break; - - case SPEC_COMP_DEF: - for (ci = compSpec.Length - 1; ci >= 0; ci--) - { - if (compSpec[ci]) - { - setCompDef(ci, (System.Object)(dim)); - } - } - break; - - default: - for (ti = tileSpec.Length - 1; ti >= 0; ti--) - { - for (ci = compSpec.Length - 1; ci >= 0; ci--) - { - if (tileSpec[ti] && compSpec[ci]) - { - setTileCompVal(ti, ci, (System.Object)(dim)); - } - } - } - break; - - } - break; - - } // end switch - } - } - - /// Returns the code-block width : - /// - ///
      - ///
    • for the specified tile/component
    • - ///
    • for the specified tile
    • - ///
    • for the specified component
    • - ///
    • default value
    • - ///
    - /// - /// The value returned depends on the value of the variable 'type' which - /// can take the following values :
    - /// - ///
      - ///
    • SPEC_DEF -> Default value is returned. t and c values are - /// ignored
    • - ///
    • SPEC_COMP_DEF -> Component default value is returned. t value is - /// ignored
    • - ///
    • SPEC_TILE_DEF -> Tile default value is returned. c value is - /// ignored
    • - ///
    • SPEC_TILE_COMP -> Tile/Component value is returned.
    • - ///
    - /// - ///
    - /// The type of the value we want to be returned - /// - /// - /// The tile index - /// - /// - /// the component index - /// - /// - /// The code-block width for the specified tile and component - /// - /// - public virtual int getCBlkWidth(byte type, int t, int c) - { - //UPGRADE_TODO: The 'System.Int32' structure does not have an equivalent to NULL. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1291'" - System.Int32[] dim = null; - switch (type) - { - - case SPEC_DEF: - dim = (System.Int32[])getDefault(); - break; - - case SPEC_COMP_DEF: - dim = (System.Int32[])getCompDef(c); - break; - - case SPEC_TILE_DEF: - dim = (System.Int32[])getTileDef(t); - break; - - case SPEC_TILE_COMP: - dim = (System.Int32[])getTileCompVal(t, c); - break; - } - return dim[0]; - } - - /// Returns the code-block height: - /// - ///
      - ///
    • for the specified tile/component
    • - ///
    • for the specified tile
    • - ///
    • for the specified component
    • - ///
    • default value
    • - ///
    - /// - /// The value returned depends on the value of the variable 'type' which - /// can take the following values : - /// - ///
      - ///
    • SPEC_DEF -> Default value is returned. t and c values are - /// ignored
    • - ///
    • SPEC_COMP_DEF -> Component default value is returned. t value is - /// ignored
    • - ///
    • SPEC_TILE_DEF -> Tile default value is returned. c value is - /// ignored
    • - ///
    • SPEC_TILE_COMP -> Tile/Component value is returned.
    • - ///
    - /// - ///
    - /// The type of the value we want to be returned - /// - /// - /// The tile index - /// - /// - /// the component index - /// - /// - /// The code-block height for the specified tile and component - /// - /// - public virtual int getCBlkHeight(byte type, int t, int c) - { - //UPGRADE_TODO: The 'System.Int32' structure does not have an equivalent to NULL. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1291'" - System.Int32[] dim = null; - switch (type) - { - - case SPEC_DEF: - dim = (System.Int32[])getDefault(); - break; - - case SPEC_COMP_DEF: - dim = (System.Int32[])getCompDef(c); - break; - - case SPEC_TILE_DEF: - dim = (System.Int32[])getTileDef(t); - break; - - case SPEC_TILE_COMP: - dim = (System.Int32[])getTileCompVal(t, c); - break; - } - return dim[1]; - } - - /// Sets default value for this module - /// - /// - /// Default value - /// - /// - public override void setDefault(System.Object value_Renamed) - { - base.setDefault(value_Renamed); - - // Store the biggest code-block dimensions - storeHighestDims((System.Int32[])value_Renamed); - } - - /// Sets default value for specified tile and specValType tag if allowed by - /// its priority. - /// - /// - /// Tile index. - /// - /// - /// Tile's default value - /// - /// - public override void setTileDef(int t, System.Object value_Renamed) - { - base.setTileDef(t, value_Renamed); - - // Store the biggest code-block dimensions - storeHighestDims((System.Int32[])value_Renamed); - } - - /// Sets default value for specified component and specValType tag if - /// allowed by its priority. - /// - /// - /// Component index - /// - /// - /// Component's default value - /// - /// - public override void setCompDef(int c, System.Object value_Renamed) - { - base.setCompDef(c, value_Renamed); - - // Store the biggest code-block dimensions - storeHighestDims((System.Int32[])value_Renamed); - } - - /// Sets value for specified tile-component. - /// - /// - /// Tie index - /// - /// - /// Component index - /// - /// - /// Tile-component's value - /// - /// - public override void setTileCompVal(int t, int c, System.Object value_Renamed) - { - base.setTileCompVal(t, c, value_Renamed); - - // Store the biggest code-block dimensions - storeHighestDims((System.Int32[])value_Renamed); - } - - /// Stores the highest code-block width and height - /// - /// - /// The 2 elements array that contains the code-block width and - /// height. - /// - /// - private void storeHighestDims(System.Int32[] dim) - { - // Store the biggest code-block dimensions - if (dim[0] > maxCBlkWidth) - { - maxCBlkWidth = dim[0]; - } - if (dim[1] > maxCBlkHeight) - { - maxCBlkHeight = dim[1]; - } - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/entropy/CodedCBlk.cs b/CSJ2K/j2k/entropy/CodedCBlk.cs deleted file mode 100644 index d81486e6..00000000 --- a/CSJ2K/j2k/entropy/CodedCBlk.cs +++ /dev/null @@ -1,119 +0,0 @@ -/* -* CVS identifier: -* -* $Id: CodedCBlk.java,v 1.9 2001/08/17 09:42:13 grosbois Exp $ -* -* Class: CodedCBlk -* -* Description: The generic coded (compressed) code-block -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -namespace CSJ2K.j2k.entropy -{ - - /// This is the generic class to store coded (compressed) code-block. It stores - /// the compressed data as well as the necessary side-information. - /// - ///

    This class is normally not used. Instead the EncRDCBlk, EncLyrdCBlk and - /// the DecLyrdCBlk subclasses are used.

    - /// - ///
    - /// - /// - /// - /// - /// - public class CodedCBlk - { - - /// The horizontal index of the code-block, within the subband. - public int n; - - /// The vertical index of the code-block, within the subband. - public int m; - - /// The number of skipped most significant bit-planes. - public int skipMSBP; - - /// The compressed data - public byte[] data; - - /// Creates a new CodedCBlk object wit the default values and without - /// allocating any space for its members. - /// - /// - public CodedCBlk() - { - } - - /// Creates a new CodedCBlk object with the specified values. - /// - /// - /// The horizontal index of the code-block, within the subband. - /// - /// - /// The vertical index of the code-block, within the subband. - /// - /// - /// The number of skipped most significant bit-planes for - /// this code-block. - /// - /// - /// The compressed data. This array is referenced by this - /// object so it should not be modified after. - /// - /// - public CodedCBlk(int m, int n, int skipMSBP, byte[] data) - { - this.m = m; - this.n = n; - this.skipMSBP = skipMSBP; - this.data = data; - } - - /// Returns the contents of the object in a string. The string contains the - /// following data: 'm', 'n', 'skipMSBP' and 'data.length. This is used for - /// debugging. - /// - /// - /// A string with the contents of the object - /// - /// - public override System.String ToString() - { - return "m=" + m + ", n=" + n + ", skipMSBP=" + skipMSBP + ", data.length=" + ((data != null) ? "" + data.Length : "(null)"); - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/entropy/PrecinctSizeSpec.cs b/CSJ2K/j2k/entropy/PrecinctSizeSpec.cs deleted file mode 100644 index 1c3b1b61..00000000 --- a/CSJ2K/j2k/entropy/PrecinctSizeSpec.cs +++ /dev/null @@ -1,492 +0,0 @@ -/* -* CVS identifier: -* -* $Id: PrecinctSizeSpec.java,v 1.18 2001/09/14 09:26:58 grosbois Exp $ -* -* Class: PrecinctSizeSpec -* -* Description: Specification of the precinct sizes -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.image; -using CSJ2K.j2k.util; -namespace CSJ2K.j2k.entropy -{ - - /// This class extends ModuleSpec class for precinct partition sizes holding - /// purposes. - /// - ///

    It stores the size a of precinct when precinct partition is used or not. - /// If precinct partition is used, we can have several packets for a given - /// resolution level whereas there is only one packet per resolution level if - /// no precinct partition is used. - /// - ///

    - public class PrecinctSizeSpec : ModuleSpec - { - - /// Name of the option - private const System.String optName = "Cpp"; - - /// Reference to wavelet number of decomposition levels for each - /// tile-component. - /// - private IntegerSpec dls; - - /// Creates a new PrecinctSizeSpec object for the specified number of tiles - /// and components. - /// - /// - /// The number of tiles - /// - /// - /// The number of components - /// - /// - /// the type of the specification module i.e. tile specific, - /// component specific or both. - /// - /// - /// Reference to the number of decomposition levels - /// specification - /// - /// - public PrecinctSizeSpec(int nt, int nc, byte type, IntegerSpec dls) : base(nt, nc, type) - { - this.dls = dls; - } - - /// Creates a new PrecinctSizeSpec object for the specified number of tiles - /// and components and the ParameterList instance. - /// - /// - /// The number of tiles - /// - /// - /// The number of components - /// - /// - /// the type of the specification module i.e. tile specific, - /// component specific or both. - /// - /// - /// The image source (used to get the image size) - /// - /// - /// The ParameterList instance - /// - /// - public PrecinctSizeSpec(int nt, int nc, byte type, BlkImgDataSrc imgsrc, IntegerSpec dls, ParameterList pl) : base(nt, nc, type) - { - - this.dls = dls; - - // The precinct sizes are stored in a 2 elements vector array, the - // first element containing a vector for the precincts width for each - // resolution level and the second element containing a vector for the - // precincts height for each resolution level. The precincts sizes are - // specified from the highest resolution level to the lowest one - // (i.e. 0). If there are less elements than the number of - // decomposition levels, the last element is used for all remaining - // resolution levels (i.e. if the precincts sizes are specified only - // for resolutions levels 5, 4 and 3, then the precincts size for - // resolution levels 2, 1 and 0 will be the same as the size used for - // resolution level 3). - - // Boolean used to know if we were previously reading a precinct's - // size or if we were reading something else. - bool wasReadingPrecinctSize = false; - - System.String param = pl.getParameter(optName); - - // Set precinct sizes to default i.e. 2^15 = - // Markers.PRECINCT_PARTITION_DEF_SIZE - System.Collections.ArrayList[] tmpv = new System.Collections.ArrayList[2]; - tmpv[0] = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); // ppx - tmpv[0].Add((System.Int32)CSJ2K.j2k.codestream.Markers.PRECINCT_PARTITION_DEF_SIZE); - tmpv[1] = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); // ppy - tmpv[1].Add((System.Int32)CSJ2K.j2k.codestream.Markers.PRECINCT_PARTITION_DEF_SIZE); - setDefault(tmpv); - - if (param == null) - { - // No precinct size specified in the command line so we do not try - // to parse it. - return; - } - - // Precinct partition is used : parse arguments - SupportClass.Tokenizer stk = new SupportClass.Tokenizer(param); - byte curSpecType = SPEC_DEF; // Specification type of the - // current parameter - bool[] tileSpec = null; // Tiles concerned by the specification - bool[] compSpec = null; // Components concerned by the specification - int ci, ti; //i, xIdx removed - - bool endOfParamList = false; - System.String word = null; // current word - System.Int32 w, h; - System.String errMsg = null; - - while ((stk.HasMoreTokens() || wasReadingPrecinctSize) && !endOfParamList) - { - - System.Collections.ArrayList[] v = new System.Collections.ArrayList[2]; // v[0] : ppx, v[1] : ppy - - // We do not read the next token if we were reading a precinct's - // size argument as we have already read the next token into word. - if (!wasReadingPrecinctSize) - { - word = stk.NextToken(); - } - - wasReadingPrecinctSize = false; - - switch (word[0]) - { - - - case 't': // Tiles specification - tileSpec = parseIdx(word, nTiles); - if (curSpecType == SPEC_COMP_DEF) - { - curSpecType = SPEC_TILE_COMP; - } - else - { - curSpecType = SPEC_TILE_DEF; - } - break; - - - case 'c': // Components specification - compSpec = parseIdx(word, nComp); - if (curSpecType == SPEC_TILE_DEF) - { - curSpecType = SPEC_TILE_COMP; - } - else - { - curSpecType = SPEC_COMP_DEF; - } - break; - - - default: - if (!System.Char.IsDigit(word[0])) - { - errMsg = "Bad construction for parameter: " + word; - throw new System.ArgumentException(errMsg); - } - - // Initialises Vector objects - v[0] = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); // ppx - v[1] = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); // ppy - - while (true) - { - - // Now get the precinct dimensions - try - { - // Get precinct width - w = System.Int32.Parse(word); - - // Get next word in argument list - try - { - word = stk.NextToken(); - } - catch (System.ArgumentOutOfRangeException) - { - errMsg = "'" + optName + "' option : could not " + "parse the precinct's width"; - throw new System.ArgumentException(errMsg); - } - // Get precinct height - h = System.Int32.Parse(word); - if (w != (1 << MathUtil.log2(w)) || h != (1 << MathUtil.log2(h))) - { - errMsg = "Precinct dimensions must be powers of 2"; - throw new System.ArgumentException(errMsg); - } - } - catch (System.FormatException) - { - errMsg = "'" + optName + "' option : the argument '" + word + "' could not be parsed."; - throw new System.ArgumentException(errMsg); - } - // Store packet's dimensions in Vector arrays - v[0].Add(w); - v[1].Add(h); - - // Try to get the next token - if (stk.HasMoreTokens()) - { - word = stk.NextToken(); - if (!System.Char.IsDigit(word[0])) - { - // The next token does not start with a digit so - // it is not a precinct's size argument. We set - // the wasReadingPrecinctSize booleen such that we - // know that we don't have to read another token - // and check for the end of the parameters list. - wasReadingPrecinctSize = true; - - if (curSpecType == SPEC_DEF) - { - setDefault(v); - } - else if (curSpecType == SPEC_TILE_DEF) - { - for (ti = tileSpec.Length - 1; ti >= 0; ti--) - { - if (tileSpec[ti]) - { - setTileDef(ti, v); - } - } - } - else if (curSpecType == SPEC_COMP_DEF) - { - for (ci = compSpec.Length - 1; ci >= 0; ci--) - { - if (compSpec[ci]) - { - setCompDef(ci, v); - } - } - } - else - { - for (ti = tileSpec.Length - 1; ti >= 0; ti--) - { - for (ci = compSpec.Length - 1; ci >= 0; ci--) - { - if (tileSpec[ti] && compSpec[ci]) - { - setTileCompVal(ti, ci, v); - } - } - } - } - // Re-initialize - curSpecType = SPEC_DEF; - tileSpec = null; - compSpec = null; - - // Go back to 'normal' parsing - break; - } - else - { - // Next token starts with a digit so read it - } - } - else - { - // We have reached the end of the parameters list so - // we store the last precinct's sizes and we stop - if (curSpecType == SPEC_DEF) - { - setDefault(v); - } - else if (curSpecType == SPEC_TILE_DEF) - { - for (ti = tileSpec.Length - 1; ti >= 0; ti--) - { - if (tileSpec[ti]) - { - setTileDef(ti, v); - } - } - } - else if (curSpecType == SPEC_COMP_DEF) - { - for (ci = compSpec.Length - 1; ci >= 0; ci--) - { - if (compSpec[ci]) - { - setCompDef(ci, v); - } - } - } - else - { - for (ti = tileSpec.Length - 1; ti >= 0; ti--) - { - for (ci = compSpec.Length - 1; ci >= 0; ci--) - { - if (tileSpec[ti] && compSpec[ci]) - { - setTileCompVal(ti, ci, v); - } - } - } - } - endOfParamList = true; - break; - } - } // while (true) - break; - - } // switch - } // while - } - - /// Returns the precinct partition width in component 'n' and tile 't' at - /// resolution level 'rl'. If the tile index is equal to -1 or if the - /// component index is equal to -1 it means that those should not be taken - /// into account. - /// - /// - /// The tile index, in raster scan order. Specify -1 if it is not - /// a specific tile. - /// - /// - /// The component index. Specify -1 if it is not a specific - /// component. - /// - /// - /// The resolution level - /// - /// - /// The precinct partition width in component 'c' and tile 't' at - /// resolution level 'rl'. - /// - /// - public virtual int getPPX(int t, int c, int rl) - { - int mrl, idx; - System.Collections.ArrayList[] v = null; - bool tileSpecified = (t != -1 ? true : false); - bool compSpecified = (c != -1 ? true : false); - - // Get the maximum number of decomposition levels and the object - // (Vector array) containing the precinct dimensions (width and - // height) for the specified (or not) tile/component - if (tileSpecified && compSpecified) - { - mrl = ((System.Int32)dls.getTileCompVal(t, c)); - v = (System.Collections.ArrayList[])getTileCompVal(t, c); - } - else if (tileSpecified && !compSpecified) - { - mrl = ((System.Int32)dls.getTileDef(t)); - v = (System.Collections.ArrayList[])getTileDef(t); - } - else if (!tileSpecified && compSpecified) - { - mrl = ((System.Int32)dls.getCompDef(c)); - v = (System.Collections.ArrayList[])getCompDef(c); - } - else - { - mrl = ((System.Int32)dls.getDefault()); - v = (System.Collections.ArrayList[])getDefault(); - } - idx = mrl - rl; - if (v[0].Count > idx) - { - return ((System.Int32)v[0][idx]); - } - else - { - return ((System.Int32)v[0][v[0].Count - 1]); - } - } - - /// Returns the precinct partition height in component 'n' and tile 't' at - /// resolution level 'rl'. If the tile index is equal to -1 or if the - /// component index is equal to -1 it means that those should not be taken - /// into account. - /// - /// - /// The tile index, in raster scan order. Specify -1 if it is not - /// a specific tile. - /// - /// - /// The component index. Specify -1 if it is not a specific - /// component. - /// - /// - /// The resolution level. - /// - /// - /// The precinct partition width in component 'n' and tile 't' at - /// resolution level 'rl'. - /// - /// - public virtual int getPPY(int t, int c, int rl) - { - int mrl, idx; - System.Collections.ArrayList[] v = null; - bool tileSpecified = (t != -1 ? true : false); - bool compSpecified = (c != -1 ? true : false); - - // Get the maximum number of decomposition levels and the object - // (Vector array) containing the precinct dimensions (width and - // height) for the specified (or not) tile/component - if (tileSpecified && compSpecified) - { - mrl = ((System.Int32)dls.getTileCompVal(t, c)); - v = (System.Collections.ArrayList[])getTileCompVal(t, c); - } - else if (tileSpecified && !compSpecified) - { - mrl = ((System.Int32)dls.getTileDef(t)); - v = (System.Collections.ArrayList[])getTileDef(t); - } - else if (!tileSpecified && compSpecified) - { - mrl = ((System.Int32)dls.getCompDef(c)); - v = (System.Collections.ArrayList[])getCompDef(c); - } - else - { - mrl = ((System.Int32)dls.getDefault()); - v = (System.Collections.ArrayList[])getDefault(); - } - idx = mrl - rl; - if (v[1].Count > idx) - { - return ((System.Int32)v[1][idx]); - } - else - { - return ((System.Int32)v[1][v[1].Count - 1]); - } - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/entropy/Progression.cs b/CSJ2K/j2k/entropy/Progression.cs deleted file mode 100644 index b3eea5de..00000000 --- a/CSJ2K/j2k/entropy/Progression.cs +++ /dev/null @@ -1,153 +0,0 @@ -/* -* CVS identifier: -* -* $Id : $ -* -* Class: Progression -* -* Description: Holds the type(s) of progression -* -* -* Modified by: -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* -* -* -*/ -using CSJ2K.j2k.codestream; -namespace CSJ2K.j2k.entropy -{ - - /// This class holds one of the different progression orders defined in - /// the bit stream. The type(s) of progression order are defined in the - /// ProgressionType interface. A Progression object is totally defined - /// by its component start and end, resolution level start and end and - /// layer start and end indexes. If no progression order change is - /// defined, there is only Progression instance. - /// - /// - /// - /// - /// - public class Progression - { - - /// Progression type as defined in ProgressionType interface - public int type; - - /// Component index for the start of a progression - public int cs; - - /// Component index for the end of a progression. - public int ce; - - /// Resolution index for the start of a progression - public int rs; - - /// Resolution index for the end of a progression. - public int re; - - /// The index of the last layer. - public int lye; - - /// Constructor. - /// - /// Builds a new Progression object with specified type and bounds - /// of progression. - /// - /// - /// The progression type - /// - /// - /// The component index start - /// - /// - /// The component index end - /// - /// - /// The resolution level index start - /// - /// - /// The resolution level index end - /// - /// - /// The layer index end - /// - /// - public Progression(int type, int cs, int ce, int rs, int re, int lye) - { - this.type = type; - this.cs = cs; - this.ce = ce; - this.rs = rs; - this.re = re; - this.lye = lye; - } - - public override System.String ToString() - { - System.String str = "type= "; - switch (type) - { - - case CSJ2K.j2k.codestream.ProgressionType.LY_RES_COMP_POS_PROG: - str += "layer, "; - break; - - case CSJ2K.j2k.codestream.ProgressionType.RES_LY_COMP_POS_PROG: - str += "res, "; - break; - - case CSJ2K.j2k.codestream.ProgressionType.RES_POS_COMP_LY_PROG: - str += "res-pos, "; - break; - - case CSJ2K.j2k.codestream.ProgressionType.POS_COMP_RES_LY_PROG: - str += "pos-comp, "; - break; - - case CSJ2K.j2k.codestream.ProgressionType.COMP_POS_RES_LY_PROG: - str += "pos-comp, "; - break; - - default: - throw new System.ApplicationException("Unknown progression type"); - - } - str += ("comp.: " + cs + "-" + ce + ", "); - str += ("res.: " + rs + "-" + re + ", "); - str += ("layer: up to " + lye); - return str; - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/entropy/ProgressionSpec.cs b/CSJ2K/j2k/entropy/ProgressionSpec.cs deleted file mode 100644 index bea02f9f..00000000 --- a/CSJ2K/j2k/entropy/ProgressionSpec.cs +++ /dev/null @@ -1,450 +0,0 @@ -/* -* CVS identifier: -* -* $Id: ProgressionSpec.java,v 1.19 2001/05/02 14:08:42 grosbois Exp $ -* -* Class: ProgressionSpec -* -* Description: Specification of the progression(s) type(s) and -* changes of progression. -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.codestream; -using CSJ2K.j2k.util; -namespace CSJ2K.j2k.entropy -{ - - /// This class extends ModuleSpec class for progression type(s) and progression - /// order changes holding purposes. - /// - ///

    It stores the progression type(s) used in the codestream. There can be - /// several progression type(s) if progression order changes are used (POC - /// markers).

    - /// - ///
    - public class ProgressionSpec : ModuleSpec - { - - /// Creates a new ProgressionSpec object for the specified number of tiles - /// and components. - /// - /// - /// The number of tiles - /// - /// - /// The number of components - /// - /// - /// the type of the specification module i.e. tile specific, - /// component specific or both. The ProgressionSpec class should only be - /// used only with the type ModuleSpec.SPEC_TYPE_TILE. - /// - /// - public ProgressionSpec(int nt, int nc, byte type) : base(nt, nc, type) - { - if (type != ModuleSpec.SPEC_TYPE_TILE) - { - throw new System.ApplicationException("Illegal use of class ProgressionSpec !"); - } - } - - /// Creates a new ProgressionSpec object for the specified number of tiles, - /// components and the ParameterList instance. - /// - /// - /// The number of tiles - /// - /// - /// The number of components - /// - /// - /// The number of layer - /// - /// - /// The number of decomposition levels specifications - /// - /// - /// the type of the specification module. The ProgressionSpec - /// class should only be used only with the type ModuleSpec.SPEC_TYPE_TILE. - /// - /// - /// The ParameterList instance - /// - /// - public ProgressionSpec(int nt, int nc, int nl, IntegerSpec dls, byte type, ParameterList pl) : base(nt, nc, type) - { - - System.String param = pl.getParameter("Aptype"); - Progression[] prog; - int mode = -1; - - if (param == null) - { - // No parameter specified - if (pl.getParameter("Rroi") == null) - { - mode = checkProgMode("res"); - } - else - { - mode = checkProgMode("layer"); - } - - if (mode == -1) - { - System.String errMsg = "Unknown progression type : '" + param + "'"; - throw new System.ArgumentException(errMsg); - } - prog = new Progression[1]; - prog[0] = new Progression(mode, 0, nc, 0, dls.Max + 1, nl); - setDefault(prog); - return; - } - - SupportClass.Tokenizer stk = new SupportClass.Tokenizer(param); - byte curSpecType = SPEC_DEF; // Specification type of the - // current parameter - bool[] tileSpec = null; // Tiles concerned by the specification - System.String word = null; // current word - System.String errMsg2 = null; // Error message - bool needInteger = false; // True if an integer value is expected - int intType = 0; // Type of read integer value (0=index of first - // resolution level, 1= index of first component, 2=index of first - // layer not included, 3= index of first resolution level not - // included, 4= index of first component not included - System.Collections.ArrayList progression = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); - int tmp = 0; - Progression curProg = null; - - while (stk.HasMoreTokens()) - { - word = stk.NextToken(); - - switch (word[0]) - { - - case 't': - // If progression were previously found, store them - if (progression.Count > 0) - { - // Ensure that all information has been taken - curProg.ce = nc; - curProg.lye = nl; - curProg.re = dls.Max + 1; - prog = new Progression[progression.Count]; - progression.CopyTo(prog); - if (curSpecType == SPEC_DEF) - { - setDefault(prog); - } - else if (curSpecType == SPEC_TILE_DEF) - { - for (int i = tileSpec.Length - 1; i >= 0; i--) - if (tileSpec[i]) - { - setTileDef(i, prog); - } - } - } - progression.Clear(); - intType = -1; - needInteger = false; - - // Tiles specification - tileSpec = parseIdx(word, nTiles); - curSpecType = SPEC_TILE_DEF; - break; - - default: - // Here, words is either a Integer (progression bound index) - // or a String (progression order type). This is determined by - // the value of needInteger. - if (needInteger) - { - // Progression bound info - try - { - tmp = (System.Int32.Parse(word)); - } - catch (System.FormatException) - { - // Progression has missing parameters - throw new System.ArgumentException("Progression " + "order" + " specification " + "has missing " + "parameters: " + param); - } - - switch (intType) - { - - case 0: // cs - if (tmp < 0 || tmp > (dls.Max + 1)) - throw new System.ArgumentException("Invalid res_start " + "in '-Aptype'" + " option: " + tmp); - curProg.rs = tmp; break; - - case 1: // rs - if (tmp < 0 || tmp > nc) - { - throw new System.ArgumentException("Invalid comp_start " + "in '-Aptype' " + "option: " + tmp); - } - curProg.cs = tmp; break; - - case 2: // lye - if (tmp < 0) - throw new System.ArgumentException("Invalid layer_end " + "in '-Aptype'" + " option: " + tmp); - if (tmp > nl) - { - tmp = nl; - } - curProg.lye = tmp; break; - - case 3: // ce - if (tmp < 0) - throw new System.ArgumentException("Invalid res_end " + "in '-Aptype'" + " option: " + tmp); - if (tmp > (dls.Max + 1)) - { - tmp = dls.Max + 1; - } - curProg.re = tmp; break; - - case 4: // re - if (tmp < 0) - throw new System.ArgumentException("Invalid comp_end " + "in '-Aptype'" + " option: " + tmp); - if (tmp > nc) - { - tmp = nc; - } - curProg.ce = tmp; break; - } - - if (intType < 4) - { - intType++; - needInteger = true; - break; - } - else if (intType == 4) - { - intType = 0; - needInteger = false; - break; - } - else - { - throw new System.ApplicationException("Error in usage of 'Aptype' " + "option: " + param); - } - } - - if (!needInteger) - { - // Progression type info - mode = checkProgMode(word); - if (mode == -1) - { - errMsg2 = "Unknown progression type : '" + word + "'"; - throw new System.ArgumentException(errMsg2); - } - needInteger = true; - intType = 0; - if (progression.Count == 0) - { - curProg = new Progression(mode, 0, nc, 0, dls.Max + 1, nl); - } - else - { - curProg = new Progression(mode, 0, nc, 0, dls.Max + 1, nl); - } - progression.Add(curProg); - } - break; - - } // switch - } // while - - if (progression.Count == 0) - { - // No progression defined - if (pl.getParameter("Rroi") == null) - { - mode = checkProgMode("res"); - } - else - { - mode = checkProgMode("layer"); - } - if (mode == -1) - { - errMsg2 = "Unknown progression type : '" + param + "'"; - throw new System.ArgumentException(errMsg2); - } - prog = new Progression[1]; - prog[0] = new Progression(mode, 0, nc, 0, dls.Max + 1, nl); - setDefault(prog); - return; - } - - // Ensure that all information has been taken - curProg.ce = nc; - curProg.lye = nl; - curProg.re = dls.Max + 1; - - // Store found progression - prog = new Progression[progression.Count]; - progression.CopyTo(prog); - - if (curSpecType == SPEC_DEF) - { - setDefault(prog); - } - else if (curSpecType == SPEC_TILE_DEF) - { - for (int i = tileSpec.Length - 1; i >= 0; i--) - if (tileSpec[i]) - { - setTileDef(i, prog); - } - } - - // Check that default value has been specified - if (getDefault() == null) - { - int ndefspec = 0; - for (int t = nt - 1; t >= 0; t--) - { - for (int c = nc - 1; c >= 0; c--) - { - if (specValType[t][c] == SPEC_DEF) - { - ndefspec++; - } - } - } - - // If some tile-component have received no specification, they - // receive the default progressiveness. - if (ndefspec != 0) - { - if (pl.getParameter("Rroi") == null) - { - mode = checkProgMode("res"); - } - else - { - mode = checkProgMode("layer"); - } - if (mode == -1) - { - errMsg2 = "Unknown progression type : '" + param + "'"; - throw new System.ArgumentException(errMsg2); - } - prog = new Progression[1]; - prog[0] = new Progression(mode, 0, nc, 0, dls.Max + 1, nl); - setDefault(prog); - } - else - { - // All tile-component have been specified, takes the first - // tile-component value as default. - setDefault(getTileCompVal(0, 0)); - switch (specValType[0][0]) - { - - case SPEC_TILE_DEF: - for (int c = nc - 1; c >= 0; c--) - { - if (specValType[0][c] == SPEC_TILE_DEF) - specValType[0][c] = SPEC_DEF; - } - tileDef[0] = null; - break; - - case SPEC_COMP_DEF: - for (int t = nt - 1; t >= 0; t--) - { - if (specValType[t][0] == SPEC_COMP_DEF) - specValType[t][0] = SPEC_DEF; - } - compDef[0] = null; - break; - - case SPEC_TILE_COMP: - specValType[0][0] = SPEC_DEF; - tileCompVal["t0c0"] = null; - break; - } - } - } - } - - /// Check if the progression mode exists and if so, return its integer - /// value. It returns -1 otherwise. - /// - /// - /// The progression mode stored in a string - /// - /// - /// The integer value of the progression mode or -1 if the - /// progression mode does not exist. - /// - /// - /// - /// - /// - private int checkProgMode(System.String mode) - { - if (mode.Equals("res")) - { - return CSJ2K.j2k.codestream.ProgressionType.RES_LY_COMP_POS_PROG; - } - else if (mode.Equals("layer")) - { - return CSJ2K.j2k.codestream.ProgressionType.LY_RES_COMP_POS_PROG; - } - else if (mode.Equals("pos-comp")) - { - return CSJ2K.j2k.codestream.ProgressionType.POS_COMP_RES_LY_PROG; - } - else if (mode.Equals("comp-pos")) - { - return CSJ2K.j2k.codestream.ProgressionType.COMP_POS_RES_LY_PROG; - } - else if (mode.Equals("res-pos")) - { - return CSJ2K.j2k.codestream.ProgressionType.RES_POS_COMP_LY_PROG; - } - else - { - // No corresponding progression mode, we return -1. - return -1; - } - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/entropy/StdEntropyCoderOptions.cs b/CSJ2K/j2k/entropy/StdEntropyCoderOptions.cs deleted file mode 100644 index 8543a33c..00000000 --- a/CSJ2K/j2k/entropy/StdEntropyCoderOptions.cs +++ /dev/null @@ -1,122 +0,0 @@ -/* -* CVS identifier: -* -* $Id: StdEntropyCoderOptions.java,v 1.10 2001/03/27 09:57:20 grosbois Exp $ -* -* Class: StdEntropyCoderOptions -* -* Description: Entropy coding engine of stripes in -* code-blocks options -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -namespace CSJ2K.j2k.entropy -{ - - /// This interface define the constants that identify the possible options for - /// the entropy coder, as well some fixed parameters of the JPEG 2000 entropy - /// coder. - /// - /// - public struct StdEntropyCoderOptions - { - /// The flag bit to indicate that selective arithmetic coding bypass - /// should be used. In this mode, the significance propagation and - /// magnitude refinement passes bypass the arithmetic encoder in the fourth - /// bit-plane and latter ones (but not the cleanup pass). Note that the - /// transition between raw and AC segments needs terminations (whether or - /// not OPT_TERM_PASS is used). - /// - public readonly static int OPT_BYPASS = 1; - /// The flag bit to indicate that the MQ states for all contexts should be - /// reset at the end of each (non-bypassed) coding pass. - /// - public readonly static int OPT_RESET_MQ = 1 << 1; - /// The flag bit to indicate that a termination should be performed after - /// each coding pass. Note that terminations are applied to both * * - /// arithmetically coded and bypassed (i.e. raw) passes . - /// - public readonly static int OPT_TERM_PASS = 1 << 2; - /// The flag bit to indicate the vertically stripe-causal context - /// formation should be used. - /// - public readonly static int OPT_VERT_STR_CAUSAL = 1 << 3; - /// The flag bit to indicate that error resilience info is embedded on MQ - /// termination. This corresponds to the predictable termination described - /// in Annex D.4.2 of the FDIS - /// - public readonly static int OPT_PRED_TERM = 1 << 4; - /// The flag bit to indicate that an error resilience segmentation symbol - /// is to be inserted at the end of each cleanup coding pass. The - /// segmentation symbol is the four symbol sequence 1010 that are sent - /// through the MQ coder using the UNIFORM context (as explained in annex - /// D.5 of FDIS). - /// - public readonly static int OPT_SEG_SYMBOLS = 1 << 5; - /// The minimum code-block dimension. The nominal width or height of a - /// code-block must never be less than this. It is 4. - /// - public readonly static int MIN_CB_DIM = 4; - /// The maximum code-block dimension. No code-block should be larger, - /// either in width or height, than this value. It is 1024. - /// - public readonly static int MAX_CB_DIM = 1024; - /// The maximum code-block area (width x height). The surface covered by - /// a nominal size block should never be larger than this. It is 4096 - /// - public readonly static int MAX_CB_AREA = 4096; - /// The stripe height. This is the nominal value of the stripe height. It - /// is 4. - /// - public readonly static int STRIPE_HEIGHT = 4; - /// The number of coding passes per bit-plane. This is the number of - /// passes per bit-plane. It is 3. - /// - public readonly static int NUM_PASSES = 3; - /// The number of most significant bit-planes where bypass mode is not to - /// be used, even if bypass mode is on: 4. - /// - public readonly static int NUM_NON_BYPASS_MS_BP = 4; - /// The number of empty passes in the most significant bit-plane. It is - /// 2. - /// - public readonly static int NUM_EMPTY_PASSES_IN_MS_BP = 2; - /// The index of the first "raw" pass, if bypass mode is on. - public readonly static int FIRST_BYPASS_PASS_IDX; - static StdEntropyCoderOptions() - { - FIRST_BYPASS_PASS_IDX = CSJ2K.j2k.entropy.StdEntropyCoderOptions.NUM_PASSES * CSJ2K.j2k.entropy.StdEntropyCoderOptions.NUM_NON_BYPASS_MS_BP - CSJ2K.j2k.entropy.StdEntropyCoderOptions.NUM_EMPTY_PASSES_IN_MS_BP; - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/entropy/decoder/ByteInputBuffer.cs b/CSJ2K/j2k/entropy/decoder/ByteInputBuffer.cs deleted file mode 100644 index 71fa1d2a..00000000 --- a/CSJ2K/j2k/entropy/decoder/ByteInputBuffer.cs +++ /dev/null @@ -1,276 +0,0 @@ -/* -* CVS identifier: -* -* $Id: ByteInputBuffer.java,v 1.13 2001/10/17 17:01:57 grosbois Exp $ -* -* Class: ByteInputBuffer -* -* Description: Provides buffering for byte based input, similar -* to the standard class ByteArrayInputStream -* -* the old jj2000.j2k.io.ByteArrayInput class by -* Diego SANTA CRUZ, Apr-26-1999 -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using System; -namespace CSJ2K.j2k.entropy.decoder -{ - - /// This class provides a byte input facility from byte buffers. It is similar - /// to the ByteArrayInputStream class, but adds the possibility to add data to - /// the stream after the creation of the object. - /// - ///

    Unlike the ByteArrayInputStream this class is not thread safe (i.e. no - /// two threads can use the same object at the same time, but different objects - /// may be used in different threads).

    - /// - ///

    This class can modify the contents of the buffer given to the - /// constructor, when the addByteArray() method is called.

    - /// - ///
    - /// - /// - /// - public class ByteInputBuffer - { - - /// The byte array containing the data - private byte[] buf; - - /// The index one greater than the last valid character in the input - /// stream buffer - /// - private int count; - - /// The index of the next character to read from the input stream buffer - /// - /// - private int pos; - - /// Creates a new byte array input stream that reads data from the - /// specified byte array. The byte array is not copied. - /// - /// - /// the input buffer. - /// - /// - public ByteInputBuffer(byte[] buf) - { - this.buf = buf; - count = buf.Length; - } - - /// Creates a new byte array input stream that reads data from the - /// specified byte array. Up to length characters are to be read from the - /// byte array, starting at the indicated offset. - /// - ///

    The byte array is not copied.

    - /// - ///
    - /// the input buffer. - /// - /// - /// the offset in the buffer of the first byte to read. - /// - /// - /// the maximum number of bytes to read from the buffer. - /// - /// - public ByteInputBuffer(byte[] buf, int offset, int length) - { - this.buf = buf; - pos = offset; - count = offset + length; - } - - /// Sets the underlying buffer byte array to the given one, with the given - /// offset and length. If 'buf' is null then the current byte buffer is - /// assumed. If 'offset' is negative, then it will be assumed to be - /// 'off+len', where 'off' and 'len' are the offset and length of the - /// current byte buffer. - /// - ///

    The byte array is not copied.

    - /// - ///
    - /// the input buffer. If null it is the current input buffer. - /// - /// - /// the offset in the buffer of the first byte to read. If - /// negative it is assumed to be the byte just after the end of the current - /// input buffer, only permitted if 'buf' is null. - /// - /// - /// the maximum number of bytes to read frmo the buffer. - /// - /// - public virtual void setByteArray(byte[] buf, int offset, int length) - { - // In same buffer? - if (buf == null) - { - if (length < 0 || count + length > this.buf.Length) - { - throw new System.ArgumentException(); - } - if (offset < 0) - { - pos = count; - count += length; - } - else - { - count = offset + length; - pos = offset; - } - } - else - { - // New input buffer - if (offset < 0 || length < 0 || offset + length > buf.Length) - { - throw new System.ArgumentException(); - } - this.buf = buf; - count = offset + length; - pos = offset; - } - } - - /// Adds the specified data to the end of the byte array stream. This - /// method modifies the byte array buffer. It can also discard the already - /// read input. - /// - /// - /// The data to add. The data is copied. - /// - /// - /// The index, in data, of the first element to add to the - /// stream. - /// - /// - /// The number of elements to add to the array. - /// - /// - //UPGRADE_NOTE: Synchronized keyword was removed from method 'addByteArray'. Lock expression was added. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1027'" - public virtual void addByteArray(byte[] data, int off, int len) - { - lock (this) - { - // Check integrity - if (len < 0 || off < 0 || len + off > buf.Length) - { - throw new System.ArgumentException(); - } - // Copy new data - if (count + len <= buf.Length) - { - // Enough place in 'buf' - Array.Copy(data, off, buf, count, len); - count += len; - } - else - { - if (count - pos + len <= buf.Length) - { - // Enough place in 'buf' if we move input data - // Move buffer - Array.Copy(buf, pos, buf, 0, count - pos); - } - else - { - // Not enough place in 'buf', use new buffer - byte[] oldbuf = buf; - buf = new byte[count - pos + len]; - // Copy buffer - Array.Copy(oldbuf, count, buf, 0, count - pos); - } - count -= pos; - pos = 0; - // Copy new data - Array.Copy(data, off, buf, count, len); - count += len; - } - } - } - - /// Reads the next byte of data from this input stream. The value byte is - /// returned as an int in the range 0 to 255. If no byte is available - /// because the end of the stream has been reached, the EOFException - /// exception is thrown. - /// - ///

    This method is not synchronized, so it is not thread safe.

    - /// - ///
    - /// The byte read in the range 0-255. - /// - /// - /// If the end of the stream is reached. - /// - /// - public virtual int readChecked() - { - if (pos < count) - { - return (int)buf[pos++] & 0xFF; - } - else - { - throw new System.IO.EndOfStreamException(); - } - } - - /// Reads the next byte of data from this input stream. The value byte is - /// returned as an int in the range 0 to 255. If no byte is available - /// because the end of the stream has been reached, -1 is returned. - /// - ///

    This method is not synchronized, so it is not thread safe.

    - /// - ///
    - /// The byte read in the range 0-255, or -1 if the end of stream - /// has been reached. - /// - /// - public virtual int read() - { - if (pos < count) - { - return (int)buf[pos++] & 0xFF; - } - else - { - return -1; - } - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/entropy/decoder/ByteToBitInput.cs b/CSJ2K/j2k/entropy/decoder/ByteToBitInput.cs deleted file mode 100644 index c69e707a..00000000 --- a/CSJ2K/j2k/entropy/decoder/ByteToBitInput.cs +++ /dev/null @@ -1,195 +0,0 @@ -/* -* CVS identifier: -* -* $Id: ByteToBitInput.java,v 1.14 2002/07/19 12:41:33 grosbois Exp $ -* -* Class: ByteToBitInput -* -* Description: Adapter to perform bit based input from a byte -* based one. -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -namespace CSJ2K.j2k.entropy.decoder -{ - - /// This class provides an adapter to perform bit based input on byte based - /// output obejcts that inherit from a 'ByteInputBuffer' class. This class also - /// performs the bit unstuffing procedure specified for the 'selective - /// arithmetic coding bypass' mode of the JPEG 2000 entropy coder. - /// - /// - public class ByteToBitInput - { - - /// The byte based input - internal ByteInputBuffer in_Renamed; - - /// The bit buffer - internal int bbuf; - - /// The position of the next bit to get from the byte buffer. When it is - /// -1 the bit buffer is empty. - /// - internal int bpos = -1; - - /// Instantiates a new 'ByteToBitInput' object that uses 'in' as the - /// underlying byte based input. - /// - /// - /// The underlying byte based input. - /// - /// - public ByteToBitInput(ByteInputBuffer in_Renamed) - { - this.in_Renamed = in_Renamed; - } - - /// Reads from the bit stream one bit. If 'bpos' is -1 then a byte is read - /// and loaded into the bit buffer, from where the bit is read. If - /// necessary the bit unstuffing will be applied. - /// - /// - /// The read bit (0 or 1). - /// - /// - public int readBit() - { - if (bpos < 0) - { - if ((bbuf & 0xFF) != 0xFF) - { - // Normal byte to read - bbuf = in_Renamed.read(); - bpos = 7; - } - else - { - // Previous byte is 0xFF => there was bit stuffing - bbuf = in_Renamed.read(); - bpos = 6; - } - } - return (bbuf >> bpos--) & 0x01; - } - - /// Checks for past errors in the decoding process by verifying the byte - /// padding with an alternating sequence of 0's and 1's. If an error is - /// detected it means that the raw bit stream has been wrongly decoded or - /// that the raw terminated segment length is too long. If no errors are - /// detected it does not necessarily mean that the raw bit stream has been - /// correctly decoded. - /// - /// - /// True if errors are found, false otherwise. - /// - /// - public virtual bool checkBytePadding() - { - int seq; // Byte padding sequence in last byte - - // If there are no spare bits and bbuf is 0xFF (not EOF), then there - // is a next byte with bit stuffing that we must load. - if (bpos < 0 && (bbuf & 0xFF) == 0xFF) - { - bbuf = in_Renamed.read(); - bpos = 6; - } - - // 1) Not yet read bits in the last byte must be an alternating - // sequence of 0s and 1s, starting with 0. - if (bpos >= 0) - { - seq = bbuf & ((1 << (bpos + 1)) - 1); - if (seq != (0x55 >> (7 - bpos))) - return true; - } - - // 2) We must have already reached the last byte in the terminated - // segment, unless last bit read is LSB of FF in which case an encoder - // can output an extra byte which is smaller than 0x80. - if (bbuf != -1) - { - if (bbuf == 0xFF && bpos == 0) - { - if ((in_Renamed.read() & 0xFF) >= 0x80) - return true; - } - else - { - if (in_Renamed.read() != -1) - return true; - } - } - - // Nothing detected - return false; - } - - /// Flushes (i.e. empties) the bit buffer, without loading any new - /// bytes. This realigns the input at the next byte boundary, if not - /// already at one. - /// - /// - internal void flush() - { - bbuf = 0; // reset any bit stuffing state - bpos = -1; - } - - /// Resets the underlying byte input to start a new segment. The bit buffer - /// is flushed. - /// - /// - /// The byte array containing the byte data. If null the - /// current byte array is assumed. - /// - /// - /// The index of the first element in 'buf' to be decoded. If - /// negative the byte just after the previous segment is assumed, only - /// valid if 'buf' is null. - /// - /// - /// The number of bytes in 'buf' to be decoded. Any subsequent - /// bytes are taken to be 0xFF. - /// - /// - internal void setByteArray(byte[] buf, int off, int len) - { - in_Renamed.setByteArray(buf, off, len); - bbuf = 0; // reset any bit stuffing state - bpos = -1; - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/entropy/decoder/CodedCBlkDataSrcDec.cs b/CSJ2K/j2k/entropy/decoder/CodedCBlkDataSrcDec.cs deleted file mode 100644 index cda5117b..00000000 --- a/CSJ2K/j2k/entropy/decoder/CodedCBlkDataSrcDec.cs +++ /dev/null @@ -1,132 +0,0 @@ -/* -* CVS identifier: -* -* $Id: CodedCBlkDataSrcDec.java,v 1.17 2001/09/14 09:26:23 grosbois Exp $ -* -* Class: CodedCBlkDataSrcDec -* -* Description: Interface that defines a source of entropy coded -* data that is transferred in a code-block by -* code-block basis (decoder side). -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.wavelet.synthesis; -namespace CSJ2K.j2k.entropy.decoder -{ - - /// This interface defines a source of entropy coded data and methods to - /// transfer it in a code-block by code-block basis. In each call to - /// 'geCodeBlock()' a specified coded code-block is returned. - /// - ///

    This interface is the source of data for the entropy decoder. See the - /// 'EntropyDecoder' class.

    - /// - ///

    For each coded-code-block the entropy-coded data is returned along with - /// its truncation point information in a 'DecLyrdCBlk' object.

    - /// - ///
    - /// - /// - /// - /// - /// - /// - /// - /// - /// - public interface CodedCBlkDataSrcDec : InvWTData - { - - /// Returns the specified coded code-block, for the specified component, in - /// the current tile. The first layer to return is indicated by 'fl'. The - /// number of layers that is returned depends on 'nl' and the amount of - /// data available. - /// - ///

    The argument 'fl' is to be used by subsequent calls to this method - /// for the same code-block. In this way supplamental data can be retrieved - /// at a later time. The fact that data from more than one layer can be - /// returned means that several packets from the same code-block, of the - /// same component, and the same tile, have been concatenated.

    - /// - ///

    The returned compressed code-block can have its progressive - /// attribute set. If this attribute is set it means that more data can be - /// obtained by subsequent calls to this method (subject to transmission - /// delays, etc). If the progressive attribute is not set it means that the - /// returned data is all the data that can be obtained for the specified - /// subblock.

    - /// - ///

    The compressed code-block is uniquely specified by the current tile, - /// the component (identified by 'c'), the subband (indentified by 'sb') - /// and the code-bock vertical and horizontal indexes 'm' and 'n'.

    - /// - ///

    The 'ulx' and 'uly' members of the returned 'DecLyrdCBlk' object - /// contain the coordinates of the top-left corner of the block, with - /// respect to the tile, not the subband.

    - /// - ///
    - /// The index of the component, from 0 to N-1. - /// - /// - /// The vertical index of the code-block to return, in the - /// specified subband. - /// - /// - /// The horizontal index of the code-block to return, in the - /// specified subband. - /// - /// - /// The subband in whic the requested code-block is. - /// - /// - /// The first layer to return. - /// - /// - /// The number of layers to return, if negative all available - /// layers are returned, starting at 'fl'. - /// - /// - /// If not null this object is used to return the compressed - /// code-block. If null a new object is created and returned. If the data - /// array in ccb is not null then it can be reused to return the compressed - /// data. - /// - /// - /// The compressed code-block, with a certain number of layers - /// determined by the available data and 'nl'. - /// - /// - DecLyrdCBlk getCodeBlock(int c, int m, int n, SubbandSyn sb, int fl, int nl, DecLyrdCBlk ccb); - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/entropy/decoder/DecLyrdCBlk.cs b/CSJ2K/j2k/entropy/decoder/DecLyrdCBlk.cs deleted file mode 100644 index 118c7d7f..00000000 --- a/CSJ2K/j2k/entropy/decoder/DecLyrdCBlk.cs +++ /dev/null @@ -1,126 +0,0 @@ -/* -* CVS identifier: -* -* $Id: DecLyrdCBlk.java,v 1.9 2001/09/14 09:25:01 grosbois Exp $ -* -* Class: DecLyrdCBlk -* -* Description: The coded (compressed) code-block -* with layered organization for the decoder. -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -namespace CSJ2K.j2k.entropy.decoder -{ - - /// This class stores coded (compressed) code-blocks that are organized in - /// layers. This object can contain either all code-block data (i.e. all - /// layers), or a subset of all the layers that make up the whole compressed - /// code-block. It is applicable to the decoder engine only. Some data of the - /// coded-block is stored in the super class, see CodedCBlk. - /// - ///

    A code-block may have its progressive attribute set (i.e. the 'prog' - /// flag is true). If a code-block is progressive then it means that more data - /// for it may be obtained for an improved quality. If the progressive flag is - /// false then no more data is available from the source for this - /// code-block.

    - /// - ///
    - /// - /// - /// - public class DecLyrdCBlk : CodedCBlk - { - - /// The horizontal coordinate of the upper-left corner of the code-block - public int ulx; - - /// The vertical coordinate of the upper left corner of the code-block - public int uly; - - /// The width of the code-block - public int w; - - /// The height of the code-block - public int h; - - /// The coded (compressed) data length. The data is stored in the 'data' - /// array (see super class). - /// - public int dl; - - /// The progressive flag, false by default (see above). - public bool prog; - - /// The number of layers in the coded data. - public int nl; - - /// The index of the first truncation point returned - public int ftpIdx; - - /// The total number of truncation points from layer 1 to the last one in - /// this object. The number of truncation points in 'data' is - /// 'nTrunc-ftpIdx'. - /// - public int nTrunc; - - /// The length of each terminated segment. If null then there is only one - /// terminated segment, and its length is 'dl'. The number of terminated - /// segments is to be deduced from 'ftpIdx', 'nTrunc' and the coding - /// options. This array contains all terminated segments from the 'ftpIdx' - /// truncation point, upto, and including, the 'nTrunc-1' truncation - /// point. Any data after 'nTrunc-1' is not included in any length. - /// - public int[] tsLengths; - - /// Object information in a string - /// - /// - /// Information in a string - /// - /// - public override System.String ToString() - { - System.String str = "Coded code-block (" + m + "," + n + "): " + skipMSBP + " MSB skipped, " + dl + " bytes, " + nTrunc + " truncation points, " + nl + " layers, " + "progressive=" + prog + ", ulx=" + ulx + ", uly=" + uly + ", w=" + w + ", h=" + h + ", ftpIdx=" + ftpIdx; - if (tsLengths != null) - { - str += " {"; - for (int i = 0; i < tsLengths.Length; i++) - str += (" " + tsLengths[i]); - str += " }"; - } - return str; - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/entropy/decoder/EntropyDecoder.cs b/CSJ2K/j2k/entropy/decoder/EntropyDecoder.cs deleted file mode 100644 index f776176e..00000000 --- a/CSJ2K/j2k/entropy/decoder/EntropyDecoder.cs +++ /dev/null @@ -1,167 +0,0 @@ -/* -* CVS identifier: -* -* $Id: EntropyDecoder.java,v 1.38 2001/09/20 12:48:01 grosbois Exp $ -* -* Class: EntropyDecoder -* -* Description: The abstract class for all entropy decoders. -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.quantization.dequantizer; -using CSJ2K.j2k.wavelet.synthesis; -namespace CSJ2K.j2k.entropy.decoder -{ - - /// This is the abstract class from which all entropy decoders must - /// inherit. This class implements the 'MultiResImgData', therefore it has the - /// concept of a current tile and all operations are performed on the current - /// tile. - /// - ///

    Default implementations of the methods in 'MultiResImgData' are provided - /// through the 'MultiResImgDataAdapter' abstract class.

    - /// - ///

    Sign magnitude representation is used (instead of two's complement) for - /// the output data. The most significant bit is used for the sign (0 if - /// positive, 1 if negative). Then the magnitude of the quantized coefficient - /// is stored in the next most significat bits. The most significant magnitude - /// bit corresponds to the most significant bit-plane and so on.

    - /// - /// - /// - /// - /// - public abstract class EntropyDecoder : MultiResImgDataAdapter, CBlkQuantDataSrcDec - { - /// Returns the horizontal code-block partition origin. Allowable values - /// are 0 and 1, nothing else. - /// - /// - virtual public int CbULX - { - get - { - return src.CbULX; - } - - } - /// Returns the vertical code-block partition origin. Allowable values are - /// 0 and 1, nothing else. - /// - /// - virtual public int CbULY - { - get - { - return src.CbULY; - } - - } - /// Returns the parameters that are used in this class and - /// implementing classes. It returns a 2D String array. Each of the - /// 1D arrays is for a different option, and they have 3 - /// elements. The first element is the option name, the second one - /// is the synopsis and the third one is a long description of what - /// the parameter is. The synopsis or description may be 'null', in - /// which case it is assumed that there is no synopsis or - /// description of the option, respectively. Null may be returned - /// if no options are supported. - /// - /// - /// the options name, their synopsis and their explanation, - /// or null if no options are supported. - /// - /// - public static System.String[][] ParameterInfo - { - get - { - return pinfo; - } - - } - - /// The prefix for entropy decoder optiojns: 'C' - public const char OPT_PREFIX = 'C'; - - /// The list of parameters that is accepted by the entropy - /// decoders. They start with 'C'. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'pinfo'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly System.String[][] pinfo = new System.String[][] { new System.String[] { "Cverber", "[on|off]", "Specifies if the entropy decoder should be verbose about detected " + "errors. If 'on' a message is printed whenever an error is detected.", "on" }, new System.String[] { "Cer", "[on|off]", "Specifies if error detection should be performed by the entropy " + "decoder engine. If errors are detected they will be concealed and " + "the resulting distortion will be less important. Note that errors " + "can only be detected if the encoder that generated the data " + "included error resilience information.", "on" } }; - - /// The bit stream transport from where to get the compressed data - /// (the source) - /// - protected internal CodedCBlkDataSrcDec src; - - /// Initializes the source of compressed data. - /// - /// - /// From where to obtain the compressed data. - /// - /// - public EntropyDecoder(CodedCBlkDataSrcDec src) : base(src) - { - this.src = src; - } - - /// Returns the subband tree, for the specified tile-component. This method - /// returns the root element of the subband tree structure, see Subband and - /// SubbandSyn. The tree comprises all the available resolution levels. - /// - ///

    The number of magnitude bits ('magBits' member variable) for - /// each subband is not initialized. - /// - ///

    - /// The index of the tile, from 0 to T-1. - /// - /// - /// The index of the component, from 0 to C-1. - /// - /// - /// The root of the tree structure. - /// - /// - public override SubbandSyn getSynSubbandTree(int t, int c) - { - return src.getSynSubbandTree(t, c); - } - public abstract CSJ2K.j2k.image.DataBlk getCodeBlock(int param1, int param2, int param3, CSJ2K.j2k.wavelet.synthesis.SubbandSyn param4, CSJ2K.j2k.image.DataBlk param5); - public abstract CSJ2K.j2k.image.DataBlk getInternCodeBlock(int param1, int param2, int param3, CSJ2K.j2k.wavelet.synthesis.SubbandSyn param4, CSJ2K.j2k.image.DataBlk param5); - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/entropy/decoder/MQDecoder.cs b/CSJ2K/j2k/entropy/decoder/MQDecoder.cs deleted file mode 100644 index eeb1d38c..00000000 --- a/CSJ2K/j2k/entropy/decoder/MQDecoder.cs +++ /dev/null @@ -1,811 +0,0 @@ -/* -* CVS identifier: -* -* $Id: MQDecoder.java,v 1.32 2001/10/17 16:58:00 grosbois Exp $ -* -* Class: MQDecoder -* -* Description: Class that encodes a number of bits using the -* MQ arithmetic decoder -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.util; -using System; -namespace CSJ2K.j2k.entropy.decoder -{ - - /// This class implements the MQ arithmetic decoder. It is implemented using - /// the software conventions decoder for better performance (i.e. execution - /// time performance). The initial states for each context of the MQ-coder are - /// specified in the constructor. - /// - /// - - // A trick to test for increased speed: merge the Qe and mPS into 1 thing by - // using the sign bit of Qe to signal mPS (positive-or-0 is 0, negative is 1), - // and doubling the Qe, nMPS and nLPS tables. This gets rid of the swicthLM - // table since it can be integrated as special cases in the doubled nMPS and - // nLPS tables. See the JPEG book, chapter 13. The decoded decision can be - // calculated as (q>>>31). - - public class MQDecoder - { - /// Returns the number of contexts in the arithmetic coder. - /// - /// - /// The number of contexts - /// - /// - virtual public int NumCtxts - { - get - { - return I.Length; - } - - } - /// Returns the underlying 'ByteInputBuffer' from where the MQ coded input - /// bytes are read. - /// - /// - /// The underlying ByteInputBuffer. - /// - /// - virtual public ByteInputBuffer ByteInputBuffer - { - get - { - return in_Renamed; - } - - } - - /// The data structures containing the probabilities for the LPS - //UPGRADE_NOTE: Final was removed from the declaration of 'qe'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - internal static readonly uint[] qe = new uint[] { 0x5601, 0x3401, 0x1801, 0x0ac1, 0x0521, 0x0221, 0x5601, 0x5401, 0x4801, 0x3801, 0x3001, 0x2401, 0x1c01, 0x1601, 0x5601, 0x5401, 0x5101, 0x4801, 0x3801, 0x3401, 0x3001, 0x2801, 0x2401, 0x2201, 0x1c01, 0x1801, 0x1601, 0x1401, 0x1201, 0x1101, 0x0ac1, 0x09c1, 0x08a1, 0x0521, 0x0441, 0x02a1, 0x0221, 0x0141, 0x0111, 0x0085, 0x0049, 0x0025, 0x0015, 0x0009, 0x0005, 0x0001, 0x5601 }; - - /// The indexes of the next MPS - //UPGRADE_NOTE: Final was removed from the declaration of 'nMPS'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - internal static readonly int[] nMPS = new int[] { 1, 2, 3, 4, 5, 38, 7, 8, 9, 10, 11, 12, 13, 29, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 45, 46 }; - - /// The indexes of the next LPS - //UPGRADE_NOTE: Final was removed from the declaration of 'nLPS'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - internal static readonly int[] nLPS = new int[] { 1, 6, 9, 12, 29, 33, 6, 14, 14, 14, 17, 18, 20, 21, 14, 14, 15, 16, 17, 18, 19, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 46 }; - - /// Whether LPS and MPS should be switched - //UPGRADE_NOTE: Final was removed from the declaration of 'switchLM'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - internal static readonly int[] switchLM = new int[] { 1, 0, 0, 0, 0, 0, 1, 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 }; - - /// The ByteInputBuffer used to read the compressed bit stream. - internal ByteInputBuffer in_Renamed; - - /// The current most probable signal for each context - internal int[] mPS; - - /// The current index of each context - internal int[] I; - - /// The current bit code - internal uint c; - - /// The bit code counter - internal uint cT; - - /// The current interval - internal uint a; - - /// The last byte read - internal uint b; - - /// Flag indicating if a marker has been found - internal bool markerFound; - - /// The initial state of each context - //UPGRADE_NOTE: Final was removed from the declaration of 'initStates '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - internal int[] initStates; - - /// Instantiates a new MQ-decoder, with the specified number of contexts - /// and initial states. The compressed bytestream is read from the - /// 'iStream' object. - /// - /// - /// the stream that contains the coded bits - /// - /// - /// The number of contexts used - /// - /// - /// The initial state for each context. A reference is - /// kept to this array to reinitialize the contexts whenever 'reset()' or - /// 'resetCtxts()' is called. - /// - /// - public MQDecoder(ByteInputBuffer iStream, int nrOfContexts, int[] initStates) - { - in_Renamed = iStream; - - // Default initialization of the statistics bins is MPS=0 and - // I=0 - I = new int[nrOfContexts]; - mPS = new int[nrOfContexts]; - // Save the initial states - this.initStates = initStates; - - // Initialize - init(); - - // Set the contexts - resetCtxts(); - } - - /// Decodes 'n' symbols from the bit stream using the same context - /// 'ctxt'. If possible the MQ-coder speedup mode will be used to speed up - /// decoding. The speedup mode is used if Q (the LPS probability for 'ctxt' - /// is low enough) and the A and C registers permit decoding several MPS - /// symbols without renormalization. - /// - ///

    Speedup mode should be used when decoding long runs of MPS with high - /// probability with the same context. - /// - ///

    This methiod will return the decoded symbols differently if speedup - /// mode was used or not. If true is returned, then speedup mode was used - /// and the 'n' decoded symbols are all the same and it is returned ain - /// bits[0] only. If false is returned then speedup mode was not used, the - /// decoded symbols are probably not all the same and they are returned in - /// bits[0], bits[1], ... bits[n-1]. - /// - ///

    - /// The array where to put the decoded symbols. Must be of - /// length 'n' or more. - /// - /// - /// The context to use in decoding the symbols. - /// - /// - /// The number of symbols to decode. - /// - /// - /// True if speedup mode was used, false if not. If speedup mode - /// was used then all the decoded symbols are the same and its value is - /// returned in 'bits[0]' only (not in bits[1], bits[2], etc.). - /// - /// - internal bool fastDecodeSymbols(int[] bits, int ctxt, uint n) - { - uint q; // LPS probability for context - int idx; // Index of current state - uint la; // cache for A register - int i; // counter - - idx = I[ctxt]; - q = qe[idx]; - - // This is a first attempt to implement speedup mode, it is probably - // not the most efficient way of doing it. - - if ((q < 0x4000) && (n <= (a - (c >> 16) - 1) / q) && (n <= (a - 0x8000) / q + 1)) - { - // Q is small enough. There will be no modification of C that - // affects decoding, and Q can be substracted from A several - // times. We will decode all MPS. - a -= n * q; - if (a >= 0x8000) - { - // No renormalization needed - bits[0] = mPS[ctxt]; - return true; // Done, used speedup mode - } - else - { - // renormalization needed - I[ctxt] = nMPS[idx]; - // Renormalize (MPS: no need for while loop) - if (cT == 0) - byteIn(); - a <<= 1; - c <<= 1; - cT--; - // End renormalization - bits[0] = mPS[ctxt]; - return true; // Done, used speedup mode - } - } - else - { - // Normal mode - la = a; // cache A register - for (i = 0; i < n; i++) - { - la -= q; - if ((c >> 16) < la) - { - if (la >= 0x8000) - { - bits[i] = mPS[ctxt]; - } - else - { - // -- MPS Exchange - if (la >= q) - { - bits[i] = mPS[ctxt]; - idx = nMPS[idx]; - q = qe[idx]; - // I[ctxt] set at end of loop - // -- Renormalize (MPS: no need for while loop) - if (cT == 0) - byteIn(); - la <<= 1; - c <<= 1; - cT--; - // -- End renormalization - } - else - { - bits[i] = 1 - mPS[ctxt]; - if (switchLM[idx] == 1) - mPS[ctxt] = 1 - mPS[ctxt]; - idx = nLPS[idx]; - q = qe[idx]; - // I[ctxt] set at end of loop - // -- Renormalize - do - { - if (cT == 0) - byteIn(); - la <<= 1; - c <<= 1; - cT--; - } - while (la < 0x8000); - // -- End renormalization - } - // -- End MPS Exchange - } - } - else - { - c -= (la << 16); - // -- LPS Exchange - if (la < q) - { - la = q; - bits[i] = mPS[ctxt]; - idx = nMPS[idx]; - q = qe[idx]; - // I[ctxt] set at end of loop - // -- Renormalize (MPS: no need for while loop) - if (cT == 0) - byteIn(); - la <<= 1; - c <<= 1; - cT--; - // -- End renormalization - } - else - { - la = q; - bits[i] = 1 - mPS[ctxt]; - if (switchLM[idx] == 1) - mPS[ctxt] = 1 - mPS[ctxt]; - idx = nLPS[idx]; - q = qe[idx]; - // I[ctxt] set at end of loop - // -- Renormalize - do - { - if (cT == 0) - byteIn(); - la <<= 1; - c <<= 1; - cT--; - } - while (la < 0x8000); - // -- End renormalization - } - // -- End LPS Exchange - } - } - a = la; // save cached A register - I[ctxt] = idx; // save current index for context - return false; // done, did not use speedup mode - } // End normal mode - } - - /// This function performs the arithmetic decoding. The function receives - /// an array in which to put the decoded symbols and an array of contexts - /// with which to decode them. - /// - ///

    Each context has a current MPS and an index describing what the - /// current probability is for the LPS. Each bit is decoded and if the - /// probability of the LPS exceeds .5, the MPS and LPS are switched. - /// - ///

    - /// The array where to place the decoded symbols. It should be - /// long enough to contain 'n' elements. - /// - /// - /// The context to use in decoding each symbol. - /// - /// - /// The number of symbols to decode - /// - /// - public void decodeSymbols(int[] bits, int[] cX, int n) - { - uint q; - int ctxt; - uint la; // cache for A register value - int index; - int i; - - // NOTE: (a < 0x8000) is equivalent to ((a & 0x8000)==0) - // since 'a' is always less than or equal to 0xFFFF - - // NOTE: conditional exchange guarantees that A for MPS is - // always greater than 0x4000 (i.e. 0.375) - // => one renormalization shift is enough for MPS - // => no need to do a renormalization while loop for MPS - - for (i = 0; i < n; i++) - { - ctxt = cX[i]; - - index = I[ctxt]; - q = qe[index]; - - a -= q; - if ((c >> 16) < a) - { - if (a >= 0x8000) - { - bits[i] = mPS[ctxt]; - } - else - { - la = a; - // -- MPS Exchange - if (la >= q) - { - bits[i] = mPS[ctxt]; - I[ctxt] = nMPS[index]; - // -- Renormalize (MPS: no need for while loop) - if (cT == 0) - byteIn(); - la <<= 1; - c <<= 1; - cT--; - // -- End renormalization - } - else - { - bits[i] = 1 - mPS[ctxt]; - if (switchLM[index] == 1) - mPS[ctxt] = 1 - mPS[ctxt]; - I[ctxt] = nLPS[index]; - // -- Renormalize - do - { - if (cT == 0) - byteIn(); - la <<= 1; - c <<= 1; - cT--; - } - while (la < 0x8000); - // -- End renormalization - } - // -- End MPS Exchange - a = la; - } - } - else - { - la = a; - c -= (la << 16); - // -- LPS Exchange - if (la < q) - { - la = q; - bits[i] = mPS[ctxt]; - I[ctxt] = nMPS[index]; - // -- Renormalize (MPS: no need for while loop) - if (cT == 0) - byteIn(); - la <<= 1; - c <<= 1; - cT--; - // -- End renormalization - } - else - { - la = q; - bits[i] = 1 - mPS[ctxt]; - if (switchLM[index] == 1) - mPS[ctxt] = 1 - mPS[ctxt]; - I[ctxt] = nLPS[index]; - // -- Renormalize - do - { - if (cT == 0) - byteIn(); - la <<= 1; - c <<= 1; - cT--; - } - while (la < 0x8000); - // -- End renormalization - } - // -- End LPS Exchange - - a = la; - } - } - } - - - /// Arithmetically decodes one symbol from the bit stream with the given - /// context and returns its decoded value. - /// - ///

    Each context has a current MPS and an index describing what the - /// current probability is for the LPS. Each bit is encoded and if the - /// probability of the LPS exceeds .5, the MPS and LPS are switched. - /// - ///

    - /// The context to use in decoding the symbol - /// - /// - /// The decoded symbol, 0 or 1. - /// - /// - public int decodeSymbol(int context) - { - uint q; - uint la; - int index; - int decision; - - index = I[context]; - q = qe[index]; - - // NOTE: (a < 0x8000) is equivalent to ((a & 0x8000)==0) - // since 'a' is always less than or equal to 0xFFFF - - // NOTE: conditional exchange guarantees that A for MPS is - // always greater than 0x4000 (i.e. 0.375) - // => one renormalization shift is enough for MPS - // => no need to do a renormalization while loop for MPS - - a -= q; - if ((c >> 16) < a) - { - if (a >= 0x8000) - { - decision = mPS[context]; - } - else - { - la = a; - // -- MPS Exchange - if (la >= q) - { - decision = mPS[context]; - I[context] = nMPS[index]; - // -- Renormalize (MPS: no need for while loop) - if (cT == 0) - byteIn(); - la <<= 1; - c <<= 1; - cT--; - // -- End renormalization - } - else - { - decision = 1 - mPS[context]; - if (switchLM[index] == 1) - mPS[context] = 1 - mPS[context]; - I[context] = nLPS[index]; - // -- Renormalize - do - { - if (cT == 0) - byteIn(); - la <<= 1; - c <<= 1; - cT--; - } - while (la < 0x8000); - // -- End renormalization - } - // -- End MPS Exchange - a = la; - } - } - else - { - la = a; - c -= (la << 16); - // -- LPS Exchange - if (la < q) - { - la = q; - decision = mPS[context]; - I[context] = nMPS[index]; - // -- Renormalize (MPS: no need for while loop) - if (cT == 0) - byteIn(); - la <<= 1; - c <<= 1; - cT--; - // -- End renormalization - } - else - { - la = q; - decision = 1 - mPS[context]; - if (switchLM[index] == 1) - mPS[context] = 1 - mPS[context]; - I[context] = nLPS[index]; - // -- Renormalize - do - { - if (cT == 0) - byteIn(); - la <<= 1; - c <<= 1; - cT--; - } - while (la < 0x8000); - // -- End renormalization - } - // -- End LPS Exchange - - a = la; - } - return decision; - } - - /// Checks for past errors in the decoding process using the predictable - /// error resilient termination. This works only if the encoder used the - /// predictable error resilient MQ termination, otherwise it reports wrong - /// results. If an error is detected it means that the MQ bit stream has - /// been wrongly decoded or that the MQ terminated segment length is too - /// long. If no errors are detected it does not necessarily mean that the - /// MQ bit stream has been correctly decoded. - /// - /// - /// True if errors are found, false otherwise. - /// - /// - public virtual bool checkPredTerm() - { - int k; // Number of bits that where added in the termination process - uint q; - - // 1) if everything has been OK, 'b' must be 0xFF if a terminating - // marker has not yet been found - if (b != 0xFF && !markerFound) - return true; - - // 2) if cT is not 0, we must have already reached the terminating - // marker - if (cT != 0 && !markerFound) - return true; - - // 3) If cT is 1 there where no spare bits at the encoder, this is all - // that we can check - if (cT == 1) - return false; - - // 4) if cT is 0, then next byte must be the second byte of a - // terminating marker (i.e. larger than 0x8F) if the terminating - // marker has not been reached yet - if (cT == 0) - { - if (!markerFound) - { - // Get next byte and check - b = (uint)in_Renamed.read() & 0xFF; - if (b <= 0x8F) - return true; - } - // Adjust cT for last byte - cT = 8; - } - - // 5) Now we can calculate the number 'k' of bits having error - // resilience information, which is the number of bits left to - // normalization in the C register, minus 1. - k = (int)(cT - 1); - - // 6) The predictable termination policy is as if an LPS interval was - // coded that caused a renormalization of 'k' bits, before the - // termination marker started - - // We first check if an LPS is decoded, that causes a renormalization - // of 'k' bits. Worst case is smallest LPS probability 'q' that causes - // a renormalization of 'k' bits. - q = ((uint)0x8000) >> k; - - // Check that we can decode an LPS interval of probability 'q' - a -= q; - if ((c >> 16) < a) - { - // Error: MPS interval decoded - return true; - } - // OK: LPS interval decoded - c -= (a << 16); - // -- LPS Exchange - // Here 'a' can not be smaller than 'q' because the minimum value - // for 'a' is 0x8000-0x4000=0x4000 and 'q' is set to a value equal - // to or smaller than that. - a = q; - // -- Renormalize - do - { - if (cT == 0) - byteIn(); - a <<= 1; - c <<= 1; - cT--; - } - while (a < 0x8000); - // -- End renormalization - // -- End LPS Exchange - - // 7) Everything seems OK, we have checked the C register for the LPS - // symbols and ensured that it is followed by bits synthetized by the - // termination marker. - return false; - } - - /// This function gets one byte of compressed bits from the in-stream. the - /// byte is added to c. If the byte is 0xFF and the next byte is greater - /// than 0x8F, the byte after 0xFF is a marker. - /// - /// - private void byteIn() - { - if (!markerFound) - { - if (b == 0xFF) - { - b = ((uint)in_Renamed.read()) & 0xFF; // Convert EOFs (-1) to 0xFF - - if (b > 0x8F) - { - markerFound = true; - // software-convention decoder: c unchanged - cT = 8; - } - else - { - c += 0xFE00 - (b << 9); - cT = 7; - } - } - else - { - b = ((uint)in_Renamed.read()) & 0xFF; // Convert EOFs (-1) to 0xFF - c += 0xFF00 - (b << 8); - cT = 8; - } - } - else - { - // software-convention decoder: c unchanged - cT = 8; - } - } - - /// Resets a context to the original probability distribution. - /// - /// - /// The number of the context (it starts at 0). - /// - /// - public void resetCtxt(int c) - { - I[c] = initStates[c]; - mPS[c] = 0; - } - - /// Resets a context to the original probability distribution. The original - /// probability distribution depends on the actual implementation of the - /// arithmetic coder or decoder. - /// - /// - /// The index of the context (it starts at 0). - /// - /// - public void resetCtxts() - { - Array.Copy(initStates, 0, I, 0, I.Length); - ArrayUtil.intArraySet(mPS, 0); - } - - /// Resets the MQ decoder to start a new segment. This is like recreating a - /// new MQDecoder object with new input data. - /// - /// - /// The byte array containing the MQ encoded data. If null the - /// current byte array is assumed. - /// - /// - /// The index of the first element in 'buf' to be decoded. If - /// negative the byte just after the previous segment is assumed, only - /// valid if 'buf' is null. - /// - /// - /// The number of bytes in 'buf' to be decoded. Any subsequent - /// bytes are taken to be 0xFF. - /// - /// - public void nextSegment(byte[] buf, int off, int len) - { - // Set the new input - in_Renamed.setByteArray(buf, off, len); - // Reinitialize MQ - init(); - } - - /// Initializes the state of the MQ coder, without modifying the current - /// context states. It sets the registers (A,C,B) and the "marker found" - /// state to the initial state, to start the decoding of a new segment. - /// - ///

    To have a complete reset of the MQ (as if a new MQDecoder object was - /// created) 'resetCtxts()' should be called after this method. - /// - ///

    - private void init() - { - // --- INITDEC - markerFound = false; - - // Read first byte - b = ((uint)in_Renamed.read()) & 0xFF; - - // Software conventions decoder - c = (b ^ 0xFF) << 16; - byteIn(); - c = c << 7; - cT = cT - 7; - a = 0x8000; - - // End of INITDEC --- - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/entropy/decoder/StdEntropyDecoder.cs b/CSJ2K/j2k/entropy/decoder/StdEntropyDecoder.cs deleted file mode 100644 index 1bfc8b89..00000000 --- a/CSJ2K/j2k/entropy/decoder/StdEntropyDecoder.cs +++ /dev/null @@ -1,2551 +0,0 @@ -/* -* CVS identifier: -* -* $Id: StdEntropyDecoder.java,v 1.30 2001/10/25 12:12:16 qtxjoas Exp $ -* -* Class: StdEntropyDecoder -* -* Description: Entropy decoding engine of stripes in code-blocks -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.decoder; -using CSJ2K.j2k.image; -using CSJ2K.j2k.util; -using CSJ2K.j2k.wavelet; -using CSJ2K.j2k.wavelet.synthesis; -namespace CSJ2K.j2k.entropy.decoder -{ - - /// This class implements the JPEG 2000 entropy decoder, which codes stripes in - /// code-blocks. This entropy decoding engine decodes one code-block at a time. - /// - ///

    The code-blocks are rectangular and their dimensions must be powers of - /// 2. Each dimension cannot be smaller than 4 and larger than 256. The product - /// of the two dimensions (i.e. area of the code-block) cannot exceed 4096.

    - /// - ///

    Context 0 of the MQ-coder is used as the uniform one (uniform, - /// non-adaptive probability distribution). Context 1 is used for RLC - /// coding. Contexts 2-10 are used for zero-coding (ZC), contexts 11-15 are - /// used for sign-coding (SC) and contexts 16-18 are used for - /// magnitude-refinement (MR).

    - /// - ///

    This implementation also provides some timing features. They can be - /// enabled by setting the 'DO_TIMING' constant of this class to true and - /// recompiling. The timing uses the 'System.currentTimeMillis()' Java API - /// call, which returns wall clock time, not the actual CPU time used. The - /// timing results will be printed on the message output. Since the times - /// reported are wall clock times and not CPU usage times they can not be added - /// to find the total used time (i.e. some time might be counted in several - /// places). When timing is disabled ('DO_TIMING' is false) there is no penalty - /// if the compiler performs some basic optimizations. Even if not the penalty - /// should be negligeable.

    - /// - ///
    - public class StdEntropyDecoder : EntropyDecoder - { - - /// Whether to collect timing information or not: false. Used as a compile - /// time directive. - /// - private const bool DO_TIMING = false; - - /// The cumulative wall time for the entropy coding engine, for each - /// component. - /// - //private long[] time; - - /// The bit based input for arithmetic coding bypass (i.e. raw) coding - private ByteToBitInput bin; - - /// The MQ decoder to use. It has in as the underlying source of coded - /// data. - /// - private MQDecoder mq; - - /// The decoder spec - private DecoderSpecs decSpec; - - /// The options that are turned on, as flag bits. The options are - /// 'OPT_TERM_PASS', 'OPT_RESET_MQ', 'OPT_VERT_STR_CAUSAL', 'OPT_BYPASS' - /// and 'OPT_SEG_SYMBOLS' as defined in the StdEntropyCoderOptions - /// interface - /// - /// - /// - /// - /// - private int options; - - /// Flag to indicate if we should try to detect errors or just ignore any - /// error resilient information - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'doer '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private bool doer; - - /// Flag to indicate if we should be verbose about bit stream errors - /// detected with the error resilience options - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'verber '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private bool verber; - - /// Number of bits used for the Zero Coding lookup table - private const int ZC_LUT_BITS = 8; - - /// Zero Coding context lookup tables for the LH global orientation - //UPGRADE_NOTE: Final was removed from the declaration of 'ZC_LUT_LH '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int[] ZC_LUT_LH = new int[1 << ZC_LUT_BITS]; - - /// Zero Coding context lookup tables for the HL global orientation - //UPGRADE_NOTE: Final was removed from the declaration of 'ZC_LUT_HL '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int[] ZC_LUT_HL = new int[1 << ZC_LUT_BITS]; - - /// Zero Coding context lookup tables for the HH global orientation - //UPGRADE_NOTE: Final was removed from the declaration of 'ZC_LUT_HH '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int[] ZC_LUT_HH = new int[1 << ZC_LUT_BITS]; - - /// Number of bits used for the Sign Coding lookup table - private const int SC_LUT_BITS = 9; - - /// Sign Coding context lookup table. The index into the table is a 9 bit - /// index, which correspond the the value in the 'state' array shifted by - /// 'SC_SHIFT'. Bits 8-5 are the signs of the horizontal-left, - /// horizontal-right, vertical-up and vertical-down neighbors, - /// respectively. Bit 4 is not used (0 or 1 makes no difference). Bits 3-0 - /// are the significance of the horizontal-left, horizontal-right, - /// vertical-up and vertical-down neighbors, respectively. The least 4 bits - /// of the value in the lookup table define the context number and the sign - /// bit defines the "sign predictor". - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'SC_LUT '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int[] SC_LUT = new int[1 << SC_LUT_BITS]; - - /// The mask to obtain the context index from the 'SC_LUT' - private const int SC_LUT_MASK = (1 << 4) - 1; - - /// The shift to obtain the sign predictor from the 'SC_LUT'. It must be - /// an unsigned shift. - /// - private const int SC_SPRED_SHIFT = 31; - - /// The sign bit for int data - private const int INT_SIGN_BIT = 1 << 31; - - /// The number of bits used for the Magnitude Refinement lookup table - private const int MR_LUT_BITS = 9; - - /// Magnitude Refinement context lookup table - //UPGRADE_NOTE: Final was removed from the declaration of 'MR_LUT '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int[] MR_LUT = new int[1 << MR_LUT_BITS]; - - /// The number of contexts used - private const int NUM_CTXTS = 19; - - /// The RLC context - private const int RLC_CTXT = 1; - - /// The UNIFORM context (with a uniform probability distribution which - /// does not adapt) - /// - private const int UNIF_CTXT = 0; - - /// The initial states for the MQ coder - //UPGRADE_NOTE: Final was removed from the declaration of 'MQ_INIT'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int[] MQ_INIT = new int[] { 46, 3, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; - - /// The 4 bits of the error resilience segmentation symbol (decimal 10, - /// which is binary sequence 1010) - /// - private const int SEG_SYMBOL = 10; - - /// The state array for entropy coding. Each element of the state array - /// stores the state of two coefficients. The lower 16 bits store the state - /// of a coefficient in row 'i' and column 'j', while the upper 16 bits - /// store the state of a coefficient in row 'i+1' and column 'j'. The 'i' - /// row is either the first or the third row of a stripe. This packing of - /// the states into 32 bit words allows a faster scan of all coefficients - /// on each coding pass and diminished the amount of data transferred. The - /// size of the state array is increased by 1 on each side (top, bottom, - /// left, right) to handle boundary conditions without any special logic. - /// - ///

    The state of a coefficient is stored in the following way in the - /// lower 16 bits, where bit 0 is the least significant bit. Bit 15 is the - /// significance of a coefficient (0 if non-significant, 1 otherwise). Bit - /// 14 is the visited state (i.e. if a coefficient has been coded in the - /// significance propagation pass of the current bit-plane). Bit 13 is the - /// "non zero-context" state (i.e. if one of the eight immediate neighbors - /// is significant it is 1, otherwise is 0). Bits 12 to 9 store the sign of - /// the already significant left, right, up and down neighbors (1 for - /// negative, 0 for positive or not yet significant). Bit 8 indicates if - /// the magnitude refinement has already been applied to the - /// coefficient. Bits 7 to 4 store the significance of the left, right, up - /// and down neighbors (1 for significant, 0 for non significant). Bits 3 - /// to 0 store the significance of the diagonal coefficients (up-left, - /// up-right, down-left and down-right; 1 for significant, 0 for non - /// significant). - /// - ///

    The upper 16 bits the state is stored as in the lower 16 bits, but - /// with the bits shifted up by 16. - /// - ///

    The lower 16 bits are referred to as "row 1" ("R1") while the upper - /// 16 bits are referred to as "row 2" ("R2"). - /// - ///

    - //UPGRADE_NOTE: Final was removed from the declaration of 'state '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private int[] state; - - /// The separation between the upper and lower bits in the state array: 16 - /// - /// - private const int STATE_SEP = 16; - - /// The flag bit for the significance in the state array, for row 1. - private const int STATE_SIG_R1 = 1 << 15; - - /// The flag bit for the "visited" bit in the state array, for row 1. - private const int STATE_VISITED_R1 = 1 << 14; - - /// The flag bit for the "not zero context" bit in the state array, for - /// row 1. This bit is always the OR of bits STATE_H_L_R1, STATE_H_R_R1, - /// STATE_V_U_R1, STATE_V_D_R1, STATE_D_UL_R1, STATE_D_UR_R1, STATE_D_DL_R1 - /// and STATE_D_DR_R1. - /// - private const int STATE_NZ_CTXT_R1 = 1 << 13; - - /// The flag bit for the horizontal-left sign in the state array, for row - /// 1. This bit can only be set if the STATE_H_L_R1 is also set. - /// - private const int STATE_H_L_SIGN_R1 = 1 << 12; - - /// The flag bit for the horizontal-right sign in the state array, for - /// row 1. This bit can only be set if the STATE_H_R_R1 is also set. - /// - private const int STATE_H_R_SIGN_R1 = 1 << 11; - - /// The flag bit for the vertical-up sign in the state array, for row - /// 1. This bit can only be set if the STATE_V_U_R1 is also set. - /// - private const int STATE_V_U_SIGN_R1 = 1 << 10; - - /// The flag bit for the vertical-down sign in the state array, for row - /// 1. This bit can only be set if the STATE_V_D_R1 is also set. - /// - private const int STATE_V_D_SIGN_R1 = 1 << 9; - - /// The flag bit for the previous MR primitive applied in the state array, - /// for row 1. - /// - private const int STATE_PREV_MR_R1 = 1 << 8; - - /// The flag bit for the horizontal-left significance in the state array, - /// for row 1. - /// - private const int STATE_H_L_R1 = 1 << 7; - - /// The flag bit for the horizontal-right significance in the state array, - /// for row 1. - /// - private const int STATE_H_R_R1 = 1 << 6; - - /// The flag bit for the vertical-up significance in the state array, for - /// row 1. - /// - private const int STATE_V_U_R1 = 1 << 5; - - /// The flag bit for the vertical-down significance in the state array, - /// for row 1. - /// - private const int STATE_V_D_R1 = 1 << 4; - - /// The flag bit for the diagonal up-left significance in the state array, - /// for row 1. - /// - private const int STATE_D_UL_R1 = 1 << 3; - - /// The flag bit for the diagonal up-right significance in the state - /// array, for row 1. - /// - private const int STATE_D_UR_R1 = 1 << 2; - - /// The flag bit for the diagonal down-left significance in the state - /// array, for row 1. - /// - private const int STATE_D_DL_R1 = 1 << 1; - - /// The flag bit for the diagonal down-right significance in the state - /// array , for row 1. - /// - private const int STATE_D_DR_R1 = 1; - - /// The flag bit for the significance in the state array, for row 2. - //UPGRADE_NOTE: Final was removed from the declaration of 'STATE_SIG_R2 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int STATE_SIG_R2 = STATE_SIG_R1 << STATE_SEP; - - /// The flag bit for the "visited" bit in the state array, for row 2. - //UPGRADE_NOTE: Final was removed from the declaration of 'STATE_VISITED_R2 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int STATE_VISITED_R2 = STATE_VISITED_R1 << STATE_SEP; - - /// The flag bit for the "not zero context" bit in the state array, for - /// row 2. This bit is always the OR of bits STATE_H_L_R2, STATE_H_R_R2, - /// STATE_V_U_R2, STATE_V_D_R2, STATE_D_UL_R2, STATE_D_UR_R2, STATE_D_DL_R2 - /// and STATE_D_DR_R2. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'STATE_NZ_CTXT_R2 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int STATE_NZ_CTXT_R2 = STATE_NZ_CTXT_R1 << STATE_SEP; - - /// The flag bit for the horizontal-left sign in the state array, for row - /// 2. This bit can only be set if the STATE_H_L_R2 is also set. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'STATE_H_L_SIGN_R2 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int STATE_H_L_SIGN_R2 = STATE_H_L_SIGN_R1 << STATE_SEP; - - /// The flag bit for the horizontal-right sign in the state array, for row - /// 2. This bit can only be set if the STATE_H_R_R2 is also set. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'STATE_H_R_SIGN_R2 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int STATE_H_R_SIGN_R2 = STATE_H_R_SIGN_R1 << STATE_SEP; - - /// The flag bit for the vertical-up sign in the state array, for row - /// 2. This bit can only be set if the STATE_V_U_R2 is also set. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'STATE_V_U_SIGN_R2 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int STATE_V_U_SIGN_R2 = STATE_V_U_SIGN_R1 << STATE_SEP; - - /// The flag bit for the vertical-down sign in the state array, for row - /// 2. This bit can only be set if the STATE_V_D_R2 is also set. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'STATE_V_D_SIGN_R2 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int STATE_V_D_SIGN_R2 = STATE_V_D_SIGN_R1 << STATE_SEP; - - /// The flag bit for the previous MR primitive applied in the state array, - /// for row 2. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'STATE_PREV_MR_R2 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int STATE_PREV_MR_R2 = STATE_PREV_MR_R1 << STATE_SEP; - - /// The flag bit for the horizontal-left significance in the state array, - /// for row 2. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'STATE_H_L_R2 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int STATE_H_L_R2 = STATE_H_L_R1 << STATE_SEP; - - /// The flag bit for the horizontal-right significance in the state array, - /// for row 2. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'STATE_H_R_R2 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int STATE_H_R_R2 = STATE_H_R_R1 << STATE_SEP; - - /// The flag bit for the vertical-up significance in the state array, for - /// row 2. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'STATE_V_U_R2 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int STATE_V_U_R2 = STATE_V_U_R1 << STATE_SEP; - - /// The flag bit for the vertical-down significance in the state array, - /// for row 2. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'STATE_V_D_R2 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int STATE_V_D_R2 = STATE_V_D_R1 << STATE_SEP; - - /// The flag bit for the diagonal up-left significance in the state array, - /// for row 2. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'STATE_D_UL_R2 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int STATE_D_UL_R2 = STATE_D_UL_R1 << STATE_SEP; - - /// The flag bit for the diagonal up-right significance in the state - /// array, for row 2. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'STATE_D_UR_R2 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int STATE_D_UR_R2 = STATE_D_UR_R1 << STATE_SEP; - - /// The flag bit for the diagonal down-left significance in the state - /// array, for row 2. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'STATE_D_DL_R2 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int STATE_D_DL_R2 = STATE_D_DL_R1 << STATE_SEP; - - /// The flag bit for the diagonal down-right significance in the state - /// array , for row 2. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'STATE_D_DR_R2 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int STATE_D_DR_R2 = STATE_D_DR_R1 << STATE_SEP; - - /// The mask to isolate the significance bits for row 1 and 2 of the state - /// array. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'SIG_MASK_R1R2 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int SIG_MASK_R1R2 = STATE_SIG_R1 | STATE_SIG_R2; - - /// The mask to isolate the visited bits for row 1 and 2 of the state - /// array. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'VSTD_MASK_R1R2 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int VSTD_MASK_R1R2 = STATE_VISITED_R1 | STATE_VISITED_R2; - - /// The mask to isolate the bits necessary to identify RLC coding state - /// (significant, visited and non-zero context, for row 1 and 2). - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'RLC_MASK_R1R2 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int RLC_MASK_R1R2 = STATE_SIG_R1 | STATE_SIG_R2 | STATE_VISITED_R1 | STATE_VISITED_R2 | STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2; - - /// The mask to obtain the ZC_LUT index from the 'state' information - // This is needed because of the STATE_V_D_SIGN, STATE_V_U_SIGN, - // STATE_H_R_SIGN, and STATE_H_L_SIGN bits. - private const int ZC_MASK = (1 << 8) - 1; - - /// The shift to obtain the SC index to 'SC_LUT' from the 'state' - /// information, for row 1. - /// - private const int SC_SHIFT_R1 = 4; - - /// The shift to obtain the SC index to 'SC_LUT' from the state - /// information, for row 2. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'SC_SHIFT_R2 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int SC_SHIFT_R2 = SC_SHIFT_R1 + STATE_SEP; - - /// The bit mask to isolate the state bits relative to the sign coding - /// lookup table ('SC_LUT'). - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'SC_MASK '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int SC_MASK = (1 << SC_LUT_BITS) - 1; - - /// The mask to obtain the MR index to 'MR_LUT' from the 'state' - /// information. It is to be applied after the 'MR_SHIFT' - /// - private const int MR_MASK = (1 << 9) - 1; - - /// The source code-block to entropy code (avoids reallocation for each - /// code-block). - /// - private DecLyrdCBlk srcblk; - - /// The maximum number of bit planes to decode for any code-block - private int mQuit; - - /// Instantiates a new entropy decoder engine, with the specified source of - /// data, nominal block width and height. - /// - /// - /// The source of data - /// - /// - /// The options to use for this encoder. It is a mix of the - /// 'OPT_TERM_PASS', 'OPT_RESET_MQ', 'OPT_VERT_STR_CAUSAL', 'OPT_BYPASS' - /// and 'OPT_SEG_SYMBOLS' option flags. - /// - /// - /// If true error detection will be performed, if any error - /// detection features have been enabled. - /// - /// - /// This flag indicates if the entropy decoder should be - /// verbose about bit stream errors that are detected and concealed. - /// - /// - /// the maximum number of bit planes to decode according to - /// the m quit condition - /// - /// - public StdEntropyDecoder(CodedCBlkDataSrcDec src, DecoderSpecs decSpec, bool doer, bool verber, int mQuit) : base(src) - { - - this.decSpec = decSpec; - this.doer = doer; - this.verber = verber; - this.mQuit = mQuit; - - // If we do timing create necessary structures -#if DO_TIMING - time = new long[src.NumComps]; - // If we are timing make sure that 'finalize' gets called. - //UPGRADE_ISSUE: Method 'java.lang.System.runFinalizersOnExit' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javalangSystem'" - // CONVERSION PROBLEM? - //System_Renamed.runFinalizersOnExit(true); -#endif - - // Initialize internal variables - state = new int[(decSpec.cblks.MaxCBlkWidth + 2) * ((decSpec.cblks.MaxCBlkHeight + 1) / 2 + 2)]; - } - -#if DO_TIMING - /// Prints the timing information, if collected, and calls 'finalize' on - /// the super class. - /// - /// - ~StdEntropyDecoder() - { - int c; - System.Text.StringBuilder sb; - - sb = new System.Text.StringBuilder("StdEntropyDecoder decompression wall " + "clock time:"); - for (c = 0; c < time.Length; c++) - { - sb.Append("\n component "); - sb.Append(c); - sb.Append(": "); - sb.Append(time[c]); - sb.Append(" ms"); - } - FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.INFO, sb.ToString()); - - //UPGRADE_NOTE: Call to 'super.finalize()' was removed. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1124'" - } -#endif - - /// Returns the specified code-block in the current tile for the specified - /// component, as a copy (see below). - /// - ///

    The returned code-block may be progressive, which is indicated by - /// the 'progressive' variable of the returned 'DataBlk' object. If a - /// code-block is progressive it means that in a later request to this - /// method for the same code-block it is possible to retrieve data which is - /// a better approximation, since meanwhile more data to decode for the - /// code-block could have been received. If the code-block is not - /// progressive then later calls to this method for the same code-block - /// will return the exact same data values. - /// - ///

    The data returned by this method is always a copy of the internal - /// data of this object, if any, and it can be modified "in place" without - /// any problems after being returned. The 'offset' of the returned data is - /// 0, and the 'scanw' is the same as the code-block width. See the - /// 'DataBlk' class. - /// - ///

    The 'ulx' and 'uly' members of the returned 'DataBlk' object - /// contain the coordinates of the top-left corner of the block, with - /// respect to the tile, not the subband. - /// - ///

    - /// The component for which to return the next code-block. - /// - /// - /// The vertical index of the code-block to return, in the - /// specified subband. - /// - /// - /// The horizontal index of the code-block to return, in the - /// specified subband. - /// - /// - /// The subband in which the code-block to return is. - /// - /// - /// If non-null this object will be used to return the new - /// code-block. If null a new one will be allocated and returned. If the - /// "data" array of the object is non-null it will be reused, if possible, - /// to return the data. - /// - /// - /// The next code-block in the current tile for component 'n', or - /// null if all code-blocks for the current tile have been returned. - /// - /// - /// - /// - /// - public override DataBlk getCodeBlock(int c, int m, int n, SubbandSyn sb, DataBlk cblk) - { - //long stime = 0L; // Start time for timed sections - int[] zc_lut; // The ZC lookup table to use - int[] out_data; // The outupt data buffer - int npasses; // The number of coding passes to perform - int curbp; // The current magnitude bit-plane (starts at 30) - bool error; // Error indicator - int tslen; // Length of first terminated segment - int tsidx; // Index of current terminated segment - ByteInputBuffer in_Renamed = null; - - bool isterm; - - // Get the code-block to decode - srcblk = src.getCodeBlock(c, m, n, sb, 1, -1, srcblk); - -#if DO_TIMING - stime = (System.DateTime.Now.Ticks - 621355968000000000) / 10000; -#endif - - // Retrieve options from decSpec - options = ((System.Int32)decSpec.ecopts.getTileCompVal(tIdx, c)); - - // Reset state - ArrayUtil.intArraySet(state, 0); - - // Initialize output code-block - if (cblk == null) - cblk = new DataBlkInt(); - cblk.progressive = srcblk.prog; - cblk.ulx = srcblk.ulx; - cblk.uly = srcblk.uly; - cblk.w = srcblk.w; - cblk.h = srcblk.h; - cblk.offset = 0; - cblk.scanw = cblk.w; - out_data = (int[])cblk.Data; - - if (out_data == null || out_data.Length < srcblk.w * srcblk.h) - { - out_data = new int[srcblk.w * srcblk.h]; - cblk.Data = out_data; - } - else - { - // Set data values to 0 - ArrayUtil.intArraySet(out_data, 0); - } - - if (srcblk.nl <= 0 || srcblk.nTrunc <= 0) - { - // 0 layers => no data to decode => return all 0s - return cblk; - } - - // Get the length of the first terminated segment - tslen = (srcblk.tsLengths == null) ? srcblk.dl : srcblk.tsLengths[0]; - tsidx = 0; - // Initialize for decoding - npasses = srcblk.nTrunc; - if (mq == null) - { - in_Renamed = new ByteInputBuffer(srcblk.data, 0, tslen); - mq = new MQDecoder(in_Renamed, NUM_CTXTS, MQ_INIT); - } - else - { - // We always start by an MQ segment - mq.nextSegment(srcblk.data, 0, tslen); - mq.resetCtxts(); - } - error = false; - - if ((options & CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_BYPASS) != 0) - { - if (bin == null) - { - if (in_Renamed == null) - in_Renamed = mq.ByteInputBuffer; - bin = new ByteToBitInput(in_Renamed); - } - } - - // Choose correct ZC lookup table for global orientation - switch (sb.orientation) - { - - case Subband.WT_ORIENT_HL: - zc_lut = ZC_LUT_HL; - break; - - case Subband.WT_ORIENT_LH: - case Subband.WT_ORIENT_LL: - zc_lut = ZC_LUT_LH; - break; - - case Subband.WT_ORIENT_HH: - zc_lut = ZC_LUT_HH; - break; - - default: - throw new System.ApplicationException("JJ2000 internal error"); - - } - - // NOTE: we don't currently detect which is the last magnitude - // bit-plane so that 'isterm' is true for the last pass of it. Doing - // so would aid marginally in error detection with the predictable - // error resilient MQ termination. However, determining which is the - // last magnitude bit-plane is quite hard (due to ROI, quantization, - // etc.) and in any case the predictable error resilient termination - // used without the arithmetic coding bypass and/or regular - // termination modes is almost useless. - - // Loop on bit-planes and passes - - curbp = 30 - srcblk.skipMSBP; - - // Check for maximum number of bitplanes quit condition - if (mQuit != -1 && (mQuit * 3 - 2) < npasses) - { - npasses = mQuit * 3 - 2; - } - - // First bit-plane has only the cleanup pass - if (curbp >= 0 && npasses > 0) - { - isterm = (options & CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_TERM_PASS) != 0 || ((options & CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_BYPASS) != 0 && (31 - CSJ2K.j2k.entropy.StdEntropyCoderOptions.NUM_NON_BYPASS_MS_BP - srcblk.skipMSBP) >= curbp); - error = cleanuppass(cblk, mq, curbp, state, zc_lut, isterm); - npasses--; - if (!error || !doer) - curbp--; - } - - // Other bit-planes have the three coding passes - if (!error || !doer) - { - while (curbp >= 0 && npasses > 0) - { - - if ((options & CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_BYPASS) != 0 && (curbp < 31 - CSJ2K.j2k.entropy.StdEntropyCoderOptions.NUM_NON_BYPASS_MS_BP - srcblk.skipMSBP)) - { - // Use bypass decoding mode (only all bit-planes - // after the first 4 bit-planes). - - // Here starts a new raw segment - bin.setByteArray(null, -1, srcblk.tsLengths[++tsidx]); - isterm = (options & CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_TERM_PASS) != 0; - error = rawSigProgPass(cblk, bin, curbp, state, isterm); - npasses--; - if (npasses <= 0 || (error && doer)) - break; - - if ((options & CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_TERM_PASS) != 0) - { - // Start a new raw segment - bin.setByteArray(null, -1, srcblk.tsLengths[++tsidx]); - } - isterm = (options & CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_TERM_PASS) != 0 || ((options & CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_BYPASS) != 0 && (31 - CSJ2K.j2k.entropy.StdEntropyCoderOptions.NUM_NON_BYPASS_MS_BP - srcblk.skipMSBP > curbp)); - error = rawMagRefPass(cblk, bin, curbp, state, isterm); - } - else - { - // Do not use bypass decoding mode - if ((options & CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_TERM_PASS) != 0) - { - // Here starts a new MQ segment - mq.nextSegment(null, -1, srcblk.tsLengths[++tsidx]); - } - isterm = (options & CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_TERM_PASS) != 0; - error = sigProgPass(cblk, mq, curbp, state, zc_lut, isterm); - npasses--; - if (npasses <= 0 || (error && doer)) - break; - - if ((options & CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_TERM_PASS) != 0) - { - // Here starts a new MQ segment - mq.nextSegment(null, -1, srcblk.tsLengths[++tsidx]); - } - isterm = (options & CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_TERM_PASS) != 0 || ((options & CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_BYPASS) != 0 && (31 - CSJ2K.j2k.entropy.StdEntropyCoderOptions.NUM_NON_BYPASS_MS_BP - srcblk.skipMSBP > curbp)); - error = magRefPass(cblk, mq, curbp, state, isterm); - } - - npasses--; - if (npasses <= 0 || (error && doer)) - break; - - if ((options & CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_TERM_PASS) != 0 || ((options & CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_BYPASS) != 0 && (curbp < 31 - CSJ2K.j2k.entropy.StdEntropyCoderOptions.NUM_NON_BYPASS_MS_BP - srcblk.skipMSBP))) - { - // Here starts a new MQ segment - mq.nextSegment(null, -1, srcblk.tsLengths[++tsidx]); - } - isterm = (options & CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_TERM_PASS) != 0 || ((options & CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_BYPASS) != 0 && (31 - CSJ2K.j2k.entropy.StdEntropyCoderOptions.NUM_NON_BYPASS_MS_BP - srcblk.skipMSBP) >= curbp); - error = cleanuppass(cblk, mq, curbp, state, zc_lut, isterm); - npasses--; - if (error && doer) - break; - // Goto next bit-plane - curbp--; - } - } - - // If an error ocurred conceal it - if (error && doer) - { - if (verber) - { - FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.WARNING, "Error detected at bit-plane " + curbp + " in code-block (" + m + "," + n + "), sb_idx " + sb.sbandIdx + ", res. level " + sb.resLvl + ". Concealing..."); - } - conceal(cblk, curbp); - } - -#if DO_TIMING - time[c] += (System.DateTime.Now.Ticks - 621355968000000000) / 10000 - stime; -#endif - - // Return decoded block - return cblk; - } - - /// Returns the specified code-block in the current tile for the specified - /// component (as a reference or copy). - /// - ///

    The returned code-block may be progressive, which is indicated by - /// the 'progressive' variable of the returned 'DataBlk' object. If a - /// code-block is progressive it means that in a later request to this - /// method for the same code-block it is possible to retrieve data which is - /// a better approximation, since meanwhile more data to decode for the - /// code-block could have been received. If the code-block is not - /// progressive then later calls to this method for the same code-block - /// will return the exact same data values.

    - /// - ///

    The data returned by this method can be the data in the internal - /// buffer of this object, if any, and thus can not be modified by the - /// caller. The 'offset' and 'scanw' of the returned data can be - /// arbitrary. See the 'DataBlk' class.

    - /// - ///

    The 'ulx' and 'uly' members of the returned 'DataBlk' object contain - /// the coordinates of the top-left corner of the block, with respect to - /// the tile, not the subband.

    - /// - ///
    - /// The component for which to return the next code-block. - /// - /// - /// The vertical index of the code-block to return, in the - /// specified subband. - /// - /// - /// The horizontal index of the code-block to return, in the - /// specified subband. - /// - /// - /// The subband in which the code-block to return is. - /// - /// - /// If non-null this object will be used to return the new - /// code-block. If null a new one will be allocated and returned. If the - /// "data" array of the object is non-null it will be reused, if possible, - /// to return the data. - /// - /// - /// The next code-block in the current tile for component 'n', or - /// null if all code-blocks for the current tile have been returned. - /// - /// - /// - /// - /// - public override DataBlk getInternCodeBlock(int c, int m, int n, SubbandSyn sb, DataBlk cblk) - { - return getCodeBlock(c, m, n, sb, cblk); - } - - /// Performs the significance propagation pass on the specified data and - /// bit-plane. It decodes all insignificant samples which have, at least, - /// one of its immediate eight neighbors already significant, using the ZC - /// and SC primitives as needed. It toggles the "visited" state bit to 1 - /// for all those samples. - /// - ///

    This method also checks for segmentation markers if those are - /// present and returns true if an error is detected, or false - /// otherwise. If an error is detected it means that the bit stream - /// contains some erroneous bit that have led to the decoding of incorrect - /// data. This data affects the whole last decoded bit-plane - /// (i.e. 'bp'). If 'true' is returned the 'conceal' method should be - /// called and no more passes should be decoded for this code-block's bit - /// stream.

    - /// - ///
    - /// The code-block data to decode - /// - /// - /// The MQ-coder to use - /// - /// - /// The bit-plane to decode - /// - /// - /// The state information for the code-block - /// - /// - /// The ZC lookup table to use in ZC. - /// - /// - /// If this pass has been terminated. If the pass has been - /// terminated it can be used to check error resilience. - /// - /// - /// True if an error was detected in the bit stream, false - /// otherwise. - /// - /// - private bool sigProgPass(DataBlk cblk, MQDecoder mq, int bp, int[] state, int[] zc_lut, bool isterm) - { - int j, sj; // The state index for line and stripe - int k, sk; // The data index for line and stripe - int dscanw; // The data scan-width - int sscanw; // The state scan-width - int jstep; // Stripe to stripe step for 'sj' - int kstep; // Stripe to stripe step for 'sk' - int stopsk; // The loop limit on the variable sk - int csj; // Local copy (i.e. cached) of 'state[j]' - int setmask; // The mask to set current and lower bit-planes to 1/2 - // approximation - int sym; // The symbol to code - int ctxt; // The context to use - int[] data; // The data buffer - int s; // The stripe index - bool causal; // Flag to indicate if stripe-causal context - // formation is to be used - int nstripes; // The number of stripes in the code-block - int sheight; // Height of the current stripe - int off_ul, off_ur, off_dr, off_dl; // offsets - bool error; // The error condition - - // Initialize local variables - dscanw = cblk.scanw; - sscanw = cblk.w + 2; - jstep = sscanw * CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT / 2 - cblk.w; - kstep = dscanw * CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT - cblk.w; - setmask = (3 << bp) >> 1; - data = (int[])cblk.Data; - nstripes = (cblk.h + CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT - 1) / CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT; - causal = (options & CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_VERT_STR_CAUSAL) != 0; - - // Pre-calculate offsets in 'state' for diagonal neighbors - off_ul = -sscanw - 1; // up-left - off_ur = -sscanw + 1; // up-right - off_dr = sscanw + 1; // down-right - off_dl = sscanw - 1; // down-left - - // Decode stripe by stripe - sk = cblk.offset; - sj = sscanw + 1; - for (s = nstripes - 1; s >= 0; s--, sk += kstep, sj += jstep) - { - sheight = (s != 0) ? CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT : cblk.h - (nstripes - 1) * CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT; - stopsk = sk + cblk.w; - // Scan by set of 1 stripe column at a time - for (; sk < stopsk; sk++, sj++) - { - // Do half top of column - j = sj; - csj = state[j]; - // If any of the two samples is not significant and has a - // non-zero context (i.e. some neighbor is significant) we can - // not skip them - if ((((~csj) & (csj << 2)) & SIG_MASK_R1R2) != 0) - { - k = sk; - // Scan first row - if ((csj & (STATE_SIG_R1 | STATE_NZ_CTXT_R1)) == STATE_NZ_CTXT_R1) - { - // Use zero coding - if (mq.decodeSymbol(zc_lut[csj & ZC_MASK]) != 0) - { - // Became significant - // Use sign coding - ctxt = SC_LUT[(SupportClass.URShift(csj, SC_SHIFT_R1)) & SC_MASK]; - sym = mq.decodeSymbol(ctxt & SC_LUT_MASK) ^ (SupportClass.URShift(ctxt, SC_SPRED_SHIFT)); - // Update data - data[k] = (sym << 31) | setmask; - // Update state information (significant bit, - // visited bit, neighbor significant bit of - // neighbors, non zero context of neighbors, sign - // of neighbors) - if (!causal) - { - // If in causal mode do not change contexts of - // previous stripe. - state[j + off_ul] |= STATE_NZ_CTXT_R2 | STATE_D_DR_R2; - state[j + off_ur] |= STATE_NZ_CTXT_R2 | STATE_D_DL_R2; - } - // Update sign state information of neighbors - if (sym != 0) - { - csj |= STATE_SIG_R1 | STATE_VISITED_R1 | STATE_NZ_CTXT_R2 | STATE_V_U_R2 | STATE_V_U_SIGN_R2; - if (!causal) - { - // If in causal mode do not change - // contexts of previous stripe. - state[j - sscanw] |= STATE_NZ_CTXT_R2 | STATE_V_D_R2 | STATE_V_D_SIGN_R2; - } - state[j + 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_H_L_R1 | STATE_H_L_SIGN_R1 | STATE_D_UL_R2; - state[j - 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_H_R_R1 | STATE_H_R_SIGN_R1 | STATE_D_UR_R2; - } - else - { - csj |= STATE_SIG_R1 | STATE_VISITED_R1 | STATE_NZ_CTXT_R2 | STATE_V_U_R2; - if (!causal) - { - // If in causal mode do not change - // contexts of previous stripe. - state[j - sscanw] |= STATE_NZ_CTXT_R2 | STATE_V_D_R2; - } - state[j + 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_H_L_R1 | STATE_D_UL_R2; - state[j - 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_H_R_R1 | STATE_D_UR_R2; - } - } - else - { - csj |= STATE_VISITED_R1; - } - } - if (sheight < 2) - { - state[j] = csj; - continue; - } - // Scan second row - if ((csj & (STATE_SIG_R2 | STATE_NZ_CTXT_R2)) == STATE_NZ_CTXT_R2) - { - k += dscanw; - // Use zero coding - if (mq.decodeSymbol(zc_lut[(SupportClass.URShift(csj, STATE_SEP)) & ZC_MASK]) != 0) - { - // Became significant - // Use sign coding - ctxt = SC_LUT[(SupportClass.URShift(csj, SC_SHIFT_R2)) & SC_MASK]; - sym = mq.decodeSymbol(ctxt & SC_LUT_MASK) ^ (SupportClass.URShift(ctxt, SC_SPRED_SHIFT)); - // Update data - data[k] = (sym << 31) | setmask; - // Update state information (significant bit, - // visited bit, neighbor significant bit of - // neighbors, non zero context of neighbors, sign - // of neighbors) - state[j + off_dl] |= STATE_NZ_CTXT_R1 | STATE_D_UR_R1; - state[j + off_dr] |= STATE_NZ_CTXT_R1 | STATE_D_UL_R1; - // Update sign state information of neighbors - if (sym != 0) - { - csj |= STATE_SIG_R2 | STATE_VISITED_R2 | STATE_NZ_CTXT_R1 | STATE_V_D_R1 | STATE_V_D_SIGN_R1; - state[j + sscanw] |= STATE_NZ_CTXT_R1 | STATE_V_U_R1 | STATE_V_U_SIGN_R1; - state[j + 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_D_DL_R1 | STATE_H_L_R2 | STATE_H_L_SIGN_R2; - state[j - 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_D_DR_R1 | STATE_H_R_R2 | STATE_H_R_SIGN_R2; - } - else - { - csj |= STATE_SIG_R2 | STATE_VISITED_R2 | STATE_NZ_CTXT_R1 | STATE_V_D_R1; - state[j + sscanw] |= STATE_NZ_CTXT_R1 | STATE_V_U_R1; - state[j + 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_D_DL_R1 | STATE_H_L_R2; - state[j - 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_D_DR_R1 | STATE_H_R_R2; - } - } - else - { - csj |= STATE_VISITED_R2; - } - } - state[j] = csj; - } - // Do half bottom of column - if (sheight < 3) - continue; - j += sscanw; - csj = state[j]; - // If any of the two samples is not significant and has a - // non-zero context (i.e. some neighbor is significant) we can - // not skip them - if ((((~csj) & (csj << 2)) & SIG_MASK_R1R2) != 0) - { - k = sk + (dscanw << 1); - // Scan first row - if ((csj & (STATE_SIG_R1 | STATE_NZ_CTXT_R1)) == STATE_NZ_CTXT_R1) - { - // Use zero coding - if (mq.decodeSymbol(zc_lut[csj & ZC_MASK]) != 0) - { - // Became significant - // Use sign coding - ctxt = SC_LUT[(SupportClass.URShift(csj, SC_SHIFT_R1)) & SC_MASK]; - sym = mq.decodeSymbol(ctxt & SC_LUT_MASK) ^ (SupportClass.URShift(ctxt, SC_SPRED_SHIFT)); - // Update data - data[k] = (sym << 31) | setmask; - // Update state information (significant bit, - // visited bit, neighbor significant bit of - // neighbors, non zero context of neighbors, sign - // of neighbors) - state[j + off_ul] |= STATE_NZ_CTXT_R2 | STATE_D_DR_R2; - state[j + off_ur] |= STATE_NZ_CTXT_R2 | STATE_D_DL_R2; - // Update sign state information of neighbors - if (sym != 0) - { - csj |= STATE_SIG_R1 | STATE_VISITED_R1 | STATE_NZ_CTXT_R2 | STATE_V_U_R2 | STATE_V_U_SIGN_R2; - state[j - sscanw] |= STATE_NZ_CTXT_R2 | STATE_V_D_R2 | STATE_V_D_SIGN_R2; - state[j + 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_H_L_R1 | STATE_H_L_SIGN_R1 | STATE_D_UL_R2; - state[j - 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_H_R_R1 | STATE_H_R_SIGN_R1 | STATE_D_UR_R2; - } - else - { - csj |= STATE_SIG_R1 | STATE_VISITED_R1 | STATE_NZ_CTXT_R2 | STATE_V_U_R2; - state[j - sscanw] |= STATE_NZ_CTXT_R2 | STATE_V_D_R2; - state[j + 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_H_L_R1 | STATE_D_UL_R2; - state[j - 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_H_R_R1 | STATE_D_UR_R2; - } - } - else - { - csj |= STATE_VISITED_R1; - } - } - if (sheight < 4) - { - state[j] = csj; - continue; - } - // Scan second row - if ((csj & (STATE_SIG_R2 | STATE_NZ_CTXT_R2)) == STATE_NZ_CTXT_R2) - { - k += dscanw; - // Use zero coding - if (mq.decodeSymbol(zc_lut[(SupportClass.URShift(csj, STATE_SEP)) & ZC_MASK]) != 0) - { - // Became significant - // Use sign coding - ctxt = SC_LUT[(SupportClass.URShift(csj, SC_SHIFT_R2)) & SC_MASK]; - sym = mq.decodeSymbol(ctxt & SC_LUT_MASK) ^ (SupportClass.URShift(ctxt, SC_SPRED_SHIFT)); - // Update data - data[k] = (sym << 31) | setmask; - // Update state information (significant bit, - // visited bit, neighbor significant bit of - // neighbors, non zero context of neighbors, sign - // of neighbors) - state[j + off_dl] |= STATE_NZ_CTXT_R1 | STATE_D_UR_R1; - state[j + off_dr] |= STATE_NZ_CTXT_R1 | STATE_D_UL_R1; - // Update sign state information of neighbors - if (sym != 0) - { - csj |= STATE_SIG_R2 | STATE_VISITED_R2 | STATE_NZ_CTXT_R1 | STATE_V_D_R1 | STATE_V_D_SIGN_R1; - state[j + sscanw] |= STATE_NZ_CTXT_R1 | STATE_V_U_R1 | STATE_V_U_SIGN_R1; - state[j + 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_D_DL_R1 | STATE_H_L_R2 | STATE_H_L_SIGN_R2; - state[j - 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_D_DR_R1 | STATE_H_R_R2 | STATE_H_R_SIGN_R2; - } - else - { - csj |= STATE_SIG_R2 | STATE_VISITED_R2 | STATE_NZ_CTXT_R1 | STATE_V_D_R1; - state[j + sscanw] |= STATE_NZ_CTXT_R1 | STATE_V_U_R1; - state[j + 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_D_DL_R1 | STATE_H_L_R2; - state[j - 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_D_DR_R1 | STATE_H_R_R2; - } - } - else - { - csj |= STATE_VISITED_R2; - } - } - state[j] = csj; - } - } - } - - error = false; - - // Check the error resilience termination - if (isterm && (options & CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_PRED_TERM) != 0) - { - error = mq.checkPredTerm(); - } - - // Reset the MQ context states if we need to - if ((options & CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_RESET_MQ) != 0) - { - mq.resetCtxts(); - } - - // Return error condition - return error; - } - - /// Performs the significance propagation pass on the specified data and - /// bit-plane. It decodes all insignificant samples which have, at least, - /// one of its immediate eight neighbors already significant, using the ZC - /// and SC primitives as needed. It toggles the "visited" state bit to 1 - /// for all those samples. - /// - ///

    This method bypasses the arithmetic coder and reads "raw" symbols - /// from the bit stream.

    - /// - ///

    This method also checks for segmentation markers if those are - /// present and returns true if an error is detected, or false - /// otherwise. If an error is detected it measn that the bit stream contains - /// some erroneous bit that have led to the decoding of incorrect - /// data. This data affects the whole last decoded bit-plane (i.e. 'bp'). If - /// 'true' is returned the 'conceal' method should be called and no more - /// passes should be decoded for this code-block's bit stream.

    - /// - ///
    - /// The code-block data to decode - /// - /// - /// The raw bit based input - /// - /// - /// The bit-plane to decode - /// - /// - /// The state information for the code-block - /// - /// - /// If this pass has been terminated. If the pass has been - /// terminated it can be used to check error resilience. - /// - /// - /// True if an error was detected in the bit stream, false - /// otherwise. - /// - /// - private bool rawSigProgPass(DataBlk cblk, ByteToBitInput bin, int bp, int[] state, bool isterm) - { - int j, sj; // The state index for line and stripe - int k, sk; // The data index for line and stripe - int dscanw; // The data scan-width - int sscanw; // The state scan-width - int jstep; // Stripe to stripe step for 'sj' - int kstep; // Stripe to stripe step for 'sk' - int stopsk; // The loop limit on the variable sk - int csj; // Local copy (i.e. cached) of 'state[j]' - int setmask; // The mask to set current and lower bit-planes to 1/2 - // approximation - int sym; // The symbol to code - int[] data; // The data buffer - int s; // The stripe index - bool causal; // Flag to indicate if stripe-causal context - // formation is to be used - int nstripes; // The number of stripes in the code-block - int sheight; // Height of the current stripe - int off_ul, off_ur, off_dr, off_dl; // offsets - bool error; // The error condition - - // Initialize local variables - dscanw = cblk.scanw; - sscanw = cblk.w + 2; - jstep = sscanw * CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT / 2 - cblk.w; - kstep = dscanw * CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT - cblk.w; - setmask = (3 << bp) >> 1; - data = (int[])cblk.Data; - nstripes = (cblk.h + CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT - 1) / CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT; - causal = (options & CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_VERT_STR_CAUSAL) != 0; - - // Pre-calculate offsets in 'state' for diagonal neighbors - off_ul = -sscanw - 1; // up-left - off_ur = -sscanw + 1; // up-right - off_dr = sscanw + 1; // down-right - off_dl = sscanw - 1; // down-left - - // Decode stripe by stripe - sk = cblk.offset; - sj = sscanw + 1; - for (s = nstripes - 1; s >= 0; s--, sk += kstep, sj += jstep) - { - sheight = (s != 0) ? CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT : cblk.h - (nstripes - 1) * CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT; - stopsk = sk + cblk.w; - // Scan by set of 1 stripe column at a time - for (; sk < stopsk; sk++, sj++) - { - // Do half top of column - j = sj; - csj = state[j]; - // If any of the two samples is not significant and has a - // non-zero context (i.e. some neighbor is significant) we can - // not skip them - if ((((~csj) & (csj << 2)) & SIG_MASK_R1R2) != 0) - { - k = sk; - // Scan first row - if ((csj & (STATE_SIG_R1 | STATE_NZ_CTXT_R1)) == STATE_NZ_CTXT_R1) - { - // Use zero coding - if (bin.readBit() != 0) - { - // Became significant - // Use sign coding - sym = bin.readBit(); - // Update data - data[k] = (sym << 31) | setmask; - // Update state information (significant bit, - // visited bit, neighbor significant bit of - // neighbors, non zero context of neighbors, sign - // of neighbors) - if (!causal) - { - // If in causal mode do not change contexts of - // previous stripe. - state[j + off_ul] |= STATE_NZ_CTXT_R2 | STATE_D_DR_R2; - state[j + off_ur] |= STATE_NZ_CTXT_R2 | STATE_D_DL_R2; - } - // Update sign state information of neighbors - if (sym != 0) - { - csj |= STATE_SIG_R1 | STATE_VISITED_R1 | STATE_NZ_CTXT_R2 | STATE_V_U_R2 | STATE_V_U_SIGN_R2; - if (!causal) - { - // If in causal mode do not change - // contexts of previous stripe. - state[j - sscanw] |= STATE_NZ_CTXT_R2 | STATE_V_D_R2 | STATE_V_D_SIGN_R2; - } - state[j + 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_H_L_R1 | STATE_H_L_SIGN_R1 | STATE_D_UL_R2; - state[j - 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_H_R_R1 | STATE_H_R_SIGN_R1 | STATE_D_UR_R2; - } - else - { - csj |= STATE_SIG_R1 | STATE_VISITED_R1 | STATE_NZ_CTXT_R2 | STATE_V_U_R2; - if (!causal) - { - // If in causal mode do not change - // contexts of previous stripe. - state[j - sscanw] |= STATE_NZ_CTXT_R2 | STATE_V_D_R2; - } - state[j + 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_H_L_R1 | STATE_D_UL_R2; - state[j - 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_H_R_R1 | STATE_D_UR_R2; - } - } - else - { - csj |= STATE_VISITED_R1; - } - } - if (sheight < 2) - { - state[j] = csj; - continue; - } - if ((csj & (STATE_SIG_R2 | STATE_NZ_CTXT_R2)) == STATE_NZ_CTXT_R2) - { - k += dscanw; - // Use zero coding - if (bin.readBit() != 0) - { - // Became significant - // Use sign coding - sym = bin.readBit(); - // Update data - data[k] = (sym << 31) | setmask; - // Update state information (significant bit, - // visited bit, neighbor significant bit of - // neighbors, non zero context of neighbors, sign - // of neighbors) - state[j + off_dl] |= STATE_NZ_CTXT_R1 | STATE_D_UR_R1; - state[j + off_dr] |= STATE_NZ_CTXT_R1 | STATE_D_UL_R1; - // Update sign state information of neighbors - if (sym != 0) - { - csj |= STATE_SIG_R2 | STATE_VISITED_R2 | STATE_NZ_CTXT_R1 | STATE_V_D_R1 | STATE_V_D_SIGN_R1; - state[j + sscanw] |= STATE_NZ_CTXT_R1 | STATE_V_U_R1 | STATE_V_U_SIGN_R1; - state[j + 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_D_DL_R1 | STATE_H_L_R2 | STATE_H_L_SIGN_R2; - state[j - 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_D_DR_R1 | STATE_H_R_R2 | STATE_H_R_SIGN_R2; - } - else - { - csj |= STATE_SIG_R2 | STATE_VISITED_R2 | STATE_NZ_CTXT_R1 | STATE_V_D_R1; - state[j + sscanw] |= STATE_NZ_CTXT_R1 | STATE_V_U_R1; - state[j + 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_D_DL_R1 | STATE_H_L_R2; - state[j - 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_D_DR_R1 | STATE_H_R_R2; - } - } - else - { - csj |= STATE_VISITED_R2; - } - } - state[j] = csj; - } - // Do half bottom of column - if (sheight < 3) - continue; - j += sscanw; - csj = state[j]; - // If any of the two samples is not significant and has a - // non-zero context (i.e. some neighbor is significant) we can - // not skip them - if ((((~csj) & (csj << 2)) & SIG_MASK_R1R2) != 0) - { - k = sk + (dscanw << 1); - // Scan first row - if ((csj & (STATE_SIG_R1 | STATE_NZ_CTXT_R1)) == STATE_NZ_CTXT_R1) - { - // Use zero coding - if (bin.readBit() != 0) - { - // Became significant - // Use sign coding - sym = bin.readBit(); - // Update data - data[k] = (sym << 31) | setmask; - // Update state information (significant bit, - // visited bit, neighbor significant bit of - // neighbors, non zero context of neighbors, sign - // of neighbors) - state[j + off_ul] |= STATE_NZ_CTXT_R2 | STATE_D_DR_R2; - state[j + off_ur] |= STATE_NZ_CTXT_R2 | STATE_D_DL_R2; - // Update sign state information of neighbors - if (sym != 0) - { - csj |= STATE_SIG_R1 | STATE_VISITED_R1 | STATE_NZ_CTXT_R2 | STATE_V_U_R2 | STATE_V_U_SIGN_R2; - state[j - sscanw] |= STATE_NZ_CTXT_R2 | STATE_V_D_R2 | STATE_V_D_SIGN_R2; - state[j + 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_H_L_R1 | STATE_H_L_SIGN_R1 | STATE_D_UL_R2; - state[j - 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_H_R_R1 | STATE_H_R_SIGN_R1 | STATE_D_UR_R2; - } - else - { - csj |= STATE_SIG_R1 | STATE_VISITED_R1 | STATE_NZ_CTXT_R2 | STATE_V_U_R2; - state[j - sscanw] |= STATE_NZ_CTXT_R2 | STATE_V_D_R2; - state[j + 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_H_L_R1 | STATE_D_UL_R2; - state[j - 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_H_R_R1 | STATE_D_UR_R2; - } - } - else - { - csj |= STATE_VISITED_R1; - } - } - if (sheight < 4) - { - state[j] = csj; - continue; - } - // Scan second row - if ((csj & (STATE_SIG_R2 | STATE_NZ_CTXT_R2)) == STATE_NZ_CTXT_R2) - { - k += dscanw; - // Use zero coding - if (bin.readBit() != 0) - { - // Became significant - // Use sign coding - sym = bin.readBit(); - // Update data - data[k] = (sym << 31) | setmask; - // Update state information (significant bit, - // visited bit, neighbor significant bit of - // neighbors, non zero context of neighbors, sign - // of neighbors) - state[j + off_dl] |= STATE_NZ_CTXT_R1 | STATE_D_UR_R1; - state[j + off_dr] |= STATE_NZ_CTXT_R1 | STATE_D_UL_R1; - // Update sign state information of neighbors - if (sym != 0) - { - csj |= STATE_SIG_R2 | STATE_VISITED_R2 | STATE_NZ_CTXT_R1 | STATE_V_D_R1 | STATE_V_D_SIGN_R1; - state[j + sscanw] |= STATE_NZ_CTXT_R1 | STATE_V_U_R1 | STATE_V_U_SIGN_R1; - state[j + 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_D_DL_R1 | STATE_H_L_R2 | STATE_H_L_SIGN_R2; - state[j - 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_D_DR_R1 | STATE_H_R_R2 | STATE_H_R_SIGN_R2; - } - else - { - csj |= STATE_SIG_R2 | STATE_VISITED_R2 | STATE_NZ_CTXT_R1 | STATE_V_D_R1; - state[j + sscanw] |= STATE_NZ_CTXT_R1 | STATE_V_U_R1; - state[j + 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_D_DL_R1 | STATE_H_L_R2; - state[j - 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_D_DR_R1 | STATE_H_R_R2; - } - } - else - { - csj |= STATE_VISITED_R2; - } - } - state[j] = csj; - } - } - } - - error = false; - - // Check the byte padding if the pass is terminated and if the error - // resilience predictable termination is signaled in COx marker. - if (isterm && (options & CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_PRED_TERM) != 0) - { - error = bin.checkBytePadding(); - } - - // Return error condition - return error; - } - - /// Performs the magnitude refinement pass on the specified data and - /// bit-plane. It decodes the samples which are significant and which do not - /// have the "visited" state bit turned on, using the MR primitive. The - /// "visited" state bit is not mofified for any samples. - /// - ///

    This method also checks for segmentation markers if those are - /// present and returns true if an error is detected, or false - /// otherwise. If an error is detected it means that the bit stream contains - /// some erroneous bit that have led to the decoding of incorrect - /// data. This data affects the whole last decoded bit-plane (i.e. 'bp'). If - /// 'true' is returned the 'conceal' method should be called and no more - /// passes should be decoded for this code-block's bit stream. - /// - ///

    - /// The code-block data to decode - /// - /// - /// The MQ-decoder to use - /// - /// - /// The bit-plane to decode - /// - /// - /// The state information for the code-block - /// - /// - /// If this pass has been terminated. If the pass has been - /// terminated it can be used to check error resilience. - /// - /// - /// True if an error was detected in the bit stream, false - /// otherwise. - /// - /// - private bool magRefPass(DataBlk cblk, MQDecoder mq, int bp, int[] state, bool isterm) - { - int j, sj; // The state index for line and stripe - int k, sk; // The data index for line and stripe - int dscanw; // The data scan-width - int sscanw; // The state scan-width - int jstep; // Stripe to stripe step for 'sj' - int kstep; // Stripe to stripe step for 'sk' - int stopsk; // The loop limit on the variable sk - int csj; // Local copy (i.e. cached) of 'state[j]' - int setmask; // The mask to set lower bit-planes to 1/2 approximation - int resetmask; // The mask to reset approximation bit-planes - int sym; // The symbol to decode - int[] data; // The data buffer - int s; // The stripe index - int nstripes; // The number of stripes in the code-block - int sheight; // Height of the current stripe - bool error; // The error condition - - // Initialize local variables - dscanw = cblk.scanw; - sscanw = cblk.w + 2; - jstep = sscanw * CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT / 2 - cblk.w; - kstep = dscanw * CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT - cblk.w; - setmask = (1 << bp) >> 1; - resetmask = (-1) << (bp + 1); - data = (int[])cblk.Data; - nstripes = (cblk.h + CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT - 1) / CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT; - - // Decode stripe by stripe - sk = cblk.offset; - sj = sscanw + 1; - for (s = nstripes - 1; s >= 0; s--, sk += kstep, sj += jstep) - { - sheight = (s != 0) ? CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT : cblk.h - (nstripes - 1) * CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT; - stopsk = sk + cblk.w; - // Scan by set of 1 stripe column at a time - for (; sk < stopsk; sk++, sj++) - { - // Do half top of column - j = sj; - csj = state[j]; - // If any of the two samples is significant and not yet - // visited in the current bit-plane we can not skip them - if ((((SupportClass.URShift(csj, 1)) & (~csj)) & VSTD_MASK_R1R2) != 0) - { - k = sk; - // Scan first row - if ((csj & (STATE_SIG_R1 | STATE_VISITED_R1)) == STATE_SIG_R1) - { - // Use MR primitive - sym = mq.decodeSymbol(MR_LUT[csj & MR_MASK]); - // Update the data - data[k] &= resetmask; - data[k] |= (sym << bp) | setmask; - // Update the STATE_PREV_MR bit - csj |= STATE_PREV_MR_R1; - } - if (sheight < 2) - { - state[j] = csj; - continue; - } - // Scan second row - if ((csj & (STATE_SIG_R2 | STATE_VISITED_R2)) == STATE_SIG_R2) - { - k += dscanw; - // Use MR primitive - sym = mq.decodeSymbol(MR_LUT[(SupportClass.URShift(csj, STATE_SEP)) & MR_MASK]); - // Update the data - data[k] &= resetmask; - data[k] |= (sym << bp) | setmask; - // Update the STATE_PREV_MR bit - csj |= STATE_PREV_MR_R2; - } - state[j] = csj; - } - // Do half bottom of column - if (sheight < 3) - continue; - j += sscanw; - csj = state[j]; - // If any of the two samples is significant and not yet - // visited in the current bit-plane we can not skip them - if ((((SupportClass.URShift(csj, 1)) & (~csj)) & VSTD_MASK_R1R2) != 0) - { - k = sk + (dscanw << 1); - // Scan first row - if ((csj & (STATE_SIG_R1 | STATE_VISITED_R1)) == STATE_SIG_R1) - { - // Use MR primitive - sym = mq.decodeSymbol(MR_LUT[csj & MR_MASK]); - // Update the data - data[k] &= resetmask; - data[k] |= (sym << bp) | setmask; - // Update the STATE_PREV_MR bit - csj |= STATE_PREV_MR_R1; - } - if (sheight < 4) - { - state[j] = csj; - continue; - } - // Scan second row - if ((state[j] & (STATE_SIG_R2 | STATE_VISITED_R2)) == STATE_SIG_R2) - { - k += dscanw; - // Use MR primitive - sym = mq.decodeSymbol(MR_LUT[(SupportClass.URShift(csj, STATE_SEP)) & MR_MASK]); - // Update the data - data[k] &= resetmask; - data[k] |= (sym << bp) | setmask; - // Update the STATE_PREV_MR bit - csj |= STATE_PREV_MR_R2; - } - state[j] = csj; - } - } - } - - error = false; - - // Check the error resilient termination - if (isterm && (options & CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_PRED_TERM) != 0) - { - error = mq.checkPredTerm(); - } - - // Reset the MQ context states if we need to - if ((options & CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_RESET_MQ) != 0) - { - mq.resetCtxts(); - } - - // Return error condition - return error; - } - - /// Performs the magnitude refinement pass on the specified data and - /// bit-plane. It decodes the samples which are significant and which do - /// not have the "visited" state bit turned on, using the MR primitive. The - /// "visited" state bit is not mofified for any samples. - /// - ///

    This method bypasses the arithmetic coder and reads "raw" symbols - /// from the bit stream. - /// - ///

    This method also checks for segmentation markers if those are - /// present and returns true if an error is detected, or false - /// otherwise. If an error is detected it measn that the bit stream - /// contains some erroneous bit that have led to the decoding of incorrect - /// data. This data affects the whole last decoded bit-plane - /// (i.e. 'bp'). If 'true' is returned the 'conceal' method should be - /// called and no more passes should be decoded for this code-block's bit - /// stream. - /// - ///

    - /// The code-block data to decode - /// - /// - /// The raw bit based input - /// - /// - /// The bit-plane to decode - /// - /// - /// The state information for the code-block - /// - /// - /// If this pass has been terminated. If the pass has been - /// terminated it can be used to check error resilience. - /// - /// - /// True if an error was detected in the bit stream, false - /// otherwise. - /// - /// - private bool rawMagRefPass(DataBlk cblk, ByteToBitInput bin, int bp, int[] state, bool isterm) - { - int j, sj; // The state index for line and stripe - int k, sk; // The data index for line and stripe - int dscanw; // The data scan-width - int sscanw; // The state scan-width - int jstep; // Stripe to stripe step for 'sj' - int kstep; // Stripe to stripe step for 'sk' - int stopsk; // The loop limit on the variable sk - int csj; // Local copy (i.e. cached) of 'state[j]' - int setmask; // The mask to set lower bit-planes to 1/2 approximation - int resetmask; // The mask to reset approximation bit-planes - int sym; // The symbol to decode - int[] data; // The data buffer - int s; // The stripe index - int nstripes; // The number of stripes in the code-block - int sheight; // Height of the current stripe - bool error; // The error condition - - // Initialize local variables - dscanw = cblk.scanw; - sscanw = cblk.w + 2; - jstep = sscanw * CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT / 2 - cblk.w; - kstep = dscanw * CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT - cblk.w; - setmask = (1 << bp) >> 1; - resetmask = (-1) << (bp + 1); - data = (int[])cblk.Data; - nstripes = (cblk.h + CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT - 1) / CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT; - - // Decode stripe by stripe - sk = cblk.offset; - sj = sscanw + 1; - for (s = nstripes - 1; s >= 0; s--, sk += kstep, sj += jstep) - { - sheight = (s != 0) ? CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT : cblk.h - (nstripes - 1) * CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT; - stopsk = sk + cblk.w; - // Scan by set of 1 stripe column at a time - for (; sk < stopsk; sk++, sj++) - { - // Do half top of column - j = sj; - csj = state[j]; - // If any of the two samples is significant and not yet - // visited in the current bit-plane we can not skip them - if ((((SupportClass.URShift(csj, 1)) & (~csj)) & VSTD_MASK_R1R2) != 0) - { - k = sk; - // Scan first row - if ((csj & (STATE_SIG_R1 | STATE_VISITED_R1)) == STATE_SIG_R1) - { - // Read raw bit (no MR primative) - sym = bin.readBit(); - // Update the data - data[k] &= resetmask; - data[k] |= (sym << bp) | setmask; - // No need to set STATE_PREV_MR_R1 since all magnitude - // refinement passes to follow are "raw" - } - if (sheight < 2) - continue; - // Scan second row - if ((csj & (STATE_SIG_R2 | STATE_VISITED_R2)) == STATE_SIG_R2) - { - k += dscanw; - // Read raw bit (no MR primative) - sym = bin.readBit(); - // Update the data - data[k] &= resetmask; - data[k] |= (sym << bp) | setmask; - // No need to set STATE_PREV_MR_R1 since all magnitude - // refinement passes to follow are "raw" - } - } - // Do half bottom of column - if (sheight < 3) - continue; - j += sscanw; - csj = state[j]; - // If any of the two samples is significant and not yet - // visited in the current bit-plane we can not skip them - if ((((SupportClass.URShift(csj, 1)) & (~csj)) & VSTD_MASK_R1R2) != 0) - { - k = sk + (dscanw << 1); - // Scan first row - if ((csj & (STATE_SIG_R1 | STATE_VISITED_R1)) == STATE_SIG_R1) - { - // Read raw bit (no MR primative) - sym = bin.readBit(); - // Update the data - data[k] &= resetmask; - data[k] |= (sym << bp) | setmask; - // No need to set STATE_PREV_MR_R1 since all magnitude - // refinement passes to follow are "raw" - } - if (sheight < 4) - continue; - // Scan second row - if ((state[j] & (STATE_SIG_R2 | STATE_VISITED_R2)) == STATE_SIG_R2) - { - k += dscanw; - // Read raw bit (no MR primative) - sym = bin.readBit(); - // Update the data - data[k] &= resetmask; - data[k] |= (sym << bp) | setmask; - // No need to set STATE_PREV_MR_R1 since all magnitude - // refinement passes to follow are "raw" - } - } - } - } - - error = false; - - // Check the byte padding if the pass is terminated and the - // predictable termination is signaled in COx marker. - if (isterm && (options & CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_PRED_TERM) != 0) - { - error = bin.checkBytePadding(); - } - - // Return error condition - return error; - } - - /// Performs the cleanup pass on the specified data and bit-plane. It - /// decodes all insignificant samples which have its "visited" state bit - /// off, using the ZC, SC, and RLC primitives. It toggles the "visited" - /// state bit to 0 (off) for all samples in the code-block. - /// - ///

    This method also checks for segmentation markers if those are - /// present and returns true if an error is detected, or false - /// otherwise. If an error is detected it measn that the bit stream - /// contains some erroneous bit that have led to the decoding of incorrect - /// data. This data affects the whole last decoded bit-plane - /// (i.e. 'bp'). If 'true' is returned the 'conceal' method should be - /// called and no more passes should be decoded for this code-block's bit - /// stream. - /// - ///

    - /// The code-block data to code - /// - /// - /// The MQ-coder to use - /// - /// - /// The bit-plane to decode - /// - /// - /// The state information for the code-block - /// - /// - /// The ZC lookup table to use in ZC. - /// - /// - /// If this pass has been terminated. If the pass has been - /// terminated it can be used to check error resilience. - /// - /// - /// True if an error was detected in the bit stream, false - /// otherwise. - /// - /// - private bool cleanuppass(DataBlk cblk, MQDecoder mq, int bp, int[] state, int[] zc_lut, bool isterm) - { - int j, sj; // The state index for line and stripe - int k, sk; // The data index for line and stripe - int dscanw; // The data scan-width - int sscanw; // The state scan-width - int jstep; // Stripe to stripe step for 'sj' - int kstep; // Stripe to stripe step for 'sk' - int stopsk; // The loop limit on the variable sk - int csj; // Local copy (i.e. cached) of 'state[j]' - int setmask; // The mask to set current and lower bit-planes to 1/2 - // approximation - int sym; // The decoded symbol - int rlclen; // Length of RLC - int ctxt; // The context to use - int[] data; // The data buffer - int s; // The stripe index - bool causal; // Flag to indicate if stripe-causal context - // formation is to be used - int nstripes; // The number of stripes in the code-block - int sheight; // Height of the current stripe - int off_ul, off_ur, off_dr, off_dl; // offsets - bool error; // The error condition - - // Initialize local variables - dscanw = cblk.scanw; - sscanw = cblk.w + 2; - jstep = sscanw * CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT / 2 - cblk.w; - kstep = dscanw * CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT - cblk.w; - setmask = (3 << bp) >> 1; - data = (int[])cblk.Data; - nstripes = (cblk.h + CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT - 1) / CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT; - causal = (options & CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_VERT_STR_CAUSAL) != 0; - - // Pre-calculate offsets in 'state' for diagonal neighbors - off_ul = -sscanw - 1; // up-left - off_ur = -sscanw + 1; // up-right - off_dr = sscanw + 1; // down-right - off_dl = sscanw - 1; // down-left - - // Decode stripe by stripe - sk = cblk.offset; - sj = sscanw + 1; - for (s = nstripes - 1; s >= 0; s--, sk += kstep, sj += jstep) - { - sheight = (s != 0) ? CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT : cblk.h - (nstripes - 1) * CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT; - stopsk = sk + cblk.w; - // Scan by set of 1 stripe column at a time - for (; sk < stopsk; sk++, sj++) - { - // Start column - j = sj; - csj = state[j]; - { - // Check for RLC: if all samples are not significant, not - // visited and do not have a non-zero context, and column - // is full height, we do RLC. - if (csj == 0 && state[j + sscanw] == 0 && sheight == CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT) - { - if (mq.decodeSymbol(RLC_CTXT) != 0) - { - // run-length is significant, decode length - rlclen = mq.decodeSymbol(UNIF_CTXT) << 1; - rlclen |= mq.decodeSymbol(UNIF_CTXT); - // Set 'k' and 'j' accordingly - k = sk + rlclen * dscanw; - if (rlclen > 1) - { - j += sscanw; - csj = state[j]; - } - } - else - { - // RLC is insignificant - // Goto next column - continue; - } - // We just decoded the length of a significant RLC - // and a sample became significant - // Use sign coding - if ((rlclen & 0x01) == 0) - { - // Sample that became significant is first row of - // its column half - ctxt = SC_LUT[(csj >> SC_SHIFT_R1) & SC_MASK]; - sym = mq.decodeSymbol(ctxt & SC_LUT_MASK) ^ (SupportClass.URShift(ctxt, SC_SPRED_SHIFT)); - // Update the data - data[k] = (sym << 31) | setmask; - // Update state information (significant bit, - // visited bit, neighbor significant bit of - // neighbors, non zero context of neighbors, sign - // of neighbors) - if (rlclen != 0 || !causal) - { - // If in causal mode do not change - // contexts of previous stripe. - state[j + off_ul] |= STATE_NZ_CTXT_R2 | STATE_D_DR_R2; - state[j + off_ur] |= STATE_NZ_CTXT_R2 | STATE_D_DL_R2; - } - // Update sign state information of neighbors - if (sym != 0) - { - csj |= STATE_SIG_R1 | STATE_VISITED_R1 | STATE_NZ_CTXT_R2 | STATE_V_U_R2 | STATE_V_U_SIGN_R2; - if (rlclen != 0 || !causal) - { - // If in causal mode do not change - // contexts of previous stripe. - state[j - sscanw] |= STATE_NZ_CTXT_R2 | STATE_V_D_R2 | STATE_V_D_SIGN_R2; - } - state[j + 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_H_L_R1 | STATE_H_L_SIGN_R1 | STATE_D_UL_R2; - state[j - 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_H_R_R1 | STATE_H_R_SIGN_R1 | STATE_D_UR_R2; - } - else - { - csj |= STATE_SIG_R1 | STATE_VISITED_R1 | STATE_NZ_CTXT_R2 | STATE_V_U_R2; - if (rlclen != 0 || !causal) - { - // If in causal mode do not change - // contexts of previous stripe. - state[j - sscanw] |= STATE_NZ_CTXT_R2 | STATE_V_D_R2; - } - state[j + 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_H_L_R1 | STATE_D_UL_R2; - state[j - 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_H_R_R1 | STATE_D_UR_R2; - } - // Changes to csj are saved later - if ((rlclen >> 1) != 0) - { - // Sample that became significant is in - // bottom half of column => jump to bottom - // half - //UPGRADE_NOTE: Labeled break statement was changed to a goto statement. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1012'" - goto top_half_brk; - } - // Otherwise sample that became significant is in - // top half of column => continue on top half - } - else - { - // Sample that became significant is second row of - // its column half - ctxt = SC_LUT[(csj >> SC_SHIFT_R2) & SC_MASK]; - sym = mq.decodeSymbol(ctxt & SC_LUT_MASK) ^ (SupportClass.URShift(ctxt, SC_SPRED_SHIFT)); - // Update the data - data[k] = (sym << 31) | setmask; - // Update state information (significant bit, - // neighbor significant bit of neighbors, non zero - // context of neighbors, sign of neighbors) - state[j + off_dl] |= STATE_NZ_CTXT_R1 | STATE_D_UR_R1; - state[j + off_dr] |= STATE_NZ_CTXT_R1 | STATE_D_UL_R1; - // Update sign state information of neighbors - if (sym != 0) - { - csj |= STATE_SIG_R2 | STATE_NZ_CTXT_R1 | STATE_V_D_R1 | STATE_V_D_SIGN_R1; - state[j + sscanw] |= STATE_NZ_CTXT_R1 | STATE_V_U_R1 | STATE_V_U_SIGN_R1; - state[j + 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_D_DL_R1 | STATE_H_L_R2 | STATE_H_L_SIGN_R2; - state[j - 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_D_DR_R1 | STATE_H_R_R2 | STATE_H_R_SIGN_R2; - } - else - { - csj |= STATE_SIG_R2 | STATE_NZ_CTXT_R1 | STATE_V_D_R1; - state[j + sscanw] |= STATE_NZ_CTXT_R1 | STATE_V_U_R1; - state[j + 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_D_DL_R1 | STATE_H_L_R2; - state[j - 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_D_DR_R1 | STATE_H_R_R2; - } - // Save changes to csj - state[j] = csj; - if ((rlclen >> 1) != 0) - { - // Sample that became significant is in bottom - // half of column => we're done with this - // column - continue; - } - // Otherwise sample that became significant is in - // top half of column => we're done with top - // column - j += sscanw; - csj = state[j]; - //UPGRADE_NOTE: Labeled break statement was changed to a goto statement. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1012'" - goto top_half_brk; - } - } - // Do half top of column - // If any of the two samples is not significant and has - // not been visited in the current bit-plane we can not - // skip them - if ((((csj >> 1) | csj) & VSTD_MASK_R1R2) != VSTD_MASK_R1R2) - { - k = sk; - // Scan first row - if ((csj & (STATE_SIG_R1 | STATE_VISITED_R1)) == 0) - { - // Use zero coding - if (mq.decodeSymbol(zc_lut[csj & ZC_MASK]) != 0) - { - // Became significant - // Use sign coding - ctxt = SC_LUT[(SupportClass.URShift(csj, SC_SHIFT_R1)) & SC_MASK]; - sym = mq.decodeSymbol(ctxt & SC_LUT_MASK) ^ (SupportClass.URShift(ctxt, SC_SPRED_SHIFT)); - // Update the data - data[k] = (sym << 31) | setmask; - // Update state information (significant bit, - // visited bit, neighbor significant bit of - // neighbors, non zero context of neighbors, - // sign of neighbors) - if (!causal) - { - // If in causal mode do not change - // contexts of previous stripe. - state[j + off_ul] |= STATE_NZ_CTXT_R2 | STATE_D_DR_R2; - state[j + off_ur] |= STATE_NZ_CTXT_R2 | STATE_D_DL_R2; - } - // Update sign state information of neighbors - if (sym != 0) - { - csj |= STATE_SIG_R1 | STATE_VISITED_R1 | STATE_NZ_CTXT_R2 | STATE_V_U_R2 | STATE_V_U_SIGN_R2; - if (!causal) - { - // If in causal mode do not change - // contexts of previous stripe. - state[j - sscanw] |= STATE_NZ_CTXT_R2 | STATE_V_D_R2 | STATE_V_D_SIGN_R2; - } - state[j + 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_H_L_R1 | STATE_H_L_SIGN_R1 | STATE_D_UL_R2; - state[j - 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_H_R_R1 | STATE_H_R_SIGN_R1 | STATE_D_UR_R2; - } - else - { - csj |= STATE_SIG_R1 | STATE_VISITED_R1 | STATE_NZ_CTXT_R2 | STATE_V_U_R2; - if (!causal) - { - // If in causal mode do not change - // contexts of previous stripe. - state[j - sscanw] |= STATE_NZ_CTXT_R2 | STATE_V_D_R2; - } - state[j + 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_H_L_R1 | STATE_D_UL_R2; - state[j - 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_H_R_R1 | STATE_D_UR_R2; - } - } - } - if (sheight < 2) - { - csj &= ~(STATE_VISITED_R1 | STATE_VISITED_R2); - state[j] = csj; - continue; - } - // Scan second row - if ((csj & (STATE_SIG_R2 | STATE_VISITED_R2)) == 0) - { - k += dscanw; - // Use zero coding - if (mq.decodeSymbol(zc_lut[(SupportClass.URShift(csj, STATE_SEP)) & ZC_MASK]) != 0) - { - // Became significant - // Use sign coding - ctxt = SC_LUT[(SupportClass.URShift(csj, SC_SHIFT_R2)) & SC_MASK]; - sym = mq.decodeSymbol(ctxt & SC_LUT_MASK) ^ (SupportClass.URShift(ctxt, SC_SPRED_SHIFT)); - // Update the data - data[k] = (sym << 31) | setmask; - // Update state information (significant bit, - // visited bit, neighbor significant bit of - // neighbors, non zero context of neighbors, - // sign of neighbors) - state[j + off_dl] |= STATE_NZ_CTXT_R1 | STATE_D_UR_R1; - state[j + off_dr] |= STATE_NZ_CTXT_R1 | STATE_D_UL_R1; - // Update sign state information of neighbors - if (sym != 0) - { - csj |= STATE_SIG_R2 | STATE_VISITED_R2 | STATE_NZ_CTXT_R1 | STATE_V_D_R1 | STATE_V_D_SIGN_R1; - state[j + sscanw] |= STATE_NZ_CTXT_R1 | STATE_V_U_R1 | STATE_V_U_SIGN_R1; - state[j + 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_D_DL_R1 | STATE_H_L_R2 | STATE_H_L_SIGN_R2; - state[j - 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_D_DR_R1 | STATE_H_R_R2 | STATE_H_R_SIGN_R2; - } - else - { - csj |= STATE_SIG_R2 | STATE_VISITED_R2 | STATE_NZ_CTXT_R1 | STATE_V_D_R1; - state[j + sscanw] |= STATE_NZ_CTXT_R1 | STATE_V_U_R1; - state[j + 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_D_DL_R1 | STATE_H_L_R2; - state[j - 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_D_DR_R1 | STATE_H_R_R2; - } - } - } - } - csj &= ~(STATE_VISITED_R1 | STATE_VISITED_R2); - state[j] = csj; - // Do half bottom of column - if (sheight < 3) - continue; - j += sscanw; - csj = state[j]; - } - //UPGRADE_NOTE: Label 'top_half_brk' was added. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1011'" - - top_half_brk:; - // end of 'top_half' block - // If any of the two samples is not significant and has - // not been visited in the current bit-plane we can not - // skip them - if ((((csj >> 1) | csj) & VSTD_MASK_R1R2) != VSTD_MASK_R1R2) - { - k = sk + (dscanw << 1); - // Scan first row - if ((csj & (STATE_SIG_R1 | STATE_VISITED_R1)) == 0) - { - // Use zero coding - if (mq.decodeSymbol(zc_lut[csj & ZC_MASK]) != 0) - { - // Became significant - // Use sign coding - ctxt = SC_LUT[(csj >> SC_SHIFT_R1) & SC_MASK]; - sym = mq.decodeSymbol(ctxt & SC_LUT_MASK) ^ (SupportClass.URShift(ctxt, SC_SPRED_SHIFT)); - // Update the data - data[k] = (sym << 31) | setmask; - // Update state information (significant bit, - // visited bit, neighbor significant bit of - // neighbors, non zero context of neighbors, - // sign of neighbors) - state[j + off_ul] |= STATE_NZ_CTXT_R2 | STATE_D_DR_R2; - state[j + off_ur] |= STATE_NZ_CTXT_R2 | STATE_D_DL_R2; - // Update sign state information of neighbors - if (sym != 0) - { - csj |= STATE_SIG_R1 | STATE_VISITED_R1 | STATE_NZ_CTXT_R2 | STATE_V_U_R2 | STATE_V_U_SIGN_R2; - state[j - sscanw] |= STATE_NZ_CTXT_R2 | STATE_V_D_R2 | STATE_V_D_SIGN_R2; - state[j + 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_H_L_R1 | STATE_H_L_SIGN_R1 | STATE_D_UL_R2; - state[j - 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_H_R_R1 | STATE_H_R_SIGN_R1 | STATE_D_UR_R2; - } - else - { - csj |= STATE_SIG_R1 | STATE_VISITED_R1 | STATE_NZ_CTXT_R2 | STATE_V_U_R2; - state[j - sscanw] |= STATE_NZ_CTXT_R2 | STATE_V_D_R2; - state[j + 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_H_L_R1 | STATE_D_UL_R2; - state[j - 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_H_R_R1 | STATE_D_UR_R2; - } - } - } - if (sheight < 4) - { - csj &= ~(STATE_VISITED_R1 | STATE_VISITED_R2); - state[j] = csj; - continue; - } - // Scan second row - if ((csj & (STATE_SIG_R2 | STATE_VISITED_R2)) == 0) - { - k += dscanw; - // Use zero coding - if (mq.decodeSymbol(zc_lut[(SupportClass.URShift(csj, STATE_SEP)) & ZC_MASK]) != 0) - { - // Became significant - // Use sign coding - ctxt = SC_LUT[(SupportClass.URShift(csj, SC_SHIFT_R2)) & SC_MASK]; - sym = mq.decodeSymbol(ctxt & SC_LUT_MASK) ^ (SupportClass.URShift(ctxt, SC_SPRED_SHIFT)); - // Update the data - data[k] = (sym << 31) | setmask; - // Update state information (significant bit, - // visited bit, neighbor significant bit of - // neighbors, non zero context of neighbors, - // sign of neighbors) - state[j + off_dl] |= STATE_NZ_CTXT_R1 | STATE_D_UR_R1; - state[j + off_dr] |= STATE_NZ_CTXT_R1 | STATE_D_UL_R1; - // Update sign state information of neighbors - if (sym != 0) - { - csj |= STATE_SIG_R2 | STATE_VISITED_R2 | STATE_NZ_CTXT_R1 | STATE_V_D_R1 | STATE_V_D_SIGN_R1; - state[j + sscanw] |= STATE_NZ_CTXT_R1 | STATE_V_U_R1 | STATE_V_U_SIGN_R1; - state[j + 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_D_DL_R1 | STATE_H_L_R2 | STATE_H_L_SIGN_R2; - state[j - 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_D_DR_R1 | STATE_H_R_R2 | STATE_H_R_SIGN_R2; - } - else - { - csj |= STATE_SIG_R2 | STATE_VISITED_R2 | STATE_NZ_CTXT_R1 | STATE_V_D_R1; - state[j + sscanw] |= STATE_NZ_CTXT_R1 | STATE_V_U_R1; - state[j + 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_D_DL_R1 | STATE_H_L_R2; - state[j - 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_D_DR_R1 | STATE_H_R_R2; - } - } - } - } - csj &= ~(STATE_VISITED_R1 | STATE_VISITED_R2); - state[j] = csj; - } - } - - // Decode segment symbol if we need to - if ((options & CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_SEG_SYMBOLS) != 0) - { - sym = mq.decodeSymbol(UNIF_CTXT) << 3; - sym |= mq.decodeSymbol(UNIF_CTXT) << 2; - sym |= mq.decodeSymbol(UNIF_CTXT) << 1; - sym |= mq.decodeSymbol(UNIF_CTXT); - // Set error condition accordingly - error = sym != SEG_SYMBOL; - } - else - { - // We can not detect any errors - error = false; - } - - // Check the error resilience termination - if (isterm && (options & CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_PRED_TERM) != 0) - { - error = mq.checkPredTerm(); - } - - // Reset the MQ context states if we need to - if ((options & CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_RESET_MQ) != 0) - { - mq.resetCtxts(); - } - - // Return error condition - return error; - } - - /// Conceals decoding errors detected in the last bit-plane. The - /// concealement resets the state of the decoded data to what it was before - /// the decoding of bit-plane 'bp' started. No more data should be decoded - /// after this method is called for this code-block's data to which it is - /// applied. - /// - /// - /// The code-block's data - /// - /// - /// The last decoded bit-plane (which contains errors). - /// - /// - private void conceal(DataBlk cblk, int bp) - { - int l; // line index - int k; // array index - int kmax; // 'k' limit - int dk; // Value of data[k] - int[] data; // the data array - int setmask; // Bitmask to set approximation to 1/2 of - // known interval on significant data - int resetmask; // Bitmask to erase all the data from - // bit-plane 'bp' - - // Initialize masks - setmask = 1 << bp; - resetmask = (-1) << (bp); - - // Get the data array - data = (int[])cblk.Data; - - // Visit each sample, apply the reset mask to it and add an - // approximation if significant. - for (l = cblk.h - 1, k = cblk.offset; l >= 0; l--) - { - for (kmax = k + cblk.w; k < kmax; k++) - { - dk = data[k]; - if ((dk & resetmask & 0x7FFFFFFF) != 0) - { - // Something was decoded in previous bit-planes => set the - // approximation for previous bit-plane - data[k] = (dk & resetmask) | setmask; - } - else - { - // Was insignificant in previous bit-planes = set to zero - data[k] = 0; - } - } - k += cblk.scanw - cblk.w; - } - } - /// Static initializer: initializes all the lookup tables. - static StdEntropyDecoder() - { - { - int i, j; - //double val, deltaMSE; - int[] inter_sc_lut; - int ds, us, rs, ls; - int dsgn, usgn, rsgn, lsgn; - int h, v; - - // Initialize the zero coding lookup tables - - // LH - - // - No neighbors significant - ZC_LUT_LH[0] = 2; - // - No horizontal or vertical neighbors significant - for (i = 1; i < 16; i++) - { - // Two or more diagonal coeffs significant - ZC_LUT_LH[i] = 4; - } - for (i = 0; i < 4; i++) - { - // Only one diagonal coeff significant - ZC_LUT_LH[1 << i] = 3; - } - // - No horizontal neighbors significant, diagonal irrelevant - for (i = 0; i < 16; i++) - { - // Only one vertical coeff significant - ZC_LUT_LH[STATE_V_U_R1 | i] = 5; - ZC_LUT_LH[STATE_V_D_R1 | i] = 5; - // The two vertical coeffs significant - ZC_LUT_LH[STATE_V_U_R1 | STATE_V_D_R1 | i] = 6; - } - // - One horiz. neighbor significant, diagonal/vertical non-significant - ZC_LUT_LH[STATE_H_L_R1] = 7; - ZC_LUT_LH[STATE_H_R_R1] = 7; - // - One horiz. significant, no vertical significant, one or more - // diagonal significant - for (i = 1; i < 16; i++) - { - ZC_LUT_LH[STATE_H_L_R1 | i] = 8; - ZC_LUT_LH[STATE_H_R_R1 | i] = 8; - } - // - One horiz. significant, one or more vertical significant, - // diagonal irrelevant - for (i = 1; i < 4; i++) - { - for (j = 0; j < 16; j++) - { - ZC_LUT_LH[STATE_H_L_R1 | (i << 4) | j] = 9; - ZC_LUT_LH[STATE_H_R_R1 | (i << 4) | j] = 9; - } - } - // - Two horiz. significant, others irrelevant - for (i = 0; i < 64; i++) - { - ZC_LUT_LH[STATE_H_L_R1 | STATE_H_R_R1 | i] = 10; - } - - // HL - - // - No neighbors significant - ZC_LUT_HL[0] = 2; - // - No horizontal or vertical neighbors significant - for (i = 1; i < 16; i++) - { - // Two or more diagonal coeffs significant - ZC_LUT_HL[i] = 4; - } - for (i = 0; i < 4; i++) - { - // Only one diagonal coeff significant - ZC_LUT_HL[1 << i] = 3; - } - // - No vertical significant, diagonal irrelevant - for (i = 0; i < 16; i++) - { - // One horiz. significant - ZC_LUT_HL[STATE_H_L_R1 | i] = 5; - ZC_LUT_HL[STATE_H_R_R1 | i] = 5; - // Two horiz. significant - ZC_LUT_HL[STATE_H_L_R1 | STATE_H_R_R1 | i] = 6; - } - // - One vert. significant, diagonal/horizontal non-significant - ZC_LUT_HL[STATE_V_U_R1] = 7; - ZC_LUT_HL[STATE_V_D_R1] = 7; - // - One vert. significant, horizontal non-significant, one or more - // diag. significant - for (i = 1; i < 16; i++) - { - ZC_LUT_HL[STATE_V_U_R1 | i] = 8; - ZC_LUT_HL[STATE_V_D_R1 | i] = 8; - } - // - One vertical significant, one or more horizontal significant, - // diagonal irrelevant - for (i = 1; i < 4; i++) - { - for (j = 0; j < 16; j++) - { - ZC_LUT_HL[(i << 6) | STATE_V_U_R1 | j] = 9; - ZC_LUT_HL[(i << 6) | STATE_V_D_R1 | j] = 9; - } - } - // - Two vertical significant, others irrelevant - for (i = 0; i < 4; i++) - { - for (j = 0; j < 16; j++) - { - ZC_LUT_HL[(i << 6) | STATE_V_U_R1 | STATE_V_D_R1 | j] = 10; - } - } - - // HH - int[] twoBits = new int[] { 3, 5, 6, 9, 10, 12 }; // Figures (between 0 and 15) - // countaning 2 and only 2 bits on in its binary representation. - - int[] oneBit = new int[] { 1, 2, 4, 8 }; // Figures (between 0 and 15) - // countaning 1 and only 1 bit on in its binary representation. - - int[] twoLeast = new int[] { 3, 5, 6, 7, 9, 10, 11, 12, 13, 14, 15 }; // Figures - // (between 0 and 15) countaining, at least, 2 bits on in its - // binary representation. - - int[] threeLeast = new int[] { 7, 11, 13, 14, 15 }; // Figures - // (between 0 and 15) countaining, at least, 3 bits on in its - // binary representation. - - // - None significant - ZC_LUT_HH[0] = 2; - - // - One horizontal+vertical significant, none diagonal - for (i = 0; i < oneBit.Length; i++) - ZC_LUT_HH[oneBit[i] << 4] = 3; - - // - Two or more horizontal+vertical significant, diagonal non-signif - for (i = 0; i < twoLeast.Length; i++) - ZC_LUT_HH[twoLeast[i] << 4] = 4; - - // - One diagonal significant, horiz./vert. non-significant - for (i = 0; i < oneBit.Length; i++) - ZC_LUT_HH[oneBit[i]] = 5; - - // - One diagonal significant, one horiz.+vert. significant - for (i = 0; i < oneBit.Length; i++) - for (j = 0; j < oneBit.Length; j++) - ZC_LUT_HH[(oneBit[i] << 4) | oneBit[j]] = 6; - - // - One diag signif, two or more horiz+vert signif - for (i = 0; i < twoLeast.Length; i++) - for (j = 0; j < oneBit.Length; j++) - ZC_LUT_HH[(twoLeast[i] << 4) | oneBit[j]] = 7; - - // - Two diagonal significant, none horiz+vert significant - for (i = 0; i < twoBits.Length; i++) - ZC_LUT_HH[twoBits[i]] = 8; - - // - Two diagonal significant, one or more horiz+vert significant - for (j = 0; j < twoBits.Length; j++) - for (i = 1; i < 16; i++) - ZC_LUT_HH[(i << 4) | twoBits[j]] = 9; - - // - Three or more diagonal significant, horiz+vert irrelevant - for (i = 0; i < 16; i++) - for (j = 0; j < threeLeast.Length; j++) - ZC_LUT_HH[(i << 4) | threeLeast[j]] = 10; - - - // Initialize the SC lookup tables - - // Use an intermediate sign code lookup table that is similar to the - // one in the VM text, in that it depends on the 'h' and 'v' - // quantities. The index into this table is a 6 bit index, the top 3 - // bits are (h+1) and the low 3 bits (v+1). - inter_sc_lut = new int[36]; - inter_sc_lut[(2 << 3) | 2] = 15; - inter_sc_lut[(2 << 3) | 1] = 14; - inter_sc_lut[(2 << 3) | 0] = 13; - inter_sc_lut[(1 << 3) | 2] = 12; - inter_sc_lut[(1 << 3) | 1] = 11; - inter_sc_lut[(1 << 3) | 0] = 12 | INT_SIGN_BIT; - inter_sc_lut[(0 << 3) | 2] = 13 | INT_SIGN_BIT; - inter_sc_lut[(0 << 3) | 1] = 14 | INT_SIGN_BIT; - inter_sc_lut[(0 << 3) | 0] = 15 | INT_SIGN_BIT; - - // Using the intermediate sign code lookup table create the final - // one. The index into this table is a 9 bit index, the low 4 bits are - // the significance of the 4 horizontal/vertical neighbors, while the - // top 4 bits are the signs of those neighbors. The bit in the middle - // is ignored. This index arrangement matches the state bits in the - // 'state' array, thus direct addressing of the table can be done from - // the sate information. - for (i = 0; i < (1 << SC_LUT_BITS) - 1; i++) - { - ds = i & 0x01; // significance of down neighbor - us = (i >> 1) & 0x01; // significance of up neighbor - rs = (i >> 2) & 0x01; // significance of right neighbor - ls = (i >> 3) & 0x01; // significance of left neighbor - dsgn = (i >> 5) & 0x01; // sign of down neighbor - usgn = (i >> 6) & 0x01; // sign of up neighbor - rsgn = (i >> 7) & 0x01; // sign of right neighbor - lsgn = (i >> 8) & 0x01; // sign of left neighbor - // Calculate 'h' and 'v' as in VM text - h = ls * (1 - 2 * lsgn) + rs * (1 - 2 * rsgn); - h = (h >= -1) ? h : -1; - h = (h <= 1) ? h : 1; - v = us * (1 - 2 * usgn) + ds * (1 - 2 * dsgn); - v = (v >= -1) ? v : -1; - v = (v <= 1) ? v : 1; - // Get context and sign predictor from 'inter_sc_lut' - SC_LUT[i] = inter_sc_lut[(h + 1) << 3 | (v + 1)]; - } - inter_sc_lut = null; - - // Initialize the MR lookup tables - - // None significant, prev MR off - MR_LUT[0] = 16; - // One or more significant, prev MR off - for (i = 1; i < (1 << (MR_LUT_BITS - 1)); i++) - { - MR_LUT[i] = 17; - } - // Previous MR on, significance irrelevant - for (; i < (1 << MR_LUT_BITS); i++) - { - MR_LUT[i] = 18; - } - } - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/entropy/encoder/BitToByteOutput.cs b/CSJ2K/j2k/entropy/encoder/BitToByteOutput.cs deleted file mode 100644 index 7c528f63..00000000 --- a/CSJ2K/j2k/entropy/encoder/BitToByteOutput.cs +++ /dev/null @@ -1,304 +0,0 @@ -/* -* CVS identifier: -* -* $Id: BitToByteOutput.java,v 1.16 2001/10/17 16:56:59 grosbois Exp $ -* -* Class: BitToByteOutput -* -* Description: Adapter to perform bit based output on a byte -* based one. -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -namespace CSJ2K.j2k.entropy.encoder -{ - - /// This class provides an adapter to perform bit based output on byte based - /// output objects that inherit from a 'ByteOutputBuffer' class. This class - /// implements the bit stuffing policy needed for the 'selective arithmetic - /// coding bypass' mode of the entropy coder. This class also delays the output - /// of a trailing 0xFF, since they are synthetized be the decoder. - /// - /// - class BitToByteOutput - { - /// Set the flag according to whether or not the predictable termination is - /// requested. - /// - /// - /// Whether or not predictable termination is requested. - /// - /// - virtual internal bool PredTerm - { - set - { - this.isPredTerm = value; - } - - } - - /// Whether or not predictable termination is requested. This value is - /// important when the last byte before termination is an 0xFF - /// - private bool isPredTerm = false; - - /// The alternating sequence of 0's and 1's used for byte padding - internal const int PAD_SEQ = 0x2A; - - /// Flag that indicates if an FF has been delayed - internal bool delFF = false; - - /// The byte based output - internal ByteOutputBuffer out_Renamed; - - /// The bit buffer - internal int bbuf; - - /// The position of the next bit to put in the bit buffer. When it is 7 - /// the bit buffer 'bbuf' is empty. The value should always be between 7 - /// and 0 (i.e. if it gets to -1, the bit buffer should be immediately - /// written to the byte output). - /// - internal int bpos = 7; - - /// The number of written bytes (excluding the bit buffer) - internal int nb = 0; - - /// Instantiates a new 'BitToByteOutput' object that uses 'out' as the - /// underlying byte based output. - /// - /// - /// The underlying byte based output - /// - /// - internal BitToByteOutput(ByteOutputBuffer out_Renamed) - { - this.out_Renamed = out_Renamed; - } - - /// Writes to the bit stream the symbols contained in the 'symbuf' - /// buffer. The least significant bit of each element in 'symbuf'is - /// written. - /// - /// - /// The symbols to write - /// - /// - /// The number of symbols in symbuf - /// - /// - internal void writeBits(int[] symbuf, int nsym) - { - int i; - int bbuf, bpos; - bbuf = this.bbuf; - bpos = this.bpos; - // Write symbol by symbol to bit buffer - for (i = 0; i < nsym; i++) - { - bbuf |= (symbuf[i] & 0x01) << (bpos--); - if (bpos < 0) - { - // Bit buffer is full, write it - if (bbuf != 0xFF) - { - // No bit-stuffing needed - if (delFF) - { - // Output delayed 0xFF if any - out_Renamed.write(0xFF); - nb++; - delFF = false; - } - out_Renamed.write(bbuf); - nb++; - bpos = 7; - } - else - { - // We need to do bit stuffing on next byte - delFF = true; - bpos = 6; // One less bit in next byte - } - bbuf = 0; - } - } - this.bbuf = bbuf; - this.bpos = bpos; - } - - /// Write a bit to the output. The least significant bit of 'bit' is - /// written to the output. - /// - /// - /// - /// - internal void writeBit(int bit) - { - bbuf |= (bit & 0x01) << (bpos--); - if (bpos < 0) - { - if (bbuf != 0xFF) - { - // No bit-stuffing needed - if (delFF) - { - // Output delayed 0xFF if any - out_Renamed.write(0xFF); - nb++; - delFF = false; - } - // Output the bit buffer - out_Renamed.write(bbuf); - nb++; - bpos = 7; - } - else - { - // We need to do bit stuffing on next byte - delFF = true; - bpos = 6; // One less bit in next byte - } - bbuf = 0; - } - } - - /// Writes the contents of the bit buffer and byte aligns the output by - /// filling bits with an alternating sequence of 0's and 1's. - /// - /// - internal virtual void flush() - { - if (delFF) - { - // There was a bit stuffing - if (bpos != 6) - { - // Bit buffer is not empty - // Output delayed 0xFF - out_Renamed.write(0xFF); - nb++; - delFF = false; - // Pad to byte boundary with an alternating sequence of 0's - // and 1's. - bbuf |= (SupportClass.URShift(PAD_SEQ, (6 - bpos))); - // Output the bit buffer - out_Renamed.write(bbuf); - nb++; - bpos = 7; - bbuf = 0; - } - else if (isPredTerm) - { - out_Renamed.write(0xFF); - nb++; - out_Renamed.write(0x2A); - nb++; - bpos = 7; - bbuf = 0; - delFF = false; - } - } - else - { - // There was no bit stuffing - if (bpos != 7) - { - // Bit buffer is not empty - // Pad to byte boundary with an alternating sequence of 0's and - // 1's. - bbuf |= (SupportClass.URShift(PAD_SEQ, (6 - bpos))); - // Output the bit buffer (bbuf can not be 0xFF) - out_Renamed.write(bbuf); - nb++; - bpos = 7; - bbuf = 0; - } - } - } - - /// Terminates the bit stream by calling 'flush()' and then - /// 'reset()'. Finally, it returns the number of bytes effectively written. - /// - /// - /// The number of bytes effectively written. - /// - /// - public virtual int terminate() - { - flush(); - int savedNb = nb; - reset(); - return savedNb; - } - - /// Resets the bit buffer to empty, without writing anything to the - /// underlying byte output, and resets the byte count. The underlying byte - /// output is NOT reset. - /// - /// - internal virtual void reset() - { - delFF = false; - bpos = 7; - bbuf = 0; - nb = 0; - } - - /// Returns the length, in bytes, of the output bit stream as written by - /// this object. If the output bit stream does not have an integer number - /// of bytes in length then it is rounded to the next integer. - /// - /// - /// The length, in bytes, of the output bit stream. - /// - /// - internal virtual int length() - { - if (delFF) - { - // If bit buffer is empty we just need 'nb' bytes. If not we need - // the delayed FF and the padded bit buffer. - return nb + 2; - } - else - { - // If the bit buffer is empty, we just need 'nb' bytes. If not, we - // add length of the padded bit buffer - return nb + ((bpos == 7) ? 0 : 1); - } - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/entropy/encoder/ByteOutputBuffer.cs b/CSJ2K/j2k/entropy/encoder/ByteOutputBuffer.cs deleted file mode 100644 index 67098147..00000000 --- a/CSJ2K/j2k/entropy/encoder/ByteOutputBuffer.cs +++ /dev/null @@ -1,184 +0,0 @@ -/* -* CVS identifier: -* -* $Id: ByteOutputBuffer.java,v 1.10 2001/05/17 15:21:16 grosbois Exp $ -* -* Class: ByteOutputBuffer -* -* Description: Provides buffering for byte based output, similar -* to the standard class ByteArrayOutputStream -* -* the old jj2000.j2k.io.ByteArrayOutput class by -* Diego SANTA CRUZ, Apr-26-1999 -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using System; -namespace CSJ2K.j2k.entropy.encoder -{ - - /// This class provides a buffering output stream similar to - /// ByteArrayOutputStream, with some additional methods. - /// - ///

    Once an array has been written to an output stream or to a byte array, - /// the object can be reused as a new stream if the reset() method is - /// called.

    - /// - ///

    Unlike the ByteArrayOutputStream class, this class is not thread - /// safe.

    - /// - ///
    - /// - /// - /// - public class ByteOutputBuffer - { - - /// The buffer where the data is stored - internal byte[] buf; - - /// The number of valid bytes in the buffer - internal int count; - - /// The buffer increase size - public const int BUF_INC = 512; - - /// The default initial buffer size - public const int BUF_DEF_LEN = 256; - - /// Creates a new byte array output stream. The buffer capacity is - /// initially BUF_DEF_LEN bytes, though its size increases if necessary. - /// - /// - public ByteOutputBuffer() - { - buf = new byte[BUF_DEF_LEN]; - } - - /// Creates a new byte array output stream, with a buffer capacity of the - /// specified size, in bytes. - /// - /// - /// the initial size. - /// - /// - public ByteOutputBuffer(int size) - { - buf = new byte[size]; - } - - /// Writes the specified byte to this byte array output stream. The - /// functionality provided by this implementation is the same as for the - /// one in the superclass, however this method is not synchronized and - /// therefore not safe thread, but faster. - /// - /// - /// The byte to write - /// - /// - public void write(int b) - { - if (count == buf.Length) - { - // Resize buffer - byte[] tmpbuf = buf; - buf = new byte[buf.Length + BUF_INC]; - Array.Copy(tmpbuf, 0, buf, 0, count); - } - buf[count++] = (byte)b; - } - - /// Copies the specified part of the stream to the 'outbuf' byte array. - /// - /// - /// The index of the first element in the stream to copy. - /// - /// - /// The number of elements of the array to copy - /// - /// - /// The destination array - /// - /// - /// The index of the first element in 'outbuf' where to write - /// the data. - /// - /// - public virtual void toByteArray(int off, int len, byte[] outbuf, int outoff) - { - // Copy the data - Array.Copy(buf, off, outbuf, outoff, len); - } - - /// Returns the number of valid bytes in the output buffer (count class - /// variable). - /// - /// - /// The number of bytes written to the buffer - /// - /// - public virtual int size() - { - return count; - } - - /// Discards all the buffered data, by resetting the counter of written - /// bytes to 0. - /// - /// - public virtual void reset() - { - count = 0; - } - - /// Returns the byte buffered at the given position in the buffer. The - /// position in the buffer is the index of the 'write()' method call after - /// the last call to 'reset()'. - /// - /// - /// The position of the byte to return - /// - /// - /// The value (betweeb 0-255) of the byte at position 'pos'. - /// - /// - public virtual int getByte(int pos) - { - if (pos >= count) - { - throw new System.ArgumentException(); - } - return buf[pos] & 0xFF; - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/entropy/encoder/CBlkRateDistStats.cs b/CSJ2K/j2k/entropy/encoder/CBlkRateDistStats.cs deleted file mode 100644 index 91f27df5..00000000 --- a/CSJ2K/j2k/entropy/encoder/CBlkRateDistStats.cs +++ /dev/null @@ -1,389 +0,0 @@ -/* -* CVS identifier: -* -* $Id: CBlkRateDistStats.java,v 1.11 2001/09/14 09:23:51 grosbois Exp $ -* -* Class: CBlkRateDistStats -* -* Description: The coded (compressed) code-block with -* rate-distortion statistics. -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.wavelet.analysis; -using System; -namespace CSJ2K.j2k.entropy.encoder -{ - - /// This class stores coded (compressed) code-blocks with their associated - /// rate-distortion statistics. This object should always contain all the - /// compressed data of the code-block. It is applicable to the encoder engine - /// only. Some data of the coded-block is stored in the super class, see - /// CodedCBlk. - /// - ///

    The rate-distortion statistics (i.e. R-D slope) is stored for valid - /// points only. The set of valid points is determined by the entropy coder - /// engine itself. Normally they are selected so as to lye in a convex hull, - /// which can be achived by using the 'selectConvexHull' method of this class, - /// but some other strategies might be employed.

    - /// - ///

    The rate (in bytes) for each truncation point (valid or not) is stored - /// in the 'truncRates' array. The rate of a truncation point is the total - /// number of bytes in 'data' (see super class) that have to be decoded to - /// reach the truncation point.

    - /// - ///

    The slope (reduction of distortion divided by the increase in rate) at - /// each of the valid truncation points is stored in 'truncSlopes'.

    - /// - ///

    The index of each valid truncation point is stored in 'truncIdxs'. The - /// index should be interpreted in the following way: a valid truncation point - /// at position 'n' has the index 'truncIdxs[n]', the rate - /// 'truncRates[truncIdxs[n]]' and the slope 'truncSlopes[n]'. The arrays - /// 'truncIdxs' and 'truncRates' have at least 'nVldTrunc' elements. The - /// 'truncRates' array has at least 'nTotTrunc' elements.

    - /// - ///

    In addition the 'isTermPass' array contains a flag for each truncation - /// point (valid and non-valid ones) that tells if the pass is terminated or - /// not. If this variable is null then it means that no pass is terminated, - /// except the last one which always is.

    - /// - ///

    The compressed data is stored in the 'data' member variable of the super - /// class.

    - /// - ///
    - /// - /// - /// - public class CBlkRateDistStats : CodedCBlk - { - - /// The subband to which the code-block belongs - public SubbandAn sb; - - /// The total number of truncation points - public int nTotTrunc; - - /// The number of valid truncation points - public int nVldTrunc; - - /// The rate (in bytes) for each truncation point (valid and non-valid - /// ones) - /// - public int[] truncRates; - - /// The distortion for each truncation point (valid and non-valid ones) - public double[] truncDists; - - /// The negative of the rate-distortion slope for each valid truncation - /// point - /// - public float[] truncSlopes; - - /// The indices of the valid truncation points, in increasing order. - public int[] truncIdxs; - - /// Array of flags indicating terminated passes (valid or non-valid - /// truncation points). - /// - public bool[] isTermPass; - - /// The number of ROI coefficients in the code-block - public int nROIcoeff = 0; - - /// Number of ROI coding passes - public int nROIcp = 0; - - /// Creates a new CBlkRateDistStats object without allocating any space for - /// 'truncRates', 'truncSlopes', 'truncDists' and 'truncIdxs' or 'data'. - /// - /// - public CBlkRateDistStats() - { - } - - /// Creates a new CBlkRateDistStats object and initializes the valid - /// truncation points, their rates and their slopes, from the 'rates' and - /// 'dist' arrays. The 'rates', 'dist' and 'termp' arrays must contain the - /// rate (in bytes), the reduction in distortion (from nothing coded) and - /// the flag indicating if termination is used, respectively, for each - /// truncation point. - /// - ///

    The valid truncation points are selected by taking them as lying on - /// a convex hull. This is done by calling the method - /// selectConvexHull().

    - /// - ///

    Note that the arrays 'rates' and 'termp' are copied, not referenced, - /// so they can be modified after a call to this constructor.

    - /// - ///
    - /// The horizontal index of the code-block, within the subband. - /// - /// - /// The vertical index of the code-block, within the subband. - /// - /// - /// The number of skipped most significant bit-planes for - /// this code-block. - /// - /// - /// The compressed data. This array is referenced by this - /// object so it should not be modified after. - /// - /// - /// The rates (in bytes) for each truncation point in the - /// compressed data. This array is modified by the method but no reference - /// is kept to it. - /// - /// - /// The reduction in distortion (with respect to no - /// information coded) for each truncation point. This array is modified by - /// the method but no reference is kept to it. - /// - /// - /// An array of boolean flags indicating, for each pass, if a - /// pass is terminated or not (true if terminated). If null then it is - /// assumed that no pass is terminated except the last one which always is. - /// - /// - /// The number of truncation points contained in 'rates', 'dist' - /// and 'termp'. - /// - /// - /// If false the convex hull is constructed as for lossy - /// coding. If true it is constructed as for lossless coding, in which case - /// it is ensured that all bit-planes are sent (i.e. the last truncation - /// point is always included). - /// - /// - public CBlkRateDistStats(int m, int n, int skipMSBP, byte[] data, int[] rates, double[] dists, bool[] termp, int np, bool inclast) : base(m, n, skipMSBP, data) - { - selectConvexHull(rates, dists, termp, np, inclast); - } - - /// Compute the rate-distorsion slopes and selects those that lie in a - /// convex hull. It will compute the slopes, select the ones that form the - /// convex hull and initialize the 'truncIdxs' and 'truncSlopes' arrays, as - /// well as 'nVldTrunc', with the selected truncation points. It will also - /// initialize 'truncRates' and 'isTermPass' arrays, as well as - /// 'nTotTrunc', with all the truncation points (selected or not). - /// - ///

    Note that the arrays 'rates' and 'termp' are copied, not - /// referenced, so they can be modified after a call to this method.

    - /// - ///
    - /// The rates (in bytes) for each truncation point in the - /// compressed data. This array is modified by the method. - /// - /// - /// The reduction in distortion (with respect to no - /// information coded) for each truncation point. This array is modified by - /// the method. - /// - /// - /// An array of boolean flags indicating, for each pass, if a - /// pass is terminated or not (true if terminated). If null then it is - /// assumed that no pass is terminated except the last one which always is. - /// - /// - /// The number of truncation points contained in 'rates', 'dist' - /// and 'termp'. - /// - /// - /// If false the convex hull is constructed as for lossy - /// coding. If true it is constructed as for lossless coding, in which case - /// it is ensured that all bit-planes are sent (i.e. the last truncation - /// point is always included). - /// - /// - public virtual void selectConvexHull(int[] rates, double[] dists, bool[] termp, int n, bool inclast) - { - int first_pnt; // The first point containing some coded data - int p; // last selected point - int k; // current point - int i; // current valid point - int npnt; // number of selected (i.e. valid) points - int delta_rate; // Rate difference - double delta_dist; // Distortion difference - float k_slope; // R-D slope for the current point - float p_slope; // R-D slope for the last selected point - //int ll_rate; // Rate for "lossless" coding (i.e. all coded info) - - // Convention: when a negative value is stored in 'rates' it meas an - // invalid point. The absolute value is always the rate for that point. - - // Look for first point with some coded info (rate not 0) - first_pnt = 0; - while (first_pnt < n && rates[first_pnt] <= 0) - { - first_pnt++; - } - - // Select the valid points - npnt = n - first_pnt; - p_slope = 0f; // To keep compiler happy - //UPGRADE_NOTE: Label 'ploop' was moved. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1014'" - do - { - p = -1; - for (k = first_pnt; k < n; k++) - { - if (rates[k] < 0) - { - // Already invalidated point - continue; - } - // Calculate decrease in distortion and rate - if (p >= 0) - { - delta_rate = rates[k] - rates[p]; - delta_dist = dists[k] - dists[p]; - } - else - { - // This is with respect to no info coded - delta_rate = rates[k]; - delta_dist = dists[k]; - } - // If exactly same distortion don't eliminate if the rates are - // equal, otherwise it can lead to infinite slope in lossless - // coding. - if (delta_dist < 0f || (delta_dist == 0f && delta_rate > 0)) - { - // This point increases distortion => invalidate - rates[k] = -rates[k]; - npnt--; - continue; // Goto next point - } - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - k_slope = (float)(delta_dist / delta_rate); - // Check that there is a decrease in distortion, slope is not - // infinite (i.e. delta_dist is not 0) and slope is - // decreasing. - if (p >= 0 && (delta_rate <= 0 || k_slope >= p_slope)) - { - // Last point was not good - rates[p] = -rates[p]; // Remove p from valid points - npnt--; - //UPGRADE_NOTE: Labeled continue statement was changed to a goto statement. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1015'" - goto ploop; // Restart from the first one - } - else - { - p_slope = k_slope; - p = k; - } - } - // If we get to last point we are done - break; - //UPGRADE_NOTE: Label 'ploop' was moved. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1014'" - - ploop:; - } - while (true); // We end the loop with the break statement - - // If in lossless mode make sure we don't eliminate any last - // bit-planes from being sent. - if (inclast && n > 0 && rates[n - 1] < 0) - { - rates[n - 1] = -rates[n - 1]; - // This rate can never be equal to any previous selected rate, - // given the selection algorithm above, so no problem arises of - // infinite slopes. - npnt++; - } - - // Initialize the arrays of this object - nTotTrunc = n; - nVldTrunc = npnt; - truncRates = new int[n]; - truncDists = new double[n]; - truncSlopes = new float[npnt]; - truncIdxs = new int[npnt]; - if (termp != null) - { - isTermPass = new bool[n]; - Array.Copy(termp, 0, isTermPass, 0, n); - } - else - { - isTermPass = null; - } - Array.Copy(rates, 0, truncRates, 0, n); - for (k = first_pnt, p = -1, i = 0; k < n; k++) - { - if (rates[k] > 0) - { - // A valid point - truncDists[k] = dists[k]; - if (p < 0) - { - // Only arrives at first valid point - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - truncSlopes[i] = (float)(dists[k] / rates[k]); - } - else - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - truncSlopes[i] = (float)((dists[k] - dists[p]) / (rates[k] - rates[p])); - } - truncIdxs[i] = k; - i++; - p = k; - } - else - { - truncDists[k] = -1; - truncRates[k] = -truncRates[k]; - } - } - } - - /// Returns the contents of the object in a string. This is used for - /// debugging. - /// - /// - /// A string with the contents of the object - /// - /// - public override System.String ToString() - { - System.String str = base.ToString() + "\n nVldTrunc=" + nVldTrunc + ", nTotTrunc=" + nTotTrunc + ", num. ROI" + " coeff=" + nROIcoeff + ", num. ROI coding passes=" + nROIcp + ", sb=" + sb.sbandIdx; - // str += "\n\ttruncRates:\n"; - // for(int i=0; i This interface defines a source of entropy coded data and methods to - /// transfer it in a code-block by code-block basis. In each call to - /// 'getNextCodeBlock()' a new coded code-block is returned. The code-block are - /// retruned in no specific-order. - /// - ///

    This interface is the source of data for the rate allocator. See the - /// 'PostCompRateAllocator' class.

    - /// - ///

    For each coded-code-block the entropy-coded data is returned along with - /// the rate-distortion statistics in a 'CBlkRateDistStats' object.

    - /// - ///
    - /// - /// - /// - /// - /// - /// - /// - public interface CodedCBlkDataSrcEnc : ForwWTDataProps - { - - /// Returns the next coded code-block in the current tile for the specified - /// component, as a copy (see below). The order in which code-blocks are - /// returned is not specified. However each code-block is returned only - /// once and all code-blocks will be returned if the method is called 'N' - /// times, where 'N' is the number of code-blocks in the tile. After all - /// the code-blocks have been returned for the current tile calls to this - /// method will return 'null'. - /// - ///

    When changing the current tile (through 'setTile()' or 'nextTile()') - /// this method will always return the first code-block, as if this method - /// was never called before for the new current tile.

    - /// - ///

    The data returned by this method is always a copy of the internal - /// data of this object, if any, and it can be modified "in place" without - /// any problems after being returned.

    - /// - ///
    - /// The component for which to return the next code-block. - /// - /// - /// If non-null this object might be used in returning the coded - /// code-block in this or any subsequent call to this method. If null a new - /// one is created and returned. If the 'data' array of 'cbb' is not null - /// it may be reused to return the compressed data. - /// - /// - /// The next coded code-block in the current tile for component - /// 'c', or null if all code-blocks for the current tile have been - /// returned. - /// - /// - /// - /// - /// - CBlkRateDistStats getNextCodeBlock(int c, CBlkRateDistStats ccb); - - /// Returns the width of a packet for the specified tile-component and - /// resolution level. - /// - /// - /// The tile - /// - /// - /// The component - /// - /// - /// The resolution level - /// - /// - /// The width of a packet for the specified tile- component and - /// resolution level. - /// - /// - int getPPX(int t, int c, int r); - - /// Returns the height of a packet for the specified tile-component and - /// resolution level. - /// - /// - /// The tile - /// - /// - /// The component - /// - /// - /// The resolution level - /// - /// - /// The height of a packet for the specified tile- component and - /// resolution level. - /// - /// - int getPPY(int t, int c, int r); - - /// Returns true if the precinct partition is used for the specified - /// component and tile, returns false otherwise - /// - /// - /// The component - /// - /// - /// The tile - /// - /// - bool precinctPartitionUsed(int c, int t); - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/entropy/encoder/EBCOTLayer.cs b/CSJ2K/j2k/entropy/encoder/EBCOTLayer.cs deleted file mode 100644 index 59ca8076..00000000 --- a/CSJ2K/j2k/entropy/encoder/EBCOTLayer.cs +++ /dev/null @@ -1,86 +0,0 @@ -/* -* CVS identifier: -* -* $Id: EBCOTLayer.java,v 1.9 2001/05/16 09:40:58 grosbois Exp $ -* -* Class: EBCOTLayer -* -* Description: Storage for layer information, -* used by EBCOTRateAllocator -* -* class that was in EBCOTRateAllocator. -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -namespace CSJ2K.j2k.entropy.encoder -{ - - /// This class holds information about each layer that is to be, or has already - /// been, allocated . It is used in the rate-allocation process to keep the - /// necessary layer information. It is used by EBCOTRateAllocator. - /// - /// - /// - /// - /// - class EBCOTLayer - { - /// This is the maximum number of bytes that should be allocated for this - /// and previous layers. This is actually the target length for the layer. - /// - /// - internal int maxBytes; - - /// The actual number of bytes which are consumed by the the current and - /// any previous layers. This is the result from a simulation when the - /// threshold for the layer has been set. - /// - /// - internal int actualBytes; - - /// If true the `maxBytes' value is the hard maximum and the threshold is - /// determined iteratively. If false the `maxBytes' value is a target - /// bitrate and the threshold is estimated from summary information - /// accumulated during block coding. - /// - /// - internal bool optimize; - - /// The rate-distortion threshold associated with the bit-stream - /// layer. When set the layer includes data up to the truncation points - /// that have a slope no smaller than 'rdThreshold'. - /// - /// - internal float rdThreshold; - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/entropy/encoder/EBCOTRateAllocator.cs b/CSJ2K/j2k/entropy/encoder/EBCOTRateAllocator.cs deleted file mode 100644 index 58964750..00000000 --- a/CSJ2K/j2k/entropy/encoder/EBCOTRateAllocator.cs +++ /dev/null @@ -1,2399 +0,0 @@ -/* -* CVS identifier: -* -* $Id: EBCOTRateAllocator.java,v 1.97 2002/05/22 14:59:44 grosbois Exp $ -* -* Class: EBCOTRateAllocator -* -* Description: Generic interface for post-compression -* rate allocator. -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.codestream; -using CSJ2K.j2k.codestream.writer; -using CSJ2K.j2k.encoder; -using CSJ2K.j2k.image; -using CSJ2K.j2k.util; -using CSJ2K.j2k.wavelet.analysis; -namespace CSJ2K.j2k.entropy.encoder -{ - - /// This implements the EBCOT post compression rate allocation algorithm. This - /// algorithm finds the most suitable truncation points for the set of - /// code-blocks, for each layer target bitrate. It works by first collecting - /// the rate distortion info from all code-blocks, in all tiles and all - /// components, and then running the rate-allocation on the whole image at - /// once, for each layer. - /// - ///

    This implementation also provides some timing features. They can be - /// enabled by setting the 'DO_TIMING' constant of this class to true and - /// recompiling. The timing uses the 'System.currentTimeMillis()' Java API - /// call, which returns wall clock time, not the actual CPU time used. The - /// timing results will be printed on the message output. Since the times - /// reported are wall clock times and not CPU usage times they can not be added - /// to find the total used time (i.e. some time might be counted in several - /// places). When timing is disabled ('DO_TIMING' is false) there is no penalty - /// if the compiler performs some basic optimizations. Even if not the penalty - /// should be negligeable.

    - /// - ///
    - /// - /// - /// - /// - /// - /// - /// - public class EBCOTRateAllocator : PostCompRateAllocator - { - - /// Whether to collect timing information or not: false. Used as a compile - /// time directive. - /// - -#if DO_TIMING - /// The wall time for the initialization. - //private long initTime; - - /// The wall time for the building of layers. - //private long buildTime; - - /// The wall time for the writing of layers. - //private long writeTime; -#endif - - /// 5D Array containing all the coded code-blocks: - /// - ///
      - ///
    • 1st index: tile index
    • - ///
    • 2nd index: component index
    • - ///
    • 3rd index: resolution level index
    • - ///
    • 4th index: subband index
    • - ///
    • 5th index: code-block index
    • - ///
    - /// - ///
    - private CBlkRateDistStats[][][][][] cblks; - - /// 6D Array containing the indices of the truncation points. It actually - /// contains the index of the element in CBlkRateDistStats.truncIdxs that - /// gives the real truncation point index. - /// - ///
      - ///
    • 1st index: tile index
    • - ///
    • 2nd index: layer index
    • - ///
    • 3rd index: component index
    • - ///
    • 4th index: resolution level index
    • - ///
    • 5th index: subband index
    • - ///
    • 6th index: code-block index
    • - ///
    - /// - ///
    - private int[][][][][][] truncIdxs; - - /// Number of precincts in each resolution level: - /// - ///
      - ///
    • 1st dim: tile index.
    • - ///
    • 2nd dim: component index.
    • - ///
    • 3nd dim: resolution level index.
    • - ///
    - /// - ///
    - private Coord[][][] numPrec; - - /// Array containing the layers information. - private EBCOTLayer[] layers; - - /// The log of 2, natural base - //UPGRADE_NOTE: Final was removed from the declaration of 'LOG2 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly double LOG2 = System.Math.Log(2); - - /// The normalization offset for the R-D summary table - private const int RD_SUMMARY_OFF = 24; - - /// The size of the summary table - private const int RD_SUMMARY_SIZE = 64; - - /// The relative precision for float data. This is the relative tolerance - /// up to which the layer slope thresholds are calculated. - /// - private const float FLOAT_REL_PRECISION = 1e-4f; - - /// The precision for float data type, in an absolute sense. Two float - /// numbers are considered "equal" if they are within this precision. - /// - private const float FLOAT_ABS_PRECISION = 1e-10f; - - /// Minimum average size of a packet. If layer has less bytes than the - /// this constant multiplied by number of packets in the layer, then the - /// layer is skipped. - /// - private const int MIN_AVG_PACKET_SZ = 32; - - /// The R-D summary information collected from the coding of all - /// code-blocks. For each entry it contains the accumulated length of all - /// truncation points that have a slope not less than - /// '2*(k-RD_SUMMARY_OFF)', where 'k' is the entry index. - /// - ///

    Therefore, the length at entry 'k' is the total number of bytes of - /// code-block data that would be obtained if the truncation slope was - /// chosen as '2*(k-RD_SUMMARY_OFF)', without counting the overhead - /// associated with the packet heads.

    - /// - ///

    This summary is used to estimate the relation of the R-D slope to - /// coded length, and to obtain absolute minimums on the slope given a - /// length.

    - ///
    - private int[] RDSlopesRates; - - /// Packet encoder. - private PktEncoder pktEnc; - - /// The layer specifications - private LayersInfo lyrSpec; - - /// The maximum slope accross all code-blocks and truncation points. - private float maxSlope; - - /// The minimum slope accross all code-blocks and truncation points. - private float minSlope; - - /// Initializes the EBCOT rate allocator of entropy coded data. The layout - /// of layers, and their bitrate constraints, is specified by the 'lyrs' - /// parameter. - /// - /// - /// The source of entropy coded data. - /// - /// - /// The layers layout specification. - /// - /// - /// The bit stream writer. - /// - /// - /// - /// - /// - public EBCOTRateAllocator(CodedCBlkDataSrcEnc src, LayersInfo lyrs, CodestreamWriter writer, EncoderSpecs encSpec, ParameterList pl) : base(src, lyrs.TotNumLayers, writer, encSpec) - { - - int minsbi, maxsbi; - int i; - SubbandAn sb, sb2; - Coord ncblks = null; - - // If we do timing create necessary structures -#if DO_TIMING - // If we are timing make sure that 'finalize' gets called. - //UPGRADE_ISSUE: Method 'java.lang.System.runFinalizersOnExit' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javalangSystem'" - // CONVERSION PROBLEM? - //System_Renamed.runFinalizersOnExit(true); - // The System.runFinalizersOnExit() method is deprecated in Java - // 1.2 since it can cause a deadlock in some cases. However, here - // we use it only for profiling purposes and is disabled in - // production code. - initTime = 0L; - buildTime = 0L; - writeTime = 0L; -#endif - - // Save the layer specs - lyrSpec = lyrs; - - //Initialize the size of the RD slope rates array - RDSlopesRates = new int[RD_SUMMARY_SIZE]; - - //Get number of tiles, components - int nt = src.getNumTiles(); - int nc = NumComps; - - //Allocate the coded code-blocks and truncation points indexes arrays - cblks = new CBlkRateDistStats[nt][][][][]; - for (int i2 = 0; i2 < nt; i2++) - { - cblks[i2] = new CBlkRateDistStats[nc][][][]; - } - truncIdxs = new int[nt][][][][][]; - for (int i3 = 0; i3 < nt; i3++) - { - truncIdxs[i3] = new int[num_Layers][][][][]; - for (int i4 = 0; i4 < num_Layers; i4++) - { - truncIdxs[i3][i4] = new int[nc][][][]; - } - } - - int cblkPerSubband; // Number of code-blocks per subband - int mrl; // Number of resolution levels - int l; // layer index - int s; //subband index - - // Used to compute the maximum number of precincts for each resolution - // level - int tx0, ty0, tx1, ty1; // Current tile position in the reference grid - int tcx0, tcy0, tcx1, tcy1; // Current tile position in the domain of - // the image component - int trx0, try0, trx1, try1; // Current tile position in the reduced - // resolution image domain - int xrsiz, yrsiz; // Component sub-sampling factors - Coord tileI = null; - Coord nTiles = null; - int xsiz, ysiz, x0siz, y0siz; - int xt0siz, yt0siz; - int xtsiz, ytsiz; - - int cb0x = src.CbULX; - int cb0y = src.CbULY; - - src.setTile(0, 0); - for (int t = 0; t < nt; t++) - { - // Loop on tiles - nTiles = src.getNumTiles(nTiles); - tileI = src.getTile(tileI); - x0siz = ImgULX; - y0siz = ImgULY; - xsiz = x0siz + ImgWidth; - ysiz = y0siz + ImgHeight; - xt0siz = src.TilePartULX; - yt0siz = src.TilePartULY; - xtsiz = src.NomTileWidth; - ytsiz = src.NomTileHeight; - - // Tile's coordinates on the reference grid - tx0 = (tileI.x == 0) ? x0siz : xt0siz + tileI.x * xtsiz; - ty0 = (tileI.y == 0) ? y0siz : yt0siz + tileI.y * ytsiz; - tx1 = (tileI.x != nTiles.x - 1) ? xt0siz + (tileI.x + 1) * xtsiz : xsiz; - ty1 = (tileI.y != nTiles.y - 1) ? yt0siz + (tileI.y + 1) * ytsiz : ysiz; - - for (int c = 0; c < nc; c++) - { - // loop on components - - //Get the number of resolution levels - sb = src.getAnSubbandTree(t, c); - mrl = sb.resLvl + 1; - - // Initialize maximum number of precincts per resolution array - if (numPrec == null) - { - Coord[][][] tmpArray = new Coord[nt][][]; - for (int i5 = 0; i5 < nt; i5++) - { - tmpArray[i5] = new Coord[nc][]; - } - numPrec = tmpArray; - } - if (numPrec[t][c] == null) - { - numPrec[t][c] = new Coord[mrl]; - } - - // Subsampling factors - xrsiz = src.getCompSubsX(c); - yrsiz = src.getCompSubsY(c); - - // Tile's coordinates in the image component domain - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - tcx0 = (int)System.Math.Ceiling(tx0 / (double)(xrsiz)); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - tcy0 = (int)System.Math.Ceiling(ty0 / (double)(yrsiz)); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - tcx1 = (int)System.Math.Ceiling(tx1 / (double)(xrsiz)); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - tcy1 = (int)System.Math.Ceiling(ty1 / (double)(yrsiz)); - - cblks[t][c] = new CBlkRateDistStats[mrl][][]; - - for (l = 0; l < num_Layers; l++) - { - truncIdxs[t][l][c] = new int[mrl][][]; - } - - for (int r = 0; r < mrl; r++) - { - // loop on resolution levels - - // Tile's coordinates in the reduced resolution image - // domain - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - trx0 = (int)System.Math.Ceiling(tcx0 / (double)(1 << (mrl - 1 - r))); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - try0 = (int)System.Math.Ceiling(tcy0 / (double)(1 << (mrl - 1 - r))); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - trx1 = (int)System.Math.Ceiling(tcx1 / (double)(1 << (mrl - 1 - r))); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - try1 = (int)System.Math.Ceiling(tcy1 / (double)(1 << (mrl - 1 - r))); - - // Calculate the maximum number of precincts for each - // resolution level taking into account tile specific - // options. - double twoppx = (double)encSpec.pss.getPPX(t, c, r); - double twoppy = (double)encSpec.pss.getPPY(t, c, r); - numPrec[t][c][r] = new Coord(); - if (trx1 > trx0) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - numPrec[t][c][r].x = (int)System.Math.Ceiling((trx1 - cb0x) / twoppx) - (int)System.Math.Floor((trx0 - cb0x) / twoppx); - } - else - { - numPrec[t][c][r].x = 0; - } - if (try1 > try0) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - numPrec[t][c][r].y = (int)System.Math.Ceiling((try1 - cb0y) / twoppy) - (int)System.Math.Floor((try0 - cb0y) / (double)twoppy); - } - else - { - numPrec[t][c][r].y = 0; - } - - minsbi = (r == 0) ? 0 : 1; - maxsbi = (r == 0) ? 1 : 4; - - cblks[t][c][r] = new CBlkRateDistStats[maxsbi][]; - for (l = 0; l < num_Layers; l++) - { - truncIdxs[t][l][c][r] = new int[maxsbi][]; - } - - for (s = minsbi; s < maxsbi; s++) - { - // loop on subbands - //Get the number of blocks in the current subband - sb2 = (SubbandAn)sb.getSubbandByIdx(r, s); - ncblks = sb2.numCb; - cblkPerSubband = ncblks.x * ncblks.y; - cblks[t][c][r][s] = new CBlkRateDistStats[cblkPerSubband]; - - for (l = 0; l < num_Layers; l++) - { - truncIdxs[t][l][c][r][s] = new int[cblkPerSubband]; - for (i = 0; i < cblkPerSubband; i++) - { - truncIdxs[t][l][c][r][s][i] = -1; - } - } - } // End loop on subbands - } // End lopp on resolution levels - } // End loop on components - if (t != nt - 1) - { - src.nextTile(); - } - } // End loop on tiles - - //Initialize the packet encoder - pktEnc = new PktEncoder(src, encSpec, numPrec, pl); - - // The layers array has to be initialized after the constructor since - // it is needed that the bit stream header has been entirely written - } - -#if DO_TIMING - /// Prints the timing information, if collected, and calls 'finalize' on - /// the super class. - /// - /// - ~EBCOTRateAllocator() - { - - System.Text.StringBuilder sb; - - sb = new System.Text.StringBuilder("EBCOTRateAllocator wall clock times:\n"); - sb.Append(" initialization: "); - sb.Append(initTime); - sb.Append(" ms\n"); - sb.Append(" layer building: "); - sb.Append(buildTime); - sb.Append(" ms\n"); - sb.Append(" final writing: "); - sb.Append(writeTime); - sb.Append(" ms"); - FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.INFO, sb.ToString()); - //UPGRADE_NOTE: Call to 'super.finalize()' was removed. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1124'" - } -#endif - /// Runs the rate allocation algorithm and writes the data to the bit - /// stream writer object provided to the constructor. - /// - /// - public override void runAndWrite() - { - //Now, run the rate allocation - buildAndWriteLayers(); - } - - /// Initializes the layers array. This must be called after the main header - /// has been entirely written or simulated, so as to take its overhead into - /// account. This method will get all the code-blocks and then initialize - /// the target bitrates for each layer, according to the specifications. - /// - /// - public override void initialize() - { - int n, i, l; - int ho; // The header overhead (in bytes) - float np; // The number of pixels divided by the number of bits per byte - double ls; // Step for log-scale - double basebytes; - int lastbytes, newbytes, nextbytes; - int loopnlyrs; - int minlsz; // The minimum allowable number of bytes in a layer - int totenclength; - int maxpkt; - int numTiles = src.getNumTiles(); - int numComps = src.NumComps; - int numLvls; - int avgPktLen; -#if DO_TIMING - long stime = 0L; -#endif - // Start by getting all the code-blocks, we need this in order to have - // an idea of the total encoded bitrate. - getAllCodeBlocks(); - -#if DO_TIMING - stime = (System.DateTime.Now.Ticks - 621355968000000000) / 10000; -#endif - - // Now get the total encoded length - totenclength = RDSlopesRates[0]; // all the encoded data - // Make a rough estimation of the packet head overhead, as 2 bytes per - // packet in average (plus EPH / SOP) , and add that to the total - // encoded length - for (int t = 0; t < numTiles; t++) - { - avgPktLen = 2; - // Add SOP length if set - if (((System.String)encSpec.sops.getTileDef(t)).ToUpper().Equals("on".ToUpper())) - { - avgPktLen += CSJ2K.j2k.codestream.Markers.SOP_LENGTH; - } - // Add EPH length if set - if (((System.String)encSpec.ephs.getTileDef(t)).ToUpper().Equals("on".ToUpper())) - { - avgPktLen += CSJ2K.j2k.codestream.Markers.EPH_LENGTH; - } - - for (int c = 0; c < numComps; c++) - { - numLvls = src.getAnSubbandTree(t, c).resLvl + 1; - if (!src.precinctPartitionUsed(c, t)) - { - // Precinct partition is not used so there is only - // one packet per resolution level/layer - totenclength += num_Layers * avgPktLen * numLvls; - } - else - { - // Precinct partition is used so for each - // component/tile/resolution level, we get the maximum - // number of packets - for (int rl = 0; rl < numLvls; rl++) - { - maxpkt = numPrec[t][c][rl].x * numPrec[t][c][rl].y; - totenclength += num_Layers * avgPktLen * maxpkt; - } - } - } // End loop on components - } // End loop on tiles - - // If any layer specifies more than 'totenclength' as its target - // length then 'totenclength' is used. This is to prevent that - // estimated layers get excessively large target lengths due to an - // excessively large target bitrate. At the end the last layer is set - // to the target length corresponding to the overall target - // bitrate. Thus, 'totenclength' can not limit the total amount of - // encoded data, as intended. - - ho = headEnc.Length; - np = src.ImgWidth * src.ImgHeight / 8f; - - // SOT marker must be taken into account - for (int t = 0; t < numTiles; t++) - { - headEnc.reset(); - headEnc.encodeTilePartHeader(0, t); - ho += headEnc.Length; - } - - layers = new EBCOTLayer[num_Layers]; - for (n = num_Layers - 1; n >= 0; n--) - { - layers[n] = new EBCOTLayer(); - } - - minlsz = 0; // To keep compiler happy - for (int t = 0; t < numTiles; t++) - { - for (int c = 0; c < numComps; c++) - { - numLvls = src.getAnSubbandTree(t, c).resLvl + 1; - - if (!src.precinctPartitionUsed(c, t)) - { - // Precinct partition is not used - minlsz += MIN_AVG_PACKET_SZ * numLvls; - } - else - { - // Precinct partition is used - for (int rl = 0; rl < numLvls; rl++) - { - maxpkt = numPrec[t][c][rl].x * numPrec[t][c][rl].y; - minlsz += MIN_AVG_PACKET_SZ * maxpkt; - } - } - } // End loop on components - } // End loop on tiles - - // Initialize layers - n = 0; - i = 0; - lastbytes = 0; - - while (n < num_Layers - 1) - { - // At an optimized layer - basebytes = System.Math.Floor(lyrSpec.getTargetBitrate(i) * np); - if (i < lyrSpec.NOptPoints - 1) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - nextbytes = (int)(lyrSpec.getTargetBitrate(i + 1) * np); - // Limit target length to 'totenclength' - if (nextbytes > totenclength) - nextbytes = totenclength; - } - else - { - nextbytes = 1; - } - loopnlyrs = lyrSpec.getExtraLayers(i) + 1; - ls = System.Math.Exp(System.Math.Log((double)nextbytes / basebytes) / loopnlyrs); - layers[n].optimize = true; - for (l = 0; l < loopnlyrs; l++) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - newbytes = (int)basebytes - lastbytes - ho; - if (newbytes < minlsz) - { - // Skip layer (too small) - basebytes *= ls; - num_Layers--; - continue; - } - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - lastbytes = (int)basebytes - ho; - layers[n].maxBytes = lastbytes; - basebytes *= ls; - n++; - } - i++; // Goto next optimization point - } - - // Ensure minimum size of last layer (this one determines overall - // bitrate) - n = num_Layers - 2; - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - nextbytes = (int)(lyrSpec.TotBitrate * np) - ho; - newbytes = nextbytes - ((n >= 0) ? layers[n].maxBytes : 0); - while (newbytes < minlsz) - { - if (num_Layers == 1) - { - if (newbytes <= 0) - { - throw new System.ArgumentException("Overall target bitrate too " + "low, given the current " + "bit stream header overhead"); - } - break; - } - // Delete last layer - num_Layers--; - n--; - newbytes = nextbytes - ((n >= 0) ? layers[n].maxBytes : 0); - } - // Set last layer to the overall target bitrate - n++; - layers[n].maxBytes = nextbytes; - layers[n].optimize = true; - - // Re-initialize progression order changes if needed Default values - Progression[] prog1; // prog2 removed - prog1 = (Progression[])encSpec.pocs.getDefault(); - int nValidProg = prog1.Length; - for (int prg = 0; prg < prog1.Length; prg++) - { - if (prog1[prg].lye > num_Layers) - { - prog1[prg].lye = num_Layers; - } - } - if (nValidProg == 0) - { - throw new System.ApplicationException("Unable to initialize rate allocator: No " + "default progression type has been defined."); - } - - // Tile specific values - for (int t = 0; t < numTiles; t++) - { - if (encSpec.pocs.isTileSpecified(t)) - { - prog1 = (Progression[])encSpec.pocs.getTileDef(t); - nValidProg = prog1.Length; - for (int prg = 0; prg < prog1.Length; prg++) - { - if (prog1[prg].lye > num_Layers) - { - prog1[prg].lye = num_Layers; - } - } - if (nValidProg == 0) - { - throw new System.ApplicationException("Unable to initialize rate allocator:" + " No default progression type has been " + "defined for tile " + t); - } - } - } // End loop on tiles - -#if DO_TIMING - initTime += (System.DateTime.Now.Ticks - 621355968000000000) / 10000 - stime; -#endif - } - - /// This method gets all the coded code-blocks from the EBCOT entropy coder - /// for every component and every tile. Each coded code-block is stored in - /// a 5D array according to the component, the resolution level, the tile, - /// the subband it belongs and its position in the subband. - /// - ///

    For each code-block, the valid slopes are computed and converted - /// into the mantissa-exponent representation. - /// - ///

    - private void getAllCodeBlocks() - { - - int numComps, numTiles; // numBytes removed - int c, r, t, s, sidx, k; - //int slope; - SubbandAn subb; - CBlkRateDistStats ccb = null; - Coord ncblks = null; - int last_sidx; - float fslope; -#if DO_TIMING - long stime = 0L; -#endif - maxSlope = 0f; - minSlope = System.Single.MaxValue; - - //Get the number of components and tiles - numComps = src.NumComps; - numTiles = src.getNumTiles(); - - SubbandAn root, sb; - int cblkToEncode = 0; - int nEncCblk = 0; - ProgressWatch pw = FacilityManager.ProgressWatch; - - //Get all coded code-blocks Goto first tile - src.setTile(0, 0); - for (t = 0; t < numTiles; t++) - { - //loop on tiles - nEncCblk = 0; - cblkToEncode = 0; - for (c = 0; c < numComps; c++) - { - root = src.getAnSubbandTree(t, c); - for (r = 0; r <= root.resLvl; r++) - { - if (r == 0) - { - sb = (SubbandAn)root.getSubbandByIdx(0, 0); - if (sb != null) - cblkToEncode += sb.numCb.x * sb.numCb.y; - } - else - { - sb = (SubbandAn)root.getSubbandByIdx(r, 1); - if (sb != null) - cblkToEncode += sb.numCb.x * sb.numCb.y; - sb = (SubbandAn)root.getSubbandByIdx(r, 2); - if (sb != null) - cblkToEncode += sb.numCb.x * sb.numCb.y; - sb = (SubbandAn)root.getSubbandByIdx(r, 3); - if (sb != null) - cblkToEncode += sb.numCb.x * sb.numCb.y; - } - } - } - if (pw != null) - { - pw.initProgressWatch(0, cblkToEncode, "Encoding tile " + t + "..."); - } - - for (c = 0; c < numComps; c++) - { - //loop on components - - //Get next coded code-block coordinates - while ((ccb = src.getNextCodeBlock(c, ccb)) != null) - { -#if DO_TIMING - stime = (System.DateTime.Now.Ticks - 621355968000000000) / 10000; -#endif - - if (pw != null) - { - nEncCblk++; - pw.updateProgressWatch(nEncCblk, null); - } - - subb = ccb.sb; - - //Get the coded code-block resolution level index - r = subb.resLvl; - - //Get the coded code-block subband index - s = subb.sbandIdx; - - //Get the number of blocks in the current subband - ncblks = subb.numCb; - - // Add code-block contribution to summary R-D table - // RDSlopesRates - last_sidx = -1; - for (k = ccb.nVldTrunc - 1; k >= 0; k--) - { - fslope = ccb.truncSlopes[k]; - if (fslope > maxSlope) - maxSlope = fslope; - if (fslope < minSlope) - minSlope = fslope; - sidx = getLimitedSIndexFromSlope(fslope); - for (; sidx > last_sidx; sidx--) - { - RDSlopesRates[sidx] += ccb.truncRates[ccb.truncIdxs[k]]; - } - last_sidx = getLimitedSIndexFromSlope(fslope); - } - - //Fills code-blocks array - cblks[t][c][r][s][(ccb.m * ncblks.x) + ccb.n] = ccb; - ccb = null; - -#if DO_TIMING - initTime += (System.DateTime.Now.Ticks - 621355968000000000) / 10000 - stime; -#endif - } - } - - if (pw != null) - { - pw.terminateProgressWatch(); - } - - //Goto next tile - if (t < numTiles - 1) - //not at last tile - src.nextTile(); - } - } - - /// This method builds all the bit stream layers and then writes them to - /// the output bit stream. Firstly it builds all the layers by computing - /// the threshold according to the layer target bit-rate, and then it - /// writes the layer bit streams according to the progressive type. - /// - /// - private void buildAndWriteLayers() - { - int nPrec = 0; - int maxBytes, actualBytes; - float rdThreshold; - SubbandAn sb; - //float threshold; - BitOutputBuffer hBuff = null; - byte[] bBuff = null; - int[] tileLengths; // Length of each tile - int tmp; - bool sopUsed; // Should SOP markers be used ? - bool ephUsed; // Should EPH markers be used ? - int nc = src.NumComps; - int nt = src.getNumTiles(); - int mrl; -#if DO_TIMING - long stime = 0L; - stime = (System.DateTime.Now.Ticks - 621355968000000000) / 10000; -#endif - - // Start with the maximum slope - rdThreshold = maxSlope; - - tileLengths = new int[nt]; - actualBytes = 0; - - // +------------------------------+ - // | First we build the layers | - // +------------------------------+ - // Bitstream is simulated to know tile length - for (int l = 0; l < num_Layers; l++) - { - //loop on layers - - maxBytes = layers[l].maxBytes; - if (layers[l].optimize) - { - rdThreshold = optimizeBitstreamLayer(l, rdThreshold, maxBytes, actualBytes); - } - else - { - if (l <= 0 || l >= num_Layers - 1) - { - throw new System.ArgumentException("The first and the" + " last layer " + "thresholds" + " must be optimized"); - } - rdThreshold = estimateLayerThreshold(maxBytes, layers[l - 1]); - } - - for (int t = 0; t < nt; t++) - { - //loop on tiles - if (l == 0) - { - // Tile header - headEnc.reset(); - headEnc.encodeTilePartHeader(0, t); - tileLengths[t] += headEnc.Length; - } - - for (int c = 0; c < nc; c++) - { - //loop on components - - // set boolean sopUsed here (SOP markers) - sopUsed = ((System.String)encSpec.sops.getTileDef(t)).ToUpper().Equals("on".ToUpper()); - // set boolean ephUsed here (EPH markers) - ephUsed = ((System.String)encSpec.ephs.getTileDef(t)).ToUpper().Equals("on".ToUpper()); - - // Go to LL band - sb = src.getAnSubbandTree(t, c); - mrl = sb.resLvl + 1; - - while (sb.subb_LL != null) - { - sb = sb.subb_LL; - } - - for (int r = 0; r < mrl; r++) - { - // loop on resolution levels - - nPrec = numPrec[t][c][r].x * numPrec[t][c][r].y; - for (int p = 0; p < nPrec; p++) - { - // loop on precincts - - findTruncIndices(l, c, r, t, sb, rdThreshold, p); - - hBuff = pktEnc.encodePacket(l + 1, c, r, t, cblks[t][c][r], truncIdxs[t][l][c][r], hBuff, bBuff, p); - if (pktEnc.PacketWritable) - { - tmp = bsWriter.writePacketHead(hBuff.Buffer, hBuff.Length, true, sopUsed, ephUsed); - tmp += bsWriter.writePacketBody(pktEnc.LastBodyBuf, pktEnc.LastBodyLen, true, pktEnc.ROIinPkt, pktEnc.ROILen); - actualBytes += tmp; - tileLengths[t] += tmp; - } - } // End loop on precincts - sb = sb.parentband; - } // End loop on resolution levels - } // End loop on components - } // end loop on tiles - layers[l].rdThreshold = rdThreshold; - layers[l].actualBytes = actualBytes; - } // end loop on layers - -#if DO_TIMING - buildTime += (System.DateTime.Now.Ticks - 621355968000000000) / 10000 - stime; - stime = (System.DateTime.Now.Ticks - 621355968000000000) / 10000; -#endif - // +--------------------------------------------------+ - // | Write tiles according to their Progression order | - // +--------------------------------------------------+ - // Reset the packet encoder before writing all packets - pktEnc.reset(); - Progression[] prog; // Progression(s) in each tile - int cs, ce, rs, re, lye; - - int[] mrlc = new int[nc]; - for (int t = 0; t < nt; t++) - { - //loop on tiles - //int[][] lysA; // layer index start for each component and - // resolution level - int[][] lys = new int[nc][]; - for (int c = 0; c < nc; c++) - { - mrlc[c] = src.getAnSubbandTree(t, c).resLvl; - lys[c] = new int[mrlc[c] + 1]; - } - - // Tile header - headEnc.reset(); - headEnc.encodeTilePartHeader(tileLengths[t], t); - bsWriter.commitBitstreamHeader(headEnc); - prog = (Progression[])encSpec.pocs.getTileDef(t); - - for (int prg = 0; prg < prog.Length; prg++) - { - // Loop on progression - lye = prog[prg].lye; - cs = prog[prg].cs; - ce = prog[prg].ce; - rs = prog[prg].rs; - re = prog[prg].re; - - switch (prog[prg].type) - { - - case CSJ2K.j2k.codestream.ProgressionType.RES_LY_COMP_POS_PROG: - writeResLyCompPos(t, rs, re, cs, ce, lys, lye); - break; - - case CSJ2K.j2k.codestream.ProgressionType.LY_RES_COMP_POS_PROG: - writeLyResCompPos(t, rs, re, cs, ce, lys, lye); - break; - - case CSJ2K.j2k.codestream.ProgressionType.POS_COMP_RES_LY_PROG: - writePosCompResLy(t, rs, re, cs, ce, lys, lye); - break; - - case CSJ2K.j2k.codestream.ProgressionType.COMP_POS_RES_LY_PROG: - writeCompPosResLy(t, rs, re, cs, ce, lys, lye); - break; - - case CSJ2K.j2k.codestream.ProgressionType.RES_POS_COMP_LY_PROG: - writeResPosCompLy(t, rs, re, cs, ce, lys, lye); - break; - - default: - throw new System.ApplicationException("Unsupported bit stream progression type"); - - } // switch on progression - - // Update next first layer index - for (int c = cs; c < ce; c++) - for (int r = rs; r < re; r++) - { - if (r > mrlc[c]) - continue; - lys[c][r] = lye; - } - } // End loop on progression - } // End loop on tiles - -#if DO_TIMING - writeTime += (System.DateTime.Now.Ticks - 621355968000000000) / 10000 - stime; -#endif - } - - /// Write a piece of bit stream according to the - /// RES_LY_COMP_POS_PROG progression mode and between given bounds - /// - /// - /// Tile index. - /// - /// - /// First resolution level index. - /// - /// - /// Last resolution level index. - /// - /// - /// First component index. - /// - /// - /// Last component index. - /// - /// - /// First layer index for each component and resolution. - /// - /// - /// Index of the last layer. - /// - /// - public virtual void writeResLyCompPos(int t, int rs, int re, int cs, int ce, int[][] lys, int lye) - { - - bool sopUsed; // Should SOP markers be used ? - bool ephUsed; // Should EPH markers be used ? - int nc = src.NumComps; - int[] mrl = new int[nc]; - SubbandAn sb; - float threshold; - BitOutputBuffer hBuff = null; - byte[] bBuff = null; - int nPrec = 0; - - // Max number of resolution levels in the tile - int maxResLvl = 0; - for (int c = 0; c < nc; c++) - { - mrl[c] = src.getAnSubbandTree(t, c).resLvl; - if (mrl[c] > maxResLvl) - maxResLvl = mrl[c]; - } - - int minlys; // minimum layer start index of each component - - for (int r = rs; r < re; r++) - { - //loop on resolution levels - if (r > maxResLvl) - continue; - - minlys = 100000; - for (int c = cs; c < ce; c++) - { - if (r < lys[c].Length && lys[c][r] < minlys) - { - minlys = lys[c][r]; - } - } - - for (int l = minlys; l < lye; l++) - { - //loop on layers - for (int c = cs; c < ce; c++) - { - //loop on components - if (r >= lys[c].Length) - continue; - if (l < lys[c][r]) - continue; - - // If no more decomposition levels for this component - if (r > mrl[c]) - continue; - - nPrec = numPrec[t][c][r].x * numPrec[t][c][r].y; - for (int p = 0; p < nPrec; p++) - { - // loop on precincts - - // set boolean sopUsed here (SOP markers) - sopUsed = ((System.String)encSpec.sops.getTileDef(t)).Equals("on"); - // set boolean ephUsed here (EPH markers) - ephUsed = ((System.String)encSpec.ephs.getTileDef(t)).Equals("on"); - - sb = src.getAnSubbandTree(t, c); - for (int i = mrl[c]; i > r; i--) - { - sb = sb.subb_LL; - } - - threshold = layers[l].rdThreshold; - findTruncIndices(l, c, r, t, sb, threshold, p); - - hBuff = pktEnc.encodePacket(l + 1, c, r, t, cblks[t][c][r], truncIdxs[t][l][c][r], hBuff, bBuff, p); - - if (pktEnc.PacketWritable) - { - bsWriter.writePacketHead(hBuff.Buffer, hBuff.Length, false, sopUsed, ephUsed); - bsWriter.writePacketBody(pktEnc.LastBodyBuf, pktEnc.LastBodyLen, false, pktEnc.ROIinPkt, pktEnc.ROILen); - } - } // End loop on precincts - } // End loop on components - } // End loop on layers - } // End loop on resolution levels - } - - /// Write a piece of bit stream according to the - /// LY_RES_COMP_POS_PROG progression mode and between given bounds - /// - /// - /// Tile index. - /// - /// - /// First resolution level index. - /// - /// - /// Last resolution level index. - /// - /// - /// First component index. - /// - /// - /// Last component index. - /// - /// - /// First layer index for each component and resolution. - /// - /// - /// Index of the last layer. - /// - /// - public virtual void writeLyResCompPos(int t, int rs, int re, int cs, int ce, int[][] lys, int lye) - { - - bool sopUsed; // Should SOP markers be used ? - bool ephUsed; // Should EPH markers be used ? - int nc = src.NumComps; - int mrl; - SubbandAn sb; - float threshold; - BitOutputBuffer hBuff = null; - byte[] bBuff = null; - int nPrec = 0; - - int minlys = 100000; // minimum layer start index of each component - for (int c = cs; c < ce; c++) - { - for (int r = 0; r < lys.Length; r++) - { - if (lys[c] != null && r < lys[c].Length && lys[c][r] < minlys) - { - minlys = lys[c][r]; - } - } - } - - for (int l = minlys; l < lye; l++) - { - // loop on layers - for (int r = rs; r < re; r++) - { - // loop on resolution level - for (int c = cs; c < ce; c++) - { - // loop on components - mrl = src.getAnSubbandTree(t, c).resLvl; - if (r > mrl) - continue; - if (r >= lys[c].Length) - continue; - if (l < lys[c][r]) - continue; - - nPrec = numPrec[t][c][r].x * numPrec[t][c][r].y; - for (int p = 0; p < nPrec; p++) - { - // loop on precincts - - // set boolean sopUsed here (SOP markers) - sopUsed = ((System.String)encSpec.sops.getTileDef(t)).Equals("on"); - // set boolean ephUsed here (EPH markers) - ephUsed = ((System.String)encSpec.ephs.getTileDef(t)).Equals("on"); - - sb = src.getAnSubbandTree(t, c); - for (int i = mrl; i > r; i--) - { - sb = sb.subb_LL; - } - - threshold = layers[l].rdThreshold; - findTruncIndices(l, c, r, t, sb, threshold, p); - - hBuff = pktEnc.encodePacket(l + 1, c, r, t, cblks[t][c][r], truncIdxs[t][l][c][r], hBuff, bBuff, p); - - if (pktEnc.PacketWritable) - { - bsWriter.writePacketHead(hBuff.Buffer, hBuff.Length, false, sopUsed, ephUsed); - bsWriter.writePacketBody(pktEnc.LastBodyBuf, pktEnc.LastBodyLen, false, pktEnc.ROIinPkt, pktEnc.ROILen); - } - } // end loop on precincts - } // end loop on components - } // end loop on resolution levels - } // end loop on layers - } - - /// Write a piece of bit stream according to the - /// COMP_POS_RES_LY_PROG progression mode and between given bounds - /// - /// - /// Tile index. - /// - /// - /// First resolution level index. - /// - /// - /// Last resolution level index. - /// - /// - /// First component index. - /// - /// - /// Last component index. - /// - /// - /// First layer index for each component and resolution. - /// - /// - /// Index of the last layer. - /// - /// - public virtual void writePosCompResLy(int t, int rs, int re, int cs, int ce, int[][] lys, int lye) - { - - bool sopUsed; // Should SOP markers be used ? - bool ephUsed; // Should EPH markers be used ? - int nc = src.NumComps; - int mrl; - SubbandAn sb; - float threshold; - BitOutputBuffer hBuff = null; - byte[] bBuff = null; - - // Computes current tile offset in the reference grid - Coord nTiles = src.getNumTiles(null); - Coord tileI = src.getTile(null); - int x0siz = src.ImgULX; - int y0siz = src.ImgULY; - int xsiz = x0siz + src.ImgWidth; - int ysiz = y0siz + src.ImgHeight; - int xt0siz = src.TilePartULX; - int yt0siz = src.TilePartULY; - int xtsiz = src.NomTileWidth; - int ytsiz = src.NomTileHeight; - int tx0 = (tileI.x == 0) ? x0siz : xt0siz + tileI.x * xtsiz; - int ty0 = (tileI.y == 0) ? y0siz : yt0siz + tileI.y * ytsiz; - int tx1 = (tileI.x != nTiles.x - 1) ? xt0siz + (tileI.x + 1) * xtsiz : xsiz; - int ty1 = (tileI.y != nTiles.y - 1) ? yt0siz + (tileI.y + 1) * ytsiz : ysiz; - - // Get precinct information (number,distance between two consecutive - // precincts in the reference grid) in each component and resolution - // level - PrecInfo prec; // temporary variable - int p; // Current precinct index - int gcd_x = 0; // Horiz. distance between 2 precincts in the ref. grid - int gcd_y = 0; // Vert. distance between 2 precincts in the ref. grid - int nPrec = 0; // Total number of found precincts - int[][] nextPrec = new int[ce][]; // Next precinct index in each - // component and resolution level - int minlys = 100000; // minimum layer start index of each component - int minx = tx1; // Horiz. offset of the second precinct in the - // reference grid - int miny = ty1; // Vert. offset of the second precinct in the - // reference grid. - int maxx = tx0; // Max. horiz. offset of precincts in the ref. grid - int maxy = ty0; // Max. vert. offset of precincts in the ref. grid - for (int c = cs; c < ce; c++) - { - mrl = src.getAnSubbandTree(t, c).resLvl; - nextPrec[c] = new int[mrl + 1]; - for (int r = rs; r < re; r++) - { - if (r > mrl) - continue; - if (r < lys[c].Length && lys[c][r] < minlys) - { - minlys = lys[c][r]; - } - p = numPrec[t][c][r].y * numPrec[t][c][r].x - 1; - for (; p >= 0; p--) - { - prec = pktEnc.getPrecInfo(t, c, r, p); - if (prec.rgulx != tx0) - { - if (prec.rgulx < minx) - minx = prec.rgulx; - if (prec.rgulx > maxx) - maxx = prec.rgulx; - } - if (prec.rguly != ty0) - { - if (prec.rguly < miny) - miny = prec.rguly; - if (prec.rguly > maxy) - maxy = prec.rguly; - } - - if (nPrec == 0) - { - gcd_x = prec.rgw; - gcd_y = prec.rgh; - } - else - { - gcd_x = MathUtil.gcd(gcd_x, prec.rgw); - gcd_y = MathUtil.gcd(gcd_y, prec.rgh); - } - nPrec++; - } // precincts - } // resolution levels - } // components - - if (nPrec == 0) - { - throw new System.ApplicationException("Image cannot have no precinct"); - } - - int pyend = (maxy - miny) / gcd_y + 1; - int pxend = (maxx - minx) / gcd_x + 1; - int y = ty0; - int x = tx0; - for (int py = 0; py <= pyend; py++) - { - // Vertical precincts - for (int px = 0; px <= pxend; px++) - { - // Horiz. precincts - for (int c = cs; c < ce; c++) - { - // Components - mrl = src.getAnSubbandTree(t, c).resLvl; - for (int r = rs; r < re; r++) - { - // Resolution levels - if (r > mrl) - continue; - if (nextPrec[c][r] >= numPrec[t][c][r].x * numPrec[t][c][r].y) - { - continue; - } - prec = pktEnc.getPrecInfo(t, c, r, nextPrec[c][r]); - if ((prec.rgulx != x) || (prec.rguly != y)) - { - continue; - } - for (int l = minlys; l < lye; l++) - { - // Layers - if (r >= lys[c].Length) - continue; - if (l < lys[c][r]) - continue; - - // set boolean sopUsed here (SOP markers) - sopUsed = ((System.String)encSpec.sops.getTileDef(t)).Equals("on"); - // set boolean ephUsed here (EPH markers) - ephUsed = ((System.String)encSpec.ephs.getTileDef(t)).Equals("on"); - - sb = src.getAnSubbandTree(t, c); - for (int i = mrl; i > r; i--) - { - sb = sb.subb_LL; - } - - threshold = layers[l].rdThreshold; - findTruncIndices(l, c, r, t, sb, threshold, nextPrec[c][r]); - - hBuff = pktEnc.encodePacket(l + 1, c, r, t, cblks[t][c][r], truncIdxs[t][l][c][r], hBuff, bBuff, nextPrec[c][r]); - - if (pktEnc.PacketWritable) - { - bsWriter.writePacketHead(hBuff.Buffer, hBuff.Length, false, sopUsed, ephUsed); - bsWriter.writePacketBody(pktEnc.LastBodyBuf, pktEnc.LastBodyLen, false, pktEnc.ROIinPkt, pktEnc.ROILen); - } - } // layers - nextPrec[c][r]++; - } // Resolution levels - } // Components - if (px != pxend) - { - x = minx + px * gcd_x; - } - else - { - x = tx0; - } - } // Horizontal precincts - if (py != pyend) - { - y = miny + py * gcd_y; - } - else - { - y = ty0; - } - } // Vertical precincts - - // Check that all precincts have been written - for (int c = cs; c < ce; c++) - { - mrl = src.getAnSubbandTree(t, c).resLvl; - for (int r = rs; r < re; r++) - { - if (r > mrl) - continue; - if (nextPrec[c][r] < numPrec[t][c][r].x * numPrec[t][c][r].y - 1) - { - throw new System.ApplicationException("JJ2000 bug: One precinct at least has " + "not been written for resolution level " + r + " of component " + c + " in tile " + t + "."); - } - } - } - } - - /// Write a piece of bit stream according to the - /// COMP_POS_RES_LY_PROG progression mode and between given bounds - /// - /// - /// Tile index. - /// - /// - /// First resolution level index. - /// - /// - /// Last resolution level index. - /// - /// - /// First component index. - /// - /// - /// Last component index. - /// - /// - /// First layer index for each component and resolution. - /// - /// - /// Index of the last layer. - /// - /// - public virtual void writeCompPosResLy(int t, int rs, int re, int cs, int ce, int[][] lys, int lye) - { - - bool sopUsed; // Should SOP markers be used ? - bool ephUsed; // Should EPH markers be used ? - int nc = src.NumComps; - int mrl; - SubbandAn sb; - float threshold; - BitOutputBuffer hBuff = null; - byte[] bBuff = null; - - // Computes current tile offset in the reference grid - Coord nTiles = src.getNumTiles(null); - Coord tileI = src.getTile(null); - int x0siz = src.ImgULX; - int y0siz = src.ImgULY; - int xsiz = x0siz + src.ImgWidth; - int ysiz = y0siz + src.ImgHeight; - int xt0siz = src.TilePartULX; - int yt0siz = src.TilePartULY; - int xtsiz = src.NomTileWidth; - int ytsiz = src.NomTileHeight; - int tx0 = (tileI.x == 0) ? x0siz : xt0siz + tileI.x * xtsiz; - int ty0 = (tileI.y == 0) ? y0siz : yt0siz + tileI.y * ytsiz; - int tx1 = (tileI.x != nTiles.x - 1) ? xt0siz + (tileI.x + 1) * xtsiz : xsiz; - int ty1 = (tileI.y != nTiles.y - 1) ? yt0siz + (tileI.y + 1) * ytsiz : ysiz; - - // Get precinct information (number,distance between two consecutive - // precincts in the reference grid) in each component and resolution - // level - PrecInfo prec; // temporary variable - int p; // Current precinct index - int gcd_x = 0; // Horiz. distance between 2 precincts in the ref. grid - int gcd_y = 0; // Vert. distance between 2 precincts in the ref. grid - int nPrec = 0; // Total number of found precincts - int[][] nextPrec = new int[ce][]; // Next precinct index in each - // component and resolution level - int minlys = 100000; // minimum layer start index of each component - int minx = tx1; // Horiz. offset of the second precinct in the - // reference grid - int miny = ty1; // Vert. offset of the second precinct in the - // reference grid. - int maxx = tx0; // Max. horiz. offset of precincts in the ref. grid - int maxy = ty0; // Max. vert. offset of precincts in the ref. grid - for (int c = cs; c < ce; c++) - { - mrl = src.getAnSubbandTree(t, c).resLvl; - for (int r = rs; r < re; r++) - { - if (r > mrl) - continue; - nextPrec[c] = new int[mrl + 1]; - if (r < lys[c].Length && lys[c][r] < minlys) - { - minlys = lys[c][r]; - } - p = numPrec[t][c][r].y * numPrec[t][c][r].x - 1; - for (; p >= 0; p--) - { - prec = pktEnc.getPrecInfo(t, c, r, p); - if (prec.rgulx != tx0) - { - if (prec.rgulx < minx) - minx = prec.rgulx; - if (prec.rgulx > maxx) - maxx = prec.rgulx; - } - if (prec.rguly != ty0) - { - if (prec.rguly < miny) - miny = prec.rguly; - if (prec.rguly > maxy) - maxy = prec.rguly; - } - - if (nPrec == 0) - { - gcd_x = prec.rgw; - gcd_y = prec.rgh; - } - else - { - gcd_x = MathUtil.gcd(gcd_x, prec.rgw); - gcd_y = MathUtil.gcd(gcd_y, prec.rgh); - } - nPrec++; - } // precincts - } // resolution levels - } // components - - if (nPrec == 0) - { - throw new System.ApplicationException("Image cannot have no precinct"); - } - - int pyend = (maxy - miny) / gcd_y + 1; - int pxend = (maxx - minx) / gcd_x + 1; - int y; - int x; - for (int c = cs; c < ce; c++) - { - // Loop on components - y = ty0; - x = tx0; - mrl = src.getAnSubbandTree(t, c).resLvl; - for (int py = 0; py <= pyend; py++) - { - // Vertical precincts - for (int px = 0; px <= pxend; px++) - { - // Horiz. precincts - for (int r = rs; r < re; r++) - { - // Resolution levels - if (r > mrl) - continue; - if (nextPrec[c][r] >= numPrec[t][c][r].x * numPrec[t][c][r].y) - { - continue; - } - prec = pktEnc.getPrecInfo(t, c, r, nextPrec[c][r]); - if ((prec.rgulx != x) || (prec.rguly != y)) - { - continue; - } - - for (int l = minlys; l < lye; l++) - { - // Layers - if (r >= lys[c].Length) - continue; - if (l < lys[c][r]) - continue; - - // set boolean sopUsed here (SOP markers) - sopUsed = ((System.String)encSpec.sops.getTileDef(t)).Equals("on"); - // set boolean ephUsed here (EPH markers) - ephUsed = ((System.String)encSpec.ephs.getTileDef(t)).Equals("on"); - - sb = src.getAnSubbandTree(t, c); - for (int i = mrl; i > r; i--) - { - sb = sb.subb_LL; - } - - threshold = layers[l].rdThreshold; - findTruncIndices(l, c, r, t, sb, threshold, nextPrec[c][r]); - - hBuff = pktEnc.encodePacket(l + 1, c, r, t, cblks[t][c][r], truncIdxs[t][l][c][r], hBuff, bBuff, nextPrec[c][r]); - - if (pktEnc.PacketWritable) - { - bsWriter.writePacketHead(hBuff.Buffer, hBuff.Length, false, sopUsed, ephUsed); - bsWriter.writePacketBody(pktEnc.LastBodyBuf, pktEnc.LastBodyLen, false, pktEnc.ROIinPkt, pktEnc.ROILen); - } - } // Layers - nextPrec[c][r]++; - } // Resolution levels - if (px != pxend) - { - x = minx + px * gcd_x; - } - else - { - x = tx0; - } - } // Horizontal precincts - if (py != pyend) - { - y = miny + py * gcd_y; - } - else - { - y = ty0; - } - } // Vertical precincts - } // components - - // Check that all precincts have been written - for (int c = cs; c < ce; c++) - { - mrl = src.getAnSubbandTree(t, c).resLvl; - for (int r = rs; r < re; r++) - { - if (r > mrl) - continue; - if (nextPrec[c][r] < numPrec[t][c][r].x * numPrec[t][c][r].y - 1) - { - throw new System.ApplicationException("JJ2000 bug: One precinct at least has " + "not been written for resolution level " + r + " of component " + c + " in tile " + t + "."); - } - } - } - } - - /// Write a piece of bit stream according to the - /// RES_POS_COMP_LY_PROG progression mode and between given bounds - /// - /// - /// Tile index. - /// - /// - /// First resolution level index. - /// - /// - /// Last resolution level index. - /// - /// - /// First component index. - /// - /// - /// Last component index. - /// - /// - /// First layer index for each component and resolution. - /// - /// - /// Last layer index. - /// - /// - public virtual void writeResPosCompLy(int t, int rs, int re, int cs, int ce, int[][] lys, int lye) - { - - bool sopUsed; // Should SOP markers be used ? - bool ephUsed; // Should EPH markers be used ? - int nc = src.NumComps; - int mrl; - SubbandAn sb; - float threshold; - BitOutputBuffer hBuff = null; - byte[] bBuff = null; - - // Computes current tile offset in the reference grid - Coord nTiles = src.getNumTiles(null); - Coord tileI = src.getTile(null); - int x0siz = src.ImgULX; - int y0siz = src.ImgULY; - int xsiz = x0siz + src.ImgWidth; - int ysiz = y0siz + src.ImgHeight; - int xt0siz = src.TilePartULX; - int yt0siz = src.TilePartULY; - int xtsiz = src.NomTileWidth; - int ytsiz = src.NomTileHeight; - int tx0 = (tileI.x == 0) ? x0siz : xt0siz + tileI.x * xtsiz; - int ty0 = (tileI.y == 0) ? y0siz : yt0siz + tileI.y * ytsiz; - int tx1 = (tileI.x != nTiles.x - 1) ? xt0siz + (tileI.x + 1) * xtsiz : xsiz; - int ty1 = (tileI.y != nTiles.y - 1) ? yt0siz + (tileI.y + 1) * ytsiz : ysiz; - - // Get precinct information (number,distance between two consecutive - // precincts in the reference grid) in each component and resolution - // level - PrecInfo prec; // temporary variable - int p; // Current precinct index - int gcd_x = 0; // Horiz. distance between 2 precincts in the ref. grid - int gcd_y = 0; // Vert. distance between 2 precincts in the ref. grid - int nPrec = 0; // Total number of found precincts - int[][] nextPrec = new int[ce][]; // Next precinct index in each - // component and resolution level - int minlys = 100000; // minimum layer start index of each component - int minx = tx1; // Horiz. offset of the second precinct in the - // reference grid - int miny = ty1; // Vert. offset of the second precinct in the - // reference grid. - int maxx = tx0; // Max. horiz. offset of precincts in the ref. grid - int maxy = ty0; // Max. vert. offset of precincts in the ref. grid - for (int c = cs; c < ce; c++) - { - mrl = src.getAnSubbandTree(t, c).resLvl; - nextPrec[c] = new int[mrl + 1]; - for (int r = rs; r < re; r++) - { - if (r > mrl) - continue; - if (r < lys[c].Length && lys[c][r] < minlys) - { - minlys = lys[c][r]; - } - p = numPrec[t][c][r].y * numPrec[t][c][r].x - 1; - for (; p >= 0; p--) - { - prec = pktEnc.getPrecInfo(t, c, r, p); - if (prec.rgulx != tx0) - { - if (prec.rgulx < minx) - minx = prec.rgulx; - if (prec.rgulx > maxx) - maxx = prec.rgulx; - } - if (prec.rguly != ty0) - { - if (prec.rguly < miny) - miny = prec.rguly; - if (prec.rguly > maxy) - maxy = prec.rguly; - } - - if (nPrec == 0) - { - gcd_x = prec.rgw; - gcd_y = prec.rgh; - } - else - { - gcd_x = MathUtil.gcd(gcd_x, prec.rgw); - gcd_y = MathUtil.gcd(gcd_y, prec.rgh); - } - nPrec++; - } // precincts - } // resolution levels - } // components - - if (nPrec == 0) - { - throw new System.ApplicationException("Image cannot have no precinct"); - } - - int pyend = (maxy - miny) / gcd_y + 1; - int pxend = (maxx - minx) / gcd_x + 1; - int x, y; - for (int r = rs; r < re; r++) - { - // Resolution levels - y = ty0; - x = tx0; - for (int py = 0; py <= pyend; py++) - { - // Vertical precincts - for (int px = 0; px <= pxend; px++) - { - // Horiz. precincts - for (int c = cs; c < ce; c++) - { - // Components - mrl = src.getAnSubbandTree(t, c).resLvl; - if (r > mrl) - continue; - if (nextPrec[c][r] >= numPrec[t][c][r].x * numPrec[t][c][r].y) - { - continue; - } - prec = pktEnc.getPrecInfo(t, c, r, nextPrec[c][r]); - if ((prec.rgulx != x) || (prec.rguly != y)) - { - continue; - } - for (int l = minlys; l < lye; l++) - { - if (r >= lys[c].Length) - continue; - if (l < lys[c][r]) - continue; - - // set boolean sopUsed here (SOP markers) - sopUsed = ((System.String)encSpec.sops.getTileDef(t)).Equals("on"); - // set boolean ephUsed here (EPH markers) - ephUsed = ((System.String)encSpec.ephs.getTileDef(t)).Equals("on"); - - sb = src.getAnSubbandTree(t, c); - for (int i = mrl; i > r; i--) - { - sb = sb.subb_LL; - } - - threshold = layers[l].rdThreshold; - findTruncIndices(l, c, r, t, sb, threshold, nextPrec[c][r]); - - hBuff = pktEnc.encodePacket(l + 1, c, r, t, cblks[t][c][r], truncIdxs[t][l][c][r], hBuff, bBuff, nextPrec[c][r]); - - if (pktEnc.PacketWritable) - { - bsWriter.writePacketHead(hBuff.Buffer, hBuff.Length, false, sopUsed, ephUsed); - bsWriter.writePacketBody(pktEnc.LastBodyBuf, pktEnc.LastBodyLen, false, pktEnc.ROIinPkt, pktEnc.ROILen); - } - } // layers - nextPrec[c][r]++; - } // Components - if (px != pxend) - { - x = minx + px * gcd_x; - } - else - { - x = tx0; - } - } // Horizontal precincts - if (py != pyend) - { - y = miny + py * gcd_y; - } - else - { - y = ty0; - } - } // Vertical precincts - } // Resolution levels - - // Check that all precincts have been written - for (int c = cs; c < ce; c++) - { - mrl = src.getAnSubbandTree(t, c).resLvl; - for (int r = rs; r < re; r++) - { - if (r > mrl) - continue; - if (nextPrec[c][r] < numPrec[t][c][r].x * numPrec[t][c][r].y - 1) - { - throw new System.ApplicationException("JJ2000 bug: One precinct at least has " + "not been written for resolution level " + r + " of component " + c + " in tile " + t + "."); - } - } - } - } - - /// This function implements the rate-distortion optimization algorithm. - /// It saves the state of any previously generated bit-stream layers and - /// then simulate the formation of a new layer in the bit stream as often - /// as necessary to find the smallest rate-distortion threshold such that - /// the total number of bytes required to represent the layer does not - /// exceed `maxBytes' minus `prevBytes'. It then restores the state of any - /// previously generated bit-stream layers and returns the threshold. - /// - /// - /// The index of the current layer - /// - /// - /// The maximum admissible slope value. Normally the threshold - /// slope of the previous layer. - /// - /// - /// The maximum number of bytes that can be written. It - /// includes the length of the current layer bistream length and all the - /// previous layers bit streams. - /// - /// - /// The number of bytes of all the previous layers. - /// - /// - /// The value of the slope threshold. - /// - /// - private float optimizeBitstreamLayer(int layerIdx, float fmaxt, int maxBytes, int prevBytes) - { - - int nt; // The total number of tiles - int nc; // The total number of components - int numLvls; // The total number of resolution levels - int actualBytes; // Actual number of bytes for a layer - float fmint; // Minimum of the current threshold interval - float ft; // Current threshold - SubbandAn sb; // Current subband - BitOutputBuffer hBuff; // The packet head buffer - byte[] bBuff; // The packet body buffer - int sidx; // The index in the summary table - bool sopUsed; // Should SOP markers be used ? - bool ephUsed; // Should EPH markers be used ? - //int precinctIdx; // Precinct index for current packet - int nPrec; // Number of precincts in the current resolution level - - // Save the packet encoder state - pktEnc.save(); - - nt = src.getNumTiles(); - nc = src.NumComps; - hBuff = null; - bBuff = null; - - // Estimate the minimum slope to start with from the summary - // information in 'RDSlopesRates'. This is a real minimum since it - // does not include the packet head overhead, which is always - // non-zero. - - // Look for the summary entry that gives 'maxBytes' or more data - for (sidx = RD_SUMMARY_SIZE - 1; sidx > 0; sidx--) - { - if (RDSlopesRates[sidx] >= maxBytes) - { - break; - } - } - // Get the corresponding minimum slope - fmint = getSlopeFromSIndex(sidx); - // Ensure that it is smaller the maximum slope - if (fmint >= fmaxt) - { - sidx--; - fmint = getSlopeFromSIndex(sidx); - } - // If we are using the last entry of the summary, then that - // corresponds to all the data, Thus, set the minimum slope to 0. - if (sidx <= 0) - fmint = 0; - - // We look for the best threshold 'ft', which is the lowest threshold - // that generates no more than 'maxBytes' code bytes. - - // The search is done iteratively using a binary split algorithm. We - // start with 'fmaxt' as the maximum possible threshold, and 'fmint' - // as the minimum threshold. The threshold 'ft' is calculated as the - // middle point of 'fmaxt'-'fmint' interval. The 'fmaxt' or 'fmint' - // bounds are moved according to the number of bytes obtained from a - // simulation, where 'ft' is used as the threshold. - - // We stop whenever the interval is sufficiently small, and thus - // enough precision is achieved. - - // Initialize threshold as the middle point of the interval. - ft = (fmaxt + fmint) / 2f; - // If 'ft' reaches 'fmint' it means that 'fmaxt' and 'fmint' are so - // close that the average is 'fmint', due to rounding. Force it to - // 'fmaxt' instead, since 'fmint' is normally an exclusive lower - // bound. - if (ft <= fmint) - ft = fmaxt; - - do - { - // Get the number of bytes used by this layer, if 'ft' is the - // threshold, by simulation. - actualBytes = prevBytes; - src.setTile(0, 0); - - for (int t = 0; t < nt; t++) - { - for (int c = 0; c < nc; c++) - { - // set boolean sopUsed here (SOP markers) - sopUsed = ((System.String)encSpec.sops.getTileDef(t)).ToUpper().Equals("on".ToUpper()); - // set boolean ephUsed here (EPH markers) - ephUsed = ((System.String)encSpec.ephs.getTileDef(t)).ToUpper().Equals("on".ToUpper()); - - // Get LL subband - sb = (SubbandAn)src.getAnSubbandTree(t, c); - numLvls = sb.resLvl + 1; - sb = (SubbandAn)sb.getSubbandByIdx(0, 0); - //loop on resolution levels - for (int r = 0; r < numLvls; r++) - { - - nPrec = numPrec[t][c][r].x * numPrec[t][c][r].y; - for (int p = 0; p < nPrec; p++) - { - - findTruncIndices(layerIdx, c, r, t, sb, ft, p); - hBuff = pktEnc.encodePacket(layerIdx + 1, c, r, t, cblks[t][c][r], truncIdxs[t][layerIdx][c][r], hBuff, bBuff, p); - - if (pktEnc.PacketWritable) - { - bBuff = pktEnc.LastBodyBuf; - actualBytes += bsWriter.writePacketHead(hBuff.Buffer, hBuff.Length, true, sopUsed, ephUsed); - actualBytes += bsWriter.writePacketBody(bBuff, pktEnc.LastBodyLen, true, pktEnc.ROIinPkt, pktEnc.ROILen); - } - } // end loop on precincts - sb = sb.parentband; - } // End loop on resolution levels - } // End loop on components - } // End loop on tiles - - // Move the interval bounds according to simulation result - if (actualBytes > maxBytes) - { - // 'ft' is too low and generates too many bytes, make it the - // new minimum. - fmint = ft; - } - else - { - // 'ft' is too high and does not generate as many bytes as we - // are allowed too, make it the new maximum. - fmaxt = ft; - } - - // Update 'ft' for the new iteration as the middle point of the - // new interval. - ft = (fmaxt + fmint) / 2f; - // If 'ft' reaches 'fmint' it means that 'fmaxt' and 'fmint' are - // so close that the average is 'fmint', due to rounding. Force it - // to 'fmaxt' instead, since 'fmint' is normally an exclusive - // lower bound. - if (ft <= fmint) - ft = fmaxt; - - // Restore previous packet encoder state - pktEnc.restore(); - - // We continue to iterate, until the threshold reaches the upper - // limit of the interval, within a FLOAT_REL_PRECISION relative - // tolerance, or a FLOAT_ABS_PRECISION absolute tolerance. This is - // the sign that the interval is sufficiently small. - } - while (ft < fmaxt * (1f - FLOAT_REL_PRECISION) && ft < (fmaxt - FLOAT_ABS_PRECISION)); - - // If we have a threshold which is close to 0, set it to 0 so that - // everything is taken into the layer. This is to avoid not sending - // some least significant bit-planes in the lossless case. We use the - // FLOAT_ABS_PRECISION value as a measure of "close" to 0. - if (ft <= FLOAT_ABS_PRECISION) - { - ft = 0f; - } - else - { - // Otherwise make the threshold 'fmaxt', just to be sure that we - // will not send more bytes than allowed. - ft = fmaxt; - } - return ft; - } - - /// This function attempts to estimate a rate-distortion slope threshold - /// which will achieve a target number of code bytes close the - /// `targetBytes' value. - /// - /// - /// The target number of bytes for the current layer - /// - /// - /// The previous layer information. - /// - /// - /// The value of the slope threshold for the estimated layer - /// - /// - private float estimateLayerThreshold(int targetBytes, EBCOTLayer lastLayer) - { - float log_sl1; // The log of the first slope used for interpolation - float log_sl2; // The log of the second slope used for interpolation - float log_len1; // The log of the first length used for interpolation - float log_len2; // The log of the second length used for interpolation - float log_isl; // The log of the interpolated slope - float log_ilen; // Log of the interpolated length - float log_ab; // Log of actual bytes in last layer - int sidx; // Index into the summary R-D info array - float log_off; // The log of the offset proportion - int tlen; // The corrected target layer length - float lthresh; // The threshold of the last layer - float eth; // The estimated threshold - - // In order to estimate the threshold we base ourselves in the summary - // R-D info in RDSlopesRates. In order to use it we must compensate - // for the overhead of the packet heads. The proportion of overhead is - // estimated using the last layer simulation results. - - // NOTE: the model used in this method is that the slope varies - // linearly with the log of the rate (i.e. length). - - // NOTE: the model used in this method is that the distortion is - // proprotional to a power of the rate. Thus, the slope is also - // proportional to another power of the rate. This translates as the - // log of the slope varies linearly with the log of the rate, which is - // what we use. - - // 1) Find the offset of the length predicted from the summary R-D - // information, to the actual length by using the last layer. - - // We ensure that the threshold we use for estimation actually - // includes some data. - lthresh = lastLayer.rdThreshold; - if (lthresh > maxSlope) - lthresh = maxSlope; - // If the slope of the last layer is too small then we just include - // all the rest (not possible to do better). - if (lthresh < FLOAT_ABS_PRECISION) - return 0f; - sidx = getLimitedSIndexFromSlope(lthresh); - // If the index is outside of the summary info array use the last two, - // or first two, indexes, as appropriate - if (sidx >= RD_SUMMARY_SIZE - 1) - sidx = RD_SUMMARY_SIZE - 2; - - // Get the logs of the lengths and the slopes - - if (RDSlopesRates[sidx + 1] == 0) - { - // Pathological case, we can not use log of 0. Add - // RDSlopesRates[sidx]+1 bytes to the rates (just a crude simple - // solution to this rare case) - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - log_len1 = (float)System.Math.Log((RDSlopesRates[sidx] << 1) + 1); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - log_len2 = (float)System.Math.Log(RDSlopesRates[sidx] + 1); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - log_ab = (float)System.Math.Log(lastLayer.actualBytes + RDSlopesRates[sidx] + 1); - } - else - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - log_len1 = (float)System.Math.Log(RDSlopesRates[sidx]); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - log_len2 = (float)System.Math.Log(RDSlopesRates[sidx + 1]); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - log_ab = (float)System.Math.Log(lastLayer.actualBytes); - } - - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - log_sl1 = (float)System.Math.Log(getSlopeFromSIndex(sidx)); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - log_sl2 = (float)System.Math.Log(getSlopeFromSIndex(sidx + 1)); - - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - log_isl = (float)System.Math.Log(lthresh); - - log_ilen = log_len1 + (log_isl - log_sl1) * (log_len1 - log_len2) / (log_sl1 - log_sl2); - - log_off = log_ab - log_ilen; - - // Do not use negative offsets (i.e. offset proportion larger than 1) - // since that is probably a sign that our model is off. To be - // conservative use an offset of 0 (i.e. offset proportiojn 1). - if (log_off < 0) - log_off = 0f; - - // 2) Correct the target layer length by the offset. - - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - tlen = (int)(targetBytes / (float)System.Math.Exp(log_off)); - - // 3) Find, from the summary R-D info, the thresholds that generate - // lengths just above and below our corrected target layer length. - - // Look for the index in the summary info array that gives the largest - // length smaller than the target length - for (sidx = RD_SUMMARY_SIZE - 1; sidx >= 0; sidx--) - { - if (RDSlopesRates[sidx] >= tlen) - break; - } - sidx++; - // Correct if out of the array - if (sidx >= RD_SUMMARY_SIZE) - sidx = RD_SUMMARY_SIZE - 1; - if (sidx <= 0) - sidx = 1; - - // Get the log of the lengths and the slopes that are just above and - // below the target length. - - if (RDSlopesRates[sidx] == 0) - { - // Pathological case, we can not use log of 0. Add - // RDSlopesRates[sidx-1]+1 bytes to the rates (just a crude simple - // solution to this rare case) - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - log_len1 = (float)System.Math.Log(RDSlopesRates[sidx - 1] + 1); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - log_len2 = (float)System.Math.Log((RDSlopesRates[sidx - 1] << 1) + 1); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - log_ilen = (float)System.Math.Log(tlen + RDSlopesRates[sidx - 1] + 1); - } - else - { - // Normal case, we can safely take the logs. - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - log_len1 = (float)System.Math.Log(RDSlopesRates[sidx]); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - log_len2 = (float)System.Math.Log(RDSlopesRates[sidx - 1]); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - log_ilen = (float)System.Math.Log(tlen); - } - - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - log_sl1 = (float)System.Math.Log(getSlopeFromSIndex(sidx)); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - log_sl2 = (float)System.Math.Log(getSlopeFromSIndex(sidx - 1)); - - // 4) Interpolate the two thresholds to find the target threshold. - - log_isl = log_sl1 + (log_ilen - log_len1) * (log_sl1 - log_sl2) / (log_len1 - log_len2); - - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - eth = (float)System.Math.Exp(log_isl); - - // Correct out of bounds results - if (eth > lthresh) - eth = lthresh; - if (eth < FLOAT_ABS_PRECISION) - eth = 0f; - - // Return the estimated threshold - return eth; - } - - /// This function finds the new truncation points indices for a packet. It - /// does so by including the data from the code-blocks in the component, - /// resolution level and tile, associated with a R-D slope which is larger - /// than or equal to 'fthresh'. - /// - /// - /// The index of the current layer - /// - /// - /// The index of the current component - /// - /// - /// The index of the current resolution level - /// - /// - /// The index of the current tile - /// - /// - /// The LL subband in the resolution level lvlIdx, which is - /// parent of all the subbands in the packet. Except for resolution level 0 - /// this subband is always a node. - /// - /// - /// The value of the rate-distortion threshold - /// - /// - private void findTruncIndices(int layerIdx, int compIdx, int lvlIdx, int tileIdx, SubbandAn subb, float fthresh, int precinctIdx) - { - int minsbi, maxsbi, b, n; // bIdx removed - //Coord ncblks = null; - SubbandAn sb; - CBlkRateDistStats cur_cblk; - PrecInfo prec = pktEnc.getPrecInfo(tileIdx, compIdx, lvlIdx, precinctIdx); - Coord cbCoord; - - sb = subb; - while (sb.subb_HH != null) - { - sb = sb.subb_HH; - } - minsbi = (lvlIdx == 0) ? 0 : 1; - maxsbi = (lvlIdx == 0) ? 1 : 4; - - int yend, xend; - - sb = (SubbandAn)subb.getSubbandByIdx(lvlIdx, minsbi); - for (int s = minsbi; s < maxsbi; s++) - { - //loop on subbands - yend = (prec.cblk[s] != null) ? prec.cblk[s].Length : 0; - for (int y = 0; y < yend; y++) - { - xend = (prec.cblk[s][y] != null) ? prec.cblk[s][y].Length : 0; - for (int x = 0; x < xend; x++) - { - cbCoord = prec.cblk[s][y][x].idx; - b = cbCoord.x + cbCoord.y * sb.numCb.x; - - //Get the current code-block - cur_cblk = cblks[tileIdx][compIdx][lvlIdx][s][b]; - for (n = 0; n < cur_cblk.nVldTrunc; n++) - { - if (cur_cblk.truncSlopes[n] < fthresh) - { - break; - } - else - { - continue; - } - } - // Store the index in the code-block truncIdxs that gives - // the real truncation index. - truncIdxs[tileIdx][layerIdx][compIdx][lvlIdx][s][b] = n - 1; - } // End loop on horizontal code-blocks - } // End loop on vertical code-blocks - sb = (SubbandAn)sb.nextSubband(); - } // End loop on subbands - } - - /// Returns the index of a slope for the summary table, limiting to the - /// admissible values. The index is calculated as RD_SUMMARY_OFF plus the - /// maximum exponent, base 2, that yields a value not larger than the slope - /// itself. - /// - ///

    If the value to return is lower than 0, 0 is returned. If it is - /// larger than the maximum table index, then the maximum is returned.

    - /// - ///
    - /// The slope value - /// - /// - /// The index for the summary table of the slope. - /// - /// - private static int getLimitedSIndexFromSlope(float slope) - { - int idx; - - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - idx = (int)System.Math.Floor(System.Math.Log(slope) / LOG2) + RD_SUMMARY_OFF; - - if (idx < 0) - { - return 0; - } - else if (idx >= RD_SUMMARY_SIZE) - { - return RD_SUMMARY_SIZE - 1; - } - else - { - return idx; - } - } - - /// Returns the minimum slope value associated with a summary table - /// index. This minimum slope is just 2^(index-RD_SUMMARY_OFF). - /// - /// - /// The summary index value. - /// - /// - /// The minimum slope value associated with a summary table index. - /// - /// - private static float getSlopeFromSIndex(int index) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - return (float)System.Math.Pow(2, (index - RD_SUMMARY_OFF)); - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/entropy/encoder/EntropyCoder.cs b/CSJ2K/j2k/entropy/encoder/EntropyCoder.cs deleted file mode 100644 index 183a7932..00000000 --- a/CSJ2K/j2k/entropy/encoder/EntropyCoder.cs +++ /dev/null @@ -1,279 +0,0 @@ -/* -* CVS identifier: -* -* $Id: EntropyCoder.java,v 1.58 2001/09/20 12:40:30 grosbois Exp $ -* -* Class: EntropyCoder -* -* Description: The abstract class for entropy encoders -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.image; -using CSJ2K.j2k.quantization.quantizer; -using CSJ2K.j2k.util; -using CSJ2K.j2k.wavelet; -using CSJ2K.j2k.wavelet.analysis; -namespace CSJ2K.j2k.entropy.encoder -{ - - /// This abstract class provides the general interface for block-based entropy - /// encoders. The input to the entropy coder is the quantized wavelet - /// coefficients, or codewords, represented in sign magnitude. The output is a - /// compressed code-block with rate-distortion information. - /// - ///

    The source of data for objects of this class are 'CBlkQuantDataSrcEnc' - /// objects.

    - /// - ///

    For more details on the sign magnitude representation used see the - /// Quantizer class.

    - /// - ///

    This class provides default implemenations for most of the methods - /// (wherever it makes sense), under the assumption that the image and - /// component dimensions, and the tiles, are not modifed by the entropy - /// coder. If that is not the case for a particular implementation then the - /// methods should be overriden.

    - /// - ///
    - /// - /// - /// - /// - /// - public abstract class EntropyCoder : ImgDataAdapter, CodedCBlkDataSrcEnc - { - /// Returns the horizontal offset of the code-block partition. Allowable - /// values are 0 and 1, nothing else. - /// - /// - virtual public int CbULX - { - get - { - return src.CbULX; - } - - } - /// Returns the vertical offset of the code-block partition. Allowable - /// values are 0 and 1, nothing else. - /// - /// - virtual public int CbULY - { - get - { - return src.CbULY; - } - - } - /// Returns the parameters that are used in this class and implementing - /// classes. It returns a 2D String array. Each of the 1D arrays is for a - /// different option, and they have 3 elements. The first element is the - /// option name, the second one is the synopsis, the third one is a long - /// description of what the parameter is and the fourth is its default - /// value. The synopsis or description may be 'null', in which case it is - /// assumed that there is no synopsis or description of the option, - /// respectively. Null may be returned if no options are supported. - /// - /// - /// the options name, their synopsis and their explanation, or null - /// if no options are supported. - /// - /// - public static System.String[][] ParameterInfo - { - get - { - return pinfo; - } - - } - - /// The prefix for entropy coder options: 'C' - public const char OPT_PREFIX = 'C'; - - /// The list of parameters that is accepted for entropy coding. Options - /// for entropy coding start with 'C'. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'pinfo'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly System.String[][] pinfo = new System.String[][]{new System.String[]{"Cblksiz", "[] " + "[[] ]", "Specifies the maximum code-block size to use for tile-component. " + "The maximum width and height is 1024, however the surface area " + "(i.e. width x height) must not exceed 4096. The minimum width and " + "height is 4.", "64 64"}, new System.String[]{"Cbypass", "[] on|off" + "[ [] on|off ...]", "Uses the lazy coding mode with the entropy coder. This will bypass " + "the MQ coder for some of the coding passes, where the distribution " + "is often close to uniform. Since the MQ codeword will be " + "terminated " + "at least once per lazy pass, it is important to use an efficient " + "termination algorithm, see the 'Cterm_type' option." + "'on' enables, 'off' disables it.", "off"}, new System.String[]{"CresetMQ", "[] on|off" + "[ [] on|off ...]", "If this is enabled the probability estimates of the MQ coder are " + "reset after each arithmetically coded (i.e. non-lazy) coding pass. " + "'on' enables, 'off' disables it.", "off"}, new System.String[]{"Cterminate", "[] on|off" + "[ [] on|off ...]", "If this is enabled the codeword (raw or MQ) is terminated on a " + "byte boundary after each coding pass. In this case it is important " + "to use an efficient termination algorithm, see the 'Cterm' option. " + "'on' enables, 'off' disables it.", "off"}, new System.String[]{"Ccausal", "[] on|off" + "[ [] on|off ...]", "Uses vertically stripe causal context formation. If this is " + "enabled " + "the context formation process in one stripe is independant of the " + "next stripe (i.e. the one below it). 'on' " + "enables, 'off' disables it.", "off"}, new System.String[]{"Cseg_symbol", "[] on|off" + "[ [] on|off ...]", - "Inserts an error resilience segmentation symbol in the MQ " + "codeword at the end of " + "each bit-plane (cleanup pass). Decoders can use this " + "information to detect and " + "conceal errors.'on' enables, 'off' disables " + "it.", "off"}, new System.String[]{"Cterm_type", "[] near_opt|easy|predict|full" + "[ [] near_opt|easy|predict|full ...]", "Specifies the algorithm used to terminate the MQ codeword. " + "The most efficient one is 'near_opt', which delivers a codeword " + "which in almost all cases is the shortest possible. The 'easy' is " + "a simpler algorithm that delivers a codeword length that is close " + "to the previous one (in average 1 bit longer). The 'predict' is" + " almost " + "the same as the 'easy' but it leaves error resilient information " + "on " + "the spare least significant bits (in average 3.5 bits), which can " + "be used by a decoder to detect errors. The 'full' algorithm " + "performs a full flush of the MQ coder and is highly inefficient.\n" + "It is important to use a good termination policy since the MQ " + "codeword can be terminated quite often, specially if the 'Cbypass'" + " or " + "'Cterminate' options are enabled (in the normal case it would be " + "terminated once per code-block, while if 'Cterminate' is specified " + "it will be done almost 3 times per bit-plane in each code-block).", "near_opt"}, new System.String[]{"Clen_calc", "[] near_opt|lazy_good|lazy" + "[ [] ...]", "Specifies the algorithm to use in calculating the necessary MQ " + "length for each decoding pass. The best one is 'near_opt', which " + "performs a rather sophisticated calculation and provides the best " + "results. The 'lazy_good' and 'lazy' are very simple algorithms " + "that " + "provide rather conservative results, 'lazy_good' one being " + "slightly " + "better. Do not change this option unless you want to experiment " + "the effect of different length calculation algorithms.", "near_opt"}, new - System.String[]{"Cpp", "[] [ ] " + "[ [] ...]", "Specifies precinct partition dimensions for tile-component. The " + "first " + "two values apply to the highest resolution and the following ones " + "(if " + "any) apply to the remaining resolutions in decreasing order. If " + "less " + "values than the number of decomposition levels are specified, " + "then the " + "last two values are used for the remaining resolutions.", null}}; - - /// The source of quantized wavelet coefficients - protected internal CBlkQuantDataSrcEnc src; - - /// Initializes the source of quantized wavelet coefficients. - /// - /// - /// The source of quantized wavelet coefficients. - /// - /// - public EntropyCoder(CBlkQuantDataSrcEnc src) : base(src) - { - this.src = src; - } - - /// Returns the code-block width for the specified tile and component. - /// - /// - /// The tile index - /// - /// - /// the component index - /// - /// - /// The code-block width for the specified tile and component - /// - /// - public abstract int getCBlkWidth(int t, int c); - - /// Returns the code-block height for the specified tile and component. - /// - /// - /// The tile index - /// - /// - /// the component index - /// - /// - /// The code-block height for the specified tile and component - /// - /// - public abstract int getCBlkHeight(int t, int c); - - /// Returns the reversibility of the tile-component data that is provided - /// by the object. Data is reversible when it is suitable for lossless and - /// lossy-to-lossless compression. - /// - ///

    Since entropy coders themselves are always reversible, it returns - /// the reversibility of the data that comes from the 'CBlkQuantDataSrcEnc' - /// source object (i.e. ROIScaler). - /// - ///

    - /// Tile index - /// - /// - /// Component index - /// - /// - /// true is the data is reversible, false if not. - /// - /// - /// - /// - /// - public virtual bool isReversible(int t, int c) - { - return src.isReversible(t, c); - } - - /// Returns a reference to the root of subband tree structure representing - /// the subband decomposition for the specified tile-component. - /// - /// - /// The index of the tile. - /// - /// - /// The index of the component. - /// - /// - /// The root of the subband tree structure, see Subband. - /// - /// - /// - /// - /// - /// - /// - /// - public virtual SubbandAn getAnSubbandTree(int t, int c) - { - return src.getAnSubbandTree(t, c); - } - - /// Creates a EntropyCoder object for the appropriate entropy coding - /// parameters in the parameter list 'pl', and having 'src' as the source - /// of quantized data. - /// - /// - /// The source of data to be entropy coded - /// - /// - /// The parameter list (or options). - /// - /// - /// Code-block size specifications - /// - /// - /// Precinct partition specifications - /// - /// - /// By-pass mode specifications - /// - /// - /// MQ-reset specifications - /// - /// - /// Regular termination specifications - /// - /// - /// Causal stripes specifications - /// - /// - /// Error resolution segment symbol use specifications - /// - /// - /// Length computation specifications - /// - /// - /// Termination type specifications - /// - /// - /// If an error occurs while parsing - /// the options in 'pl' - /// - /// - public static EntropyCoder createInstance(CBlkQuantDataSrcEnc src, ParameterList pl, CBlkSizeSpec cblks, PrecinctSizeSpec pss, StringSpec bms, StringSpec mqrs, StringSpec rts, StringSpec css, StringSpec sss, StringSpec lcs, StringSpec tts) - { - // Check parameters - pl.checkList(OPT_PREFIX, CSJ2K.j2k.util.ParameterList.toNameArray(pinfo)); - return new StdEntropyCoder(src, cblks, pss, bms, mqrs, rts, css, sss, lcs, tts); - } - public abstract CSJ2K.j2k.entropy.encoder.CBlkRateDistStats getNextCodeBlock(int param1, CSJ2K.j2k.entropy.encoder.CBlkRateDistStats param2); - public abstract bool precinctPartitionUsed(int param1, int param2); - public abstract int getPPX(int param1, int param2, int param3); - public abstract int getPPY(int param1, int param2, int param3); - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/entropy/encoder/LayersInfo.cs b/CSJ2K/j2k/entropy/encoder/LayersInfo.cs deleted file mode 100644 index 0a567db3..00000000 --- a/CSJ2K/j2k/entropy/encoder/LayersInfo.cs +++ /dev/null @@ -1,250 +0,0 @@ -/* -* CVS identifier: -* -* $Id: LayersInfo.java,v 1.7 2001/04/15 14:31:22 grosbois Exp $ -* -* Class: LayersInfo -* -* Description: Specification of a layer -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using System; -namespace CSJ2K.j2k.entropy.encoder -{ - - /// This class stores the specification of a layer distribution in the bit - /// stream. The specification is made of optimization points and a number of - /// extra layers to add between the optimization points. Each optimization - /// point creates a layer which is optimized by the rate allocator to the - /// specified target bitrate. The extra layers are added by the rate allocator - /// between the optimized layers, with the difference that they are not - /// optimized (i.e. they have no precise target bitrate). - /// - ///

    The overall target bitrate for the bit stream is always added as the - /// last optimization point without any extra layers after it. If there are - /// some optimization points whose target bitrate is larger than the overall - /// target bitrate, the overall target bitrate will still appear as the last - /// optimization point, even though it does not follow the increasing target - /// bitrate order of the other optimization points. The rate allocator is - /// responsible for eliminating layers that have target bitrates larger than - /// the overall target bitrate.

    - /// - ///

    Optimization points can be added with the addOptPoint() method. It takes - /// the target bitrate for the optimized layer and the number of extra layers - /// to add after it.

    - /// - ///

    Information about the total number of layers, total number of - /// optimization points, target bitrates, etc. can be obtained with the other - /// methods.

    - /// - ///
    - public class LayersInfo - { - /// Returns the overall target bitrate for the entire bit stream. - /// - /// - /// The overall target bitrate - /// - /// - virtual public float TotBitrate - { - get - { - return totbrate; - } - - } - /// Returns the total number of layers, according to the layer - /// specification of this object and the overall target bitrate. - /// - /// - /// The total number of layers, according to the layer spec. - /// - /// - virtual public int TotNumLayers - { - get - { - return totlyrs; - } - - } - /// Returns the number of layers to optimize, or optimization points, as - /// specified by this object. - /// - /// - /// The number of optimization points - /// - /// - virtual public int NOptPoints - { - get - { - // overall target bitrate is counted as extra - return nopt + 1; - } - - } - - /// The initial size for the arrays: 10 - private const int SZ_INIT = 10; - - /// The size increment for the arrays - private const int SZ_INCR = 5; - - /// The total number of layers - // Starts at 1: overall target bitrate is always an extra optimized layer - internal int totlyrs = 1; - - /// The overall target bitrate, for the whole bit stream - internal float totbrate; - - /// The number of optimized layers, or optimization points, without - /// counting the extra one coming from the overall target bitrate - /// - internal int nopt; - - /// The target bitrate to which specified layers should be optimized. - internal float[] optbrate = new float[SZ_INIT]; - - /// The number of extra layers to be added after an optimized layer. After - /// the layer that is optimized to optbrate[i], extralyrs[i] extra layers - /// should be added. These layers are allocated between the bitrate - /// optbrate[i] and the next optimized bitrate optbrate[i+1] or, if it does - /// not exist, the overall target bitrate. - /// - internal int[] extralyrs = new int[SZ_INIT]; - - /// Creates a new LayersInfo object. The overall target bitrate 'brate' is - /// always an extra optimization point, with no extra layers are after - /// it. Note that any optimization points that are added with addOptPoint() - /// are always added before the overall target bitrate. - /// - /// - /// The overall target bitrate for the bit stream - /// - /// - public LayersInfo(float brate) - { - if (brate <= 0) - { - throw new System.ArgumentException("Overall target bitrate must " + "be a positive number"); - } - totbrate = brate; - } - - /// Returns the target bitrate of the optmimization point 'n'. - /// - /// - /// The optimization point index (starts at 0). - /// - /// - /// The target bitrate (in bpp) for the optimization point 'n'. - /// - /// - public virtual float getTargetBitrate(int n) - { - // overall target bitrate is counted as extra - return (n < nopt) ? optbrate[n] : totbrate; - } - - /// Returns the number of extra layers to add after the optimization point - /// 'n', but before optimization point 'n+1'. If there is no optimization - /// point 'n+1' then they should be added before the overall target - /// bitrate. - /// - /// - /// The optimization point index (starts at 0). - /// - /// - /// The number of extra (unoptimized) layers to add after the - /// optimization point 'n' - /// - /// - public virtual int getExtraLayers(int n) - { - // overall target bitrate is counted as extra - return (n < nopt) ? extralyrs[n] : 0; - } - - /// Adds a new optimization point, with target bitrate 'brate' and with - /// 'elyrs' (unoptimized) extra layers after it. The target bitrate 'brate' - /// must be larger than the previous optimization point. The arguments are - /// checked and IllegalArgumentException is thrown if they are not correct. - /// - /// - /// The target bitrate for the optimized layer. - /// - /// - /// The number of extra (unoptimized) layers to add after the - /// optimized layer. - /// - /// - public virtual void addOptPoint(float brate, int elyrs) - { - // Check validity of arguments - if (brate <= 0) - { - throw new System.ArgumentException("Target bitrate must be positive"); - } - if (elyrs < 0) - { - throw new System.ArgumentException("The number of extra layers " + "must be 0 or more"); - } - if (nopt > 0 && optbrate[nopt - 1] >= brate) - { - throw new System.ArgumentException("New optimization point must have " + "a target bitrate higher than the " + "preceding one"); - } - // Check room for new optimization point - if (optbrate.Length == nopt) - { - // Need more room - float[] tbr = optbrate; - int[] tel = extralyrs; - // both arrays always have same size - optbrate = new float[optbrate.Length + SZ_INCR]; - extralyrs = new int[extralyrs.Length + SZ_INCR]; - Array.Copy(tbr, 0, optbrate, 0, nopt); - Array.Copy(tel, 0, extralyrs, 0, nopt); - } - // Add new optimization point - optbrate[nopt] = brate; - extralyrs[nopt] = elyrs; - nopt++; - // Update total number of layers - totlyrs += 1 + elyrs; - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/entropy/encoder/MQCoder.cs b/CSJ2K/j2k/entropy/encoder/MQCoder.cs deleted file mode 100644 index 197ea158..00000000 --- a/CSJ2K/j2k/entropy/encoder/MQCoder.cs +++ /dev/null @@ -1,1560 +0,0 @@ -/* -* CVS identifier: -* -* $Id: MQCoder.java,v 1.36 2002/01/10 10:31:28 grosbois Exp $ -* -* Class: MQCoder -* -* Description: Class that encodes a number of bits using the -* MQ arithmetic coder -* -* -* Diego SANTA CRUZ, Jul-26-1999 (improved speed) -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.util; -using System; -namespace CSJ2K.j2k.entropy.encoder -{ - - /// This class implements the MQ arithmetic coder. When initialized a specific - /// state can be specified for each context, which may be adapted to the - /// probability distribution that is expected for that context. - /// - ///

    The type of length calculation and termination can be chosen at - /// construction time. - /// - /// ---- Tricks that have been tried to improve speed ---- - /// - ///

    1) Merging Qe and mPS and doubling the lookup tables
    - /// - /// Merge the mPS into Qe, as the sign bit (if Qe>=0 the sense of MPS is 0, if - /// Qe<0 the sense is 1), and double the lookup tables. The first half of the - /// lookup tables correspond to Qe>=0 (i.e. the sense of MPS is 0) and the - /// second half to Qe<0 (i.e. the sense of MPS is 1). The nLPS lookup table is - /// modified to incorporate the changes in the sense of MPS, by making it jump - /// from the first to the second half and vice-versa, when a change is - /// specified by the swicthLM lookup table. See JPEG book, section 13.2, page - /// 225.
    - /// - /// There is NO speed improvement in doing this, actually there is a slight - /// decrease, probably due to the fact that often Q has to be negated. Also the - /// fact that a brach of the type "if (bit==mPS[li])" is replaced by two - /// simpler braches of the type "if (bit==0)" and "if (q<0)" may contribute to - /// that.

    - /// - ///

    2) Removing cT
    - /// - /// It is possible to remove the cT counter by setting a flag bit in the high - /// bits of the C register. This bit will be automatically shifted left - /// whenever a renormalization shift occurs, which is equivalent to decreasing - /// cT. When the flag bit reaches the sign bit (leftmost bit), which is - /// equivalenet to cT==0, the byteOut() procedure is called. This test can be - /// done efficiently with "c<0" since C is a signed quantity. Care must be - /// taken in byteOut() to reset the bit in order to not interfere with other - /// bits in the C register. See JPEG book, page 228.
    - /// - /// There is NO speed improvement in doing this. I don't really know why since - /// the number of operations whenever a renormalization occurs is - /// decreased. Maybe it is due to the number of extra operations in the - /// byteOut(), terminate() and getNumCodedBytes() procedures.

    - /// - ///

    3) Change the convention of MPS and LPS.
    - /// - /// Making the LPS interval be above the MPS interval (MQ coder convention is - /// the opposite) can reduce the number of operations along the MPS path. In - /// order to generate the same bit stream as with the MQ convention the output - /// bytes need to be modified accordingly. The basic rule for this is that C = - /// (C'^0xFF...FF)-A, where C is the codestream for the MQ convention and C' is - /// the codestream generated by this other convention. Note that this affects - /// bit-stuffing as well.
    - /// - /// This has not been tested yet.
    - /// - ///

    4) Removing normalization while loop on MPS path
    - /// - /// Since in the MPS path Q is guaranteed to be always greater than 0x4000 - /// (decimal 0.375) it is never necessary to do more than 1 renormalization - /// shift. Therefore the test of the while loop, and the loop itself, can be - /// removed.

    - /// - ///

    5) Simplifying test on A register
    - /// - /// Since A is always less than or equal to 0xFFFF, the test "(a & 0x8000)==0" - /// can be replaced by the simplete test "a < 0x8000". This test is simpler in - /// Java since it involves only 1 operation (although the original test can be - /// converted to only one operation by smart Just-In-Time compilers)
    - /// - /// This change has been integrated in the decoding procedures.

    - /// - ///

    6) Speedup mode
    - /// - /// Implemented a method that uses the speedup mode of the MQ-coder if - /// possible. This should greately improve performance when coding long runs of - /// MPS symbols that have high probability. However, to take advantage of this, - /// the entropy coder implementation has to explicetely use it. The generated - /// bit stream is the same as if no speedup mode would have been used.
    - /// - /// Implemented but performance not tested yet.

    - /// - ///

    7) Multiple-symbol coding
    - /// - /// Since the time spent in a method call is non-negligable, coding several - /// symbols with one method call reduces the overhead per coded symbol. The - /// decodeSymbols() method implements this. However, to take advantage of it, - /// the implementation of the entropy coder has to explicitely use it.
    - /// - /// Implemented but performance not tested yet.

    - /// - ///
    - public class MQCoder - { - /// Set the length calculation type to the specified type. - /// - /// - /// The type of length calculation to use. One of - /// 'LENGTH_LAZY', 'LENGTH_LAZY_GOOD' or 'LENGTH_NEAR_OPT'. - /// - /// - virtual public int LenCalcType - { - set - { - // Verify the ttype and ltype - if (value != LENGTH_LAZY && value != LENGTH_LAZY_GOOD && value != LENGTH_NEAR_OPT) - { - throw new System.ArgumentException("Unrecognized length " + "calculation type code: " + value); - } - - if (value == LENGTH_NEAR_OPT) - { - if (savedC == null) - savedC = new int[SAVED_LEN]; - if (savedCT == null) - savedCT = new int[SAVED_LEN]; - if (savedA == null) - savedA = new int[SAVED_LEN]; - if (savedB == null) - savedB = new int[SAVED_LEN]; - if (savedDelFF == null) - savedDelFF = new bool[SAVED_LEN]; - } - this.ltype = value; - } - - } - /// Set termination type to the specified type. - /// - /// - /// The type of termination to use. One of 'TERM_FULL', - /// 'TERM_NEAR_OPT', 'TERM_EASY' or 'TERM_PRED_ER'. - /// - /// - virtual public int TermType - { - set - { - if (value != TERM_FULL && value != TERM_NEAR_OPT && value != TERM_EASY && value != TERM_PRED_ER) - { - throw new System.ArgumentException("Unrecognized termination " + "type code: " + value); - } - this.ttype = value; - } - - } - /// Returns the number of contexts in the arithmetic coder. - /// - /// - /// The number of contexts - /// - /// - virtual public int NumCtxts - { - get - { - return I.Length; - } - - } - /// Returns the number of bytes that are necessary from the compressed - /// output stream to decode all the symbols that have been coded this - /// far. The number of returned bytes does not include anything coded - /// previous to the last time the 'terminate()' or 'reset()' methods where - /// called. - /// - ///

    The values returned by this method are then to be used in finishing - /// the length calculation with the 'finishLengthCalculation()' method, - /// after compensation of the offset in the number of bytes due to previous - /// terminated segments.

    - /// - ///

    This method should not be called if the current coding pass is to be - /// terminated. The 'terminate()' method should be called instead.

    - /// - ///

    The calculation is done based on the type of length calculation - /// specified at the constructor.

    - /// - ///
    - /// The number of bytes in the compressed output stream necessary - /// to decode all the information coded this far. - /// - /// - virtual public int NumCodedBytes - { - get - { - // NOTE: testing these algorithms for correctness is quite - // difficult. One way is to modify the rate allocator so that not all - // bit-planes are output if the distortion estimate for last passes is - // the same as for the previous ones. - - switch (ltype) - { - - case LENGTH_LAZY_GOOD: - // This one is a bit better than LENGTH_LAZY. - int bitsInN3Bytes; // The minimum amount of bits that can be - // stored in the 3 bytes following the current byte buffer 'b'. - - if (b >= 0xFE) - { - // The byte after b can have a bit stuffed so ther could be - // one less bit available - bitsInN3Bytes = 22; // 7 + 8 + 7 - } - else - { - // We are sure that next byte after current byte buffer has no - // bit stuffing - bitsInN3Bytes = 23; // 8 + 7 + 8 - } - if ((11 - cT + 16) <= bitsInN3Bytes) - { - return nrOfWrittenBytes + (delFF ? 1 : 0) + 1 + 3; - } - else - { - return nrOfWrittenBytes + (delFF ? 1 : 0) + 1 + 4; - } - //goto case LENGTH_LAZY; - - case LENGTH_LAZY: - // This is the very basic one that appears in the VM text - if ((27 - cT) <= 22) - { - return nrOfWrittenBytes + (delFF ? 1 : 0) + 1 + 3; - } - else - { - return nrOfWrittenBytes + (delFF ? 1 : 0) + 1 + 4; - } - //goto case LENGTH_NEAR_OPT; - - case LENGTH_NEAR_OPT: - // This is the best length calculation implemented in this class. - // It is almost always optimal. In order to calculate the length - // it is necessary to know which bytes will follow in the MQ - // bit stream, so we need to wait until termination to perform it. - // Save the state to perform the calculation later, in - // finishLengthCalculation() - saveState(); - // Return current number of output bytes to use it later in - // finishLengthCalculation() - return nrOfWrittenBytes; - - default: - throw new System.ApplicationException("Illegal length calculation type code"); - - } - } - - } - - /// Identifier for the lazy length calculation. The lazy length - /// calculation is not optimal but is extremely simple. - /// - public const int LENGTH_LAZY = 0; - - /// Identifier for a very simple length calculation. This provides better - /// results than the 'LENGTH_LAZY' computation. This is the old length - /// calculation that was implemented in this class. - /// - public const int LENGTH_LAZY_GOOD = 1; - - /// Identifier for the near optimal length calculation. This calculation - /// is more complex than the lazy one but provides an almost optimal length - /// calculation. - /// - public const int LENGTH_NEAR_OPT = 2; - - /// The identifier fort the termination that uses a full flush. This is - /// the less efficient termination. - /// - public const int TERM_FULL = 0; - - /// The identifier for the termination that uses the near optimal length - /// calculation to terminate the arithmetic codewrod - /// - public const int TERM_NEAR_OPT = 1; - - /// The identifier for the easy termination that is simpler than the - /// 'TERM_NEAR_OPT' one but slightly less efficient. - /// - public const int TERM_EASY = 2; - - /// The identifier for the predictable termination policy for error - /// resilience. This is the same as the 'TERM_EASY' one but an special - /// sequence of bits is embodied in the spare bits for error resilience - /// purposes. - /// - public const int TERM_PRED_ER = 3; - - /// The data structures containing the probabilities for the LPS - //UPGRADE_NOTE: Final was removed from the declaration of 'qe'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - internal static readonly int[] qe = new int[] { 0x5601, 0x3401, 0x1801, 0x0ac1, 0x0521, 0x0221, 0x5601, 0x5401, 0x4801, 0x3801, 0x3001, 0x2401, 0x1c01, 0x1601, 0x5601, 0x5401, 0x5101, 0x4801, 0x3801, 0x3401, 0x3001, 0x2801, 0x2401, 0x2201, 0x1c01, 0x1801, 0x1601, 0x1401, 0x1201, 0x1101, 0x0ac1, 0x09c1, 0x08a1, 0x0521, 0x0441, 0x02a1, 0x0221, 0x0141, 0x0111, 0x0085, 0x0049, 0x0025, 0x0015, 0x0009, 0x0005, 0x0001, 0x5601 }; - - /// The indexes of the next MPS - //UPGRADE_NOTE: Final was removed from the declaration of 'nMPS'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - internal static readonly int[] nMPS = new int[] { 1, 2, 3, 4, 5, 38, 7, 8, 9, 10, 11, 12, 13, 29, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 45, 46 }; - - /// The indexes of the next LPS - //UPGRADE_NOTE: Final was removed from the declaration of 'nLPS'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - internal static readonly int[] nLPS = new int[] { 1, 6, 9, 12, 29, 33, 6, 14, 14, 14, 17, 18, 20, 21, 14, 14, 15, 16, 17, 18, 19, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 46 }; - - /// Whether LPS and MPS should be switched - //UPGRADE_NOTE: Final was removed from the declaration of 'switchLM'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - internal static readonly int[] switchLM = new int[] { 1, 0, 0, 0, 0, 0, 1, 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 }; - // Having ints proved to be more efficient than booleans - - /// The ByteOutputBuffer used to write the compressed bit stream. - internal ByteOutputBuffer out_Renamed; - - /// The current most probable signal for each context - internal int[] mPS; - - /// The current index of each context - internal int[] I; - - /// The current bit code - internal int c; - - /// The bit code counter - internal int cT; - - /// The current interval - internal int a; - - /// The last encoded byte of data - internal int b; - - /// If a 0xFF byte has been delayed and not yet been written to the output - /// (in the MQ we can never have more than 1 0xFF byte in a row). - /// - internal bool delFF; - - /// The number of written bytes so far, excluding any delayed 0xFF - /// bytes. Upon initialization it is -1 to indicated that the byte buffer - /// 'b' is empty as well. - /// - internal int nrOfWrittenBytes = -1; - - /// The initial state of each context - internal int[] initStates; - - /// The termination type to use. One of 'TERM_FULL', 'TERM_NEAR_OPT', - /// 'TERM_EASY' or 'TERM_PRED_ER'. - /// - internal int ttype; - - /// The length calculation type to use. One of 'LENGTH_LAZY', - /// 'LENGTH_LAZY_GOOD', 'LENGTH_NEAR_OPT'. - /// - internal int ltype; - - /// Saved values of the C register. Used for the LENGTH_NEAR_OPT length - /// calculation. - /// - internal int[] savedC; - - /// Saved values of CT counter. Used for the LENGTH_NEAR_OPT length - /// calculation. - /// - internal int[] savedCT; - - /// Saved values of the A register. Used for the LENGTH_NEAR_OPT length - /// calculation. - /// - internal int[] savedA; - - /// Saved values of the B byte buffer. Used for the LENGTH_NEAR_OPT length - /// calculation. - /// - internal int[] savedB; - - /// Saved values of the delFF (i.e. delayed 0xFF) state. Used for the - /// LENGTH_NEAR_OPT length calculation. - /// - internal bool[] savedDelFF; - - /// Number of saved states. Used for the LENGTH_NEAR_OPT length - /// calculation. - /// - internal int nSaved; - - /// The initial length of the arrays to save sates - //UPGRADE_NOTE: Final was removed from the declaration of 'SAVED_LEN '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - internal static readonly int SAVED_LEN = 32 * CSJ2K.j2k.entropy.StdEntropyCoderOptions.NUM_PASSES; - - /// The increase in length for the arrays to save states - //UPGRADE_NOTE: Final was removed from the declaration of 'SAVED_INC '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - internal static readonly int SAVED_INC = 4 * CSJ2K.j2k.entropy.StdEntropyCoderOptions.NUM_PASSES; - - /// Instantiates a new MQ-coder, with the specified number of contexts and - /// initial states. The compressed bytestream is written to the 'oStream' - /// object. - /// - /// - /// where to output the compressed data. - /// - /// - /// The number of contexts used by the MQ coder. - /// - /// - /// The initial state for each context. A reference is kept to - /// this array to reinitialize the contexts whenever 'reset()' or - /// 'resetCtxts()' is called. - /// - /// - public MQCoder(ByteOutputBuffer oStream, int nrOfContexts, int[] init) - { - out_Renamed = oStream; - - // --- INITENC - - // Default initialization of the statistics bins is MPS=0 and - // I=0 - I = new int[nrOfContexts]; - mPS = new int[nrOfContexts]; - initStates = init; - - a = 0x8000; - c = 0; - if (b == 0xFF) - { - cT = 13; - } - else - { - cT = 12; - } - - resetCtxts(); - - // End of INITENC --- - b = 0; - } - - /// This method performs the coding of the symbol 'bit', using context - /// 'ctxt', 'n' times, using the MQ-coder speedup mode if possible. - /// - ///

    If the symbol 'bit' is the current more probable symbol (MPS) and - /// qe[ctxt]<=0x4000, and (A-0x8000)>=qe[ctxt], speedup mode will be - /// used. Otherwise the normal mode will be used. The speedup mode can - /// significantly improve the speed of arithmetic coding when several MPS - /// symbols, with a high probability distribution, must be coded with the - /// same context. The generated bit stream is the same as if the normal mode - /// was used.

    - /// - ///

    This method is also faster than the 'codeSymbols()' and - /// 'codeSymbol()' ones, for coding the same symbols with the same context - /// several times, when speedup mode can not be used, although not - /// significantly.

    - /// - ///
    - /// The symbol do code, 0 or 1. - /// - /// - /// The context to us in coding the symbol. - /// - /// - /// The number of times that the symbol must be coded. - /// - /// - public void fastCodeSymbols(int bit, int ctxt, int n) - { - int q; // cache for context's Qe - int la; // cache for A register - int nc; // counter for renormalization shifts - int ns; // the maximum length of a speedup mode run - int li; // cache for I[ctxt] - - li = I[ctxt]; // cache current index - q = qe[li]; // retrieve current LPS prob. - - if ((q <= 0x4000) && (bit == mPS[ctxt]) && ((ns = (a - 0x8000) / q + 1) > 1)) - { - // Do speed up mode - // coding MPS, no conditional exchange can occur and - // speedup mode is possible for more than 1 symbol - do - { - // do as many speedup runs as necessary - if (n <= ns) - { - // All symbols in this run - // code 'n' symbols - la = n * q; // accumulated Q - a -= la; - c += la; - if (a >= 0x8000) - { - // no renormalization - I[ctxt] = li; // save the current state - return; // done - } - I[ctxt] = nMPS[li]; // goto next state and save it - // -- Renormalization (MPS: no need for while loop) - a <<= 1; // a is doubled - c <<= 1; // c is doubled - cT--; - if (cT == 0) - { - byteOut(); - } - // -- End of renormalization - return; // done - } - else - { - // Not all symbols in this run - // code 'ns' symbols - la = ns * q; // accumulated Q - c += la; - a -= la; - // cache li and q for next iteration - li = nMPS[li]; - q = qe[li]; // New q is always less than current one - // new I[ctxt] is stored in last run - // Renormalization always occurs since we exceed 'ns' - // -- Renormalization (MPS: no need for while loop) - a <<= 1; // a is doubled - c <<= 1; // c is doubled - cT--; - if (cT == 0) - { - byteOut(); - } - // -- End of renormalization - n -= ns; // symbols left to code - ns = (a - 0x8000) / q + 1; // max length of next speedup run - continue; // goto next iteration - } - } - while (n > 0); - } - // end speed up mode - else - { - // No speedup mode - // Either speedup mode is not possible or not worth doing it - // because of probable conditional exchange - // Code everything as in normal mode - la = a; // cache A register in local variable - do - { - if (bit == mPS[ctxt]) - { - // -- code MPS - la -= q; // Interval division associated with MPS coding - if (la >= 0x8000) - { - // Interval big enough - c += q; - } - else - { - // Interval too short - if (la < q) - { - // Probabilities are inverted - la = q; - } - else - { - c += q; - } - // cache new li and q for next iteration - li = nMPS[li]; - q = qe[li]; - // new I[ctxt] is stored after end of loop - // -- Renormalization (MPS: no need for while loop) - la <<= 1; // a is doubled - c <<= 1; // c is doubled - cT--; - if (cT == 0) - { - byteOut(); - } - // -- End of renormalization - } - } - else - { - // -- code LPS - la -= q; // Interval division according to LPS coding - if (la < q) - { - c += q; - } - else - { - la = q; - } - if (switchLM[li] != 0) - { - mPS[ctxt] = 1 - mPS[ctxt]; - } - // cache new li and q for next iteration - li = nLPS[li]; - q = qe[li]; - // new I[ctxt] is stored after end of loop - // -- Renormalization - // sligthly better than normal loop - nc = 0; - do - { - la <<= 1; - nc++; // count number of necessary shifts - } - while (la < 0x8000); - if (cT > nc) - { - c <<= nc; - cT -= nc; - } - else - { - do - { - c <<= cT; - nc -= cT; - // cT = 0; // not necessary - byteOut(); - } - while (cT <= nc); - c <<= nc; - cT -= nc; - } - // -- End of renormalization - } - n--; - } - while (n > 0); - I[ctxt] = li; // store new I[ctxt] - a = la; // save cached A register - } - } - - /// This function performs the arithmetic encoding of several symbols - /// together. The function receives an array of symbols that are to be - /// encoded and an array containing the contexts with which to encode them. - /// - ///

    The advantage of using this function is that the cost of the method - /// call is amortized by the number of coded symbols per method call.

    - /// - ///

    Each context has a current MPS and an index describing what the - /// current probability is for the LPS. Each bit is encoded and if the - /// probability of the LPS exceeds .5, the MPS and LPS are switched.

    - /// - ///
    - /// An array containing the symbols to be encoded. Valid - /// symbols are 0 and 1. - /// - /// - /// The context for each of the symbols to be encoded. - /// - /// - /// The number of symbols to encode. - /// - /// - public void codeSymbols(int[] bits, int[] cX, int n) - { - int q; - int li; // local cache of I[context] - int la; - int nc; - int ctxt; // context of current symbol - int i; // counter - - // NOTE: here we could use symbol aggregation to speed things up. - // It remains to be studied. - - la = a; // cache A register in local variable - for (i = 0; i < n; i++) - { - // NOTE: (a<0x8000) is equivalent to ((a&0x8000)==0) - // since 'a' is always less than or equal to 0xFFFF - - // NOTE: conditional exchange guarantees that A for MPS is - // always greater than 0x4000 (i.e. 0.375) - // => one renormalization shift is enough for MPS - // => no need to do a renormalization while loop for MPS - - ctxt = cX[i]; - li = I[ctxt]; - q = qe[li]; // Retrieve current LPS prob. - - if (bits[i] == mPS[ctxt]) - { - // -- Code MPS - - la -= q; // Interval division associated with MPS coding - - if (la >= 0x8000) - { - // Interval big enough - c += q; - } - else - { - // Interval too short - if (la < q) - { - // Probabilities are inverted - la = q; - } - else - { - c += q; - } - - I[ctxt] = nMPS[li]; - - // -- Renormalization (MPS: no need for while loop) - la <<= 1; // a is doubled - c <<= 1; // c is doubled - cT--; - if (cT == 0) - { - byteOut(); - } - // -- End of renormalization - } - } - else - { - // -- Code LPS - la -= q; // Interval division according to LPS coding - - if (la < q) - { - c += q; - } - else - { - la = q; - } - if (switchLM[li] != 0) - { - mPS[ctxt] = 1 - mPS[ctxt]; - } - I[ctxt] = nLPS[li]; - - // -- Renormalization - - // sligthly better than normal loop - nc = 0; - do - { - la <<= 1; - nc++; // count number of necessary shifts - } - while (la < 0x8000); - if (cT > nc) - { - c <<= nc; - cT -= nc; - } - else - { - do - { - c <<= cT; - nc -= cT; - // cT = 0; // not necessary - byteOut(); - } - while (cT <= nc); - c <<= nc; - cT -= nc; - } - - // -- End of renormalization - } - } - a = la; // save cached A register - } - - - /// This function performs the arithmetic encoding of one symbol. The - /// function receives a bit that is to be encoded and a context with which - /// to encode it. - /// - ///

    Each context has a current MPS and an index describing what the - /// current probability is for the LPS. Each bit is encoded and if the - /// probability of the LPS exceeds .5, the MPS and LPS are switched.

    - /// - ///
    - /// The symbol to be encoded, must be 0 or 1. - /// - /// - /// the context with which to encode the symbol. - /// - /// - public void codeSymbol(int bit, int context) - { - int q; - int li; // local cache of I[context] - int la; - int n; - - // NOTE: (a < 0x8000) is equivalent to ((a & 0x8000)==0) - // since 'a' is always less than or equal to 0xFFFF - - // NOTE: conditional exchange guarantees that A for MPS is - // always greater than 0x4000 (i.e. 0.375) - // => one renormalization shift is enough for MPS - // => no need to do a renormalization while loop for MPS - - li = I[context]; - q = qe[li]; // Retrieve current LPS prob. - - if (bit == mPS[context]) - { - // -- Code MPS - - a -= q; // Interval division associated with MPS coding - - if (a >= 0x8000) - { - // Interval big enough - c += q; - } - else - { - // Interval too short - if (a < q) - { - // Probabilities are inverted - a = q; - } - else - { - c += q; - } - - I[context] = nMPS[li]; - - // -- Renormalization (MPS: no need for while loop) - a <<= 1; // a is doubled - c <<= 1; // c is doubled - cT--; - if (cT == 0) - { - byteOut(); - } - // -- End of renormalization - } - } - else - { - // -- Code LPS - - la = a; // cache A register in local variable - la -= q; // Interval division according to LPS coding - - if (la < q) - { - c += q; - } - else - { - la = q; - } - if (switchLM[li] != 0) - { - mPS[context] = 1 - mPS[context]; - } - I[context] = nLPS[li]; - - // -- Renormalization - - // sligthly better than normal loop - n = 0; - do - { - la <<= 1; - n++; // count number of necessary shifts - } - while (la < 0x8000); - if (cT > n) - { - c <<= n; - cT -= n; - } - else - { - do - { - c <<= cT; - n -= cT; - // cT = 0; // not necessary - byteOut(); - } - while (cT <= n); - c <<= n; - cT -= n; - } - - // -- End of renormalization - a = la; // save cached A register - } - } - - /// This function puts one byte of compressed bits in the output stream. - /// The highest 8 bits of c are then put in b to be the next byte to - /// write. This method delays the output of any 0xFF bytes until a non 0xFF - /// byte has to be written to the output bit stream (the 'delFF' variable - /// signals if there is a delayed 0xff byte). - /// - /// - private void byteOut() - { - if (nrOfWrittenBytes >= 0) - { - if (b == 0xFF) - { - // Delay 0xFF byte - delFF = true; - b = SupportClass.URShift(c, 20); - c &= 0xFFFFF; - cT = 7; - } - else if (c < 0x8000000) - { - // Write delayed 0xFF bytes - if (delFF) - { - out_Renamed.write(0xFF); - delFF = false; - nrOfWrittenBytes++; - } - out_Renamed.write(b); - nrOfWrittenBytes++; - b = SupportClass.URShift(c, 19); - c &= 0x7FFFF; - cT = 8; - } - else - { - b++; - if (b == 0xFF) - { - // Delay 0xFF byte - delFF = true; - c &= 0x7FFFFFF; - b = SupportClass.URShift(c, 20); - c &= 0xFFFFF; - cT = 7; - } - else - { - // Write delayed 0xFF bytes - if (delFF) - { - out_Renamed.write(0xFF); - delFF = false; - nrOfWrittenBytes++; - } - out_Renamed.write(b); - nrOfWrittenBytes++; - b = ((SupportClass.URShift(c, 19)) & 0xFF); - c &= 0x7FFFF; - cT = 8; - } - } - } - else - { - // NOTE: carry bit can never be set if the byte buffer was empty - b = (SupportClass.URShift(c, 19)); - c &= 0x7FFFF; - cT = 8; - nrOfWrittenBytes++; - } - } - - /// This function flushes the remaining encoded bits and makes sure that - /// enough information is written to the bit stream to be able to finish - /// decoding, and then it reinitializes the internal state of the MQ coder - /// but without modifying the context states. - /// - ///

    After calling this method the 'finishLengthCalculation()' method - /// should be called, after compensating the returned length for the length - /// of previous coded segments, so that the length calculation is - /// finalized.

    - /// - ///

    The type of termination used depends on the one specified at the - /// constructor.

    - /// - ///
    - /// The length of the arithmetic codeword after termination, in - /// bytes. - /// - /// - public virtual int terminate() - { - switch (ttype) - { - - case TERM_FULL: - //sets the remaining bits of the last byte of the coded bits. - int tempc = c + a; - c = c | 0xFFFF; - if (c >= tempc) - { - c = c - 0x8000; - } - - int remainingBits = 27 - cT; - - // Flushes remainingBits - do - { - c <<= cT; - if (b != 0xFF) - { - remainingBits -= 8; - } - else - { - remainingBits -= 7; - } - byteOut(); - } - while (remainingBits > 0); - - b |= (1 << (-remainingBits)) - 1; - if (b == 0xFF) - { - // Delay 0xFF bytes - delFF = true; - } - else - { - // Write delayed 0xFF bytes - if (delFF) - { - out_Renamed.write(0xFF); - delFF = false; - nrOfWrittenBytes++; - } - out_Renamed.write(b); - nrOfWrittenBytes++; - } - break; - - case TERM_PRED_ER: - case TERM_EASY: - // The predictable error resilient and easy termination are the - // same, except for the fact that the easy one can modify the - // spare bits in the last byte to maximize the likelihood of - // having a 0xFF, while the error resilient one can not touch - // these bits. - - // In the predictable error resilient case the spare bits will be - // recalculated by the decoder and it will check if they are the - // same as as in the codestream and then deduce an error - // probability from there. - - int k; // number of bits to push out - - k = (11 - cT) + 1; - - c <<= cT; - for (; k > 0; k -= cT, c <<= cT) - { - byteOut(); - } - - // Make any spare bits 1s if in easy termination - if (k < 0 && ttype == TERM_EASY) - { - // At this stage there is never a carry bit in C, so we can - // freely modify the (-k) least significant bits. - b |= (1 << (-k)) - 1; - } - - byteOut(); // Push contents of byte buffer - break; - - case TERM_NEAR_OPT: - - // This algorithm terminates in the shortest possible way, besides - // the fact any previous 0xFF 0x7F sequences are not - // eliminated. The probabalility of having those sequences is - // extremely low. - - // The calculation of the length is based on the fact that the - // decoder will pad the codestream with an endless string of - // (binary) 1s. If the codestream, padded with 1s, is within the - // bounds of the current interval then correct decoding is - // guaranteed. The lower inclusive bound of the current interval - // is the value of C (i.e. if only lower intervals would be coded - // in the future). The upper exclusive bound of the current - // interval is C+A (i.e. if only upper intervals would be coded in - // the future). We therefore calculate the minimum length that - // would be needed so that padding with 1s gives a codestream - // within the interval. - - // In general, such a calculation needs the value of the next byte - // that appears in the codestream. Here, since we are terminating, - // the next value can be anything we want that lies within the - // interval, we use the lower bound since this minimizes the - // length. To calculate the necessary length at any other place - // than the termination it is necessary to know the next bytes - // that will appear in the codestream, which involves storing the - // codestream and the sate of the MQCoder at various points (a - // worst case approach can be used, but it is much more - // complicated and the calculated length would be only marginally - // better than much simple calculations, if not the same). - - int cLow; - int cUp; - int bLow; - int bUp; - - // Initialize the upper (exclusive) and lower bound (inclusive) of - // the valid interval (the actual interval is the concatenation of - // bUp and cUp, and bLow and cLow). - cLow = c; - cUp = c + a; - bLow = bUp = b; - - // We start by normalizing the C register to the sate cT = 0 - // (i.e., just before byteOut() is called) - cLow <<= cT; - cUp <<= cT; - // Progate eventual carry bits and reset them in Clow, Cup NOTE: - // carry bit can never be set if the byte buffer was empty so no - // problem with propagating a carry into an empty byte buffer. - if ((cLow & (1 << 27)) != 0) - { - // Carry bit in cLow - if (bLow == 0xFF) - { - // We can not propagate carry bit, do bit stuffing - delFF = true; // delay 0xFF - // Get next byte buffer - bLow = SupportClass.URShift(cLow, 20); - bUp = SupportClass.URShift(cUp, 20); - cLow &= 0xFFFFF; - cUp &= 0xFFFFF; - // Normalize to cT = 0 - cLow <<= 7; - cUp <<= 7; - } - else - { - // we can propagate carry bit - bLow++; // propagate - cLow &= ~(1 << 27); // reset carry in cLow - } - } - if ((cUp & (1 << 27)) != 0) - { - bUp++; // propagate - cUp &= ~(1 << 27); // reset carry - } - - // From now on there can never be a carry bit on cLow, since we - // always output bLow. - - // Loop testing for the condition and doing byte output if they - // are not met. - while (true) - { - // If decoder's codestream is within interval stop - // If preceding byte is 0xFF only values [0,127] are valid - if (delFF) - { - // If delayed 0xFF - if (bLow <= 127 && bUp > 127) - break; - // We will write more bytes so output delayed 0xFF now - out_Renamed.write(0xFF); - nrOfWrittenBytes++; - delFF = false; - } - else - { - // No delayed 0xFF - if (bLow <= 255 && bUp > 255) - break; - } - - // Output next byte - // We could output anything within the interval, but using - // bLow simplifies things a lot. - - // We should not have any carry bit here - - // Output bLow - if (bLow < 255) - { - // Transfer byte bits from C to B - // (if the byte buffer was empty output nothing) - if (nrOfWrittenBytes >= 0) - out_Renamed.write(bLow); - nrOfWrittenBytes++; - bUp -= bLow; - bUp <<= 8; - // Here bLow would be 0 - bUp |= (SupportClass.URShift(cUp, 19)) & 0xFF; - bLow = (SupportClass.URShift(cLow, 19)) & 0xFF; - // Clear upper bits (just pushed out) from cUp Clow. - cLow &= 0x7FFFF; - cUp &= 0x7FFFF; - // Goto next state where CT is 0 - cLow <<= 8; - cUp <<= 8; - // Here there can be no carry on Cup, Clow - } - else - { - // bLow = 0xFF - // Transfer byte bits from C to B - // Since the byte to output is 0xFF we can delay it - delFF = true; - bUp -= bLow; - bUp <<= 7; - // Here bLow would be 0 - bUp |= (cUp >> 20) & 0x7F; - bLow = (cLow >> 20) & 0x7F; - // Clear upper bits (just pushed out) from cUp Clow. - cLow &= 0xFFFFF; - cUp &= 0xFFFFF; - // Goto next state where CT is 0 - cLow <<= 7; - cUp <<= 7; - // Here there can be no carry on Cup, Clow - } - } - break; - - default: - throw new System.ApplicationException("Illegal termination type code"); - - } - - // Reinitialize the state (without modifying the contexts) - int len; - - len = nrOfWrittenBytes; - a = 0x8000; - c = 0; - b = 0; - cT = 12; - delFF = false; - nrOfWrittenBytes = -1; - - // Return the terminated length - return len; - } - - /// Resets a context to the original probability distribution, and sets its - /// more probable symbol to 0. - /// - /// - /// The number of the context (it starts at 0). - /// - /// - public void resetCtxt(int c) - { - I[c] = initStates[c]; - mPS[c] = 0; - } - - /// Resets all contexts to their original probability distribution and sets - /// all more probable symbols to 0. - /// - /// - public void resetCtxts() - { - Array.Copy(initStates, 0, I, 0, I.Length); - ArrayUtil.intArraySet(mPS, 0); - } - - /// Reinitializes the MQ coder and the underlying 'ByteOutputBuffer' buffer - /// as if a new object was instantaited. All the data in the - /// 'ByteOutputBuffer' buffer is erased and the state and contexts of the - /// MQ coder are reinitialized). Additionally any saved MQ states are - /// discarded. - /// - /// - public void reset() - { - - // Reset the output buffer - out_Renamed.reset(); - - a = 0x8000; - c = 0; - b = 0; - if (b == 0xFF) - cT = 13; - else - cT = 12; - resetCtxts(); - nrOfWrittenBytes = -1; - delFF = false; - - nSaved = 0; - } - - /// Saves the current state of the MQ coder (just the registers, not the - /// contexts) so that a near optimal length calculation can be performed - /// later. - /// - /// - private void saveState() - { - // Increase capacity if necessary - if (nSaved == savedC.Length) - { - System.Object tmp; - tmp = savedC; - savedC = new int[nSaved + SAVED_INC]; - // CONVERSION PROBLEM? - Array.Copy((System.Array)tmp, 0, savedC, 0, nSaved); - tmp = savedCT; - savedCT = new int[nSaved + SAVED_INC]; - Array.Copy((System.Array)tmp, 0, savedCT, 0, nSaved); - tmp = savedA; - savedA = new int[nSaved + SAVED_INC]; - Array.Copy((System.Array)tmp, 0, savedA, 0, nSaved); - tmp = savedB; - savedB = new int[nSaved + SAVED_INC]; - Array.Copy((System.Array)tmp, 0, savedB, 0, nSaved); - tmp = savedDelFF; - savedDelFF = new bool[nSaved + SAVED_INC]; - Array.Copy((System.Array)tmp, 0, savedDelFF, 0, nSaved); - } - // Save the current sate - savedC[nSaved] = c; - savedCT[nSaved] = cT; - savedA[nSaved] = a; - savedB[nSaved] = b; - savedDelFF[nSaved] = delFF; - nSaved++; - } - - /// Terminates the calculation of the required length for each coding - /// pass. This method must be called just after the 'terminate()' one has - /// been called for each terminated MQ segment. - /// - ///

    The values in 'rates' must have been compensated for any offset due - /// to previous terminated segments, so that the correct index to the - /// stored coded data is used.

    - /// - ///
    - /// The array containing the values returned by - /// 'getNumCodedBytes()' for each coding pass. - /// - /// - /// The index in the 'rates' array of the last terminated length. - /// - /// - public virtual void finishLengthCalculation(int[] rates, int n) - { - if (ltype != LENGTH_NEAR_OPT) - { - // For the simple calculations the only thing we need to do is to - // ensure that the calculated lengths are no greater than the - // terminated one - if (n > 0 && rates[n - 1] > rates[n]) - { - // We need correction - int tl = rates[n]; // The terminated length - n--; - do - { - rates[n--] = tl; - } - while (n >= 0 && rates[n] > tl); - } - } - else - { - // We need to perform the more sophisticated near optimal - // calculation. - - // The calculation of the length is based on the fact that the - // decoder will pad the codestream with an endless string of - // (binary) 1s after termination. If the codestream, padded with - // 1s, is within the bounds of the current interval then correct - // decoding is guaranteed. The lower inclusive bound of the - // current interval is the value of C (i.e. if only lower - // intervals would be coded in the future). The upper exclusive - // bound of the current interval is C+A (i.e. if only upper - // intervals would be coded in the future). We therefore calculate - // the minimum length that would be needed so that padding with 1s - // gives a codestream within the interval. - - // In order to know what will be appended to the current base of - // the interval we need to know what is in the MQ bit stream after - // the current last output byte until the termination. This is why - // this calculation has to be performed after the MQ segment has - // been entirely coded and terminated. - - int cLow; // lower bound on the C register for correct decoding - int cUp; // upper bound on the C register for correct decoding - int bLow; // lower bound on the byte buffer for correct decoding - int bUp; // upper bound on the byte buffer for correct decoding - int ridx; // index in the rates array of the pass we are - // calculating - int sidx; // index in the saved state array - int clen; // current calculated length - bool cdFF; // the current delayed FF state - int nb; // the next byte of output - int minlen; // minimum possible length - int maxlen; // maximum possible length - - // Start on the first pass of this segment - ridx = n - nSaved; - // Minimum allowable length is length of previous termination - minlen = (ridx - 1 >= 0) ? rates[ridx - 1] : 0; - // Maximum possible length is the terminated length - maxlen = rates[n]; - for (sidx = 0; ridx < n; ridx++, sidx++) - { - // Load the initial values of the bounds - cLow = savedC[sidx]; - cUp = savedC[sidx] + savedA[sidx]; - bLow = savedB[sidx]; - bUp = savedB[sidx]; - // Normalize to cT=0 and propagate and reset any carry bits - cLow <<= savedCT[sidx]; - if ((cLow & 0x8000000) != 0) - { - bLow++; - cLow &= 0x7FFFFFF; - } - cUp <<= savedCT[sidx]; - if ((cUp & 0x8000000) != 0) - { - bUp++; - cUp &= 0x7FFFFFF; - } - // Initialize current calculated length - cdFF = savedDelFF[sidx]; - // rates[ridx] contains the number of bytes already output - // when the state was saved, compensated for the offset in the - // output stream. - clen = rates[ridx] + (cdFF ? 1 : 0); - while (true) - { - // If we are at end of coded data then this is the length - if (clen >= maxlen) - { - clen = maxlen; - break; - } - // Check for sufficiency of coded data - if (cdFF) - { - if (bLow < 128 && bUp >= 128) - { - // We are done for this pass - clen--; // Don't need delayed FF - break; - } - } - else - { - if (bLow < 256 && bUp >= 256) - { - // We are done for this pass - break; - } - } - // Update bounds with next byte of coded data and - // normalize to cT = 0 again. - nb = (clen >= minlen) ? out_Renamed.getByte(clen) : 0; - bLow -= nb; - bUp -= nb; - clen++; - if (nb == 0xFF) - { - bLow <<= 7; - bLow |= (cLow >> 20) & 0x7F; - cLow &= 0xFFFFF; - cLow <<= 7; - bUp <<= 7; - bUp |= (cUp >> 20) & 0x7F; - cUp &= 0xFFFFF; - cUp <<= 7; - cdFF = true; - } - else - { - bLow <<= 8; - bLow |= (cLow >> 19) & 0xFF; - cLow &= 0x7FFFF; - cLow <<= 8; - bUp <<= 8; - bUp |= (cUp >> 19) & 0xFF; - cUp &= 0x7FFFF; - cUp <<= 8; - cdFF = false; - } - // Test again - } - // Store the rate found - rates[ridx] = (clen >= minlen) ? clen : minlen; - } - // Reset the saved states - nSaved = 0; - } - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/entropy/encoder/PostCompRateAllocator.cs b/CSJ2K/j2k/entropy/encoder/PostCompRateAllocator.cs deleted file mode 100644 index 6bc2b711..00000000 --- a/CSJ2K/j2k/entropy/encoder/PostCompRateAllocator.cs +++ /dev/null @@ -1,368 +0,0 @@ -/* -* CVS identifier: -* -* $Id: PostCompRateAllocator.java,v 1.53 2001/08/28 09:24:47 grosbois Exp $ -* -* Class: PostCompRateAllocator -* -* Description: Generic interface for post-compression -* rate allocator. -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.codestream; -using CSJ2K.j2k.codestream.writer; -using CSJ2K.j2k.encoder; -using CSJ2K.j2k.image; -using CSJ2K.j2k.util; -namespace CSJ2K.j2k.entropy.encoder -{ - - /// This is the abstract class from which post-compression rate allocators - /// which generate layers should inherit. The source of data is a - /// 'CodedCBlkDataSrcEnc' which delivers entropy coded blocks with - /// rate-distortion statistics. - /// - ///

    The post compression rate allocator implementation should create the - /// layers, according to a rate allocation policy, and send the packets to a - /// CodestreamWriter. Since the rate allocator sends the packets to the bit - /// stream then it should output the packets to the bit stream in the order - /// imposed by the bit stream profiles.

    - /// - ///
    - /// - /// - /// - /// - /// - public abstract class PostCompRateAllocator : ImgDataAdapter - { - /// Keep a reference to the header encoder. - /// - /// - /// The header encoder - /// - /// - virtual public HeaderEncoder HeaderEncoder - { - set - { - this.headEnc = value; - } - - } - /// Returns the number of layers that are actually generated. - /// - /// - /// The number of layers generated. - /// - /// - virtual public int NumLayers - { - get - { - return num_Layers; - } - - } - /// Returns the parameters that are used in this class and implementing - /// classes. It returns a 2D String array. Each of the 1D arrays is for a - /// different option, and they have 3 elements. The first element is the - /// option name, the second one is the synopsis, the third one is a long - /// description of what the parameter is and the fourth is its default - /// value. The synopsis or description may be 'null', in which case it is - /// assumed that there is no synopsis or description of the option, - /// respectively. Null may be returned if no options are supported. - /// - /// - /// the options name, their synopsis and their explanation, - /// or null if no options are supported. - /// - /// - public static System.String[][] ParameterInfo - { - get - { - return pinfo; - } - - } - - /// The prefix for rate allocation options: 'A' - public const char OPT_PREFIX = 'A'; - - /// The list of parameters that is accepted for entropy coding. Options - /// for entropy coding start with 'R'. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'pinfo'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly System.String[][] pinfo = new System.String[][]{new System.String[]{"Aptype", "[] res|layer|res-pos|" + "pos-comp|comp-pos [res_start comp_start layer_end res_end " + "comp_end " + "prog] [[res_start comp_start ly_end res_end comp_end prog] ...] [" + "[] ...]", "Specifies which type of progression should be used when " + "generating " + "the codestream. The 'res' value generates a resolution " + "progressive codestream with the number of layers specified by " + "'Alayers' option. The 'layer' value generates a layer progressive " + "codestream with multiple layers. In any case the rate-allocation " + "algorithm optimizes for best quality in each layer. The quality " + "measure is mean squared error (MSE) or a weighted version of it " + "(WMSE). If no progression type is specified or imposed by other " + "modules, the default value is 'layer'.\n" + "It is also possible to describe progression order changes. In " + "this case, 'res_start' is the index (from 0) of the first " + "resolution " + "level, 'comp_start' is the index (from 0) of the first component, " + "'ly_end' is the index (from 0) of the first layer not included, " + "'res_end' is the index (from 0) of the first resolution level not " + "included, 'comp_end' is index (from 0) of the first component not " + "included and 'prog' is the progression type to be used " + "for the rest of the tile/image. Several progression order changes " + "can be specified, one after the other.", null}, new System.String[]{"Alayers", "[ [+] [] [...]] | sl]", "Explicitly specifies the codestream layer formation parameters. " + "The parameter specifies the bitrate to which the first " + "layer should be optimized. The parameter, if present, " + "specifies the number of extra layers that should be added for " + "scalability. These extra layers are not optimized. " + "Any extra and parameters add more layers, in the " + - "same way. An additional layer is always added at the end, which" + " is " + "optimized to the overall target bitrate of the bit stream. Any " + "layers (optimized or not) whose target bitrate is higher that the " + "overall target bitrate are silently ignored. The bitrates of the " + "extra layers that are added through the parameter are " + "approximately log-spaced between the other target bitrates. If " + "several [+] constructs appear the " + " parameters " + "must appear in increasing order. The rate allocation algorithm " + "ensures that all coded layers have a minimal reasonable size, if " + "not these layers are silently ignored.\n" + "If the 'sl' (i.e. 'single layer') argument is specified, the " + "generated codestream will" + " only contain one layer (with a bit rate specified thanks to the" + " '-rate' or 'nbytes' options).", "0.015 +20 2.0 +10"}}; - - /// The source of entropy coded data - protected internal CodedCBlkDataSrcEnc src; - - /// The source of entropy coded data - protected internal EncoderSpecs encSpec; - - /// The number of layers. - protected internal int num_Layers; - - /// The bit-stream writer - internal CodestreamWriter bsWriter; - - /// The header encoder - internal HeaderEncoder headEnc; - - /// Initializes the source of entropy coded data. - /// - /// - /// The source of entropy coded data. - /// - /// - /// The number of layers to create - /// - /// - /// The progressive type, as defined in 'ProgressionType'. - /// - /// - /// The packet bit stream writer. - /// - /// - /// - /// - /// - public PostCompRateAllocator(CodedCBlkDataSrcEnc src, int nl, CodestreamWriter bw, EncoderSpecs encSpec) : base(src) - { - this.src = src; - this.encSpec = encSpec; - num_Layers = nl; - bsWriter = bw; - } - - /// Initializes the rate allocation points, taking into account header - /// overhead and such. This method must be called after the header has been - /// simulated but before calling the runAndWrite() one. The header must be - /// rewritten after a call to this method since the number of layers may - /// change. - /// - /// - /// Whether or not the old syntax is used. - /// - /// - /// - /// - /// - public abstract void initialize(); - - /// Runs the rate allocation algorithm and writes the data to the - /// bit stream. This must be called after the initialize() method. - /// - /// - /// - /// - /// - public abstract void runAndWrite(); - - /// Creates a PostCompRateAllocator object for the appropriate rate - /// allocation parameters in the parameter list 'pl', having 'src' as the - /// source of entropy coded data, 'rate' as the target bitrate and 'bw' as - /// the bit stream writer object. - /// - /// - /// The source of entropy coded data. - /// - /// - /// The parameter lis (or options). - /// - /// - /// The target bitrate for the rate allocation - /// - /// - /// The bit stream writer object, where the bit stream data will - /// be written. - /// - /// - public static PostCompRateAllocator createInstance(CodedCBlkDataSrcEnc src, ParameterList pl, float rate, CodestreamWriter bw, EncoderSpecs encSpec) - { - // Check parameters - pl.checkList(OPT_PREFIX, CSJ2K.j2k.util.ParameterList.toNameArray(pinfo)); - - // Construct the layer specification from the 'Alayers' option - LayersInfo lyrs = parseAlayers(pl.getParameter("Alayers"), rate); - - int nTiles = encSpec.nTiles; - int nComp = encSpec.nComp; - int numLayers = lyrs.TotNumLayers; - - // Parse the progressive type - encSpec.pocs = new ProgressionSpec(nTiles, nComp, numLayers, encSpec.dls, ModuleSpec.SPEC_TYPE_TILE_COMP, pl); - - return new EBCOTRateAllocator(src, lyrs, bw, encSpec, pl); - } - - /// Convenience method that parses the 'Alayers' option. - /// - /// - /// The parameters of the 'Alayers' option - /// - /// - /// The overall target bitrate - /// - /// - /// The layer specification. - /// - /// - private static LayersInfo parseAlayers(System.String params_Renamed, float rate) - { - LayersInfo lyrs; - SupportClass.StreamTokenizerSupport stok; - bool islayer, ratepending; - float r; - - lyrs = new LayersInfo(rate); - stok = new SupportClass.StreamTokenizerSupport(new System.IO.StringReader(params_Renamed)); - stok.EOLIsSignificant(false); - - try - { - stok.NextToken(); - } - catch (System.IO.IOException) - { - throw new System.ApplicationException("An IOException has ocurred where it " + "should never occur"); - } - ratepending = false; - islayer = false; - r = 0; // to keep compiler happy - while (stok.ttype != SupportClass.StreamTokenizerSupport.TT_EOF) - { - switch (stok.ttype) - { - - case SupportClass.StreamTokenizerSupport.TT_NUMBER: - if (islayer) - { - // layer parameter - try - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - lyrs.addOptPoint(r, (int)stok.nval); - } - catch (System.ArgumentException e) - { - //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Throwable.getMessage' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" - throw new System.ArgumentException("Error in 'Alayers' " + "option: " + e.Message); - } - ratepending = false; - islayer = false; - } - else - { - // rate parameter - if (ratepending) - { - // Add pending rate parameter - try - { - lyrs.addOptPoint(r, 0); - } - catch (System.ArgumentException e) - { - //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Throwable.getMessage' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" - throw new System.ArgumentException("Error in 'Alayers' " + "option: " + e.Message); - } - } - // Now store new rate parameter - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - r = (float)stok.nval; - ratepending = true; - } - break; - - case '+': - if (!ratepending || islayer) - { - throw new System.ArgumentException("Layer parameter without " + "previous rate parameter " + "in 'Alayers' option"); - } - islayer = true; // Next number is layer parameter - break; - - case SupportClass.StreamTokenizerSupport.TT_WORD: - try - { - stok.NextToken(); - } - catch (System.IO.IOException) - { - throw new System.ApplicationException("An IOException has ocurred where it " + "should never occur"); - } - if (stok.ttype != SupportClass.StreamTokenizerSupport.TT_EOF) - { - throw new System.ArgumentException("'sl' argument of " + "'-Alayers' option must be " + "used alone."); - } - break; - - default: - throw new System.ArgumentException("Error parsing 'Alayers' " + "option"); - - } - try - { - stok.NextToken(); - } - catch (System.IO.IOException) - { - throw new System.ApplicationException("An IOException has ocurred where it " + "should never occur"); - } - } - if (islayer) - { - throw new System.ArgumentException("Error parsing 'Alayers' " + "option"); - } - if (ratepending) - { - try - { - lyrs.addOptPoint(r, 0); - } - catch (System.ArgumentException e) - { - //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Throwable.getMessage' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" - throw new System.ArgumentException("Error in 'Alayers' " + "option: " + e.Message); - } - } - return lyrs; - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/entropy/encoder/StdEntropyCoder.cs b/CSJ2K/j2k/entropy/encoder/StdEntropyCoder.cs deleted file mode 100644 index 4bb3da74..00000000 --- a/CSJ2K/j2k/entropy/encoder/StdEntropyCoder.cs +++ /dev/null @@ -1,3725 +0,0 @@ -/* -* CVS identifier: -* -* $Id: StdEntropyCoder.java,v 1.41 2002/07/04 15:53:32 grosbois Exp $ -* -* Class: StdEntropyCoder -* -* Description: Entropy coding engine of stripes in code-blocks -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.image; -using CSJ2K.j2k.quantization.quantizer; -using CSJ2K.j2k.util; -using CSJ2K.j2k.wavelet; -using CSJ2K.j2k.wavelet.analysis; -using System; -namespace CSJ2K.j2k.entropy.encoder -{ - - /// This class implements the JPEG 2000 entropy coder, which codes stripes in - /// code-blocks. This entropy coding engine can function in a single-threaded - /// mode where one code-block is encoded at a time, or in a multi-threaded mode - /// where multiple code-blocks are entropy coded in parallel. The interface - /// presented by this class is the same in both modes. - /// - ///

    The number of threads used by this entropy coder is specified by the - /// "jj2000.j2k.entropy.encoder.StdEntropyCoder.nthreads" Java system - /// property. If set to "0" the single threaded implementation is used. If set - /// to 'n' ('n' larger than 0) then 'n' extra threads are started by this class - /// which are used to encode the code-blocks in parallel (i.e. ideally 'n' - /// code-blocks will be encoded in parallel at a time). On multiprocessor - /// machines under a "native threads" Java Virtual Machine implementation each - /// one of these threads can run on a separate processor speeding up the - /// encoding time. By default the single-threaded implementation is used. The - /// multi-threaded implementation currently assumes that the vast majority of - /// consecutive calls to 'getNextCodeBlock()' will be done on the same - /// component. If this is not the case, the speed-up that can be expected on - /// multiprocessor machines might be significantly decreased.

    - /// - ///

    The code-blocks are rectangular, with dimensions which must be powers of - /// 2. Each dimension has to be no smaller than 4 and no larger than 256. The - /// product of the two dimensions (i.e. area of the code-block) may not exceed - /// 4096.

    - /// - ///

    Context 0 of the MQ-coder is used as the uniform one (uniform, - /// non-adaptive probability distribution). Context 1 is used for RLC - /// coding. Contexts 2-10 are used for zero-coding (ZC), contexts 11-15 are - /// used for sign-coding (SC) and contexts 16-18 are used for - /// magnitude-refinement (MR).

    - /// - ///

    This implementation buffers the symbols and calls the MQ coder only once - /// per stripe and per coding pass, to reduce the method call overhead.

    - /// - ///

    This implementation also provides some timing features. They can be - /// enabled by setting the 'DO_TIMING' constant of this class to true and - /// recompiling. The timing uses the 'System.currentTimeMillis()' Java API - /// call, which returns wall clock time, not the actual CPU time used. The - /// timing results will be printed on the message output. Since the times - /// reported are wall clock times and not CPU usage times they can not be added - /// to find the total used time (i.e. some time might be counted in several - /// places). When timing is disabled ('DO_TIMING' is false) there is no penalty - /// if the compiler performs some basic optimizations. Even if not the penalty - /// should be negligeable.

    - /// - ///

    The source module must implement the CBlkQuantDataSrcEnc interface and - /// code-block's data is received in a CBlkWTData instance. This modules sends - /// code-block's information in a CBlkRateDistStats instance.

    - /// - ///
    - /// - /// - /// - /// - /// - /// - /// - public class StdEntropyCoder : EntropyCoder - { - - /// Whether to collect timing information or not: false. Used as a compile - /// time directive. - /// - private const bool DO_TIMING = false; - - /// The cumulative wall time for the entropy coding engine, for each - /// component. In the single-threaded implementation it is the total time, - /// in the multi-threaded implementation it is the time spent managing the - /// compressor threads only. - /// - //private long[] time; - - /// The Java system property name for the number of threads to use: - /// jj2000.j2k.entropy.encoder.StdEntropyCoder.nthreads - /// - public const System.String THREADS_PROP_NAME = "jj2000.j2k.entropy.encoder.StdEntropyCoder.nthreads"; - - /// The default value for the property in THREADS_PROP_NAME: 0 - public const System.String DEF_THREADS_NUM = "0"; - - /// The increase in priority for the compressor threads, currently 3. The - /// compressor threads will have a priority of THREADS_PRIORITY_INC more - /// than the priority of the thread calling this class constructor. Used - /// only in the multi-threaded implementation. - /// - public const int THREADS_PRIORITY_INC = 0; - - /// The pool of threads, for the threaded implementation. It is null, if - /// non threaded implementation is used - /// - private ThreadPool tPool; - - /// The queue of idle compressors. Used in multithreaded - /// implementation only - /// - private System.Collections.ArrayList idleComps; - - /// The queue of completed compressors, for each component. Used - /// in multithreaded implementation only. - /// - private System.Collections.ArrayList[] completedComps; - - /// The number of busy compressors, for each component. Used in - /// multithreaded implementation only. - /// - private int[] nBusyComps; - - /// A flag indicating for each component if all the code-blocks of the * - /// current tile have been returned. Used in multithreaded implementation - /// only. - /// - private bool[] finishedTileComponent; - - /// The MQ coder used, for each thread - private MQCoder[] mqT; - - /// The raw bit output used, for each thread - private BitToByteOutput[] boutT; - - /// The output stream used, for each thread - private ByteOutputBuffer[] outT; - - /// The code-block size specifications - private CBlkSizeSpec cblks; - - /// The precinct partition specifications - private PrecinctSizeSpec pss; - - /// By-pass mode specifications - public StringSpec bms; - - /// MQ reset specifications - public StringSpec mqrs; - - /// Regular termination specifications - public StringSpec rts; - - /// Causal stripes specifications - public StringSpec css; - - /// Error resilience segment symbol use specifications - public StringSpec sss; - - /// The length calculation specifications - public StringSpec lcs; - - /// The termination type specifications - public StringSpec tts; - - /// The options that are turned on, as flag bits. One element for each - /// tile-component. The options are 'OPT_TERM_PASS', 'OPT_RESET_MQ', - /// 'OPT_VERT_STR_CAUSAL', 'OPT_BYPASS' and 'OPT_SEG_SYMBOLS' as defined in - /// the StdEntropyCoderOptions interface - /// - /// - /// - /// - /// - private int[][] opts = null; - - /// The length calculation type for each tile-component - private int[][] lenCalc = null; - - /// The termination type for each tile-component - private int[][] tType = null; - - /// Number of bits used for the Zero Coding lookup table - private const int ZC_LUT_BITS = 8; - - /// Zero Coding context lookup tables for the LH global orientation - //UPGRADE_NOTE: Final was removed from the declaration of 'ZC_LUT_LH '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int[] ZC_LUT_LH = new int[1 << ZC_LUT_BITS]; - - /// Zero Coding context lookup tables for the HL global orientation - //UPGRADE_NOTE: Final was removed from the declaration of 'ZC_LUT_HL '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int[] ZC_LUT_HL = new int[1 << ZC_LUT_BITS]; - - /// Zero Coding context lookup tables for the HH global orientation - //UPGRADE_NOTE: Final was removed from the declaration of 'ZC_LUT_HH '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int[] ZC_LUT_HH = new int[1 << ZC_LUT_BITS]; - - /// Number of bits used for the Sign Coding lookup table - private const int SC_LUT_BITS = 9; - - /// Sign Coding context lookup table. The index into the table is a 9 bit - /// index, which correspond the the value in the 'state' array shifted by - /// 'SC_SHIFT'. Bits 8-5 are the signs of the horizontal-left, - /// horizontal-right, vertical-up and vertical-down neighbors, - /// respectively. Bit 4 is not used (0 or 1 makes no difference). Bits 3-0 - /// are the significance of the horizontal-left, horizontal-right, - /// vertical-up and vertical-down neighbors, respectively. The least 4 bits - /// of the value in the lookup table define the context number and the sign - /// bit defines the "sign predictor". - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'SC_LUT '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int[] SC_LUT = new int[1 << SC_LUT_BITS]; - - /// The mask to obtain the context index from the 'SC_LUT' - private const int SC_LUT_MASK = (1 << 4) - 1; - - /// The shift to obtain the sign predictor from the 'SC_LUT'. It must be - /// an unsigned shift. - /// - private const int SC_SPRED_SHIFT = 31; - - /// The sign bit for int data - private const int INT_SIGN_BIT = 1 << 31; - - /// The number of bits used for the Magnitude Refinement lookup table - private const int MR_LUT_BITS = 9; - - /// Magnitude Refinement context lookup table - //UPGRADE_NOTE: Final was removed from the declaration of 'MR_LUT '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int[] MR_LUT = new int[1 << MR_LUT_BITS]; - - /// The number of contexts used - private const int NUM_CTXTS = 19; - - /// The RLC context - private const int RLC_CTXT = 1; - - /// The UNIFORM context (with a uniform probability distribution which - /// does not adapt) - /// - private const int UNIF_CTXT = 0; - - /// The initial states for the MQ coder - //UPGRADE_NOTE: Final was removed from the declaration of 'MQ_INIT'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int[] MQ_INIT = new int[] { 46, 3, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; - - /// The 4 bits of the error resilience segmentation symbol (1010) - //UPGRADE_NOTE: Final was removed from the declaration of 'SEG_SYMBOLS'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int[] SEG_SYMBOLS = new int[] { 1, 0, 1, 0 }; - - /// The 4 contexts for the error resilience segmentation symbol (always - /// the UNIFORM context, UNIF_CTXT) - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'SEG_SYMB_CTXTS '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int[] SEG_SYMB_CTXTS = new int[] { UNIF_CTXT, UNIF_CTXT, UNIF_CTXT, UNIF_CTXT }; - - /// The state array for each thread. Each element of the state array stores - /// the state of two coefficients. The lower 16 bits store the state of a - /// coefficient in row 'i' and column 'j', while the upper 16 bits store - /// the state of a coefficient in row 'i+1' and column 'j'. The 'i' row is - /// either the first or the third row of a stripe. This packing of the - /// states into 32 bit words allows a faster scan of all coefficients on - /// each coding pass and diminished the amount of data transferred. The - /// size of the state array is increased by 1 on each side (top, bottom, - /// left, right) to handle boundary conditions without any special logic. - /// - ///

    The state of a coefficient is stored in the following way in the - /// lower 16 bits, where bit 0 is the least significant bit. Bit 15 is the - /// significance of a coefficient (0 if non-significant, 1 otherwise). Bit - /// 14 is the visited state (i.e. if a coefficient has been coded in the - /// significance propagation pass of the current bit-plane). Bit 13 is the - /// "non zero-context" state (i.e. if one of the eight immediate neighbors - /// is significant it is 1, otherwise is 0). Bits 12 to 9 store the sign of - /// the already significant left, right, up and down neighbors (1 for - /// negative, 0 for positive or not yet significant). Bit 8 indicates if - /// the magnitude refinement has already been applied to the - /// coefficient. Bits 7 to 4 store the significance of the left, right, up - /// and down neighbors (1 for significant, 0 for non significant). Bits 3 - /// to 0 store the significance of the diagonal coefficients (up-left, - /// up-right, down-left and down-right; 1 for significant, 0 for non - /// significant).

    - /// - ///

    The upper 16 bits the state is stored as in the lower 16 bits, but - /// with the bits shifted up by 16.

    - /// - ///

    The lower 16 bits are referred to as "row 1" ("R1") while the upper - /// 16 bits are referred to as "row 2" ("R2").

    - /// - ///
    - private int[][] stateT; - - /* The separation between the upper and lower bits in the state array: 16 - * */ - private const int STATE_SEP = 16; - - /// The flag bit for the significance in the state array, for row 1. - private const int STATE_SIG_R1 = 1 << 15; - - /// The flag bit for the "visited" bit in the state array, for row 1. - private const int STATE_VISITED_R1 = 1 << 14; - - /// The flag bit for the "not zero context" bit in the state array, for - /// row 1. This bit is always the OR of bits STATE_H_L_R1, STATE_H_R_R1, - /// STATE_V_U_R1, STATE_V_D_R1, STATE_D_UL_R1, STATE_D_UR_R1, STATE_D_DL_R1 - /// and STATE_D_DR_R1. - /// - private const int STATE_NZ_CTXT_R1 = 1 << 13; - - /// The flag bit for the horizontal-left sign in the state array, for row - /// 1. This bit can only be set if the STATE_H_L_R1 is also set. - /// - private const int STATE_H_L_SIGN_R1 = 1 << 12; - - /// The flag bit for the horizontal-right sign in the state array, for - /// row 1. This bit can only be set if the STATE_H_R_R1 is also set. - /// - private const int STATE_H_R_SIGN_R1 = 1 << 11; - - /// The flag bit for the vertical-up sign in the state array, for row - /// 1. This bit can only be set if the STATE_V_U_R1 is also set. - /// - private const int STATE_V_U_SIGN_R1 = 1 << 10; - - /// The flag bit for the vertical-down sign in the state array, for row - /// 1. This bit can only be set if the STATE_V_D_R1 is also set. - /// - private const int STATE_V_D_SIGN_R1 = 1 << 9; - - /// The flag bit for the previous MR primitive applied in the state array, - /// for row 1. - /// - private const int STATE_PREV_MR_R1 = 1 << 8; - - /// The flag bit for the horizontal-left significance in the state array, - /// for row 1. - /// - private const int STATE_H_L_R1 = 1 << 7; - - /// The flag bit for the horizontal-right significance in the state array, - /// for row 1. - /// - private const int STATE_H_R_R1 = 1 << 6; - - /// The flag bit for the vertical-up significance in the state array, for - /// row 1. - /// - private const int STATE_V_U_R1 = 1 << 5; - - /// The flag bit for the vertical-down significance in the state array, - /// for row 1. - /// - private const int STATE_V_D_R1 = 1 << 4; - - /// The flag bit for the diagonal up-left significance in the state array, - /// for row 1. - /// - private const int STATE_D_UL_R1 = 1 << 3; - - /// The flag bit for the diagonal up-right significance in the state - /// array, for row 1. - /// - private const int STATE_D_UR_R1 = 1 << 2; - - /// The flag bit for the diagonal down-left significance in the state - /// array, for row 1. - /// - private const int STATE_D_DL_R1 = 1 << 1; - - /// The flag bit for the diagonal down-right significance in the state - /// array , for row 1. - /// - private const int STATE_D_DR_R1 = 1; - - /// The flag bit for the significance in the state array, for row 2. - //UPGRADE_NOTE: Final was removed from the declaration of 'STATE_SIG_R2 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int STATE_SIG_R2 = STATE_SIG_R1 << STATE_SEP; - - /// The flag bit for the "visited" bit in the state array, for row 2. - //UPGRADE_NOTE: Final was removed from the declaration of 'STATE_VISITED_R2 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int STATE_VISITED_R2 = STATE_VISITED_R1 << STATE_SEP; - - /// The flag bit for the "not zero context" bit in the state array, for - /// row 2. This bit is always the OR of bits STATE_H_L_R2, STATE_H_R_R2, - /// STATE_V_U_R2, STATE_V_D_R2, STATE_D_UL_R2, STATE_D_UR_R2, STATE_D_DL_R2 - /// and STATE_D_DR_R2. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'STATE_NZ_CTXT_R2 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int STATE_NZ_CTXT_R2 = STATE_NZ_CTXT_R1 << STATE_SEP; - - /// The flag bit for the horizontal-left sign in the state array, for row - /// 2. This bit can only be set if the STATE_H_L_R2 is also set. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'STATE_H_L_SIGN_R2 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int STATE_H_L_SIGN_R2 = STATE_H_L_SIGN_R1 << STATE_SEP; - - /// The flag bit for the horizontal-right sign in the state array, for - /// row 2. This bit can only be set if the STATE_H_R_R2 is also set. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'STATE_H_R_SIGN_R2 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int STATE_H_R_SIGN_R2 = STATE_H_R_SIGN_R1 << STATE_SEP; - - /// The flag bit for the vertical-up sign in the state array, for row - /// 2. This bit can only be set if the STATE_V_U_R2 is also set. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'STATE_V_U_SIGN_R2 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int STATE_V_U_SIGN_R2 = STATE_V_U_SIGN_R1 << STATE_SEP; - - /// The flag bit for the vertical-down sign in the state array, for row - /// 2. This bit can only be set if the STATE_V_D_R2 is also set. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'STATE_V_D_SIGN_R2 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int STATE_V_D_SIGN_R2 = STATE_V_D_SIGN_R1 << STATE_SEP; - - /// The flag bit for the previous MR primitive applied in the state array, - /// for row 2. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'STATE_PREV_MR_R2 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int STATE_PREV_MR_R2 = STATE_PREV_MR_R1 << STATE_SEP; - - /// The flag bit for the horizontal-left significance in the state array, - /// for row 2. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'STATE_H_L_R2 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int STATE_H_L_R2 = STATE_H_L_R1 << STATE_SEP; - - /// The flag bit for the horizontal-right significance in the state array, - /// for row 2. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'STATE_H_R_R2 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int STATE_H_R_R2 = STATE_H_R_R1 << STATE_SEP; - - /// The flag bit for the vertical-up significance in the state array, for - /// row 2. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'STATE_V_U_R2 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int STATE_V_U_R2 = STATE_V_U_R1 << STATE_SEP; - - /// The flag bit for the vertical-down significance in the state array, - /// for row 2. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'STATE_V_D_R2 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int STATE_V_D_R2 = STATE_V_D_R1 << STATE_SEP; - - /// The flag bit for the diagonal up-left significance in the state array, - /// for row 2. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'STATE_D_UL_R2 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int STATE_D_UL_R2 = STATE_D_UL_R1 << STATE_SEP; - - /// The flag bit for the diagonal up-right significance in the state - /// array, for row 2. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'STATE_D_UR_R2 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int STATE_D_UR_R2 = STATE_D_UR_R1 << STATE_SEP; - - /// The flag bit for the diagonal down-left significance in the state - /// array, for row 2. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'STATE_D_DL_R2 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int STATE_D_DL_R2 = STATE_D_DL_R1 << STATE_SEP; - - /// The flag bit for the diagonal down-right significance in the state - /// array , for row 2. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'STATE_D_DR_R2 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int STATE_D_DR_R2 = STATE_D_DR_R1 << STATE_SEP; - - /// The mask to isolate the significance bits for row 1 and 2 of the state - /// array. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'SIG_MASK_R1R2 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int SIG_MASK_R1R2 = STATE_SIG_R1 | STATE_SIG_R2; - - /// The mask to isolate the visited bits for row 1 and 2 of the state - /// array. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'VSTD_MASK_R1R2 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int VSTD_MASK_R1R2 = STATE_VISITED_R1 | STATE_VISITED_R2; - - /// The mask to isolate the bits necessary to identify RLC coding state - /// (significant, visited and non-zero context, for row 1 and 2). - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'RLC_MASK_R1R2 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int RLC_MASK_R1R2 = STATE_SIG_R1 | STATE_SIG_R2 | STATE_VISITED_R1 | STATE_VISITED_R2 | STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2; - - /// The mask to obtain the ZC_LUT index from the state information - // This is needed because of the STATE_V_D_SIGN_R1, STATE_V_U_SIGN_R1, - // STATE_H_R_SIGN_R1, and STATE_H_L_SIGN_R1 bits. - private const int ZC_MASK = (1 << 8) - 1; - - /// The shift to obtain the SC index to 'SC_LUT' from the state - /// information, for row 1. - /// - private const int SC_SHIFT_R1 = 4; - - /// The shift to obtain the SC index to 'SC_LUT' from the state - /// information, for row 2. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'SC_SHIFT_R2 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int SC_SHIFT_R2 = SC_SHIFT_R1 + STATE_SEP; - - /// The bit mask to isolate the state bits relative to the sign coding - /// lookup table ('SC_LUT'). - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'SC_MASK '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int SC_MASK = (1 << SC_LUT_BITS) - 1; - - /// The mask to obtain the MR index to 'MR_LUT' from the 'state' - /// information. It is to be applied after the 'MR_SHIFT'. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'MR_MASK '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int MR_MASK = (1 << MR_LUT_BITS) - 1; - - /// The number of bits used to index in the 'fm' lookup table, 7. The 'fs' - /// table is indexed with one less bit. - /// - private const int MSE_LKP_BITS = 7; - - private const int MSE_LKP_BITS_M1 = 6; - - /// The number of fractional bits used to store data in the 'fm' and 'fs' - /// lookup tables. - /// - private const int MSE_LKP_FRAC_BITS = 13; - - /// Distortion estimation lookup table for bits coded using the sign-code - /// (SC) primative, for lossy coding (i.e. normal). - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'FS_LOSSY '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int[] FS_LOSSY = new int[1 << MSE_LKP_BITS_M1]; - - /// Distortion estimation lookup table for bits coded using the - /// magnitude-refinement (MR) primative, for lossy coding (i.e. normal) - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'FM_LOSSY '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int[] FM_LOSSY = new int[1 << MSE_LKP_BITS]; - - /// Distortion estimation lookup table for bits coded using the sign-code - /// (SC) primative, for lossless coding and last bit-plane. This table is - /// different from 'fs_lossy' since when doing lossless coding the residual - /// distortion after the last bit-plane is coded is strictly 0. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'FS_LOSSLESS '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int[] FS_LOSSLESS = new int[1 << MSE_LKP_BITS_M1]; - - /// Distortion estimation lookup table for bits coded using the - /// magnitude-refinement (MR) primative, for lossless coding and last - /// bit-plane. This table is different from 'fs_lossless' since when doing - /// lossless coding the residual distortion after the last bit-plane is - /// coded is strictly 0. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'FM_LOSSLESS '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int[] FM_LOSSLESS = new int[1 << MSE_LKP_BITS]; - - /// The buffer for distortion values (avoids reallocation for each - /// code-block), for each thread. - /// - private double[][] distbufT; - - /// The buffer for rate values (avoids reallocation for each - /// code-block), for each thread. - /// - private int[][] ratebufT; - - /// The buffer for indicating terminated passes (avoids reallocation for - /// each code-block), for each thread. - /// - private bool[][] istermbufT; - - /// The source code-block to entropy code (avoids reallocation for each - /// code-block), for each thread. - /// - private CBlkWTData[] srcblkT; - - /// Buffer for symbols to send to the MQ-coder, for each thread. Used to - /// reduce the number of calls to the MQ coder. - /// - // NOTE: The symbol buffer has not prooved to be of any great improvement - // in encoding time, but it does not hurt. It's performance should be - // better studied under different JVMs. - private int[][] symbufT; - - /// Buffer for the contexts to use when sending buffered symbols to the - /// MQ-coder, for each thread. Used to reduce the number of calls to the MQ - /// coder. - /// - private int[][] ctxtbufT; - - /// boolean used to signal if the precinct partition is used for - /// each component and each tile. - /// - private bool[][] precinctPartition; - - //UPGRADE_NOTE: Field 'EnclosingInstance' was added to class 'Compressor' to access its enclosing instance. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1019'" - /// Class that takes care of running the 'compressCodeBlock()' method with - /// thread local arguments. Used only in multithreaded implementation. - /// - /// - private class Compressor : IThreadRunnable - { - private void InitBlock(StdEntropyCoder enclosingInstance) - { - this.enclosingInstance = enclosingInstance; - } - private StdEntropyCoder enclosingInstance; - /// Returns the index of this compressor. - /// - /// - /// The index of this compressor. - /// - /// - virtual public int Idx - { - get - { - return idx; - } - - } - public StdEntropyCoder Enclosing_Instance - { - get - { - return enclosingInstance; - } - - } - /// The index of this compressor. Used to access thread local - /// variables - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'idx '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private int idx; - - /// The object where to store the compressed code-block - // Should be private, but some buggy JDK 1.1 compilers complain - internal CBlkRateDistStats ccb; - - /// The component on which to compress - // Should be private, but some buggy JDK 1.1 compilers complain - internal int c; - - /// The options bitmask to use in compression - // Should be private, but some buggy JDK 1.1 compilers complain - internal int options; - - /// The reversible flag to use in compression - // Should be private, but some buggy JDK 1.1 compilers complain - internal bool rev; - - /// The length calculation type to use in compression - // Should be private, but some buggy JDK 1.1 compilers complain - internal int lcType; - - /// The MQ termination type to use in compression - // Should be private, but some buggy JDK 1.1 compilers complain - internal int tType; - - /// The cumulative wall time for this compressor, for each - /// component. - /// - //private long[] time; - - /// Creates a new compressor object with the given index. - /// - /// - /// The index of this compressor. - /// - /// - internal Compressor(StdEntropyCoder enclosingInstance, int idx) - { - InitBlock(enclosingInstance); - this.idx = idx; -#if DO_TIMING - time = new long[Enclosing_Instance.src.NumComps]; -#endif - } - - /// Calls the 'compressCodeBlock()' method with thread local - /// arguments. Once completed it adds itself to the 'completedComps[c]' - /// stack, where 'c' is the component for which this compressor is - /// running. This last step occurs even if exceptions are thrown by the - /// 'compressCodeBlock()' method. - /// - /// - public virtual void Run() - { - // Start the code-block compression - try - { -#if DO_TIMING - long stime = 0L; - stime = (System.DateTime.Now.Ticks - 621355968000000000) / 10000; -#endif - CSJ2K.j2k.entropy.encoder.StdEntropyCoder.compressCodeBlock(c, ccb, Enclosing_Instance.srcblkT[idx], Enclosing_Instance.mqT[idx], Enclosing_Instance.boutT[idx], Enclosing_Instance.outT[idx], Enclosing_Instance.stateT[idx], Enclosing_Instance.distbufT[idx], Enclosing_Instance.ratebufT[idx], Enclosing_Instance.istermbufT[idx], Enclosing_Instance.symbufT[idx], Enclosing_Instance.ctxtbufT[idx], options, rev, lcType, tType); -#if DO_TIMING - time[c] += (System.DateTime.Now.Ticks - 621355968000000000) / 10000 - stime; -#endif - } - finally - { - // Join the queue of completed compression, even if exceptions - // occurred. - Enclosing_Instance.completedComps[c].Add(this); - } - } - } - - /// Instantiates a new entropy coder engine, with the specified source of - /// data, nominal block width and height. - /// - ///

    If the 'OPT_PRED_TERM' option is given then the MQ termination must - /// be 'TERM_PRED_ER' or an exception is thrown.

    - /// - ///
    - /// The source of data - /// - /// - /// Code-block size specifications - /// - /// - /// Precinct partition specifications - /// - /// - /// By-pass mode specifications - /// - /// - /// MQ-reset specifications - /// - /// - /// Regular termination specifications - /// - /// - /// Causal stripes specifications - /// - /// - /// Error resolution segment symbol use specifications - /// - /// - /// Length computation specifications - /// - /// - /// Termination type specifications - /// - /// - /// - /// - /// - public StdEntropyCoder(CBlkQuantDataSrcEnc src, CBlkSizeSpec cblks, PrecinctSizeSpec pss, StringSpec bms, StringSpec mqrs, StringSpec rts, StringSpec css, StringSpec sss, StringSpec lcs, StringSpec tts) : base(src) - { - this.cblks = cblks; - this.pss = pss; - this.bms = bms; - this.mqrs = mqrs; - this.rts = rts; - this.css = css; - this.sss = sss; - this.lcs = lcs; - this.tts = tts; - int maxCBlkWidth, maxCBlkHeight; - int i; // Counter - int nt; // The number of threads - int tsl; // Size for thread structures - - // Get the biggest width/height for the code-blocks - maxCBlkWidth = cblks.MaxCBlkWidth; - maxCBlkHeight = cblks.MaxCBlkHeight; - - nt = Environment.ProcessorCount; - /* - // Get the number of threads to use, or default to one - try - { - //UPGRADE_ISSUE: Method 'java.lang.System.getProperty' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javalangSystem'" - nt = System.Int32.Parse(System_Renamed.getProperty(THREADS_PROP_NAME, DEF_THREADS_NUM)); - if (nt < 0) - throw new System.FormatException(); - } - catch (System.FormatException e) - { - throw new System.ArgumentException("Invalid number of threads " + "for " + "entropy coding in property " + THREADS_PROP_NAME); - } - */ - - // If we do timing create necessary structures -#if DO_TIMING - time = new long[src.NumComps]; - // If we are timing make sure that 'finalize' gets called. - //UPGRADE_ISSUE: Method 'java.lang.System.runFinalizersOnExit' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javalangSystem'" - // CONVERSION PROBLEM? - //System_Renamed.runFinalizersOnExit(true); -#endif - // If using multithreaded implementation get necessasry objects - if (nt > 0) - { - FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.INFO, "Using multithreaded entropy coder " + "with " + nt + " compressor threads."); - tsl = nt; - tPool = new ThreadPool(nt, (System.Int32)SupportClass.ThreadClass.Current().Priority + THREADS_PRIORITY_INC, "StdEntropyCoder"); - idleComps = new System.Collections.ArrayList(); - completedComps = new System.Collections.ArrayList[src.NumComps]; - nBusyComps = new int[src.NumComps]; - finishedTileComponent = new bool[src.NumComps]; - for (i = src.NumComps - 1; i >= 0; i--) - { - completedComps[i] = new System.Collections.ArrayList(); - } - for (i = 0; i < nt; i++) - { - idleComps.Add(new StdEntropyCoder.Compressor(this, i)); - } - } - else - { - tsl = 1; - tPool = null; - idleComps = null; - completedComps = null; - nBusyComps = null; - finishedTileComponent = null; - } - - // Allocate data structures - outT = new ByteOutputBuffer[tsl]; - mqT = new MQCoder[tsl]; - boutT = new BitToByteOutput[tsl]; - stateT = new int[tsl][]; - for (int i2 = 0; i2 < tsl; i2++) - { - stateT[i2] = new int[(maxCBlkWidth + 2) * ((maxCBlkHeight + 1) / 2 + 2)]; - } - symbufT = new int[tsl][]; - for (int i3 = 0; i3 < tsl; i3++) - { - symbufT[i3] = new int[maxCBlkWidth * (CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT * 2 + 2)]; - } - ctxtbufT = new int[tsl][]; - for (int i4 = 0; i4 < tsl; i4++) - { - ctxtbufT[i4] = new int[maxCBlkWidth * (CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT * 2 + 2)]; - } - distbufT = new double[tsl][]; - for (int i5 = 0; i5 < tsl; i5++) - { - distbufT[i5] = new double[32 * CSJ2K.j2k.entropy.StdEntropyCoderOptions.NUM_PASSES]; - } - ratebufT = new int[tsl][]; - for (int i6 = 0; i6 < tsl; i6++) - { - ratebufT[i6] = new int[32 * CSJ2K.j2k.entropy.StdEntropyCoderOptions.NUM_PASSES]; - } - istermbufT = new bool[tsl][]; - for (int i7 = 0; i7 < tsl; i7++) - { - istermbufT[i7] = new bool[32 * CSJ2K.j2k.entropy.StdEntropyCoderOptions.NUM_PASSES]; - } - srcblkT = new CBlkWTData[tsl]; - for (i = 0; i < tsl; i++) - { - outT[i] = new ByteOutputBuffer(); - mqT[i] = new MQCoder(outT[i], NUM_CTXTS, MQ_INIT); - } - precinctPartition = new bool[src.NumComps][]; - for (int i8 = 0; i8 < src.NumComps; i8++) - { - precinctPartition[i8] = new bool[src.getNumTiles()]; - } - - // Create the subband description for each component and each tile - //Subband sb = null; - Coord numTiles = null; - int nc = NumComps; - numTiles = src.getNumTiles(numTiles); - initTileComp(getNumTiles(), nc); - - for (int c = 0; c < nc; c++) - { - for (int tY = 0; tY < numTiles.y; tY++) - { - for (int tX = 0; tX < numTiles.x; tX++) - { - precinctPartition[c][tIdx] = false; - } - } - } - } - -#if DO_TIMING - /// Prints the timing information, if collected, and calls 'finalize' on - /// the super class. - /// - /// - ~StdEntropyCoder() - { - - int c; - System.Text.StringBuilder sb; - - if (tPool == null) - { - // Single threaded implementation - sb = new System.Text.StringBuilder("StdEntropyCoder compression wall " + "clock time:"); - for (c = 0; c < time.Length; c++) - { - sb.Append("\n component "); - sb.Append(c); - sb.Append(": "); - sb.Append(time[c]); - sb.Append(" ms"); - } - FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.INFO, sb.ToString()); - } - else - { - // Multithreaded implementation - Compressor compr; - MsgLogger msglog = FacilityManager.getMsgLogger(); - - sb = new System.Text.StringBuilder("StdEntropyCoder manager thread " + "wall clock time:"); - for (c = 0; c < time.Length; c++) - { - sb.Append("\n component "); - sb.Append(c); - sb.Append(": "); - sb.Append(time[c]); - sb.Append(" ms"); - } - System.Collections.IEnumerator Enum = idleComps.GetEnumerator(); - sb.Append("\nStdEntropyCoder compressor threads wall clock " + "time:"); - //UPGRADE_TODO: Method 'java.util.Enumeration.hasMoreElements' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationhasMoreElements'" - while (Enum.MoveNext()) - { - //UPGRADE_TODO: Method 'java.util.Enumeration.nextElement' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationnextElement'" - compr = (Compressor)(Enum.Current); - for (c = 0; c < time.Length; c++) - { - sb.Append("\n compressor "); - sb.Append(compr.Idx); - sb.Append(", component "); - sb.Append(c); - sb.Append(": "); - sb.Append(compr.getTiming(c)); - sb.Append(" ms"); - } - } - FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.INFO, sb.ToString()); - } - - //UPGRADE_NOTE: Call to 'super.finalize()' was removed. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1124'" - } -#endif - - /// Returns the code-block width for the specified tile and component. - /// - /// - /// The tile index - /// - /// - /// the component index - /// - /// - /// The code-block width for the specified tile and component - /// - /// - public override int getCBlkWidth(int t, int c) - { - return cblks.getCBlkWidth(ModuleSpec.SPEC_TILE_COMP, t, c); - } - - /// Returns the code-block height for the specified tile and component. - /// - /// - /// The tile index - /// - /// - /// The component index - /// - /// - /// The code-block height for the specified tile and component. - /// - /// - public override int getCBlkHeight(int t, int c) - { - return cblks.getCBlkHeight(ModuleSpec.SPEC_TILE_COMP, t, c); - } - - /// Returns the next coded code-block in the current tile for the specified - /// component, as a copy (see below). The order in which code-blocks are - /// returned is not specified. However each code-block is returned only - /// once and all code-blocks will be returned if the method is called 'N' - /// times, where 'N' is the number of code-blocks in the tile. After all - /// the code-blocks have been returned for the current tile calls to this - /// method will return 'null'. - /// - ///

    When changing the current tile (through 'setTile()' or 'nextTile()') - /// this method will always return the first code-block, as if this method - /// was never called before for the new current tile.

    - /// - ///

    The data returned by this method is always a copy of the internal - /// data of this object, if any, and it can be modified "in place" without - /// any problems after being returned.

    - /// - ///
    - /// The component for which to return the next code-block. - /// - /// - /// If non-null this object might be used in returning the coded - /// code-block in this or any subsequent call to this method. If null a new - /// one is created and returned. If the 'data' array of 'cbb' is not null - /// it may be reused to return the compressed data. - /// - /// - /// The next coded code-block in the current tile for component - /// 'n', or null if all code-blocks for the current tile have been - /// returned. - /// - /// - /// - /// - /// - public override CBlkRateDistStats getNextCodeBlock(int c, CBlkRateDistStats ccb) - { -#if DO_TIMING - long stime = 0L; // Start time for timed sections -#endif - if (tPool == null) - { - // Use single threaded implementation - // Get code-block data from source - srcblkT[0] = src.getNextInternCodeBlock(c, srcblkT[0]); - -#if DO_TIMING - stime = (System.DateTime.Now.Ticks - 621355968000000000) / 10000; -#endif - - if (srcblkT[0] == null) - { - // We got all code-blocks - return null; - } - // Initialize thread local variables - if ((opts[tIdx][c] & CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_BYPASS) != 0 && boutT[0] == null) - { - boutT[0] = new BitToByteOutput(outT[0]); - } - // Initialize output code-block - if (ccb == null) - { - ccb = new CBlkRateDistStats(); - } - // Compress code-block - compressCodeBlock(c, ccb, srcblkT[0], mqT[0], boutT[0], outT[0], stateT[0], distbufT[0], ratebufT[0], istermbufT[0], symbufT[0], ctxtbufT[0], opts[tIdx][c], isReversible(tIdx, c), lenCalc[tIdx][c], tType[tIdx][c]); - -#if DO_TIMING - time[c] += (System.DateTime.Now.Ticks - 621355968000000000) / 10000 - stime; -#endif - - // Return result - return ccb; - } - else - { - // Use multiple threaded implementation - int cIdx; // Compressor idx - Compressor compr; // Compressor - -#if DO_TIMING - stime = (System.DateTime.Now.Ticks - 621355968000000000) / 10000; -#endif - // Give data to all free compressors, using the current component - while (!finishedTileComponent[c] && !(idleComps.Count == 0)) - { - // Get an idle compressor - compr = (Compressor)SupportClass.StackSupport.Pop(idleComps); - cIdx = compr.Idx; - // Get data for the compressor and wake it up -#if DO_TIMING - time[c] += (System.DateTime.Now.Ticks - 621355968000000000) / 10000 - stime; -#endif - srcblkT[cIdx] = src.getNextInternCodeBlock(c, srcblkT[cIdx]); -#if DO_TIMING - stime = (System.DateTime.Now.Ticks - 621355968000000000) / 10000; -#endif - if (srcblkT[cIdx] != null) - { - // Initialize thread local variables - if ((opts[tIdx][c] & CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_BYPASS) != 0 && boutT[cIdx] == null) - { - boutT[cIdx] = new BitToByteOutput(outT[cIdx]); - } - // Initialize output code-block and compressor thread - if (ccb == null) - ccb = new CBlkRateDistStats(); - compr.ccb = ccb; - compr.c = c; - compr.options = opts[tIdx][c]; - compr.rev = isReversible(tIdx, c); - compr.lcType = lenCalc[tIdx][c]; - compr.tType = tType[tIdx][c]; - nBusyComps[c]++; - ccb = null; - // Send compressor to execution in thread pool - tPool.runTarget(compr, completedComps[c]); - } - else - { - // We finished with all the code-blocks in the current - // tile component - idleComps.Add(compr); - finishedTileComponent[c] = true; - } - } - // If there are threads for this component which result has not - // been returned yet, get it - if (nBusyComps[c] > 0) - { - lock (completedComps[c]) - { - // If no compressor is done, wait until one is - if ((completedComps[c].Count == 0)) - { - try - { -#if DO_TIMING - time[c] += (System.DateTime.Now.Ticks - 621355968000000000) / 10000 - stime; -#endif - System.Threading.Monitor.Wait(completedComps[c]); -#if DO_TIMING - stime = (System.DateTime.Now.Ticks - 621355968000000000) / 10000; -#endif - } - catch (System.Threading.ThreadInterruptedException) - { - } - } - // Remove the thread from the completed queue and put it - // on the idle queue - compr = (Compressor)SupportClass.StackSupport.Pop(completedComps[c]); - cIdx = compr.Idx; - nBusyComps[c]--; - idleComps.Add(compr); - // Check targets error condition - tPool.checkTargetErrors(); - // Get the result of compression and return that. -#if DO_TIMING - time[c] += (System.DateTime.Now.Ticks - 621355968000000000) / 10000 - stime; -#endif - return compr.ccb; - } - } - else - { - // Check targets error condition - tPool.checkTargetErrors(); - // Printing timing info if necessary -#if DO_TIMING - time[c] += (System.DateTime.Now.Ticks - 621355968000000000) / 10000 - stime; -#endif - // Nothing is running => no more code-blocks - return null; - } - } - } - - /// Changes the current tile, given the new indexes. An - /// IllegalArgumentException is thrown if the indexes do not correspond to - /// a valid tile. - /// - ///

    This default implementation just changes the tile in the source.

    - /// - ///
    - /// The horizontal index of the tile. - /// - /// - /// The vertical index of the new tile. - /// - /// - public override void setTile(int x, int y) - { - base.setTile(x, y); - // Reset the tile specific variables - if (finishedTileComponent != null) - { - for (int c = src.NumComps - 1; c >= 0; c--) - { - finishedTileComponent[c] = false; - } - } - } - - /// Advances to the next tile, in standard scan-line order (by rows then - /// columns). An NoNextElementException is thrown if the current tile is - /// the last one (i.e. there is no next tile). - /// - ///

    This default implementation just advances to the next tile in the - /// source.

    - /// - ///
    - public override void nextTile() - { - // Reset the tilespecific variables - if (finishedTileComponent != null) - { - for (int c = src.NumComps - 1; c >= 0; c--) - { - finishedTileComponent[c] = false; - } - } - base.nextTile(); - } - - - /// Compresses the code-block in 'srcblk' and puts the results in 'ccb', - /// using the specified options and temporary storage. - /// - /// - /// The component for which to return the next code-block. - /// - /// - /// The object where the compressed data will be stored. If the - /// 'data' array of 'cbb' is not null it may be reused to return the - /// compressed data. - /// - /// - /// The code-block data to code - /// - /// - /// The MQ-coder to use - /// - /// - /// The bit level output to use. Used only if 'OPT_BYPASS' is - /// turned on in the 'options' argument. - /// - /// - /// The byte buffer trough which the compressed data is stored. - /// - /// - /// The state information for the code-block - /// - /// - /// The buffer where to store the distortion at - /// the end of each coding pass. - /// - /// - /// The buffer where to store the rate (i.e. coded lenth) at - /// the end of each coding pass. - /// - /// - /// The buffer where to store the terminated flag for each - /// coding pass. - /// - /// - /// The buffer to hold symbols to send to the MQ coder - /// - /// - /// A buffer to hold the contexts to use in sending the - /// buffered symbols to the MQ coder. - /// - /// - /// The options to use when coding this code-block - /// - /// - /// The reversible flag. Should be true if the source of this - /// code-block's data is reversible. - /// - /// - /// The type of length calculation to use with the MQ coder. - /// - /// - /// The type of termination to use with the MQ coder. - /// - /// - /// - /// - /// - static private void compressCodeBlock(int c, CBlkRateDistStats ccb, CBlkWTData srcblk, MQCoder mq, BitToByteOutput bout, ByteOutputBuffer out_Renamed, int[] state, double[] distbuf, int[] ratebuf, bool[] istermbuf, int[] symbuf, int[] ctxtbuf, int options, bool rev, int lcType, int tType) - { - // NOTE: This method should not access any non-final instance or - // static variables, either directly or indirectly through other - // methods in order to be sure that the method is thread safe. - - int[] zc_lut; // The ZC lookup table to use - int skipbp; // The number of non-significant bit-planes to skip - int curbp; // The current magnitude bit-plane (starts at 30) - int[] fm; // The distortion estimation lookup table for MR - int[] fs; // The distortion estimation lookup table for SC - int lmb; // The least significant magnitude bit - int npass; // The number of coding passes, for R-D statistics - double msew; // The distortion (MSE weight) for the current bit-plane - double totdist; // The total cumulative distortion decrease - int ltpidx; // The index of the last pass which is terminated - - // Check error-resilient termination - if ((options & CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_PRED_TERM) != 0 && tType != MQCoder.TERM_PRED_ER) - { - throw new System.ArgumentException("Embedded error-resilient info " + "in MQ termination option " + "specified but incorrect MQ " + "termination " + "policy specified"); - } - // Set MQ flags - mq.LenCalcType = lcType; - mq.TermType = tType; - - lmb = 30 - srcblk.magbits + 1; - // If there are more bit-planes to code than the implementation - // bit-depth set lmb to 0 - lmb = (lmb < 0) ? 0 : lmb; - - // Reset state - ArrayUtil.intArraySet(state, 0); - - // Find the most significant bit-plane - skipbp = calcSkipMSBP(srcblk, lmb); - - // Initialize output code-block - ccb.m = srcblk.m; - ccb.n = srcblk.n; - ccb.sb = srcblk.sb; - ccb.nROIcoeff = srcblk.nROIcoeff; - ccb.skipMSBP = skipbp; - if (ccb.nROIcoeff != 0) - { - ccb.nROIcp = 3 * (srcblk.nROIbp - skipbp - 1) + 1; - } - else - { - ccb.nROIcp = 0; - } - - // Choose correct ZC lookup table for global orientation - switch (srcblk.sb.orientation) - { - - case Subband.WT_ORIENT_HL: - zc_lut = ZC_LUT_HL; - break; - - case Subband.WT_ORIENT_LL: - case Subband.WT_ORIENT_LH: - zc_lut = ZC_LUT_LH; - break; - - case Subband.WT_ORIENT_HH: - zc_lut = ZC_LUT_HH; - break; - - default: - throw new System.ApplicationException("JJ2000 internal error"); - - } - - // Loop on significant magnitude bit-planes doing the 3 passes - curbp = 30 - skipbp; - fs = FS_LOSSY; - fm = FM_LOSSY; - msew = System.Math.Pow(2, ((curbp - lmb) << 1) - MSE_LKP_FRAC_BITS) * srcblk.sb.stepWMSE * srcblk.wmseScaling; - totdist = 0f; - npass = 0; - ltpidx = -1; - - // First significant bit-plane has only the pass pass - if (curbp >= lmb) - { - // Do we need the "lossless" 'fs' table ? - if (rev && curbp == lmb) - { - fs = FM_LOSSLESS; - } - // We terminate if regular termination, last bit-plane, or next - // bit-plane is "raw". - istermbuf[npass] = (options & CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_TERM_PASS) != 0 || curbp == lmb || ((options & CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_BYPASS) != 0 && (31 - CSJ2K.j2k.entropy.StdEntropyCoderOptions.NUM_NON_BYPASS_MS_BP - skipbp) >= curbp); - totdist += cleanuppass(srcblk, mq, istermbuf[npass], curbp, state, fs, zc_lut, symbuf, ctxtbuf, ratebuf, npass, ltpidx, options) * msew; - distbuf[npass] = totdist; - if (istermbuf[npass]) - ltpidx = npass; - npass++; - msew *= 0.25; - curbp--; - } - // Other bit-planes have all passes - while (curbp >= lmb) - { - // Do we need the "lossless" 'fs' and 'fm' tables ? - if (rev && curbp == lmb) - { - fs = FS_LOSSLESS; - fm = FM_LOSSLESS; - } - - // Do the significance propagation pass - // We terminate if regular termination only - istermbuf[npass] = (options & CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_TERM_PASS) != 0; - if ((options & CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_BYPASS) == 0 || (31 - CSJ2K.j2k.entropy.StdEntropyCoderOptions.NUM_NON_BYPASS_MS_BP - skipbp <= curbp)) - { - // No bypass coding - totdist += sigProgPass(srcblk, mq, istermbuf[npass], curbp, state, fs, zc_lut, symbuf, ctxtbuf, ratebuf, npass, ltpidx, options) * msew; - } - else - { - // Bypass ("raw") coding - bout.PredTerm = (options & CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_PRED_TERM) != 0; - totdist += rawSigProgPass(srcblk, bout, istermbuf[npass], curbp, state, fs, ratebuf, npass, ltpidx, options) * msew; - } - distbuf[npass] = totdist; - if (istermbuf[npass]) - ltpidx = npass; - npass++; - - // Do the magnitude refinement pass - // We terminate if regular termination or bypass ("raw") coding - istermbuf[npass] = (options & CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_TERM_PASS) != 0 || ((options & CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_BYPASS) != 0 && (31 - CSJ2K.j2k.entropy.StdEntropyCoderOptions.NUM_NON_BYPASS_MS_BP - skipbp > curbp)); - if ((options & CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_BYPASS) == 0 || (31 - CSJ2K.j2k.entropy.StdEntropyCoderOptions.NUM_NON_BYPASS_MS_BP - skipbp <= curbp)) - { - // No bypass coding - totdist += magRefPass(srcblk, mq, istermbuf[npass], curbp, state, fm, symbuf, ctxtbuf, ratebuf, npass, ltpidx, options) * msew; - } - else - { - // Bypass ("raw") coding - bout.PredTerm = (options & CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_PRED_TERM) != 0; - totdist += rawMagRefPass(srcblk, bout, istermbuf[npass], curbp, state, fm, ratebuf, npass, ltpidx, options) * msew; - } - distbuf[npass] = totdist; - if (istermbuf[npass]) - ltpidx = npass; - npass++; - - // Do the clenup pass - // We terminate if regular termination, last bit-plane, or next - // bit-plane is "raw". - istermbuf[npass] = (options & CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_TERM_PASS) != 0 || curbp == lmb || ((options & CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_BYPASS) != 0 && (31 - CSJ2K.j2k.entropy.StdEntropyCoderOptions.NUM_NON_BYPASS_MS_BP - skipbp) >= curbp); - totdist += cleanuppass(srcblk, mq, istermbuf[npass], curbp, state, fs, zc_lut, symbuf, ctxtbuf, ratebuf, npass, ltpidx, options) * msew; - distbuf[npass] = totdist; - - if (istermbuf[npass]) - ltpidx = npass; - npass++; - - // Goto next bit-plane - msew *= 0.25; - curbp--; - } - - // Copy compressed data and rate-distortion statistics to output - ccb.data = new byte[out_Renamed.size()]; - out_Renamed.toByteArray(0, out_Renamed.size(), ccb.data, 0); - checkEndOfPassFF(ccb.data, ratebuf, istermbuf, npass); - ccb.selectConvexHull(ratebuf, distbuf, (options & (CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_BYPASS | CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_TERM_PASS)) != 0 ? istermbuf : null, npass, rev); - - // Reset MQ coder and bit output for next code-block - mq.reset(); - if (bout != null) - bout.reset(); - } - - /// Calculates the number of magnitude bit-planes that are to be skipped, - /// because they are non-significant. The algorithm looks for the largest - /// magnitude and calculates the most significant bit-plane of it. - /// - /// - /// The code-block of data to scan - /// - /// - /// The least significant magnitude bit in the data - /// - /// - /// The number of magnitude bit-planes to skip (i.e. all zero most - /// significant bit-planes). - /// - /// - static private int calcSkipMSBP(CBlkWTData cblk, int lmb) - { - int k, kmax, mask; - int[] data; - int maxmag; - int mag; - int w, h; - int msbp; - int l; - - data = (int[])cblk.Data; - w = cblk.w; - h = cblk.h; - - // First look for the maximum magnitude in the code-block - maxmag = 0; - // Consider only magnitude bits that are in non-fractional bit-planes. - mask = 0x7FFFFFFF & (~((1 << lmb) - 1)); - for (l = h - 1, k = cblk.offset; l >= 0; l--) - { - for (kmax = k + w; k < kmax; k++) - { - mag = data[k] & mask; - if (mag > maxmag) - maxmag = mag; - } - k += cblk.scanw - w; - } - // Now calculate the number of all zero most significant - // bit-planes for the maximum magnitude. - msbp = 30; - do - { - if (((1 << msbp) & maxmag) != 0) - break; - msbp--; - } - while (msbp >= lmb); - - // Return the number of non-significant bit-planes to skip - return 30 - msbp; - } - - /// Performs the significance propagation pass on the specified data and - /// bit-plane. It codes all insignificant samples which have, at least, one - /// of its immediate eight neighbors already significant, using the ZC and - /// SC primitives as needed. It toggles the "visited" state bit to 1 for - /// all those samples. - /// - /// - /// The code-block data to code - /// - /// - /// The MQ-coder to use - /// - /// - /// If true it performs an MQ-coder termination after the end - /// of the pass - /// - /// - /// The bit-plane to code - /// - /// - /// The state information for the code-block - /// - /// - /// The distortion estimation lookup table for SC - /// - /// - /// The ZC lookup table to use in ZC. - /// - /// - /// The buffer to hold symbols to send to the MQ coder - /// - /// - /// A buffer to hold the contexts to use in sending the - /// buffered symbols to the MQ coder. - /// - /// - /// The buffer where to store the rate (i.e. coded lenth) at - /// the end of this coding pass. - /// - /// - /// The coding pass index. Is the index in the 'ratebuf' array - /// where to store the coded length after this coding pass. - /// - /// - /// The index of the last pass that was terminated, or - /// negative if none. - /// - /// - /// The bitmask of entropy coding options to apply to the - /// code-block - /// - /// - /// The decrease in distortion for this pass, in the fixed-point - /// normalized representation of the 'FS_LOSSY' and 'FS_LOSSLESS' tables. - /// - /// - static private int sigProgPass(CBlkWTData srcblk, MQCoder mq, bool doterm, int bp, int[] state, int[] fs, int[] zc_lut, int[] symbuf, int[] ctxtbuf, int[] ratebuf, int pidx, int ltpidx, int options) - { - int j, sj; // The state index for line and stripe - int k, sk; // The data index for line and stripe - int nsym = 0; // Symbol counter for symbol and context buffers - int dscanw; // The data scan-width - int sscanw; // The state and packed state scan-width - int jstep; // Stripe to stripe step for 'sj' - int kstep; // Stripe to stripe step for 'sk' - int stopsk; // The loop limit on the variable sk - int csj; // Local copy (i.e. cached) of 'state[j]' - int mask; // The mask for the current bit-plane - int sym; // The symbol to code - int ctxt; // The context to use - int[] data; // The data buffer - int dist; // The distortion reduction for this pass - int shift; // Shift amount for distortion - int upshift; // Shift left amount for distortion - int downshift; // Shift right amount for distortion - int normval; // The normalized sample magnitude value - int s; // The stripe index - bool causal; // Flag to indicate if stripe-causal context - // formation is to be used - int nstripes; // The number of stripes in the code-block - int sheight; // Height of the current stripe - int off_ul, off_ur, off_dr, off_dl; // offsets - - // Initialize local variables - dscanw = srcblk.scanw; - sscanw = srcblk.w + 2; - jstep = sscanw * CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT / 2 - srcblk.w; - kstep = dscanw * CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT - srcblk.w; - mask = 1 << bp; - data = (int[])srcblk.Data; - nstripes = (srcblk.h + CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT - 1) / CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT; - dist = 0; - // We use the MSE_LKP_BITS-1 bits below the bit just coded for - // distortion estimation. - shift = bp - MSE_LKP_BITS_M1; - upshift = (shift >= 0) ? 0 : -shift; - downshift = (shift <= 0) ? 0 : shift; - causal = (options & CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_VERT_STR_CAUSAL) != 0; - - // Pre-calculate offsets in 'state' for diagonal neighbors - off_ul = -sscanw - 1; // up-left - off_ur = -sscanw + 1; // up-right - off_dr = sscanw + 1; // down-right - off_dl = sscanw - 1; // down-left - - // Code stripe by stripe - sk = srcblk.offset; - sj = sscanw + 1; - for (s = nstripes - 1; s >= 0; s--, sk += kstep, sj += jstep) - { - sheight = (s != 0) ? CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT : srcblk.h - (nstripes - 1) * CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT; - stopsk = sk + srcblk.w; - // Scan by set of 1 stripe column at a time - for (nsym = 0; sk < stopsk; sk++, sj++) - { - // Do half top of column - j = sj; - csj = state[j]; - // If any of the two samples is not significant and has a - // non-zero context (i.e. some neighbor is significant) we can - // not skip them - if ((((~csj) & (csj << 2)) & SIG_MASK_R1R2) != 0) - { - k = sk; - // Scan first row - if ((csj & (STATE_SIG_R1 | STATE_NZ_CTXT_R1)) == STATE_NZ_CTXT_R1) - { - // Apply zero coding - ctxtbuf[nsym] = zc_lut[csj & ZC_MASK]; - if ((symbuf[nsym++] = SupportClass.URShift((data[k] & mask), bp)) != 0) - { - // Became significant - // Apply sign coding - sym = SupportClass.URShift(data[k], 31); - ctxt = SC_LUT[(SupportClass.URShift(csj, SC_SHIFT_R1)) & SC_MASK]; - symbuf[nsym] = sym ^ (SupportClass.URShift(ctxt, SC_SPRED_SHIFT)); - ctxtbuf[nsym++] = ctxt & SC_LUT_MASK; - // Update state information (significant bit, - // visited bit, neighbor significant bit of - // neighbors, non zero context of neighbors, sign - // of neighbors) - if (!causal) - { - // If in causal mode do not change contexts of - // previous stripe. - state[j + off_ul] |= STATE_NZ_CTXT_R2 | STATE_D_DR_R2; - state[j + off_ur] |= STATE_NZ_CTXT_R2 | STATE_D_DL_R2; - } - // Update sign state information of neighbors - if (sym != 0) - { - csj |= STATE_SIG_R1 | STATE_VISITED_R1 | STATE_NZ_CTXT_R2 | STATE_V_U_R2 | STATE_V_U_SIGN_R2; - if (!causal) - { - // If in causal mode do not change - // contexts of previous stripe. - state[j - sscanw] |= STATE_NZ_CTXT_R2 | STATE_V_D_R2 | STATE_V_D_SIGN_R2; - } - state[j + 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_H_L_R1 | STATE_H_L_SIGN_R1 | STATE_D_UL_R2; - state[j - 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_H_R_R1 | STATE_H_R_SIGN_R1 | STATE_D_UR_R2; - } - else - { - csj |= STATE_SIG_R1 | STATE_VISITED_R1 | STATE_NZ_CTXT_R2 | STATE_V_U_R2; - if (!causal) - { - // If in causal mode do not change - // contexts of previous stripe. - state[j - sscanw] |= STATE_NZ_CTXT_R2 | STATE_V_D_R2; - } - state[j + 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_H_L_R1 | STATE_D_UL_R2; - state[j - 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_H_R_R1 | STATE_D_UR_R2; - } - // Update distortion - normval = (data[k] >> downshift) << upshift; - dist += fs[normval & ((1 << MSE_LKP_BITS_M1) - 1)]; - } - else - { - csj |= STATE_VISITED_R1; - } - } - if (sheight < 2) - { - state[j] = csj; - continue; - } - // Scan second row - if ((csj & (STATE_SIG_R2 | STATE_NZ_CTXT_R2)) == STATE_NZ_CTXT_R2) - { - k += dscanw; - // Apply zero coding - ctxtbuf[nsym] = zc_lut[(SupportClass.URShift(csj, STATE_SEP)) & ZC_MASK]; - if ((symbuf[nsym++] = SupportClass.URShift((data[k] & mask), bp)) != 0) - { - // Became significant - // Apply sign coding - sym = SupportClass.URShift(data[k], 31); - ctxt = SC_LUT[(SupportClass.URShift(csj, SC_SHIFT_R2)) & SC_MASK]; - symbuf[nsym] = sym ^ (SupportClass.URShift(ctxt, SC_SPRED_SHIFT)); - ctxtbuf[nsym++] = ctxt & SC_LUT_MASK; - // Update state information (significant bit, - // visited bit, neighbor significant bit of - // neighbors, non zero context of neighbors, sign - // of neighbors) - state[j + off_dl] |= STATE_NZ_CTXT_R1 | STATE_D_UR_R1; - state[j + off_dr] |= STATE_NZ_CTXT_R1 | STATE_D_UL_R1; - // Update sign state information of neighbors - if (sym != 0) - { - csj |= STATE_SIG_R2 | STATE_VISITED_R2 | STATE_NZ_CTXT_R1 | STATE_V_D_R1 | STATE_V_D_SIGN_R1; - state[j + sscanw] |= STATE_NZ_CTXT_R1 | STATE_V_U_R1 | STATE_V_U_SIGN_R1; - state[j + 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_D_DL_R1 | STATE_H_L_R2 | STATE_H_L_SIGN_R2; - state[j - 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_D_DR_R1 | STATE_H_R_R2 | STATE_H_R_SIGN_R2; - } - else - { - csj |= STATE_SIG_R2 | STATE_VISITED_R2 | STATE_NZ_CTXT_R1 | STATE_V_D_R1; - state[j + sscanw] |= STATE_NZ_CTXT_R1 | STATE_V_U_R1; - state[j + 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_D_DL_R1 | STATE_H_L_R2; - state[j - 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_D_DR_R1 | STATE_H_R_R2; - } - // Update distortion - normval = (data[k] >> downshift) << upshift; - dist += fs[normval & ((1 << MSE_LKP_BITS_M1) - 1)]; - } - else - { - csj |= STATE_VISITED_R2; - } - } - state[j] = csj; - } - // Do half bottom of column - if (sheight < 3) - continue; - j += sscanw; - csj = state[j]; - // If any of the two samples is not significant and has a - // non-zero context (i.e. some neighbor is significant) we can - // not skip them - if ((((~csj) & (csj << 2)) & SIG_MASK_R1R2) != 0) - { - k = sk + (dscanw << 1); - // Scan first row - if ((csj & (STATE_SIG_R1 | STATE_NZ_CTXT_R1)) == STATE_NZ_CTXT_R1) - { - // Apply zero coding - ctxtbuf[nsym] = zc_lut[csj & ZC_MASK]; - if ((symbuf[nsym++] = SupportClass.URShift((data[k] & mask), bp)) != 0) - { - // Became significant - // Apply sign coding - sym = SupportClass.URShift(data[k], 31); - ctxt = SC_LUT[(SupportClass.URShift(csj, SC_SHIFT_R1)) & SC_MASK]; - symbuf[nsym] = sym ^ (SupportClass.URShift(ctxt, SC_SPRED_SHIFT)); - ctxtbuf[nsym++] = ctxt & SC_LUT_MASK; - // Update state information (significant bit, - // visited bit, neighbor significant bit of - // neighbors, non zero context of neighbors, sign - // of neighbors) - state[j + off_ul] |= STATE_NZ_CTXT_R2 | STATE_D_DR_R2; - state[j + off_ur] |= STATE_NZ_CTXT_R2 | STATE_D_DL_R2; - // Update sign state information of neighbors - if (sym != 0) - { - csj |= STATE_SIG_R1 | STATE_VISITED_R1 | STATE_NZ_CTXT_R2 | STATE_V_U_R2 | STATE_V_U_SIGN_R2; - state[j - sscanw] |= STATE_NZ_CTXT_R2 | STATE_V_D_R2 | STATE_V_D_SIGN_R2; - state[j + 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_H_L_R1 | STATE_H_L_SIGN_R1 | STATE_D_UL_R2; - state[j - 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_H_R_R1 | STATE_H_R_SIGN_R1 | STATE_D_UR_R2; - } - else - { - csj |= STATE_SIG_R1 | STATE_VISITED_R1 | STATE_NZ_CTXT_R2 | STATE_V_U_R2; - state[j - sscanw] |= STATE_NZ_CTXT_R2 | STATE_V_D_R2; - state[j + 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_H_L_R1 | STATE_D_UL_R2; - state[j - 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_H_R_R1 | STATE_D_UR_R2; - } - // Update distortion - normval = (data[k] >> downshift) << upshift; - dist += fs[normval & ((1 << MSE_LKP_BITS_M1) - 1)]; - } - else - { - csj |= STATE_VISITED_R1; - } - } - if (sheight < 4) - { - state[j] = csj; - continue; - } - // Scan second row - if ((csj & (STATE_SIG_R2 | STATE_NZ_CTXT_R2)) == STATE_NZ_CTXT_R2) - { - k += dscanw; - // Apply zero coding - ctxtbuf[nsym] = zc_lut[(SupportClass.URShift(csj, STATE_SEP)) & ZC_MASK]; - if ((symbuf[nsym++] = SupportClass.URShift((data[k] & mask), bp)) != 0) - { - // Became significant - // Apply sign coding - sym = SupportClass.URShift(data[k], 31); - ctxt = SC_LUT[(SupportClass.URShift(csj, SC_SHIFT_R2)) & SC_MASK]; - symbuf[nsym] = sym ^ (SupportClass.URShift(ctxt, SC_SPRED_SHIFT)); - ctxtbuf[nsym++] = ctxt & SC_LUT_MASK; - // Update state information (significant bit, - // visited bit, neighbor significant bit of - // neighbors, non zero context of neighbors, sign - // of neighbors) - state[j + off_dl] |= STATE_NZ_CTXT_R1 | STATE_D_UR_R1; - state[j + off_dr] |= STATE_NZ_CTXT_R1 | STATE_D_UL_R1; - // Update sign state information of neighbors - if (sym != 0) - { - csj |= STATE_SIG_R2 | STATE_VISITED_R2 | STATE_NZ_CTXT_R1 | STATE_V_D_R1 | STATE_V_D_SIGN_R1; - state[j + sscanw] |= STATE_NZ_CTXT_R1 | STATE_V_U_R1 | STATE_V_U_SIGN_R1; - state[j + 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_D_DL_R1 | STATE_H_L_R2 | STATE_H_L_SIGN_R2; - state[j - 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_D_DR_R1 | STATE_H_R_R2 | STATE_H_R_SIGN_R2; - } - else - { - csj |= STATE_SIG_R2 | STATE_VISITED_R2 | STATE_NZ_CTXT_R1 | STATE_V_D_R1; - state[j + sscanw] |= STATE_NZ_CTXT_R1 | STATE_V_U_R1; - state[j + 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_D_DL_R1 | STATE_H_L_R2; - state[j - 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_D_DR_R1 | STATE_H_R_R2; - } - // Update distortion - normval = (data[k] >> downshift) << upshift; - dist += fs[normval & ((1 << MSE_LKP_BITS_M1) - 1)]; - } - else - { - csj |= STATE_VISITED_R2; - } - } - state[j] = csj; - } - } - // Code all buffered symbols - mq.codeSymbols(symbuf, ctxtbuf, nsym); - } - // Reset the MQ context states if we need to - if ((options & CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_RESET_MQ) != 0) - { - mq.resetCtxts(); - } - - // Terminate the MQ bit stream if we need to - if (doterm) - { - ratebuf[pidx] = mq.terminate(); // Termination has special length - } - else - { - // Use normal length calculation - ratebuf[pidx] = mq.NumCodedBytes; - } - // Add length of previous segments, if any - if (ltpidx >= 0) - { - ratebuf[pidx] += ratebuf[ltpidx]; - } - // Finish length calculation if needed - if (doterm) - { - mq.finishLengthCalculation(ratebuf, pidx); - } - - // Return the reduction in distortion - return dist; - } - - /// Performs the significance propagation pass on the specified data and - /// bit-plane, without using the arithmetic coder. It codes all - /// insignificant samples which have, at least, one of its immediate eight - /// neighbors already significant, using the ZC and SC primitives as - /// needed. It toggles the "visited" state bit to 1 for all those samples. - /// - ///

    In this method, the arithmetic coder is bypassed, and raw bits are - /// directly written in the bit stream (useful when distribution are close - /// to uniform, for intance, at high bit-rates and at lossless - /// compression).

    - /// - ///
    - /// The code-block data to code - /// - /// - /// The bit based output - /// - /// - /// If true the bit based output is byte aligned after the - /// end of the pass. - /// - /// - /// The bit-plane to code - /// - /// - /// The state information for the code-block - /// - /// - /// The distortion estimation lookup table for SC - /// - /// - /// The buffer where to store the rate (i.e. coded lenth) at - /// the end of this coding pass. - /// - /// - /// The coding pass index. Is the index in the 'ratebuf' array - /// where to store the coded length after this coding pass. - /// - /// - /// The index of the last pass that was terminated, or - /// negative if none. - /// - /// - /// The bitmask of entropy coding options to apply to the - /// code-block - /// - /// - /// The decrease in distortion for this pass, in the fixed-point - /// normalized representation of the 'FS_LOSSY' and 'FS_LOSSLESS' tables. - /// - /// - static private int rawSigProgPass(CBlkWTData srcblk, BitToByteOutput bout, bool doterm, int bp, int[] state, int[] fs, int[] ratebuf, int pidx, int ltpidx, int options) - { - int j, sj; // The state index for line and stripe - int k, sk; // The data index for line and stripe - int dscanw; // The data scan-width - int sscanw; // The state scan-width - int jstep; // Stripe to stripe step for 'sj' - int kstep; // Stripe to stripe step for 'sk' - int stopsk; // The loop limit on the variable sk - int csj; // Local copy (i.e. cached) of 'state[j]' - int mask; // The mask for the current bit-plane - int nsym = 0; // Number of symbol - int sym; // The symbol to code - int[] data; // The data buffer - int dist; // The distortion reduction for this pass - int shift; // Shift amount for distortion - int upshift; // Shift left amount for distortion - int downshift; // Shift right amount for distortion - int normval; // The normalized sample magnitude value - int s; // The stripe index - bool causal; // Flag to indicate if stripe-causal context - // formation is to be used - int nstripes; // The number of stripes in the code-block - int sheight; // Height of the current stripe - int off_ul, off_ur, off_dr, off_dl; // offsets - - // Initialize local variables - dscanw = srcblk.scanw; - sscanw = srcblk.w + 2; - jstep = sscanw * CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT / 2 - srcblk.w; - kstep = dscanw * CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT - srcblk.w; - mask = 1 << bp; - data = (int[])srcblk.Data; - nstripes = (srcblk.h + CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT - 1) / CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT; - dist = 0; - // We use the MSE_LKP_BITS-1 bits below the bit just coded for - // distortion estimation. - shift = bp - MSE_LKP_BITS_M1; - upshift = (shift >= 0) ? 0 : -shift; - downshift = (shift <= 0) ? 0 : shift; - causal = (options & CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_VERT_STR_CAUSAL) != 0; - - // Pre-calculate offsets in 'state' for neighbors - off_ul = -sscanw - 1; // up-left - off_ur = -sscanw + 1; // up-right - off_dr = sscanw + 1; // down-right - off_dl = sscanw - 1; // down-left - - // Code stripe by stripe - sk = srcblk.offset; - sj = sscanw + 1; - for (s = nstripes - 1; s >= 0; s--, sk += kstep, sj += jstep) - { - sheight = (s != 0) ? CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT : srcblk.h - (nstripes - 1) * CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT; - stopsk = sk + srcblk.w; - // Scan by set of 1 stripe column at a time - for (; sk < stopsk; sk++, sj++) - { - // Do half top of column - j = sj; - csj = state[j]; - // If any of the two samples is not significant and has a - // non-zero context (i.e. some neighbor is significant) we can - // not skip them - if ((((~csj) & (csj << 2)) & SIG_MASK_R1R2) != 0) - { - k = sk; - // Scan first row - if ((csj & (STATE_SIG_R1 | STATE_NZ_CTXT_R1)) == STATE_NZ_CTXT_R1) - { - // Apply zero coding - sym = SupportClass.URShift((data[k] & mask), bp); - bout.writeBit(sym); - nsym++; - if (sym != 0) - { - // Became significant - // Apply sign coding - sym = SupportClass.URShift(data[k], 31); - bout.writeBit(sym); - nsym++; - // Update state information (significant bit, - // visited bit, neighbor significant bit of - // neighbors, non zero context of neighbors, sign - // of neighbors) - if (!causal) - { - // If in causal mode do not change contexts of - // previous stripe. - state[j + off_ul] |= STATE_NZ_CTXT_R2 | STATE_D_DR_R2; - state[j + off_ur] |= STATE_NZ_CTXT_R2 | STATE_D_DL_R2; - } - // Update sign state information of neighbors - if (sym != 0) - { - csj |= STATE_SIG_R1 | STATE_VISITED_R1 | STATE_NZ_CTXT_R2 | STATE_V_U_R2 | STATE_V_U_SIGN_R2; - if (!causal) - { - // If in causal mode do not change - // contexts of previous stripe. - state[j - sscanw] |= STATE_NZ_CTXT_R2 | STATE_V_D_R2 | STATE_V_D_SIGN_R2; - } - state[j + 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_H_L_R1 | STATE_H_L_SIGN_R1 | STATE_D_UL_R2; - state[j - 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_H_R_R1 | STATE_H_R_SIGN_R1 | STATE_D_UR_R2; - } - else - { - csj |= STATE_SIG_R1 | STATE_VISITED_R1 | STATE_NZ_CTXT_R2 | STATE_V_U_R2; - if (!causal) - { - // If in causal mode do not change - // contexts of previous stripe. - state[j - sscanw] |= STATE_NZ_CTXT_R2 | STATE_V_D_R2; - } - state[j + 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_H_L_R1 | STATE_D_UL_R2; - state[j - 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_H_R_R1 | STATE_D_UR_R2; - } - // Update distortion - normval = (data[k] >> downshift) << upshift; - dist += fs[normval & ((1 << MSE_LKP_BITS_M1) - 1)]; - } - else - { - csj |= STATE_VISITED_R1; - } - } - if (sheight < 2) - { - state[j] = csj; - continue; - } - // Scan second row - if ((csj & (STATE_SIG_R2 | STATE_NZ_CTXT_R2)) == STATE_NZ_CTXT_R2) - { - k += dscanw; - // Apply zero coding - sym = SupportClass.URShift((data[k] & mask), bp); - bout.writeBit(sym); - nsym++; - if (sym != 0) - { - // Became significant - // Apply sign coding - sym = SupportClass.URShift(data[k], 31); - bout.writeBit(sym); - nsym++; - // Update state information (significant bit, - // visited bit, neighbor significant bit of - // neighbors, non zero context of neighbors, sign - // of neighbors) - state[j + off_dl] |= STATE_NZ_CTXT_R1 | STATE_D_UR_R1; - state[j + off_dr] |= STATE_NZ_CTXT_R1 | STATE_D_UL_R1; - // Update sign state information of neighbors - if (sym != 0) - { - csj |= STATE_SIG_R2 | STATE_VISITED_R2 | STATE_NZ_CTXT_R1 | STATE_V_D_R1 | STATE_V_D_SIGN_R1; - state[j + sscanw] |= STATE_NZ_CTXT_R1 | STATE_V_U_R1 | STATE_V_U_SIGN_R1; - state[j + 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_D_DL_R1 | STATE_H_L_R2 | STATE_H_L_SIGN_R2; - state[j - 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_D_DR_R1 | STATE_H_R_R2 | STATE_H_R_SIGN_R2; - } - else - { - csj |= STATE_SIG_R2 | STATE_VISITED_R2 | STATE_NZ_CTXT_R1 | STATE_V_D_R1; - state[j + sscanw] |= STATE_NZ_CTXT_R1 | STATE_V_U_R1; - state[j + 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_D_DL_R1 | STATE_H_L_R2; - state[j - 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_D_DR_R1 | STATE_H_R_R2; - } - // Update distortion - normval = (data[k] >> downshift) << upshift; - dist += fs[normval & ((1 << MSE_LKP_BITS_M1) - 1)]; - } - else - { - csj |= STATE_VISITED_R2; - } - } - state[j] = csj; - } - // Do half bottom of column - if (sheight < 3) - continue; - j += sscanw; - csj = state[j]; - // If any of the two samples is not significant and has a - // non-zero context (i.e. some neighbor is significant) we can - // not skip them - if ((((~csj) & (csj << 2)) & SIG_MASK_R1R2) != 0) - { - k = sk + (dscanw << 1); - // Scan first row - if ((csj & (STATE_SIG_R1 | STATE_NZ_CTXT_R1)) == STATE_NZ_CTXT_R1) - { - sym = SupportClass.URShift((data[k] & mask), bp); - bout.writeBit(sym); - nsym++; - if (sym != 0) - { - // Became significant - // Apply sign coding - sym = SupportClass.URShift(data[k], 31); - bout.writeBit(sym); - nsym++; - // Update state information (significant bit, - // visited bit, neighbor significant bit of - // neighbors, non zero context of neighbors, sign - // of neighbors) - state[j + off_ul] |= STATE_NZ_CTXT_R2 | STATE_D_DR_R2; - state[j + off_ur] |= STATE_NZ_CTXT_R2 | STATE_D_DL_R2; - // Update sign state information of neighbors - if (sym != 0) - { - csj |= STATE_SIG_R1 | STATE_VISITED_R1 | STATE_NZ_CTXT_R2 | STATE_V_U_R2 | STATE_V_U_SIGN_R2; - state[j - sscanw] |= STATE_NZ_CTXT_R2 | STATE_V_D_R2 | STATE_V_D_SIGN_R2; - state[j + 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_H_L_R1 | STATE_H_L_SIGN_R1 | STATE_D_UL_R2; - state[j - 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_H_R_R1 | STATE_H_R_SIGN_R1 | STATE_D_UR_R2; - } - else - { - csj |= STATE_SIG_R1 | STATE_VISITED_R1 | STATE_NZ_CTXT_R2 | STATE_V_U_R2; - state[j - sscanw] |= STATE_NZ_CTXT_R2 | STATE_V_D_R2; - state[j + 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_H_L_R1 | STATE_D_UL_R2; - state[j - 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_H_R_R1 | STATE_D_UR_R2; - } - // Update distortion - normval = (data[k] >> downshift) << upshift; - dist += fs[normval & ((1 << MSE_LKP_BITS_M1) - 1)]; - } - else - { - csj |= STATE_VISITED_R1; - } - } - if (sheight < 4) - { - state[j] = csj; - continue; - } - if ((csj & (STATE_SIG_R2 | STATE_NZ_CTXT_R2)) == STATE_NZ_CTXT_R2) - { - k += dscanw; - // Apply zero coding - sym = SupportClass.URShift((data[k] & mask), bp); - bout.writeBit(sym); - nsym++; - if (sym != 0) - { - // Became significant - // Apply sign coding - sym = SupportClass.URShift(data[k], 31); - bout.writeBit(sym); - nsym++; - // Update state information (significant bit, - // visited bit, neighbor significant bit of - // neighbors, non zero context of neighbors, sign - // of neighbors) - state[j + off_dl] |= STATE_NZ_CTXT_R1 | STATE_D_UR_R1; - state[j + off_dr] |= STATE_NZ_CTXT_R1 | STATE_D_UL_R1; - // Update sign state information of neighbors - if (sym != 0) - { - csj |= STATE_SIG_R2 | STATE_VISITED_R2 | STATE_NZ_CTXT_R1 | STATE_V_D_R1 | STATE_V_D_SIGN_R1; - state[j + sscanw] |= STATE_NZ_CTXT_R1 | STATE_V_U_R1 | STATE_V_U_SIGN_R1; - state[j + 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_D_DL_R1 | STATE_H_L_R2 | STATE_H_L_SIGN_R2; - state[j - 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_D_DR_R1 | STATE_H_R_R2 | STATE_H_R_SIGN_R2; - } - else - { - csj |= STATE_SIG_R2 | STATE_VISITED_R2 | STATE_NZ_CTXT_R1 | STATE_V_D_R1; - state[j + sscanw] |= STATE_NZ_CTXT_R1 | STATE_V_U_R1; - state[j + 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_D_DL_R1 | STATE_H_L_R2; - state[j - 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_D_DR_R1 | STATE_H_R_R2; - } - // Update distortion - normval = (data[k] >> downshift) << upshift; - dist += fs[normval & ((1 << MSE_LKP_BITS_M1) - 1)]; - } - else - { - csj |= STATE_VISITED_R2; - } - } - state[j] = csj; - } - } - } - - // Get length and terminate if needed - if (doterm) - { - ratebuf[pidx] = bout.terminate(); - } - else - { - ratebuf[pidx] = bout.length(); - } - // Add length of previous segments, if any - if (ltpidx >= 0) - { - ratebuf[pidx] += ratebuf[ltpidx]; - } - - // Return the reduction in distortion - return dist; - } - - /// Performs the magnitude refinement pass on the specified data and - /// bit-plane. It codes the samples which are significant and which do not - /// have the "visited" state bit turned on, using the MR primitive. The - /// "visited" state bit is not mofified for any samples. - /// - /// - /// The code-block data to code - /// - /// - /// The MQ-coder to use - /// - /// - /// If true it performs an MQ-coder termination after the end - /// of the pass - /// - /// - /// The bit-plane to code - /// - /// - /// The state information for the code-block - /// - /// - /// The distortion estimation lookup table for MR - /// - /// - /// The buffer to hold symbols to send to the MQ coder - /// - /// - /// A buffer to hold the contexts to use in sending the - /// buffered symbols to the MQ coder. - /// - /// - /// The buffer where to store the rate (i.e. coded lenth) at - /// the end of this coding pass. - /// - /// - /// The coding pass index. Is the index in the 'ratebuf' array - /// where to store the coded length after this coding pass. - /// - /// - /// The index of the last pass that was terminated, or - /// negative if none. - /// - /// - /// The bitmask of entropy coding options to apply to the - /// code-block - /// - /// - /// The decrease in distortion for this pass, in the fixed-point - /// normalized representation of the 'FS_LOSSY' and 'FS_LOSSLESS' tables. - /// - /// - static private int magRefPass(CBlkWTData srcblk, MQCoder mq, bool doterm, int bp, int[] state, int[] fm, int[] symbuf, int[] ctxtbuf, int[] ratebuf, int pidx, int ltpidx, int options) - { - int j, sj; // The state index for line and stripe - int k, sk; // The data index for line and stripe - int nsym = 0; // Symbol counter for symbol and context buffers - int dscanw; // The data scan-width - int sscanw; // The state scan-width - int jstep; // Stripe to stripe step for 'sj' - int kstep; // Stripe to stripe step for 'sk' - int stopsk; // The loop limit on the variable sk - int csj; // Local copy (i.e. cached) of 'state[j]' - int mask; // The mask for the current bit-plane - int[] data; // The data buffer - int dist; // The distortion reduction for this pass - int shift; // Shift amount for distortion - int upshift; // Shift left amount for distortion - int downshift; // Shift right amount for distortion - int normval; // The normalized sample magnitude value - int s; // The stripe index - int nstripes; // The number of stripes in the code-block - int sheight; // Height of the current stripe - - // Initialize local variables - dscanw = srcblk.scanw; - sscanw = srcblk.w + 2; - jstep = sscanw * CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT / 2 - srcblk.w; - kstep = dscanw * CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT - srcblk.w; - mask = 1 << bp; - data = (int[])srcblk.Data; - nstripes = (srcblk.h + CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT - 1) / CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT; - dist = 0; - // We use the bit just coded plus MSE_LKP_BITS-1 bits below the bit - // just coded for distortion estimation. - shift = bp - MSE_LKP_BITS_M1; - upshift = (shift >= 0) ? 0 : -shift; - downshift = (shift <= 0) ? 0 : shift; - - // Code stripe by stripe - sk = srcblk.offset; - sj = sscanw + 1; - for (s = nstripes - 1; s >= 0; s--, sk += kstep, sj += jstep) - { - sheight = (s != 0) ? CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT : srcblk.h - (nstripes - 1) * CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT; - stopsk = sk + srcblk.w; - // Scan by set of 1 stripe column at a time - for (nsym = 0; sk < stopsk; sk++, sj++) - { - // Do half top of column - j = sj; - csj = state[j]; - // If any of the two samples is significant and not yet - // visited in the current bit-plane we can not skip them - if ((((SupportClass.URShift(csj, 1)) & (~csj)) & VSTD_MASK_R1R2) != 0) - { - k = sk; - // Scan first row - if ((csj & (STATE_SIG_R1 | STATE_VISITED_R1)) == STATE_SIG_R1) - { - // Apply MR primitive - symbuf[nsym] = SupportClass.URShift((data[k] & mask), bp); - ctxtbuf[nsym++] = MR_LUT[csj & MR_MASK]; - // Update the STATE_PREV_MR bit - csj |= STATE_PREV_MR_R1; - // Update distortion - normval = (data[k] >> downshift) << upshift; - dist += fm[normval & ((1 << MSE_LKP_BITS) - 1)]; - } - if (sheight < 2) - { - state[j] = csj; - continue; - } - // Scan second row - if ((csj & (STATE_SIG_R2 | STATE_VISITED_R2)) == STATE_SIG_R2) - { - k += dscanw; - // Apply MR primitive - symbuf[nsym] = SupportClass.URShift((data[k] & mask), bp); - ctxtbuf[nsym++] = MR_LUT[(SupportClass.URShift(csj, STATE_SEP)) & MR_MASK]; - // Update the STATE_PREV_MR bit - csj |= STATE_PREV_MR_R2; - // Update distortion - normval = (data[k] >> downshift) << upshift; - dist += fm[normval & ((1 << MSE_LKP_BITS) - 1)]; - } - state[j] = csj; - } - // Do half bottom of column - if (sheight < 3) - continue; - j += sscanw; - csj = state[j]; - // If any of the two samples is significant and not yet - // visited in the current bit-plane we can not skip them - if ((((SupportClass.URShift(csj, 1)) & (~csj)) & VSTD_MASK_R1R2) != 0) - { - k = sk + (dscanw << 1); - // Scan first row - if ((csj & (STATE_SIG_R1 | STATE_VISITED_R1)) == STATE_SIG_R1) - { - // Apply MR primitive - symbuf[nsym] = SupportClass.URShift((data[k] & mask), bp); - ctxtbuf[nsym++] = MR_LUT[csj & MR_MASK]; - // Update the STATE_PREV_MR bit - csj |= STATE_PREV_MR_R1; - // Update distortion - normval = (data[k] >> downshift) << upshift; - dist += fm[normval & ((1 << MSE_LKP_BITS) - 1)]; - } - if (sheight < 4) - { - state[j] = csj; - continue; - } - // Scan second row - if ((state[j] & (STATE_SIG_R2 | STATE_VISITED_R2)) == STATE_SIG_R2) - { - k += dscanw; - // Apply MR primitive - symbuf[nsym] = SupportClass.URShift((data[k] & mask), bp); - ctxtbuf[nsym++] = MR_LUT[(SupportClass.URShift(csj, STATE_SEP)) & MR_MASK]; - // Update the STATE_PREV_MR bit - csj |= STATE_PREV_MR_R2; - // Update distortion - normval = (data[k] >> downshift) << upshift; - dist += fm[normval & ((1 << MSE_LKP_BITS) - 1)]; - } - state[j] = csj; - } - } - // Code all buffered symbols, if any - if (nsym > 0) - mq.codeSymbols(symbuf, ctxtbuf, nsym); - } - - // Reset the MQ context states if we need to - if ((options & CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_RESET_MQ) != 0) - { - mq.resetCtxts(); - } - - // Terminate the MQ bit stream if we need to - if (doterm) - { - ratebuf[pidx] = mq.terminate(); // Termination has special length - } - else - { - // Use normal length calculation - ratebuf[pidx] = mq.NumCodedBytes; - } - // Add length of previous segments, if any - if (ltpidx >= 0) - { - ratebuf[pidx] += ratebuf[ltpidx]; - } - // Finish length calculation if needed - if (doterm) - { - mq.finishLengthCalculation(ratebuf, pidx); - } - - // Return the reduction in distortion - return dist; - } - - /// Performs the magnitude refinement pass on the specified data and - /// bit-plane, without using the arithmetic coder. It codes the samples - /// which are significant and which do not have the "visited" state bit - /// turned on, using the MR primitive. The "visited" state bit is not - /// mofified for any samples. - /// - ///

    In this method, the arithmetic coder is bypassed, and raw bits are - /// directly written in the bit stream (useful when distribution are close - /// to uniform, for intance, at high bit-rates and at lossless - /// compression). The 'STATE_PREV_MR_R1' and 'STATE_PREV_MR_R2' bits are - /// not set because they are used only when the arithmetic coder is not - /// bypassed.

    - /// - ///
    - /// The code-block data to code - /// - /// - /// The bit based output - /// - /// - /// If true the bit based output is byte aligned after the - /// end of the pass. - /// - /// - /// The bit-plane to code - /// - /// - /// The state information for the code-block - /// - /// - /// The distortion estimation lookup table for MR - /// - /// - /// The buffer where to store the rate (i.e. coded lenth) at - /// the end of this coding pass. - /// - /// - /// The coding pass index. Is the index in the 'ratebuf' array - /// where to store the coded length after this coding pass. - /// - /// - /// The index of the last pass that was terminated, or - /// negative if none. - /// - /// - /// The bitmask of entropy coding options to apply to the - /// code-block - /// - /// - /// The decrease in distortion for this pass, in the fixed-point - /// normalized representation of the 'FS_LOSSY' and 'FS_LOSSLESS' tables. - /// - /// - static private int rawMagRefPass(CBlkWTData srcblk, BitToByteOutput bout, bool doterm, int bp, int[] state, int[] fm, int[] ratebuf, int pidx, int ltpidx, int options) - { - int j, sj; // The state index for line and stripe - int k, sk; // The data index for line and stripe - int dscanw; // The data scan-width - int sscanw; // The state scan-width - int jstep; // Stripe to stripe step for 'sj' - int kstep; // Stripe to stripe step for 'sk' - int stopsk; // The loop limit on the variable sk - int csj; // Local copy (i.e. cached) of 'state[j]' - int mask; // The mask for the current bit-plane - int[] data; // The data buffer - int dist; // The distortion reduction for this pass - int shift; // Shift amount for distortion - int upshift; // Shift left amount for distortion - int downshift; // Shift right amount for distortion - int normval; // The normalized sample magnitude value - int s; // The stripe index - int nstripes; // The number of stripes in the code-block - int sheight; // Height of the current stripe - int nsym = 0; - - // Initialize local variables - dscanw = srcblk.scanw; - sscanw = srcblk.w + 2; - jstep = sscanw * CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT / 2 - srcblk.w; - kstep = dscanw * CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT - srcblk.w; - mask = 1 << bp; - data = (int[])srcblk.Data; - nstripes = (srcblk.h + CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT - 1) / CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT; - dist = 0; - // We use the bit just coded plus MSE_LKP_BITS-1 bits below the bit - // just coded for distortion estimation. - shift = bp - MSE_LKP_BITS_M1; - upshift = (shift >= 0) ? 0 : -shift; - downshift = (shift <= 0) ? 0 : shift; - - // Code stripe by stripe - sk = srcblk.offset; - sj = sscanw + 1; - for (s = nstripes - 1; s >= 0; s--, sk += kstep, sj += jstep) - { - sheight = (s != 0) ? CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT : srcblk.h - (nstripes - 1) * CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT; - stopsk = sk + srcblk.w; - // Scan by set of 1 stripe column at a time - for (; sk < stopsk; sk++, sj++) - { - // Do half top of column - j = sj; - csj = state[j]; - // If any of the two samples is significant and not yet - // visited in the current bit-plane we can not skip them - if ((((SupportClass.URShift(csj, 1)) & (~csj)) & VSTD_MASK_R1R2) != 0) - { - k = sk; - // Scan first row - if ((csj & (STATE_SIG_R1 | STATE_VISITED_R1)) == STATE_SIG_R1) - { - // Code bit "raw" - bout.writeBit(SupportClass.URShift((data[k] & mask), bp)); - nsym++; - // No need to set STATE_PREV_MR_R1 since all magnitude - // refinement passes to follow are "raw" - // Update distortion - normval = (data[k] >> downshift) << upshift; - dist += fm[normval & ((1 << MSE_LKP_BITS) - 1)]; - } - if (sheight < 2) - continue; - // Scan second row - if ((csj & (STATE_SIG_R2 | STATE_VISITED_R2)) == STATE_SIG_R2) - { - k += dscanw; - // Code bit "raw" - bout.writeBit(SupportClass.URShift((data[k] & mask), bp)); - nsym++; - // No need to set STATE_PREV_MR_R2 since all magnitude - // refinement passes to follow are "raw" - // Update distortion - normval = (data[k] >> downshift) << upshift; - dist += fm[normval & ((1 << MSE_LKP_BITS) - 1)]; - } - } - // Do half bottom of column - if (sheight < 3) - continue; - j += sscanw; - csj = state[j]; - // If any of the two samples is significant and not yet - // visited in the current bit-plane we can not skip them - if ((((SupportClass.URShift(csj, 1)) & (~csj)) & VSTD_MASK_R1R2) != 0) - { - k = sk + (dscanw << 1); - // Scan first row - if ((csj & (STATE_SIG_R1 | STATE_VISITED_R1)) == STATE_SIG_R1) - { - // Code bit "raw" - bout.writeBit(SupportClass.URShift((data[k] & mask), bp)); - nsym++; - // No need to set STATE_PREV_MR_R1 since all magnitude - // refinement passes to follow are "raw" - // Update distortion - normval = (data[k] >> downshift) << upshift; - dist += fm[normval & ((1 << MSE_LKP_BITS) - 1)]; - } - if (sheight < 4) - continue; - // Scan second row - if ((state[j] & (STATE_SIG_R2 | STATE_VISITED_R2)) == STATE_SIG_R2) - { - k += dscanw; - // Code bit "raw" - bout.writeBit(SupportClass.URShift((data[k] & mask), bp)); - nsym++; - // No need to set STATE_PREV_MR_R2 since all magnitude - // refinement passes to follow are "raw" - // Update distortion - normval = (data[k] >> downshift) << upshift; - dist += fm[normval & ((1 << MSE_LKP_BITS) - 1)]; - } - } - } - } - - // Get length and terminate if needed - if (doterm) - { - ratebuf[pidx] = bout.terminate(); - } - else - { - ratebuf[pidx] = bout.length(); - } - - // Add length of previous segments, if any - if (ltpidx >= 0) - { - ratebuf[pidx] += ratebuf[ltpidx]; - } - - // Return the reduction in distortion - return dist; - } - - /// Performs the cleanup pass on the specified data and bit-plane. It codes - /// all insignificant samples which have its "visited" state bit off, using - /// the ZC, SC, and RLC primitives. It toggles the "visited" state bit to 0 - /// (off) for all samples in the code-block. - /// - /// - /// The code-block data to code - /// - /// - /// The MQ-coder to use - /// - /// - /// If true it performs an MQ-coder termination after the end - /// of the pass - /// - /// - /// The bit-plane to code - /// - /// - /// The state information for the code-block - /// - /// - /// The distortion estimation lookup table for SC - /// - /// - /// The ZC lookup table to use in ZC. - /// - /// - /// The buffer to hold symbols to send to the MQ coder - /// - /// - /// A buffer to hold the contexts to use in sending the - /// buffered symbols to the MQ coder. - /// - /// - /// The buffer where to store the rate (i.e. coded lenth) at - /// the end of this coding pass. - /// - /// - /// The coding pass index. Is the index in the 'ratebuf' array - /// where to store the coded length after this coding pass. - /// - /// - /// The index of the last pass that was terminated, or - /// negative if none. - /// - /// - /// The bitmask of entropy coding options to apply to the - /// code-block - /// - /// - /// The decrease in distortion for this pass, in the fixed-point - /// normalized representation of the 'FS_LOSSY' and 'FS_LOSSLESS' tables. - /// - /// - static private int cleanuppass(CBlkWTData srcblk, MQCoder mq, bool doterm, int bp, int[] state, int[] fs, int[] zc_lut, int[] symbuf, int[] ctxtbuf, int[] ratebuf, int pidx, int ltpidx, int options) - { - // NOTE: The speedup mode of the MQ coder has been briefly tried to - // speed up the coding of insignificants RLCs, without any success - // (i.e. no speedup whatsoever). The use of the speedup mode should be - // revisisted more in depth and the implementationn of it in MQCoder - // should be reviewed for optimization opportunities. - int j, sj; // The state index for line and stripe - int k, sk; // The data index for line and stripe - int nsym = 0; // Symbol counter for symbol and context buffers - int dscanw; // The data scan-width - int sscanw; // The state scan-width - int jstep; // Stripe to stripe step for 'sj' - int kstep; // Stripe to stripe step for 'sk' - int stopsk; // The loop limit on the variable sk - int csj; // Local copy (i.e. cached) of 'state[j]' - int mask; // The mask for the current bit-plane - int sym; // The symbol to code - int rlclen; // Length of RLC - int ctxt; // The context to use - int[] data; // The data buffer - int dist; // The distortion reduction for this pass - int shift; // Shift amount for distortion - int upshift; // Shift left amount for distortion - int downshift; // Shift right amount for distortion - int normval; // The normalized sample magnitude value - int s; // The stripe index - bool causal; // Flag to indicate if stripe-causal context - // formation is to be used - int nstripes; // The number of stripes in the code-block - int sheight; // Height of the current stripe - int off_ul, off_ur, off_dr, off_dl; // offsets - - // Initialize local variables - dscanw = srcblk.scanw; - sscanw = srcblk.w + 2; - jstep = sscanw * CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT / 2 - srcblk.w; - kstep = dscanw * CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT - srcblk.w; - mask = 1 << bp; - data = (int[])srcblk.Data; - nstripes = (srcblk.h + CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT - 1) / CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT; - dist = 0; - // We use the MSE_LKP_BITS-1 bits below the bit just coded for - // distortion estimation. - shift = bp - MSE_LKP_BITS_M1; - upshift = (shift >= 0) ? 0 : -shift; - downshift = (shift <= 0) ? 0 : shift; - causal = (options & CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_VERT_STR_CAUSAL) != 0; - - // Pre-calculate offsets in 'state' for diagonal neighbors - off_ul = -sscanw - 1; // up-left - off_ur = -sscanw + 1; // up-right - off_dr = sscanw + 1; // down-right - off_dl = sscanw - 1; // down-left - - // Code stripe by stripe - sk = srcblk.offset; - sj = sscanw + 1; - for (s = nstripes - 1; s >= 0; s--, sk += kstep, sj += jstep) - { - sheight = (s != 0) ? CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT : srcblk.h - (nstripes - 1) * CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT; - stopsk = sk + srcblk.w; - // Scan by set of 1 stripe column at a time - for (nsym = 0; sk < stopsk; sk++, sj++) - { - // Start column - j = sj; - csj = state[j]; - { - // Check for RLC: if all samples are not significant, not - // visited and do not have a non-zero context, and column - // is full height, we do RLC. - if (csj == 0 && state[j + sscanw] == 0 && sheight == CSJ2K.j2k.entropy.StdEntropyCoderOptions.STRIPE_HEIGHT) - { - k = sk; - if ((data[k] & mask) != 0) - { - rlclen = 0; - } - else if ((data[k += dscanw] & mask) != 0) - { - rlclen = 1; - } - else if ((data[k += dscanw] & mask) != 0) - { - rlclen = 2; - j += sscanw; - csj = state[j]; - } - else if ((data[k += dscanw] & mask) != 0) - { - rlclen = 3; - j += sscanw; - csj = state[j]; - } - else - { - // Code insignificant RLC - symbuf[nsym] = 0; - ctxtbuf[nsym++] = RLC_CTXT; - // Goto next column - continue; - } - // Code significant RLC - symbuf[nsym] = 1; - ctxtbuf[nsym++] = RLC_CTXT; - // Send MSB bit index - symbuf[nsym] = rlclen >> 1; - ctxtbuf[nsym++] = UNIF_CTXT; - // Send LSB bit index - symbuf[nsym] = rlclen & 0x01; - ctxtbuf[nsym++] = UNIF_CTXT; - // Code sign of sample that became significant - // Update distortion - normval = (data[k] >> downshift) << upshift; - dist += fs[normval & ((1 << MSE_LKP_BITS_M1) - 1)]; - // Apply sign coding - sym = SupportClass.URShift(data[k], 31); - if ((rlclen & 0x01) == 0) - { - // Sample that became significant is first row of - // its column half - ctxt = SC_LUT[(SupportClass.URShift(csj, SC_SHIFT_R1)) & SC_MASK]; - symbuf[nsym] = sym ^ (SupportClass.URShift(ctxt, SC_SPRED_SHIFT)); - ctxtbuf[nsym++] = ctxt & SC_LUT_MASK; - // Update state information (significant bit, - // visited bit, neighbor significant bit of - // neighbors, non zero context of neighbors, sign - // of neighbors) - if (rlclen != 0 || !causal) - { - // If in causal mode do not change contexts of - // previous stripe. - state[j + off_ul] |= STATE_NZ_CTXT_R2 | STATE_D_DR_R2; - state[j + off_ur] |= STATE_NZ_CTXT_R2 | STATE_D_DL_R2; - } - // Update sign state information of neighbors - if (sym != 0) - { - csj |= STATE_SIG_R1 | STATE_VISITED_R1 | STATE_NZ_CTXT_R2 | STATE_V_U_R2 | STATE_V_U_SIGN_R2; - if (rlclen != 0 || !causal) - { - // If in causal mode do not change - // contexts of previous stripe. - state[j - sscanw] |= STATE_NZ_CTXT_R2 | STATE_V_D_R2 | STATE_V_D_SIGN_R2; - } - state[j + 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_H_L_R1 | STATE_H_L_SIGN_R1 | STATE_D_UL_R2; - state[j - 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_H_R_R1 | STATE_H_R_SIGN_R1 | STATE_D_UR_R2; - } - else - { - csj |= STATE_SIG_R1 | STATE_VISITED_R1 | STATE_NZ_CTXT_R2 | STATE_V_U_R2; - if (rlclen != 0 || !causal) - { - // If in causal mode do not change - // contexts of previous stripe. - state[j - sscanw] |= STATE_NZ_CTXT_R2 | STATE_V_D_R2; - } - state[j + 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_H_L_R1 | STATE_D_UL_R2; - state[j - 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_H_R_R1 | STATE_D_UR_R2; - } - // Changes to csj are saved later - if ((rlclen >> 1) != 0) - { - // Sample that became significant is in bottom - // half of column => jump to bottom half - //UPGRADE_NOTE: Labeled break statement was changed to a goto statement. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1012'" - goto top_half_brk; - } - // Otherwise sample that became significant is in - // top half of column => continue on top half - } - else - { - // Sample that became significant is second row of - // its column half - ctxt = SC_LUT[(SupportClass.URShift(csj, SC_SHIFT_R2)) & SC_MASK]; - symbuf[nsym] = sym ^ (SupportClass.URShift(ctxt, SC_SPRED_SHIFT)); - ctxtbuf[nsym++] = ctxt & SC_LUT_MASK; - // Update state information (significant bit, - // neighbor significant bit of neighbors, non zero - // context of neighbors, sign of neighbors) - state[j + off_dl] |= STATE_NZ_CTXT_R1 | STATE_D_UR_R1; - state[j + off_dr] |= STATE_NZ_CTXT_R1 | STATE_D_UL_R1; - // Update sign state information of neighbors - if (sym != 0) - { - csj |= STATE_SIG_R2 | STATE_NZ_CTXT_R1 | STATE_V_D_R1 | STATE_V_D_SIGN_R1; - state[j + sscanw] |= STATE_NZ_CTXT_R1 | STATE_V_U_R1 | STATE_V_U_SIGN_R1; - state[j + 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_D_DL_R1 | STATE_H_L_R2 | STATE_H_L_SIGN_R2; - state[j - 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_D_DR_R1 | STATE_H_R_R2 | STATE_H_R_SIGN_R2; - } - else - { - csj |= STATE_SIG_R2 | STATE_NZ_CTXT_R1 | STATE_V_D_R1; - state[j + sscanw] |= STATE_NZ_CTXT_R1 | STATE_V_U_R1; - state[j + 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_D_DL_R1 | STATE_H_L_R2; - state[j - 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_D_DR_R1 | STATE_H_R_R2; - } - // Save changes to csj - state[j] = csj; - if ((rlclen >> 1) != 0) - { - // Sample that became significant is in bottom - // half of column => we're done with this - // column - continue; - } - // Otherwise sample that became significant is in - // top half of column => we're done with top - // column - j += sscanw; - csj = state[j]; - //UPGRADE_NOTE: Labeled break statement was changed to a goto statement. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1012'" - goto top_half_brk; - } - } - // Do half top of column - // If any of the two samples is not significant and has - // not been visited in the current bit-plane we can not - // skip them - if ((((csj >> 1) | csj) & VSTD_MASK_R1R2) != VSTD_MASK_R1R2) - { - k = sk; - // Scan first row - if ((csj & (STATE_SIG_R1 | STATE_VISITED_R1)) == 0) - { - // Apply zero coding - ctxtbuf[nsym] = zc_lut[csj & ZC_MASK]; - if ((symbuf[nsym++] = SupportClass.URShift((data[k] & mask), bp)) != 0) - { - // Became significant - // Apply sign coding - sym = SupportClass.URShift(data[k], 31); - ctxt = SC_LUT[(SupportClass.URShift(csj, SC_SHIFT_R1)) & SC_MASK]; - symbuf[nsym] = sym ^ (SupportClass.URShift(ctxt, SC_SPRED_SHIFT)); - ctxtbuf[nsym++] = ctxt & SC_LUT_MASK; - // Update state information (significant bit, - // visited bit, neighbor significant bit of - // neighbors, non zero context of neighbors, - // sign of neighbors) - if (!causal) - { - // If in causal mode do not change - // contexts of previous stripe. - state[j + off_ul] |= STATE_NZ_CTXT_R2 | STATE_D_DR_R2; - state[j + off_ur] |= STATE_NZ_CTXT_R2 | STATE_D_DL_R2; - } - // Update sign state information of neighbors - if (sym != 0) - { - csj |= STATE_SIG_R1 | STATE_VISITED_R1 | STATE_NZ_CTXT_R2 | STATE_V_U_R2 | STATE_V_U_SIGN_R2; - if (!causal) - { - // If in causal mode do not change - // contexts of previous stripe. - state[j - sscanw] |= STATE_NZ_CTXT_R2 | STATE_V_D_R2 | STATE_V_D_SIGN_R2; - } - state[j + 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_H_L_R1 | STATE_H_L_SIGN_R1 | STATE_D_UL_R2; - state[j - 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_H_R_R1 | STATE_H_R_SIGN_R1 | STATE_D_UR_R2; - } - else - { - csj |= STATE_SIG_R1 | STATE_VISITED_R1 | STATE_NZ_CTXT_R2 | STATE_V_U_R2; - if (!causal) - { - // If in causal mode do not change - // contexts of previous stripe. - state[j - sscanw] |= STATE_NZ_CTXT_R2 | STATE_V_D_R2; - } - state[j + 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_H_L_R1 | STATE_D_UL_R2; - state[j - 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_H_R_R1 | STATE_D_UR_R2; - } - // Update distortion - normval = (data[k] >> downshift) << upshift; - dist += fs[normval & ((1 << MSE_LKP_BITS_M1) - 1)]; - } - } - if (sheight < 2) - { - csj &= ~(STATE_VISITED_R1 | STATE_VISITED_R2); - state[j] = csj; - continue; - } - // Scan second row - if ((csj & (STATE_SIG_R2 | STATE_VISITED_R2)) == 0) - { - k += dscanw; - // Apply zero coding - ctxtbuf[nsym] = zc_lut[(SupportClass.URShift(csj, STATE_SEP)) & ZC_MASK]; - if ((symbuf[nsym++] = SupportClass.URShift((data[k] & mask), bp)) != 0) - { - // Became significant - // Apply sign coding - sym = SupportClass.URShift(data[k], 31); - ctxt = SC_LUT[(SupportClass.URShift(csj, SC_SHIFT_R2)) & SC_MASK]; - symbuf[nsym] = sym ^ (SupportClass.URShift(ctxt, SC_SPRED_SHIFT)); - ctxtbuf[nsym++] = ctxt & SC_LUT_MASK; - // Update state information (significant bit, - // visited bit, neighbor significant bit of - // neighbors, non zero context of neighbors, - // sign of neighbors) - state[j + off_dl] |= STATE_NZ_CTXT_R1 | STATE_D_UR_R1; - state[j + off_dr] |= STATE_NZ_CTXT_R1 | STATE_D_UL_R1; - // Update sign state information of neighbors - if (sym != 0) - { - csj |= STATE_SIG_R2 | STATE_VISITED_R2 | STATE_NZ_CTXT_R1 | STATE_V_D_R1 | STATE_V_D_SIGN_R1; - state[j + sscanw] |= STATE_NZ_CTXT_R1 | STATE_V_U_R1 | STATE_V_U_SIGN_R1; - state[j + 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_D_DL_R1 | STATE_H_L_R2 | STATE_H_L_SIGN_R2; - state[j - 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_D_DR_R1 | STATE_H_R_R2 | STATE_H_R_SIGN_R2; - } - else - { - csj |= STATE_SIG_R2 | STATE_VISITED_R2 | STATE_NZ_CTXT_R1 | STATE_V_D_R1; - state[j + sscanw] |= STATE_NZ_CTXT_R1 | STATE_V_U_R1; - state[j + 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_D_DL_R1 | STATE_H_L_R2; - state[j - 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_D_DR_R1 | STATE_H_R_R2; - } - // Update distortion - normval = (data[k] >> downshift) << upshift; - dist += fs[normval & ((1 << MSE_LKP_BITS_M1) - 1)]; - } - } - } - csj &= ~(STATE_VISITED_R1 | STATE_VISITED_R2); - state[j] = csj; - // Do half bottom of column - if (sheight < 3) - continue; - j += sscanw; - csj = state[j]; - } - //UPGRADE_NOTE: Label 'top_half_brk' was added. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1011'" - - top_half_brk:; - // end of 'top_half' block - // If any of the two samples is not significant and has - // not been visited in the current bit-plane we can not - // skip them - if ((((csj >> 1) | csj) & VSTD_MASK_R1R2) != VSTD_MASK_R1R2) - { - k = sk + (dscanw << 1); - // Scan first row - if ((csj & (STATE_SIG_R1 | STATE_VISITED_R1)) == 0) - { - // Apply zero coding - ctxtbuf[nsym] = zc_lut[csj & ZC_MASK]; - if ((symbuf[nsym++] = SupportClass.URShift((data[k] & mask), bp)) != 0) - { - // Became significant - // Apply sign coding - sym = SupportClass.URShift(data[k], 31); - ctxt = SC_LUT[(SupportClass.URShift(csj, SC_SHIFT_R1)) & SC_MASK]; - symbuf[nsym] = sym ^ (SupportClass.URShift(ctxt, SC_SPRED_SHIFT)); - ctxtbuf[nsym++] = ctxt & SC_LUT_MASK; - // Update state information (significant bit, - // visited bit, neighbor significant bit of - // neighbors, non zero context of neighbors, - // sign of neighbors) - state[j + off_ul] |= STATE_NZ_CTXT_R2 | STATE_D_DR_R2; - state[j + off_ur] |= STATE_NZ_CTXT_R2 | STATE_D_DL_R2; - // Update sign state information of neighbors - if (sym != 0) - { - csj |= STATE_SIG_R1 | STATE_VISITED_R1 | STATE_NZ_CTXT_R2 | STATE_V_U_R2 | STATE_V_U_SIGN_R2; - state[j - sscanw] |= STATE_NZ_CTXT_R2 | STATE_V_D_R2 | STATE_V_D_SIGN_R2; - state[j + 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_H_L_R1 | STATE_H_L_SIGN_R1 | STATE_D_UL_R2; - state[j - 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_H_R_R1 | STATE_H_R_SIGN_R1 | STATE_D_UR_R2; - } - else - { - csj |= STATE_SIG_R1 | STATE_VISITED_R1 | STATE_NZ_CTXT_R2 | STATE_V_U_R2; - state[j - sscanw] |= STATE_NZ_CTXT_R2 | STATE_V_D_R2; - state[j + 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_H_L_R1 | STATE_D_UL_R2; - state[j - 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_H_R_R1 | STATE_D_UR_R2; - } - // Update distortion - normval = (data[k] >> downshift) << upshift; - dist += fs[normval & ((1 << MSE_LKP_BITS_M1) - 1)]; - } - } - if (sheight < 4) - { - csj &= ~(STATE_VISITED_R1 | STATE_VISITED_R2); - state[j] = csj; - continue; - } - // Scan second row - if ((csj & (STATE_SIG_R2 | STATE_VISITED_R2)) == 0) - { - k += dscanw; - // Apply zero coding - ctxtbuf[nsym] = zc_lut[(SupportClass.URShift(csj, STATE_SEP)) & ZC_MASK]; - if ((symbuf[nsym++] = SupportClass.URShift((data[k] & mask), bp)) != 0) - { - // Became significant - // Apply sign coding - sym = SupportClass.URShift(data[k], 31); - ctxt = SC_LUT[(SupportClass.URShift(csj, SC_SHIFT_R2)) & SC_MASK]; - symbuf[nsym] = sym ^ (SupportClass.URShift(ctxt, SC_SPRED_SHIFT)); - ctxtbuf[nsym++] = ctxt & SC_LUT_MASK; - // Update state information (significant bit, - // visited bit, neighbor significant bit of - // neighbors, non zero context of neighbors, - // sign of neighbors) - state[j + off_dl] |= STATE_NZ_CTXT_R1 | STATE_D_UR_R1; - state[j + off_dr] |= STATE_NZ_CTXT_R1 | STATE_D_UL_R1; - // Update sign state information of neighbors - if (sym != 0) - { - csj |= STATE_SIG_R2 | STATE_VISITED_R2 | STATE_NZ_CTXT_R1 | STATE_V_D_R1 | STATE_V_D_SIGN_R1; - state[j + sscanw] |= STATE_NZ_CTXT_R1 | STATE_V_U_R1 | STATE_V_U_SIGN_R1; - state[j + 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_D_DL_R1 | STATE_H_L_R2 | STATE_H_L_SIGN_R2; - state[j - 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_D_DR_R1 | STATE_H_R_R2 | STATE_H_R_SIGN_R2; - } - else - { - csj |= STATE_SIG_R2 | STATE_VISITED_R2 | STATE_NZ_CTXT_R1 | STATE_V_D_R1; - state[j + sscanw] |= STATE_NZ_CTXT_R1 | STATE_V_U_R1; - state[j + 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_D_DL_R1 | STATE_H_L_R2; - state[j - 1] |= STATE_NZ_CTXT_R1 | STATE_NZ_CTXT_R2 | STATE_D_DR_R1 | STATE_H_R_R2; - } - // Update distortion - normval = (data[k] >> downshift) << upshift; - dist += fs[normval & ((1 << MSE_LKP_BITS_M1) - 1)]; - } - } - } - csj &= ~(STATE_VISITED_R1 | STATE_VISITED_R2); - state[j] = csj; - } - // Code all buffered symbols, if any - if (nsym > 0) - mq.codeSymbols(symbuf, ctxtbuf, nsym); - } - - // Insert a segment marker if we need to - if ((options & CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_SEG_SYMBOLS) != 0) - { - mq.codeSymbols(SEG_SYMBOLS, SEG_SYMB_CTXTS, SEG_SYMBOLS.Length); - } - - // Reset the MQ context states if we need to - if ((options & CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_RESET_MQ) != 0) - { - mq.resetCtxts(); - } - - // Terminate the MQ bit stream if we need to - if (doterm) - { - ratebuf[pidx] = mq.terminate(); // Termination has special length - } - else - { - // Use normal length calculation - ratebuf[pidx] = mq.NumCodedBytes; - } - // Add length of previous segments, if any - if (ltpidx >= 0) - { - ratebuf[pidx] += ratebuf[ltpidx]; - } - // Finish length calculation if needed - if (doterm) - { - mq.finishLengthCalculation(ratebuf, pidx); - } - // Return the reduction in distortion - return dist; - } - - /// Ensures that at the end of a non-terminated coding pass there is not a - /// 0xFF byte, modifying the stored rates if necessary. - /// - ///

    Due to error resiliance reasons, a coding pass should never have its - /// last byte be a 0xFF, since that can lead to the emulation of a resync - /// marker. This method checks if that is the case, and reduces the rate - /// for a given pass if necessary. The ommitted 0xFF will be synthetized by - /// the decoder if necessary, as required by JPEG 2000. This method should - /// only be called once that the entire code-block is coded.

    - /// - ///

    Passes that are terminated are not checked for the 0xFF byte, since - /// it is assumed that the termination procedure does not output any - /// trailing 0xFF. Checking the terminated segments would involve much more - /// than just modifying the stored rates.

    - /// - ///

    NOTE: It is assumed by this method that the coded data does not - /// contain consecutive 0xFF bytes, as is the case with the MQ and - /// 'arithemetic coding bypass' bit stuffing policy. However, the - /// termination policies used should also respect this requirement.

    - /// - ///
    - /// The coded data for the code-block - /// - /// - /// The rate (i.e. accumulated number of bytes) for each - /// coding pass - /// - /// - /// An array of flags indicating, for each pass, if it is - /// terminated or not. If null it is assumed that no pass is terminated, - /// except the last one. - /// - /// - /// The number of coding passes - /// - /// - static private void checkEndOfPassFF(byte[] data, int[] rates, bool[] isterm, int n) - { - int dp; // the position to test in 'data' - - // If a pass ends in 0xFF we need to reduce the number of bytes in it, - // so that it does not end in 0xFF. We only need to go back one byte - // since there can be no consecutive 0xFF bytes. - - // If there are no terminated passes avoid the test on 'isterm' - if (isterm == null) - { - for (n--; n >= 0; n--) - { - dp = rates[n] - 1; - if (dp >= 0 && (data[dp] == (byte)0xFF)) - { - rates[n]--; - } - } - } - else - { - for (n--; n >= 0; n--) - { - if (!isterm[n]) - { - dp = rates[n] - 1; - if (dp >= 0 && (data[dp] == (byte)0xFF)) - { - rates[n]--; - } - } - } - } - } - - /// Load options, length calculation type and termination type for each - /// tile-component. - /// - /// - /// The number of tiles - /// - /// - /// The number of components - /// - /// - public virtual void initTileComp(int nt, int nc) - { - - opts = new int[nt][]; - for (int i2 = 0; i2 < nt; i2++) - { - opts[i2] = new int[nc]; - } - lenCalc = new int[nt][]; - for (int i3 = 0; i3 < nt; i3++) - { - lenCalc[i3] = new int[nc]; - } - tType = new int[nt][]; - for (int i4 = 0; i4 < nt; i4++) - { - tType[i4] = new int[nc]; - } - - for (int t = 0; t < nt; t++) - { - for (int c = 0; c < nc; c++) - { - opts[t][c] = 0; - - // Bypass coding mode ? - if (((System.String)bms.getTileCompVal(t, c)).ToUpper().Equals("on".ToUpper())) - { - opts[t][c] |= CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_BYPASS; - } - // MQ reset after each coding pass ? - if (((System.String)mqrs.getTileCompVal(t, c)).ToUpper().Equals("on".ToUpper())) - { - opts[t][c] |= CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_RESET_MQ; - } - // MQ termination after each arithmetically coded coding pass ? - if (((System.String)rts.getTileCompVal(t, c)).ToUpper().Equals("on".ToUpper())) - { - opts[t][c] |= CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_TERM_PASS; - } - // Vertically stripe-causal context mode ? - if (((System.String)css.getTileCompVal(t, c)).ToUpper().Equals("on".ToUpper())) - { - opts[t][c] |= CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_VERT_STR_CAUSAL; - } - // Error resilience segmentation symbol insertion ? - if (((System.String)sss.getTileCompVal(t, c)).ToUpper().Equals("on".ToUpper())) - { - opts[t][c] |= CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_SEG_SYMBOLS; - } - - // Set length calculation type of the MQ coder - System.String lCalcType = (System.String)lcs.getTileCompVal(t, c); - if (lCalcType.Equals("near_opt")) - { - lenCalc[t][c] = MQCoder.LENGTH_NEAR_OPT; - } - else if (lCalcType.Equals("lazy_good")) - { - lenCalc[t][c] = MQCoder.LENGTH_LAZY_GOOD; - } - else if (lCalcType.Equals("lazy")) - { - lenCalc[t][c] = MQCoder.LENGTH_LAZY; - } - else - { - throw new System.ArgumentException("Unrecognized or " + "unsupported MQ " + "length calculation."); - } - - // Set termination type of MQ coder - System.String termType = (System.String)tts.getTileCompVal(t, c); - if (termType.ToUpper().Equals("easy".ToUpper())) - { - tType[t][c] = MQCoder.TERM_EASY; - } - else if (termType.ToUpper().Equals("full".ToUpper())) - { - tType[t][c] = MQCoder.TERM_FULL; - } - else if (termType.ToUpper().Equals("near_opt".ToUpper())) - { - tType[t][c] = MQCoder.TERM_NEAR_OPT; - } - else if (termType.ToUpper().Equals("predict".ToUpper())) - { - tType[t][c] = MQCoder.TERM_PRED_ER; - opts[t][c] |= CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_PRED_TERM; - if ((opts[t][c] & (CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_TERM_PASS | CSJ2K.j2k.entropy.StdEntropyCoderOptions.OPT_BYPASS)) == 0) - { - FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.INFO, "Using error resilient MQ" + " termination, but terminating only at " + "the end of code-blocks. The error " + "protection offered by this option will" + " be very weak. Specify the " + "'Cterminate' " + "and/or 'Cbypass' option for " + "increased error resilience."); - } - } - else - { - throw new System.ArgumentException("Unrecognized or " + "unsupported " + "MQ coder " + "termination."); - } - } // End loop on components - } // End loop on tiles - } - - /// Returns the precinct partition width for the specified component, tile - /// and resolution level. - /// - /// - /// the tile index - /// - /// - /// the component - /// - /// - /// the resolution level - /// - /// - /// The precinct partition width for the specified component, tile - /// and resolution level - /// - /// - public override int getPPX(int t, int c, int rl) - { - return pss.getPPX(t, c, rl); - } - - /// Returns the precinct partition height for the specified component, tile - /// and resolution level. - /// - /// - /// the tile index - /// - /// - /// the component - /// - /// - /// the resolution level - /// - /// - /// The precinct partition height for the specified component, tile - /// and resolution level - /// - /// - public override int getPPY(int t, int c, int rl) - { - return pss.getPPY(t, c, rl); - } - - /// Returns true if precinct partition is used for the specified component - /// and tile, returns false otherwise. - /// - /// - /// The component - /// - /// - /// The tile - /// - /// - /// True if precinct partition is used for the specified component - /// and tile, returns false otherwise. - /// - /// - public override bool precinctPartitionUsed(int c, int t) - { - return precinctPartition[c][t]; - } - /// Static initializer: initializes all the lookup tables. - static StdEntropyCoder() - { - { - int i, j; - double val, deltaMSE; - int[] inter_sc_lut; - int ds, us, rs, ls; - int dsgn, usgn, rsgn, lsgn; - int h, v; - - // Initialize the zero coding lookup tables - - // LH - - // - No neighbors significant - ZC_LUT_LH[0] = 2; - - // - No horizontal or vertical neighbors significant - for (i = 1; i < 16; i++) - { - // Two or more diagonal coeffs significant - ZC_LUT_LH[i] = 4; - } - for (i = 0; i < 4; i++) - { - // Only one diagonal coeff significant - ZC_LUT_LH[1 << i] = 3; - } - // - No horizontal neighbors significant, diagonal irrelevant - for (i = 0; i < 16; i++) - { - // Only one vertical coeff significant - ZC_LUT_LH[STATE_V_U_R1 | i] = 5; - ZC_LUT_LH[STATE_V_D_R1 | i] = 5; - // The two vertical coeffs significant - ZC_LUT_LH[STATE_V_U_R1 | STATE_V_D_R1 | i] = 6; - } - // - One horiz. neighbor significant, diagonal/vertical non-significant - ZC_LUT_LH[STATE_H_L_R1] = 7; - ZC_LUT_LH[STATE_H_R_R1] = 7; - // - One horiz. significant, no vertical significant, one or more - // diagonal significant - for (i = 1; i < 16; i++) - { - ZC_LUT_LH[STATE_H_L_R1 | i] = 8; - ZC_LUT_LH[STATE_H_R_R1 | i] = 8; - } - // - One horiz. significant, one or more vertical significant, - // diagonal irrelevant - for (i = 1; i < 4; i++) - { - for (j = 0; j < 16; j++) - { - ZC_LUT_LH[STATE_H_L_R1 | (i << 4) | j] = 9; - ZC_LUT_LH[STATE_H_R_R1 | (i << 4) | j] = 9; - } - } - // - Two horiz. significant, others irrelevant - for (i = 0; i < 64; i++) - { - ZC_LUT_LH[STATE_H_L_R1 | STATE_H_R_R1 | i] = 10; - } - - // HL - - // - No neighbors significant - ZC_LUT_HL[0] = 2; - // - No horizontal or vertical neighbors significant - for (i = 1; i < 16; i++) - { - // Two or more diagonal coeffs significant - ZC_LUT_HL[i] = 4; - } - for (i = 0; i < 4; i++) - { - // Only one diagonal coeff significant - ZC_LUT_HL[1 << i] = 3; - } - // - No vertical significant, diagonal irrelevant - for (i = 0; i < 16; i++) - { - // One horiz. significant - ZC_LUT_HL[STATE_H_L_R1 | i] = 5; - ZC_LUT_HL[STATE_H_R_R1 | i] = 5; - // Two horiz. significant - ZC_LUT_HL[STATE_H_L_R1 | STATE_H_R_R1 | i] = 6; - } - // - One vert. significant, diagonal/horizontal non-significant - ZC_LUT_HL[STATE_V_U_R1] = 7; - ZC_LUT_HL[STATE_V_D_R1] = 7; - // - One vert. significant, horizontal non-significant, one or more - // diag. significant - for (i = 1; i < 16; i++) - { - ZC_LUT_HL[STATE_V_U_R1 | i] = 8; - ZC_LUT_HL[STATE_V_D_R1 | i] = 8; - } - // - One vertical significant, one or more horizontal significant, - // diagonal irrelevant - for (i = 1; i < 4; i++) - { - for (j = 0; j < 16; j++) - { - ZC_LUT_HL[(i << 6) | STATE_V_U_R1 | j] = 9; - ZC_LUT_HL[(i << 6) | STATE_V_D_R1 | j] = 9; - } - } - // - Two vertical significant, others irrelevant - for (i = 0; i < 4; i++) - { - for (j = 0; j < 16; j++) - { - ZC_LUT_HL[(i << 6) | STATE_V_U_R1 | STATE_V_D_R1 | j] = 10; - } - } - - // HH - int[] twoBits = new int[] { 3, 5, 6, 9, 10, 12 }; // Figures (between 0 and 15) - // countaning 2 and only 2 bits on in its binary representation. - - int[] oneBit = new int[] { 1, 2, 4, 8 }; // Figures (between 0 and 15) - // countaning 1 and only 1 bit on in its binary representation. - - int[] twoLeast = new int[] { 3, 5, 6, 7, 9, 10, 11, 12, 13, 14, 15 }; // Figures - // (between 0 and 15) countaining, at least, 2 bits on in its - // binary representation. - - int[] threeLeast = new int[] { 7, 11, 13, 14, 15 }; // Figures - // (between 0 and 15) countaining, at least, 3 bits on in its - // binary representation. - - // - None significant - ZC_LUT_HH[0] = 2; - - // - One horizontal+vertical significant, none diagonal - for (i = 0; i < oneBit.Length; i++) - ZC_LUT_HH[oneBit[i] << 4] = 3; - - // - Two or more horizontal+vertical significant, diagonal non-signif - for (i = 0; i < twoLeast.Length; i++) - ZC_LUT_HH[twoLeast[i] << 4] = 4; - - // - One diagonal significant, horiz./vert. non-significant - for (i = 0; i < oneBit.Length; i++) - ZC_LUT_HH[oneBit[i]] = 5; - - // - One diagonal significant, one horiz.+vert. significant - for (i = 0; i < oneBit.Length; i++) - for (j = 0; j < oneBit.Length; j++) - ZC_LUT_HH[(oneBit[i] << 4) | oneBit[j]] = 6; - - // - One diag signif, two or more horiz+vert signif - for (i = 0; i < twoLeast.Length; i++) - for (j = 0; j < oneBit.Length; j++) - ZC_LUT_HH[(twoLeast[i] << 4) | oneBit[j]] = 7; - - // - Two diagonal significant, none horiz+vert significant - for (i = 0; i < twoBits.Length; i++) - ZC_LUT_HH[twoBits[i]] = 8; - - // - Two diagonal significant, one or more horiz+vert significant - for (j = 0; j < twoBits.Length; j++) - for (i = 1; i < 16; i++) - ZC_LUT_HH[(i << 4) | twoBits[j]] = 9; - - // - Three or more diagonal significant, horiz+vert irrelevant - for (i = 0; i < 16; i++) - for (j = 0; j < threeLeast.Length; j++) - ZC_LUT_HH[(i << 4) | threeLeast[j]] = 10; - - // Initialize the SC lookup tables - - // Use an intermediate sign code lookup table that is similar to the - // one in the VM text, in that it depends on the 'h' and 'v' - // quantities. The index into this table is a 6 bit index, the top 3 - // bits are (h+1) and the low 3 bits (v+1). - inter_sc_lut = new int[36]; - inter_sc_lut[(2 << 3) | 2] = 15; - inter_sc_lut[(2 << 3) | 1] = 14; - inter_sc_lut[(2 << 3) | 0] = 13; - inter_sc_lut[(1 << 3) | 2] = 12; - inter_sc_lut[(1 << 3) | 1] = 11; - inter_sc_lut[(1 << 3) | 0] = 12 | INT_SIGN_BIT; - inter_sc_lut[(0 << 3) | 2] = 13 | INT_SIGN_BIT; - inter_sc_lut[(0 << 3) | 1] = 14 | INT_SIGN_BIT; - inter_sc_lut[(0 << 3) | 0] = 15 | INT_SIGN_BIT; - - // Using the intermediate sign code lookup table create the final - // one. The index into this table is a 9 bit index, the low 4 bits are - // the significance of the 4 horizontal/vertical neighbors, while the - // top 4 bits are the signs of those neighbors. The bit in the middle - // is ignored. This index arrangement matches the state bits in the - // 'state' array, thus direct addressing of the table can be done from - // the sate information. - for (i = 0; i < (1 << SC_LUT_BITS) - 1; i++) - { - ds = i & 0x01; // significance of down neighbor - us = (i >> 1) & 0x01; // significance of up neighbor - rs = (i >> 2) & 0x01; // significance of right neighbor - ls = (i >> 3) & 0x01; // significance of left neighbor - dsgn = (i >> 5) & 0x01; // sign of down neighbor - usgn = (i >> 6) & 0x01; // sign of up neighbor - rsgn = (i >> 7) & 0x01; // sign of right neighbor - lsgn = (i >> 8) & 0x01; // sign of left neighbor - // Calculate 'h' and 'v' as in VM text - h = ls * (1 - 2 * lsgn) + rs * (1 - 2 * rsgn); - h = (h >= -1) ? h : -1; - h = (h <= 1) ? h : 1; - v = us * (1 - 2 * usgn) + ds * (1 - 2 * dsgn); - v = (v >= -1) ? v : -1; - v = (v <= 1) ? v : 1; - // Get context and sign predictor from 'inter_sc_lut' - SC_LUT[i] = inter_sc_lut[(h + 1) << 3 | (v + 1)]; - } - inter_sc_lut = null; - - // Initialize the MR lookup tables - - // None significant, prev MR off - MR_LUT[0] = 16; - // One or more significant, prev MR off - for (i = 1; i < (1 << (MR_LUT_BITS - 1)); i++) - { - MR_LUT[i] = 17; - } - // Previous MR on, significance irrelevant - for (; i < (1 << MR_LUT_BITS); i++) - { - MR_LUT[i] = 18; - } - - // Initialize the distortion estimation lookup tables - - // fs tables - for (i = 0; i < (1 << MSE_LKP_BITS_M1); i++) - { - // In fs we index by val-1, since val is really: 1 <= val < 2 - val = (double)i / (1 << MSE_LKP_BITS_M1) + 1.0; - deltaMSE = val * val; - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - FS_LOSSLESS[i] = (int)System.Math.Floor(deltaMSE * ((double)(1 << MSE_LKP_FRAC_BITS)) + 0.5); - val -= 1.5; - deltaMSE -= val * val; - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - FS_LOSSY[i] = (int)System.Math.Floor(deltaMSE * ((double)(1 << MSE_LKP_FRAC_BITS)) + 0.5); - } - - // fm tables - for (i = 0; i < (1 << MSE_LKP_BITS); i++) - { - val = (double)i / (1 << MSE_LKP_BITS_M1); - deltaMSE = (val - 1.0) * (val - 1.0); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - FM_LOSSLESS[i] = (int)System.Math.Floor(deltaMSE * ((double)(1 << MSE_LKP_FRAC_BITS)) + 0.5); - val -= ((i < (1 << MSE_LKP_BITS_M1)) ? 0.5 : 1.5); - deltaMSE -= val * val; - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - FM_LOSSY[i] = (int)System.Math.Floor(deltaMSE * ((double)(1 << MSE_LKP_FRAC_BITS)) + 0.5); - } - } - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/fileformat/FileFormatBoxes.cs b/CSJ2K/j2k/fileformat/FileFormatBoxes.cs deleted file mode 100644 index a8f64248..00000000 --- a/CSJ2K/j2k/fileformat/FileFormatBoxes.cs +++ /dev/null @@ -1,102 +0,0 @@ -/* -* cvs identifier: -* -* $Id: FileFormatBoxes.java,v 1.10 2001/02/14 12:22:20 qtxjoas Exp $ -* -* Class: FileFormatMarkers -* -* Description: Contains definitions of boxes used in jp2 files -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* -* -* -*/ -namespace CSJ2K.j2k.fileformat -{ - - - /// This class contains all the markers used in the JPEG 2000 Part I file format - /// - /// - /// - /// - /// - /// - /// - /// - public struct FileFormatBoxes - { - /// * Main boxes *** - - public const int READER_REQUIREMENTS_BOX = 0x72726571; - public const int JP2_SIGNATURE_BOX = 0x6a502020; - public const int FILE_TYPE_BOX = 0x66747970; - public const int JP2_HEADER_BOX = 0x6a703268; - public const int CONTIGUOUS_CODESTREAM_BOX = 0x6a703263; - public const int INTELLECTUAL_PROPERTY_BOX = 0x64703269; - public const int XML_BOX = 0x786d6c20; - public const int UUID_BOX = 0x75756964; - public const int UUID_INFO_BOX = 0x75696e66; - /// JP2 Header boxes - public const int IMAGE_HEADER_BOX = 0x69686472; - public const int BITS_PER_COMPONENT_BOX = 0x62706363; - public const int COLOUR_SPECIFICATION_BOX = 0x636f6c72; - public const int PALETTE_BOX = 0x70636c72; - public const int COMPONENT_MAPPING_BOX = 0x636d6170; - public const int CHANNEL_DEFINITION_BOX = 0x63646566; - public const int RESOLUTION_BOX = 0x72657320; - public const int CAPTURE_RESOLUTION_BOX = 0x72657363; - public const int DEFAULT_DISPLAY_RESOLUTION_BOX = 0x72657364; - /// UUID Info Boxes - public const int UUID_LIST_BOX = 0x75637374; - public const int URL_BOX = 0x75726c20; - /// end of UUID Info boxes - /// Image Header Box Fields - public const int IMB_VERS = 0x0100; - public const int IMB_C = 7; - public const int IMB_UnkC = 1; - public const int IMB_IPR = 0; - /// end of Image Header Box Fields - /// Colour Specification Box Fields - public const int CSB_METH = 1; - public const int CSB_PREC = 0; - public const int CSB_APPROX = 0; - public const int CSB_ENUM_SRGB = 16; - public const int CSB_ENUM_GREY = 17; - /// en of Colour Specification Box Fields - /// File Type Fields - public const int FT_BR = 0x6a703220; - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/fileformat/reader/FileFormatReader.cs b/CSJ2K/j2k/fileformat/reader/FileFormatReader.cs deleted file mode 100644 index 5fbaa475..00000000 --- a/CSJ2K/j2k/fileformat/reader/FileFormatReader.cs +++ /dev/null @@ -1,451 +0,0 @@ -/* -* cvs identifier: -* -* $Id: FileFormatReader.java,v 1.16 2002/07/25 14:04:08 grosbois Exp $ -* -* Class: FileFormatReader -* -* Description: Reads the file format -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.io; -using CSJ2K.j2k.util; -namespace CSJ2K.j2k.fileformat.reader -{ - - /// This class reads the file format wrapper that may or may not exist around a - /// valid JPEG 2000 codestream. Since no information from the file format is - /// used in the actual decoding, this class simply goes through the file and - /// finds the first valid codestream. - /// - /// - /// - /// - /// - public class FileFormatReader - { - /// This method creates and returns an array of positions to contiguous - /// codestreams in the file - /// - /// - /// The positions of the contiguous codestreams in the file - /// - /// - virtual public long[] CodeStreamPos - { - get - { - int size = codeStreamPos.Count; - long[] pos = new long[size]; - for (int i = 0; i < size; i++) - pos[i] = (long)((System.Int32)(codeStreamPos[i])); - return pos; - } - - } - /// This method returns the position of the first contiguous codestreams in - /// the file - /// - /// - /// The position of the first contiguous codestream in the file - /// - /// - virtual public int FirstCodeStreamPos - { - get - { - return ((System.Int32)(codeStreamPos[0])); - } - - } - /// This method returns the length of the first contiguous codestreams in - /// the file - /// - /// - /// The length of the first contiguous codestream in the file - /// - /// - virtual public int FirstCodeStreamLength - { - get - { - return ((System.Int32)(codeStreamLength[0])); - } - - } - - /// The random access from which the file format boxes are read - private RandomAccessIO in_Renamed; - - /// The positions of the codestreams in the fileformat - private System.Collections.ArrayList codeStreamPos; - - /// The lengths of the codestreams in the fileformat - private System.Collections.ArrayList codeStreamLength; - - /// Flag indicating whether or not the JP2 file format is used - public bool JP2FFUsed; - - /// The constructor of the FileFormatReader - /// - /// - /// The RandomAccessIO from which to read the file format - /// - /// - public FileFormatReader(RandomAccessIO in_Renamed) - { - this.in_Renamed = in_Renamed; - } - - /// This method checks whether the given RandomAccessIO is a valid JP2 file - /// and if so finds the first codestream in the file. Currently, the - /// information in the codestream is not used - /// - /// - /// The RandomAccessIO from which to read the file format - /// - /// - /// If an I/O error ocurred. - /// - /// - /// If end of file is reached - /// - /// - public virtual void readFileFormat() - { - - //int foundCodeStreamBoxes = 0; - int box; - int length; - long longLength = 0; - int pos; - short marker; - bool jp2HeaderBoxFound = false; - bool lastBoxFound = false; - - try - { - - // Go through the randomaccessio and find the first contiguous - // codestream box. Check also that the File Format is correct - - // Make sure that the first 12 bytes is the JP2_SIGNATURE_BOX or - // if not that the first 2 bytes is the SOC marker - if (in_Renamed.readInt() != 0x0000000c || in_Renamed.readInt() != CSJ2K.j2k.fileformat.FileFormatBoxes.JP2_SIGNATURE_BOX || in_Renamed.readInt() != 0x0d0a870a) - { - // Not a JP2 file - in_Renamed.seek(0); - - marker = (short)in_Renamed.readShort(); - if (marker != CSJ2K.j2k.codestream.Markers.SOC) - //Standard syntax marker found - throw new System.ApplicationException("File is neither valid JP2 file nor " + "valid JPEG 2000 codestream"); - JP2FFUsed = false; - in_Renamed.seek(0); - return; - } - - // The JP2 File format is being used - JP2FFUsed = true; - - // Read File Type box - if (!readFileTypeBox()) - { - // Not a valid JP2 file or codestream - throw new System.ApplicationException("Invalid JP2 file: File Type box missing"); - } - - // Read all remaining boxes - while (!lastBoxFound) - { - pos = in_Renamed.Pos; - length = in_Renamed.readInt(); - if ((pos + length) == in_Renamed.length()) - lastBoxFound = true; - - box = in_Renamed.readInt(); - if (length == 0) - { - lastBoxFound = true; - length = in_Renamed.length() - in_Renamed.Pos; - } - else if (length == 1) - { - longLength = in_Renamed.readLong(); - throw new System.IO.IOException("File too long."); - } - else - longLength = (long)0; - - switch (box) - { - - case CSJ2K.j2k.fileformat.FileFormatBoxes.CONTIGUOUS_CODESTREAM_BOX: - if (!jp2HeaderBoxFound) - { - throw new System.ApplicationException("Invalid JP2 file: JP2Header box not " + "found before Contiguous codestream " + "box "); - } - readContiguousCodeStreamBox(pos, length, longLength); - break; - - case CSJ2K.j2k.fileformat.FileFormatBoxes.JP2_HEADER_BOX: - if (jp2HeaderBoxFound) - throw new System.ApplicationException("Invalid JP2 file: Multiple " + "JP2Header boxes found"); - readJP2HeaderBox(pos, length, longLength); - jp2HeaderBoxFound = true; - break; - - case CSJ2K.j2k.fileformat.FileFormatBoxes.INTELLECTUAL_PROPERTY_BOX: - readIntPropertyBox(length); - break; - - case CSJ2K.j2k.fileformat.FileFormatBoxes.XML_BOX: - readXMLBox(length); - break; - - case CSJ2K.j2k.fileformat.FileFormatBoxes.UUID_BOX: - readUUIDBox(length); - break; - - case CSJ2K.j2k.fileformat.FileFormatBoxes.UUID_INFO_BOX: - readUUIDInfoBox(length); - break; - - case CSJ2K.j2k.fileformat.FileFormatBoxes.READER_REQUIREMENTS_BOX: - readReaderRequirementsBox(length); - break; - - default: - FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.WARNING, "Unknown box-type: 0x" + System.Convert.ToString(box, 16)); - break; - - } - if (!lastBoxFound) - in_Renamed.seek(pos + length); - } - } - catch (System.IO.EndOfStreamException) - { - throw new System.ApplicationException("EOF reached before finding Contiguous " + "Codestream Box"); - } - - if (codeStreamPos.Count == 0) - { - // Not a valid JP2 file or codestream - throw new System.ApplicationException("Invalid JP2 file: Contiguous codestream box " + "missing"); - } - - return; - } - - /// This method reads the File Type box. - /// - /// - /// false if the File Type box was not found or invalid else true - /// - /// - /// If an I/O error ocurred. - /// - /// If the end of file was reached - /// - /// - public virtual bool readFileTypeBox() - { - int length; - long longLength = 0; - int pos; - int nComp; - bool foundComp = false; - - // Get current position in file - pos = in_Renamed.Pos; - - // Read box length (LBox) - length = in_Renamed.readInt(); - if (length == 0) - { - // This can not be last box - throw new System.ApplicationException("Zero-length of Profile Box"); - } - - // Check that this is a File Type box (TBox) - if (in_Renamed.readInt() != CSJ2K.j2k.fileformat.FileFormatBoxes.FILE_TYPE_BOX) - { - return false; - } - - // Check for XLBox - if (length == 1) - { - // Box has 8 byte length; - longLength = in_Renamed.readLong(); - throw new System.IO.IOException("File too long."); - } - - // Read Brand field - in_Renamed.readInt(); - - // Read MinV field - in_Renamed.readInt(); - - // Check that there is at least one FT_BR entry in in - // compatibility list - nComp = (length - 16) / 4; // Number of compatibilities. - for (int i = nComp; i > 0; i--) - { - if (in_Renamed.readInt() == CSJ2K.j2k.fileformat.FileFormatBoxes.FT_BR) - foundComp = true; - } - if (!foundComp) - { - return false; - } - - return true; - } - - /// This method reads the JP2Header box - /// - /// - /// The position in the file - /// - /// - /// The length of the JP2Header box - /// - /// - /// length The length of the JP2Header box if greater than - /// 1<<32 - /// - /// - /// false if the JP2Header box was not found or invalid else true - /// - /// - /// If an I/O error ocurred. - /// - /// - /// If the end of file was reached - /// - /// - public virtual bool readJP2HeaderBox(long pos, int length, long longLength) - { - - if (length == 0) - { - // This can not be last box - throw new System.ApplicationException("Zero-length of JP2Header Box"); - } - - // Here the JP2Header data (DBox) would be read if we were to use it - - return true; - } - - /// This method skips the Contiguous codestream box and adds position - /// of contiguous codestream to a vector - /// - /// - /// The position in the file - /// - /// - /// The length of the JP2Header box - /// - /// - /// length The length of the JP2Header box if greater than 1<<32 - /// - /// - /// false if the Contiguous codestream box was not found or invalid - /// else true - /// - /// - /// If an I/O error ocurred. - /// - /// - /// If the end of file was reached - /// - /// - public virtual bool readContiguousCodeStreamBox(long pos, int length, long longLength) - { - - // Add new codestream position to position vector - int ccpos = in_Renamed.Pos; - - if (codeStreamPos == null) - codeStreamPos = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); - codeStreamPos.Add((System.Int32)ccpos); - - // Add new codestream length to length vector - if (codeStreamLength == null) - codeStreamLength = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); - codeStreamLength.Add((System.Int32)length); - - return true; - } - - /// This method reads the contents of the Intellectual property box - /// - /// - public virtual void readIntPropertyBox(int length) - { - } - - /// This method reads the contents of the XML box - /// - /// - public virtual void readXMLBox(int length) - { - } - - /// This method reads the contents of the Intellectual property box - /// - /// - public virtual void readUUIDBox(int length) - { - } - - /// This method reads the contents of the Intellectual property box - /// - /// - public virtual void readUUIDInfoBox(int length) - { - } - - /// This method reads the contents of the Reader requirements box - /// - /// - public virtual void readReaderRequirementsBox(int length) - { - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/fileformat/writer/FileFormatWriter.cs b/CSJ2K/j2k/fileformat/writer/FileFormatWriter.cs deleted file mode 100644 index b79f7d13..00000000 --- a/CSJ2K/j2k/fileformat/writer/FileFormatWriter.cs +++ /dev/null @@ -1,364 +0,0 @@ -/* -* cvs identifier: -* -* $Id: FileFormatWriter.java,v 1.13 2001/02/16 11:53:54 qtxjoas Exp $ -* -* Class: FileFormatWriter -* -* Description: Writes the file format -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.io; -namespace CSJ2K.j2k.fileformat.writer -{ - - /// This class writes the file format wrapper that may or may not exist around - /// a valid JPEG 2000 codestream. This class writes the simple possible legal - /// fileformat - /// - /// - /// - /// - /// - public class FileFormatWriter - { - - /// The file from which to read the codestream and write file - private BEBufferedRandomAccessFile fi; - - /// The name of the file from which to read the codestream and to write - /// the JP2 file - /// - private System.String filename; - - /// Image height - private int height; - - /// Image width - private int width; - - /// Number of components - private int nc; - - /// Bits per component - private int[] bpc; - - /// Flag indicating whether number of bits per component varies - private bool bpcVaries; - - /// Length of codestream - private int clength; - - /// Length of Colour Specification Box - private const int CSB_LENGTH = 15; - - /// Length of File Type Box - private const int FTB_LENGTH = 20; - - /// Length of Image Header Box - private const int IHB_LENGTH = 22; - - /// base length of Bits Per Component box - private const int BPC_LENGTH = 8; - - - - /// The constructor of the FileFormatWriter. It receives all the - /// information necessary about a codestream to generate a legal JP2 file - /// - /// - /// The name of the file that is to be made a JP2 file - /// - /// - /// The height of the image - /// - /// - /// The width of the image - /// - /// - /// The number of components - /// - /// - /// The number of bits per component - /// - /// - /// Length of codestream - /// - /// - public FileFormatWriter(System.String filename, int height, int width, int nc, int[] bpc, int clength) - { - this.height = height; - this.width = width; - this.nc = nc; - this.bpc = bpc; - this.filename = filename; - this.clength = clength; - - bpcVaries = false; - int fixbpc = bpc[0]; - for (int i = nc - 1; i > 0; i--) - { - if (bpc[i] != fixbpc) - bpcVaries = true; - } - } - - - - /// This method reads the codestream and writes the file format wrapper and - /// the codestream to the same file - /// - /// - /// The number of bytes increases because of the file format - /// - /// - /// If an I/O error ocurred. - /// - /// - public virtual int writeFileFormat() - { - byte[] codestream; - - try - { - // Read and buffer the codestream - fi = new BEBufferedRandomAccessFile(filename, "rw+"); - codestream = new byte[clength]; - fi.readFully(codestream, 0, clength); - - // Write the JP2_SINATURE_BOX - fi.seek(0); - fi.writeInt(0x0000000c); - fi.writeInt(CSJ2K.j2k.fileformat.FileFormatBoxes.JP2_SIGNATURE_BOX); - fi.writeInt(0x0d0a870a); - - // Write File Type box - writeFileTypeBox(); - - // Write JP2 Header box - writeJP2HeaderBox(); - - // Write the Codestream box - writeContiguousCodeStreamBox(codestream); - - fi.close(); - } - catch (System.Exception e) - { - throw new System.ApplicationException("Error while writing JP2 file format(2): " + e.Message + "\n" + e.StackTrace); - } - if (bpcVaries) - return 12 + FTB_LENGTH + 8 + IHB_LENGTH + CSB_LENGTH + BPC_LENGTH + nc + 8; - else - return 12 + FTB_LENGTH + 8 + IHB_LENGTH + CSB_LENGTH + 8; - } - - /// This method writes the File Type box - /// - /// - /// If an I/O error ocurred. - /// - /// - public virtual void writeFileTypeBox() - { - // Write box length (LBox) - // LBox(4) + TBox (4) + BR(4) + MinV(4) + CL(4) = 20 - fi.writeInt(FTB_LENGTH); - - // Write File Type box (TBox) - fi.writeInt(CSJ2K.j2k.fileformat.FileFormatBoxes.FILE_TYPE_BOX); - - // Write File Type data (DBox) - // Write Brand box (BR) - fi.writeInt(CSJ2K.j2k.fileformat.FileFormatBoxes.FT_BR); - - // Write Minor Version - fi.writeInt(0); - - // Write Compatibility list - fi.writeInt(CSJ2K.j2k.fileformat.FileFormatBoxes.FT_BR); - } - - /// This method writes the JP2Header box - /// - /// - /// If an I/O error ocurred. - /// - /// - public virtual void writeJP2HeaderBox() - { - - // Write box length (LBox) - // if the number of bits per components varies, a bpcc box is written - if (bpcVaries) - fi.writeInt(8 + IHB_LENGTH + CSB_LENGTH + BPC_LENGTH + nc); - else - fi.writeInt(8 + IHB_LENGTH + CSB_LENGTH); - - // Write a JP2Header (TBox) - fi.writeInt(CSJ2K.j2k.fileformat.FileFormatBoxes.JP2_HEADER_BOX); - - // Write image header box - writeImageHeaderBox(); - - // Write Colour Bpecification Box - writeColourSpecificationBox(); - - // if the number of bits per components varies write bpcc box - if (bpcVaries) - writeBitsPerComponentBox(); - } - - /// This method writes the Bits Per Component box - /// - /// - /// If an I/O error ocurred. - /// - /// - public virtual void writeBitsPerComponentBox() - { - - // Write box length (LBox) - fi.writeInt(BPC_LENGTH + nc); - - // Write a Bits Per Component box (TBox) - fi.writeInt(CSJ2K.j2k.fileformat.FileFormatBoxes.BITS_PER_COMPONENT_BOX); - - // Write bpc fields - for (int i = 0; i < nc; i++) - { - fi.writeByte(bpc[i] - 1); - } - } - - /// This method writes the Colour Specification box - /// - /// - /// If an I/O error ocurred. - /// - /// - public virtual void writeColourSpecificationBox() - { - - // Write box length (LBox) - fi.writeInt(CSB_LENGTH); - - // Write a Bits Per Component box (TBox) - fi.writeInt(CSJ2K.j2k.fileformat.FileFormatBoxes.COLOUR_SPECIFICATION_BOX); - - // Write METH field - fi.writeByte(CSJ2K.j2k.fileformat.FileFormatBoxes.CSB_METH); - - // Write PREC field - fi.writeByte(CSJ2K.j2k.fileformat.FileFormatBoxes.CSB_PREC); - - // Write APPROX field - fi.writeByte(CSJ2K.j2k.fileformat.FileFormatBoxes.CSB_APPROX); - - // Write EnumCS field - if (nc > 1) - fi.writeInt(CSJ2K.j2k.fileformat.FileFormatBoxes.CSB_ENUM_SRGB); - else - fi.writeInt(CSJ2K.j2k.fileformat.FileFormatBoxes.CSB_ENUM_GREY); - } - - /// This method writes the Image Header box - /// - /// - /// If an I/O error ocurred. - /// - /// - public virtual void writeImageHeaderBox() - { - - // Write box length - fi.writeInt(IHB_LENGTH); - - // Write ihdr box name - fi.writeInt(CSJ2K.j2k.fileformat.FileFormatBoxes.IMAGE_HEADER_BOX); - - // Write HEIGHT field - fi.writeInt(height); - - // Write WIDTH field - fi.writeInt(width); - - // Write NC field - fi.writeShort(nc); - - // Write BPC field - // if the number of bits per component varies write 0xff else write - // number of bits per components - if (bpcVaries) - fi.writeByte(0xff); - else - fi.writeByte(bpc[0] - 1); - - // Write C field - fi.writeByte(CSJ2K.j2k.fileformat.FileFormatBoxes.IMB_C); - - // Write UnkC field - fi.writeByte(CSJ2K.j2k.fileformat.FileFormatBoxes.IMB_UnkC); - - // Write IPR field - fi.writeByte(CSJ2K.j2k.fileformat.FileFormatBoxes.IMB_IPR); - } - - /// This method writes the Contiguous codestream box - /// - /// - /// The contiguous codestream - /// - /// - /// If an I/O error ocurred. - /// - /// - public virtual void writeContiguousCodeStreamBox(byte[] cs) - { - - // Write box length (LBox) - // This value is set to 0 since in this implementation, this box is - // always last - fi.writeInt(clength + 8); - - // Write contiguous codestream box name (TBox) - fi.writeInt(CSJ2K.j2k.fileformat.FileFormatBoxes.CONTIGUOUS_CODESTREAM_BOX); - - // Write codestream - for (int i = 0; i < clength; i++) - fi.writeByte(cs[i]); - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/image/BlkImgDataSrc.cs b/CSJ2K/j2k/image/BlkImgDataSrc.cs deleted file mode 100644 index 47e5b4e1..00000000 --- a/CSJ2K/j2k/image/BlkImgDataSrc.cs +++ /dev/null @@ -1,178 +0,0 @@ -/* -* CVS identifier: -* -* $Id: BlkImgDataSrc.java,v 1.9 2001/01/24 14:58:12 grosbois Exp $ -* -* Class: BlkImgDataSrc -* -* Description: Defines methods to transfer image data in blocks. -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -namespace CSJ2K.j2k.image -{ - - /// This interface defines the methods to transfer image data in blocks, - /// without following any particular order (random access). This interface does - /// not define the methods to access the image characteristics, such as width, - /// height, number of components, tiles, etc., or to change the current - /// tile. That is provided by other interfaces such as ImgData. - /// - ///

    This interface has the notion of a current tile. All data, coordinates - /// and dimensions are always relative to the current tile. If there is only - /// one tile then it is equivalent as having no tiles. - /// - ///

    A block of requested data may never cross tile boundaries. This should - /// be enforced by the implementing class, or the source of image data. - /// - ///

    This interface defines the methods that can be used to retrieve image - /// data. Implementing classes need not buffer all the image data, they can ask - /// their source to load the data they need. - /// - ///

    - /// - /// - /// - public interface BlkImgDataSrc : ImgData - { - - /// Returns the position of the fixed point in the specified component, or - /// equivalently the number of fractional bits. This is the position of the - /// least significant integral (i.e. non-fractional) bit, which is - /// equivalent to the number of fractional bits. For instance, for - /// fixed-point values with 2 fractional bits, 2 is returned. For - /// floating-point data this value does not apply and 0 should be - /// returned. Position 0 is the position of the least significant bit in - /// the data. - /// - /// - /// The index of the component. - /// - /// - /// The position of the fixed-point, which is the same as the - /// number of fractional bits. For floating-point data 0 is returned. - /// - /// - int getFixedPoint(int c); - - /// Returns, in the blk argument, a block of image data containing the - /// specifed rectangular area, in the specified component. The data is - /// returned, as a reference to the internal data, if any, instead of as a - /// copy, therefore the returned data should not be modified. - /// - ///

    The rectangular area to return is specified by the 'ulx', 'uly', 'w' - /// and 'h' members of the 'blk' argument, relative to the current - /// tile. These members are not modified by this method. The 'offset' and - /// 'scanw' of the returned data can be arbitrary. See the 'DataBlk' class. - /// - ///

    This method, in general, is more efficient than the 'getCompData()' - /// method since it may not copy the data. However if the array of returned - /// data is to be modified by the caller then the other method is probably - /// preferable. - /// - ///

    If possible, the data in the returned 'DataBlk' should be the - /// internal data itself, instead of a copy, in order to increase the data - /// transfer efficiency. However, this depends on the particular - /// implementation (it may be more convenient to just return a copy of the - /// data). This is the reason why the returned data should not be modified. - /// - ///

    If the data array in blk is null, then a new one - /// is created if necessary. The implementation of this interface may - /// choose to return the same array or a new one, depending on what is more - /// efficient. Therefore, the data array in blk prior to the - /// method call should not be considered to contain the returned data, a - /// new array may have been created. Instead, get the array from - /// blk after the method has returned. - /// - ///

    The returned data may have its 'progressive' attribute set. In this - /// case the returned data is only an approximation of the "final" data. - /// - ///

    - /// Its coordinates and dimensions specify the area to return, - /// relative to the current tile. Some fields in this object are modified - /// to return the data. - /// - /// - /// The index of the component from which to get the data. - /// - /// - /// The requested DataBlk - /// - /// - /// - /// - /// - DataBlk getInternCompData(DataBlk blk, int c); - - /// Returns, in the blk argument, a block of image data containing the - /// specifed rectangular area, in the specified component. The data is - /// returned, as a copy of the internal data, therefore the returned data - /// can be modified "in place". - /// - ///

    The rectangular area to return is specified by the 'ulx', 'uly', 'w' - /// and 'h' members of the 'blk' argument, relative to the current - /// tile. These members are not modified by this method. The 'offset' of - /// the returned data is 0, and the 'scanw' is the same as the block's - /// width. See the 'DataBlk' class. - /// - ///

    This method, in general, is less efficient than the - /// 'getInternCompData()' method since, in general, it copies the - /// data. However if the array of returned data is to be modified by the - /// caller then this method is preferable. - /// - ///

    If the data array in 'blk' is 'null', then a new one is created. If - /// the data array is not 'null' then it is reused, and it must be large - /// enough to contain the block's data. Otherwise an 'ArrayStoreException' - /// or an 'IndexOutOfBoundsException' is thrown by the Java system. - /// - ///

    The returned data may have its 'progressive' attribute set. In this - /// case the returned data is only an approximation of the "final" data. - /// - ///

    - /// Its coordinates and dimensions specify the area to return, - /// relative to the current tile. If it contains a non-null data array, - /// then it must be large enough. If it contains a null data array a new - /// one is created. Some fields in this object are modified to return the - /// data. - /// - /// - /// The index of the component from which to get the data. - /// - /// - /// - /// - /// - DataBlk getCompData(DataBlk blk, int c); - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/image/CompTransfSpec.cs b/CSJ2K/j2k/image/CompTransfSpec.cs deleted file mode 100644 index 7c2c64cd..00000000 --- a/CSJ2K/j2k/image/CompTransfSpec.cs +++ /dev/null @@ -1,108 +0,0 @@ -/* -* CVS identifier: -* -* $Id: CompTransfSpec.java,v 1.18 2001/04/10 14:23:26 grosbois Exp $ -* -* Class: CompTransfSpec -* -* Description: Component Transformation specification -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.image.invcomptransf; -namespace CSJ2K.j2k.image -{ - - /// This class extends the ModuleSpec class in order to hold tile - /// specifications for multiple component transformation - /// - /// - /// - /// - /// - public class CompTransfSpec : ModuleSpec - { - /// Check if component transformation is used in any of the tiles. This - /// method must not be used by the encoder. - /// - /// - /// True if a component transformation is used in at least on - /// tile. - /// - /// - virtual public bool CompTransfUsed - { - get - { - if (((System.Int32)def) != InvCompTransf.NONE) - { - return true; - } - - if (tileDef != null) - { - for (int t = nTiles - 1; t >= 0; t--) - { - if (tileDef[t] != null && (((System.Int32)tileDef[t]) != InvCompTransf.NONE)) - { - return true; - } - } - } - return false; - } - - } - - /// Constructs an empty 'CompTransfSpec' with the specified number of tiles - /// and components. This constructor is called by the decoder. Note: The - /// number of component is here for symmetry purpose. It is useless since - /// only tile specifications are meaningful. - /// - /// - /// Number of tiles - /// - /// - /// Number of components - /// - /// - /// the type of the specification module i.e. tile specific, - /// component specific or both. - /// - /// - public CompTransfSpec(int nt, int nc, byte type) : base(nt, nc, type) - { - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/image/Coord.cs b/CSJ2K/j2k/image/Coord.cs deleted file mode 100644 index 2f8ff35e..00000000 --- a/CSJ2K/j2k/image/Coord.cs +++ /dev/null @@ -1,103 +0,0 @@ -/* -* CVS identifier: -* -* $Id: Coord.java,v 1.14 2002/04/30 13:18:24 grosbois Exp $ -* -* Class: Coord -* -* Description: Class for storage of 2-D coordinates -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -namespace CSJ2K.j2k.image -{ - - /// This class represents 2-D coordinates. - /// - /// - public class Coord - { - /// The horizontal coordinate - public int x; - - /// The vertical coordinate - public int y; - - /// Creates a new coordinate object given with the (0,0) coordinates - /// - /// - public Coord() - { - } - - /// Creates a new coordinate object given the two coordinates. - /// - /// - /// The horizontal coordinate. - /// - /// - /// The vertical coordinate. - /// - /// - public Coord(int x, int y) - { - this.x = x; - this.y = y; - } - - /// Creates a new coordinate object given another Coord object i.e. copy - /// constructor - /// - /// - /// The Coord object to be copied. - /// - /// - public Coord(Coord c) - { - this.x = c.x; - this.y = c.y; - } - - /// Returns a string representation of the object coordinates - /// - /// - /// The vertical and the horizontal coordinates - /// - /// - public override System.String ToString() - { - return "(" + x + "," + y + ")"; - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/image/DataBlk.cs b/CSJ2K/j2k/image/DataBlk.cs deleted file mode 100644 index 4998b919..00000000 --- a/CSJ2K/j2k/image/DataBlk.cs +++ /dev/null @@ -1,233 +0,0 @@ -/* -* CVS Identifier: -* -* $Id: DataBlk.java,v 1.7 2001/04/15 14:32:05 grosbois Exp $ -* -* Interface: DataBlk -* -* Description: A generic interface to hold 2D blocks of data. -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -namespace CSJ2K.j2k.image -{ - - /// This is a generic abstract class to store data from a block of an - /// image. This class does not have the notion of components. Therefore, it - /// should be used for data from a single component. Subclasses should - /// implement the different types of storage (int, float, - /// etc.). - /// - ///

    The data is always stored in one array, of the type matching the data - /// type (i.e. for 'int' it's an 'int[]'). The data should be stored in the - /// array in standard scan-line order. That is the samples go from the top-left - /// corner of the code-block to the lower-right corner by line and then - /// column.

    - /// - ///

    The member variable 'offset' gives the index in the array of the first - /// data element (i.e. the top-left coefficient (ulx,uly)). The member variable - /// 'scanw' gives the width of the scan that is used to store the data, that - /// can be different from the width of the block. Element '(x,y)' of the - /// code-block (i.e. '(ulx,uly)' is the top-left coefficient), will appear at - /// position 'offset+(y-uly)*scanw+(x-ulx)' in the array of data.

    - /// - ///

    A block of data can have the progressive attribute set. Data is - /// progressive when it is obtained by successive refinement and the values in - /// this block are approximations of the "final" values. When the final values - /// are returned the progressive attribute must be turned off.

    - /// - ///

    The classes DataBlkInt and DataBlkFloat provide - /// implementations for int and float types respectively.

    - /// - ///
    - /// - /// - /// - /// - /// - /// - public abstract class DataBlk - { - /// Returns the data type of the DataBlk object, as defined in - /// this class. - /// - /// - /// The data type of the object, as defined in thsi class. - /// - /// - public abstract int DataType { get; } - //UPGRADE_NOTE: Respective javadoc comments were merged. It should be changed in order to comply with .NET documentation conventions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1199'" - /// Returns the array containing the data, or null if there is no data. The - /// returned array is of the type returned by getDataType() (e.g., - /// for TYPE_INT, it is a int[]). - /// - ///

    Each implementing class should provide a type specific equivalent - /// method (e.g., getDataInt() in DataBlkInt) which - /// returns an array of the correct type explicetely and not through an - /// Object.

    - /// - ///
    - /// The array containing the data, or null if there is no - /// data. - /// - /// - /// - /// - /// - /// Sets the data array to the specified one. The type of the specified - /// data array must match the one returned by getDataType() (e.g., - /// for TYPE_INT, it should be a int[]). If the wrong - /// type of array is given a ClassCastException will be thrown. - /// - ///

    The size of the array is not necessarily checked for consistency - /// with w and h or any other fields.

    - /// - ///

    Each implementing class should provide a type specific equivalent - /// method (e.g., setDataInt() in DataBlkInt) which takes - /// an array of the correct type explicetely and not through an - /// Object.

    - /// - ///
    - /// The new data array to use - /// - /// - /// - /// - /// - public abstract System.Object Data { get; set; } - - /// The identifier for the byte data type, as signed 8 bits. - public const int TYPE_BYTE = 0; - - /// The identifier for the short data type, as signed 16 bits. - public const int TYPE_SHORT = 1; - - /// The identifier for the int data type, as signed 32 bits. - public const int TYPE_INT = 3; - - /// The identifier for the float data type - public const int TYPE_FLOAT = 4; - - /// The horizontal coordinate (in pixels) of the upper-left corner of the - /// block of data. This is relative to the component of the image from - /// where this block was filled or is to be filled. - /// - public int ulx; - - /// The vertical coordinate of the upper-left corner of the block of - /// data. This is relative to the component of the image from where this - /// block was filled or is to be filled. - /// - public int uly; - - /// The width of the block, in pixels. - public int w; - - /// The height of the block, in pixels. - public int h; - - /// The offset in the array of the top-left coefficient - public int offset; - - /// The width of the scanlines used to store the data in the array - public int scanw; - - /// The progressive attribute (false by default) - public bool progressive; - - /// Returns the size in bits, given the data type. The data type must be - /// one defined in this class. An IllegalArgumentException is - /// thrown if type is not defined in this class. - /// - /// - /// The data type. - /// - /// - /// The size in bits of the data type. - /// - /// - public static int getSize(int type) - { - switch (type) - { - - case TYPE_BYTE: - return 8; - - case TYPE_SHORT: - return 16; - - case TYPE_INT: - case TYPE_FLOAT: - return 32; - - default: - throw new System.ArgumentException(); - - } - } - - /// Returns a string of informations about the DataBlk - /// - /// - /// Block dimensions and progressiveness in a string - /// - /// - public override System.String ToString() - { - System.String typeString = ""; - switch (DataType) - { - - case TYPE_BYTE: - typeString = "Unsigned Byte"; - break; - - case TYPE_SHORT: - typeString = "Short"; - break; - - case TYPE_INT: - typeString = "Integer"; - break; - - case TYPE_FLOAT: - typeString = "Float"; - break; - } - - return "DataBlk: " + "upper-left(" + ulx + "," + uly + "), width=" + w + ", height=" + h + ", progressive=" + progressive + ", offset=" + offset + ", scanw=" + scanw + ", type=" + typeString; - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/image/DataBlkFloat.cs b/CSJ2K/j2k/image/DataBlkFloat.cs deleted file mode 100644 index f78b3201..00000000 --- a/CSJ2K/j2k/image/DataBlkFloat.cs +++ /dev/null @@ -1,207 +0,0 @@ -/* -* CVS Identifier: -* -* $Id: DataBlkFloat.java,v 1.7 2001/10/09 12:52:01 grosbois Exp $ -* -* Interface: DataBlkFloat -* -* Description: A float implementation of DataBlk -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using System; -namespace CSJ2K.j2k.image -{ - - /// This is an implementation of the DataBlk interface for 32 bit - /// floating point data (float). - /// - ///

    The methods in this class are declared final, so that they can be - /// inlined by inlining compilers.

    - /// - ///
    - /// - /// - /// - public class DataBlkFloat : DataBlk - { - /// Returns the identifier of this data type, TYPE_FLOAT, as - /// defined in DataBlk. - /// - /// - /// The type of data stored. Always DataBlk.TYPE_FLOAT - /// - /// - /// - /// - /// - override public int DataType - { - get - { - return TYPE_FLOAT; - } - - } - //UPGRADE_NOTE: Respective javadoc comments were merged. It should be changed in order to comply with .NET documentation conventions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1199'" - /// Returns the array containing the data, or null if there is no data - /// array. The returned array is a float array. - /// - /// - /// The array of data (a float[]) or null if there is no data. - /// - /// - /// Sets the data array to the specified one. The provided array must be a - /// float array, otherwise a ClassCastException is thrown. The size of the - /// array is not checked for consistency with the block's dimensions. - /// - /// - /// The data array to use. Must be a float array. - /// - /// - override public System.Object Data - { - get - { - return data; - } - - set - { - data = (float[])value; - } - - } - //UPGRADE_NOTE: Respective javadoc comments were merged. It should be changed in order to comply with .NET documentation conventions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1199'" - /// Returns the array containing the data, or null if there is no data - /// array. - /// - /// - /// The array of data or null if there is no data. - /// - /// - /// Sets the data array to the specified one. The size of the array is not - /// checked for consistency with the block's dimensions. - /// - /// - /// The data array to use. - /// - /// - virtual public float[] DataFloat - { - get - { - return data; - } - - set - { - data = value; - } - - } - /// The array where the data is stored - private float[] data; - - /// Creates a DataBlkFloat with 0 dimensions and no data array - /// (i.e. data is null). - /// - /// - public DataBlkFloat() - { - } - - /// Creates a DataBlkFloat with the specified dimensions and position. The - /// data array is initialized to an array of size w*h. - /// - /// - /// The horizontal coordinate of the upper-left corner of the - /// block - /// - /// - /// The vertical coordinate of the upper-left corner of the - /// block - /// - /// - /// The width of the block (in pixels) - /// - /// - /// The height of the block (in pixels) - /// - /// - public DataBlkFloat(int ulx, int uly, int w, int h) - { - this.ulx = ulx; - this.uly = uly; - this.w = w; - this.h = h; - offset = 0; - scanw = w; - data = new float[w * h]; - } - - /// Copy constructor. Creates a DataBlkFloat which is the copy of the - /// DataBlkFloat given as paramter. - /// - /// - /// the object to be copied. - /// - /// - public DataBlkFloat(DataBlkFloat src) - { - this.ulx = src.ulx; - this.uly = src.uly; - this.w = src.w; - this.h = src.h; - this.offset = 0; - this.scanw = this.w; - this.data = new float[this.w * this.h]; - for (int i = 0; i < this.h; i++) - Array.Copy(src.data, i * src.scanw, this.data, i * this.scanw, this.w); - } - - /// Returns a string of informations about the DataBlkInt. - /// - /// - public override System.String ToString() - { - System.String str = base.ToString(); - if (data != null) - { - str += (",data=" + data.Length + " bytes"); - } - return str; - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/image/DataBlkInt.cs b/CSJ2K/j2k/image/DataBlkInt.cs deleted file mode 100644 index ba74bc4e..00000000 --- a/CSJ2K/j2k/image/DataBlkInt.cs +++ /dev/null @@ -1,208 +0,0 @@ -/* -* CVS Identifier: -* -* $Id: DataBlkInt.java,v 1.7 2001/10/09 12:51:54 grosbois Exp $ -* -* Interface: DataBlkInt -* -* Description: A signed int implementation of DataBlk -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using System; -namespace CSJ2K.j2k.image -{ - - /// This is an implementation of the DataBlk interface for signed 32 - /// bit integral data. - /// - ///

    The methods in this class are declared final, so that they can be - /// inlined by inlining compilers.

    - /// - ///
    - /// - /// - /// - public class DataBlkInt : DataBlk - { - /// Returns the identifier of this data type, TYPE_INT, as defined - /// in DataBlk. - /// - /// - /// The type of data stored. Always DataBlk.TYPE_INT - /// - /// - /// - /// - /// - override public int DataType - { - get - { - return TYPE_INT; - } - - } - //UPGRADE_NOTE: Respective javadoc comments were merged. It should be changed in order to comply with .NET documentation conventions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1199'" - /// Returns the array containing the data, or null if there is no data - /// array. The returned array is a int array. - /// - /// - /// The array of data (a int[]) or null if there is no data. - /// - /// - /// Sets the data array to the specified one. The provided array must be a - /// int array, otherwise a ClassCastException is thrown. The size of the - /// array is not checked for consistency with the block's dimensions. - /// - /// - /// The data array to use. Must be a int array. - /// - /// - override public System.Object Data - { - get - { - return data_array; - } - - set - { - data_array = (int[])value; - } - - } - //UPGRADE_NOTE: Respective javadoc comments were merged. It should be changed in order to comply with .NET documentation conventions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1199'" - /// Returns the array containing the data, or null if there is no data - /// array. - /// - /// - /// The array of data or null if there is no data. - /// - /// - /// Sets the data array to the specified one. The size of the array is not - /// checked for consistency with the block's dimensions. This method is - /// more efficient than setData - /// - /// - /// The data array to use. - /// - /// - virtual public int[] DataInt - { - get - { - return data_array; - } - - set - { - data_array = value; - } - - } - /// The array where the data is stored - public int[] data_array; - - /// Creates a DataBlkInt with 0 dimensions and no data array (i.e. data is - /// null). - /// - /// - public DataBlkInt() - { - } - - /// Creates a DataBlkInt with the specified dimensions and position. The - /// data array is initialized to an array of size w*h. - /// - /// - /// The horizontal coordinate of the upper-left corner of the - /// block - /// - /// - /// The vertical coordinate of the upper-left corner of the - /// block - /// - /// - /// The width of the block (in pixels) - /// - /// - /// The height of the block (in pixels) - /// - /// - public DataBlkInt(int ulx, int uly, int w, int h) - { - this.ulx = ulx; - this.uly = uly; - this.w = w; - this.h = h; - offset = 0; - scanw = w; - data_array = new int[w * h]; - } - - /// Copy constructor. Creates a DataBlkInt which is the copy of the - /// DataBlkInt given as paramter. - /// - /// - /// the object to be copied. - /// - /// - public DataBlkInt(DataBlkInt src) - { - this.ulx = src.ulx; - this.uly = src.uly; - this.w = src.w; - this.h = src.h; - this.offset = 0; - this.scanw = this.w; - this.data_array = new int[this.w * this.h]; - for (int i = 0; i < this.h; i++) - Array.Copy(src.data_array, i * src.scanw, this.data_array, i * this.scanw, this.w); - } - - /// Returns a string of informations about the DataBlkInt. - /// - /// - public override System.String ToString() - { - System.String str = base.ToString(); - if (data_array != null) - { - str += (",data=" + data_array.Length + " bytes"); - } - return str; - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/image/ImgData.cs b/CSJ2K/j2k/image/ImgData.cs deleted file mode 100644 index 99529f68..00000000 --- a/CSJ2K/j2k/image/ImgData.cs +++ /dev/null @@ -1,364 +0,0 @@ -/* -* CVS Identifier: -* -* $Id: ImgData.java,v 1.10 2001/09/14 09:17:46 grosbois Exp $ -* -* Interface: ImgData -* -* Description: The interface for classes that provide image -* data. -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -namespace CSJ2K.j2k.image -{ - - /// This interface defines methods to access image attributes (width, height, - /// number of components, etc.). The image can be tiled or not (i.e. if the - /// image is not tiled then there is only 1 tile). It should be implemented by - /// all classes that provide image data, such as image file readers, color - /// transforms, wavelet transforms, etc. This interface, however, does not - /// define methods to transfer image data (i.e. pixel data), that is defined by - /// other interfaces, such as 'BlkImgDataSrc'. - /// - /// - /// - /// - /// - public interface ImgData - { - /// Returns the overall width of the current tile in pixels. This is the - /// tile's width without accounting for any component subsampling. This is - /// also referred as the reference grid width in the current tile. - /// - /// - /// The total current tile's width in pixels. - /// - /// - int TileWidth - { - get; - - } - /// Returns the overall height of the current tile in pixels. This is the - /// tile's height without accounting for any component subsampling. This is - /// also referred as the reference grid height in the current tile. - /// - /// - /// The total current tile's height in pixels. - /// - /// - int TileHeight - { - get; - - } - /// Returns the nominal tiles width - int NomTileWidth - { - get; - - } - /// Returns the nominal tiles height - int NomTileHeight - { - get; - - } - /// Returns the overall width of the image in pixels. This is the image's - /// width without accounting for any component subsampling or tiling. - /// - /// - /// The total image's width in pixels. - /// - /// - int ImgWidth - { - get; - - } - /// Returns the overall height of the image in pixels. This is the image's - /// height without accounting for any component subsampling or tiling. - /// - /// - /// The total image's height in pixels. - /// - /// - int ImgHeight - { - get; - - } - /// Returns the number of components in the image. - /// - /// - /// The number of components in the image. - /// - /// - int NumComps - { - get; - - } - /// Returns the index of the current tile, relative to a standard scan-line - /// order. - /// - /// - /// The current tile's index (starts at 0). - /// - /// - int TileIdx - { - get; - - } - /// Returns the horizontal tile partition offset in the reference grid - int TilePartULX - { - get; - - } - /// Returns the vertical tile partition offset in the reference grid - int TilePartULY - { - get; - - } - /// Returns the horizontal coordinate of the image origin, the top-left - /// corner, in the canvas system, on the reference grid. - /// - /// - /// The horizontal coordinate of the image origin in the canvas - /// system, on the reference grid. - /// - /// - int ImgULX - { - get; - - } - /// Returns the vertical coordinate of the image origin, the top-left - /// corner, in the canvas system, on the reference grid. - /// - /// - /// The vertical coordinate of the image origin in the canvas - /// system, on the reference grid. - /// - /// - int ImgULY - { - get; - - } - - /// Returns the component subsampling factor in the horizontal direction, - /// for the specified component. This is, approximately, the ratio of - /// dimensions between the reference grid and the component itself, see the - /// 'ImgData' interface desription for details. - /// - /// - /// The index of the component (between 0 and N-1) - /// - /// - /// The horizontal subsampling factor of component 'c' - /// - /// - /// - /// - /// - int getCompSubsX(int c); - - /// Returns the component subsampling factor in the vertical direction, for - /// the specified component. This is, approximately, the ratio of - /// dimensions between the reference grid and the component itself, see the - /// 'ImgData' interface desription for details. - /// - /// - /// The index of the component (between 0 and N-1) - /// - /// - /// The vertical subsampling factor of component 'c' - /// - /// - /// - /// - /// - int getCompSubsY(int c); - - /// Returns the width in pixels of the specified tile-component - /// - /// - /// Tile index - /// - /// - /// The index of the component, from 0 to N-1. - /// - /// - /// The width in pixels of component c in tilet. - /// - /// - int getTileCompWidth(int t, int c); - - /// Returns the height in pixels of the specified tile-component. - /// - /// - /// The tile index. - /// - /// - /// The index of the component, from 0 to N-1. - /// - /// - /// The height in pixels of component c in tile - /// t. - /// - /// - int getTileCompHeight(int t, int c); - - /// Returns the width in pixels of the specified component in the overall - /// image. - /// - /// - /// The index of the component, from 0 to N-1. - /// - /// - /// The width in pixels of component c in the overall - /// image. - /// - /// - int getCompImgWidth(int c); - - /// Returns the height in pixels of the specified component in the overall - /// image. - /// - /// - /// The index of the component, from 0 to N-1. - /// - /// - /// The height in pixels of component n in the overall - /// image. - /// - /// - int getCompImgHeight(int c); - - /// Returns the number of bits, referred to as the "range bits", - /// corresponding to the nominal range of the image data in the specified - /// component. If this number is n then for unsigned data the - /// nominal range is between 0 and 2^b-1, and for signed data it is between - /// -2^(b-1) and 2^(b-1)-1. In the case of transformed data which is not in - /// the image domain (e.g., wavelet coefficients), this method returns the - /// "range bits" of the image data that generated the coefficients. - /// - /// - /// The index of the component. - /// - /// - /// The number of bits corresponding to the nominal range of the - /// image data (in the image domain). - /// - /// - int getNomRangeBits(int c); - - /// Changes the current tile, given the new indices. An - /// IllegalArgumentException is thrown if the coordinates do not correspond - /// to a valid tile. - /// - /// - /// The horizontal index of the tile. - /// - /// - /// The vertical index of the new tile. - /// - /// - void setTile(int x, int y); - - /// Advances to the next tile, in standard scan-line order (by rows then - /// columns). An NoNextElementException is thrown if the current tile is - /// the last one (i.e. there is no next tile). - /// - /// - void nextTile(); - - /// Returns the indixes of the current tile. These are the horizontal and - /// vertical indexes of the current tile. - /// - /// - /// If not null this object is used to return the information. If - /// null a new one is created and returned. - /// - /// - /// The current tile's indices (vertical and horizontal indexes). - /// - /// - Coord getTile(Coord co); - - /// Returns the horizontal coordinate of the upper-left corner of the - /// specified component in the current tile. - /// - /// - /// The index of the component. - /// - /// - int getCompULX(int c); - - /// Returns the vertical coordinate of the upper-left corner of the - /// specified component in the current tile. - /// - /// - /// The index of the component. - /// - /// - int getCompULY(int c); - - /// Returns the number of tiles in the horizontal and vertical directions. - /// - /// - /// If not null this object is used to return the information. If - /// null a new one is created and returned. - /// - /// - /// The number of tiles in the horizontal (Coord.x) and vertical - /// (Coord.y) directions. - /// - /// - Coord getNumTiles(Coord co); - - /// Returns the total number of tiles in the image. - /// - /// - /// The total number of tiles in the image. - /// - /// - int getNumTiles(); - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/image/ImgDataAdapter.cs b/CSJ2K/j2k/image/ImgDataAdapter.cs deleted file mode 100644 index 32e0500f..00000000 --- a/CSJ2K/j2k/image/ImgDataAdapter.cs +++ /dev/null @@ -1,513 +0,0 @@ -/* -* CVS identifier: -* -* $Id: ImgDataAdapter.java,v 1.8 2001/09/14 09:17:23 grosbois Exp $ -* -* Class: ImgDataAdapter -* -* Description: A default implementation of the ImgData -* interface that has an ImgData source and just -* returns the values of the source. -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -namespace CSJ2K.j2k.image -{ - - /// This class provides a default implementation of the methods in the - /// 'ImgData' interface. The default implementation is just to return the value - /// of the source, where the source is another 'ImgData' object. - /// - ///

    This abstract class can be used to facilitate the development of other - /// classes that implement 'ImgData'. For example a YCbCr color transform can - /// inherit from this class and all the trivial methods do not have to be - /// re-implemented.

    - /// - ///

    If the default implementation of a method provided in this class does - /// not suit a particular implementation of the 'ImgData' interface, the method - /// can be overridden to implement the proper behavior.

    - /// - ///
    - /// - /// - /// - public abstract class ImgDataAdapter : ImgData - { - /// Returns the overall width of the current tile in pixels. This is the - /// tile's width without accounting for any component subsampling. This is - /// also referred as the reference grid width in the current tile. - /// - ///

    This default implementation returns the value of the source.

    - /// - ///
    - /// The total current tile's width in pixels. - /// - /// - virtual public int TileWidth - { - get - { - return imgdatasrc.TileWidth; - } - - } - /// Returns the overall height of the current tile in pixels. This is the - /// tile's height without accounting for any component subsampling. This is - /// also referred as the reference grid height in the current tile. - /// - ///

    This default implementation returns the value of the source.

    - /// - ///
    - /// The total current tile's height in pixels. - /// - /// - virtual public int TileHeight - { - get - { - return imgdatasrc.TileHeight; - } - - } - /// Returns the nominal tiles width - virtual public int NomTileWidth - { - get - { - return imgdatasrc.NomTileWidth; - } - - } - /// Returns the nominal tiles height - virtual public int NomTileHeight - { - get - { - return imgdatasrc.NomTileHeight; - } - - } - /// Returns the overall width of the image in pixels. This is the image's - /// width without accounting for any component subsampling or tiling. - /// - ///

    This default implementation returns the value of the source.

    - /// - ///
    - /// The total image's width in pixels. - /// - /// - virtual public int ImgWidth - { - get - { - return imgdatasrc.ImgWidth; - } - - } - /// Returns the overall height of the image in pixels. This is the image's - /// height without accounting for any component subsampling or tiling. - /// - ///

    This default implementation returns the value of the source.

    - /// - ///
    - /// The total image's height in pixels. - /// - /// - virtual public int ImgHeight - { - get - { - return imgdatasrc.ImgHeight; - } - - } - /// Returns the number of components in the image. - /// - ///

    This default implementation returns the value of the source.

    - /// - ///
    - /// The number of components in the image. - /// - /// - virtual public int NumComps - { - get - { - return imgdatasrc.NumComps; - } - - } - /// Returns the index of the current tile, relative to a standard scan-line - /// order. - /// - ///

    This default implementation returns the value of the source.

    - /// - ///
    - /// The current tile's index (starts at 0). - /// - /// - virtual public int TileIdx - { - get - { - return imgdatasrc.TileIdx; - } - - } - /// Returns the horizontal tile partition offset in the reference grid - virtual public int TilePartULX - { - get - { - return imgdatasrc.TilePartULX; - } - - } - /// Returns the vertical tile offset in the reference grid - virtual public int TilePartULY - { - get - { - return imgdatasrc.TilePartULY; - } - - } - /// Returns the horizontal coordinate of the image origin, the top-left - /// corner, in the canvas system, on the reference grid. - /// - ///

    This default implementation returns the value of the source.

    - /// - ///
    - /// The horizontal coordinate of the image origin in the canvas - /// system, on the reference grid. - /// - /// - virtual public int ImgULX - { - get - { - return imgdatasrc.ImgULX; - } - - } - /// Returns the vertical coordinate of the image origin, the top-left - /// corner, in the canvas system, on the reference grid. - /// - ///

    This default implementation returns the value of the source.

    - /// - ///
    - /// The vertical coordinate of the image origin in the canvas - /// system, on the reference grid. - /// - /// - virtual public int ImgULY - { - get - { - return imgdatasrc.ImgULY; - } - - } - - /// Index of the current tile - protected internal int tIdx = 0; - - /// The ImgData source - protected internal ImgData imgdatasrc; - - /// Instantiates the ImgDataAdapter object specifying the ImgData source. - /// - /// - /// From where to obtain all the ImgData values. - /// - /// - protected internal ImgDataAdapter(ImgData src) - { - imgdatasrc = src; - } - - /// Returns the component subsampling factor in the horizontal direction, - /// for the specified component. This is, approximately, the ratio of - /// dimensions between the reference grid and the component itself, see the - /// 'ImgData' interface desription for details. - /// - ///

    This default implementation returns the value of the source.

    - /// - ///
    - /// The index of the component (between 0 and N-1) - /// - /// - /// The horizontal subsampling factor of component 'c' - /// - /// - /// - /// - /// - public virtual int getCompSubsX(int c) - { - return imgdatasrc.getCompSubsX(c); - } - - /// Returns the component subsampling factor in the vertical direction, for - /// the specified component. This is, approximately, the ratio of - /// dimensions between the reference grid and the component itself, see the - /// 'ImgData' interface desription for details. - /// - ///

    This default implementation returns the value of the source.

    - /// - ///
    - /// The index of the component (between 0 and N-1) - /// - /// - /// The vertical subsampling factor of component 'c' - /// - /// - /// - /// - /// - public virtual int getCompSubsY(int c) - { - return imgdatasrc.getCompSubsY(c); - } - - /// Returns the width in pixels of the specified tile-component - /// tile. - /// - ///

    This default implementation returns the value of the source.

    - /// - ///
    - /// Tile index - /// - /// - /// The index of the component, from 0 to N-1. - /// - /// - /// The width in pixels of component c in tilet. - /// - /// - public virtual int getTileCompWidth(int t, int c) - { - return imgdatasrc.getTileCompWidth(t, c); - } - - /// Returns the height in pixels of the specified tile-component. - /// - ///

    This default implementation returns the value of the source.

    - /// - ///
    - /// The tile index. - /// - /// - /// The index of the component, from 0 to N-1. - /// - /// - /// The height in pixels of component c in tile - /// t. - /// - /// - public virtual int getTileCompHeight(int t, int c) - { - return imgdatasrc.getTileCompHeight(t, c); - } - - /// Returns the width in pixels of the specified component in the overall - /// image. - /// - ///

    This default implementation returns the value of the source.

    - /// - ///
    - /// The index of the component, from 0 to N-1. - /// - /// - /// The width in pixels of component c in the overall - /// image. - /// - /// - public virtual int getCompImgWidth(int c) - { - return imgdatasrc.getCompImgWidth(c); - } - - /// Returns the height in pixels of the specified component in the overall - /// image. - /// - ///

    This default implementation returns the value of the source.

    - /// - ///
    - /// The index of the component, from 0 to N-1. - /// - /// - /// The height in pixels of component c in the overall - /// image. - /// - /// - public virtual int getCompImgHeight(int c) - { - return imgdatasrc.getCompImgHeight(c); - } - - /// Returns the number of bits, referred to as the "range bits", - /// corresponding to the nominal range of the image data in the specified - /// component. If this number is n then for unsigned data the - /// nominal range is between 0 and 2^b-1, and for signed data it is between - /// -2^(b-1) and 2^(b-1)-1. In the case of transformed data which is not in - /// the image domain (e.g., wavelet coefficients), this method returns the - /// "range bits" of the image data that generated the coefficients. - /// - ///

    This default implementation returns the value of the source.

    - /// - ///
    - /// The index of the component. - /// - /// - /// The number of bits corresponding to the nominal range of the - /// image data (in the image domain). - /// - /// - public virtual int getNomRangeBits(int c) - { - return imgdatasrc.getNomRangeBits(c); - } - - /// Changes the current tile, given the new indexes. An - /// IllegalArgumentException is thrown if the indexes do not correspond to - /// a valid tile. - /// - ///

    This default implementation just changes the tile in the source.

    - /// - ///
    - /// The horizontal index of the tile. - /// - /// - /// The vertical index of the new tile. - /// - /// - public virtual void setTile(int x, int y) - { - imgdatasrc.setTile(x, y); - tIdx = TileIdx; - } - - /// Advances to the next tile, in standard scan-line order (by rows then - /// columns). An NoNextElementException is thrown if the current tile is - /// the last one (i.e. there is no next tile). - /// - ///

    This default implementation just advances to the next tile in the - /// source.

    - /// - ///
    - public virtual void nextTile() - { - imgdatasrc.nextTile(); - tIdx = TileIdx; - } - - /// Returns the indexes of the current tile. These are the horizontal and - /// vertical indexes of the current tile. - /// - ///

    This default implementation returns the value of the source.

    - /// - ///
    - /// If not null this object is used to return the information. If - /// null a new one is created and returned. - /// - /// - /// The current tile's indexes (vertical and horizontal indexes). - /// - /// - public virtual Coord getTile(Coord co) - { - return imgdatasrc.getTile(co); - } - - /// Returns the horizontal coordinate of the upper-left corner of the - /// specified component in the current tile. - /// - ///

    This default implementation returns the value of the source.

    - /// - ///
    - /// The component index. - /// - /// - public virtual int getCompULX(int c) - { - return imgdatasrc.getCompULX(c); - } - - /// Returns the vertical coordinate of the upper-left corner of the - /// specified component in the current tile. - /// - ///

    This default implementation returns the value of the source.

    - /// - ///
    - /// The component index. - /// - /// - public virtual int getCompULY(int c) - { - return imgdatasrc.getCompULY(c); - } - - /// Returns the number of tiles in the horizontal and vertical directions. - /// - ///

    This default implementation returns the value of the source.

    - /// - ///
    - /// If not null this object is used to return the information. If - /// null a new one is created and returned. - /// - /// - /// The number of tiles in the horizontal (Coord.x) and vertical - /// (Coord.y) directions. - /// - /// - public virtual Coord getNumTiles(Coord co) - { - return imgdatasrc.getNumTiles(co); - } - - /// Returns the total number of tiles in the image. - /// - ///

    This default implementation returns the value of the source.

    - /// - ///
    - /// The total number of tiles in the image. - /// - /// - public virtual int getNumTiles() - { - return imgdatasrc.getNumTiles(); - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/image/ImgDataConverter.cs b/CSJ2K/j2k/image/ImgDataConverter.cs deleted file mode 100644 index 72683b4d..00000000 --- a/CSJ2K/j2k/image/ImgDataConverter.cs +++ /dev/null @@ -1,420 +0,0 @@ -/* -* CVS Identifier: -* -* $Id: ImgDataConverter.java,v 1.13 2001/02/27 19:16:03 grosbois Exp $ -* -* Interface: ImgDataConverter -* -* Description: The abstract class for classes that provide -* Image Data Convertres (int -> float, float->int). -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -namespace CSJ2K.j2k.image -{ - - /// This class is responsible of all data type conversions. It should be used, - /// at encoder side, between Tiler and ForwardWT modules and, at decoder side, - /// between InverseWT/CompDemixer and ImgWriter modules. The conversion is - /// realized when a block of data is requested: if source and destination data - /// type are the same one, it does nothing, else appropriate cast is done. All - /// the methods of the 'ImgData' interface are implemented by the - /// 'ImgDataAdapter' class that is the superclass of this one, so they don't - /// need to be reimplemented by subclasses. - /// - /// - public class ImgDataConverter : ImgDataAdapter, BlkImgDataSrc - { - - /// The block used to request data from the source in the case that a - /// conversion seems necessary. It can be either int or float at - /// initialization time. It will be checked (and corrected if necessary) by - /// the source whenever necessary - /// - private DataBlk srcBlk = new DataBlkInt(); - - /// The source of image data - private BlkImgDataSrc src; - - /// The number of fraction bits in the casted ints - private int fp; - - /// Constructs a new ImgDataConverter object that operates on the specified - /// source of image data. - /// - /// - /// The source from where to get the data to be transformed - /// - /// - /// The number of fraction bits in the casted ints - /// - /// - /// - /// - /// - public ImgDataConverter(BlkImgDataSrc imgSrc, int fp) : base(imgSrc) - { - src = imgSrc; - this.fp = fp; - } - - /// Constructs a new ImgDataConverter object that operates on the specified - /// source of image data. - /// - /// - /// The source from where to get the data to be transformed - /// - /// - /// - /// - /// - public ImgDataConverter(BlkImgDataSrc imgSrc) : base(imgSrc) - { - src = imgSrc; - fp = 0; - } - - /// Returns the position of the fixed point in the specified - /// component. This is the position of the least significant integral - /// (i.e. non-fractional) bit, which is equivalent to the number of - /// fractional bits. For instance, for fixed-point values with 2 fractional - /// bits, 2 is returned. For floating-point data this value does not apply - /// and 0 should be returned. Position 0 is the position of the least - /// significant bit in the data. - /// - /// - /// The index of the component. - /// - /// - /// The position of the fixed-point, which is the same as the - /// number of fractional bits. - /// - /// - public virtual int getFixedPoint(int c) - { - return fp; - } - - /// Returns, in the blk argument, a block of image data containing the - /// specifed rectangular area, in the specified component, using the - /// 'transfer type' specified in the block given as argument. The data is - /// returned, as a copy of the internal data, therefore the returned data - /// can be modified "in place". - /// - ///

    The rectangular area to return is specified by the 'ulx', 'uly', 'w' - /// and 'h' members of the 'blk' argument, relative to the current - /// tile. These members are not modified by this method. The 'offset' of - /// the returned data is 0, and the 'scanw' is the same as the block's - /// width. See the 'DataBlk' class. - /// - ///

    This method, in general, is less efficient than the - /// 'getInternCompData()' method since, in general, it copies the - /// data. However if the array of returned data is to be modified by the - /// caller then this method is preferable. - /// - ///

    If the data array in 'blk' is 'null', then a new one is created. If - /// the data array is not 'null' then it is reused, and it must be large - /// enough to contain the block's data. Otherwise an 'ArrayStoreException' - /// or an 'IndexOutOfBoundsException' is thrown by the Java system. - /// - ///

    The returned data may have its 'progressive' attribute set. In this - /// case the returned data is only an approximation of the "final" data. - /// - ///

    - /// Its coordinates and dimensions specify the area to return, - /// relative to the current tile. If it contains a non-null data array, - /// then it must be large enough. If it contains a null data array a new - /// one is created. Some fields in this object are modified to return the - /// data. - /// - /// - /// The index of the component from which to get the data. - /// - /// - /// - /// - /// - public virtual DataBlk getCompData(DataBlk blk, int c) - { - return getData(blk, c, false); - } - - /// Returns, in the blk argument, a block of image data containing the - /// specifed rectangular area, in the specified component, using the - /// 'transfer type' defined in the block given as argument. The data is - /// returned, as a reference to the internal data, if any, instead of as a - /// copy, therefore the returned data should not be modified. - /// - ///

    The rectangular area to return is specified by the 'ulx', 'uly', 'w' - /// and 'h' members of the 'blk' argument, relative to the current - /// tile. These members are not modified by this method. The 'offset' and - /// 'scanw' of the returned data can be arbitrary. See the 'DataBlk' class. - /// - ///

    If source data and expected data (blk) are using the same type, - /// block returned without any modification. If not appropriate cast is - /// used. - /// - ///

    This method, in general, is more efficient than the 'getCompData()' - /// method since it may not copy the data. However if the array of returned - /// data is to be modified by the caller then the other method is probably - /// preferable. - /// - ///

    If the data array in blk is null, then a new one - /// is created if necessary. The implementation of this interface may - /// choose to return the same array or a new one, depending on what is more - /// efficient. Therefore, the data array in blk prior to the - /// method call should not be considered to contain the returned data, a - /// new array may have been created. Instead, get the array from - /// blk after the method has returned. - /// - ///

    The returned data may have its 'progressive' attribute set. In this - /// case the returned data is only an approximation of the "final" data. - /// - ///

    - /// Its coordinates and dimensions specify the area to return, - /// relative to the current tile. Some fields in this object are modified - /// to return the data. - /// - /// - /// The index of the component from which to get the data. - /// - /// - /// The requested DataBlk - /// - /// - /// - /// - /// - public DataBlk getInternCompData(DataBlk blk, int c) - { - return getData(blk, c, true); - } - - /// Implements the 'getInternCompData()' and the 'getCompData()' - /// methods. The 'intern' flag signals which of the two methods should run - /// as. - /// - /// - /// The data block to get. - /// - /// - /// The index of the component from which to get the data. - /// - /// - /// If true behave as 'getInternCompData(). Otherwise behave - /// as 'getCompData()' - /// - /// - /// The requested data block - /// - /// - /// - /// - /// - /// - /// - /// - private DataBlk getData(DataBlk blk, int c, bool intern) - { - DataBlk reqBlk; // Reference to block used in request to source - - // Keep request data type - int otype = blk.DataType; - - if (otype == srcBlk.DataType) - { - // Probably requested type is same as source type - reqBlk = blk; - } - else - { - // Probably requested type is not the same as source type - reqBlk = srcBlk; - // We need to copy requested coordinates and size - reqBlk.ulx = blk.ulx; - reqBlk.uly = blk.uly; - reqBlk.w = blk.w; - reqBlk.h = blk.h; - } - - // Get source data block - if (intern) - { - // We can use the intern variant - srcBlk = src.getInternCompData(reqBlk, c); - } - else - { - // Do not use the intern variant. Note that this is not optimal - // since if we are going to convert below then we could have used - // the intern variant. But there is currently no way to know if we - // will need to do conversion or not before getting the data. - srcBlk = src.getCompData(reqBlk, c); - } - - // Check if casting is needed - if (srcBlk.DataType == otype) - { - return srcBlk; - } - - int i; - int k, kSrc, kmin; - float mult; - int w = srcBlk.w; - int h = srcBlk.h; - - switch (otype) - { - - case DataBlk.TYPE_FLOAT: // Cast INT -> FLOAT - - float[] farr; - int[] srcIArr; - - // Get data array from resulting blk - farr = (float[])blk.Data; - if (farr == null || farr.Length < w * h) - { - farr = new float[w * h]; - blk.Data = farr; - } - - blk.scanw = srcBlk.w; - blk.offset = 0; - blk.progressive = srcBlk.progressive; - srcIArr = (int[])srcBlk.Data; - - // Cast data from source to blk - fp = src.getFixedPoint(c); - if (fp != 0) - { - mult = 1.0f / (1 << fp); - for (i = h - 1, k = w * h - 1, kSrc = srcBlk.offset + (h - 1) * srcBlk.scanw + w - 1; i >= 0; i--) - { - for (kmin = k - w; k > kmin; k--, kSrc--) - { - farr[k] = ((srcIArr[kSrc] * mult)); - } - // Jump to geggining of next line in source - kSrc -= (srcBlk.scanw - w); - } - } - else - { - for (i = h - 1, k = w * h - 1, kSrc = srcBlk.offset + (h - 1) * srcBlk.scanw + w - 1; i >= 0; i--) - { - for (kmin = k - w; k > kmin; k--, kSrc--) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - farr[k] = ((float)(srcIArr[kSrc])); - } - // Jump to geggining of next line in source - kSrc -= (srcBlk.scanw - w); - } - } - break; // End of cast INT-> FLOAT - - - case DataBlk.TYPE_INT: // cast FLOAT -> INT - int[] iarr; - float[] srcFArr; - - // Get data array from resulting blk - iarr = (int[])blk.Data; - if (iarr == null || iarr.Length < w * h) - { - iarr = new int[w * h]; - blk.Data = iarr; - } - blk.scanw = srcBlk.w; - blk.offset = 0; - blk.progressive = srcBlk.progressive; - srcFArr = (float[])srcBlk.Data; - - // Cast data from source to blk - if (fp != 0) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - mult = (float)(1 << fp); - for (i = h - 1, k = w * h - 1, kSrc = srcBlk.offset + (h - 1) * srcBlk.scanw + w - 1; i >= 0; i--) - { - for (kmin = k - w; k > kmin; k--, kSrc--) - { - if (srcFArr[kSrc] > 0.0f) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - iarr[k] = (int)(srcFArr[kSrc] * mult + 0.5f); - } - else - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - iarr[k] = (int)(srcFArr[kSrc] * mult - 0.5f); - } - } - // Jump to geggining of next line in source - kSrc -= (srcBlk.scanw - w); - } - } - else - { - for (i = h - 1, k = w * h - 1, kSrc = srcBlk.offset + (h - 1) * srcBlk.scanw + w - 1; i >= 0; i--) - { - for (kmin = k - w; k > kmin; k--, kSrc--) - { - if (srcFArr[kSrc] > 0.0f) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - iarr[k] = (int)(srcFArr[kSrc] + 0.5f); - } - else - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - iarr[k] = (int)(srcFArr[kSrc] - 0.5f); - } - } - // Jump to geggining of next line in source - kSrc -= (srcBlk.scanw - w); - } - } - break; // End cast FLOAT -> INT - - default: - throw new System.ArgumentException("Only integer and float data " + "are " + "supported by JJ2000"); - - } - return blk; - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/image/ImgDataJoiner.cs b/CSJ2K/j2k/image/ImgDataJoiner.cs deleted file mode 100644 index 2b3ff780..00000000 --- a/CSJ2K/j2k/image/ImgDataJoiner.cs +++ /dev/null @@ -1,724 +0,0 @@ -/* -* CVS identifier: -* -* $Id: ImgDataJoiner.java,v 1.12 2001/09/14 09:17:00 grosbois Exp $ -* -* Class: ImgDataJoiner -* -* Description: Get ImgData from different sources -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -namespace CSJ2K.j2k.image -{ - - /// This class implements the ImgData interface and allows to obtain data from - /// different sources. Here, one source is represented by an ImgData and a - /// component index. The typical use of this class is when the encoder needs - /// different components (Red, Green, Blue, alpha, ...) from different input - /// files (i.e. from different ImgReader objects). - /// - ///

    All input ImgData must not be tiled (i.e. must have only 1 tile) and the - /// image origin must be the canvas origin. The different inputs can have - /// different dimensions though (this will lead to different subsampling - /// factors for each component).

    - /// - ///

    The input ImgData and component index list must be defined when - /// constructing this class and can not be modified later.

    - /// - ///
    - /// - /// - /// - /// - /// - public class ImgDataJoiner : BlkImgDataSrc - { - /// Returns the overall width of the current tile in pixels. This is the - /// tile's width without accounting for any component subsampling. - /// - /// - /// The total current tile's width in pixels. - /// - /// - virtual public int TileWidth - { - get - { - return w; - } - - } - /// Returns the overall height of the current tile in pixels. This is the - /// tile's height without accounting for any component subsampling. - /// - /// - /// The total current tile's height in pixels. - /// - /// - virtual public int TileHeight - { - get - { - return h; - } - - } - /// Returns the nominal tiles width - virtual public int NomTileWidth - { - get - { - return w; - } - - } - /// Returns the nominal tiles height - virtual public int NomTileHeight - { - get - { - return h; - } - - } - /// Returns the overall width of the image in pixels. This is the image's - /// width without accounting for any component subsampling or tiling. - /// - /// - /// The total image's width in pixels. - /// - /// - virtual public int ImgWidth - { - get - { - return w; - } - - } - /// Returns the overall height of the image in pixels. This is the image's - /// height without accounting for any component subsampling or tiling. - /// - /// - /// The total image's height in pixels. - /// - /// - virtual public int ImgHeight - { - get - { - return h; - } - - } - /// Returns the number of components in the image. - /// - /// - /// The number of components in the image. - /// - /// - virtual public int NumComps - { - get - { - return nc; - } - - } - /// Returns the index of the current tile, relative to a standard scan-line - /// order. This default implementations assumes no tiling, so 0 is always - /// returned. - /// - /// - /// The current tile's index (starts at 0). - /// - /// - virtual public int TileIdx - { - get - { - return 0; - } - - } - /// Returns the horizontal tile partition offset in the reference grid - virtual public int TilePartULX - { - get - { - return 0; - } - - } - /// Returns the vertical tile partition offset in the reference grid - virtual public int TilePartULY - { - get - { - return 0; - } - - } - /// Returns the horizontal coordinate of the image origin, the top-left - /// corner, in the canvas system, on the reference grid. - /// - /// - /// The horizontal coordinate of the image origin in the canvas - /// system, on the reference grid. - /// - /// - virtual public int ImgULX - { - get - { - return 0; - } - - } - /// Returns the vertical coordinate of the image origin, the top-left - /// corner, in the canvas system, on the reference grid. - /// - /// - /// The vertical coordinate of the image origin in the canvas - /// system, on the reference grid. - /// - /// - virtual public int ImgULY - { - get - { - return 0; - } - - } - - /// The width of the image - private int w; - - /// The height of the image - private int h; - - /// The number of components in the image - private int nc; - - /// The list of input ImgData - private BlkImgDataSrc[] imageData; - - /// The component index associated with each ImgData - private int[] compIdx; - - /// The subsampling factor along the horizontal direction, for every - /// component - /// - private int[] subsX; - - /// The subsampling factor along the vertical direction, for every - /// component - /// - private int[] subsY; - - /// Class constructor. Each input BlkImgDataSrc and its component index - /// must appear in the order wanted for the output components.
    - /// - /// Example: Reading R,G,B components from 3 PGM files.
    - /// - /// BlkImgDataSrc[] idList =
    - /// {
    - /// new ImgReaderPGM(new BEBufferedRandomAccessFile("R.pgm", "r")),
    - /// new ImgReaderPGM(new BEBufferedRandomAccessFile("G.pgm", "r")),
    - /// new ImgReaderPGM(new BEBufferedRandomAccessFile("B.pgm", "r"))
    - /// };
    - /// int[] compIdx = {0,0,0};
    - /// ImgDataJoiner idj = new ImgDataJoiner(idList, compIdx); - ///
    - /// - ///

    Of course, the 2 arrays must have the same length (This length is - /// the number of output components). The image width and height are - /// definded to be the maximum values of all the input ImgData. - /// - ///

    - /// The list of input BlkImgDataSrc in an array. - /// - /// - /// The component index associated with each ImgData. - /// - /// - public ImgDataJoiner(BlkImgDataSrc[] imD, int[] cIdx) - { - int i; - int maxW, maxH; - - // Initializes - imageData = imD; - compIdx = cIdx; - if (imageData.Length != compIdx.Length) - throw new System.ArgumentException("imD and cIdx must have the" + " same length"); - - nc = imD.Length; - - subsX = new int[nc]; - subsY = new int[nc]; - - // Check that no source is tiled and that the image origin is at the - // canvas origin. - for (i = 0; i < nc; i++) - { - if (imD[i].getNumTiles() != 1 || imD[i].getCompULX(cIdx[i]) != 0 || imD[i].getCompULY(cIdx[i]) != 0) - { - throw new System.ArgumentException("All input components must, " + "not use tiles and must " + "have " + "the origin at the canvas " + "origin"); - } - } - - // Guess component subsampling factors based on the fact that the - // ceil() operation relates the reference grid size to the component's - // size, through the subsampling factor. - - // Mhhh, difficult problem. For now just assume that one of the - // subsampling factors is always 1 and that the component width is - // always larger than its subsampling factor, which covers most of the - // cases. We check the correctness of the solution once found to chek - // out hypothesis. - - // Look for max width and height. - maxW = 0; - maxH = 0; - for (i = 0; i < nc; i++) - { - if (imD[i].getCompImgWidth(cIdx[i]) > maxW) - maxW = imD[i].getCompImgWidth(cIdx[i]); - if (imD[i].getCompImgHeight(cIdx[i]) > maxH) - maxH = imD[i].getCompImgHeight(cIdx[i]); - } - // Set the image width and height as the maximum ones - w = maxW; - h = maxH; - - // Now get the sumsampling factors and check the subsampling factors, - // just to see if above hypothesis were correct. - for (i = 0; i < nc; i++) - { - // This calculation only holds if the subsampling factor is less - // than the component width - subsX[i] = (maxW + imD[i].getCompImgWidth(cIdx[i]) - 1) / imD[i].getCompImgWidth(cIdx[i]); - subsY[i] = (maxH + imD[i].getCompImgHeight(cIdx[i]) - 1) / imD[i].getCompImgHeight(cIdx[i]); - if ((maxW + subsX[i] - 1) / subsX[i] != imD[i].getCompImgWidth(cIdx[i]) || (maxH + subsY[i] - 1) / subsY[i] != imD[i].getCompImgHeight(cIdx[i])) - { - throw new System.ApplicationException("Can not compute component subsampling " + "factors: strange subsampling."); - } - } - } - - /// Returns the component subsampling factor in the horizontal direction, - /// for the specified component. This is, approximately, the ratio of - /// dimensions between the reference grid and the component itself, see the - /// 'ImgData' interface desription for details. - /// - /// - /// The index of the component (between 0 and N-1) - /// - /// - /// The horizontal subsampling factor of component 'c' - /// - /// - /// - /// - /// - public virtual int getCompSubsX(int c) - { - return subsX[c]; - } - - /// Returns the component subsampling factor in the vertical direction, for - /// the specified component. This is, approximately, the ratio of - /// dimensions between the reference grid and the component itself, see the - /// 'ImgData' interface desription for details. - /// - /// - /// The index of the component (between 0 and N-1) - /// - /// - /// The vertical subsampling factor of component 'c' - /// - /// - /// - /// - /// - public virtual int getCompSubsY(int c) - { - return subsY[c]; - } - - - /// Returns the width in pixels of the specified tile-component - /// - /// - /// Tile index - /// - /// - /// The index of the component, from 0 to N-1. - /// - /// - /// The width in pixels of component c in tilet. - /// - /// - public virtual int getTileCompWidth(int t, int c) - { - return imageData[c].getTileCompWidth(t, compIdx[c]); - } - - /// Returns the height in pixels of the specified tile-component. - /// - /// - /// The tile index. - /// - /// - /// The index of the component, from 0 to N-1. - /// - /// - /// The height in pixels of component c in the current - /// tile. - /// - /// - public virtual int getTileCompHeight(int t, int c) - { - return imageData[c].getTileCompHeight(t, compIdx[c]); - } - - /// Returns the width in pixels of the specified component in the overall - /// image. - /// - /// - /// The index of the component, from 0 to N-1. - /// - /// - /// The width in pixels of component c in the overall - /// image. - /// - /// - public virtual int getCompImgWidth(int c) - { - return imageData[c].getCompImgWidth(compIdx[c]); - } - - /// Returns the height in pixels of the specified component in the - /// overall image. - /// - /// - /// The index of the component, from 0 to N-1. - /// - /// - /// The height in pixels of component n in the overall - /// image. - /// - /// - /// - /// - public virtual int getCompImgHeight(int n) - { - return imageData[n].getCompImgHeight(compIdx[n]); - } - - /// Returns the number of bits, referred to as the "range bits", - /// corresponding to the nominal range of the data in the specified - /// component. If this number is b then for unsigned data the - /// nominal range is between 0 and 2^b-1, and for signed data it is between - /// -2^(b-1) and 2^(b-1)-1. For floating point data this value is not - /// applicable. - /// - /// - /// The index of the component. - /// - /// - /// The number of bits corresponding to the nominal range of the - /// data. Fro floating-point data this value is not applicable and the - /// return value is undefined. - /// - /// - public virtual int getNomRangeBits(int c) - { - return imageData[c].getNomRangeBits(compIdx[c]); - } - - /// Returns the position of the fixed point in the specified - /// component. This is the position of the least significant integral - /// (i.e. non-fractional) bit, which is equivalent to the number of - /// fractional bits. For instance, for fixed-point values with 2 fractional - /// bits, 2 is returned. For floating-point data this value does not apply - /// and 0 should be returned. Position 0 is the position of the least - /// significant bit in the data. - /// - /// - /// The index of the component. - /// - /// - /// The position of the fixed-point, which is the same as the - /// number of fractional bits. For floating-point data 0 is returned. - /// - /// - public virtual int getFixedPoint(int c) - { - return imageData[c].getFixedPoint(compIdx[c]); - } - - /// Returns, in the blk argument, a block of image data containing the - /// specifed rectangular area, in the specified component. The data is - /// returned, as a reference to the internal data, if any, instead of as a - /// copy, therefore the returned data should not be modified. - /// - ///

    The rectangular area to return is specified by the 'ulx', 'uly', 'w' - /// and 'h' members of the 'blk' argument, relative to the current - /// tile. These members are not modified by this method. The 'offset' and - /// 'scanw' of the returned data can be arbitrary. See the 'DataBlk' class. - /// - ///

    This method, in general, is more efficient than the 'getCompData()' - /// method since it may not copy the data. However if the array of returned - /// data is to be modified by the caller then the other method is probably - /// preferable. - /// - ///

    If the data array in blk is null, then a new one - /// is created if necessary. The implementation of this interface may - /// choose to return the same array or a new one, depending on what is more - /// efficient. Therefore, the data array in blk prior to the - /// method call should not be considered to contain the returned data, a - /// new array may have been created. Instead, get the array from - /// blk after the method has returned. - /// - ///

    The returned data may have its 'progressive' attribute set. In this - /// case the returned data is only an approximation of the "final" data. - /// - ///

    - /// Its coordinates and dimensions specify the area to return, - /// relative to the current tile. Some fields in this object are modified - /// to return the data. - /// - /// - /// The index of the component from which to get the data. - /// - /// - /// The requested DataBlk - /// - /// - /// - /// - /// - public virtual DataBlk getInternCompData(DataBlk blk, int c) - { - return imageData[c].getInternCompData(blk, compIdx[c]); - } - - /// Returns, in the blk argument, a block of image data containing the - /// specifed rectangular area, in the specified component. The data is - /// returned, as a copy of the internal data, therefore the returned data - /// can be modified "in place". - /// - ///

    The rectangular area to return is specified by the 'ulx', 'uly', 'w' - /// and 'h' members of the 'blk' argument, relative to the current - /// tile. These members are not modified by this method. The 'offset' of - /// the returned data is 0, and the 'scanw' is the same as the block's - /// width. See the 'DataBlk' class. - /// - ///

    This method, in general, is less efficient than the - /// 'getInternCompData()' method since, in general, it copies the - /// data. However if the array of returned data is to be modified by the - /// caller then this method is preferable. - /// - ///

    If the data array in 'blk' is 'null', then a new one is created. If - /// the data array is not 'null' then it is reused, and it must be large - /// enough to contain the block's data. Otherwise an 'ArrayStoreException' - /// or an 'IndexOutOfBoundsException' is thrown by the Java system. - /// - ///

    The returned data may have its 'progressive' attribute set. In this - /// case the returned data is only an approximation of the "final" data. - /// - ///

    - /// Its coordinates and dimensions specify the area to return, - /// relative to the current tile. If it contains a non-null data array, - /// then it must be large enough. If it contains a null data array a new - /// one is created. Some fields in this object are modified to return the - /// data. - /// - /// - /// The index of the component from which to get the data. - /// - /// - /// The requested DataBlk - /// - /// - /// - /// - /// - public virtual DataBlk getCompData(DataBlk blk, int c) - { - return imageData[c].getCompData(blk, compIdx[c]); - } - - /// Changes the current tile, given the new coordinates. An - /// IllegalArgumentException is thrown if the coordinates do not correspond - /// to a valid tile. - /// - /// - /// The horizontal coordinate of the tile. - /// - /// - /// The vertical coordinate of the new tile. - /// - /// - public virtual void setTile(int x, int y) - { - if (x != 0 || y != 0) - { - throw new System.ArgumentException(); - } - } - - /// Advances to the next tile, in standard scan-line order (by rows then - /// columns). A NoNextElementException is thrown if the current tile is the - /// last one (i.e. there is no next tile). This default implementation - /// assumes no tiling, so NoNextElementException() is always thrown. - /// - /// - public virtual void nextTile() - { - throw new NoNextElementException(); - } - - /// Returns the coordinates of the current tile. This default - /// implementation assumes no-tiling, so (0,0) is returned. - /// - /// - /// If not null this object is used to return the information. If - /// null a new one is created and returned. - /// - /// - /// The current tile's coordinates. - /// - /// - public virtual Coord getTile(Coord co) - { - if (co != null) - { - co.x = 0; - co.y = 0; - return co; - } - else - { - return new Coord(0, 0); - } - } - - /// Returns the horizontal coordinate of the upper-left corner of the - /// specified component in the current tile. - /// - /// - /// The component index. - /// - /// - public virtual int getCompULX(int c) - { - return 0; - } - - /// Returns the vertical coordinate of the upper-left corner of the - /// specified component in the current tile. - /// - /// - /// The component index. - /// - /// - public virtual int getCompULY(int c) - { - return 0; - } - - /// Returns the number of tiles in the horizontal and vertical - /// directions. This default implementation assumes no tiling, so (1,1) is - /// always returned. - /// - /// - /// If not null this object is used to return the information. If - /// null a new one is created and returned. - /// - /// - /// The number of tiles in the horizontal (Coord.x) and vertical - /// (Coord.y) directions. - /// - /// - public virtual Coord getNumTiles(Coord co) - { - if (co != null) - { - co.x = 1; - co.y = 1; - return co; - } - else - { - return new Coord(1, 1); - } - } - - /// Returns the total number of tiles in the image. This default - /// implementation assumes no tiling, so 1 is always returned. - /// - /// - /// The total number of tiles in the image. - /// - /// - public virtual int getNumTiles() - { - return 1; - } - - /// Returns a string of information about the object, more than 1 line - /// long. The information string includes information from the several - /// input ImgData (their toString() method are called one after the other). - /// - /// - /// A string of information about the object. - /// - /// - public override System.String ToString() - { - System.String string_Renamed = "ImgDataJoiner: WxH = " + w + "x" + h; - for (int i = 0; i < nc; i++) - { - //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Object.toString' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" - string_Renamed += ("\n- Component " + i + " " + imageData[i]); - } - return string_Renamed; - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/image/Tiler.cs b/CSJ2K/j2k/image/Tiler.cs deleted file mode 100644 index 9d23770a..00000000 --- a/CSJ2K/j2k/image/Tiler.cs +++ /dev/null @@ -1,748 +0,0 @@ -/* -* CVS identifier: -* -* $Id: Tiler.java,v 1.34 2001/09/14 09:16:09 grosbois Exp $ -* -* Class: Tiler -* -* Description: An object to create TiledImgData from -* ImgData -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.util; -namespace CSJ2K.j2k.image -{ - - /// This class places an image in the canvas coordinate system, tiles it, if so - /// specified, and performs the coordinate conversions transparently. The - /// source must be a 'BlkImgDataSrc' which is not tiled and has a the image - /// origin at the canvas origin (i.e. it is not "canvased"), or an exception is - /// thrown by the constructor. A tiled and "canvased" output is given through - /// the 'BlkImgDataSrc' interface. See the 'ImgData' interface for a - /// description of the canvas and tiling. - /// - ///

    All tiles produced are rectangular, non-overlapping and their union - /// covers all the image. However, the tiling may not be uniform, depending on - /// the nominal tile size, tiling origin, component subsampling and other - /// factors. Therefore it might not be assumed that all tiles are of the same - /// width and height.

    - /// - ///

    The nominal dimension of the tiles is the maximal one, in the reference - /// grid. All the components of the image have the same number of tiles.

    - /// - ///
    - /// - /// - /// - /// - /// - public class Tiler : ImgDataAdapter, BlkImgDataSrc - { - /// Returns the overall width of the current tile in pixels. This is the - /// tile's width without accounting for any component subsampling. - /// - /// - /// The total current tile width in pixels. - /// - /// - override public int TileWidth - { - get - { - return tileW; - } - - } - /// Returns the overall height of the current tile in pixels. This is the - /// tile's width without accounting for any component subsampling. - /// - /// - /// The total current tile height in pixels. - /// - /// - override public int TileHeight - { - get - { - return tileH; - } - - } - /// Returns the index of the current tile, relative to a standard scan-line - /// order. - /// - /// - /// The current tile's index (starts at 0). - /// - /// - override public int TileIdx - { - get - { - return ty * ntX + tx; - } - - } - /// Returns the horizontal tile partition offset in the reference grid - override public int TilePartULX - { - get - { - return xt0siz; - } - - } - /// Returns the vertical tile partition offset in the reference grid - override public int TilePartULY - { - get - { - return yt0siz; - } - - } - /// Returns the horizontal coordinate of the image origin, the top-left - /// corner, in the canvas system, on the reference grid. - /// - /// - /// The horizontal coordinate of the image origin in the canvas - /// system, on the reference grid. - /// - /// - override public int ImgULX - { - get - { - return x0siz; - } - - } - /// Returns the vertical coordinate of the image origin, the top-left - /// corner, in the canvas system, on the reference grid. - /// - /// - /// The vertical coordinate of the image origin in the canvas - /// system, on the reference grid. - /// - /// - override public int ImgULY - { - get - { - return y0siz; - } - - } - /// Returns the nominal width of the tiles in the reference grid. - /// - /// - /// The nominal tile width, in the reference grid. - /// - /// - override public int NomTileWidth - { - get - { - return xtsiz; - } - - } - /// Returns the nominal width of the tiles in the reference grid. - /// - /// - /// The nominal tile width, in the reference grid. - /// - /// - override public int NomTileHeight - { - get - { - return ytsiz; - } - - } - - /// The source of image data - private BlkImgDataSrc src = null; - - /// Horizontal coordinate of the upper left hand reference grid point. - private int x0siz; - - /// Vertical coordinate of the upper left hand reference grid point. - private int y0siz; - - /// The horizontal coordinate of the tiling origin in the canvas system, - /// on the reference grid. - /// - private int xt0siz; - - /// The vertical coordinate of the tiling origin in the canvas system, on - /// the reference grid. - /// - private int yt0siz; - - /// The nominal width of the tiles, on the reference grid. If 0 then there - /// is no tiling in that direction. - /// - private int xtsiz; - - /// The nominal height of the tiles, on the reference grid. If 0 then - /// there is no tiling in that direction. - /// - private int ytsiz; - - /// The number of tiles in the horizontal direction. - private int ntX; - - /// The number of tiles in the vertical direction. - private int ntY; - - /// The component width in the current active tile, for each component - private int[] compW = null; - - /// The component height in the current active tile, for each component - private int[] compH = null; - - /// The horizontal coordinates of the upper-left corner of the components - /// in the current tile - /// - private int[] tcx0 = null; - - /// The vertical coordinates of the upper-left corner of the components in - /// the current tile. - /// - private int[] tcy0 = null; - - /// The horizontal index of the current tile - private int tx; - - /// The vertical index of the current tile - private int ty; - - /// The width of the current tile, on the reference grid. - private int tileW; - - /// The height of the current tile, on the reference grid. - private int tileH; - - /// Constructs a new tiler with the specified 'BlkImgDataSrc' source, - /// image origin, tiling origin and nominal tile size. - /// - /// - /// The 'BlkImgDataSrc' source from where to get the image - /// data. It must not be tiled and the image origin must be at '(0,0)' on - /// its canvas. - /// - /// - /// The horizontal coordinate of the image origin in the canvas - /// system, on the reference grid (i.e. the image's top-left corner in the - /// reference grid). - /// - /// - /// The vertical coordinate of the image origin in the canvas - /// system, on the reference grid (i.e. the image's top-left corner in the - /// reference grid). - /// - /// - /// The horizontal tiling origin, in the canvas system, on the - /// reference grid. It must satisfy 'px<=ax'. - /// - /// - /// The vertical tiling origin, in the canvas system, on the - /// reference grid. It must satisfy 'py<=ay'. - /// - /// - /// The nominal tile width, on the reference grid. If 0 then - /// there is no tiling in that direction. - /// - /// - /// The nominal tile height, on the reference grid. If 0 then - /// there is no tiling in that direction. - /// - /// - /// If src is tiled or "canvased", or - /// if the arguments do not satisfy the specified constraints. - /// - /// - public Tiler(BlkImgDataSrc src, int ax, int ay, int px, int py, int nw, int nh) : base(src) - { - - // Initialize - this.src = src; - this.x0siz = ax; - this.y0siz = ay; - this.xt0siz = px; - this.yt0siz = py; - this.xtsiz = nw; - this.ytsiz = nh; - - // Verify that input is not tiled - if (src.getNumTiles() != 1) - { - throw new System.ArgumentException("Source is tiled"); - } - // Verify that source is not "canvased" - if (src.ImgULX != 0 || src.ImgULY != 0) - { - throw new System.ArgumentException("Source is \"canvased\""); - } - // Verify that arguments satisfy trivial requirements - if (x0siz < 0 || y0siz < 0 || xt0siz < 0 || yt0siz < 0 || xtsiz < 0 || ytsiz < 0 || xt0siz > x0siz || yt0siz > y0siz) - { - throw new System.ArgumentException("Invalid image origin, " + "tiling origin or nominal " + "tile size"); - } - - // If no tiling has been specified, creates a unique tile with maximum - // dimension. - if (xtsiz == 0) - xtsiz = x0siz + src.ImgWidth - xt0siz; - if (ytsiz == 0) - ytsiz = y0siz + src.ImgHeight - yt0siz; - - // Automatically adjusts xt0siz,yt0siz so that tile (0,0) always - // overlaps with the image. - if (x0siz - xt0siz >= xtsiz) - { - xt0siz += ((x0siz - xt0siz) / xtsiz) * xtsiz; - } - if (y0siz - yt0siz >= ytsiz) - { - yt0siz += ((y0siz - yt0siz) / ytsiz) * ytsiz; - } - if (x0siz - xt0siz >= xtsiz || y0siz - yt0siz >= ytsiz) - { - FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.INFO, "Automatically adjusted tiling " + "origin to equivalent one (" + xt0siz + "," + yt0siz + ") so that " + "first tile overlaps the image"); - } - - // Calculate the number of tiles - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - ntX = (int)System.Math.Ceiling((x0siz + src.ImgWidth) / (double)xtsiz); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - ntY = (int)System.Math.Ceiling((y0siz + src.ImgHeight) / (double)ytsiz); - } - - /// Returns the width in pixels of the specified tile-component. - /// - /// - /// Tile index - /// - /// - /// The index of the component, from 0 to N-1. - /// - /// - /// The width of specified tile-component. - /// - /// - public override int getTileCompWidth(int t, int c) - { - if (t != TileIdx) - { - throw new System.ApplicationException("Asking the width of a tile-component which is " + "not in the current tile (call setTile() or " + "nextTile() methods before)."); - } - return compW[c]; - } - - /// Returns the height in pixels of the specified tile-component. - /// - /// - /// The tile index. - /// - /// - /// The index of the component, from 0 to N-1. - /// - /// - /// The height of specified tile-component. - /// - /// - public override int getTileCompHeight(int t, int c) - { - if (t != TileIdx) - { - throw new System.ApplicationException("Asking the width of a tile-component which is " + "not in the current tile (call setTile() or " + "nextTile() methods before)."); - } - return compH[c]; - } - - /// Returns the position of the fixed point in the specified - /// component. This is the position of the least significant integral - /// (i.e. non-fractional) bit, which is equivalent to the number of - /// fractional bits. For instance, for fixed-point values with 2 fractional - /// bits, 2 is returned. For floating-point data this value does not apply - /// and 0 should be returned. Position 0 is the position of the least - /// significant bit in the data. - /// - /// - /// The index of the component. - /// - /// - /// The position of the fixed-point, which is the same as the - /// number of fractional bits. For floating-point data 0 is returned. - /// - /// - public virtual int getFixedPoint(int c) - { - return src.getFixedPoint(c); - } - - /// Returns, in the blk argument, a block of image data containing the - /// specifed rectangular area, in the specified component. The data is - /// returned, as a reference to the internal data, if any, instead of as a - /// copy, therefore the returned data should not be modified. - /// - ///

    The rectangular area to return is specified by the 'ulx', 'uly', 'w' - /// and 'h' members of the 'blk' argument, relative to the current - /// tile. These members are not modified by this method. The 'offset' and - /// 'scanw' of the returned data can be arbitrary. See the 'DataBlk' - /// class.

    - /// - ///

    This method, in general, is more efficient than the 'getCompData()' - /// method since it may not copy the data. However if the array of returned - /// data is to be modified by the caller then the other method is probably - /// preferable.

    - /// - ///

    If the data array in blk is null, then a new one - /// is created if necessary. The implementation of this interface may - /// choose to return the same array or a new one, depending on what is more - /// efficient. Therefore, the data array in blk prior to the - /// method call should not be considered to contain the returned data, a - /// new array may have been created. Instead, get the array from - /// blk after the method has returned.

    - /// - ///

    The returned data may have its 'progressive' attribute set. In this - /// case the returned data is only an approximation of the "final" - /// data.

    - /// - ///
    - /// Its coordinates and dimensions specify the area to return, - /// relative to the current tile. Some fields in this object are modified - /// to return the data. - /// - /// - /// The index of the component from which to get the data. - /// - /// - /// The requested DataBlk - /// - /// - /// - /// - /// - public DataBlk getInternCompData(DataBlk blk, int c) - { - // Check that block is inside tile - if (blk.ulx < 0 || blk.uly < 0 || blk.w > compW[c] || blk.h > compH[c]) - { - throw new System.ArgumentException("Block is outside the tile"); - } - // Translate to the sources coordinates - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - int incx = (int)System.Math.Ceiling(x0siz / (double)src.getCompSubsX(c)); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - int incy = (int)System.Math.Ceiling(y0siz / (double)src.getCompSubsY(c)); - blk.ulx -= incx; - blk.uly -= incy; - blk = src.getInternCompData(blk, c); - // Translate back to the tiled coordinates - blk.ulx += incx; - blk.uly += incy; - return blk; - } - - /// Returns, in the blk argument, a block of image data containing the - /// specifed rectangular area, in the specified component. The data is - /// returned, as a copy of the internal data, therefore the returned data - /// can be modified "in place". - /// - ///

    The rectangular area to return is specified by the 'ulx', 'uly', 'w' - /// and 'h' members of the 'blk' argument, relative to the current - /// tile. These members are not modified by this method. The 'offset' of - /// the returned data is 0, and the 'scanw' is the same as the block's - /// width. See the 'DataBlk' class.

    - /// - ///

    This method, in general, is less efficient than the - /// 'getInternCompData()' method since, in general, it copies the - /// data. However if the array of returned data is to be modified by the - /// caller then this method is preferable.

    - /// - ///

    If the data array in 'blk' is 'null', then a new one is created. If - /// the data array is not 'null' then it is reused, and it must be large - /// enough to contain the block's data. Otherwise an 'ArrayStoreException' - /// or an 'IndexOutOfBoundsException' is thrown by the Java system.

    - /// - ///

    The returned data may have its 'progressive' attribute set. In this - /// case the returned data is only an approximation of the "final" - /// data.

    - /// - ///
    - /// Its coordinates and dimensions specify the area to return, - /// relative to the current tile. If it contains a non-null data array, - /// then it must be large enough. If it contains a null data array a new - /// one is created. Some fields in this object are modified to return the - /// data. - /// - /// - /// The index of the component from which to get the data. - /// - /// - /// The requested DataBlk - /// - /// - /// - /// - /// - public DataBlk getCompData(DataBlk blk, int c) - { - // Check that block is inside tile - if (blk.ulx < 0 || blk.uly < 0 || blk.w > compW[c] || blk.h > compH[c]) - { - throw new System.ArgumentException("Block is outside the tile"); - } - // Translate to the source's coordinates - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - int incx = (int)System.Math.Ceiling(x0siz / (double)src.getCompSubsX(c)); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - int incy = (int)System.Math.Ceiling(y0siz / (double)src.getCompSubsY(c)); - blk.ulx -= incx; - blk.uly -= incy; - blk = src.getCompData(blk, c); - // Translate back to the tiled coordinates - blk.ulx += incx; - blk.uly += incy; - return blk; - } - - /// Changes the current tile, given the new tile indexes. An - /// IllegalArgumentException is thrown if the coordinates do not correspond - /// to a valid tile. - /// - /// - /// The horizontal index of the tile. - /// - /// - /// The vertical index of the new tile. - /// - /// - public override void setTile(int x, int y) - { - // Check tile indexes - if (x < 0 || y < 0 || x >= ntX || y >= ntY) - { - throw new System.ArgumentException("Tile's indexes out of bounds"); - } - - // Set new current tile - tx = x; - ty = y; - // Calculate tile origins - int tx0 = (x != 0) ? xt0siz + x * xtsiz : x0siz; - int ty0 = (y != 0) ? yt0siz + y * ytsiz : y0siz; - int tx1 = (x != ntX - 1) ? (xt0siz + (x + 1) * xtsiz) : (x0siz + src.ImgWidth); - int ty1 = (y != ntY - 1) ? (yt0siz + (y + 1) * ytsiz) : (y0siz + src.ImgHeight); - // Set general variables - tileW = tx1 - tx0; - tileH = ty1 - ty0; - // Set component specific variables - int nc = src.NumComps; - if (compW == null) - compW = new int[nc]; - if (compH == null) - compH = new int[nc]; - if (tcx0 == null) - tcx0 = new int[nc]; - if (tcy0 == null) - tcy0 = new int[nc]; - for (int i = 0; i < nc; i++) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - tcx0[i] = (int)System.Math.Ceiling(tx0 / (double)src.getCompSubsX(i)); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - tcy0[i] = (int)System.Math.Ceiling(ty0 / (double)src.getCompSubsY(i)); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - compW[i] = (int)System.Math.Ceiling(tx1 / (double)src.getCompSubsX(i)) - tcx0[i]; - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - compH[i] = (int)System.Math.Ceiling(ty1 / (double)src.getCompSubsY(i)) - tcy0[i]; - } - } - - /// Advances to the next tile, in standard scan-line order (by rows then - /// columns). An NoNextElementException is thrown if the current tile is - /// the last one (i.e. there is no next tile). - /// - /// - public override void nextTile() - { - if (tx == ntX - 1 && ty == ntY - 1) - { - // Already at last tile - throw new NoNextElementException(); - } - else if (tx < ntX - 1) - { - // If not at end of current tile line - setTile(tx + 1, ty); - } - else - { - // First tile at next line - setTile(0, ty + 1); - } - } - - /// Returns the horizontal and vertical indexes of the current tile. - /// - /// - /// If not null this object is used to return the - /// information. If null a new one is created and returned. - /// - /// - /// The current tile's horizontal and vertical indexes.. - /// - /// - public override Coord getTile(Coord co) - { - if (co != null) - { - co.x = tx; - co.y = ty; - return co; - } - else - { - return new Coord(tx, ty); - } - } - - /// Returns the horizontal coordinate of the upper-left corner of the - /// specified component in the current tile. - /// - /// - /// The component index. - /// - /// - public override int getCompULX(int c) - { - return tcx0[c]; - } - - /// Returns the vertical coordinate of the upper-left corner of the - /// specified component in the current tile. - /// - /// - /// The component index. - /// - /// - public override int getCompULY(int c) - { - return tcy0[c]; - } - - /// Returns the number of tiles in the horizontal and vertical directions. - /// - /// - /// If not null this object is used to return the information. If - /// null a new one is created and returned. - /// - /// - /// The number of tiles in the horizontal (Coord.x) and vertical - /// (Coord.y) directions. - /// - /// - public override Coord getNumTiles(Coord co) - { - if (co != null) - { - co.x = ntX; - co.y = ntY; - return co; - } - else - { - return new Coord(ntX, ntY); - } - } - - /// Returns the total number of tiles in the image. - /// - /// - /// The total number of tiles in the image. - /// - /// - public override int getNumTiles() - { - return ntX * ntY; - } - - /// Returns the tiling origin, referred to as '(xt0siz,yt0siz)' in the - /// codestream header (SIZ marker segment). - /// - /// - /// If not null this object is used to return the information. If - /// null a new one is created and returned. - /// - /// - /// The coordinate of the tiling origin, in the canvas system, on - /// the reference grid. - /// - /// - /// - /// - /// - public Coord getTilingOrigin(Coord co) - { - if (co != null) - { - co.x = xt0siz; - co.y = yt0siz; - return co; - } - else - { - return new Coord(xt0siz, yt0siz); - } - } - - /// Returns a String object representing Tiler's informations - /// - /// - /// Tiler's infos in a string - /// - /// - public override System.String ToString() - { - //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Object.toString' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" - return "Tiler: source= " + src + "\n" + getNumTiles() + " tile(s), nominal width=" + xtsiz + ", nominal height=" + ytsiz; - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/image/forwcomptransf/ForwCompTransf.cs b/CSJ2K/j2k/image/forwcomptransf/ForwCompTransf.cs deleted file mode 100644 index 7ec78b24..00000000 --- a/CSJ2K/j2k/image/forwcomptransf/ForwCompTransf.cs +++ /dev/null @@ -1,890 +0,0 @@ -/* -* CVS Identifier: -* -* $Id: ForwCompTransf.java,v 1.20 2001/09/14 09:14:57 grosbois Exp $ -* -* Class: ForwCompTransf -* -* Description: Component transformations applied to tiles -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.encoder; -using CSJ2K.j2k.util; -using CSJ2K.j2k.wavelet.analysis; -using System; -namespace CSJ2K.j2k.image.forwcomptransf -{ - - /// This class apply component transformations to the tiles depending on user - /// specifications. These transformations can be used to improve compression - /// efficiency but are not related to colour transforms used to map colour - /// values for display purposes. JPEG 2000 part I defines 2 component - /// transformations: RCT (Reversible Component Transformation) and ICT - /// (Irreversible Component Transformation). - /// - /// - /// - /// - /// - public class ForwCompTransf : ImgDataAdapter, BlkImgDataSrc - { - /// Returns the parameters that are used in this class and implementing - /// classes. It returns a 2D String array. Each of the 1D arrays is for a - /// different option, and they have 4 elements. The first element is the - /// option name, the second one is the synopsis, the third one is a long - /// description of what the parameter is and the fourth is its default - /// value. The synopsis or description may be 'null', in which case it is - /// assumed that there is no synopsis or description of the option, - /// respectively. Null may be returned if no options are supported. - /// - /// - /// the options name, their synopsis and their explanation, or null - /// if no options are supported. - /// - /// - public static System.String[][] ParameterInfo - { - get - { - return pinfo; - } - - } - /// Returns true if this transform is reversible in current - /// tile. Reversible component transformations are those which operation - /// can be completely reversed without any loss of information (not even - /// due to rounding). - /// - /// - /// Reversibility of component transformation in current tile - /// - /// - virtual public bool Reversible - { - get - { - switch (transfType) - { - - case NONE: - case FORW_RCT: - return true; - - case FORW_ICT: - return false; - - default: - throw new System.ArgumentException("Non JPEG 2000 part I" + " component transformation"); - - } - } - - } - /// Identifier for no component transformation. Value is 0. - public const int NONE = 0; - - /// Identifier for the Forward Reversible Component Transformation - /// (FORW_RCT). Value is 1. - /// - public const int FORW_RCT = 1; - - /// Identifier for the Forward Irreversible Component Transformation - /// (FORW_ICT). Value is 2 - /// - public const int FORW_ICT = 2; - - /// The source of image data - private BlkImgDataSrc src; - - /// The component transformations specifications - private CompTransfSpec cts; - - /// The wavelet filter specifications - private AnWTFilterSpec wfs; - - /// The type of the current component transformation. JPEG 2000 part 1 - /// supports only NONE, FORW_RCT and FORW_ICT types - /// - private int transfType = NONE; - - /// The bit-depths of transformed components - private int[] tdepth; - - /// Output block used instead of the one provided as an argument if the - /// later is DataBlkFloat. - /// - private DataBlk outBlk; - - /// Block used to request component with index 0 - private DataBlkInt block0; - - /// Block used to request component with index 1 - private DataBlkInt block1; - - /// Block used to request component with index 2 - private DataBlkInt block2; - - /// Constructs a new ForwCompTransf object that operates on the specified - /// source of image data. - /// - /// - /// The source from where to get the data to be transformed - /// - /// - /// The encoder specifications - /// - /// - /// - /// - /// - public ForwCompTransf(BlkImgDataSrc imgSrc, EncoderSpecs encSpec) : base(imgSrc) - { - this.cts = encSpec.cts; - this.wfs = encSpec.wfs; - src = imgSrc; - } - - /// The prefix for component transformation type: 'M' - public const char OPT_PREFIX = 'M'; - - /// The list of parameters that is accepted by the forward component - /// transformation module. Options start with an 'M'. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'pinfo'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly System.String[][] pinfo = new System.String[][] { new System.String[] { "Mct", "[] [on|off] ...", "Specifies in which tiles to use a multiple component transform. " + "Note that this multiple component transform can only be applied " + "in tiles that contain at least three components and whose " + "components are processed with the same wavelet filters and " + "quantization type. " + "If the wavelet transform is reversible (w5x3 filter), the " + "Reversible Component Transformation (RCT) is applied. If not " + "(w9x7 filter), the Irreversible Component Transformation (ICT)" + " is used.", null } }; - - /// Returns the position of the fixed point in the specified - /// component. This is the position of the least significant integral - /// (i.e. non-fractional) bit, which is equivalent to the number of - /// fractional bits. For instance, for fixed-point values with 2 fractional - /// bits, 2 is returned. For floating-point data this value does not apply - /// and 0 should be returned. Position 0 is the position of the least - /// significant bit in the data. - /// - ///

    This default implementation assumes that the number of fractional - /// bits is not modified by the component mixer.

    - /// - ///
    - /// The index of the component. - /// - /// - /// The value of the fixed point position of the source since the - /// color transform does not affect it. - /// - /// - public virtual int getFixedPoint(int c) - { - return src.getFixedPoint(c); - } - - /// Calculates the bitdepths of the transformed components, given the - /// bitdepth of the un-transformed components and the component - /// transformation type. - /// - /// - /// The bitdepth of each non-transformed components. - /// - /// - /// The type ID of the component transformation. - /// - /// - /// If not null the results are stored in this array, - /// otherwise a new array is allocated and returned. - /// - /// - /// The bitdepth of each transformed component. - /// - /// - public static int[] calcMixedBitDepths(int[] ntdepth, int ttype, int[] tdepth) - { - - if (ntdepth.Length < 3 && ttype != NONE) - { - throw new System.ArgumentException(); - } - - if (tdepth == null) - { - tdepth = new int[ntdepth.Length]; - } - - switch (ttype) - { - - case NONE: - Array.Copy(ntdepth, 0, tdepth, 0, ntdepth.Length); - break; - - case FORW_RCT: - if (ntdepth.Length > 3) - { - Array.Copy(ntdepth, 3, tdepth, 3, ntdepth.Length - 3); - } - // The formulas are: - // tdepth[0] = ceil(log2(2^(ntdepth[0])+2^ntdepth[1]+ - // 2^(ntdepth[2])))-2+1 - // tdepth[1] = ceil(log2(2^(ntdepth[1])+2^(ntdepth[2])-1))+1 - // tdepth[2] = ceil(log2(2^(ntdepth[0])+2^(ntdepth[1])-1))+1 - // The MathUtil.log2(x) function calculates floor(log2(x)), so we - // use 'MathUtil.log2(2*x-1)+1', which calculates ceil(log2(x)) - // for any x>=1, x integer. - tdepth[0] = MathUtil.log2((1 << ntdepth[0]) + (2 << ntdepth[1]) + (1 << ntdepth[2]) - 1) - 2 + 1; - tdepth[1] = MathUtil.log2((1 << ntdepth[2]) + (1 << ntdepth[1]) - 1) + 1; - tdepth[2] = MathUtil.log2((1 << ntdepth[0]) + (1 << ntdepth[1]) - 1) + 1; - break; - - case FORW_ICT: - if (ntdepth.Length > 3) - { - Array.Copy(ntdepth, 3, tdepth, 3, ntdepth.Length - 3); - } - // The MathUtil.log2(x) function calculates floor(log2(x)), so we - // use 'MathUtil.log2(2*x-1)+1', which calculates ceil(log2(x)) - // for any x>=1, x integer. - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - tdepth[0] = MathUtil.log2((int)System.Math.Floor((1 << ntdepth[0]) * 0.299072 + (1 << ntdepth[1]) * 0.586914 + (1 << ntdepth[2]) * 0.114014) - 1) + 1; - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - tdepth[1] = MathUtil.log2((int)System.Math.Floor((1 << ntdepth[0]) * 0.168701 + (1 << ntdepth[1]) * 0.331299 + (1 << ntdepth[2]) * 0.5) - 1) + 1; - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - tdepth[2] = MathUtil.log2((int)System.Math.Floor((1 << ntdepth[0]) * 0.5 + (1 << ntdepth[1]) * 0.418701 + (1 << ntdepth[2]) * 0.081299) - 1) + 1; - break; - } - - return tdepth; - } - - /// Initialize some variables used with RCT. It must be called, at least, - /// at the beginning of each new tile. - /// - /// - private void initForwRCT() - { - int i; - int tIdx = TileIdx; - - if (src.NumComps < 3) - { - throw new System.ArgumentException(); - } - // Check that the 3 components have the same dimensions - if (src.getTileCompWidth(tIdx, 0) != src.getTileCompWidth(tIdx, 1) || src.getTileCompWidth(tIdx, 0) != src.getTileCompWidth(tIdx, 2) || src.getTileCompHeight(tIdx, 0) != src.getTileCompHeight(tIdx, 1) || src.getTileCompHeight(tIdx, 0) != src.getTileCompHeight(tIdx, 2)) - { - throw new System.ArgumentException("Can not use RCT " + "on components with different " + "dimensions"); - } - // Initialize bitdepths - int[] utd; // Premix bitdepths - utd = new int[src.NumComps]; - for (i = utd.Length - 1; i >= 0; i--) - { - utd[i] = src.getNomRangeBits(i); - } - tdepth = calcMixedBitDepths(utd, FORW_RCT, null); - } - - /// Initialize some variables used with ICT. It must be called, at least, - /// at the beginning of a new tile. - /// - /// - private void initForwICT() - { - int i; - int tIdx = TileIdx; - - if (src.NumComps < 3) - { - throw new System.ArgumentException(); - } - // Check that the 3 components have the same dimensions - if (src.getTileCompWidth(tIdx, 0) != src.getTileCompWidth(tIdx, 1) || src.getTileCompWidth(tIdx, 0) != src.getTileCompWidth(tIdx, 2) || src.getTileCompHeight(tIdx, 0) != src.getTileCompHeight(tIdx, 1) || src.getTileCompHeight(tIdx, 0) != src.getTileCompHeight(tIdx, 2)) - { - throw new System.ArgumentException("Can not use ICT " + "on components with different " + "dimensions"); - } - // Initialize bitdepths - int[] utd; // Premix bitdepths - utd = new int[src.NumComps]; - for (i = utd.Length - 1; i >= 0; i--) - { - utd[i] = src.getNomRangeBits(i); - } - tdepth = calcMixedBitDepths(utd, FORW_ICT, null); - } - - /// Returns a string with a descriptive text of which forward component - /// transformation is used. This can be either "Forward RCT" or "Forward - /// ICT" or "No component transformation" depending on the current tile. - /// - /// - /// A descriptive string - /// - /// - public override System.String ToString() - { - switch (transfType) - { - - case FORW_RCT: - return "Forward RCT"; - - case FORW_ICT: - return "Forward ICT"; - - case NONE: - return "No component transformation"; - - default: - throw new System.ArgumentException("Non JPEG 2000 part I" + " component transformation"); - - } - } - - /// Returns the number of bits, referred to as the "range bits", - /// corresponding to the nominal range of the data in the specified - /// component and in the current tile. If this number is b then for - /// unsigned data the nominal range is between 0 and 2^b-1, and for signed - /// data it is between -2^(b-1) and 2^(b-1)-1. Note that this value can be - /// affected by the multiple component transform. - /// - /// - /// The index of the component. - /// - /// - /// The bitdepth of component 'c' after mixing. - /// - /// - public override int getNomRangeBits(int c) - { - switch (transfType) - { - - case FORW_RCT: - case FORW_ICT: - return tdepth[c]; - - case NONE: - return src.getNomRangeBits(c); - - default: - throw new System.ArgumentException("Non JPEG 2000 part I" + " component transformation"); - - } - } - - /// Apply forward component transformation associated with the current - /// tile. If no component transformation has been requested by the user, - /// data are not modified. - /// - ///

    This method calls the getInternCompData() method, but respects the - /// definitions of the getCompData() method defined in the BlkImgDataSrc - /// interface.

    - /// - ///
    - /// Determines the rectangular area to return, and the data is - /// returned in this object. - /// - /// - /// Index of the output component. - /// - /// - /// The requested DataBlk - /// - /// - /// - /// - /// - public virtual DataBlk getCompData(DataBlk blk, int c) - { - // If requesting a component whose index is greater than 3 or there is - // no transform return a copy of data (getInternCompData returns the - // actual data in those cases) - if (c >= 3 || transfType == NONE) - { - return src.getCompData(blk, c); - } - else - { - // We can use getInternCompData (since data is a copy anyways) - return getInternCompData(blk, c); - } - } - - /// Apply the component transformation associated with the current tile. If - /// no component transformation has been requested by the user, data are - /// not modified. Else, appropriate method is called (forwRCT or forwICT). - /// - /// - /// - /// - /// - /// - /// - /// - /// Determines the rectangular area to return. - /// - /// - /// Index of the output component. - /// - /// - /// The requested DataBlk - /// - /// - public virtual DataBlk getInternCompData(DataBlk blk, int c) - { - switch (transfType) - { - - case NONE: - return src.getInternCompData(blk, c); - - case FORW_RCT: - return forwRCT(blk, c); - - case FORW_ICT: - return forwICT(blk, c); - - default: - throw new System.ArgumentException("Non JPEG 2000 part 1 " + "component" + " transformation for tile: " + tIdx); - - } - } - - /// Apply forward component transformation to obtain requested component - /// from specified block of data. Whatever the type of requested DataBlk, - /// it always returns a DataBlkInt. - /// - /// - /// Determine the rectangular area to return - /// - /// - /// The index of the requested component - /// - /// - /// Data of requested component - /// - /// - private DataBlk forwRCT(DataBlk blk, int c) - { - int k, k0, k1, k2, mink, i; - int w = blk.w; //width of output block - int h = blk.h; //height of ouput block - int[] outdata; //array of output data - - //If asking for Yr, Ur or Vr do transform - if (c >= 0 && c <= 2) - { - // Check that request data type is int - if (blk.DataType != DataBlk.TYPE_INT) - { - if (outBlk == null || outBlk.DataType != DataBlk.TYPE_INT) - { - outBlk = new DataBlkInt(); - } - outBlk.w = w; - outBlk.h = h; - outBlk.ulx = blk.ulx; - outBlk.uly = blk.uly; - blk = outBlk; - } - - //Reference to output block data array - outdata = (int[])blk.Data; - - //Create data array of blk if necessary - if (outdata == null || outdata.Length < h * w) - { - outdata = new int[h * w]; - blk.Data = outdata; - } - - // Block buffers for input RGB data - int[] data0, data1, bdata; // input data arrays - - if (block0 == null) - block0 = new DataBlkInt(); - if (block1 == null) - block1 = new DataBlkInt(); - if (block2 == null) - block2 = new DataBlkInt(); - block0.w = block1.w = block2.w = blk.w; - block0.h = block1.h = block2.h = blk.h; - block0.ulx = block1.ulx = block2.ulx = blk.ulx; - block0.uly = block1.uly = block2.uly = blk.uly; - - //Fill in buffer blocks (to be read only) - // Returned blocks may have different size and position - block0 = (DataBlkInt)src.getInternCompData(block0, 0); - data0 = (int[])block0.Data; - block1 = (DataBlkInt)src.getInternCompData(block1, 1); - data1 = (int[])block1.Data; - block2 = (DataBlkInt)src.getInternCompData(block2, 2); - bdata = (int[])block2.Data; - - // Set the progressiveness of the output data - blk.progressive = block0.progressive || block1.progressive || block2.progressive; - blk.offset = 0; - blk.scanw = w; - - //Perform conversion - - // Initialize general indexes - k = w * h - 1; - k0 = block0.offset + (h - 1) * block0.scanw + w - 1; - k1 = block1.offset + (h - 1) * block1.scanw + w - 1; - k2 = block2.offset + (h - 1) * block2.scanw + w - 1; - - switch (c) - { - - case 0: //RGB to Yr conversion - for (i = h - 1; i >= 0; i--) - { - for (mink = k - w; k > mink; k--, k0--, k1--, k2--) - { - // Use int arithmetic with 12 fractional bits - // and rounding - outdata[k] = (data0[k] + 2 * data1[k] + bdata[k]) >> 2; // Same as / 4 - } - // Jump to beggining of previous line in input - k0 -= (block0.scanw - w); - k1 -= (block1.scanw - w); - k2 -= (block2.scanw - w); - } - break; - - - case 1: //RGB to Ur conversion - for (i = h - 1; i >= 0; i--) - { - for (mink = k - w; k > mink; k--, k1--, k2--) - { - // Use int arithmetic with 12 fractional bits - // and rounding - outdata[k] = bdata[k2] - data1[k1]; - } - // Jump to beggining of previous line in input - k1 -= (block1.scanw - w); - k2 -= (block2.scanw - w); - } - break; - - - case 2: //RGB to Vr conversion - for (i = h - 1; i >= 0; i--) - { - for (mink = k - w; k > mink; k--, k0--, k1--) - { - // Use int arithmetic with 12 fractional bits - // and rounding - outdata[k] = data0[k0] - data1[k1]; - } - // Jump to beggining of previous line in input - k0 -= (block0.scanw - w); - k1 -= (block1.scanw - w); - } - break; - } - } - else if (c >= 3) - { - // Requesting a component which is not Y, Ur or Vr => - // just pass the data - return src.getInternCompData(blk, c); - } - else - { - // Requesting a non valid component index - throw new System.ArgumentException(); - } - return blk; - } - - /// Apply forward irreversible component transformation to obtain requested - /// component from specified block of data. Whatever the type of requested - /// DataBlk, it always returns a DataBlkFloat. - /// - /// - /// Determine the rectangular area to return - /// - /// - /// The index of the requested component - /// - /// - /// Data of requested component - /// - /// - private DataBlk forwICT(DataBlk blk, int c) - { - int k, k0, k1, k2, mink, i; - int w = blk.w; //width of output block - int h = blk.h; //height of ouput block - float[] outdata; //array of output data - - if (blk.DataType != DataBlk.TYPE_FLOAT) - { - if (outBlk == null || outBlk.DataType != DataBlk.TYPE_FLOAT) - { - outBlk = new DataBlkFloat(); - } - outBlk.w = w; - outBlk.h = h; - outBlk.ulx = blk.ulx; - outBlk.uly = blk.uly; - blk = outBlk; - } - - //Reference to output block data array - outdata = (float[])blk.Data; - - //Create data array of blk if necessary - if (outdata == null || outdata.Length < w * h) - { - outdata = new float[h * w]; - blk.Data = outdata; - } - - //If asking for Y, Cb or Cr do transform - if (c >= 0 && c <= 2) - { - - int[] data0, data1, data2; // input data arrays - - if (block0 == null) - { - block0 = new DataBlkInt(); - } - if (block1 == null) - { - block1 = new DataBlkInt(); - } - if (block2 == null) - { - block2 = new DataBlkInt(); - } - block0.w = block1.w = block2.w = blk.w; - block0.h = block1.h = block2.h = blk.h; - block0.ulx = block1.ulx = block2.ulx = blk.ulx; - block0.uly = block1.uly = block2.uly = blk.uly; - - // Returned blocks may have different size and position - block0 = (DataBlkInt)src.getInternCompData(block0, 0); - data0 = (int[])block0.Data; - block1 = (DataBlkInt)src.getInternCompData(block1, 1); - data1 = (int[])block1.Data; - block2 = (DataBlkInt)src.getInternCompData(block2, 2); - data2 = (int[])block2.Data; - - // Set the progressiveness of the output data - blk.progressive = block0.progressive || block1.progressive || block2.progressive; - blk.offset = 0; - blk.scanw = w; - - //Perform conversion - - // Initialize general indexes - k = w * h - 1; - k0 = block0.offset + (h - 1) * block0.scanw + w - 1; - k1 = block1.offset + (h - 1) * block1.scanw + w - 1; - k2 = block2.offset + (h - 1) * block2.scanw + w - 1; - - switch (c) - { - - case 0: - //RGB to Y conversion - for (i = h - 1; i >= 0; i--) - { - for (mink = k - w; k > mink; k--, k0--, k1--, k2--) - { - outdata[k] = 0.299f * data0[k0] + 0.587f * data1[k1] + 0.114f * data2[k2]; - } - // Jump to beggining of previous line in input - k0 -= (block0.scanw - w); - k1 -= (block1.scanw - w); - k2 -= (block2.scanw - w); - } - break; - - - case 1: - //RGB to Cb conversion - for (i = h - 1; i >= 0; i--) - { - for (mink = k - w; k > mink; k--, k0--, k1--, k2--) - { - outdata[k] = (-0.16875f) * data0[k0] - 0.33126f * data1[k1] + 0.5f * data2[k2]; - } - // Jump to beggining of previous line in input - k0 -= (block0.scanw - w); - k1 -= (block1.scanw - w); - k2 -= (block2.scanw - w); - } - break; - - - case 2: - //RGB to Cr conversion - for (i = h - 1; i >= 0; i--) - { - for (mink = k - w; k > mink; k--, k0--, k1--, k2--) - { - outdata[k] = 0.5f * data0[k0] - 0.41869f * data1[k1] - 0.08131f * data2[k2]; - } - // Jump to beggining of previous line in input - k0 -= (block0.scanw - w); - k1 -= (block1.scanw - w); - k2 -= (block2.scanw - w); - } - break; - } - } - else if (c >= 3) - { - // Requesting a component which is not Y, Cb or Cr => - // just pass the data - - // Variables - DataBlkInt indb = new DataBlkInt(blk.ulx, blk.uly, w, h); - int[] indata; // input data array - - // Get the input data - // (returned block may be larger than requested one) - src.getInternCompData(indb, c); - indata = (int[])indb.Data; - - // Copy the data converting from int to float - k = w * h - 1; - k0 = indb.offset + (h - 1) * indb.scanw + w - 1; - for (i = h - 1; i >= 0; i--) - { - for (mink = k - w; k > mink; k--, k0--) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - outdata[k] = (float)indata[k0]; - } - // Jump to beggining of next line in input - k0 += indb.w - w; - } - - // Set the progressivity - blk.progressive = indb.progressive; - blk.offset = 0; - blk.scanw = w; - return blk; - } - else - { - // Requesting a non valid component index - throw new System.ArgumentException(); - } - return blk; - } - - /// Changes the current tile, given the new indexes. An - /// IllegalArgumentException is thrown if the indexes do not correspond to - /// a valid tile. - /// - ///

    This default implementation changes the tile in the source and - /// re-initializes properly component transformation variables..

    - /// - ///
    - /// The horizontal index of the tile. - /// - /// - /// The vertical index of the new tile. - /// - /// - public override void setTile(int x, int y) - { - src.setTile(x, y); - tIdx = TileIdx; // index of the current tile - - // initializations - System.String str = (System.String)cts.getTileDef(tIdx); - if (str.Equals("none")) - { - transfType = NONE; - } - else if (str.Equals("rct")) - { - transfType = FORW_RCT; - initForwRCT(); - } - else if (str.Equals("ict")) - { - transfType = FORW_ICT; - initForwICT(); - } - else - { - throw new System.ArgumentException("Component transformation" + " not recognized"); - } - } - - /// Goes to the next tile, in standard scan-line order (by rows then by - /// columns). An NoNextElementException is thrown if the current tile is - /// the last one (i.e. there is no next tile). - /// - ///

    This default implementation just advances to the next tile in the - /// source and re-initializes properly component transformation - /// variables.

    - /// - ///
    - public override void nextTile() - { - src.nextTile(); - tIdx = TileIdx; // index of the current tile - - // initializations - System.String str = (System.String)cts.getTileDef(tIdx); - if (str.Equals("none")) - { - transfType = NONE; - } - else if (str.Equals("rct")) - { - transfType = FORW_RCT; - initForwRCT(); - } - else if (str.Equals("ict")) - { - transfType = FORW_ICT; - initForwICT(); - } - else - { - throw new System.ArgumentException("Component transformation" + " not recognized"); - } - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/image/forwcomptransf/ForwCompTransfSpec.cs b/CSJ2K/j2k/image/forwcomptransf/ForwCompTransfSpec.cs deleted file mode 100644 index 882a15e0..00000000 --- a/CSJ2K/j2k/image/forwcomptransf/ForwCompTransfSpec.cs +++ /dev/null @@ -1,438 +0,0 @@ -/* -* CVS identifier: -* -* $Id: ForwCompTransfSpec.java,v 1.7 2001/05/08 16:10:18 grosbois Exp $ -* -* Class: ForwCompTransfSpec -* -* Description: Component Transformation specification for encoder -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.util; -using CSJ2K.j2k.wavelet; -using CSJ2K.j2k.wavelet.analysis; -namespace CSJ2K.j2k.image.forwcomptransf -{ - - /// This class extends CompTransfSpec class in order to hold encoder specific - /// aspects of CompTransfSpec. - /// - /// - /// - /// - /// - public class ForwCompTransfSpec : CompTransfSpec, FilterTypes - { - /// Constructs a new 'ForwCompTransfSpec' for the specified number of - /// components and tiles, the wavelet filters type and the parameter of the - /// option 'Mct'. This constructor is called by the encoder. It also checks - /// that the arguments belong to the recognized arguments list. - /// - ///

    This constructor chose the component transformation type depending - /// on the wavelet filters : RCT with w5x3 filter and ICT with w9x7 - /// filter. Note: All filters must use the same data type.

    - /// - ///
    - /// The number of tiles - /// - /// - /// The number of components - /// - /// - /// the type of the specification module i.e. tile specific, - /// component specific or both. - /// - /// - /// The wavelet filter specifications - /// - /// - /// The ParameterList - /// - /// - public ForwCompTransfSpec(int nt, int nc, byte type, AnWTFilterSpec wfs, ParameterList pl) : base(nt, nc, type) - { - - System.String param = pl.getParameter("Mct"); - - if (param == null) - { - // The option has not been specified - - // If less than three component, do not use any component - // transformation - if (nc < 3) - { - setDefault("none"); - return; - } - // If the compression is lossless, uses RCT - else if (pl.getBooleanParameter("lossless")) - { - setDefault("rct"); - return; - } - else - { - AnWTFilter[][] anfilt; - int[] filtType = new int[nComp]; - for (int c = 0; c < 3; c++) - { - anfilt = (AnWTFilter[][])wfs.getCompDef(c); - filtType[c] = anfilt[0][0].FilterType; - } - - // Check that the three first components use the same filters - bool reject = false; - for (int c = 1; c < 3; c++) - { - if (filtType[c] != filtType[0]) - reject = true; - } - - if (reject) - { - setDefault("none"); - } - else - { - anfilt = (AnWTFilter[][])wfs.getCompDef(0); - if (anfilt[0][0].FilterType == CSJ2K.j2k.wavelet.FilterTypes_Fields.W9X7) - { - setDefault("ict"); - } - else - { - setDefault("rct"); - } - } - } - - // Each tile receives a component transform specification - // according the type of wavelet filters that are used by the - // three first components - for (int t = 0; t < nt; t++) - { - AnWTFilter[][] anfilt; - int[] filtType = new int[nComp]; - for (int c = 0; c < 3; c++) - { - anfilt = (AnWTFilter[][])wfs.getTileCompVal(t, c); - filtType[c] = anfilt[0][0].FilterType; - } - - // Check that the three components use the same filters - bool reject = false; - for (int c = 1; c < nComp; c++) - { - if (filtType[c] != filtType[0]) - reject = true; - } - - if (reject) - { - setTileDef(t, "none"); - } - else - { - anfilt = (AnWTFilter[][])wfs.getTileCompVal(t, 0); - if (anfilt[0][0].FilterType == CSJ2K.j2k.wavelet.FilterTypes_Fields.W9X7) - { - setTileDef(t, "ict"); - } - else - { - setTileDef(t, "rct"); - } - } - } - return; - } - - // Parse argument - SupportClass.Tokenizer stk = new SupportClass.Tokenizer(param); - System.String word; // current word - byte curSpecType = SPEC_DEF; // Specification type of the - // current parameter - bool[] tileSpec = null; // Tiles concerned by the - // specification - //System.Boolean value_Renamed; - - while (stk.HasMoreTokens()) - { - word = stk.NextToken(); - - switch (word[0]) - { - - case 't': // Tiles specification - tileSpec = parseIdx(word, nTiles); - if (curSpecType == SPEC_COMP_DEF) - { - curSpecType = SPEC_TILE_COMP; - } - else - { - curSpecType = SPEC_TILE_DEF; - } - break; - - case 'c': // Components specification - throw new System.ArgumentException("Component specific " + " parameters" + " not allowed with " + "'-Mct' option"); - - default: - if (word.Equals("off")) - { - if (curSpecType == SPEC_DEF) - { - setDefault("none"); - } - else if (curSpecType == SPEC_TILE_DEF) - { - for (int i = tileSpec.Length - 1; i >= 0; i--) - if (tileSpec[i]) - { - setTileDef(i, "none"); - } - } - } - else if (word.Equals("on")) - { - if (nc < 3) - { - throw new System.ArgumentException("Cannot use component" + " transformation on a " + "image with less than " + "three components"); - } - - if (curSpecType == SPEC_DEF) - { - // Set arbitrarily the default - // value to RCT (later will be found the suitable - // component transform for each tile) - setDefault("rct"); - } - else if (curSpecType == SPEC_TILE_DEF) - { - for (int i = tileSpec.Length - 1; i >= 0; i--) - { - if (tileSpec[i]) - { - if (getFilterType(i, wfs) == CSJ2K.j2k.wavelet.FilterTypes_Fields.W5X3) - { - setTileDef(i, "rct"); - } - else - { - setTileDef(i, "ict"); - } - } - } - } - } - else - { - throw new System.ArgumentException("Default parameter of " + "option Mct not" + " recognized: " + param); - } - - // Re-initialize - curSpecType = SPEC_DEF; - tileSpec = null; - break; - - } - } - - // Check that default value has been specified - if (getDefault() == null) - { - // If not, set arbitrarily the default value to 'none' but - // specifies explicitely a default value for each tile depending - // on the wavelet transform that is used - setDefault("none"); - - for (int t = 0; t < nt; t++) - { - if (isTileSpecified(t)) - { - continue; - } - - AnWTFilter[][] anfilt; - int[] filtType = new int[nComp]; - for (int c = 0; c < 3; c++) - { - anfilt = (AnWTFilter[][])wfs.getTileCompVal(t, c); - filtType[c] = anfilt[0][0].FilterType; - } - - // Check that the three components use the same filters - bool reject = false; - for (int c = 1; c < nComp; c++) - { - if (filtType[c] != filtType[0]) - reject = true; - } - - if (reject) - { - setTileDef(t, "none"); - } - else - { - anfilt = (AnWTFilter[][])wfs.getTileCompVal(t, 0); - if (anfilt[0][0].FilterType == CSJ2K.j2k.wavelet.FilterTypes_Fields.W9X7) - { - setTileDef(t, "ict"); - } - else - { - setTileDef(t, "rct"); - } - } - } - } - - // Check validity of component transformation of each tile compared to - // the filter used. - for (int t = nt - 1; t >= 0; t--) - { - - if (((System.String)getTileDef(t)).Equals("none")) - { - // No comp. transf is used. No check is needed - continue; - } - else if (((System.String)getTileDef(t)).Equals("rct")) - { - // Tile is using Reversible component transform - int filterType = getFilterType(t, wfs); - switch (filterType) - { - - case CSJ2K.j2k.wavelet.FilterTypes_Fields.W5X3: // OK - break; - - case CSJ2K.j2k.wavelet.FilterTypes_Fields.W9X7: // Must use ICT - if (isTileSpecified(t)) - { - // User has requested RCT -> Error - throw new System.ArgumentException("Cannot use RCT " + "with 9x7 filter " + "in tile " + t); - } - else - { - // Specify ICT for this tile - setTileDef(t, "ict"); - } - break; - - default: - throw new System.ArgumentException("Default filter is " + "not JPEG 2000 part" + " I compliant"); - - } - } - else - { - // ICT - int filterType = getFilterType(t, wfs); - switch (filterType) - { - - case CSJ2K.j2k.wavelet.FilterTypes_Fields.W5X3: // Must use RCT - if (isTileSpecified(t)) - { - // User has requested ICT -> Error - throw new System.ArgumentException("Cannot use ICT " + "with filter 5x3 " + "in tile " + t); - } - else - { - setTileDef(t, "rct"); - } - break; - - case CSJ2K.j2k.wavelet.FilterTypes_Fields.W9X7: // OK - break; - - default: - throw new System.ArgumentException("Default filter is " + "not JPEG 2000 part" + " I compliant"); - - } - } - } - } - - /// Get the filter type common to all component of a given tile. If the - /// tile index is -1, it searches common filter type of default - /// specifications. - /// - /// - /// The tile index - /// - /// - /// The analysis filters specifications - /// - /// - /// The filter type common to all the components - /// - /// - private int getFilterType(int t, AnWTFilterSpec wfs) - { - AnWTFilter[][] anfilt; - int[] filtType = new int[nComp]; - for (int c = 0; c < nComp; c++) - { - if (t == -1) - { - anfilt = (AnWTFilter[][])wfs.getCompDef(c); - } - else - { - anfilt = (AnWTFilter[][])wfs.getTileCompVal(t, c); - } - filtType[c] = anfilt[0][0].FilterType; - } - - // Check that all filters are the same one - bool reject = false; - for (int c = 1; c < nComp; c++) - { - if (filtType[c] != filtType[0]) - reject = true; - } - if (reject) - { - throw new System.ArgumentException("Can not use component" + " transformation when " + "components do not use " + "the same filters"); - } - return filtType[0]; - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/image/input/ImgReader.cs b/CSJ2K/j2k/image/input/ImgReader.cs deleted file mode 100644 index d6e27c98..00000000 --- a/CSJ2K/j2k/image/input/ImgReader.cs +++ /dev/null @@ -1,507 +0,0 @@ -/// CVS identifier: -/// -/// $Id: ImgReader.java,v 1.10 2002/07/25 15:07:44 grosbois Exp $ -/// -/// Class: ImgReader -/// -/// Description: Generic interface for image readers (from -/// file or other resource) -/// -/// -/// -/// COPYRIGHT: -/// -/// This software module was originally developed by Raphaël Grosbois and -/// Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -/// Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -/// Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -/// Centre France S.A) in the course of development of the JPEG2000 -/// standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -/// software module is an implementation of a part of the JPEG 2000 -/// Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -/// Systems AB and Canon Research Centre France S.A (collectively JJ2000 -/// Partners) agree not to assert against ISO/IEC and users of the JPEG -/// 2000 Standard (Users) any of their rights under the copyright, not -/// including other intellectual property rights, for this software module -/// with respect to the usage by ISO/IEC and Users of this software module -/// or modifications thereof for use in hardware or software products -/// claiming conformance to the JPEG 2000 Standard. Those intending to use -/// this software module in hardware or software products are advised that -/// their use may infringe existing patents. The original developers of -/// this software module, JJ2000 Partners and ISO/IEC assume no liability -/// for use of this software module or modifications thereof. No license -/// or right to this software module is granted for non JPEG 2000 Standard -/// conforming products. JJ2000 Partners have full right to use this -/// software module for his/her own purpose, assign or donate this -/// software module to any third party and to inhibit third parties from -/// using this software module for non JPEG 2000 Standard conforming -/// products. This copyright notice must be included in all copies or -/// derivative works of this software module. -/// -/// Copyright (c) 1999/2000 JJ2000 Partners. -/// -/// -namespace CSJ2K.j2k.image.input -{ - - /// This is the generic interface to be implemented by all image file (or other - /// resource) readers for different image file formats. - /// - ///

    An ImgReader behaves as an ImgData object. Whenever image data is - /// requested through the getInternCompData() or getCompData() methods, the - /// image data will be read (if it is not buffered) and returned. Implementing - /// classes should not buffer large amounts of data, so as to reduce memory - /// usage.

    - /// - ///

    This class sets the image origin to (0,0). All default implementations - /// of the methods assume this.

    - /// - ///

    This class provides default implementations of many methods. These - /// default implementations assume that there is no tiling (i.e., the only tile - /// is the entire image), that the image origin is (0,0) in the canvas system - /// and that there is no component subsampling (all components are the same - /// size), but they can be overloaded by the implementating class if need - /// be.

    - /// - ///
    - public abstract class ImgReader : BlkImgDataSrc - { - /// Returns the width of the current tile in pixels, assuming there is - /// no-tiling. Since no-tiling is assumed this is the same as the width of - /// the image. The value of w is returned. - /// - /// - /// The total image width in pixels. - /// - /// - virtual public int TileWidth - { - get - { - return w; - } - - } - /// Returns the overall height of the current tile in pixels, assuming - /// there is no-tiling. Since no-tiling is assumed this is the same as the - /// width of the image. The value of h is returned. - /// - /// - /// The total image height in pixels. - /// - virtual public int TileHeight - { - get - { - return h; - } - - } - /// Returns the nominal tiles width - virtual public int NomTileWidth - { - get - { - return w; - } - - } - /// Returns the nominal tiles height - virtual public int NomTileHeight - { - get - { - return h; - } - - } - /// Returns the overall width of the image in pixels. This is the image's - /// width without accounting for any component subsampling or tiling. The - /// value of w is returned. - /// - /// - /// The total image's width in pixels. - /// - /// - virtual public int ImgWidth - { - get - { - return w; - } - - } - /// Returns the overall height of the image in pixels. This is the image's - /// height without accounting for any component subsampling or tiling. The - /// value of h is returned. - /// - /// - /// The total image's height in pixels. - /// - /// - virtual public int ImgHeight - { - get - { - return h; - } - - } - /// Returns the number of components in the image. The value of nc - /// is returned. - /// - /// - /// The number of components in the image. - /// - /// - virtual public int NumComps - { - get - { - return nc; - } - - } - /// Returns the index of the current tile, relative to a standard scan-line - /// order. This default implementations assumes no tiling, so 0 is always - /// returned. - /// - /// - /// The current tile's index (starts at 0). - /// - /// - virtual public int TileIdx - { - get - { - return 0; - } - - } - /// Returns the horizontal tile partition offset in the reference grid - virtual public int TilePartULX - { - get - { - return 0; - } - - } - /// Returns the vertical tile partition offset in the reference grid - virtual public int TilePartULY - { - get - { - return 0; - } - - } - /// Returns the horizontal coordinate of the image origin, the top-left - /// corner, in the canvas system, on the reference grid. - /// - /// - /// The horizontal coordinate of the image origin in the canvas - /// system, on the reference grid. - /// - /// - virtual public int ImgULX - { - get - { - return 0; - } - - } - /// Returns the vertical coordinate of the image origin, the top-left - /// corner, in the canvas system, on the reference grid. - /// - /// - /// The vertical coordinate of the image origin in the canvas - /// system, on the reference grid. - /// - /// - virtual public int ImgULY - { - get - { - return 0; - } - - } - - /// The width of the image - protected internal int w; - - /// The height of the image - protected internal int h; - - /// The number of components in the image - protected internal int nc; - - /// Closes the underlying file or network connection from where the - /// image data is being read. - /// - /// - /// If an I/O error occurs. - /// - public abstract void close(); - - /// Returns the component subsampling factor in the horizontal direction, - /// for the specified component. This is, approximately, the ratio of - /// dimensions between the reference grid and the component itself, see the - /// 'ImgData' interface desription for details. - /// - /// - /// The index of the component (between 0 and C-1) - /// - /// - /// The horizontal subsampling factor of component 'c' - /// - /// - /// - /// - /// - public virtual int getCompSubsX(int c) - { - return 1; - } - - /// Returns the component subsampling factor in the vertical direction, for - /// the specified component. This is, approximately, the ratio of - /// dimensions between the reference grid and the component itself, see the - /// 'ImgData' interface desription for details. - /// - /// - /// The index of the component (between 0 and C-1) - /// - /// - /// The vertical subsampling factor of component 'c' - /// - /// - /// - /// - /// - public virtual int getCompSubsY(int c) - { - return 1; - } - - /// Returns the width in pixels of the specified tile-component. This - /// default implementation assumes no tiling and no component subsampling - /// (i.e., all components, or components, have the same dimensions in - /// pixels). - /// - /// - /// Tile index - /// - /// - /// The index of the component, from 0 to C-1. - /// - /// - /// The width in pixels of component c in tilet. - /// - /// - public virtual int getTileCompWidth(int t, int c) - { - if (t != 0) - { - throw new System.ApplicationException("Asking a tile-component width for a tile index" + " greater than 0 whereas there is only one tile"); - } - return w; - } - - /// Returns the height in pixels of the specified tile-component. This - /// default implementation assumes no tiling and no component subsampling - /// (i.e., all components, or components, have the same dimensions in - /// pixels). - /// - /// - /// The tile index - /// - /// - /// The index of the component, from 0 to C-1. - /// - /// - /// The height in pixels of component c in tile - /// t. - /// - /// - public virtual int getTileCompHeight(int t, int c) - { - if (t != 0) - { - throw new System.ApplicationException("Asking a tile-component width for a tile index" + " greater than 0 whereas there is only one tile"); - } - return h; - } - - /// Returns the width in pixels of the specified component in the overall - /// image. This default implementation assumes no component, or component, - /// subsampling (i.e. all components have the same dimensions in pixels). - /// - /// - /// The index of the component, from 0 to C-1. - /// - /// - /// The width in pixels of component c in the overall - /// image. - /// - /// - public virtual int getCompImgWidth(int c) - { - return w; - } - - /// Returns the height in pixels of the specified component in the overall - /// image. This default implementation assumes no component, or component, - /// subsampling (i.e. all components have the same dimensions in pixels). - /// - /// - /// The index of the component, from 0 to C-1. - /// - /// - /// The height in pixels of component c in the overall - /// image. - /// - /// - public virtual int getCompImgHeight(int c) - { - return h; - } - - /// Changes the current tile, given the new coordinates. An - /// IllegalArgumentException is thrown if the coordinates do not correspond - /// to a valid tile. This default implementation assumes no tiling so the - /// only valid arguments are x=0, y=0. - /// - /// - /// The horizontal coordinate of the tile. - /// - /// - /// The vertical coordinate of the new tile. - /// - /// - public virtual void setTile(int x, int y) - { - if (x != 0 || y != 0) - { - throw new System.ArgumentException(); - } - } - - /// Advances to the next tile, in standard scan-line order (by rows then - /// columns). A NoNextElementException is thrown if the current tile is the - /// last one (i.e. there is no next tile). This default implementation - /// assumes no tiling, so NoNextElementException() is always thrown. - /// - /// - public virtual void nextTile() - { - throw new NoNextElementException(); - } - - /// Returns the coordinates of the current tile. This default - /// implementation assumes no-tiling, so (0,0) is returned. - /// - /// - /// If not null this object is used to return the information. If - /// null a new one is created and returned. - /// - /// - /// The current tile's coordinates. - /// - /// - public virtual Coord getTile(Coord co) - { - if (co != null) - { - co.x = 0; - co.y = 0; - return co; - } - else - { - return new Coord(0, 0); - } - } - - /// Returns the horizontal coordinate of the upper-left corner of the - /// specified component in the current tile. - /// - /// - /// The component index. - /// - /// - public virtual int getCompULX(int c) - { - return 0; - } - - /// Returns the vertical coordinate of the upper-left corner of the - /// specified component in the current tile. - /// - /// - /// The component index. - /// - /// - public virtual int getCompULY(int c) - { - return 0; - } - - /// Returns the number of tiles in the horizontal and vertical - /// directions. This default implementation assumes no tiling, so (1,1) is - /// always returned. - /// - /// - /// If not null this object is used to return the information. If - /// null a new one is created and returned. - /// - /// - /// The number of tiles in the horizontal (Coord.x) and vertical - /// (Coord.y) directions. - /// - /// - public virtual Coord getNumTiles(Coord co) - { - if (co != null) - { - co.x = 1; - co.y = 1; - return co; - } - else - { - return new Coord(1, 1); - } - } - - /// Returns the total number of tiles in the image. This default - /// implementation assumes no tiling, so 1 is always returned. - /// - /// - /// The total number of tiles in the image. - /// - /// - public virtual int getNumTiles() - { - return 1; - } - - /// Returns true if the data read was originally signed in the specified - /// component, false if not. - /// - /// - /// The index of the component, from 0 to C-1. - /// - /// - /// true if the data was originally signed, false if not. - /// - /// - public abstract bool isOrigSigned(int c); - public abstract int getFixedPoint(int param1); - public abstract CSJ2K.j2k.image.DataBlk getInternCompData(CSJ2K.j2k.image.DataBlk param1, int param2); - public abstract int getNomRangeBits(int param1); - public abstract CSJ2K.j2k.image.DataBlk getCompData(CSJ2K.j2k.image.DataBlk param1, int param2); - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/image/input/ImgReaderGDI.cs b/CSJ2K/j2k/image/input/ImgReaderGDI.cs deleted file mode 100644 index 124898af..00000000 --- a/CSJ2K/j2k/image/input/ImgReaderGDI.cs +++ /dev/null @@ -1,400 +0,0 @@ -/* -* -* Class: ImgWriterGDI -* -* Description: Image writer for System.Drawing.GDI streams -* -* */ - -using System; -using System.Drawing; -using System.Drawing.Imaging; -using System.IO; - -namespace CSJ2K.j2k.image.input -{ - public class ImgReaderGDI : ImgReader - { - /// The number of bits that determine the nominal dynamic range - private int rb; - - /// Buffer for the components of each pixel(in the current block) - private int[][] barr; - - /// Data block used only to store coordinates of the buffered blocks - private DataBlkInt dbi = new DataBlkInt(); - - /// Temporary DataBlkInt object (needed when encoder uses floating-point - /// filters). This avoid allocating new DataBlk at each time - /// - private DataBlkInt intBlk; - - private Image image; - - public ImgReaderGDI(Image image) - { - if (image.PixelFormat != PixelFormat.Format24bppRgb) - throw new ArgumentException("Only 24bpp RGB images are currently supported"); - - this.image = image; - - w = image.Width; - h = image.Height; - - nc = 3; - rb = 8; - } - - /// Closes the underlying file from where the image data is being read. No - /// operations are possible after a call to this method. - /// - /// - /// If an I/O error occurs. - /// - /// - public override void close() - { - image.Dispose(); - image = null; - - barr = null; - } - - /// Returns the number of bits corresponding to the nominal range of the - /// data in the specified component. This is the value rb (range bits) that - /// was specified in the constructor, which normally is 8 for non bilevel - /// data, and 1 for bilevel data. - /// - ///

    If this number is b then the nominal range is between - /// -2^(b-1) and 2^(b-1)-1, since unsigned data is level shifted to have a - /// nominal avergae of 0. - /// - ///

    - /// The index of the component. - /// - /// - /// The number of bits corresponding to the nominal range of the - /// data. For floating-point data this value is not applicable and the - /// return value is undefined. - /// - /// - public override int getNomRangeBits(int c) - { - // Check component index - if (c < 0 || c > 2) - throw new System.ArgumentException(); - - return rb; - } - - /// Returns the position of the fixed point in the specified component - /// (i.e. the number of fractional bits), which is always 0 for this - /// ImgReader. - /// - /// - /// The index of the component. - /// - /// - /// The position of the fixed-point (i.e. the number of fractional - /// bits). Always 0 for this ImgReader. - /// - /// - public override int getFixedPoint(int c) - { - // Check component index - if (c < 0 || c > 2) - throw new System.ArgumentException(); - return 0; - } - - /// Returns, in the blk argument, the block of image data containing the - /// specifed rectangular area, in the specified component. The data is - /// returned, as a reference to the internal data, if any, instead of as a - /// copy, therefore the returned data should not be modified. - /// - ///

    After being read the coefficients are level shifted by subtracting - /// 2^(nominal bit range - 1) - /// - ///

    The rectangular area to return is specified by the 'ulx', 'uly', 'w' - /// and 'h' members of the 'blk' argument, relative to the current - /// tile. These members are not modified by this method. The 'offset' and - /// 'scanw' of the returned data can be arbitrary. See the 'DataBlk' class. - /// - ///

    If the data array in blk is null, then a new one - /// is created if necessary. The implementation of this interface may - /// choose to return the same array or a new one, depending on what is more - /// efficient. Therefore, the data array in blk prior to the - /// method call should not be considered to contain the returned data, a - /// new array may have been created. Instead, get the array from - /// blk after the method has returned. - /// - ///

    The returned data always has its 'progressive' attribute unset - /// (i.e. false). - /// - ///

    When an I/O exception is encountered the JJ2KExceptionHandler is - /// used. The exception is passed to its handleException method. The action - /// that is taken depends on the action that has been registered in - /// JJ2KExceptionHandler. See JJ2KExceptionHandler for details. - /// - ///

    This method implements buffering for the 3 components: When the - /// first one is asked, all the 3 components are read and stored until they - /// are needed. - /// - ///

    - /// Its coordinates and dimensions specify the area to - /// return. Some fields in this object are modified to return the data. - /// - /// - /// The index of the component from which to get the data. Only 0, - /// 1 and 3 are valid. - /// - /// - /// The requested DataBlk - /// - /// - /// - /// - /// - /// - /// - /// - public override DataBlk getInternCompData(DataBlk blk, int c) - { - // Check component index - if (c < 0 || c > 2) - throw new System.ArgumentException(); - - // Check type of block provided as an argument - if (blk.DataType != DataBlk.TYPE_INT) - { - if (intBlk == null) - intBlk = new DataBlkInt(blk.ulx, blk.uly, blk.w, blk.h); - else - { - intBlk.ulx = blk.ulx; - intBlk.uly = blk.uly; - intBlk.w = blk.w; - intBlk.h = blk.h; - } - blk = intBlk; - } - - // If asking a component for the first time for this block, read all of the components - if ((barr == null) || (dbi.ulx > blk.ulx) || (dbi.uly > blk.uly) || (dbi.ulx + dbi.w < blk.ulx + blk.w) || (dbi.uly + dbi.h < blk.uly + blk.h)) - { - int i; - int[] red, green, blue, alpha; - int componentCount = (image.PixelFormat == PixelFormat.Format32bppArgb) ? 4 : 3; - - barr = new int[componentCount][]; - - // Reset data arrays if needed - if (barr[c] == null || barr[c].Length < blk.w * blk.h) - { - barr[c] = new int[blk.w * blk.h]; - } - blk.Data = barr[c]; - - i = (c + 1) % 3; - if (barr[i] == null || barr[i].Length < blk.w * blk.h) - { - barr[i] = new int[blk.w * blk.h]; - } - i = (c + 2) % 3; - if (barr[i] == null || barr[i].Length < blk.w * blk.h) - { - barr[i] = new int[blk.w * blk.h]; - } - - if (componentCount == 4) - { - if (barr[3] == null || barr[3].Length < blk.w * blk.h) - barr[3] = new int[blk.w * blk.h]; - } - - // set attributes of the DataBlk used for buffering - dbi.ulx = blk.ulx; - dbi.uly = blk.uly; - dbi.w = blk.w; - dbi.h = blk.h; - - red = barr[0]; - green = barr[1]; - blue = barr[2]; - alpha = (componentCount == 4) ? barr[3] : null; - - Bitmap bitmap = (Bitmap)image; - BitmapData data = bitmap.LockBits(new Rectangle(blk.ulx, blk.uly, blk.w, blk.h), ImageLockMode.ReadOnly, - (componentCount == 3) ? PixelFormat.Format24bppRgb : PixelFormat.Format32bppArgb); - unsafe - { - byte* ptr = (byte*)data.Scan0.ToPointer(); - - int k = 0; - for (int j = 0; j < blk.w * blk.h; j++) - { - blue[k] = ((byte)*(ptr + 0) & 0xFF) - 128; - green[k] = ((byte)*(ptr + 1) & 0xFF) - 128; - red[k] = ((byte)*(ptr + 2) & 0xFF) - 128; - if (componentCount == 4) - alpha[k] = ((byte)*(ptr + 3) & 0xFF) - 128; - - ++k; - ptr += 3; - } - } - bitmap.UnlockBits(data); - - barr[0] = red; - barr[1] = green; - barr[2] = blue; - if (componentCount == 4) - barr[3] = alpha; - - // Set buffer attributes - blk.Data = barr[c]; - blk.offset = 0; - blk.scanw = blk.w; - } - else - { - //Asking for the 2nd or 3rd (or 4th) block component - blk.Data = barr[c]; - blk.offset = (blk.ulx - dbi.ulx) * dbi.w + blk.ulx - dbi.ulx; - blk.scanw = dbi.scanw; - } - - // Turn off the progressive attribute - blk.progressive = false; - return blk; - } - - /// Returns, in the blk argument, a block of image data containing the - /// specifed rectangular area, in the specified component. The data is - /// returned, as a copy of the internal data, therefore the returned data - /// can be modified "in place". - /// - ///

    After being read the coefficients are level shifted by subtracting - /// 2^(nominal bit range - 1) - /// - ///

    The rectangular area to return is specified by the 'ulx', 'uly', 'w' - /// and 'h' members of the 'blk' argument, relative to the current - /// tile. These members are not modified by this method. The 'offset' of - /// the returned data is 0, and the 'scanw' is the same as the block's - /// width. See the 'DataBlk' class. - /// - ///

    If the data array in 'blk' is 'null', then a new one is created. If - /// the data array is not 'null' then it is reused, and it must be large - /// enough to contain the block's data. Otherwise an 'ArrayStoreException' - /// or an 'IndexOutOfBoundsException' is thrown by the Java system. - /// - ///

    The returned data has its 'progressive' attribute unset - /// (i.e. false). - /// - ///

    When an I/O exception is encountered the JJ2KExceptionHandler is - /// used. The exception is passed to its handleException method. The action - /// that is taken depends on the action that has been registered in - /// JJ2KExceptionHandler. See JJ2KExceptionHandler for details. - /// - ///

    - /// Its coordinates and dimensions specify the area to - /// return. If it contains a non-null data array, then it must have the - /// correct dimensions. If it contains a null data array a new one is - /// created. The fields in this object are modified to return the data. - /// - /// - /// The index of the component from which to get the data. Only - /// 0,1 and 2 are valid. - /// - /// - /// The requested DataBlk - /// - /// - /// - /// - /// - /// - /// - /// - public override DataBlk getCompData(DataBlk blk, int c) - { - // NOTE: can not directly call getInterCompData since that returns - // internally buffered data. - int ulx, uly, w, h; - - // Check type of block provided as an argument - if (blk.DataType != DataBlk.TYPE_INT) - { - DataBlkInt tmp = new DataBlkInt(blk.ulx, blk.uly, blk.w, blk.h); - blk = tmp; - } - - int[] bakarr = (int[])blk.Data; - // Save requested block size - ulx = blk.ulx; - uly = blk.uly; - w = blk.w; - h = blk.h; - // Force internal data buffer to be different from external - blk.Data = null; - getInternCompData(blk, c); - // Copy the data - if (bakarr == null) - { - bakarr = new int[w * h]; - } - if (blk.offset == 0 && blk.scanw == w) - { - // Requested and returned block buffer are the same size - // CONVERSION PROBLEM? - Array.Copy((System.Array)blk.Data, 0, (System.Array)bakarr, 0, w * h); - } - else - { - // Requested and returned block are different - for (int i = h - 1; i >= 0; i--) - { - // copy line by line - // CONVERSION PROBLEM? - Array.Copy((System.Array)blk.Data, blk.offset + i * blk.scanw, (System.Array)bakarr, i * w, w); - } - } - blk.Data = bakarr; - blk.offset = 0; - blk.scanw = blk.w; - return blk; - } - - /// Returns true if the data read was originally signed in the specified - /// component, false if not. This method always returns false since PPM - /// data is always unsigned. - /// - /// - /// The index of the component, from 0 to N-1. - /// - /// - /// always false, since PPM data is always unsigned. - /// - /// - public override bool isOrigSigned(int c) - { - // Check component index - if (c < 0 || c > 2) - throw new System.ArgumentException(); - return false; - } - - /// Returns a string of information about the object, more than 1 line - /// long. The information string includes information from the underlying - /// RandomAccessFile (its toString() method is called in turn). - /// - /// - /// A string of information about the object. - /// - /// - public override System.String ToString() - { - return "ImgReaderGDI: WxH = " + w + "x" + h + ", Component = 0,1,2"; - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/image/input/ImgReaderPGM.cs b/CSJ2K/j2k/image/input/ImgReaderPGM.cs deleted file mode 100644 index a7fec8ac..00000000 --- a/CSJ2K/j2k/image/input/ImgReaderPGM.cs +++ /dev/null @@ -1,519 +0,0 @@ -/* -* -* Class: ImageWriterRawPGM -* -* Description: Image writer for unsigned 8 bit data in -* PGM files. -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -namespace CSJ2K.j2k.image.input -{ - - /// This class implements the ImgData interface for reading 8 bit unsigned data - /// from a binary PGM file. - /// - ///

    After being read the coefficients are level shifted by subtracting - /// 2^(nominal bit range-1)

    - /// - ///

    The TransferType (see ImgData) of this class is TYPE_INT.

    - /// - ///

    NOTE: This class is not thread safe, for reasons of internal buffering. - /// - ///

    - /// - /// - /// - public class ImgReaderPGM : ImgReader - { - - /// DC offset value used when reading image - public static int DC_OFFSET = 128; - - /// Where to read the data from - //UPGRADE_TODO: Class 'java.io.RandomAccessFile' was converted to 'System.IO.FileStream' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioRandomAccessFile'" - private System.IO.FileStream in_Renamed; - - /// The offset of the raw pixel data in the PGM file - private int offset; - - /// The number of bits that determine the nominal dynamic range - private int rb; - - /// The line buffer. - // This makes the class not thrad safe - // (but it is not the only one making it so) - private byte[] buf; - - /// Temporary DataBlkInt object (needed when encoder uses floating-point - /// filters). This avoid allocating new DataBlk at each time - /// - private DataBlkInt intBlk; - - /// Creates a new PGM file reader from the specified file. - /// - /// - /// The input file. - /// - /// - /// If an error occurs while opening the file. - /// - /// - public ImgReaderPGM(System.IO.FileInfo file) : this(SupportClass.RandomAccessFileSupport.CreateRandomAccessFile(file, "r")) - { - } - - /// Creates a new PGM file reader from the specified file name. - /// - /// - /// The input file name. - /// - /// - /// If an error occurs while opening the file. - /// - /// - public ImgReaderPGM(System.String fname) : this(SupportClass.RandomAccessFileSupport.CreateRandomAccessFile(fname, "r")) - { - } - - /// Creates a new PGM file reader from the specified RandomAccessFile - /// object. The file header is read to acquire the image size. - /// - /// - /// From where to read the data - /// - /// - /// if an EOF is read - /// - /// if an error occurs when opening the file - /// - /// - //UPGRADE_TODO: Class 'java.io.RandomAccessFile' was converted to 'System.IO.FileStream' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioRandomAccessFile'" - public ImgReaderPGM(System.IO.FileStream in_Renamed) - { - this.in_Renamed = in_Renamed; - - confirmFileType(); - skipCommentAndWhiteSpace(); - this.w = readHeaderInt(); - skipCommentAndWhiteSpace(); - this.h = readHeaderInt(); - skipCommentAndWhiteSpace(); - /*Read the highest pixel value from header (not used)*/ - readHeaderInt(); - this.nc = 1; - this.rb = 8; - } - - - /// Closes the underlying RandomAccessFile from where the image data is - /// being read. No operations are possible after a call to this method. - /// - /// - /// If an I/O error occurs. - /// - /// - public override void close() - { - in_Renamed.Close(); - in_Renamed = null; - } - - /// Returns the number of bits corresponding to the nominal range of the - /// data in the specified component. This is the value rb (range bits) that - /// was specified in the constructor, which normally is 8 for non bilevel - /// data, and 1 for bilevel data. - /// - ///

    If this number is b then the nominal range is between - /// -2^(b-1) and 2^(b-1)-1, since unsigned data is level shifted to have a - /// nominal average of 0. - /// - ///

    - /// The index of the component. - /// - /// - /// The number of bits corresponding to the nominal range of the - /// data. Fro floating-point data this value is not applicable and the - /// return value is undefined. - /// - /// - public override int getNomRangeBits(int c) - { - // Check component index - if (c != 0) - throw new System.ArgumentException(); - - return rb; - } - - - /// Returns the position of the fixed point in the specified component - /// (i.e. the number of fractional bits), which is always 0 for this - /// ImgReader. - /// - /// - /// The index of the component. - /// - /// - /// The position of the fixed-point (i.e. the number of fractional - /// bits). Always 0 for this ImgReader. - /// - /// - public override int getFixedPoint(int c) - { - // Check component index - if (c != 0) - throw new System.ArgumentException(); - return 0; - } - - - /// Returns, in the blk argument, the block of image data containing the - /// specifed rectangular area, in the specified component. The data is - /// returned, as a reference to the internal data, if any, instead of as a - /// copy, therefore the returned data should not be modified. - /// - ///

    After being read the coefficients are level shifted by subtracting - /// 2^(nominal bit range - 1) - /// - ///

    The rectangular area to return is specified by the 'ulx', 'uly', 'w' - /// and 'h' members of the 'blk' argument, relative to the current - /// tile. These members are not modified by this method. The 'offset' and - /// 'scanw' of the returned data can be arbitrary. See the 'DataBlk' class. - /// - ///

    If the data array in blk is null, then a new one - /// is created if necessary. The implementation of this interface may - /// choose to return the same array or a new one, depending on what is more - /// efficient. Therefore, the data array in blk prior to the - /// method call should not be considered to contain the returned data, a - /// new array may have been created. Instead, get the array from - /// blk after the method has returned. - /// - ///

    The returned data always has its 'progressive' attribute unset - /// (i.e. false). - /// - ///

    When an I/O exception is encountered the JJ2KExceptionHandler is - /// used. The exception is passed to its handleException method. The action - /// that is taken depends on the action that has been registered in - /// JJ2KExceptionHandler. See JJ2KExceptionHandler for details. - /// - ///

    - /// Its coordinates and dimensions specify the area to - /// return. Some fields in this object are modified to return the data. - /// - /// - /// The index of the component from which to get the data. Only 0 - /// is valid. - /// - /// - /// The requested DataBlk - /// - /// - /// - /// - /// - /// - /// - /// - public override DataBlk getInternCompData(DataBlk blk, int c) - { - int k, j, i, mi; - int[] barr; - - // Check component index - if (c != 0) - throw new System.ArgumentException(); - - // Check type of block provided as an argument - if (blk.DataType != DataBlk.TYPE_INT) - { - if (intBlk == null) - intBlk = new DataBlkInt(blk.ulx, blk.uly, blk.w, blk.h); - else - { - intBlk.ulx = blk.ulx; - intBlk.uly = blk.uly; - intBlk.w = blk.w; - intBlk.h = blk.h; - } - blk = intBlk; - } - - // Get data array - barr = (int[])blk.Data; - if (barr == null || barr.Length < blk.w * blk.h) - { - barr = new int[blk.w * blk.h]; - blk.Data = barr; - } - - // Check line buffer - if (buf == null || buf.Length < blk.w) - { - buf = new byte[blk.w]; - } - - try - { - // Read line by line - mi = blk.uly + blk.h; - for (i = blk.uly; i < mi; i++) - { - // Reposition in input - in_Renamed.Seek(offset + i * w + blk.ulx, System.IO.SeekOrigin.Begin); - in_Renamed.Read(buf, 0, blk.w); - for (k = (i - blk.uly) * blk.w + blk.w - 1, j = blk.w - 1; j >= 0; j--, k--) - { - barr[k] = (((int)buf[j]) & 0xFF) - DC_OFFSET; - } - } - } - catch (System.IO.IOException e) - { - JJ2KExceptionHandler.handleException(e); - } - - // Turn off the progressive attribute - blk.progressive = false; - // Set buffer attributes - blk.offset = 0; - blk.scanw = blk.w; - return blk; - } - - /// Returns, in the blk argument, a block of image data containing the - /// specifed rectangular area, in the specified component. The data is - /// returned, as a copy of the internal data, therefore the returned data - /// can be modified "in place". - /// - ///

    After being read the coefficients are level shifted by subtracting - /// 2^(nominal bit range - 1) - /// - ///

    The rectangular area to return is specified by the 'ulx', 'uly', 'w' - /// and 'h' members of the 'blk' argument, relative to the current - /// tile. These members are not modified by this method. The 'offset' of - /// the returned data is 0, and the 'scanw' is the same as the block's - /// width. See the 'DataBlk' class. - /// - ///

    If the data array in 'blk' is 'null', then a new one is created. If - /// the data array is not 'null' then it is reused, and it must be large - /// enough to contain the block's data. Otherwise an 'ArrayStoreException' - /// or an 'IndexOutOfBoundsException' is thrown by the Java system. - /// - ///

    The returned data has its 'progressive' attribute unset - /// (i.e. false). - /// - ///

    This method just calls 'getInternCompData(blk, n)'. - /// - ///

    When an I/O exception is encountered the JJ2KExceptionHandler is - /// used. The exception is passed to its handleException method. The action - /// that is taken depends on the action that has been registered in - /// JJ2KExceptionHandler. See JJ2KExceptionHandler for details. - /// - ///

    - /// Its coordinates and dimensions specify the area to - /// return. If it contains a non-null data array, then it must have the - /// correct dimensions. If it contains a null data array a new one is - /// created. The fields in this object are modified to return the data. - /// - /// - /// The index of the component from which to get the data. Only 0 - /// is valid. - /// - /// - /// The requested DataBlk - /// - /// - /// - /// - /// - /// - /// - /// - public override DataBlk getCompData(DataBlk blk, int c) - { - return getInternCompData(blk, c); - } - - /// Returns a byte read from the RandomAccessIO. The number of read byted - /// are counted to keep track of the offset of the pixel data in the PGM - /// file - /// - /// - /// One byte read from the header of the PGM file. - /// - /// - /// If an I/O error occurs. - /// - /// - /// If an EOF is read - /// - /// - private byte countedByteRead() - { - offset++; - return (byte)in_Renamed.ReadByte(); - } - - /// Checks that the RandomAccessIO begins with 'P5' - /// - /// - /// If an I/O error occurs. - /// - /// If an EOF is read - /// - /// - private void confirmFileType() - { - byte[] type = new byte[] { 80, 53 }; // 'P5' - int i; - byte b; - - for (i = 0; i < 2; i++) - { - b = countedByteRead(); - if (b != type[i]) - { - if (i == 1 && b == 50) - { - //i.e 'P2' - throw new System.ArgumentException("JJ2000 does not support" + " ascii-PGM files. Use " + " raw-PGM file instead. "); - } - else - { - throw new System.ArgumentException("Not a raw-PGM file"); - } - } - } - } - - /// Skips any line in the header starting with '#' and any space, tab, line - /// feed or carriage return. - /// - /// - /// If an I/O error occurs. - /// - /// if an EOF is read - /// - /// - private void skipCommentAndWhiteSpace() - { - - bool done = false; - byte b; - - while (!done) - { - b = countedByteRead(); - if (b == 35) - { - // Comment start - while (b != 10 && b != 13) - { - // Comment ends in end of line - b = countedByteRead(); - } - } - else if (!(b == 9 || b == 10 || b == 13 || b == 32)) - { - // If not whitespace - done = true; - } - } - // Put last valid byte in - offset--; - in_Renamed.Seek(offset, System.IO.SeekOrigin.Begin); - } - - - /// Returns an int read from the header of the PGM file. - /// - /// - /// One int read from the header of the PGM file. - /// - /// - /// If an I/O error occurs. - /// - /// If an EOF is read - /// - /// - private int readHeaderInt() - { - int res = 0; - byte b = 0; - - b = countedByteRead(); - while (b != 32 && b != 10 && b != 9 && b != 13) - { - // While not whitespace - res = res * 10 + b - 48; // Covert ASCII to numerical value - b = countedByteRead(); - } - return res; - } - - /// Returns true if the data read was originally signed in the specified - /// component, false if not. This method returns always false since PGM - /// data is always unsigned. - /// - /// - /// The index of the component, from 0 to N-1. - /// - /// - /// always false, since PGM data is always unsigned. - /// - /// - public override bool isOrigSigned(int c) - { - // Check component index - if (c != 0) - throw new System.ArgumentException(); - return false; - } - - /// Returns a string of information about the object, more than 1 line - /// long. The information string includes information from the underlying - /// RandomAccessIO (its toString() method is called in turn). - /// - /// - /// A string of information about the object. - /// - /// - public override System.String ToString() - { - //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Object.toString' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" - return "ImgReaderPGM: WxH = " + w + "x" + h + ", Component = 0" + "\nUnderlying RandomAccessIO:\n" + in_Renamed.ToString(); - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/image/input/ImgReaderPGX.cs b/CSJ2K/j2k/image/input/ImgReaderPGX.cs deleted file mode 100644 index 0b209366..00000000 --- a/CSJ2K/j2k/image/input/ImgReaderPGX.cs +++ /dev/null @@ -1,667 +0,0 @@ -/* -* CVS identifier: -* -* $Id: ImgReaderPGX.java,v 1.13 2002/07/25 15:08:13 grosbois Exp $ -* -* Class: ImgReaderPGX -* -* Description: Image Reader for PGX files (custom file format -* for VM3A) -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.io; -namespace CSJ2K.j2k.image.input -{ - - /// This class extends the ImgReader abstract class for reading PGX files. PGX - /// is a custom monochrome file format invented specifically to simplify the - /// use of JPEG 2000 with images of different bit-depths in the range 1 to 31 - /// bits per pixel. - /// - ///

    The file consists of a one line text header followed by the data.

    - /// - ///

    - /// Header: "PG"+ ws +<endianess>+ ws - /// +[sign]+ws + <bit-depth>+" - /// "+<width>+" "+<height>+'\n'

    - /// - ///

    where:
    - ///

      - ///
    • ws (white-spaces) is any combination of characters ' ' and - /// '\t'.
    • - ///
    • endianess equals "LM" or "ML"(resp. little-endian or - /// big-endian)
    • - ///
    • sign equals "+" or "-" (resp. unsigned or signed). If omited, - /// values are supposed to be unsigned.
    • - ///
    • bit-depth that can be any number between 1 and 31.
    • - ///
    • width and height are the image dimensions (in - /// pixels).
    • - ///
    - /// - /// Data: The image binary values appear one after the other (in raster - /// order) immediately after the last header character ('\n') and are - /// byte-aligned (they are packed into 1,2 or 4 bytes per sample, depending - /// upon the bit-depth value). - ///

    - /// - ///

    If the data is unisigned, level shifting is applied subtracting - /// 2^(bitdepth - 1)

    - /// - ///

    Since it is not possible to know the input file byte-ordering before - /// reading its header, this class can not be construct from a - /// RandomAccessIO. So, the constructor has to open first the input file, to - /// read only its header, and then it can create the appropriate - /// BufferedRandomAccessFile (Big-Endian or Little-Endian byte-ordering).

    - /// - ///

    NOTE: This class is not thread safe, for reasons of internal - /// buffering.

    - /// - ///
    - /// - /// - /// - /// - /// - /// - /// - /// - /// - public class ImgReaderPGX : ImgReader, EndianType - { - - /// The offset of the raw pixel data in the PGX file - private int offset; - - /// The RandomAccessIO where to get datas from - //UPGRADE_TODO: Class 'java.io.RandomAccessFile' was converted to 'System.IO.FileStream' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioRandomAccessFile'" - private System.IO.FileStream in_Renamed; - - /// The bit-depth of the input file (must be between 1 and 31) - private int bitDepth; - - /// Whether the input datas are signed or not - private bool isSigned; - - - /// The pack length of one sample (in bytes, according to the output - /// bit-depth - /// - private int packBytes; - - /// The byte ordering to use, as defined in EndianType - private int byteOrder; - - /// The line buffer. - // This makes the class not thrad safe - // (but it is not the only one making it so) - private byte[] buf; - - /// Temporary DataBlkInt object (needed when encoder uses floating-point - /// filters). This avoid allocating new DataBlk at each time - /// - private DataBlkInt intBlk; - - /// Creates a new PGX file reader from the specified File object. - /// - /// - /// The input file as File object. - /// - /// - /// If an I/O error occurs. - /// - /// - public ImgReaderPGX(System.IO.FileInfo in_Renamed) - { - System.String header; - - // Check if specified file exists - bool tmpBool; - if (System.IO.File.Exists(in_Renamed.FullName)) - tmpBool = true; - else - tmpBool = System.IO.Directory.Exists(in_Renamed.FullName); - if (!tmpBool) - { - throw new System.ArgumentException("PGX file " + in_Renamed.Name + " does not exist"); - } - - //Opens the given file - this.in_Renamed = SupportClass.RandomAccessFileSupport.CreateRandomAccessFile(in_Renamed, "r"); - try - { - System.IO.StreamReader in_reader = new System.IO.StreamReader(this.in_Renamed); - //UPGRADE_ISSUE: Method 'java.io.RandomAccessFile.readLine' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javaioRandomAccessFilereadLine'" - header = in_reader.ReadLine(); - } - catch (System.IO.IOException) - { - throw new System.IO.IOException(in_Renamed.Name + " is not a PGX file"); - } - if (header == null) - { - throw new System.IO.IOException(in_Renamed.Name + " is an empty file"); - } - offset = (header.Length + 1); - - //Get informations from header - SupportClass.Tokenizer st = new SupportClass.Tokenizer(header); - try - { - int nTokens = st.Count; - - // Magic Number - if (!(st.NextToken()).Equals("PG")) - throw new System.IO.IOException(in_Renamed.Name + " is not a PGX file"); - - // Endianess - System.String tmp = st.NextToken(); - if (tmp.Equals("LM")) - byteOrder = CSJ2K.j2k.io.EndianType_Fields.LITTLE_ENDIAN; - else if (tmp.Equals("ML")) - byteOrder = CSJ2K.j2k.io.EndianType_Fields.BIG_ENDIAN; - else - throw new System.IO.IOException(in_Renamed.Name + " is not a PGX file"); - - // Unsigned/signed if present in the header - if (nTokens == 6) - { - tmp = st.NextToken(); - if (tmp.Equals("+")) - isSigned = false; - else if (tmp.Equals("-")) - isSigned = true; - else - throw new System.IO.IOException(in_Renamed.Name + " is not a PGX file"); - } - - // bit-depth, width, height - try - { - bitDepth = (System.Int32.Parse(st.NextToken())); - // bitDepth must be between 1 and 31 - if ((bitDepth <= 0) || (bitDepth > 31)) - throw new System.IO.IOException(in_Renamed.Name + " is not a valid PGX file"); - - w = (System.Int32.Parse(st.NextToken())); - h = (System.Int32.Parse(st.NextToken())); - } - catch (System.FormatException) - { - throw new System.IO.IOException(in_Renamed.Name + " is not a PGX file"); - } - } - catch (System.ArgumentOutOfRangeException) - { - throw new System.IO.IOException(in_Renamed.Name + " is not a PGX file"); - } - - // Number of component - nc = 1; - - // Number of bytes per data - if (bitDepth <= 8) - packBytes = 1; - else if (bitDepth <= 16) - packBytes = 2; - // <= 31 - else - packBytes = 4; - } - - /// Creates a new PGX file reader from the specified file name. - /// - /// - /// The input file name. - /// - /// - public ImgReaderPGX(System.String inName) : this(new System.IO.FileInfo(inName)) - { - } - - /// Closes the underlying RandomAccessIO from where the image data is being - /// read. No operations are possible after a call to this method. - /// - /// - /// If an I/O error occurs. - /// - /// - public override void close() - { - in_Renamed.Close(); - in_Renamed = null; - buf = null; - } - - /// Returns the number of bits corresponding to the nominal range of the - /// data in the specified component. This is the value of bitDepth which is - /// read in the PGX file header. - /// - ///

    If this number is b then the nominal range is between - /// -2^(b-1) and 2^(b-1)-1, for originally signed or unsigned data - /// (unsigned data is level shifted to have a nominal average of 0). - /// - ///

    - /// The index of the component. - /// - /// - /// The number of bits corresponding to the nominal range of the - /// data. - /// - /// - public override int getNomRangeBits(int c) - { - // Check component index - if (c != 0) - throw new System.ArgumentException(); - - return bitDepth; - } - - /// Returns the position of the fixed point in the specified component - /// (i.e. the number of fractional bits), which is always 0 for this - /// ImgReader. - /// - /// - /// The index of the component. - /// - /// - /// The position of the fixed-point (i.e. the number of fractional - /// bits). Always 0 for this ImgReader. - /// - /// - public override int getFixedPoint(int c) - { - // Check component index - if (c != 0) - throw new System.ArgumentException(); - return 0; - } - - /// Returns, in the blk argument, the block of image data containing the - /// specifed rectangular area, in the specified component. The data is - /// returned, as a reference to the internal data, if any, instead of as a - /// copy, therefore the returned data should not be modified. - /// - ///

    After being read the coefficients are level shifted by subtracting - /// 2^(nominal bit range - 1)

    - /// - ///

    The rectangular area to return is specified by the 'ulx', 'uly', 'w' - /// and 'h' members of the 'blk' argument, relative to the current - /// tile. These members are not modified by this method. The 'offset' and - /// 'scanw' of the returned data can be arbitrary. See the 'DataBlk' - /// class.

    - /// - ///

    If the data array in blk is null, then a new one - /// is created if necessary. The implementation of this interface may - /// choose to return the same array or a new one, depending on what is more - /// efficient. Therefore, the data array in blk prior to the - /// method call should not be considered to contain the returned data, a - /// new array may have been created. Instead, get the array from - /// blk after the method has returned.

    - /// - ///

    The returned data always has its 'progressive' attribute unset - /// (i.e. false).

    - /// - ///

    When an I/O exception is encountered the JJ2KExceptionHandler is - /// used. The exception is passed to its handleException method. The action - /// that is taken depends on the action that has been registered in - /// JJ2KExceptionHandler. See JJ2KExceptionHandler for details.

    - /// - ///
    - /// Its coordinates and dimensions specify the area to - /// return. Some fields in this object are modified to return the data. - /// - /// - /// The index of the component from which to get the data. Only 0 - /// is valid. - /// - /// - /// The requested DataBlk - /// - /// - /// - /// - /// - /// - /// - public override DataBlk getInternCompData(DataBlk blk, int c) - { - int k, j, i, mi; // counters - int levShift = 1 << (bitDepth - 1); - - // Check component index - if (c != 0) - throw new System.ArgumentException(); - - // Check type of block provided as an argument - if (blk.DataType != DataBlk.TYPE_INT) - { - if (intBlk == null) - intBlk = new DataBlkInt(blk.ulx, blk.uly, blk.w, blk.h); - else - { - intBlk.ulx = blk.ulx; - intBlk.uly = blk.uly; - intBlk.w = blk.w; - intBlk.h = blk.h; - } - blk = intBlk; - } - - // Get data array - int[] barr = (int[])blk.Data; - if (barr == null || barr.Length < blk.w * blk.h * packBytes) - { - barr = new int[blk.w * blk.h]; - blk.Data = barr; - } - - int paddingLength = (32 - bitDepth); - if (buf == null || buf.Length < packBytes * blk.w) - { - buf = new byte[packBytes * blk.w]; - } - try - { - switch (packBytes) - { - - // Switch between one of the 3 byte packet type - case 1: // Samples packed into 1 byte - // Read line by line - mi = blk.uly + blk.h; - if (isSigned) - { - for (i = blk.uly; i < mi; i++) - { - // Reposition in input - in_Renamed.Seek(offset + i * w + blk.ulx, System.IO.SeekOrigin.Begin); - in_Renamed.Read(buf, 0, blk.w); - for (k = (i - blk.uly) * blk.w + blk.w - 1, j = blk.w - 1; j >= 0; k--) - barr[k] = (((buf[j--] & 0xFF) << paddingLength) >> paddingLength); - } - } - else - { - // Not signed - for (i = blk.uly; i < mi; i++) - { - // Reposition in input - in_Renamed.Seek(offset + i * w + blk.ulx, System.IO.SeekOrigin.Begin); - in_Renamed.Read(buf, 0, blk.w); - for (k = (i - blk.uly) * blk.w + blk.w - 1, j = blk.w - 1; j >= 0; k--) - barr[k] = (SupportClass.URShift(((buf[j--] & 0xFF) << paddingLength), paddingLength)) - levShift; - } - } - break; - - - case 2: // Samples packed into 2 bytes - // Read line by line - mi = blk.uly + blk.h; - if (isSigned) - { - for (i = blk.uly; i < mi; i++) - { - // Reposition in input - in_Renamed.Seek(offset + 2 * (i * w + blk.ulx), System.IO.SeekOrigin.Begin); - in_Renamed.Read(buf, 0, blk.w << 1); - switch (byteOrder) - { - - case CSJ2K.j2k.io.EndianType_Fields.LITTLE_ENDIAN: - for (k = (i - blk.uly) * blk.w + blk.w - 1, j = (blk.w << 1) - 1; j >= 0; k--) - { - barr[k] = ((((buf[j--] & 0xFF) << 8) | (buf[j--] & 0xFF)) << paddingLength) >> paddingLength; - } - break; - - case CSJ2K.j2k.io.EndianType_Fields.BIG_ENDIAN: - for (k = (i - blk.uly) * blk.w + blk.w - 1, j = (blk.w << 1) - 1; j >= 0; k--) - { - barr[k] = (((buf[j--] & 0xFF) | ((buf[j--] & 0xFF) << 8)) << paddingLength) >> paddingLength; - } - break; - - default: - throw new System.ApplicationException("Internal JJ2000 bug"); - - } - } - } - else - { - // If not signed - for (i = blk.uly; i < mi; i++) - { - // Reposition in input - in_Renamed.Seek(offset + 2 * (i * w + blk.ulx), System.IO.SeekOrigin.Begin); - in_Renamed.Read(buf, 0, blk.w << 1); - switch (byteOrder) - { - - case CSJ2K.j2k.io.EndianType_Fields.LITTLE_ENDIAN: - for (k = (i - blk.uly) * blk.w + blk.w - 1, j = (blk.w << 1) - 1; j >= 0; k--) - { - barr[k] = (SupportClass.URShift(((((buf[j--] & 0xFF) << 8) | (buf[j--] & 0xFF)) << paddingLength), paddingLength)) - levShift; - } - break; - - case CSJ2K.j2k.io.EndianType_Fields.BIG_ENDIAN: - for (k = (i - blk.uly) * blk.w + blk.w - 1, j = (blk.w << 1) - 1; j >= 0; k--) - { - barr[k] = (SupportClass.URShift((((buf[j--] & 0xFF) | ((buf[j--] & 0xFF) << 8)) << paddingLength), paddingLength)) - levShift; - } - break; - - default: - throw new System.ApplicationException("Internal JJ2000 bug"); - - } - } - } - break; - - - case 4: // Samples packed into 4 bytes - // Read line by line - mi = blk.uly + blk.h; - if (isSigned) - { - for (i = blk.uly; i < mi; i++) - { - // Reposition in input - in_Renamed.Seek(offset + 4 * (i * w + blk.ulx), System.IO.SeekOrigin.Begin); - in_Renamed.Read(buf, 0, blk.w << 2); - switch (byteOrder) - { - - case CSJ2K.j2k.io.EndianType_Fields.LITTLE_ENDIAN: - for (k = (i - blk.uly) * blk.w + blk.w - 1, j = (blk.w << 2) - 1; j >= 0; k--) - { - barr[k] = ((((buf[j--] & 0xFF) << 24) | ((buf[j--] & 0xFF) << 16) | ((buf[j--] & 0xFF) << 8) | (buf[j--] & 0xFF)) << paddingLength) >> paddingLength; - } - break; - - case CSJ2K.j2k.io.EndianType_Fields.BIG_ENDIAN: - for (k = (i - blk.uly) * blk.w + blk.w - 1, j = (blk.w << 2) - 1; j >= 0; k--) - { - barr[k] = (((buf[j--] & 0xFF) | ((buf[j--] & 0xFF) << 8) | ((buf[j--] & 0xFF) << 16) | ((buf[j--] & 0xFF) << 24)) << paddingLength) >> paddingLength; - } - break; - - default: - throw new System.ApplicationException("Internal JJ2000 bug"); - - } - } - } - else - { - for (i = blk.uly; i < mi; i++) - { - // Reposition in input - in_Renamed.Seek(offset + 4 * (i * w + blk.ulx), System.IO.SeekOrigin.Begin); - in_Renamed.Read(buf, 0, blk.w << 2); - switch (byteOrder) - { - - case CSJ2K.j2k.io.EndianType_Fields.LITTLE_ENDIAN: - for (k = (i - blk.uly) * blk.w + blk.w - 1, j = (blk.w << 2) - 1; j >= 0; k--) - { - barr[k] = (SupportClass.URShift(((((buf[j--] & 0xFF) << 24) | ((buf[j--] & 0xFF) << 16) | ((buf[j--] & 0xFF) << 8) | (buf[j--] & 0xFF)) << paddingLength), paddingLength)) - levShift; - } - break; - - case CSJ2K.j2k.io.EndianType_Fields.BIG_ENDIAN: - for (k = (i - blk.uly) * blk.w + blk.w - 1, j = (blk.w << 2) - 1; j >= 0; k--) - { - barr[k] = (SupportClass.URShift((((buf[j--] & 0xFF) | ((buf[j--] & 0xFF) << 8) | ((buf[j--] & 0xFF) << 16) | ((buf[j--] & 0xFF) << 24)) << paddingLength), paddingLength)) - levShift; - } - break; - - default: - throw new System.ApplicationException("Internal JJ2000 bug"); - - } - } - } - break; - - - default: - throw new System.IO.IOException("PGX supports only bit-depth between" + " 1 and 31"); - - } - } - catch (System.IO.IOException e) - { - JJ2KExceptionHandler.handleException(e); - } - - // Turn off the progressive attribute - blk.progressive = false; - // Set buffer attributes - blk.offset = 0; - blk.scanw = blk.w; - return blk; - } - - /// Returns, in the blk argument, a block of image data containing the - /// specifed rectangular area, in the specified component. The data is - /// returned, as a copy of the internal data, therefore the returned data - /// can be modified "in place". - /// - ///

    After being read the coefficients are level shifted by subtracting - /// 2^(nominal bit range - 1) - /// - ///

    The rectangular area to return is specified by the 'ulx', 'uly', 'w' - /// and 'h' members of the 'blk' argument, relative to the current - /// tile. These members are not modified by this method. The 'offset' of - /// the returned data is 0, and the 'scanw' is the same as the block's - /// width. See the 'DataBlk' class.

    - /// - ///

    If the data array in 'blk' is 'null', then a new one is created. If - /// the data array is not 'null' then it is reused, and it must be large - /// enough to contain the block's data. Otherwise an 'ArrayStoreException' - /// or an 'IndexOutOfBoundsException' is thrown by the Java system.

    - /// - ///

    The returned data has its 'progressive' attribute unset - /// (i.e. false).

    - /// - ///

    This method just calls 'getInternCompData(blk,c)'.

    - /// - ///

    When an I/O exception is encountered the JJ2KExceptionHandler is - /// used. The exception is passed to its handleException method. The action - /// that is taken depends on the action that has been registered in - /// JJ2KExceptionHandler. See JJ2KExceptionHandler for details. - /// - ///

    - /// Its coordinates and dimensions specify the area to - /// return. If it contains a non-null data array, then it must have the - /// correct dimensions. If it contains a null data array a new one is - /// created. The fields in this object are modified to return the data. - /// - /// - /// The index of the component from which to get the data. Only 0 - /// is valid. - /// - /// - /// The requested DataBlk - /// - /// - /// - /// - /// - /// - /// - public override DataBlk getCompData(DataBlk blk, int c) - { - return getInternCompData(blk, c); - } - - /// Returns true if the data read was originally signed in the specified - /// component, false if not. - /// - /// - /// The index of the component, from 0 to N-1. - /// - /// - /// true if the data was originally signed, false if not. - /// - /// - public override bool isOrigSigned(int c) - { - // Check component index - if (c != 0) - throw new System.ArgumentException(); - return isSigned; - } - - /// Returns a string of information about the object, more than 1 line - /// long. The information string includes information from the underlying - /// RandomAccessIO (its toString() method is called in turn). - /// - /// - /// A string of information about the object. - /// - /// - public override System.String ToString() - { - //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Object.toString' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" - return "ImgReaderPGX: WxH = " + w + "x" + h + ", Component = 0" + ", Bit-depth = " + bitDepth + ", signed = " + isSigned + "\nUnderlying RandomAccessIO:\n" + in_Renamed.ToString(); - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/image/input/ImgReaderPPM.cs b/CSJ2K/j2k/image/input/ImgReaderPPM.cs deleted file mode 100644 index e3487b9e..00000000 --- a/CSJ2K/j2k/image/input/ImgReaderPPM.cs +++ /dev/null @@ -1,600 +0,0 @@ -/* -* -* Class: ImgWriterPPM -* -* Description: Image writer for unsigned 8 bit data in -* PPM files. -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using System; -namespace CSJ2K.j2k.image.input -{ - - /// This class implements the ImgData interface for reading 8 bits unsigned - /// data from a binary PPM file - /// - ///

    After being read the coefficients are level shifted by subtracting - /// 2^(nominal bit range - 1) - /// - ///

    The transfer type (see ImgData) of this class is TYPE_INT. - /// - ///

    This class is buffered: the 3 input components(R,G,B) are read - /// when the first one (R) is asked. The 2 others are stored until they are - /// needed. - /// - ///

    NOTE: This class is not thread safe, for reasons of internal buffering. - /// - ///

    - /// - /// - /// - public class ImgReaderPPM : ImgReader - { - - /// DC offset value used when reading image - public static int DC_OFFSET = 128; - - /// Where to read the data from - //UPGRADE_TODO: Class 'java.io.RandomAccessFile' was converted to 'System.IO.FileStream' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioRandomAccessFile'" - private System.IO.FileStream in_Renamed; - - /// The offset of the raw pixel data in the PPM file - private int offset; - - /// The number of bits that determine the nominal dynamic range - private int rb; - - /// Buffer for the 3 components of each pixel(in the current block) - private int[][] barr = new int[3][]; - - /// Data block used only to store coordinates of the buffered blocks - private DataBlkInt dbi = new DataBlkInt(); - - /// The line buffer. - // This makes the class not thread safe (but it is not the only one making - // it so) - private byte[] buf; - - /// Temporary DataBlkInt object (needed when encoder uses floating-point - /// filters). This avoid allocating new DataBlk at each time - /// - private DataBlkInt intBlk; - - /// Creates a new PPM file reader from the specified file. - /// - /// - /// The input file. - /// - /// - /// If an error occurs while opening the file. - /// - /// - public ImgReaderPPM(System.IO.FileInfo file) : this(SupportClass.RandomAccessFileSupport.CreateRandomAccessFile(file, "r")) - { - } - - /// Creates a new PPM file reader from the specified file name. - /// - /// - /// The input file name. - /// - /// - /// If an error occurs while opening the file. - /// - /// - public ImgReaderPPM(System.String fname) : this(SupportClass.RandomAccessFileSupport.CreateRandomAccessFile(fname, "r")) - { - } - - /// Creates a new PPM file reader from the specified RandomAccessFile - /// object. The file header is read to acquire the image size. - /// - /// - /// From where to read the data - /// - /// - /// if an EOF is read - /// - /// if an error occurs when opening the file - /// - /// - //UPGRADE_TODO: Class 'java.io.RandomAccessFile' was converted to 'System.IO.FileStream' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioRandomAccessFile'" - private ImgReaderPPM(System.IO.FileStream in_Renamed) - { - this.in_Renamed = in_Renamed; - - confirmFileType(); - skipCommentAndWhiteSpace(); - w = readHeaderInt(); - skipCommentAndWhiteSpace(); - h = readHeaderInt(); - skipCommentAndWhiteSpace(); - /*Read the highest pixel value from header (not used)*/ - readHeaderInt(); - nc = 3; - rb = 8; - } - - /// Closes the underlying file from where the image data is being read. No - /// operations are possible after a call to this method. - /// - /// - /// If an I/O error occurs. - /// - /// - public override void close() - { - in_Renamed.Close(); - in_Renamed = null; - // Free memory - barr[0] = null; - barr[1] = null; - barr[2] = null; - buf = null; - } - - - /// Returns the number of bits corresponding to the nominal range of the - /// data in the specified component. This is the value rb (range bits) that - /// was specified in the constructor, which normally is 8 for non bilevel - /// data, and 1 for bilevel data. - /// - ///

    If this number is b then the nominal range is between - /// -2^(b-1) and 2^(b-1)-1, since unsigned data is level shifted to have a - /// nominal avergae of 0. - /// - ///

    - /// The index of the component. - /// - /// - /// The number of bits corresponding to the nominal range of the - /// data. For floating-point data this value is not applicable and the - /// return value is undefined. - /// - /// - public override int getNomRangeBits(int c) - { - // Check component index - if (c < 0 || c > 2) - throw new System.ArgumentException(); - - return rb; - } - - /// Returns the position of the fixed point in the specified component - /// (i.e. the number of fractional bits), which is always 0 for this - /// ImgReader. - /// - /// - /// The index of the component. - /// - /// - /// The position of the fixed-point (i.e. the number of fractional - /// bits). Always 0 for this ImgReader. - /// - /// - public override int getFixedPoint(int c) - { - // Check component index - if (c < 0 || c > 2) - throw new System.ArgumentException(); - return 0; - } - - - /// Returns, in the blk argument, the block of image data containing the - /// specifed rectangular area, in the specified component. The data is - /// returned, as a reference to the internal data, if any, instead of as a - /// copy, therefore the returned data should not be modified. - /// - ///

    After being read the coefficients are level shifted by subtracting - /// 2^(nominal bit range - 1) - /// - ///

    The rectangular area to return is specified by the 'ulx', 'uly', 'w' - /// and 'h' members of the 'blk' argument, relative to the current - /// tile. These members are not modified by this method. The 'offset' and - /// 'scanw' of the returned data can be arbitrary. See the 'DataBlk' class. - /// - ///

    If the data array in blk is null, then a new one - /// is created if necessary. The implementation of this interface may - /// choose to return the same array or a new one, depending on what is more - /// efficient. Therefore, the data array in blk prior to the - /// method call should not be considered to contain the returned data, a - /// new array may have been created. Instead, get the array from - /// blk after the method has returned. - /// - ///

    The returned data always has its 'progressive' attribute unset - /// (i.e. false). - /// - ///

    When an I/O exception is encountered the JJ2KExceptionHandler is - /// used. The exception is passed to its handleException method. The action - /// that is taken depends on the action that has been registered in - /// JJ2KExceptionHandler. See JJ2KExceptionHandler for details. - /// - ///

    This method implements buffering for the 3 components: When the - /// first one is asked, all the 3 components are read and stored until they - /// are needed. - /// - ///

    - /// Its coordinates and dimensions specify the area to - /// return. Some fields in this object are modified to return the data. - /// - /// - /// The index of the component from which to get the data. Only 0, - /// 1 and 3 are valid. - /// - /// - /// The requested DataBlk - /// - /// - /// - /// - /// - /// - /// - /// - public override DataBlk getInternCompData(DataBlk blk, int c) - { - // Check component index - if (c < 0 || c > 2) - throw new System.ArgumentException(); - - // Check type of block provided as an argument - if (blk.DataType != DataBlk.TYPE_INT) - { - if (intBlk == null) - intBlk = new DataBlkInt(blk.ulx, blk.uly, blk.w, blk.h); - else - { - intBlk.ulx = blk.ulx; - intBlk.uly = blk.uly; - intBlk.w = blk.w; - intBlk.h = blk.h; - } - blk = intBlk; - } - - // If asking a component for the first time for this block, read the 3 - // components - if ((barr[c] == null) || (dbi.ulx > blk.ulx) || (dbi.uly > blk.uly) || (dbi.ulx + dbi.w < blk.ulx + blk.w) || (dbi.uly + dbi.h < blk.uly + blk.h)) - { - int k, j, i, mi; - int[] red, green, blue; - - // Reset data arrays if needed - if (barr[c] == null || barr[c].Length < blk.w * blk.h) - { - barr[c] = new int[blk.w * blk.h]; - } - blk.Data = barr[c]; - - i = (c + 1) % 3; - if (barr[i] == null || barr[i].Length < blk.w * blk.h) - { - barr[i] = new int[blk.w * blk.h]; - } - i = (c + 2) % 3; - if (barr[i] == null || barr[i].Length < blk.w * blk.h) - { - barr[i] = new int[blk.w * blk.h]; - } - - // set attributes of the DataBlk used for buffering - dbi.ulx = blk.ulx; - dbi.uly = blk.uly; - dbi.w = blk.w; - dbi.h = blk.h; - - // Check line buffer - if (buf == null || buf.Length < 3 * blk.w) - { - buf = new byte[3 * blk.w]; - } - - red = barr[0]; - green = barr[1]; - blue = barr[2]; - - try - { - // Read line by line - mi = blk.uly + blk.h; - for (i = blk.uly; i < mi; i++) - { - // Reposition in input offset takes care of - // header offset - in_Renamed.Seek(offset + i * 3 * w + 3 * blk.ulx, System.IO.SeekOrigin.Begin); - in_Renamed.Read(buf, 0, 3 * blk.w); - - for (k = (i - blk.uly) * blk.w + blk.w - 1, j = 3 * blk.w - 1; j >= 0; k--) - { - // Read every third sample - blue[k] = (((byte)buf[j--]) & 0xFF) - DC_OFFSET; - green[k] = (((byte)buf[j--]) & 0xFF) - DC_OFFSET; - red[k] = (((byte)buf[j--]) & 0xFF) - DC_OFFSET; - } - } - } - catch (System.IO.IOException e) - { - JJ2KExceptionHandler.handleException(e); - } - barr[0] = red; - barr[1] = green; - barr[2] = blue; - - // Set buffer attributes - blk.Data = barr[c]; - blk.offset = 0; - blk.scanw = blk.w; - } - else - { - //Asking for the 2nd or 3rd block component - blk.Data = barr[c]; - blk.offset = (blk.ulx - dbi.ulx) * dbi.w + blk.ulx - dbi.ulx; - blk.scanw = dbi.scanw; - } - - // Turn off the progressive attribute - blk.progressive = false; - return blk; - } - - /// Returns, in the blk argument, a block of image data containing the - /// specifed rectangular area, in the specified component. The data is - /// returned, as a copy of the internal data, therefore the returned data - /// can be modified "in place". - /// - ///

    After being read the coefficients are level shifted by subtracting - /// 2^(nominal bit range - 1) - /// - ///

    The rectangular area to return is specified by the 'ulx', 'uly', 'w' - /// and 'h' members of the 'blk' argument, relative to the current - /// tile. These members are not modified by this method. The 'offset' of - /// the returned data is 0, and the 'scanw' is the same as the block's - /// width. See the 'DataBlk' class. - /// - ///

    If the data array in 'blk' is 'null', then a new one is created. If - /// the data array is not 'null' then it is reused, and it must be large - /// enough to contain the block's data. Otherwise an 'ArrayStoreException' - /// or an 'IndexOutOfBoundsException' is thrown by the Java system. - /// - ///

    The returned data has its 'progressive' attribute unset - /// (i.e. false). - /// - ///

    When an I/O exception is encountered the JJ2KExceptionHandler is - /// used. The exception is passed to its handleException method. The action - /// that is taken depends on the action that has been registered in - /// JJ2KExceptionHandler. See JJ2KExceptionHandler for details. - /// - ///

    - /// Its coordinates and dimensions specify the area to - /// return. If it contains a non-null data array, then it must have the - /// correct dimensions. If it contains a null data array a new one is - /// created. The fields in this object are modified to return the data. - /// - /// - /// The index of the component from which to get the data. Only - /// 0,1 and 2 are valid. - /// - /// - /// The requested DataBlk - /// - /// - /// - /// - /// - /// - /// - /// - public override DataBlk getCompData(DataBlk blk, int c) - { - // NOTE: can not directly call getInterCompData since that returns - // internally buffered data. - int ulx, uly, w, h; - - // Check type of block provided as an argument - if (blk.DataType != DataBlk.TYPE_INT) - { - DataBlkInt tmp = new DataBlkInt(blk.ulx, blk.uly, blk.w, blk.h); - blk = tmp; - } - - int[] bakarr = (int[])blk.Data; - // Save requested block size - ulx = blk.ulx; - uly = blk.uly; - w = blk.w; - h = blk.h; - // Force internal data buffer to be different from external - blk.Data = null; - getInternCompData(blk, c); - // Copy the data - if (bakarr == null) - { - bakarr = new int[w * h]; - } - if (blk.offset == 0 && blk.scanw == w) - { - // Requested and returned block buffer are the same size - // CONVERSION PROBLEM? - Array.Copy((System.Array)blk.Data, 0, (System.Array)bakarr, 0, w * h); - } - else - { - // Requested and returned block are different - for (int i = h - 1; i >= 0; i--) - { - // copy line by line - // CONVERSION PROBLEM? - Array.Copy((System.Array)blk.Data, blk.offset + i * blk.scanw, (System.Array)bakarr, i * w, w); - } - } - blk.Data = bakarr; - blk.offset = 0; - blk.scanw = blk.w; - return blk; - } - - /// Returns a byte read from the RandomAccessFile. The number of read byted - /// are counted to keep track of the offset of the pixel data in the PPM - /// file - /// - /// - /// One byte read from the header of the PPM file. - /// - /// - private byte countedByteRead() - { - offset++; - return (byte)in_Renamed.ReadByte(); - } - - /// Checks that the file begins with 'P6' - /// - /// - private void confirmFileType() - { - byte[] type = new byte[] { 80, 54 }; - int i; - byte b; - - for (i = 0; i < 2; i++) - { - b = countedByteRead(); - if (b != type[i]) - { - if (i == 1 && b == 51) - { - // i.e 'P3' - throw new System.ArgumentException("JJ2000 does not support" + " ascii-PPM files. Use " + " raw-PPM file instead. "); - } - else - { - throw new System.ArgumentException("Not a raw-PPM file"); - } - } - } - } - - /// Skips any line in the header starting with '#' and any space, tab, line - /// feed or carriage return. - /// - /// - private void skipCommentAndWhiteSpace() - { - - bool done = false; - byte b; - - while (!done) - { - b = countedByteRead(); - if (b == 35) - { - // Comment start - while (b != 10 && b != 13) - { - // While not comment end (end-of-line) - b = countedByteRead(); - } - } - else if (!(b == 9 || b == 10 || b == 13 || b == 32)) - { - // If not whitespace - done = true; - } - } - // Put back last valid byte - offset--; - in_Renamed.Seek(offset, System.IO.SeekOrigin.Begin); - } - - /// Returns an int read from the header of the PPM file. - /// - /// - /// One int read from the header of the PPM file. - /// - /// - private int readHeaderInt() - { - int res = 0; - byte b = 0; - - b = countedByteRead(); - while (b != 32 && b != 10 && b != 9 && b != 13) - { - // While not whitespace - res = res * 10 + b - 48; // Convert from ASCII to decimal - b = countedByteRead(); - } - return res; - } - - /// Returns true if the data read was originally signed in the specified - /// component, false if not. This method always returns false since PPM - /// data is always unsigned. - /// - /// - /// The index of the component, from 0 to N-1. - /// - /// - /// always false, since PPM data is always unsigned. - /// - /// - public override bool isOrigSigned(int c) - { - // Check component index - if (c < 0 || c > 2) - throw new System.ArgumentException(); - return false; - } - - /// Returns a string of information about the object, more than 1 line - /// long. The information string includes information from the underlying - /// RandomAccessFile (its toString() method is called in turn). - /// - /// - /// A string of information about the object. - /// - /// - public override System.String ToString() - { - //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Object.toString' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" - return "ImgReaderPPM: WxH = " + w + "x" + h + ", Component = 0,1,2" + "\nUnderlying RandomAccessFile:\n" + in_Renamed.ToString(); - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/image/invcomptransf/InvCompTransf.cs b/CSJ2K/j2k/image/invcomptransf/InvCompTransf.cs deleted file mode 100644 index 2a2bca98..00000000 --- a/CSJ2K/j2k/image/invcomptransf/InvCompTransf.cs +++ /dev/null @@ -1,809 +0,0 @@ -/* -* CVS Identifier: -* -* $Id: InvCompTransf.java,v 1.19 2001/10/29 20:06:35 qtxjoas Exp $ -* -* Class: InvCompTransf -* -* Description: Inverse Component transformations applied to tiles -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.decoder; -using CSJ2K.j2k.util; -using CSJ2K.j2k.wavelet.synthesis; -using System; -namespace CSJ2K.j2k.image.invcomptransf -{ - - /// This class apply inverse component transformations to the tiles depending - /// on specification read from the codestream header. These transformations can - /// be used to improve compression efficiency but are not related to colour - /// transforms used to map colour values for display purposes. JPEG 2000 part I - /// defines 2 component transformations: RCT (Reversible Component - /// Transformation) and ICT (Irreversible Component Transformation). - /// - /// - /// - /// - /// - public class InvCompTransf : ImgDataAdapter, BlkImgDataSrc - { - /// Returns the parameters that are used in this class and implementing - /// classes. It returns a 2D String array. Each of the 1D arrays is for a - /// different option, and they have 4 elements. The first element is the - /// option name, the second one is the synopsis, the third one is a long - /// description of what the parameter is and the fourth is its default - /// value. The synopsis or description may be 'null', in which case it is - /// assumed that there is no synopsis or description of the option, - /// respectively. Null may be returned if no options are supported. - /// - /// - /// the options name, their synopsis and their explanation, - /// or null if no options are supported. - /// - /// - public static System.String[][] ParameterInfo - { - get - { - return pinfo; - } - - } - /// Returns true if this transform is reversible in current - /// tile. Reversible component transformations are those which operation - /// can be completely reversed without any loss of information (not even - /// due to rounding). - /// - /// - /// Reversibility of component transformation in current - /// tile - /// - /// - virtual public bool Reversible - { - get - { - switch (transfType) - { - - case NONE: - case INV_RCT: - return true; - - case INV_ICT: - return false; - - default: - throw new System.ArgumentException("Non JPEG 2000 part I" + " component transformation"); - - } - } - - } - - /// Identifier for no component transformation. Value is 0. - public const int NONE = 0; - - /// The prefix for inverse component transformation options: 'M' - public const char OPT_PREFIX = 'M'; - - /// The list of parameters that is accepted by the inverse - /// component transformation module. They start with 'M'. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'pinfo'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly System.String[][] pinfo = null; - - /// Identifier for the Inverse Reversible Component Transformation - /// (INV_RCT). Value is 1. - /// - public const int INV_RCT = 1; - - /// Identifier for the Inverse Irreversible Component - /// Transformation (INV_ICT). Value is 2 - /// - public const int INV_ICT = 2; - - /// The source of image data - private BlkImgDataSrc src; - - /// The component transformations specifications - private CompTransfSpec cts; - - /// The wavelet filter specifications - private SynWTFilterSpec wfs; - - /// The type of the current component transformation JPEG 2000 - /// part I only support NONE, FORW_RCT and FORW_ICT types - /// - private int transfType = NONE; - - /// Buffer for each component of output data - private int[][] outdata = new int[3][]; - - /// Block used to request component 0 - private DataBlk block0; - - /// Block used to request component 1 - private DataBlk block1; - - /// Block used to request component 2 - private DataBlk block2; - - /// Data block used only to store coordinates and progressiveness - /// of the buffered blocks - /// - private DataBlkInt dbi = new DataBlkInt(); - - /// The bit-depths of un-transformed components - private int[] utdepth; - - /// Flag indicating whether the decoder should skip the component - /// transform - /// - private bool noCompTransf = false; - - /// Constructs a new ForwCompTransf object that operates on the - /// specified source of image data. - /// - /// - /// The source from where to get the data to be - /// transformed - /// - /// - /// The decoder specifications - /// - /// - /// The bit depth of the un-transformed components - /// - /// - /// The command line optinons of the decoder - /// - /// - /// - /// - /// - public InvCompTransf(BlkImgDataSrc imgSrc, DecoderSpecs decSpec, int[] utdepth, ParameterList pl) : base(imgSrc) - { - this.cts = decSpec.cts; - this.wfs = decSpec.wfs; - src = imgSrc; - this.utdepth = utdepth; - noCompTransf = !(pl.getBooleanParameter("comp_transf")); - } - - /// Returns a string with a descriptive text of which inverse component - /// transformation is used. This can be either "Inverse RCT" or "Inverse - /// ICT" or "No component transformation" depending on the current tile. - /// - /// - /// A descriptive string - /// - /// - public override System.String ToString() - { - switch (transfType) - { - - case INV_RCT: - return "Inverse RCT"; - - case INV_ICT: - return "Inverse ICT"; - - case NONE: - return "No component transformation"; - - default: - throw new System.ArgumentException("Non JPEG 2000 part I" + " component transformation"); - - } - } - - /// Returns the position of the fixed point in the specified - /// component. This is the position of the least significant integral - /// (i.e. non-fractional) bit, which is equivalent to the number of - /// fractional bits. For instance, for fixed-point values with 2 fractional - /// bits, 2 is returned. For floating-point data this value does not apply - /// and 0 should be returned. Position 0 is the position of the least - /// significant bit in the data. - /// - ///

    This default implementation assumes that the number of fractional - /// bits is not modified by the component mixer. - /// - ///

    - /// The index of the component. - /// - /// - /// The value of the fixed point position of the source since the - /// color transform does not affect it. - /// - /// - public virtual int getFixedPoint(int c) - { - return src.getFixedPoint(c); - } - - /// Calculates the bitdepths of the transformed components, given the - /// bitdepth of the un-transformed components and the component - /// tranformation type. - /// - /// - /// The bitdepth of each un-transformed component - /// - /// - /// The type ID of the inverse component tranformation - /// - /// - /// If not null the results are stored in this - /// array, otherwise a new array is allocated and returned. - /// - /// - /// The bitdepth of each transformed component. - /// - /// - public static int[] calcMixedBitDepths(int[] utdepth, int ttype, int[] tdepth) - { - - if (utdepth.Length < 3 && ttype != NONE) - { - throw new System.ArgumentException(); - } - - if (tdepth == null) - { - tdepth = new int[utdepth.Length]; - } - - switch (ttype) - { - - case NONE: - Array.Copy(utdepth, 0, tdepth, 0, utdepth.Length); - break; - - case INV_RCT: - if (utdepth.Length > 3) - { - Array.Copy(utdepth, 3, tdepth, 3, utdepth.Length - 3); - } - // The formulas are: - // tdepth[0] = ceil(log2(2^(utdepth[0])+2^utdepth[1]+ - // 2^(utdepth[2])))-2+1 - // tdepth[1] = ceil(log2(2^(utdepth[0])+2^(utdepth[1])-1))+1 - // tdepth[2] = ceil(log2(2^(utdepth[1])+2^(utdepth[2])-1))+1 - // The MathUtil.log2(x) function calculates floor(log2(x)), so we - // use 'MathUtil.log2(2*x-1)+1', which calculates ceil(log2(x)) - // for any x>=1, x integer. - tdepth[0] = MathUtil.log2((1 << utdepth[0]) + (2 << utdepth[1]) + (1 << utdepth[2]) - 1) - 2 + 1; - tdepth[1] = MathUtil.log2((1 << utdepth[2]) + (1 << utdepth[1]) - 1) + 1; - tdepth[2] = MathUtil.log2((1 << utdepth[0]) + (1 << utdepth[1]) - 1) + 1; - break; - - case INV_ICT: - if (utdepth.Length > 3) - { - Array.Copy(utdepth, 3, tdepth, 3, utdepth.Length - 3); - } - // The MathUtil.log2(x) function calculates floor(log2(x)), so we - // use 'MathUtil.log2(2*x-1)+1', which calculates ceil(log2(x)) - // for any x>=1, x integer. - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - tdepth[0] = MathUtil.log2((int)System.Math.Floor((1 << utdepth[0]) * 0.299072 + (1 << utdepth[1]) * 0.586914 + (1 << utdepth[2]) * 0.114014) - 1) + 1; - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - tdepth[1] = MathUtil.log2((int)System.Math.Floor((1 << utdepth[0]) * 0.168701 + (1 << utdepth[1]) * 0.331299 + (1 << utdepth[2]) * 0.5) - 1) + 1; - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - tdepth[2] = MathUtil.log2((int)System.Math.Floor((1 << utdepth[0]) * 0.5 + (1 << utdepth[1]) * 0.418701 + (1 << utdepth[2]) * 0.081299) - 1) + 1; - break; - } - - return tdepth; - } - - /// Returns the number of bits, referred to as the "range bits", - /// corresponding to the nominal range of the data in the specified - /// component. If this number is b then for unsigned data the - /// nominal range is between 0 and 2^b-1, and for signed data it is between - /// -2^(b-1) and 2^(b-1)-1. - /// - /// - /// The index of the component. - /// - /// - /// The bitdepth of un-transformed component 'c'. - /// - /// - public override int getNomRangeBits(int c) - { - return utdepth[c]; - } - - /// Apply inverse component transformation associated with the current - /// tile. If no component transformation has been requested by the user, - /// data are not modified. - /// - ///

    This method calls the getInternCompData() method, but respects the - /// definitions of the getCompData() method defined in the BlkImgDataSrc - /// interface. - /// - ///

    - /// Determines the rectangular area to return, and the - /// data is returned in this object. - /// - /// - /// Index of the output component. - /// - /// - /// The requested DataBlk - /// - /// - /// - /// - /// - public virtual DataBlk getCompData(DataBlk blk, int c) - { - // If requesting a component whose index is greater than 3 or there is - // no transform return a copy of data (getInternCompData returns the - // actual data in those cases) - if (c >= 3 || transfType == NONE || noCompTransf) - { - return src.getCompData(blk, c); - } - else - { - // We can use getInternCompData (since data is a copy anyways) - return getInternCompData(blk, c); - } - } - - /// Apply the inverse component transformation associated with the current - /// tile. If no component transformation has been requested by the user, - /// data are not modified. Else, appropriate method is called (invRCT or - /// invICT). - /// - /// - /// - /// - /// - /// - /// - /// - /// Determines the rectangular area to return. - /// - /// - /// Index of the output component. - /// - /// - /// The requested DataBlk - /// - /// - public virtual DataBlk getInternCompData(DataBlk blk, int c) - { - // if specified in the command line that no component transform should - // be made, return original data - if (noCompTransf) - return src.getInternCompData(blk, c); - - switch (transfType) - { - - case NONE: - return src.getInternCompData(blk, c); - - - case INV_RCT: - return invRCT(blk, c); - - case INV_ICT: - return invICT(blk, c); - - default: - throw new System.ArgumentException("Non JPEG 2000 part I" + " component transformation"); - - } - } - - /// Apply inverse component transformation to obtain requested component - /// from specified block of data. Whatever the type of requested DataBlk, - /// it always returns a DataBlkInt. - /// - /// - /// Determine the rectangular area to return - /// - /// - /// The index of the requested component - /// - /// - /// Data of requested component - /// - /// - private DataBlk invRCT(DataBlk blk, int c) - { - // If the component number is three or greater, return original data - if (c >= 3 && c < NumComps) - { - // Requesting a component whose index is greater than 3 - return src.getInternCompData(blk, c); - } - // If asking a component for the first time for this block, - // do transform for the 3 components - else if ((outdata[c] == null) || (dbi.ulx > blk.ulx) || (dbi.uly > blk.uly) || (dbi.ulx + dbi.w < blk.ulx + blk.w) || (dbi.uly + dbi.h < blk.uly + blk.h)) - { - int k, k0, k1, k2, mink, i; - int w = blk.w; //width of output block - int h = blk.h; //height of ouput block - - //Reference to output block data array - outdata[c] = (int[])blk.Data; - - //Create data array of blk if necessary - if (outdata[c] == null || outdata[c].Length != h * w) - { - outdata[c] = new int[h * w]; - blk.Data = outdata[c]; - } - - outdata[(c + 1) % 3] = new int[outdata[c].Length]; - outdata[(c + 2) % 3] = new int[outdata[c].Length]; - - if (block0 == null || block0.DataType != DataBlk.TYPE_INT) - block0 = new DataBlkInt(); - if (block1 == null || block1.DataType != DataBlk.TYPE_INT) - block1 = new DataBlkInt(); - if (block2 == null || block2.DataType != DataBlk.TYPE_INT) - block2 = new DataBlkInt(); - block0.w = block1.w = block2.w = blk.w; - block0.h = block1.h = block2.h = blk.h; - block0.ulx = block1.ulx = block2.ulx = blk.ulx; - block0.uly = block1.uly = block2.uly = blk.uly; - - int[] data0, data1, data2; // input data arrays - - // Fill in buffer blocks (to be read only) - // Returned blocks may have different size and position - block0 = (DataBlkInt)src.getInternCompData(block0, 0); - data0 = (int[])block0.Data; - block1 = (DataBlkInt)src.getInternCompData(block1, 1); - data1 = (int[])block1.Data; - block2 = (DataBlkInt)src.getInternCompData(block2, 2); - data2 = (int[])block2.Data; - - // Set the progressiveness of the output data - blk.progressive = block0.progressive || block1.progressive || block2.progressive; - blk.offset = 0; - blk.scanw = w; - - // set attributes of the DataBlk used for buffering - dbi.progressive = blk.progressive; - dbi.ulx = blk.ulx; - dbi.uly = blk.uly; - dbi.w = blk.w; - dbi.h = blk.h; - - // Perform conversion - - // Initialize general indexes - k = w * h - 1; - k0 = block0.offset + (h - 1) * block0.scanw + w - 1; - k1 = block1.offset + (h - 1) * block1.scanw + w - 1; - k2 = block2.offset + (h - 1) * block2.scanw + w - 1; - - for (i = h - 1; i >= 0; i--) - { - for (mink = k - w; k > mink; k--, k0--, k1--, k2--) - { - outdata[1][k] = (data0[k0] - ((data1[k1] + data2[k2]) >> 2)); - outdata[0][k] = data2[k2] + outdata[1][k]; - outdata[2][k] = data1[k1] + outdata[1][k]; - } - // Jump to beggining of previous line in input - k0 -= (block0.scanw - w); - k1 -= (block1.scanw - w); - k2 -= (block2.scanw - w); - } - outdata[c] = null; - } - else if ((c >= 0) && (c < 3)) - { - //Asking for the 2nd or 3rd block component - blk.Data = outdata[c]; - blk.progressive = dbi.progressive; - blk.offset = (blk.uly - dbi.uly) * dbi.w + blk.ulx - dbi.ulx; - blk.scanw = dbi.w; - outdata[c] = null; - } - else - { - // Requesting a non valid component index - throw new System.ArgumentException(); - } - return blk; - } - - /// Apply inverse irreversible component transformation to obtain requested - /// component from specified block of data. Whatever the type of requested - /// DataBlk, it always returns a DataBlkFloat. - /// - /// - /// Determine the rectangular area to return - /// - /// - /// The index of the requested component - /// - /// - /// Data of requested component - /// - /// - private DataBlk invICT(DataBlk blk, int c) - { - if (c >= 3 && c < NumComps) - { - // Requesting a component whose index is greater than 3 - int k, k0, mink, i; // k1, k2 removed - int w = blk.w; //width of output block - int h = blk.h; //height of ouput block - - int[] out_data; // array of output data - - //Reference to output block data array - out_data = (int[])blk.Data; - - //Create data array of blk if necessary - if (out_data == null) - { - out_data = new int[h * w]; - blk.Data = out_data; - } - - // Variables - DataBlkFloat indb = new DataBlkFloat(blk.ulx, blk.uly, w, h); - float[] indata; // input data array - - // Get the input data - // (returned block may be larger than requested one) - src.getInternCompData(indb, c); - indata = (float[])indb.Data; - - // Copy the data converting from int to int - k = w * h - 1; - k0 = indb.offset + (h - 1) * indb.scanw + w - 1; - for (i = h - 1; i >= 0; i--) - { - for (mink = k - w; k > mink; k--, k0--) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - out_data[k] = (int)(indata[k0]); - } - // Jump to beggining of previous line in input - k0 -= (indb.scanw - w); - } - - // Set the progressivity and offset - blk.progressive = indb.progressive; - blk.offset = 0; - blk.scanw = w; - } - // If asking a component for the first time for this block, - // do transform for the 3 components - else if ((outdata[c] == null) || (dbi.ulx > blk.ulx) || (dbi.uly > blk.uly) || (dbi.ulx + dbi.w < blk.ulx + blk.w) || (dbi.uly + dbi.h < blk.uly + blk.h)) - { - int k, k0, k1, k2, mink, i; - int w = blk.w; //width of output block - int h = blk.h; //height of ouput block - - //Reference to output block data array - outdata[c] = (int[])blk.Data; - - //Create data array of blk if necessary - if (outdata[c] == null || outdata[c].Length != w * h) - { - outdata[c] = new int[h * w]; - blk.Data = outdata[c]; - } - - outdata[(c + 1) % 3] = new int[outdata[c].Length]; - outdata[(c + 2) % 3] = new int[outdata[c].Length]; - - if (block0 == null || block0.DataType != DataBlk.TYPE_FLOAT) - block0 = new DataBlkFloat(); - if (block2 == null || block2.DataType != DataBlk.TYPE_FLOAT) - block2 = new DataBlkFloat(); - if (block1 == null || block1.DataType != DataBlk.TYPE_FLOAT) - block1 = new DataBlkFloat(); - block0.w = block2.w = block1.w = blk.w; - block0.h = block2.h = block1.h = blk.h; - block0.ulx = block2.ulx = block1.ulx = blk.ulx; - block0.uly = block2.uly = block1.uly = blk.uly; - - float[] data0, data1, data2; // input data arrays - - // Fill in buffer blocks (to be read only) - // Returned blocks may have different size and position - block0 = (DataBlkFloat)src.getInternCompData(block0, 0); - data0 = (float[])block0.Data; - block2 = (DataBlkFloat)src.getInternCompData(block2, 1); - data2 = (float[])block2.Data; - block1 = (DataBlkFloat)src.getInternCompData(block1, 2); - data1 = (float[])block1.Data; - - // Set the progressiveness of the output data - blk.progressive = block0.progressive || block1.progressive || block2.progressive; - blk.offset = 0; - blk.scanw = w; - - // set attributes of the DataBlk used for buffering - dbi.progressive = blk.progressive; - dbi.ulx = blk.ulx; - dbi.uly = blk.uly; - dbi.w = blk.w; - dbi.h = blk.h; - - //Perform conversion - - // Initialize general indexes - k = w * h - 1; - k0 = block0.offset + (h - 1) * block0.scanw + w - 1; - k2 = block2.offset + (h - 1) * block2.scanw + w - 1; - k1 = block1.offset + (h - 1) * block1.scanw + w - 1; - - for (i = h - 1; i >= 0; i--) - { - for (mink = k - w; k > mink; k--, k0--, k2--, k1--) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - outdata[0][k] = (int)(data0[k0] + 1.402f * data1[k1] + 0.5f); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - outdata[1][k] = (int)(data0[k0] - 0.34413f * data2[k2] - 0.71414f * data1[k1] + 0.5f); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - outdata[2][k] = (int)(data0[k0] + 1.772f * data2[k2] + 0.5f); - } - // Jump to beggining of previous line in input - k0 -= (block0.scanw - w); - k2 -= (block2.scanw - w); - k1 -= (block1.scanw - w); - } - outdata[c] = null; - } - else if ((c >= 0) && (c <= 3)) - { - //Asking for the 2nd or 3rd block component - blk.Data = outdata[c]; - blk.progressive = dbi.progressive; - blk.offset = (blk.uly - dbi.uly) * dbi.w + blk.ulx - dbi.ulx; - blk.scanw = dbi.w; - outdata[c] = null; - } - else - { - // Requesting a non valid component index - throw new System.ArgumentException(); - } - return blk; - } - - /// Changes the current tile, given the new indexes. An - /// IllegalArgumentException is thrown if the indexes do not - /// correspond to a valid tile. - /// - ///

    This default implementation changes the tile in the source - /// and re-initializes properly component transformation variables.. - /// - ///

    - /// The horizontal index of the tile. - /// - /// - /// The vertical index of the new tile. - /// - /// - /// - public override void setTile(int x, int y) - { - src.setTile(x, y); - tIdx = TileIdx; // index of the current tile - - // initializations - if (((System.Int32)cts.getTileDef(tIdx)) == NONE) - transfType = NONE; - else - { - int nc = src.NumComps > 3 ? 3 : src.NumComps; - int rev = 0; - for (int c = 0; c < nc; c++) - { - rev += (wfs.isReversible(tIdx, c) ? 1 : 0); - } - if (rev == 3) - { - // All WT are reversible - transfType = INV_RCT; - } - else if (rev == 0) - { - // All WT irreversible - transfType = INV_ICT; - } - else - { - // Error - throw new System.ArgumentException("Wavelet transformation and " + "component transformation" + " not coherent in tile" + tIdx); - } - } - } - - /// Advances to the next tile, in standard scan-line order (by rows - /// then columns). An NoNextElementException is thrown if the - /// current tile is the last one (i.e. there is no next tile). - /// - ///

    This default implementation just advances to the next tile - /// in the source and re-initializes properly component - /// transformation variables. - /// - /// - ///

    - public override void nextTile() - { - src.nextTile(); - tIdx = TileIdx; // index of the current tile - - // initializations - if (((System.Int32)cts.getTileDef(tIdx)) == NONE) - transfType = NONE; - else - { - int nc = src.NumComps > 3 ? 3 : src.NumComps; - int rev = 0; - for (int c = 0; c < nc; c++) - { - rev += (wfs.isReversible(tIdx, c) ? 1 : 0); - } - if (rev == 3) - { - // All WT are reversible - transfType = INV_RCT; - } - else if (rev == 0) - { - // All WT irreversible - transfType = INV_ICT; - } - else - { - // Error - throw new System.ArgumentException("Wavelet transformation and " + "component transformation" + " not coherent in tile" + tIdx); - } - } - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/image/output/ImgWriter.cs b/CSJ2K/j2k/image/output/ImgWriter.cs deleted file mode 100644 index d79a7bd5..00000000 --- a/CSJ2K/j2k/image/output/ImgWriter.cs +++ /dev/null @@ -1,190 +0,0 @@ -/* -* CVS identifier: -* -* $Id: ImgWriter.java,v 1.12 2001/09/14 09:13:11 grosbois Exp $ -* -* Class: ImgWriter -* -* Description: Generic interface for all image writer -* classes (to file or other resource) -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using System; -namespace CSJ2K.j2k.image.output -{ - - /// This is the generic interface to be implemented by all image file (or other - /// resource) writers for different formats. - /// - ///

    Each object inheriting from this class should have a source ImgData - /// object associated with it. The image data to write to the file is obtained - /// from the associated ImgData object. In general this object would be - /// specified at construction time.

    - /// - ///

    Depending on the actual type of file that is written a call to any - /// write() or writeAll() method will write data from one component, several - /// components or all components. For example, a PGM writer will write data - /// from only one component (defined in the constructor) while a PPM writer - /// will write 3 components (normally R,G,B).

    - /// - ///
    - public abstract class ImgWriter - { - - /// The defaukt height used when writing strip by strip in the 'write()' - /// method. It is 64. - /// - public const int DEF_STRIP_HEIGHT = 64; - - /// The source ImagaData object, from where to get the image data - protected internal BlkImgDataSrc src; - - /// The width of the image - protected internal int w; - - /// The height of the image - protected internal int h; - - /// Closes the underlying file or netwrok connection to where the data is - /// written. The implementing class must write all buffered data before - /// closing the file or resource. Any call to other methods of the class - /// become illegal after a call to this one. - /// - /// - /// If an I/O error occurs. - /// - /// - public abstract void close(); - - /// Writes all buffered data to the file or resource. If the implementing - /// class does onot use buffering nothing should be done. - /// - /// - /// If an I/O error occurs. - /// - /// - public abstract void flush(); - - /// Flushes the buffered data before the object is garbage collected. If an - /// exception is thrown the object finalization is halted, but is otherwise - /// ignored. - /// - /// - /// If an I/O error occurs. It halts the - /// finalization of the object, but is otherwise ignored. - /// - /// - /// - /// - /// - ~ImgWriter() - { - flush(); - } - - /// Writes the source's current tile to the output. The requests of data - /// issued by the implementing class to the source ImgData object should be - /// done by blocks or strips, in order to reduce memory usage. - /// - ///

    The implementing class should only write data that is not - /// "progressive" (in other words that it is final), see DataBlk for - /// details.

    - /// - ///
    - /// If an I/O error occurs. - /// - /// - /// - /// - /// - public abstract void write(); - - /// Writes the entire image or only specified tiles to the output. The - /// implementation in this class calls the write() method for each tile - /// starting with the upper-left one and proceding in standard scanline - /// order. It changes the current tile of the source data. - /// - /// - /// If an I/O error occurs. - /// - /// - /// - /// - /// - public virtual void writeAll() - { - // Find the list of tile to decode. - Coord nT = src.getNumTiles(null); - - // Loop on vertical tiles - for (int y = 0; y < nT.y; y++) - { - // Loop on horizontal tiles - for (int x = 0; x < nT.x; x++) - { - src.setTile(x, y); - write(); - } // End loop on horizontal tiles - } // End loop on vertical tiles - } - - /// Writes the data of the specified area to the file, coordinates are - /// relative to the current tile of the source. - /// - ///

    The implementing class should only write data that is not - /// "progressive" (in other words that is final), see DataBlk for - /// details.

    - /// - ///
    - /// The horizontal coordinate of the upper-left corner of the - /// area to write, relative to the current tile. - /// - /// - /// The vertical coordinate of the upper-left corner of the area - /// to write, relative to the current tile. - /// - /// - /// The width of the area to write. - /// - /// - /// The height of the area to write. - /// - /// - /// If an I/O error occurs. - /// - /// - public abstract void write(int ulx, int uly, int w, int h); - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/image/output/ImgWriterPGM.cs b/CSJ2K/j2k/image/output/ImgWriterPGM.cs deleted file mode 100644 index c30d7ff6..00000000 --- a/CSJ2K/j2k/image/output/ImgWriterPGM.cs +++ /dev/null @@ -1,415 +0,0 @@ -/* -* CVS identifier: -* -* $Id: ImgWriterPGM.java,v 1.14 2002/07/19 14:13:38 grosbois Exp $ -* -* Class: ImgWriterRawPGM -* -* Description: Image writer for unsigned 8 bit data in -* PGM file format. -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.util; -namespace CSJ2K.j2k.image.output -{ - - /// This class writes a component from an image in 8 bit unsigned data to a - /// binary PGM file. The size of the image that is written to the file is the - /// size of the component from which to get the data, not the size of the - /// source image (they differ if there is some sub-sampling). - /// - ///

    Before writing, all coefficients are inversly level shifted and then - /// "saturated" (they are limited to the nominal dynamic range).
    Ex: - /// if the nominal range is 0-255, the following algorithm is applied:
    - /// if coeff<0, output=0
    if coeff>255, output=255
    else - /// output=coeff

    - /// - ///

    The write() methods of an object of this class may not be called - /// concurrently from different threads.

    - /// - ///

    NOTE: This class is not thread safe, for reasons of internal - /// buffering.

    - /// - ///
    - public class ImgWriterPGM : ImgWriter - { - - /// Value used to inverse level shift - private int levShift; - - /// Where to write the data - //UPGRADE_TODO: Class 'java.io.RandomAccessFile' was converted to 'System.IO.FileStream' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioRandomAccessFile'" - private System.IO.FileStream out_Renamed; - - /// The index of the component from where to get the data - private int c; - - /// The number of fractional bits in the source data - private int fb; - - /// A DataBlk, just used to avoid allocating a new one each time - /// it is needed - /// - private DataBlkInt db = new DataBlkInt(); - - /// The offset of the raw pixel data in the PGM file - private int offset; - - /// The line buffer. - // This makes the class not thrad safe - // (but it is not the only one making it so) - private byte[] buf; - - /// Creates a new writer to the specified File object, to write data from - /// the specified component. - /// - ///

    The size of the image that is written to the file is the size of the - /// component from which to get the data, specified by b, not the size of - /// the source image (they differ if there is some sub-sampling).

    - /// - ///
    - /// The file where to write the data - /// - /// - /// The source from where to get the image data to write. - /// - /// - /// The index of the component from where to get the data. - /// - /// - public ImgWriterPGM(System.IO.FileInfo out_Renamed, BlkImgDataSrc imgSrc, int c) - { - // Check that imgSrc is of the correct type - // Check that the component index is valid - if (c < 0 || c >= imgSrc.NumComps) - { - throw new System.ArgumentException("Invalid number of components"); - } - - // Check that imgSrc is of the correct type - if (imgSrc.getNomRangeBits(c) > 8) - { - FacilityManager.getMsgLogger().println("Warning: Component " + c + " has nominal bitdepth " + imgSrc.getNomRangeBits(c) + ". Pixel values will be " + "down-shifted to fit bitdepth of 8 for PGM file", 8, 8); - } - - // Initialize - bool tmpBool; - if (System.IO.File.Exists(out_Renamed.FullName)) - tmpBool = true; - else - tmpBool = System.IO.Directory.Exists(out_Renamed.FullName); - bool tmpBool2; - if (System.IO.File.Exists(out_Renamed.FullName)) - { - System.IO.File.Delete(out_Renamed.FullName); - tmpBool2 = true; - } - else if (System.IO.Directory.Exists(out_Renamed.FullName)) - { - System.IO.Directory.Delete(out_Renamed.FullName); - tmpBool2 = true; - } - else - tmpBool2 = false; - if (tmpBool && !tmpBool2) - { - throw new System.IO.IOException("Could not reset file"); - } - this.out_Renamed = SupportClass.RandomAccessFileSupport.CreateRandomAccessFile(out_Renamed, "rw"); - src = imgSrc; - this.c = c; - w = imgSrc.ImgWidth; - h = imgSrc.ImgHeight; - fb = imgSrc.getFixedPoint(c); - levShift = 1 << (imgSrc.getNomRangeBits(c) - 1); - - writeHeaderInfo(); - } - - /// Creates a new writer to the specified file, to write data from the - /// specified component. - /// - ///

    The size of the image that is written to the file is the size of the - /// component from which to get the data, specified by b, not the size of - /// the source image (they differ if there is some sub-sampling). - /// - ///

    - /// The name of the file where to write the data - /// - /// - /// The source from where to get the image data to write. - /// - /// - /// The index of the component from where to get the data. - /// - /// - public ImgWriterPGM(System.String fname, BlkImgDataSrc imgSrc, int c) : this(new System.IO.FileInfo(fname), imgSrc, c) - { - } - - /// Closes the underlying file or netwrok connection to where the data is - /// written. Any call to other methods of the class become illegal after a - /// call to this one. - /// - /// - /// If an I/O error occurs. - /// - /// - public override void close() - { - int i; - // Finish writing the file, writing 0s at the end if the data at end - // has not been written. - if (out_Renamed.Length != w * h + offset) - { - // Goto end of file - out_Renamed.Seek(out_Renamed.Length, System.IO.SeekOrigin.Begin); - // Fill with 0s - for (i = offset + w * h - (int)out_Renamed.Length; i > 0; i--) - { - out_Renamed.WriteByte((System.Byte)0); - } - } - out_Renamed.Close(); - src = null; - out_Renamed = null; - db = null; - } - - /// Writes all buffered data to the file or resource. - /// - /// - /// If an I/O error occurs. - /// - /// - public override void flush() - { - // No flush needed here since we are using a RandomAccessFile Get rid - // of line buffer (is this a good choice?) - buf = null; - } - - /// Writes the data of the specified area to the file, coordinates are - /// relative to the current tile of the source. Before writing, the - /// coefficients are limited to the nominal range. - /// - ///

    This method may not be called concurrently from different - /// threads.

    - /// - ///

    If the data returned from the BlkImgDataSrc source is progressive, - /// then it is requested over and over until it is not progressive - /// anymore.

    - /// - ///
    - /// The horizontal coordinate of the upper-left corner of the - /// area to write, relative to the current tile. - /// - /// - /// The vertical coordinate of the upper-left corner of the area - /// to write, relative to the current tile. - /// - /// - /// The width of the area to write. - /// - /// - /// The height of the area to write. - /// - /// - /// If an I/O error occurs. - /// - /// - public override void write(int ulx, int uly, int w, int h) - { - int k, i, j; - int fracbits = fb; // In local variable for faster access - int tOffx, tOffy; // Active tile offset in the X and Y direction - - // Initialize db - db.ulx = ulx; - db.uly = uly; - db.w = w; - db.h = h; - // Get the current active tile offset - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - tOffx = src.getCompULX(c) - (int)System.Math.Ceiling(src.ImgULX / (double)src.getCompSubsX(c)); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - tOffy = src.getCompULY(c) - (int)System.Math.Ceiling(src.ImgULY / (double)src.getCompSubsY(c)); - // Check the array size - if (db.data_array != null && db.data_array.Length < w * h) - { - // A new one will be allocated by getInternCompData() - db.data_array = null; - } - // Request the data and make sure it is not - // progressive - do - { - db = (DataBlkInt)src.getInternCompData(db, c); - } - while (db.progressive); - - // variables used during coeff saturation - int tmp, maxVal = (1 << src.getNomRangeBits(c)) - 1; - - // If nominal bitdepth greater than 8, calculate down shift - int downShift = src.getNomRangeBits(c) - 8; - if (downShift < 0) - { - downShift = 0; - } - - // Check line buffer - if (buf == null || buf.Length < w) - { - buf = new byte[w]; // Expand buffer - } - - // Write line by line - for (i = 0; i < h; i++) - { - // Skip to beggining of line in file - out_Renamed.Seek(this.offset + this.w * (uly + tOffy + i) + ulx + tOffx, System.IO.SeekOrigin.Begin); - // Write all bytes in the line - if (fracbits == 0) - { - for (k = db.offset + i * db.scanw + w - 1, j = w - 1; j >= 0; j--, k--) - { - tmp = db.data_array[k] + levShift; - buf[j] = (byte)(((tmp < 0) ? 0 : ((tmp > maxVal) ? maxVal : tmp)) >> downShift); - } - } - else - { - for (k = db.offset + i * db.scanw + w - 1, j = w - 1; j >= 0; j--, k--) - { - tmp = (db.data_array[k] >> fracbits) + levShift; - buf[j] = (byte)(((tmp < 0) ? 0 : ((tmp > maxVal) ? maxVal : tmp)) >> downShift); - } - } - out_Renamed.Write(buf, 0, w); - } - } - - /// Writes the source's current tile to the output. The requests of data - /// issued to the source BlkImgDataSrc object are done by strips, in order - /// to reduce memory usage. - /// - ///

    If the data returned from the BlkImgDataSrc source is progressive, - /// then it is requested over and over until it is not progressive - /// anymore.

    - /// - ///
    - /// If an I/O error occurs. - /// - /// - /// - /// - /// - public override void write() - { - int i; - int tIdx = src.TileIdx; - int tw = src.getTileCompWidth(tIdx, c); // Tile width - int th = src.getTileCompHeight(tIdx, c); // Tile height - // Write in strips - for (i = 0; i < th; i += DEF_STRIP_HEIGHT) - { - write(0, i, tw, (th - i < DEF_STRIP_HEIGHT) ? th - i : DEF_STRIP_HEIGHT); - } - } - - /// Writes the header info of the PGM file : - /// - /// P5 - /// width height - /// 255 - /// - /// - /// If there is an IOException - /// - /// - private void writeHeaderInfo() - { - byte[] byteVals; - int i; - System.String val; - - // write 'P5' to file - out_Renamed.WriteByte((System.Byte)'P'); // 'P' - out_Renamed.WriteByte((System.Byte)'5'); // '5' - out_Renamed.WriteByte((System.Byte)'\n'); // newline - offset = 3; - // Write width in ASCII - val = System.Convert.ToString(w); - byteVals = System.Text.ASCIIEncoding.ASCII.GetBytes(val); - for (i = 0; i < byteVals.Length; i++) - { - out_Renamed.WriteByte((byte)byteVals[i]); - offset++; - } - out_Renamed.WriteByte((System.Byte)' '); // blank - offset++; - // Write height in ASCII - val = System.Convert.ToString(h); - byteVals = System.Text.ASCIIEncoding.ASCII.GetBytes(val); - for (i = 0; i < byteVals.Length; i++) - { - out_Renamed.WriteByte((byte)byteVals[i]); - offset++; - } - // Write maxval - out_Renamed.WriteByte((System.Byte)'\n'); // newline - out_Renamed.WriteByte((System.Byte)'2'); // '2' - out_Renamed.WriteByte((System.Byte)'5'); // '5' - out_Renamed.WriteByte((System.Byte)'5'); // '5' - out_Renamed.WriteByte((System.Byte)'\n'); // newline - offset += 5; - } - - /// Returns a string of information about the object, more than 1 line - /// long. The information string includes information from the underlying - /// RandomAccessFile (its toString() method is called in turn). - /// - /// - /// A string of information about the object. - /// - /// - public override System.String ToString() - { - //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Object.toString' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" - return "ImgWriterPGM: WxH = " + w + "x" + h + ", Component=" + c + "\nUnderlying RandomAccessFile:\n" + out_Renamed.ToString(); - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/image/output/ImgWriterPGX.cs b/CSJ2K/j2k/image/output/ImgWriterPGX.cs deleted file mode 100644 index 8423f122..00000000 --- a/CSJ2K/j2k/image/output/ImgWriterPGX.cs +++ /dev/null @@ -1,536 +0,0 @@ -/* -* CVS identifier: -* -* $Id: ImgWriterPGX.java,v 1.14 2002/07/19 14:10:46 grosbois Exp $ -* -* Class: ImgWriterPGX -* -* Description: Image Writer for PGX files (custom file format -* for VM3A) -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -namespace CSJ2K.j2k.image.output -{ - - /// This class extends the ImgWriter abstract class for writing PGX files. PGX - /// is a custom monochrome file format invented specifically to simplify the - /// use of VM3A with images of different bit-depths in the range 1 to 31 bits - /// per pixel. - /// - ///

    The file consists of a one line text header followed by the data.

    - /// - ///

    - /// Header: "PG"+ ws +<endianess>+ ws - /// +[sign]+ws + <bit-depth>+" - /// "+<width>+" "+<height>+'\n'

    - /// - ///

    where:
    - ///

      - ///
    • ws (white-spaces) is any combination of characters ' ' and - /// '\t'.
    • - ///
    • endianess equals "LM" or "ML"(resp. little-endian or - /// big-endian)
    • - ///
    • sign equals "+" or "-" (resp. unsigned or signed). If omited, - /// values are supposed to be unsigned.
    • - ///
    • bit-depth that can be any number between 1 and 31.
    • - ///
    • width and height are the image dimensions (in - /// pixels).
    • - ///
    - /// - /// Data: The image binary values appear one after the other (in raster - /// order) immediately after the last header character ('\n') and are - /// byte-aligned (they are packed into 1,2 or 4 bytes per sample, depending - /// upon the bit-depth value). - ///

    - /// - ///

    If the data is unsigned, level shifting is applied adding 2^(bit depth - /// - 1)

    - /// - ///

    NOTE: This class is not thread safe, for reasons of internal - /// buffering.

    - /// - ///
    - /// - /// - /// - /// - /// - /// - public class ImgWriterPGX : ImgWriter - { - - /// Used during saturation (2^bitdepth-1 if unsigned, 2^(bitdepth-1)-1 if - /// signed) - /// - internal int maxVal; - - /// Used during saturation (0 if unsigned, -2^(bitdepth-1) if signed) - internal int minVal; - - /// Used with level-shiting - internal int levShift; - - /// Whether the data must be signed when writing or not. In the latter - /// case inverse level shifting must be applied - /// - internal bool isSigned; - - /// The bit-depth of the input file (must be between 1 and 31) - private int bitDepth; - - /// Where to write the data - //UPGRADE_TODO: Class 'java.io.RandomAccessFile' was converted to 'System.IO.FileStream' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioRandomAccessFile'" - private System.IO.FileStream out_Renamed; - - /// The offset of the raw pixel data in the PGX file - private int offset; - - /// A DataBlk, just used to avoid allocating a new one each time it is - /// needed - /// - private DataBlkInt db = new DataBlkInt(); - - /// The number of fractional bits in the source data - private int fb; - - /// The index of the component from where to get the data - private int c; - - /// The pack length of one sample (in bytes, according to the output - /// bit-depth - /// - private int packBytes; - - /// The line buffer. - // This makes the class not thrad safe - // (but it is not the only one making it so) - private byte[] buf; - - /// Creates a new writer to the specified File object, to write data from - /// the specified component. - /// - ///

    The size of the image that is written to the file is the size of the - /// component from which to get the data, specified by b, not the size of - /// the source image (they differ if there is some sub-sampling).

    - /// - ///

    All the header informations are given by the BlkImgDataSrc source - /// (component width, component height, bit-depth) and sign flag, which are - /// provided to the constructor. The endianness is always big-endian (MSB - /// first).

    - /// - ///
    - /// The file where to write the data - /// - /// - /// The source from where to get the image data to write. - /// - /// - /// The index of the component from where to get the data. - /// - /// - /// Whether the datas are signed or not (needed only when - /// writing header). - /// - /// - /// - /// - /// - public ImgWriterPGX(System.IO.FileInfo out_Renamed, BlkImgDataSrc imgSrc, int c, bool isSigned) - { - //Initialize - this.c = c; - bool tmpBool; - if (System.IO.File.Exists(out_Renamed.FullName)) - tmpBool = true; - else - tmpBool = System.IO.Directory.Exists(out_Renamed.FullName); - bool tmpBool2; - if (System.IO.File.Exists(out_Renamed.FullName)) - { - System.IO.File.Delete(out_Renamed.FullName); - tmpBool2 = true; - } - else if (System.IO.Directory.Exists(out_Renamed.FullName)) - { - System.IO.Directory.Delete(out_Renamed.FullName); - tmpBool2 = true; - } - else - tmpBool2 = false; - if (tmpBool && !tmpBool2) - { - throw new System.IO.IOException("Could not reset file"); - } - this.out_Renamed = SupportClass.RandomAccessFileSupport.CreateRandomAccessFile(out_Renamed, "rw"); - this.isSigned = isSigned; - src = imgSrc; - w = src.ImgWidth; - h = src.ImgHeight; - fb = imgSrc.getFixedPoint(c); - - bitDepth = src.getNomRangeBits(this.c); - if ((bitDepth <= 0) || (bitDepth > 31)) - { - throw new System.IO.IOException("PGX supports only bit-depth between " + "1 and 31"); - } - if (bitDepth <= 8) - { - packBytes = 1; - } - else if (bitDepth <= 16) - { - packBytes = 2; - } - else - { - // <= 31 - packBytes = 4; - } - - // Writes PGX header - System.String tmpString = "PG " + "ML " + ((this.isSigned) ? "- " : "+ ") + bitDepth + " " + w + " " + h + "\n"; // component height - - byte[] tmpByte = System.Text.ASCIIEncoding.ASCII.GetBytes(tmpString); - for (int i = 0; i < tmpByte.Length; i++) - { - this.out_Renamed.WriteByte((byte)tmpByte[i]); - } - - offset = tmpByte.Length; - maxVal = this.isSigned ? ((1 << (src.getNomRangeBits(c) - 1)) - 1) : ((1 << src.getNomRangeBits(c)) - 1); - minVal = this.isSigned ? ((-1) * (1 << (src.getNomRangeBits(c) - 1))) : 0; - - levShift = (this.isSigned) ? 0 : 1 << (src.getNomRangeBits(c) - 1); - } - - /// Creates a new writer to the specified file, to write data from the - /// specified component. - /// - ///

    The size of the image that is written to the file is the size of the - /// component from which to get the data, specified by b, not the size of - /// the source image (they differ if there is some sub-sampling).

    - /// - ///

    All header information is given by the BlkImgDataSrc source - /// (component width, component height, bit-depth) and sign flag, which are - /// provided to the constructor. The endianness is always big-endian (MSB - /// first). - /// - ///

    - /// The name of the file where to write the data - /// - /// - /// The source from where to get the image data to write. - /// - /// - /// The index of the component from where to get the data. - /// - /// - /// Whether the datas are signed or not (needed only when - /// writing header). - /// - /// - /// - /// - /// - public ImgWriterPGX(System.String fname, BlkImgDataSrc imgSrc, int c, bool isSigned) : this(new System.IO.FileInfo(fname), imgSrc, c, isSigned) - { - } - - /// Closes the underlying file or netwrok connection to where the data is - /// written. Any call to other methods of the class become illegal after a - /// call to this one. - /// - /// - /// If an I/O error occurs. - /// - /// - public override void close() - { - int i; - // Finish writing the file, writing 0s at the end if the data at end - // has not been written. - if (out_Renamed.Length != w * h * packBytes + offset) - { - // Goto end of file - out_Renamed.Seek(out_Renamed.Length, System.IO.SeekOrigin.Begin); - // Fill with 0s - for (i = offset + w * h * packBytes - (int)out_Renamed.Length; i > 0; i--) - { - out_Renamed.WriteByte((System.Byte)0); - } - } - out_Renamed.Close(); - src = null; - out_Renamed = null; - db = null; - } - - /// Writes all buffered data to the file or resource. - /// - /// - /// If an I/O error occurs. - /// - /// - public override void flush() - { - // No flush is needed since we use RandomAccessFile - // Get rid of line buffer (is this a good choice?) - buf = null; - } - - /// Writes the data of the specified area to the file, coordinates are - /// relative to the current tile of the source. Before writing, the - /// coefficients are limited to the nominal range and packed into 1,2 or 4 - /// bytes (according to the bit-depth). - /// - ///

    If the data is unisigned, level shifting is applied adding 2^(bit - /// depth - 1)

    - /// - ///

    This method may not be called concurrently from different - /// threads.

    - /// - ///

    If the data returned from the BlkImgDataSrc source is progressive, - /// then it is requested over and over until it is not progressive - /// anymore.

    - /// - ///
    - /// The horizontal coordinate of the upper-left corner of the - /// area to write, relative to the current tile. - /// - /// - /// The vertical coordinate of the upper-left corner of the area - /// to write, relative to the current tile. - /// - /// - /// The width of the area to write. - /// - /// - /// The height of the area to write. - /// - /// - /// If an I/O error occurs. - /// - /// - public override void write(int ulx, int uly, int w, int h) - { - int k, i, j; - int fracbits = fb; // In local variable for faster access - int tOffx, tOffy; // Active tile offset in the X and Y direction - - // Initialize db - db.ulx = ulx; - db.uly = uly; - db.w = w; - db.h = h; - // Get the current active tile offset - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - tOffx = src.getCompULX(c) - (int)System.Math.Ceiling(src.ImgULX / (double)src.getCompSubsX(c)); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - tOffy = src.getCompULY(c) - (int)System.Math.Ceiling(src.ImgULY / (double)src.getCompSubsY(c)); - // Check the array size - if (db.data_array != null && db.data_array.Length < w * h) - { - // A new one will be allocated by getInternCompData() - db.data_array = null; - } - // Request the data and make sure it is not - // progressive - do - { - db = (DataBlkInt)src.getInternCompData(db, c); - } - while (db.progressive); - - int tmp; - - - // Check line buffer - if (buf == null || buf.Length < packBytes * w) - { - buf = new byte[packBytes * w]; // Expand buffer - } - - switch (packBytes) - { - - - case 1: // Samples packed into 1 byte - // Write line by line - for (i = 0; i < h; i++) - { - // Skip to beggining of line in file - out_Renamed.Seek(offset + this.w * (uly + tOffy + i) + ulx + tOffx, System.IO.SeekOrigin.Begin); - // Write all bytes in the line - if (fracbits == 0) - { - for (k = db.offset + i * db.scanw + w - 1, j = w - 1; j >= 0; k--) - { - tmp = db.data_array[k] + levShift; - buf[j--] = (byte)((tmp < minVal) ? minVal : ((tmp > maxVal) ? maxVal : tmp)); - } - } - else - { - for (k = db.offset + i * db.scanw + w - 1, j = w - 1; j >= 0; k--) - { - tmp = (SupportClass.URShift(db.data_array[k], fracbits)) + levShift; - buf[j--] = (byte)((tmp < minVal) ? minVal : ((tmp > maxVal) ? maxVal : tmp)); - } - } - out_Renamed.Write(buf, 0, w); - } - break; - - - case 2: // Samples packed in to 2 bytes (short) - // Write line by line - for (i = 0; i < h; i++) - { - - // Skip to beggining of line in file - out_Renamed.Seek(offset + 2 * (this.w * (uly + tOffy + i) + ulx + tOffx), System.IO.SeekOrigin.Begin); - // Write all bytes in the line - if (fracbits == 0) - { - for (k = db.offset + i * db.scanw + w - 1, j = (w << 1) - 1; j >= 0; k--) - { - tmp = db.data_array[k] + levShift; - tmp = (tmp < minVal) ? minVal : ((tmp > maxVal) ? maxVal : tmp); - buf[j--] = (byte)tmp; // no need for 0xFF mask since - // truncation will do it already - buf[j--] = (byte)(SupportClass.URShift(tmp, 8)); - } - } - else - { - for (k = db.offset + i * db.scanw + w - 1, j = (w << 1) - 1; j >= 0; k--) - { - tmp = (SupportClass.URShift(db.data_array[k], fracbits)) + levShift; - tmp = (tmp < minVal) ? minVal : ((tmp > maxVal) ? maxVal : tmp); - buf[j--] = (byte)tmp; // no need for 0xFF mask since - // truncation will do it already - buf[j--] = (byte)(SupportClass.URShift(tmp, 8)); - } - } - out_Renamed.Write(buf, 0, w << 1); - } - break; - - - case 4: - // Write line by line - for (i = 0; i < h; i++) - { - // Skip to beggining of line in file - out_Renamed.Seek(offset + 4 * (this.w * (uly + tOffy + i) + ulx + tOffx), System.IO.SeekOrigin.Begin); - // Write all bytes in the line - if (fracbits == 0) - { - for (k = db.offset + i * db.scanw + w - 1, j = (w << 2) - 1; j >= 0; k--) - { - tmp = db.data_array[k] + levShift; - tmp = (tmp < minVal) ? minVal : ((tmp > maxVal) ? maxVal : tmp); - buf[j--] = (byte)tmp; // No need to use 0xFF - buf[j--] = (byte)(SupportClass.URShift(tmp, 8)); // masks since truncation - buf[j--] = (byte)(SupportClass.URShift(tmp, 16)); // will have already the - buf[j--] = (byte)(SupportClass.URShift(tmp, 24)); // same effect - } - } - else - { - for (k = db.offset + i * db.scanw + w - 1, j = (w << 2) - 1; j >= 0; k--) - { - tmp = (SupportClass.URShift(db.data_array[k], fracbits)) + levShift; - tmp = (tmp < minVal) ? minVal : ((tmp > maxVal) ? maxVal : tmp); - buf[j--] = (byte)tmp; // No need to use 0xFF - buf[j--] = (byte)(SupportClass.URShift(tmp, 8)); // masks since truncation - buf[j--] = (byte)(SupportClass.URShift(tmp, 16)); // will have already the - buf[j--] = (byte)(SupportClass.URShift(tmp, 24)); // same effect - } - } - out_Renamed.Write(buf, 0, w << 2); - } - break; - - - default: - throw new System.IO.IOException("PGX supports only bit-depth between " + "1 and 31"); - - } - } - - /// Writes the source's current tile to the output. The requests of data - /// issued to the source BlkImgDataSrc object are done by strips, in order - /// to reduce memory usage. - /// - ///

    If the data returned from the BlkImgDataSrc source is progressive, - /// then it is requested over and over until it is not progressive - /// anymore.

    - /// - ///
    - /// If an I/O error occurs. - /// - /// - /// - /// - /// - public override void write() - { - int i; - int tIdx = src.TileIdx; - int tw = src.getTileCompWidth(tIdx, c); // Tile width - int th = src.getTileCompHeight(tIdx, c); // Tile height - // Write in strips - for (i = 0; i < th; i += DEF_STRIP_HEIGHT) - { - write(0, i, tw, (th - i < DEF_STRIP_HEIGHT) ? th - i : DEF_STRIP_HEIGHT); - } - } - - /// Returns a string of information about the object, more than 1 line - /// long. The information string includes information from the underlying - /// RandomAccessFile (its toString() method is called in turn). - /// - /// - /// A string of information about the object. - /// - /// - public override System.String ToString() - { - //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Object.toString' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" - return "ImgWriterPGX: WxH = " + w + "x" + h + ", Component = " + c + ", Bit-depth = " + bitDepth + ", signed = " + isSigned + "\nUnderlying RandomAccessFile:\n" + out_Renamed.ToString(); - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/image/output/ImgWriterPPM.cs b/CSJ2K/j2k/image/output/ImgWriterPPM.cs deleted file mode 100644 index 3c926e1d..00000000 --- a/CSJ2K/j2k/image/output/ImgWriterPPM.cs +++ /dev/null @@ -1,463 +0,0 @@ -/* -* CVS identifier: -* -* $Id: ImgWriterPPM.java,v 1.16 2002/07/25 15:10:14 grosbois Exp $ -* -* Class: ImgWriterRawPPM -* -* Description: Image writer for unsigned 8 bit data in -* PPM file format. -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -namespace CSJ2K.j2k.image.output -{ - - /// This class writes 3 components from an image in 8 bit unsigned data to a - /// binary PPM file. - /// - ///

    The size of the image that is written is the size of the source - /// image. No component subsampling is allowed in any of the components that - /// are written to the file. - /// - ///

    Before writing, all coefficients are inversly level-shifted and then - /// "saturated" (they are limited * to the nominal dynamic range).
    - /// - /// Ex: if the nominal range is 0-255, the following algorithm is - /// applied:
    - /// - /// if coeff<0, output=0
    - /// - /// if coeff>255, output=255
    - /// - /// else output=coeff
    - /// - /// The write() methods of an object of this class may not be called - /// concurrently from different threads. - /// - ///

    NOTE: This class is not thread safe, for reasons of internal buffering. - /// - ///

    - public class ImgWriterPPM : ImgWriter - { - - /// Value used to inverse level shift. One for each component - private int[] levShift = new int[3]; - - /// Where to write the data - //UPGRADE_TODO: Class 'java.io.RandomAccessFile' was converted to 'System.IO.FileStream' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioRandomAccessFile'" - private System.IO.FileStream out_Renamed; - - /// The array of indexes of the components from where to get the data - private int[] cps = new int[3]; - - /// The array of the number of fractional bits in the components of the - /// source data - /// - private int[] fb = new int[3]; - - /// A DataBlk, just used to avoid allocating a new one each time - /// it is needed - /// - private DataBlkInt db = new DataBlkInt(); - - /// The offset of the raw pixel data in the PPM file - private int offset; - - /// The line buffer. - // This makes the class not thrad safe - // (but it is not the only one making it so) - private byte[] buf; - - /// Creates a new writer to the specified File object, to write data from - /// the specified component. - /// - ///

    The three components that will be written as R, G and B must be - /// specified through the b1, b2 and b3 arguments.

    - /// - ///
    - /// The file where to write the data - /// - /// - /// The source from where to get the image data to write. - /// - /// - /// The index of the first component from where to get the data, - /// that will be written as the red channel. - /// - /// - /// The index of the second component from where to get the data, - /// that will be written as the green channel. - /// - /// - /// The index of the third component from where to get the data, - /// that will be written as the green channel. - /// - /// - /// - /// - /// - public ImgWriterPPM(System.IO.FileInfo out_Renamed, BlkImgDataSrc imgSrc, int n1, int n2, int n3) - { - // Check that imgSrc is of the correct type - // Check that the component index is valid - if ((n1 < 0) || (n1 >= imgSrc.NumComps) || (n2 < 0) || (n2 >= imgSrc.NumComps) || (n3 < 0) || (n3 >= imgSrc.NumComps) || (imgSrc.getNomRangeBits(n1) > 8) || (imgSrc.getNomRangeBits(n2) > 8) || (imgSrc.getNomRangeBits(n3) > 8)) - { - throw new System.ArgumentException("Invalid component indexes"); - } - // Initialize - w = imgSrc.getCompImgWidth(n1); - h = imgSrc.getCompImgHeight(n1); - // Check that all components have same width and height - if (w != imgSrc.getCompImgWidth(n2) || w != imgSrc.getCompImgWidth(n3) || h != imgSrc.getCompImgHeight(n2) || h != imgSrc.getCompImgHeight(n3)) - { - throw new System.ArgumentException("All components must have the" + " same dimensions and no" + " subsampling"); - } - w = imgSrc.ImgWidth; - h = imgSrc.ImgHeight; - - // Continue initialization - bool tmpBool; - if (System.IO.File.Exists(out_Renamed.FullName)) - tmpBool = true; - else - tmpBool = System.IO.Directory.Exists(out_Renamed.FullName); - bool tmpBool2; - if (System.IO.File.Exists(out_Renamed.FullName)) - { - System.IO.File.Delete(out_Renamed.FullName); - tmpBool2 = true; - } - else if (System.IO.Directory.Exists(out_Renamed.FullName)) - { - System.IO.Directory.Delete(out_Renamed.FullName); - tmpBool2 = true; - } - else - tmpBool2 = false; - if (tmpBool && !tmpBool2) - { - throw new System.IO.IOException("Could not reset file"); - } - this.out_Renamed = SupportClass.RandomAccessFileSupport.CreateRandomAccessFile(out_Renamed, "rw"); - src = imgSrc; - cps[0] = n1; - cps[1] = n2; - cps[2] = n3; - fb[0] = imgSrc.getFixedPoint(n1); - fb[1] = imgSrc.getFixedPoint(n2); - fb[2] = imgSrc.getFixedPoint(n3); - - levShift[0] = 1 << (imgSrc.getNomRangeBits(n1) - 1); - levShift[1] = 1 << (imgSrc.getNomRangeBits(n2) - 1); - levShift[2] = 1 << (imgSrc.getNomRangeBits(n3) - 1); - - writeHeaderInfo(); - } - - /// Creates a new writer to the specified file, to write data from the - /// specified component. - /// - ///

    The three components that will be written as R, G and B must be - /// specified through the b1, b2 and b3 arguments.

    - /// - ///
    - /// The name of the file where to write the data - /// - /// - /// The source from where to get the image data to write. - /// - /// - /// The index of the first component from where to get the data, - /// that will be written as the red channel. - /// - /// - /// The index of the second component from where to get the data, - /// that will be written as the green channel. - /// - /// - /// The index of the third component from where to get the data, - /// that will be written as the green channel. - /// - /// - /// - /// - /// - public ImgWriterPPM(System.String fname, BlkImgDataSrc imgSrc, int n1, int n2, int n3) : this(new System.IO.FileInfo(fname), imgSrc, n1, n2, n3) - { - } - - /// Closes the underlying file or netwrok connection to where the data is - /// written. Any call to other methods of the class become illegal after a - /// call to this one. - /// - /// - /// If an I/O error occurs. - /// - /// - public override void close() - { - int i; - // Finish writing the file, writing 0s at the end if the data at end - // has not been written. - if (out_Renamed.Length != 3 * w * h + offset) - { - // Goto end of file - out_Renamed.Seek(out_Renamed.Length, System.IO.SeekOrigin.Begin); - // Fill with 0s n all the components - for (i = 3 * w * h + offset - (int)out_Renamed.Length; i > 0; i--) - { - out_Renamed.WriteByte((System.Byte)0); - } - } - out_Renamed.Close(); - src = null; - out_Renamed = null; - db = null; - } - - /// Writes all buffered data to the file or resource. - /// - /// - /// If an I/O error occurs. - /// - /// - public override void flush() - { - // No flush needed here since we are using a RandomAccessFile Get rid - // of line buffer (is this a good choice?) - buf = null; - } - - /// Writes the data of the specified area to the file, coordinates are - /// relative to the current tile of the source. Before writing, the - /// coefficients are limited to the nominal range. - /// - ///

    This method may not be called concurrently from different - /// threads.

    - /// - ///

    If the data returned from the BlkImgDataSrc source is progressive, - /// then it is requested over and over until it is not progressive - /// anymore.

    - /// - ///
    - /// The horizontal coordinate of the upper-left corner of the - /// area to write, relative to the current tile. - /// - /// - /// The vertical coordinate of the upper-left corner of the area - /// to write, relative to the current tile. - /// - /// - /// The width of the area to write. - /// - /// - /// The height of the area to write. - /// - /// - /// If an I/O error occurs. - /// - /// - public override void write(int ulx, int uly, int w, int h) - { - int k, j, i, c; - // In local variables for faster access - int fracbits; - // variables used during coeff saturation - int shift, tmp, maxVal; - int tOffx, tOffy; // Active tile offset in the X and Y direction - - // Active tiles in all components have same offset since they are at - // same resolution (PPM does not support anything else) - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - tOffx = src.getCompULX(cps[0]) - (int)System.Math.Ceiling(src.ImgULX / (double)src.getCompSubsX(cps[0])); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - tOffy = src.getCompULY(cps[0]) - (int)System.Math.Ceiling(src.ImgULY / (double)src.getCompSubsY(cps[0])); - - // Check the array size - if (db.data_array != null && db.data_array.Length < w) - { - // A new one will be allocated by getInternCompData() - db.data_array = null; - } - - // Check the line buffer - if (buf == null || buf.Length < 3 * w) - { - buf = new byte[3 * w]; - } - - // Write the data to the file - // Write line by line - for (i = 0; i < h; i++) - { - // Write into buffer first loop over the three components and - // write for each - for (c = 0; c < 3; c++) - { - maxVal = (1 << src.getNomRangeBits(cps[c])) - 1; - shift = levShift[c]; - - // Initialize db - db.ulx = ulx; - db.uly = uly + i; - db.w = w; - db.h = 1; - - // Request the data and make sure it is not progressive - do - { - db = (DataBlkInt)src.getInternCompData(db, cps[c]); - } - while (db.progressive); - // Get the fracbits value - fracbits = fb[c]; - // Write all bytes in the line - if (fracbits == 0) - { - for (k = db.offset + w - 1, j = 3 * w - 1 + c - 2; j >= 0; k--) - { - tmp = db.data_array[k] + shift; - buf[j] = (byte)((tmp < 0) ? 0 : ((tmp > maxVal) ? maxVal : tmp)); - j -= 3; - } - } - else - { - for (k = db.offset + w - 1, j = 3 * w - 1 + c - 2; j >= 0; k--) - { - tmp = (SupportClass.URShift(db.data_array[k], fracbits)) + shift; - buf[j] = (byte)((tmp < 0) ? 0 : ((tmp > maxVal) ? maxVal : tmp)); - j -= 3; - } - } - } - // Write buffer into file - out_Renamed.Seek(offset + 3 * (this.w * (uly + tOffy + i) + ulx + tOffx), System.IO.SeekOrigin.Begin); - out_Renamed.Write(buf, 0, 3 * w); - } - } - - /// Writes the source's current tile to the output. The requests of data - /// issued to the source BlkImgDataSrc object are done by strips, in order - /// to reduce memory usage. - /// - ///

    If the data returned from the BlkImgDataSrc source is progressive, - /// then it is requested over and over until it is not progressive any - /// more. - /// - ///

    - /// If an I/O error occurs. - /// - /// - public override void write() - { - int i; - int tIdx = src.TileIdx; - int tw = src.getTileCompWidth(tIdx, 0); // Tile width - int th = src.getTileCompHeight(tIdx, 0); // Tile height - // Write in strips - for (i = 0; i < th; i += DEF_STRIP_HEIGHT) - { - write(0, i, tw, ((th - i) < DEF_STRIP_HEIGHT) ? th - i : DEF_STRIP_HEIGHT); - } - } - - /// Writes the header info of the PPM file : - /// - /// P6
    - /// - /// width height
    - /// - /// 255
    - /// - ///
    - /// If there is an I/O Error - /// - /// - private void writeHeaderInfo() - { - byte[] byteVals; - int i; - System.String val; - - // write 'P6' to file - out_Renamed.Seek(0, System.IO.SeekOrigin.Begin); - out_Renamed.WriteByte((System.Byte)80); - out_Renamed.WriteByte((System.Byte)54); - out_Renamed.WriteByte((System.Byte)10); // new line - offset = 3; - // Write width in ASCII - val = System.Convert.ToString(w); - byteVals = System.Text.ASCIIEncoding.ASCII.GetBytes(val); - for (i = 0; i < byteVals.Length; i++) - { - out_Renamed.WriteByte((byte)byteVals[i]); - offset++; - } - out_Renamed.WriteByte((System.Byte)32); // blank - offset++; - // Write height in ASCII - val = System.Convert.ToString(h); - byteVals = System.Text.ASCIIEncoding.ASCII.GetBytes(val); - for (i = 0; i < byteVals.Length; i++) - { - out_Renamed.WriteByte((byte)byteVals[i]); - offset++; - } - - out_Renamed.WriteByte((System.Byte)10); // newline - out_Renamed.WriteByte((System.Byte)50); // '2' - out_Renamed.WriteByte((System.Byte)53); // '5' - out_Renamed.WriteByte((System.Byte)53); // '5' - out_Renamed.WriteByte((System.Byte)10); // newline - offset += 5; - } - - - /// Returns a string of information about the object, more than 1 line - /// long. The information string includes information from the underlying - /// RandomAccessFile (its toString() method is called in turn). - /// - /// - /// A string of information about the object. - /// - /// - public override System.String ToString() - { - //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Object.toString' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" - return "ImgWriterPPM: WxH = " + w + "x" + h + ", Components = " + cps[0] + "," + cps[1] + "," + cps[2] + "\nUnderlying RandomAccessFile:\n" + out_Renamed.ToString(); - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/io/BEBufferedRandomAccessFile.cs b/CSJ2K/j2k/io/BEBufferedRandomAccessFile.cs deleted file mode 100644 index 9dbda311..00000000 --- a/CSJ2K/j2k/io/BEBufferedRandomAccessFile.cs +++ /dev/null @@ -1,440 +0,0 @@ -/* -* CVS Identifier: -* -* $Id: BEBufferedRandomAccessFile.java,v 1.18 2001/07/17 13:13:35 grosbois Exp $ -* -* Interface: RandomAccessIO.java -* -* Description: Class for random access I/O (big-endian ordering). -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using System; -namespace CSJ2K.j2k.io -{ - - /// This class defines a Buffered Random Access File, where all I/O is - /// considered to be big-endian. It extends the - /// BufferedRandomAccessFile class. - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - public class BEBufferedRandomAccessFile : BufferedRandomAccessFile, RandomAccessIO, EndianType - { - - /// Constructor. Always needs a size for the buffer. - /// - /// - /// The file associated with the buffer - /// - /// - /// "r" for read, "rw" or "rw+" for read and write mode ("rw+" - /// opens the file for update whereas "rw" removes it - /// before. So the 2 modes are different only if the file - /// already exists). - /// - /// - /// The number of bytes to buffer - /// - /// - /// If an I/O error ocurred. - /// - /// - public BEBufferedRandomAccessFile(System.IO.FileInfo file, System.String mode, int bufferSize) : base(file, mode, bufferSize) - { - byte_Ordering = CSJ2K.j2k.io.EndianType_Fields.BIG_ENDIAN; - } - - /// Constructor. Uses the default value for the byte-buffer size (512 - /// bytes). - /// - /// - /// The file associated with the buffer - /// - /// - /// "r" for read, "rw" or "rw+" for read and write mode ("rw+" - /// opens the file for update whereas "rw" removes it - /// before. So the 2 modes are different only if the file - /// already exists). - /// - /// - /// If an I/O error ocurred. - /// - /// - public BEBufferedRandomAccessFile(System.IO.FileInfo file, System.String mode) : base(file, mode) - { - byte_Ordering = CSJ2K.j2k.io.EndianType_Fields.BIG_ENDIAN; - } - - /// Constructor. Always needs a size for the buffer. - /// - /// - /// The name of the file associated with the buffer - /// - /// - /// "r" for read, "rw" or "rw+" for read and write mode ("rw+" - /// opens the file for update whereas "rw" removes it - /// before. So the 2 modes are different only if the file - /// already exists). - /// - /// - /// The number of bytes to buffer - /// - /// - /// If an I/O error ocurred. - /// - /// - public BEBufferedRandomAccessFile(System.String name, System.String mode, int bufferSize) : base(name, mode, bufferSize) - { - byte_Ordering = CSJ2K.j2k.io.EndianType_Fields.BIG_ENDIAN; - } - - /// Constructor. Uses the default value for the byte-buffer size (512 - /// bytes). - /// - /// - /// The name of the file associated with the buffer - /// - /// - /// "r" for read, "rw" or "rw+" for read and write mode ("rw+" - /// opens the file for update whereas "rw" removes it - /// before. So the 2 modes are different only if the file - /// already exists). - /// - /// - /// If an I/O error ocurred. - /// - /// - public BEBufferedRandomAccessFile(System.String name, System.String mode) : base(name, mode) - { - byte_Ordering = CSJ2K.j2k.io.EndianType_Fields.BIG_ENDIAN; - } - - /// Writes the short value of v (i.e., 16 least significant bits) - /// to the output. Prior to writing, the output should be realigned at the - /// byte level. - /// - ///

    Signed or unsigned data can be written. To write a signed value just - /// pass the short value as an argument. To write unsigned data - /// pass the int value as an argument (it will be automatically - /// casted, and only the 16 least significant bits will be written).

    - /// - ///
    - /// The value to write to the output - /// - /// - /// If an I/O error ocurred. - /// - /// - public override void writeShort(int v) - { - write(SupportClass.URShift(v, 8)); - write(v); - } - - /// Writes the int value of v (i.e., the 32 bits) to the - /// output. Prior to writing, the output should be realigned at the byte - /// level. - /// - /// - /// The value to write to the output - /// - /// - /// If an I/O error ocurred. - /// - /// - public override void writeInt(int v) - { - write(SupportClass.URShift(v, 24)); - write(SupportClass.URShift(v, 16)); - write(SupportClass.URShift(v, 8)); - write(v); - } - - /// Writes the long value of v (i.e., the 64 bits) to the - /// output. Prior to writing, the output should be realigned at the byte - /// level. - /// - /// - /// The value to write to the output - /// - /// - /// If an I/O error ocurred. - /// - /// - public override void writeLong(long v) - { - write((int)(SupportClass.URShift(v, 56))); - write((int)(SupportClass.URShift(v, 48))); - write((int)(SupportClass.URShift(v, 40))); - write((int)(SupportClass.URShift(v, 32))); - write((int)(SupportClass.URShift(v, 24))); - write((int)(SupportClass.URShift(v, 16))); - write((int)(SupportClass.URShift(v, 8))); - write((int)v); - } - - /// Writes the IEEE float value v (i.e., 32 bits) to the - /// output. Prior to writing, the output should be realigned at the byte - /// level. - /// - /// - /// The value to write to the output - /// - /// - /// If an I/O error ocurred. - /// - /// - public override void writeFloat(float v) - { - // CONVERSION PROBLEM? OPTIMIZE!!! - //byte[] floatbytes = BitConverter.GetBytes(v); - //for (int i = floatbytes.Length-1; i >= 0 ; i--) write(floatbytes[i]); - - //UPGRADE_ISSUE: Method 'java.lang.Float.floatToIntBits' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javalangFloatfloatToIntBits_float'" - //int intV = Float.floatToIntBits(v); - int intV = BitConverter.ToInt32(BitConverter.GetBytes(v), 0); - write(SupportClass.URShift(intV, 24)); - write(SupportClass.URShift(intV, 16)); - write(SupportClass.URShift(intV, 8)); - write(intV); - } - - /// Writes the IEEE double value v (i.e., 64 bits) to the - /// output. Prior to writing, the output should be realigned at the byte - /// level. - /// - /// - /// The value to write to the output - /// - /// - /// If an I/O error ocurred. - /// - /// - public override void writeDouble(double v) - { - //byte[] doublebytes = BitConverter.GetBytes(v); - //for (int i = doublebytes.Length-1; i >= 0 ; i--) write(doublebytes[i]); - - //UPGRADE_ISSUE: Method 'java.lang.Double.doubleToLongBits' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javalangDoubledoubleToLongBits_double'" - //long longV = Double.doubleToLongBits(v); - long longV = BitConverter.ToInt64(BitConverter.GetBytes(v), 0); - write((int)(SupportClass.URShift(longV, 56))); - write((int)(SupportClass.URShift(longV, 48))); - write((int)(SupportClass.URShift(longV, 40))); - write((int)(SupportClass.URShift(longV, 32))); - write((int)(SupportClass.URShift(longV, 24))); - write((int)(SupportClass.URShift(longV, 16))); - write((int)(SupportClass.URShift(longV, 8))); - write((int)(longV)); - - } - - /// Reads a signed short (i.e. 16 bit) from the input. Prior to reading, - /// the input should be realigned at the byte level. - /// - /// - /// The next byte-aligned signed short (16 bit) from the input. - /// - /// - /// If the end-of file was reached before - /// getting all the necessary data. - /// - /// - /// If an I/O error ocurred. - /// - /// - public override short readShort() - { - return (short)((read() << 8) | (read())); - } - - /// Reads an unsigned short (i.e., 16 bit) from the input. It is returned - /// as an int since Java does not have an unsigned short - /// type. Prior to reading, the input should be realigned at the byte - /// level. - /// - /// - /// The next byte-aligned unsigned short (16 bit) from the input, - /// as an int. - /// - /// - /// If the end-of file was reached before - /// getting all the necessary data. - /// - /// - /// If an I/O error ocurred. - /// - /// - public override int readUnsignedShort() - { - return ((read() << 8) | read()); - } - - /// Reads a signed int (i.e., 32 bit) from the input. Prior to reading, the - /// input should be realigned at the byte level. - /// - /// - /// The next byte-aligned signed int (32 bit) from the input. - /// - /// - /// If the end-of file was reached before - /// getting all the necessary data. - /// - /// - /// If an I/O error ocurred. - /// - /// - public override int readInt() - { - return ((read() << 24) | (read() << 16) | (read() << 8) | read()); - } - - /// Reads an unsigned int (i.e., 32 bit) from the input. It is returned as - /// a long since Java does not have an unsigned short type. Prior - /// to reading, the input should be realigned at the byte level. - /// - /// - /// The next byte-aligned unsigned int (32 bit) from the input, as - /// a long. - /// - /// - /// If the end-of file was reached before - /// getting all the necessary data. - /// - /// - /// If an I/O error ocurred. - /// - /// - public override long readUnsignedInt() - { - return (long)((read() << 24) | (read() << 16) | (read() << 8) | read()); - } - - /// Reads a signed long (i.e., 64 bit) from the input. Prior to reading, - /// the input should be realigned at the byte level. - /// - /// - /// The next byte-aligned signed long (64 bit) from the input. - /// - /// - /// If the end-of file was reached before - /// getting all the necessary data. - /// - /// - /// If an I/O error ocurred. - /// - /// - public override long readLong() - { - //byte[] longbytes = new byte[8]; - //for (int i = longbytes.Length-1; i >= 0; i--) longbytes[i] = read(); - //return BitConverter.ToInt64(longbytes, 0); - return ((long)(((ulong)read() << 56) | ((ulong)read() << 48) | ((ulong)read() << 40) | ((ulong)read() << 32) | ((ulong)read() << 24) | ((ulong)read() << 16) | ((ulong)read() << 8) | ((ulong)read()))); - } - - /// Reads an IEEE single precision (i.e., 32 bit) floating-point number - /// from the input. Prior to reading, the input should be realigned at the - /// byte level. - /// - /// - /// The next byte-aligned IEEE float (32 bit) from the input. - /// - /// - /// If the end-of file was reached before - /// getting all the necessary data. - /// - /// - /// If an I/O error ocurred. - /// - /// - public override float readFloat() - { - // CONVERSION PROBLEM? OPTIMIZE!!! - //byte[] floatbytes = new byte[4]; - //for (int i = floatbytes.Length-1; i >= 0 ; i--) floatbytes[i] = (byte)read(); - //return BitConverter.ToSingle(floatbytes, 0); - - //UPGRADE_ISSUE: Method 'java.lang.Float.intBitsToFloat' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javalangFloatintBitsToFloat_int'" - //return Float.intBitsToFloat((read() << 24) | (read() << 16) | (read() << 8) | (read())); - return BitConverter.ToSingle(BitConverter.GetBytes((read() << 24) | (read() << 16) | (read() << 8) | (read())), 0); - - } - - /// Reads an IEEE double precision (i.e., 64 bit) floating-point number - /// from the input. Prior to reading, the input should be realigned at the - /// byte level. - /// - /// - /// The next byte-aligned IEEE double (64 bit) from the input. - /// - /// - /// If the end-of file was reached before - /// getting all the necessary data. - /// - /// - /// If an I/O error ocurred. - /// - /// - public override double readDouble() - { - // CONVERSION PROBLEM? OPTIMIZE!!! - //byte[] doublebytes = new byte[8]; - //for (int i = doublebytes.Length-1; i >=0 ; i--) doublebytes[i] = (byte)read(); - //return BitConverter.ToDouble(doublebytes, 0); - - //UPGRADE_ISSUE: Method 'java.lang.Double.longBitsToDouble' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javalangDoublelongBitsToDouble_long'" - //return Double.longBitsToDouble(((long) read() << 56) | ((long) read() << 48) | ((long) read() << 40) | ((long) read() << 32) | ((long) read() << 24) | ((long) read() << 16) | ((long) read() << 8) | ((long) read())); - - return BitConverter.ToDouble(BitConverter.GetBytes(((long)read() << 56) | ((long)read() << 48) | ((long)read() << 40) | ((long)read() << 32) | ((long)read() << 24) | ((long)read() << 16) | ((long)read() << 8) | ((long)read())), 0); - - } - - /// Returns a string of information about the file and the endianess - /// - /// - public override System.String ToString() - { - return base.ToString() + "\nBig-Endian ordering"; - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/io/BinaryDataInput.cs b/CSJ2K/j2k/io/BinaryDataInput.cs deleted file mode 100644 index d4e24035..00000000 --- a/CSJ2K/j2k/io/BinaryDataInput.cs +++ /dev/null @@ -1,252 +0,0 @@ -/* -* CVS Identifier: -* -* $Id: BinaryDataInput.java,v 1.12 2001/07/23 09:27:26 grosbois Exp $ -* -* Interface: BinaryDataInput -* -* Description: Stream like interface for binary -* input from a stream or file. -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -namespace CSJ2K.j2k.io -{ - - /// This interface defines the input of binary data from streams and/or files. - /// - ///

    Byte level input (i.e., for byte, int, long, float, etc.) should always - /// be byte aligned. For example, a request to read an int should - /// always realign the input at the byte level.

    - /// - ///

    The implementation of this interface should clearly define if multi-byte - /// input data is read in little- or big-endian byte ordering (least - /// significant byte first or most significant byte first, respectively).

    - /// - ///
    - /// - /// - /// - public interface BinaryDataInput - { - /// Returns the endianess (i.e., byte ordering) of the implementing - /// class. Note that an implementing class may implement only one type of - /// endianness or both, which would be decided at creatiuon time. - /// - /// - /// Either EndianType.BIG_ENDIAN or - /// EndianType.LITTLE_ENDIAN - /// - /// - /// - /// - /// - int ByteOrdering - { - get; - - } - - /// Should read a signed byte (i.e., 8 bit) from the input. reading, the - /// input should be realigned at the byte level. - /// - /// - /// The next byte-aligned signed byte (8 bit) from the input. - /// - /// - /// If the end-of file was reached before getting - /// all the necessary data. - /// - /// - /// If an I/O error ocurred. - /// - /// - byte readByte(); - - /// Should read an unsigned byte (i.e., 8 bit) from the input. It is - /// returned as an int since Java does not have an unsigned byte - /// type. Prior to reading, the input should be realigned at the byte - /// level. - /// - /// - /// The next byte-aligned unsigned byte (8 bit) from the input, as - /// an int. - /// - /// - /// If the end-of file was reached before getting - /// all the necessary data. - /// - /// - /// If an I/O error ocurred. - /// - /// - byte readUnsignedByte(); - - /// Should read a signed short (i.e., 16 bit) from the input. Prior to - /// reading, the input should be realigned at the byte level. - /// - /// - /// The next byte-aligned signed short (16 bit) from the input. - /// - /// - /// If the end-of file was reached before getting - /// all the necessary data. - /// - /// - /// If an I/O error ocurred. - /// - /// - short readShort(); - - /// Should read an unsigned short (i.e., 16 bit) from the input. It is - /// returned as an int since Java does not have an unsigned short - /// type. Prior to reading, the input should be realigned at the byte - /// level. - /// - /// - /// The next byte-aligned unsigned short (16 bit) from the input, - /// as an int. - /// - /// - /// If the end-of file was reached before getting - /// all the necessary data. - /// - /// - /// If an I/O error ocurred. - /// - /// - int readUnsignedShort(); - - /// Should read a signed int (i.e., 32 bit) from the input. Prior to - /// reading, the input should be realigned at the byte level. - /// - /// - /// The next byte-aligned signed int (32 bit) from the input. - /// - /// - /// If the end-of file was reached before getting - /// all the necessary data. - /// - /// - /// If an I/O error ocurred. - /// - /// - int readInt(); - - /// Should read an unsigned int (i.e., 32 bit) from the input. It is - /// returned as a long since Java does not have an unsigned short - /// type. Prior to reading, the input should be realigned at the byte - /// level. - /// - /// - /// The next byte-aligned unsigned int (32 bit) from the input, as - /// a long. - /// - /// - /// If the end-of file was reached before getting - /// all the necessary data. - /// - /// - /// If an I/O error ocurred. - /// - /// - long readUnsignedInt(); - - /// Should read a signed long (i.e., 64 bit) from the input. Prior to - /// reading, the input should be realigned at the byte level. - /// - /// - /// The next byte-aligned signed long (64 bit) from the input. - /// - /// - /// If the end-of file was reached before getting - /// all the necessary data. - /// - /// - /// If an I/O error ocurred. - /// - /// - long readLong(); - - /// Should read an IEEE single precision (i.e., 32 bit) floating-point - /// number from the input. Prior to reading, the input should be realigned - /// at the byte level. - /// - /// - /// The next byte-aligned IEEE float (32 bit) from the input. - /// - /// - /// If the end-of file was reached before getting - /// all the necessary data. - /// - /// - /// If an I/O error ocurred. - /// - /// - float readFloat(); - - /// Should read an IEEE double precision (i.e., 64 bit) floating-point - /// number from the input. Prior to reading, the input should be realigned - /// at the byte level. - /// - /// - /// The next byte-aligned IEEE double (64 bit) from the input. - /// - /// - /// If the end-of file was reached before getting - /// all the necessary data. - /// - /// - /// If an I/O error ocurred. - /// - /// - double readDouble(); - - /// Skips n bytes from the input. Prior to skipping, the input - /// should be realigned at the byte level. - /// - /// - /// The number of bytes to skip - /// - /// - /// If the end-of file was reached before all the - /// bytes could be skipped. - /// - /// - /// If an I/O error ocurred. - /// - /// - int skipBytes(int n); - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/io/BinaryDataOutput.cs b/CSJ2K/j2k/io/BinaryDataOutput.cs deleted file mode 100644 index dd5b6273..00000000 --- a/CSJ2K/j2k/io/BinaryDataOutput.cs +++ /dev/null @@ -1,201 +0,0 @@ -/* -* CVS Identifier: -* -* $Id: BinaryDataOutput.java,v 1.11 2000/09/05 09:24:33 grosbois Exp $ -* -* Interface: BinaryDataOutput -* -* Description: Stream like interface for bit as well as byte -* level output to a stream or file. -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* -* -* -*/ -namespace CSJ2K.j2k.io -{ - - /// This interface defines the output of binary data to streams and/or files. - /// - ///

    Byte level output (i.e., for byte, int, long, float, etc.) should - /// always be byte aligned. For example, a request to write an - /// int should always realign the output at the byte level. - /// - ///

    The implementation of this interface should clearly define if - /// multi-byte output data is written in little- or big-endian byte - /// ordering (least significant byte first or most significant byte - /// first, respectively). - /// - ///

    - /// - /// - /// - public interface BinaryDataOutput - { - /// Returns the endianness (i.e., byte ordering) of the implementing - /// class. Note that an implementing class may implement only one - /// type of endianness or both, which would be decided at creatiuon - /// time. - /// - /// - /// Either EndianType.BIG_ENDIAN or - /// EndianType.LITTLE_ENDIAN - /// - /// - /// - /// - /// - /// - /// - int ByteOrdering - { - get; - - } - - /// Should write the byte value of v (i.e., 8 least - /// significant bits) to the output. Prior to writing, the output - /// should be realigned at the byte level. - /// - ///

    Signed or unsigned data can be written. To write a signed - /// value just pass the byte value as an argument. To - /// write unsigned data pass the int value as an argument - /// (it will be automatically casted, and only the 8 least - /// significant bits will be written). - /// - ///

    - /// The value to write to the output - /// - /// - /// If an I/O error ocurred. - /// - /// - /// - /// - void writeByte(int v); - - /// Should write the short value of v (i.e., 16 least - /// significant bits) to the output. Prior to writing, the output - /// should be realigned at the byte level. - /// - ///

    Signed or unsigned data can be written. To write a signed - /// value just pass the short value as an argument. To - /// write unsigned data pass the int value as an argument - /// (it will be automatically casted, and only the 16 least - /// significant bits will be written). - /// - ///

    - /// The value to write to the output - /// - /// - /// If an I/O error ocurred. - /// - /// - /// - /// - void writeShort(int v); - - /// Should write the int value of v (i.e., the 32 bits) to - /// the output. Prior to writing, the output should be realigned at - /// the byte level. - /// - /// - /// The value to write to the output - /// - /// - /// If an I/O error ocurred. - /// - /// - /// - /// - void writeInt(int v); - - /// Should write the long value of v (i.e., the 64 bits) - /// to the output. Prior to writing, the output should be realigned - /// at the byte level. - /// - /// - /// The value to write to the output - /// - /// - /// If an I/O error ocurred. - /// - /// - /// - /// - void writeLong(long v); - - /// Should write the IEEE float value v (i.e., 32 bits) to - /// the output. Prior to writing, the output should be realigned at - /// the byte level. - /// - /// - /// The value to write to the output - /// - /// - /// If an I/O error ocurred. - /// - /// - /// - /// - void writeFloat(float v); - - /// Should write the IEEE double value v (i.e., 64 bits) - /// to the output. Prior to writing, the output should be realigned - /// at the byte level. - /// - /// - /// The value to write to the output - /// - /// - /// If an I/O error ocurred. - /// - /// - /// - /// - void writeDouble(double v); - - /// Any data that has been buffered must be written, and the stream should - /// be realigned at the byte level. - /// - /// - /// If an I/O error ocurred. - /// - /// - /// - /// - void flush(); - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/io/BufferedRandomAccessFile.cs b/CSJ2K/j2k/io/BufferedRandomAccessFile.cs deleted file mode 100644 index 2a5cf0c3..00000000 --- a/CSJ2K/j2k/io/BufferedRandomAccessFile.cs +++ /dev/null @@ -1,742 +0,0 @@ -/* -* CVS Identifier: -* -* $Id: BufferedRandomAccessFile.java,v 1.21 2001/04/15 14:34:29 grosbois Exp $ -* -* Interface: RandomAccessIO.java -* -* Description: Abstract class for buffered random access I/O. -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using System; -namespace CSJ2K.j2k.io -{ - - /// This class defines a Buffered Random Access File. It implements the - /// BinaryDataInput and BinaryDataOutput interfaces so that - /// binary data input/output can be performed. This class is abstract since no - /// assumption is done about the byte ordering type (little Endian, big - /// Endian). So subclasses will have to implement methods like - /// readShort(), writeShort(), readFloat(), ... - /// - ///

    BufferedRandomAccessFile (BRAF for short) is a - /// RandomAccessFile containing an extra buffer. When the BRAF is - /// accessed, it checks if the requested part of the file is in the buffer or - /// not. If that is the case, the read/write is done on the buffer. If not, the - /// file is uppdated to reflect the current status of the buffer and the file - /// is then accessed for a new buffer containing the requested byte/bit. - /// - ///

    - /// - /// - /// - /// - /// - /// - /// - /// - /// - public abstract class BufferedRandomAccessFile : RandomAccessIO, EndianType - { - /// Returns the current offset in the file - /// - /// - virtual public int Pos - { - get - { - return (offset + position); - } - - } - /// Returns the endianess (i.e., byte ordering) of the implementing - /// class. Note that an implementing class may implement only one - /// type of endianness or both, which would be decided at creation - /// time. - /// - /// - /// Either EndianType.BIG_ENDIAN or - /// EndianType.LITTLE_ENDIAN - /// - /// - /// - /// - /// - virtual public int ByteOrdering - { - get - { - return byte_Ordering; - } - - } - - /// The name of the current file - private System.String fileName; - - /// Whether the opened file is read only or not (defined by the constructor - /// arguments) - /// - /// - private bool isReadOnly = true; - - /// The RandomAccessFile associated with the buffer - /// - /// - //UPGRADE_TODO: Class 'java.io.RandomAccessFile' was converted to 'System.IO.FileStream' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioRandomAccessFile'" - private System.IO.FileStream theFile; - - /// Buffer of bytes containing the part of the file that is currently being - /// accessed - /// - /// - protected internal byte[] byteBuffer; - - /// Boolean keeping track of whether the byte buffer has been changed since - /// it was read. - /// - /// - protected internal bool byteBufferChanged; - - /// The current offset of the buffer (which will differ from the offset of - /// the file) - /// - /// - protected internal int offset; - - /// The current position in the byte-buffer - /// - /// - protected internal int position; - - /// The maximum number of bytes that can be read from the buffer - /// - /// - protected internal int maxByte; - - /// Whether the end of the file is in the current buffer or not - /// - /// - protected internal bool isEOFInBuffer; - - /* The endianess of the class */ - protected internal int byte_Ordering; - - /// Constructor. Always needs a size for the buffer. - /// - /// - /// The file associated with the buffer - /// - /// - /// "r" for read, "rw" or "rw+" for read and write mode ("rw+" - /// opens the file for update whereas "rw" removes it - /// before. So the 2 modes are different only if the file - /// already exists). - /// - /// - /// The number of bytes to buffer - /// - /// - /// If an I/O error ocurred. - /// - /// - protected internal BufferedRandomAccessFile(System.IO.FileInfo file, System.String mode, int bufferSize) - { - - fileName = file.Name; - if (mode.Equals("rw") || mode.Equals("rw+")) - { - // mode read / write - isReadOnly = false; - if (mode.Equals("rw")) - { - // mode read / (over)write - bool tmpBool; - if (System.IO.File.Exists(file.FullName)) - tmpBool = true; - else - tmpBool = System.IO.Directory.Exists(file.FullName); - if (tmpBool) - // Output file already exists - { - bool tmpBool2; - if (System.IO.File.Exists(file.FullName)) - { - System.IO.File.Delete(file.FullName); - tmpBool2 = true; - } - else if (System.IO.Directory.Exists(file.FullName)) - { - System.IO.Directory.Delete(file.FullName); - tmpBool2 = true; - } - else - tmpBool2 = false; - bool generatedAux = tmpBool2; - } - } - mode = "rw"; - } - theFile = SupportClass.RandomAccessFileSupport.CreateRandomAccessFile(file, mode); - byteBuffer = new byte[bufferSize]; - readNewBuffer(0); - } - - /// Constructor. Uses the default value for the byte-buffer - /// size (512 bytes). - /// - /// - /// The file associated with the buffer - /// - /// - /// "r" for read, "rw" or "rw+" for read and write mode - /// ("rw+" opens the file for update whereas "rw" removes - /// it before. So the 2 modes are different only if the - /// file already exists). - /// - /// - /// If an I/O error ocurred. - /// - /// - protected internal BufferedRandomAccessFile(System.IO.FileInfo file, System.String mode) : this(file, mode, 512) - { - } - - /// Constructor. Always needs a size for the buffer. - /// - /// - /// The name of the file associated with the buffer - /// - /// - /// "r" for read, "rw" or "rw+" for read and write mode - /// ("rw+" opens the file for update whereas "rw" removes - /// it before. So the 2 modes are different only if the - /// file already exists). - /// - /// - /// The number of bytes to buffer - /// - /// - /// If an I/O error ocurred. - /// - /// - protected internal BufferedRandomAccessFile(System.String name, System.String mode, int bufferSize) : this(new System.IO.FileInfo(name), mode, bufferSize) - { - } - - /// Constructor. Uses the default value for the byte-buffer - /// size (512 bytes). - /// - /// - /// The name of the file associated with the buffer - /// - /// - /// "r" for read, "rw" or "rw+" for read and write mode - /// ("rw+" opens the file for update whereas "rw" removes - /// it before. So the 2 modes are different only if the - /// file already exists). - /// - /// - /// If an I/O error ocurred. - /// - /// - protected internal BufferedRandomAccessFile(System.String name, System.String mode) : this(name, mode, 512) - { - } - - /// Reads a new buffer from the file. If there has been any - /// changes made since the buffer was read, the buffer is - /// first written to the file. - /// - /// - /// The offset where to move to. - /// - /// - /// If an I/O error ocurred. - /// - /// - protected internal void readNewBuffer(int off) - { - - /* If the buffer have changed. We need to write it to - * the file before reading a new buffer. - */ - if (byteBufferChanged) - { - flush(); - } - // Don't allow to seek beyond end of file if reading only - if (isReadOnly && off >= theFile.Length) - { - throw new System.IO.EndOfStreamException(); - } - // Set new offset - offset = off; - - theFile.Seek(offset, System.IO.SeekOrigin.Begin); - - maxByte = theFile.Read(byteBuffer, 0, byteBuffer.Length); - position = 0; - - if (maxByte < byteBuffer.Length) - { - // Not enough data in input file. - isEOFInBuffer = true; - if (maxByte == -1) - { - maxByte++; - } - } - else - { - isEOFInBuffer = false; - } - } - - /// Closes the buffered random access file - /// - /// - /// If an I/O error ocurred. - /// - /// - public virtual void close() - { - /* If the buffer has been changed, it need to be saved before - * closing - */ - flush(); - byteBuffer = null; // Release the byte-buffer reference - theFile.Close(); - } - - /// Returns the current length of the stream, in bytes, taking into - /// account any buffering. - /// - /// - /// The length of the stream, in bytes. - /// - /// - /// If an I/O error ocurred. - /// - /// - public virtual int length() - { - int len; - - len = (int)theFile.Length; - - // If the position in the buffer is not past the end of the file, - // the length of theFile is the length of the stream - if ((offset + maxByte) <= len) - { - return (len); - } - else - { - // If not, the file is extended due to the buffering - return (offset + maxByte); - } - } - - /// Moves the current position to the given offset at which the - /// next read or write occurs. The offset is measured from the - /// beginning of the stream. - /// - /// - /// The offset where to move to. - /// - /// - /// If in read-only and seeking beyond EOF. - /// - /// - /// If an I/O error ocurred. - /// - /// - public virtual void seek(int off) - { - /* If the new offset is within the buffer, only the pos value needs - * to be modified. Else, the buffer must be moved. */ - if ((off >= offset) && (off < (offset + byteBuffer.Length))) - { - if (isReadOnly && isEOFInBuffer && off > offset + maxByte) - { - // We are seeking beyond EOF in read-only mode! - throw new System.IO.EndOfStreamException(); - } - position = off - offset; - } - else - { - readNewBuffer(off); - } - } - - /// Reads an unsigned byte of data from the stream. Prior to reading, the - /// stream is realigned at the byte level. - /// - /// - /// The byte read. - /// - /// - /// If an I/O error ocurred. - /// - /// - /// If the end of file was reached - /// - /// - public byte readByte() { return read(); } - public byte readUnsignedByte() { return read(); } - public byte read() - { - if (position < maxByte) - { - // The byte can be read from the buffer - // In Java, the bytes are always signed. - return (byteBuffer[position++]); - } - else if (isEOFInBuffer) - { - // EOF is reached - position = maxByte + 1; // Set position to EOF - throw new System.IO.EndOfStreamException(); - } - else - { - // End of the buffer is reached - readNewBuffer(offset + position); - return read(); - } - } - - /// Reads up to len bytes of data from this file into an array of - /// bytes. This method reads repeatedly from the stream until all the bytes - /// are read. This method blocks until all the bytes are read, the end of - /// the stream is detected, or an exception is thrown. - /// - /// - /// The buffer into which the data is to be read. It must be long - /// enough. - /// - /// - /// The index in 'b' where to place the first byte read. - /// - /// - /// The number of bytes to read. - /// - /// - /// If the end-of file was reached before - /// getting all the necessary data. - /// - /// - /// If an I/O error ocurred. - /// - /// - public void readFully(byte[] b, int off, int len) - { - int clen; // current length to read - while (len > 0) - { - // There still is some data to read - if (position < maxByte) - { - // We can read some data from buffer - clen = maxByte - position; - if (clen > len) - clen = len; - Array.Copy(byteBuffer, position, b, off, clen); - position += clen; - off += clen; - len -= clen; - } - else if (isEOFInBuffer) - { - position = maxByte + 1; // Set position to EOF - throw new System.IO.EndOfStreamException(); - } - else - { - // Buffer empty => get more data - readNewBuffer(offset + position); - } - } - } - - /// Writes a byte to the stream. Prior to writing, the stream is - /// realigned at the byte level. - /// - /// - /// The byte to write. The lower 8 bits of b are - /// written. - /// - /// - /// If an I/O error ocurred. - /// - /// - public void write(int b) - { - // As long as pos is less than the length of the buffer we can write - // to the buffer. If the position is after the buffer a new buffer is - // needed - if (position < byteBuffer.Length) - { - if (isReadOnly) - throw new System.IO.IOException("File is read only"); - byteBuffer[position] = (byte)b; - if (position >= maxByte) - { - maxByte = position + 1; - } - position++; - byteBufferChanged = true; - } - else - { - readNewBuffer(offset + position); - write(b); - } - } - - /// Writes a byte to the stream. Prior to writing, the stream is - /// realigned at the byte level. - /// - /// - /// The byte to write. - /// - /// - /// If an I/O error ocurred. - /// - /// - public void write(byte b) - { - // As long as pos is less than the length of the buffer we can write - // to the buffer. If the position is after the buffer a new buffer is - // needed - if (position < byteBuffer.Length) - { - if (isReadOnly) - throw new System.IO.IOException("File is read only"); - byteBuffer[position] = b; - if (position >= maxByte) - { - maxByte = position + 1; - } - position++; - byteBufferChanged = true; - } - else - { - readNewBuffer(offset + position); - write(b); - } - } - - /// Writes aan array of bytes to the stream. Prior to writing, the stream is - /// realigned at the byte level. - /// - /// - /// The array of bytes to write. - /// - /// - /// The first byte in b to write - /// - /// - /// The number of bytes from b to write - /// - /// - /// If an I/O error ocurred. - /// - /// - public void write(byte[] b, int offset, int length) - { - int i, stop; - stop = offset + length; - if (stop > b.Length) - throw new System.IndexOutOfRangeException("Index of bound " + b.Length); - for (i = offset; i < stop; i++) - { - write(b[i]); - } - } - - /// Writes the byte value of v (i.e., 8 least - /// significant bits) to the output. Prior to writing, the output - /// should be realigned at the byte level. - /// - ///

    Signed or unsigned data can be written. To write a signed - /// value just pass the byte value as an argument. To - /// write unsigned data pass the int value as an argument - /// (it will be automatically casted, and only the 8 least - /// significant bits will be written). - /// - ///

    - /// The value to write to the output - /// - /// - /// If an I/O error ocurred. - /// - /// - public void writeByte(int v) - { - write(v); - } - - /// Any data that has been buffered must be written (including - /// buffering at the bit level), and the stream should be realigned - /// at the byte level. - /// - /// - /// If an I/O error ocurred. - /// - /// - public void flush() - { - if (byteBufferChanged) - { - theFile.Seek(offset, System.IO.SeekOrigin.Begin); - theFile.Write(byteBuffer, 0, maxByte); - byteBufferChanged = false; - } - } - /* - /// Reads a signed byte (i.e., 8 bit) from the input. Prior to - /// reading, the input should be realigned at the byte level. - /// - /// - /// The next byte-aligned signed byte (8 bit) from the - /// input. - /// - /// - /// If the end-of file was reached before - /// getting all the necessary data. - /// - /// - /// If an I/O error ocurred. - /// - /// - public byte readByte() - { - if (pos < maxByte) - { - // The byte can be read from the buffer - // In Java, the bytes are always signed. - return byteBuffer[pos++]; - } - else if (isEOFInBuffer) - { - // EOF is reached - pos = maxByte + 1; // Set position to EOF - throw new System.IO.EndOfStreamException(); - } - else - { - // End of the buffer is reached - readNewBuffer(offset + pos); - return readByte(); - } - } - - /// Reads an unsigned byte (i.e., 8 bit) from the input. It is - /// returned as an int since Java does not have an - /// unsigned byte type. Prior to reading, the input should be - /// realigned at the byte level. - /// - /// - /// The next byte-aligned unsigned byte (8 bit) from the - /// input, as an int. - /// - /// - /// If the end-of file was reached before - /// getting all the necessary data. - /// - /// - /// If an I/O error ocurred. - /// - /// - public int readUnsignedByte() - { - return read(); - } - */ - /// Skips n bytes from the input. Prior to skipping, the - /// input should be realigned at the byte level. - /// - /// - /// The number of bytes to skip - /// - /// - /// If the end-of file was reached before - /// all the bytes could be skipped. - /// - /// - /// If an I/O error ocurred. - /// - /// - public virtual int skipBytes(int n) - { - if (n < 0) - throw new System.ArgumentException("Can not skip negative number " + "of bytes"); - if (n <= (maxByte - position)) - { - position += n; - return n; - } - else - { - seek(offset + position + n); - return n; - } - } - - /// Returns a string of information about the file - /// - /// - public override System.String ToString() - { - return "BufferedRandomAccessFile: " + fileName + " (" + ((isReadOnly) ? "read only" : "read/write") + ")"; - } - public abstract int readUnsignedShort(); - public abstract void writeLong(long param1); - public abstract void writeShort(int param1); - public abstract float readFloat(); - public abstract short readShort(); - public abstract double readDouble(); - public abstract int readInt(); - public abstract long readLong(); - public abstract long readUnsignedInt(); - public abstract void writeDouble(double param1); - public abstract void writeFloat(float param1); - public abstract void writeInt(int param1); - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/io/EndianType.cs b/CSJ2K/j2k/io/EndianType.cs deleted file mode 100644 index 8d06f719..00000000 --- a/CSJ2K/j2k/io/EndianType.cs +++ /dev/null @@ -1,80 +0,0 @@ -/* -* CVS Identifier: -* -* $Id: EndianType.java,v 1.10 2000/09/05 09:24:36 grosbois Exp $ -* -* Interface: EndianType -* -* Description: Defines the two types of endianess (i.e. byte -* ordering). -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* -* -* -*/ -namespace CSJ2K.j2k.io -{ - - /// This interface defines constants for the two types of byte - /// ordering: little- and big-endian. - /// - ///

    Little-endian is least significant byte first. - /// - ///

    Big-endian is most significant byte first. - /// - ///

    This interface defines the constants only. In order to use the - /// constants in any other class you can either use the fully qualified - /// name (e.g., EndianType.LITTLE_ENDIAN) or declare this - /// interface in the implements clause of the class and then access the - /// identifier directly. - /// - ///

    - public struct EndianType_Fields - { - /// Identifier for big-endian byte ordering (i.e. most significant - /// byte first) - /// - public const int BIG_ENDIAN = 0; - /// Identifier for little-endian byte ordering (i.e. least - /// significant byte first) - /// - public const int LITTLE_ENDIAN = 1; - } - public interface EndianType - { - //UPGRADE_NOTE: Members of interface 'EndianType' were extracted into structure 'EndianType_Fields'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1045'" - - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/io/RandomAccessIO.cs b/CSJ2K/j2k/io/RandomAccessIO.cs deleted file mode 100644 index bbefedc4..00000000 --- a/CSJ2K/j2k/io/RandomAccessIO.cs +++ /dev/null @@ -1,170 +0,0 @@ -/* -* CVS Identifier: -* -* $Id: RandomAccessIO.java,v 1.15 2001/10/24 12:07:02 grosbois Exp $ -* -* Interface: RandomAccessIO.java -* -* Description: Interface definition for random access I/O. -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -namespace CSJ2K.j2k.io -{ - - /// This abstract class defines the interface to perform random access I/O. It - /// implements the BinaryDataInput and BinaryDataOutput - /// interfaces so that binary data input/output can be performed. - /// - ///

    This interface supports streams of up to 2 GB in length.

    - /// - ///
    - /// - /// - /// - /// - /// - public interface RandomAccessIO : BinaryDataInput, BinaryDataOutput - { - /// Returns the current position in the stream, which is the position from - /// where the next byte of data would be read. The first byte in the stream - /// is in position 0. - /// - /// - /// The offset of the current position, in bytes. - /// - /// - /// If an I/O error ocurred. - /// - /// - int Pos - { - get; - - } - - /// Closes the I/O stream. Prior to closing the stream, any buffered data - /// (at the bit and byte level) should be written. - /// - /// - /// If an I/O error ocurred. - /// - /// - void close(); - - /// Returns the current length of the stream, in bytes, taking into account - /// any buffering. - /// - /// - /// The length of the stream, in bytes. - /// - /// - /// If an I/O error ocurred. - /// - /// - int length(); - - /// Moves the current position for the next read or write operation to - /// offset. The offset is measured from the beginning of the stream. The - /// offset may be set beyond the end of the file, if in write mode. Setting - /// the offset beyond the end of the file does not change the file - /// length. The file length will change only by writing after the offset - /// has been set beyond the end of the file. - /// - /// - /// The offset where to move to. - /// - /// - /// If in read-only and seeking beyond EOF. - /// - /// - /// If an I/O error ocurred. - /// - /// - void seek(int off); - - /// Reads a byte of data from the stream. Prior to reading, the stream is - /// realigned at the byte level. - /// - /// - /// The byte read, as an int. - /// - /// - /// If the end-of file was reached. - /// - /// - /// If an I/O error ocurred. - /// - /// - byte read(); - - /// Reads up to len bytes of data from this file into an array of - /// bytes. This method reads repeatedly from the stream until all the bytes - /// are read. This method blocks until all the bytes are read, the end of - /// the stream is detected, or an exception is thrown. - /// - /// - /// The buffer into which the data is to be read. It must be long - /// enough. - /// - /// - /// The index in 'b' where to place the first byte read. - /// - /// - /// The number of bytes to read. - /// - /// - /// If the end-of file was reached before - /// getting all the necessary data. - /// - /// - /// If an I/O error ocurred. - /// - /// - void readFully(byte[] b, int off, int len); - - /// Writes a byte to the stream. Prior to writing, the stream is realigned - /// at the byte level. - /// - /// - /// The byte to write. The lower 8 bits of b are - /// written. - /// - /// - /// If an I/O error ocurred. - /// - /// - void write(byte b); - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/quantization/GuardBitsSpec.cs b/CSJ2K/j2k/quantization/GuardBitsSpec.cs deleted file mode 100644 index d2fe55a0..00000000 --- a/CSJ2K/j2k/quantization/GuardBitsSpec.cs +++ /dev/null @@ -1,249 +0,0 @@ -/* -* CVS identifier: -* -* $Id: GuardBitsSpec.java,v 1.13 2000/09/19 14:11:01 grosbois Exp $ -* -* Class: GuardBitsSpec -* -* Description: Guard bits specifications -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* -* -* -*/ -using CSJ2K.j2k.util; -namespace CSJ2K.j2k.quantization -{ - - /// This class extends ModuleSpec class in order to hold specifications about - /// number of guard bits in each tile-component. - /// - /// - /// - /// - /// - public class GuardBitsSpec : ModuleSpec - { - - /// Constructs an empty 'GuardBitsSpec' with specified number of tile and - /// components. This constructor is called by the decoder. - /// - /// - /// Number of tiles - /// - /// - /// Number of components - /// - /// - /// the type of the specification module i.e. tile specific, - /// component specific or both. - /// - /// - public GuardBitsSpec(int nt, int nc, byte type) : base(nt, nc, type) - { - } - - /// Constructs a new 'GuardBitsSpec' for the specified number of components - /// and tiles and the arguments of "-Qguard_bits" option. - /// - /// - /// The number of tiles - /// - /// - /// The number of components - /// - /// - /// the type of the specification module i.e. tile specific, - /// component specific or both. - /// - /// - /// The ParameterList - /// - /// - public GuardBitsSpec(int nt, int nc, byte type, ParameterList pl) : base(nt, nc, type) - { - - System.String param = pl.getParameter("Qguard_bits"); - if (param == null) - { - throw new System.ArgumentException("Qguard_bits option not " + "specified"); - } - - // Parse argument - SupportClass.Tokenizer stk = new SupportClass.Tokenizer(param); - System.String word; // current word - byte curSpecType = SPEC_DEF; // Specification type of the - // current parameter - bool[] tileSpec = null; // Tiles concerned by the specification - bool[] compSpec = null; // Components concerned by the specification - System.Int32 value_Renamed; // value of the guard bits - - while (stk.HasMoreTokens()) - { - word = stk.NextToken().ToLower(); - - switch (word[0]) - { - - case 't': // Tiles specification - tileSpec = parseIdx(word, nTiles); - if (curSpecType == SPEC_COMP_DEF) - curSpecType = SPEC_TILE_COMP; - else - curSpecType = SPEC_TILE_DEF; - break; - - case 'c': // Components specification - compSpec = parseIdx(word, nComp); - if (curSpecType == SPEC_TILE_DEF) - curSpecType = SPEC_TILE_COMP; - else - curSpecType = SPEC_COMP_DEF; - break; - - default: // Step size value - try - { - value_Renamed = System.Int32.Parse(word); - } - catch (System.FormatException) - { - throw new System.ArgumentException("Bad parameter for " + "-Qguard_bits option" + " : " + word); - } - - if ((float)value_Renamed <= 0.0f) - { - throw new System.ArgumentException("Guard bits value " + "must be positive : " + value_Renamed); - } - - - if (curSpecType == SPEC_DEF) - { - setDefault((System.Object)value_Renamed); - } - else if (curSpecType == SPEC_TILE_DEF) - { - for (int i = tileSpec.Length - 1; i >= 0; i--) - if (tileSpec[i]) - { - setTileDef(i, (System.Object)value_Renamed); - } - } - else if (curSpecType == SPEC_COMP_DEF) - { - for (int i = compSpec.Length - 1; i >= 0; i--) - if (compSpec[i]) - { - setCompDef(i, (System.Object)value_Renamed); - } - } - else - { - for (int i = tileSpec.Length - 1; i >= 0; i--) - { - for (int j = compSpec.Length - 1; j >= 0; j--) - { - if (tileSpec[i] && compSpec[j]) - { - setTileCompVal(i, j, (System.Object)value_Renamed); - } - } - } - } - - // Re-initialize - curSpecType = SPEC_DEF; - tileSpec = null; - compSpec = null; - break; - - } - } - - // Check that default value has been specified - if (getDefault() == null) - { - int ndefspec = 0; - for (int t = nt - 1; t >= 0; t--) - { - for (int c = nc - 1; c >= 0; c--) - { - if (specValType[t][c] == SPEC_DEF) - { - ndefspec++; - } - } - } - - // If some tile-component have received no specification, it takes - // the default value defined in ParameterList - if (ndefspec != 0) - { - setDefault((System.Object)System.Int32.Parse(pl.DefaultParameterList.getParameter("Qguard_bits"))); - } - else - { - // All tile-component have been specified, takes the first - // tile-component value as default. - setDefault(getTileCompVal(0, 0)); - switch (specValType[0][0]) - { - - case SPEC_TILE_DEF: - for (int c = nc - 1; c >= 0; c--) - { - if (specValType[0][c] == SPEC_TILE_DEF) - specValType[0][c] = SPEC_DEF; - } - tileDef[0] = null; - break; - - case SPEC_COMP_DEF: - for (int t = nt - 1; t >= 0; t--) - { - if (specValType[t][0] == SPEC_COMP_DEF) - specValType[t][0] = SPEC_DEF; - } - compDef[0] = null; - break; - - case SPEC_TILE_COMP: - specValType[0][0] = SPEC_DEF; - tileCompVal["t0c0"] = null; - break; - } - } - } - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/quantization/QuantStepSizeSpec.cs b/CSJ2K/j2k/quantization/QuantStepSizeSpec.cs deleted file mode 100644 index 31dd3c8d..00000000 --- a/CSJ2K/j2k/quantization/QuantStepSizeSpec.cs +++ /dev/null @@ -1,252 +0,0 @@ -/* -* CVS identifier: -* -* $Id: QuantStepSizeSpec.java,v 1.12 2001/10/24 12:05:04 grosbois Exp $ -* -* Class: QuantStepSizeSpec -* -* Description: Quantization base normalized step size specifications -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.util; -namespace CSJ2K.j2k.quantization -{ - - /// This class extends ModuleSpec class in order to hold specifications about - /// the quantization base normalized step size to use in each tile-component. - /// - /// - /// - /// - /// - public class QuantStepSizeSpec : ModuleSpec - { - - /// Constructs an empty 'QuantStepSizeSpec' with specified number of - /// tile and components. This constructor is called by the decoder. - /// - /// - /// Number of tiles - /// - /// - /// Number of components - /// - /// - /// the type of the specification module i.e. tile specific, - /// component specific or both. - /// - /// - public QuantStepSizeSpec(int nt, int nc, byte type) : base(nt, nc, type) - { - } - - /// Constructs a new 'QuantStepSizeSpec' for the specified number of - /// components and tiles and the arguments of "-Qstep" option. - /// - /// - /// The number of tiles - /// - /// - /// The number of components - /// - /// - /// the type of the specification module i.e. tile specific, - /// component specific or both. - /// - /// - /// The ParameterList - /// - /// - public QuantStepSizeSpec(int nt, int nc, byte type, ParameterList pl) : base(nt, nc, type) - { - - System.String param = pl.getParameter("Qstep"); - if (param == null) - { - throw new System.ArgumentException("Qstep option not specified"); - } - - // Parse argument - SupportClass.Tokenizer stk = new SupportClass.Tokenizer(param); - System.String word; // current word - byte curSpecType = SPEC_DEF; // Specification type of the - // current parameter - bool[] tileSpec = null; // Tiles concerned by the specification - bool[] compSpec = null; // Components concerned by the specification - System.Single value_Renamed; // value of the current step size - - while (stk.HasMoreTokens()) - { - word = stk.NextToken().ToLower(); - - switch (word[0]) - { - - case 't': // Tiles specification - tileSpec = parseIdx(word, nTiles); - if (curSpecType == SPEC_COMP_DEF) - curSpecType = SPEC_TILE_COMP; - else - curSpecType = SPEC_TILE_DEF; - break; - - case 'c': // Components specification - compSpec = parseIdx(word, nComp); - if (curSpecType == SPEC_TILE_DEF) - curSpecType = SPEC_TILE_COMP; - else - curSpecType = SPEC_COMP_DEF; - break; - - default: // Step size value - try - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - value_Renamed = System.Single.Parse(word); - } - catch (System.FormatException) - { - throw new System.ArgumentException("Bad parameter for " + "-Qstep option : " + word); - } - - //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Float.floatValue' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" - if ((float)value_Renamed <= 0.0f) - { - //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Float.toString' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" - throw new System.ArgumentException("Normalized base step " + "must be positive : " + value_Renamed); - } - - - if (curSpecType == SPEC_DEF) - { - setDefault((System.Object)value_Renamed); - } - else if (curSpecType == SPEC_TILE_DEF) - { - for (int i = tileSpec.Length - 1; i >= 0; i--) - if (tileSpec[i]) - { - setTileDef(i, (System.Object)value_Renamed); - } - } - else if (curSpecType == SPEC_COMP_DEF) - { - for (int i = compSpec.Length - 1; i >= 0; i--) - if (compSpec[i]) - { - setCompDef(i, (System.Object)value_Renamed); - } - } - else - { - for (int i = tileSpec.Length - 1; i >= 0; i--) - { - for (int j = compSpec.Length - 1; j >= 0; j--) - { - if (tileSpec[i] && compSpec[j]) - { - setTileCompVal(i, j, (System.Object)value_Renamed); - } - } - } - } - - // Re-initialize - curSpecType = SPEC_DEF; - tileSpec = null; - compSpec = null; - break; - - } - } - - // Check that default value has been specified - if (getDefault() == null) - { - int ndefspec = 0; - for (int t = nt - 1; t >= 0; t--) - { - for (int c = nc - 1; c >= 0; c--) - { - if (specValType[t][c] == SPEC_DEF) - { - ndefspec++; - } - } - } - - // If some tile-component have received no specification, it takes - // the default value defined in ParameterList - if (ndefspec != 0) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - setDefault((System.Object)System.Single.Parse(pl.DefaultParameterList.getParameter("Qstep"))); - } - else - { - // All tile-component have been specified, takes the first - // tile-component value as default. - setDefault(getTileCompVal(0, 0)); - switch (specValType[0][0]) - { - - case SPEC_TILE_DEF: - for (int c = nc - 1; c >= 0; c--) - { - if (specValType[0][c] == SPEC_TILE_DEF) - specValType[0][c] = SPEC_DEF; - } - tileDef[0] = null; - break; - - case SPEC_COMP_DEF: - for (int t = nt - 1; t >= 0; t--) - { - if (specValType[t][0] == SPEC_COMP_DEF) - specValType[t][0] = SPEC_DEF; - } - compDef[0] = null; - break; - - case SPEC_TILE_COMP: - specValType[0][0] = SPEC_DEF; - tileCompVal["t0c0"] = null; - break; - } - } - } - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/quantization/QuantTypeSpec.cs b/CSJ2K/j2k/quantization/QuantTypeSpec.cs deleted file mode 100644 index 142bf208..00000000 --- a/CSJ2K/j2k/quantization/QuantTypeSpec.cs +++ /dev/null @@ -1,390 +0,0 @@ -/* -* CVS identifier: -* -* $Id: QuantTypeSpec.java,v 1.18 2001/10/24 12:05:18 grosbois Exp $ -* -* Class: QuantTypeSpec -* -* Description: Quantization type specifications -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.util; -namespace CSJ2K.j2k.quantization -{ - - /// This class extends ModuleSpec class in order to hold specifications about - /// the quantization type to use in each tile-component. Supported quantization - /// type are:
    - /// - ///
      - ///
    • Reversible (no quantization)
    • - ///
    • Derived (the quantization step size is derived from the one of the - /// LL-subband)
    • - ///
    • Expounded (the quantization step size of each subband is signalled in - /// the codestream headers)
    • - ///
    - /// - ///
    - /// - /// - /// - public class QuantTypeSpec : ModuleSpec - { - /// Check the reversibility of the whole image. - /// - /// - /// Whether or not the whole image is reversible - /// - /// - virtual public bool FullyReversible - { - get - { - // The whole image is reversible if default specification is - // rev and no tile default, component default and - // tile-component value has been specificied - if (((System.String)getDefault()).Equals("reversible")) - { - for (int t = nTiles - 1; t >= 0; t--) - for (int c = nComp - 1; c >= 0; c--) - if (specValType[t][c] != SPEC_DEF) - return false; - return true; - } - - return false; - } - - } - /// Check the irreversibility of the whole image. - /// - /// - /// Whether or not the whole image is reversible - /// - /// - virtual public bool FullyNonReversible - { - get - { - // The whole image is irreversible no tile-component is reversible - for (int t = nTiles - 1; t >= 0; t--) - for (int c = nComp - 1; c >= 0; c--) - if (((System.String)getSpec(t, c)).Equals("reversible")) - return false; - return true; - } - - } - - /// Constructs an empty 'QuantTypeSpec' with the specified number of tiles - /// and components. This constructor is called by the decoder. - /// - /// - /// Number of tiles - /// - /// - /// Number of components - /// - /// - /// the type of the allowed specifications for this module - /// i.e. tile specific, component specific or both. - /// - /// - public QuantTypeSpec(int nt, int nc, byte type) : base(nt, nc, type) - { - } - - - /// Constructs a new 'QuantTypeSpec' for the specified number of components - /// and tiles and the arguments of "-Qtype" option. This constructor is - /// called by the encoder. - /// - /// - /// The number of tiles - /// - /// - /// The number of components - /// - /// - /// the type of the specification module i.e. tile specific, - /// component specific or both. - /// - /// - /// The ParameterList - /// - /// - public QuantTypeSpec(int nt, int nc, byte type, ParameterList pl) : base(nt, nc, type) - { - - System.String param = pl.getParameter("Qtype"); - if (param == null) - { - if (pl.getBooleanParameter("lossless")) - { - setDefault("reversible"); - } - else - { - setDefault("expounded"); - } - return; - } - - // Parse argument - SupportClass.Tokenizer stk = new SupportClass.Tokenizer(param); - System.String word; // current word - byte curSpecValType = SPEC_DEF; // Specification type of the - // current parameter - bool[] tileSpec = null; // Tiles concerned by the specification - bool[] compSpec = null; // Components concerned by the specification - - while (stk.HasMoreTokens()) - { - word = stk.NextToken().ToLower(); - - switch (word[0]) - { - - case 't': // Tiles specification - tileSpec = parseIdx(word, nTiles); - - if (curSpecValType == SPEC_COMP_DEF) - { - curSpecValType = SPEC_TILE_COMP; - } - else - { - curSpecValType = SPEC_TILE_DEF; - } - break; - - case 'c': // Components specification - compSpec = parseIdx(word, nComp); - - if (curSpecValType == SPEC_TILE_DEF) - { - curSpecValType = SPEC_TILE_COMP; - } - else - { - curSpecValType = SPEC_COMP_DEF; - } - break; - - case 'r': - // reversible specification - case 'd': - // derived quantization step size specification - case 'e': // expounded quantization step size specification - if (!word.ToUpper().Equals("reversible".ToUpper()) && !word.ToUpper().Equals("derived".ToUpper()) && !word.ToUpper().Equals("expounded".ToUpper())) - { - throw new System.ArgumentException("Unknown parameter " + "for " + "'-Qtype' option: " + word); - } - - if (pl.getBooleanParameter("lossless") && (word.ToUpper().Equals("derived".ToUpper()) || word.ToUpper().Equals("expounded".ToUpper()))) - { - throw new System.ArgumentException("Cannot use non " + "reversible " + "quantization with " + "'-lossless' option"); - } - - if (curSpecValType == SPEC_DEF) - { - // Default specification - setDefault(word); - } - else if (curSpecValType == SPEC_TILE_DEF) - { - // Tile default specification - for (int i = tileSpec.Length - 1; i >= 0; i--) - { - if (tileSpec[i]) - { - setTileDef(i, word); - } - } - } - else if (curSpecValType == SPEC_COMP_DEF) - { - // Component default specification - for (int i = compSpec.Length - 1; i >= 0; i--) - if (compSpec[i]) - { - setCompDef(i, word); - } - } - else - { - // Tile-component specification - for (int i = tileSpec.Length - 1; i >= 0; i--) - { - for (int j = compSpec.Length - 1; j >= 0; j--) - { - if (tileSpec[i] && compSpec[j]) - { - setTileCompVal(i, j, word); - } - } - } - } - - // Re-initialize - curSpecValType = SPEC_DEF; - tileSpec = null; - compSpec = null; - break; - - - default: - throw new System.ArgumentException("Unknown parameter for " + "'-Qtype' option: " + word); - - } - } - - // Check that default value has been specified - if (getDefault() == null) - { - int ndefspec = 0; - for (int t = nt - 1; t >= 0; t--) - { - for (int c = nc - 1; c >= 0; c--) - { - if (specValType[t][c] == SPEC_DEF) - { - ndefspec++; - } - } - } - - // If some tile-component have received no specification, the - // quantization type is 'reversible' (if '-lossless' is specified) - // or 'expounded' (if not). - if (ndefspec != 0) - { - if (pl.getBooleanParameter("lossless")) - { - setDefault("reversible"); - } - else - { - setDefault("expounded"); - } - } - else - { - // All tile-component have been specified, takes arbitrarily - // the first tile-component value as default and modifies the - // specification type of all tile-component sharing this - // value. - setDefault(getTileCompVal(0, 0)); - - switch (specValType[0][0]) - { - - case SPEC_TILE_DEF: - for (int c = nc - 1; c >= 0; c--) - { - if (specValType[0][c] == SPEC_TILE_DEF) - specValType[0][c] = SPEC_DEF; - } - tileDef[0] = null; - break; - - case SPEC_COMP_DEF: - for (int t = nt - 1; t >= 0; t--) - { - if (specValType[t][0] == SPEC_COMP_DEF) - specValType[t][0] = SPEC_DEF; - } - compDef[0] = null; - break; - - case SPEC_TILE_COMP: - specValType[0][0] = SPEC_DEF; - tileCompVal["t0c0"] = null; - break; - } - } - } - } - - /// Returns true if given tile-component uses derived quantization step - /// size. - /// - /// - /// Tile index - /// - /// - /// Component index - /// - /// - /// True if derived quantization step size - /// - /// - public virtual bool isDerived(int t, int c) - { - if (((System.String)getTileCompVal(t, c)).Equals("derived")) - { - return true; - } - else - { - return false; - } - } - - /// Check the reversibility of the given tile-component. - /// - /// - /// The index of the tile - /// - /// - /// The index of the component - /// - /// - /// Whether or not the tile-component is reversible - /// - /// - public virtual bool isReversible(int t, int c) - { - if (((System.String)getTileCompVal(t, c)).Equals("reversible")) - { - return true; - } - else - { - return false; - } - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/quantization/QuantizationType.cs b/CSJ2K/j2k/quantization/QuantizationType.cs deleted file mode 100644 index 255d692d..00000000 --- a/CSJ2K/j2k/quantization/QuantizationType.cs +++ /dev/null @@ -1,72 +0,0 @@ -/* -* CVS identifier: -* -* $Id: QuantizationType.java,v 1.10 2000/09/19 14:11:30 grosbois Exp $ -* -* Class: QuantizationType -* -* Description: This interface defines the possible -* quantization types. -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* -* -* -*/ -namespace CSJ2K.j2k.quantization -{ - - /// This interface defines the IDs of the possible quantization types. JPEG - /// 2000 part I support only the scalar quantization with dead zone. However - /// other quantization type may be defined in JPEG 2000 extensions (for - /// instance Trellis Coded Quantization). - /// - ///

    This interface defines the constants only. In order to use the - /// constants in any other class you can either use the fully qualified - /// name (e.g., QuantizationType.Q_TYPE_SCALAR_DZ) or declare - /// this interface in the implements clause of the class and then - /// access the identifier directly. - /// - ///

    - public struct QuantizationType_Fields - { - /// The ID of the scalar deadzone dequantizer - public readonly static int Q_TYPE_SCALAR_DZ = 0; - } - public interface QuantizationType - { - //UPGRADE_NOTE: Members of interface 'QuantizationType' were extracted into structure 'QuantizationType_Fields'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1045'" - - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/quantization/dequantizer/CBlkQuantDataSrcDec.cs b/CSJ2K/j2k/quantization/dequantizer/CBlkQuantDataSrcDec.cs deleted file mode 100644 index 70348fda..00000000 --- a/CSJ2K/j2k/quantization/dequantizer/CBlkQuantDataSrcDec.cs +++ /dev/null @@ -1,185 +0,0 @@ -/* -* CVS identifier: -* -* $Id: CBlkQuantDataSrcDec.java,v 1.9 2001/09/14 08:58:36 grosbois Exp $ -* -* Class: CBlkQuantDataSrcDec -* -* Description: Interface that defines a source of -* quantized wavelet data to be transferred in a -* code-block by code-block basis (decoder side). -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.entropy.decoder; -using CSJ2K.j2k.image; -using CSJ2K.j2k.wavelet.synthesis; -namespace CSJ2K.j2k.quantization.dequantizer -{ - - /// This interface defines a source of quantized wavelet coefficients and - /// methods to transfer them in a code-block by code-block basis, fro the - /// decoder side. In each call to 'getCodeBlock()' or 'getInternCodeBlock()' a - /// new code-block is returned. - /// - ///

    This class is the source of data for the dequantizer. See the - /// 'Dequantizer' class. - /// - ///

    Code-block data is returned in sign-magnitude representation, instead of - /// the normal two's complement one. Only integral types are used. The sign - /// magnitude representation is more adequate for entropy coding. In sign - /// magnitude representation, the most significant bit is used for the sign (0 - /// if positive, 1 if negative) and the magnitude of the coefficient is stored - /// in the next M most significant bits. The rest of the bits (least - /// significant bits) can contain a fractional value of the quantized - /// coefficient. The number 'M' of magnitude bits is communicated in the - /// 'magbits' member variable of the 'CBlkWTData'. - /// - ///

    - /// - /// - /// - /// - /// - /// - /// - /// - /// - public interface CBlkQuantDataSrcDec : InvWTData - { - - /// Returns the specified code-block in the current tile for the specified - /// component, as a copy (see below). - /// - ///

    The returned code-block may be progressive, which is indicated by - /// the 'progressive' variable of the returned 'DataBlk' object. If a - /// code-block is progressive it means that in a later request to this - /// method for the same code-block it is possible to retrieve data which is - /// a better approximation, since meanwhile more data to decode for the - /// code-block could have been received. If the code-block is not - /// progressive then later calls to this method for the same code-block - /// will return the exact same data values.

    - /// - ///

    The data returned by this method is always a copy of the internal - /// data of this object, if any, and it can be modified "in place" without - /// any problems after being returned. The 'offset' of the returned data is - /// 0, and the 'scanw' is the same as the code-block width. See the - /// 'DataBlk' class.

    - /// - ///

    The 'ulx' and 'uly' members of the returned 'DataBlk' object contain - /// the coordinates of the top-left corner of the block, with respect to - /// the tile, not the subband.

    - /// - ///
    - /// The component for which to return the next code-block. - /// - /// - /// The vertical index of the code-block to return, in the - /// specified subband. - /// - /// - /// The horizontal index of the code-block to return, in the - /// specified subband. - /// - /// - /// The subband in which the code-block to return is. - /// - /// - /// If non-null this object will be used to return the new - /// code-block. If null a new one will be allocated and returned. If the - /// "data" array of the object is non-null it will be reused, if possible, - /// to return the data. - /// - /// - /// The next code-block in the current tile for component 'n', or - /// null if all code-blocks for the current tile have been returned. - /// - /// - /// - /// - /// - DataBlk getCodeBlock(int c, int m, int n, SubbandSyn sb, DataBlk cblk); - - /// Returns the specified code-block in the current tile for the specified - /// component (as a reference or copy). - /// - ///

    The returned code-block may be progressive, which is indicated by - /// the 'progressive' variable of the returned 'DataBlk' object. If a - /// code-block is progressive it means that in a later request to this - /// method for the same code-block it is possible to retrieve data which is - /// a better approximation, since meanwhile more data to decode for the - /// code-block could have been received. If the code-block is not - /// progressive then later calls to this method for the same code-block - /// will return the exact same data values.

    - /// - ///

    The data returned by this method can be the data in the internal - /// buffer of this object, if any, and thus can not be modified by the - /// caller. The 'offset' and 'scanw' of the returned data can be - /// arbitrary. See the 'DataBlk' class.

    - /// - ///

    The 'ulx' and 'uly' members of the returned 'DataBlk' object contain - /// the coordinates of the top-left corner of the block, with respect to - /// the tile, not the subband.

    - /// - ///
    - /// The component for which to return the next code-block. - /// - /// - /// The vertical index of the code-block to return, in the - /// specified subband. - /// - /// - /// The horizontal index of the code-block to return, in the - /// specified subband. - /// - /// - /// The subband in which the code-block to return is. - /// - /// - /// If non-null this object will be used to return the new - /// code-block. If null a new one will be allocated and returned. If the - /// "data" array of the object is non-null it will be reused, if possible, - /// to return the data. - /// - /// - /// The next code-block in the current tile for component 'n', or - /// null if all code-blocks for the current tile have been returned. - /// - /// - /// - /// - /// - DataBlk getInternCodeBlock(int c, int m, int n, SubbandSyn sb, DataBlk cblk); - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/quantization/dequantizer/Dequantizer.cs b/CSJ2K/j2k/quantization/dequantizer/Dequantizer.cs deleted file mode 100644 index 64f5c5e5..00000000 --- a/CSJ2K/j2k/quantization/dequantizer/Dequantizer.cs +++ /dev/null @@ -1,339 +0,0 @@ -/* -* CVS identifier: -* -* $Id: Dequantizer.java,v 1.37 2001/10/29 20:07:28 qtxjoas Exp $ -* -* Class: Dequantizer -* -* Description: The abstract class for all dequantizers. -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.decoder; -using CSJ2K.j2k.image; -using CSJ2K.j2k.image.invcomptransf; -using CSJ2K.j2k.wavelet; -using CSJ2K.j2k.wavelet.synthesis; -namespace CSJ2K.j2k.quantization.dequantizer -{ - - /// This is the abstract class from which all dequantizers must inherit. This - /// class has the concept of a current tile and all operations are performed on - /// the current tile. - /// - ///

    This class provides default implemenations for most of the methods - /// (wherever it makes sense), under the assumption that the image and - /// component dimensions, and the tiles, are not modifed by the dequantizer. If - /// that is not the case for a particular implementation then the methods - /// should be overriden.

    - /// - ///

    Sign magnitude representation is used (instead of two's complement) for - /// the input data. The most significant bit is used for the sign (0 if - /// positive, 1 if negative). Then the magnitude of the quantized coefficient - /// is stored in the next most significat bits. The most significant magnitude - /// bit corresponds to the most significant bit-plane and so on.

    - /// - ///

    The output data is either in floating-point, or in fixed-point two's - /// complement. In case of floating-point data the the value returned by - /// getFixedPoint() must be 0. If the case of fixed-point data the number of - /// fractional bits must be defined at the constructor of the implementing - /// class and all operations must be performed accordingly. Each component may - /// have a different number of fractional bits.

    - /// - ///
    - public abstract class Dequantizer : MultiResImgDataAdapter, CBlkWTDataSrcDec - { - /// Returns the horizontal code-block partition origin. Allowable values - /// are 0 and 1, nothing else. - /// - /// - virtual public int CbULX - { - get - { - return src.CbULX; - } - - } - /// Returns the vertical code-block partition origin. Allowable values are - /// 0 and 1, nothing else. - /// - /// - virtual public int CbULY - { - get - { - return src.CbULY; - } - - } - /// Returns the parameters that are used in this class and - /// implementing classes. It returns a 2D String array. Each of the - /// 1D arrays is for a different option, and they have 3 - /// elements. The first element is the option name, the second one - /// is the synopsis and the third one is a long description of what - /// the parameter is. The synopsis or description may be 'null', in - /// which case it is assumed that there is no synopsis or - /// description of the option, respectively. Null may be returned - /// if no options are supported. - /// - /// - /// the options name, their synopsis and their explanation, - /// or null if no options are supported. - /// - /// - public static System.String[][] ParameterInfo - { - get - { - return pinfo; - } - - } - - /// The prefix for dequantizer options: 'Q' - public const char OPT_PREFIX = 'Q'; - - /// The list of parameters that is accepted by the bit stream - /// readers. They start with 'Q' - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'pinfo'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly System.String[][] pinfo = null; - - /// The entropy decoder from where to get the quantized data (the - /// source). - /// - protected internal CBlkQuantDataSrcDec src; - - /// The "range bits" for each transformed component - protected internal int[] rb = null; - - /// The "range bits" for each un-transformed component - protected internal int[] utrb = null; - - /// The inverse component transformation specifications - private CompTransfSpec cts; - - /// Reference to the wavelet filter specifications - private SynWTFilterSpec wfs; - - /// Initializes the source of compressed data. - /// - /// - /// From where to obtain the quantized data. - /// - /// - /// The number of "range bits" for each component (must be the - /// "range bits" of the un-transformed components. For a definition of - /// "range bits" see the getNomRangeBits() method. - /// - /// - /// - /// - /// - public Dequantizer(CBlkQuantDataSrcDec src, int[] utrb, DecoderSpecs decSpec) : base(src) - { - if (utrb.Length != src.NumComps) - { - throw new System.ArgumentException(); - } - this.src = src; - this.utrb = utrb; - this.cts = decSpec.cts; - this.wfs = decSpec.wfs; - } - - /// Returns the number of bits, referred to as the "range bits", - /// corresponding to the nominal range of the data in the specified - /// component. - /// - ///

    The returned value corresponds to the nominal dynamic range of the - /// reconstructed image data, not of the wavelet coefficients - /// themselves. This is because different subbands have different gains and - /// thus different nominal ranges. To have an idea of the nominal range in - /// each subband the subband analysis gain value from the subband tree - /// structure, returned by the getSynSubbandTree() method, can be used. See - /// the Subband class for more details.

    - /// - ///

    If this number is b then for unsigned data the nominal range - /// is between 0 and 2^b-1, and for signed data it is between -2^(b-1) and - /// 2^(b-1)-1.

    - /// - ///
    - /// The index of the component - /// - /// - /// The number of bits corresponding to the nominal range of the - /// data. - /// - /// - /// - /// - /// - public virtual int getNomRangeBits(int c) - { - return rb[c]; - } - - /// Returns the subband tree, for the specified tile-component. This method - /// returns the root element of the subband tree structure, see Subband and - /// SubbandSyn. The tree comprises all the available resolution levels. - /// - ///

    The number of magnitude bits ('magBits' member variable) for each - /// subband may have not been not initialized (it depends on the actual - /// dequantizer and its implementation). However, they are not necessary - /// for the subsequent steps in the decoder chain. - /// - ///

    - /// The index of the tile, from 0 to T-1. - /// - /// - /// The index of the component, from 0 to C-1. - /// - /// - /// The root of the tree structure. - /// - /// - public override SubbandSyn getSynSubbandTree(int t, int c) - { - return src.getSynSubbandTree(t, c); - } - - /// Changes the current tile, given the new indexes. An - /// IllegalArgumentException is thrown if the indexes do not - /// correspond to a valid tile. - /// - ///

    This default implementation changes the tile in the source - /// and re-initializes properly component transformation variables.. - /// - ///

    - /// The horizontal index of the tile. - /// - /// - /// The vertical index of the new tile. - /// - /// - public override void setTile(int x, int y) - { - src.setTile(x, y); - tIdx = TileIdx; // index of the current tile - - // initializations - int cttype = 0; - if (((System.Int32)cts.getTileDef(tIdx)) == InvCompTransf.NONE) - cttype = InvCompTransf.NONE; - else - { - int nc = src.NumComps > 3 ? 3 : src.NumComps; - int rev = 0; - for (int c = 0; c < nc; c++) - rev += (wfs.isReversible(tIdx, c) ? 1 : 0); - if (rev == 3) - { - // All WT are reversible - cttype = InvCompTransf.INV_RCT; - } - else if (rev == 0) - { - // All WT irreversible - cttype = InvCompTransf.INV_ICT; - } - else - { - // Error - throw new System.ArgumentException("Wavelet transformation " + "and " + "component transformation" + " not coherent in tile" + tIdx); - } - } - - switch (cttype) - { - - case InvCompTransf.NONE: - rb = utrb; - break; - - case InvCompTransf.INV_RCT: - rb = InvCompTransf.calcMixedBitDepths(utrb, InvCompTransf.INV_RCT, null); - break; - - case InvCompTransf.INV_ICT: - rb = InvCompTransf.calcMixedBitDepths(utrb, InvCompTransf.INV_ICT, null); - break; - - default: - throw new System.ArgumentException("Non JPEG 2000 part I " + "component" + " transformation for tile: " + tIdx); - - } - } - - /// Advances to the next tile, in standard scan-line order (by rows then - /// columns). An NoNextElementException is thrown if the current tile is - /// the last one (i.e. there is no next tile). - /// - ///

    This default implementation just advances to the next tile in the - /// source and re-initializes properly component transformation variables. - /// - ///

    - public override void nextTile() - { - src.nextTile(); - tIdx = TileIdx; // index of the current tile - - // initializations - int cttype = ((System.Int32)cts.getTileDef(tIdx)); - switch (cttype) - { - - case InvCompTransf.NONE: - rb = utrb; - break; - - case InvCompTransf.INV_RCT: - rb = InvCompTransf.calcMixedBitDepths(utrb, InvCompTransf.INV_RCT, null); - break; - - case InvCompTransf.INV_ICT: - rb = InvCompTransf.calcMixedBitDepths(utrb, InvCompTransf.INV_ICT, null); - break; - - default: - throw new System.ArgumentException("Non JPEG 2000 part I " + "component" + " transformation for tile: " + tIdx); - - } - } - public abstract CSJ2K.j2k.image.DataBlk getCodeBlock(int param1, int param2, int param3, CSJ2K.j2k.wavelet.synthesis.SubbandSyn param4, CSJ2K.j2k.image.DataBlk param5); - public abstract int getFixedPoint(int param1); - public abstract CSJ2K.j2k.image.DataBlk getInternCodeBlock(int param1, int param2, int param3, CSJ2K.j2k.wavelet.synthesis.SubbandSyn param4, CSJ2K.j2k.image.DataBlk param5); - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/quantization/dequantizer/DequantizerParams.cs b/CSJ2K/j2k/quantization/dequantizer/DequantizerParams.cs deleted file mode 100644 index b4e7b485..00000000 --- a/CSJ2K/j2k/quantization/dequantizer/DequantizerParams.cs +++ /dev/null @@ -1,68 +0,0 @@ -/* -* CVS identifier: -* -* $Id: DequantizerParams.java,v 1.16 2000/09/19 14:11:54 grosbois Exp $ -* -* Class: DequantizerParams -* -* Description: Generic class to hold dequantizer -* parameters. -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -*/ -namespace CSJ2K.j2k.quantization.dequantizer -{ - - /// This is the generic ineterface for dequantization parameters. Generally, - /// for each type of dequantizer, there should be a corresponding class to - /// store its parameters. The parameters are those that come from the bit - /// stream header, that concern dequantization. - /// - /// - public abstract class DequantizerParams - { - /// Returns the type of the dequantizer for which the parameters are. The - /// types are defined in the Dequantizer class. - /// - /// - /// The type of the dequantizer for which the parameters - /// are. - /// - /// - /// - /// - /// - public abstract int DequantizerType { get; } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/quantization/dequantizer/StdDequantizer.cs b/CSJ2K/j2k/quantization/dequantizer/StdDequantizer.cs deleted file mode 100644 index 9255b1f7..00000000 --- a/CSJ2K/j2k/quantization/dequantizer/StdDequantizer.cs +++ /dev/null @@ -1,404 +0,0 @@ -/* -* CVS identifier: -* -* $Id: StdDequantizer.java,v 1.15 2002/07/19 12:50:23 grosbois Exp $ -* -* Class: StdDequantizer -* -* Description: Scalar deadzone dequantizer that returns integers -* or floats. -* This is a merger of the ScalarDZDeqInt and -* ScalarDZDeqFloat classes by Joel Askelof and Diego -* Santa Cruz. -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.decoder; -using CSJ2K.j2k.image; -using CSJ2K.j2k.wavelet.synthesis; -namespace CSJ2K.j2k.quantization.dequantizer -{ - - /// This class implements a scalar dequantizer with deadzone. The output can be - /// either integer ('int') or floating-point ('float') data. The dequantization - /// step sizes and other parameters are taken from a StdDequantizerParams - /// class, which inherits from DequantizerParams. - /// - ///

    Sign magnitude representation is used (instead of two's complement) for - /// the input data. The most significant bit is used for the sign (0 if - /// positive, 1 if negative). Then the magnitude of the quantized coefficient - /// is stored in the next most significat bits. The most significant magnitude - /// bit corresponds to the most significant bit-plane and so on.

    - /// - ///

    When reversible quantization is used, this class only converts between - /// the sign-magnitude representation and the integer (or eventually - /// fixed-point) output, since there is no true quantization.

    - /// - ///

    The output data is fixed-point two's complement for 'int' output and - /// floating-point for 'float' output. The type of output and the number number - /// of fractional bits for 'int' output are defined at the constructor. Each - /// component may have a different number of fractional bits.

    - /// - ///

    The reconstruction levels used by the dequantizer are exactly what is - /// received from the entropy decoder. It is assumed that the entropy decoder - /// always returns codewords that are midways in the decoded intervals. In this - /// way the dequantized values will always lie midways in the quantization - /// intervals.

    - /// - ///
    - public class StdDequantizer : Dequantizer - { - - /// The quantizer type spec - private QuantTypeSpec qts; - - /// The quantizer step sizes spec - private QuantStepSizeSpec qsss; - - /// The number of guard bits spec - private GuardBitsSpec gbs; - - /// The decoding parameters of the dequantizer - //private StdDequantizerParams params_Renamed; - - /// The 'DataBlkInt' object used to request data, used when output data is - /// not int - /// - private DataBlkInt inblk; - - /// Type of the current output data - private int outdtype; - - /// Initializes the source of compressed data. And sets the number of range - /// bits and fraction bits and receives the parameters for the dequantizer. - /// - /// - /// From where to obtain the quantized data. - /// - /// - /// The number of "range bits" (bitdepth) for each component - /// (must be the "range bits" of the un-transformed components). For a - /// definition of "range bits" see the getNomRangeBits() method. - /// - /// - /// The quantizer type spec - /// - /// - /// The dequantizer step sizes spec - /// - /// - /// - /// - /// - /// Thrown if 'outdt' is neither - /// TYPE_FLOAT nor TYPE_INT, or if 'param' specify reversible quantization - /// and 'outdt' is not TYPE_INT or 'fp' has non-zero values, or if 'outdt' - /// is TYPE_FLOAT and 'fp' has non-zero values. - /// - /// - public StdDequantizer(CBlkQuantDataSrcDec src, int[] utrb, DecoderSpecs decSpec) : base(src, utrb, decSpec) - { - - if (utrb.Length != src.NumComps) - { - throw new System.ArgumentException("Invalid rb argument"); - } - this.qsss = decSpec.qsss; - this.qts = decSpec.qts; - this.gbs = decSpec.gbs; - } - - /// Returns the position of the fixed point in the output data for the - /// specified component. This is the position of the least significant - /// integral (i.e. non-fractional) bit, which is equivalent to the number - /// of fractional bits. For instance, for fixed-point values with 2 - /// fractional bits, 2 is returned. For floating-point data this value does - /// not apply and 0 should be returned. Position 0 is the position of the - /// least significant bit in the data. If the output data is 'float' then 0 - /// is always returned. - /// - ///

    Note: Fractional bits are no more supported by JJ2000.

    - /// - ///
    - /// The index of the component. - /// - /// - /// The position of the fixed-point, which is the same as the - /// number of fractional bits. For floating-point data 0 is returned. - /// - /// - public override int getFixedPoint(int c) - { - return 0; - } - - /// Returns the specified code-block in the current tile for the specified - /// component, as a copy (see below). - /// - ///

    The returned code-block may be progressive, which is indicated by - /// the 'progressive' variable of the returned 'DataBlk' object. If a - /// code-block is progressive it means that in a later request to this - /// method for the same code-block it is possible to retrieve data which is - /// a better approximation, since meanwhile more data to decode for the - /// code-block could have been received. If the code-block is not - /// progressive then later calls to this method for the same code-block - /// will return the exact same data values.

    - /// - ///

    The data returned by this method is always a copy of the internal - /// data of this object, if any, and it can be modified "in place" without - /// any problems after being returned. The 'offset' of the returned data is - /// 0, and the 'scanw' is the same as the code-block width. See the - /// 'DataBlk' class.

    - /// - ///
    - /// The component for which to return the next code-block. - /// - /// - /// The vertical index of the code-block to return, in the - /// specified subband. - /// - /// - /// The horizontal index of the code-block to return, in the - /// specified subband. - /// - /// - /// The subband in which the code-block to return is. - /// - /// - /// If non-null this object will be used to return the new - /// code-block. If null a new one will be allocated and returned. If the - /// "data" array of the object is non-null it will be reused, if possible, - /// to return the data. - /// - /// - /// The next code-block in the current tile for component 'n', or - /// null if all code-blocks for the current tile have been returned. - /// - /// - /// - /// - /// - public override DataBlk getCodeBlock(int c, int m, int n, SubbandSyn sb, DataBlk cblk) - { - return getInternCodeBlock(c, m, n, sb, cblk); - } - - /// Returns the specified code-block in the current tile for the specified - /// component (as a reference or copy). - /// - ///

    The returned code-block may be progressive, which is indicated by - /// the 'progressive' variable of the returned 'DataBlk' - /// object. If a code-block is progressive it means that in a later request - /// to this method for the same code-block it is possible to retrieve data - /// which is a better approximation, since meanwhile more data to decode - /// for the code-block could have been received. If the code-block is not - /// progressive then later calls to this method for the same code-block - /// will return the exact same data values.

    - /// - ///

    The data returned by this method can be the data in the internal - /// buffer of this object, if any, and thus can not be modified by the - /// caller. The 'offset' and 'scanw' of the returned data can be - /// arbitrary. See the 'DataBlk' class.

    - /// - ///
    - /// The component for which to return the next code-block. - /// - /// - /// The vertical index of the code-block to return, in the - /// specified subband. - /// - /// - /// The horizontal index of the code-block to return, in the - /// specified subband. - /// - /// - /// The subband in which the code-block to return is. - /// - /// - /// If non-null this object will be used to return the new - /// code-block. If null a new one will be allocated and returned. If the - /// "data" array of the object is non-null it will be reused, if possible, - /// to return the data. - /// - /// - /// The next code-block in the current tile for component 'n', or - /// null if all code-blocks for the current tile have been returned. - /// - /// - /// - /// - /// - public override DataBlk getInternCodeBlock(int c, int m, int n, SubbandSyn sb, DataBlk cblk) - { - // This method is declared final since getNextCodeBlock() relies on - // the actual implementation of this method. - int j, jmin, k; - int temp; - float step; - int shiftBits; - int magBits; - int[] outiarr, inarr; - float[] outfarr; - int w, h; - bool reversible = qts.isReversible(tIdx, c); - bool derived = qts.isDerived(tIdx, c); - StdDequantizerParams params_Renamed = (StdDequantizerParams)qsss.getTileCompVal(tIdx, c); - int G = ((System.Int32)gbs.getTileCompVal(tIdx, c)); - - outdtype = cblk.DataType; - - if (reversible && outdtype != DataBlk.TYPE_INT) - { - throw new System.ArgumentException("Reversible quantizations " + "must use int data"); - } - - // To get compiler happy - outiarr = null; - outfarr = null; - inarr = null; - - // Get source data and initialize output DataBlk object. - switch (outdtype) - { - - case DataBlk.TYPE_INT: - // With int data we can use the same DataBlk object to get the - // data from the source and return the dequantized data, and we - // can also work "in place" (i.e. same buffer). - cblk = src.getCodeBlock(c, m, n, sb, cblk); - // Input and output arrays are the same - outiarr = (int[])cblk.Data; - break; - - case DataBlk.TYPE_FLOAT: - // With float data we must use a different DataBlk objects to get - // the data from the source and to return the dequantized data. - inblk = (DataBlkInt)src.getInternCodeBlock(c, m, n, sb, inblk); - inarr = inblk.DataInt; - if (cblk == null) - { - cblk = new DataBlkFloat(); - } - // Copy the attributes of the CodeBlock object - cblk.ulx = inblk.ulx; - cblk.uly = inblk.uly; - cblk.w = inblk.w; - cblk.h = inblk.h; - cblk.offset = 0; - cblk.scanw = cblk.w; - cblk.progressive = inblk.progressive; - // Get output data array and check its size - outfarr = (float[])cblk.Data; - if (outfarr == null || outfarr.Length < cblk.w * cblk.h) - { - outfarr = new float[cblk.w * cblk.h]; - cblk.Data = outfarr; - } - break; - } - - magBits = sb.magbits; - - // Calculate quantization step and number of magnitude bits - // depending on reversibility and derivedness and perform - // inverse quantization - if (reversible) - { - shiftBits = 31 - magBits; - // For int data Inverse quantization happens "in-place". The input - // array has an offset of 0 and scan width equal to the code-block - // width. - for (j = outiarr.Length - 1; j >= 0; j--) - { - temp = outiarr[j]; // input array is same as output one - outiarr[j] = (temp >= 0) ? (temp >> shiftBits) : -((temp & 0x7FFFFFFF) >> shiftBits); - } - } - else - { - // Not reversible - if (derived) - { - // Max resolution level - int mrl = src.getSynSubbandTree(TileIdx, c).resLvl; - step = params_Renamed.nStep[0][0] * (1L << (rb[c] + sb.anGainExp + mrl - sb.level)); - } - else - { - step = params_Renamed.nStep[sb.resLvl][sb.sbandIdx] * (1L << (rb[c] + sb.anGainExp)); - } - shiftBits = 31 - magBits; - - // Adjust step to the number of shiftBits - step /= (1 << shiftBits); - - switch (outdtype) - { - - case DataBlk.TYPE_INT: - // For int data Inverse quantization happens "in-place". The - // input array has an offset of 0 and scan width equal to the - // code-block width. - for (j = outiarr.Length - 1; j >= 0; j--) - { - temp = outiarr[j]; // input array is same as output one - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - outiarr[j] = (int)(((float)((temp >= 0) ? temp : -(temp & 0x7FFFFFFF))) * step); - } - break; - - case DataBlk.TYPE_FLOAT: - // For float data the inverse quantization can not happen - // "in-place". - w = cblk.w; - h = cblk.h; - for (j = w * h - 1, k = inblk.offset + (h - 1) * inblk.scanw + w - 1, jmin = w * (h - 1); j >= 0; jmin -= w) - { - for (; j >= jmin; k--, j--) - { - temp = inarr[k]; - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - outfarr[j] = ((float)((temp >= 0) ? temp : -(temp & 0x7FFFFFFF))) * step; - } - // Jump to beggining of previous line in input - k -= (inblk.scanw - w); - } - break; - } - } - // Return the output code-block - return cblk; - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/quantization/dequantizer/StdDequantizerParams.cs b/CSJ2K/j2k/quantization/dequantizer/StdDequantizerParams.cs deleted file mode 100644 index ec58235a..00000000 --- a/CSJ2K/j2k/quantization/dequantizer/StdDequantizerParams.cs +++ /dev/null @@ -1,132 +0,0 @@ -/* -* CVS identifier: -* -* $Id: StdDequantizerParams.java,v 1.9 2000/09/19 14:12:09 grosbois Exp $ -* -* Class: StdDequantizerParams -* -* Description: Parameters for the scalar deadzone dequantizers -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -*/ -using CSJ2K.j2k.wavelet; -namespace CSJ2K.j2k.quantization.dequantizer -{ - - /// This class holds the parameters for the scalar deadzone dequantizer - /// (StdDequantizer class) for the current tile. Its constructor decodes the - /// parameters from the main header and tile headers. - /// - /// - /// - /// - /// - public class StdDequantizerParams : DequantizerParams - { - /// Returns the type of the dequantizer for which the parameters are. The - /// types are defined in the Dequantizer class. - /// - /// - /// The type of the dequantizer for which the parameters - /// are. Always Q_TYPE_SCALAR_DZ. - /// - /// - /// - /// - /// - override public int DequantizerType - { - get - { - return CSJ2K.j2k.quantization.QuantizationType_Fields.Q_TYPE_SCALAR_DZ; - } - - } - - /// The quantization step "exponent" value, for each resolution level and - /// subband, as it appears in the codestream. The first index is the - /// resolution level, and the second the subband index (within the - /// resolution level), as specified in the Subband class. When in derived - /// quantization mode only the first resolution level (level 0) appears. - /// - ///

    For non-reversible systems this value corresponds to ceil(log2(D')), - /// where D' is the quantization step size normalized to data of a dynamic - /// range of 1. The true quantization step size is (2^R)*D', where R is - /// ceil(log2(dr)), where 'dr' is the dynamic range of the subband samples, - /// in the corresponding subband. - /// - ///

    For reversible systems the exponent value in 'exp' is used to - /// determine the number of magnitude bits in the quantized - /// coefficients. It is, in fact, the dynamic range of the subband data. - /// - ///

    In general the index of the first subband in a resolution level is - /// not 0. The exponents appear, within each resolution level, at their - /// subband index, and not in the subband order starting from 0. For - /// instance, resolution level 3, the first subband has the index 16, then - /// the exponent of the subband is exp[3][16], not exp[3][0]. - /// - ///

    - /// - /// - /// - public int[][] exp; - - /// The quantization step for non-reversible systems, normalized to a - /// dynamic range of 1, for each resolution level and subband, as derived - /// from the exponent-mantissa representation in the codestream. The first - /// index is the resolution level, and the second the subband index (within - /// the resolution level), as specified in the Subband class. When in - /// derived quantization mode only the first resolution level (level 0) - /// appears. - /// - ///

    The true step size D is obtained as follows: D=(2^R)*D', where - /// 'R=ceil(log2(dr))' and 'dr' is the dynamic range of the subband - /// samples, in the corresponding subband. - /// - ///

    This value is 'null' for reversible systems (i.e. there is no true - /// quantization, 'D' is always 1). - /// - ///

    In general the index of the first subband in a resolution level is - /// not 0. The steps appear, within each resolution level, at their subband - /// index, and not in the subband order starting from 0. For instance, if - /// resolution level 3, the first subband has the index 16, then the step - /// of the subband is nStep[3][16], not nStep[3][0]. - /// - ///

    - /// - /// - /// - public float[][] nStep; - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/quantization/quantizer/CBlkQuantDataSrcEnc.cs b/CSJ2K/j2k/quantization/quantizer/CBlkQuantDataSrcEnc.cs deleted file mode 100644 index dfffec2b..00000000 --- a/CSJ2K/j2k/quantization/quantizer/CBlkQuantDataSrcEnc.cs +++ /dev/null @@ -1,166 +0,0 @@ -/* -* CVS identifier: -* -* $Id: CBlkQuantDataSrcEnc.java,v 1.10 2001/09/14 08:51:46 grosbois Exp $ -* -* Class: CBlkQuantDataSrcEnc -* -* Description: Interface that defines a source of -* quantized wavelet data to be transferred in a -* code-block by code-block basis. -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.entropy.encoder; -using CSJ2K.j2k.wavelet.analysis; -namespace CSJ2K.j2k.quantization.quantizer -{ - - /// This interface defines a source of quantized wavelet coefficients and - /// methods to transfer them in a code-block by code-block basis. In each call - /// to 'getNextCodeBlock()' or 'getNextInternCodeBlock()' a new code-block is - /// returned. The code-blocks are returned in no specific order. - /// - ///

    This class is the source of data for the entropy coder. See the - /// 'EntropyCoder' class.

    - /// - ///

    Code-block data is returned in sign-magnitude representation, instead of - /// the normal two's complement one. Only integral types are used. The sign - /// magnitude representation is more adequate for entropy coding. In sign - /// magnitude representation, the most significant bit is used for the sign (0 - /// if positive, 1 if negative) and the magnitude of the coefficient is stored - /// in the next M most significant bits. The rest of the bits (least - /// significant bits) can contain a fractional value of the quantized - /// coefficient. The number 'M' of magnitude bits is communicated in the - /// 'magbits' member variable of the 'CBlkWTData'.

    - /// - ///

    Note that no more of one object may request data, otherwise one object - /// would get some of the data and another one another part, in no defined - /// manner.

    - /// - ///
    - /// - /// - /// - /// - /// - /// - /// - /// - /// - public interface CBlkQuantDataSrcEnc : ForwWTDataProps - { - - /// Returns the next code-block in the current tile for the specified - /// component, as a copy (see below). The order in which code-blocks are - /// returned is not specified. However each code-block is returned only - /// once and all code-blocks will be returned if the method is called 'N' - /// times, where 'N' is the number of code-blocks in the tile. After all - /// the code-blocks have been returned for the current tile calls to this - /// method will return 'null'. - /// - ///

    When changing the current tile (through 'setTile()' or 'nextTile()') - /// this method will always return the first code-block, as if this method - /// was never called before for the new current tile.

    - /// - ///

    The data returned by this method is always a copy of the internal - /// data of this object, if any, and it can be modified "in place" without - /// any problems after being returned. The 'offset' of the returned data is - /// 0, and the 'scanw' is the same as the code-block width. See the - /// 'CBlkWTData' class.

    - /// - ///

    The 'ulx' and 'uly' members of the returned 'CBlkWTData' object - /// contain the coordinates of the top-left corner of the block, with - /// respect to the tile, not the subband.

    - /// - ///
    - /// The component for which to return the next code-block. - /// - /// - /// If non-null this object will be used to return the new - /// code-block. If null a new one will be allocated and returned. If the - /// "data" array of the object is non-null it will be reused, if possible, - /// to return the data. - /// - /// - /// The next code-block in the current tile for component 'c', or - /// null if all code-blocks for the current tile have been returned. - /// - /// - /// - /// - /// - CBlkWTData getNextCodeBlock(int c, CBlkWTData cblk); - - /// Returns the next code-block in the current tile for the specified - /// component. The order in which code-blocks are returned is not - /// specified. However each code-block is returned only once and all - /// code-blocks will be returned if the method is called 'N' times, where - /// 'N' is the number of code-blocks in the tile. After all the code-blocks - /// have been returned for the current tile calls to this method will - /// return 'null'. - /// - ///

    When changing the current tile (through 'setTile()' or 'nextTile()') - /// this method will always return the first code-block, as if this method - /// was never called before for the new current tile.

    - /// - ///

    The data returned by this method can be the data in the internal - /// buffer of this object, if any, and thus can not be modified by the - /// caller. The 'offset' and 'scanw' of the returned data can be - /// arbitrary. See the 'CBlkWTData' class.

    - /// - ///

    The 'ulx' and 'uly' members of the returned 'CBlkWTData' object - /// contain the coordinates of the top-left corner of the block, with - /// respect to the tile, not the subband.

    - /// - ///
    - /// The component for which to return the next code-block. - /// - /// - /// If non-null this object will be used to return the new - /// code-block. If null a new one will be allocated and returned. If the - /// "data" array of the object is non-null it will be reused, if possible, - /// to return the data. - /// - /// - /// The next code-block in the current tile for component 'n', or - /// null if all code-blocks for the current tile have been returned. - /// - /// - /// - /// - /// - CBlkWTData getNextInternCodeBlock(int c, CBlkWTData cblk); - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/quantization/quantizer/Quantizer.cs b/CSJ2K/j2k/quantization/quantizer/Quantizer.cs deleted file mode 100644 index 1c361725..00000000 --- a/CSJ2K/j2k/quantization/quantizer/Quantizer.cs +++ /dev/null @@ -1,288 +0,0 @@ -/* -* CVS identifier: -* -* $Id: Quantizer.java,v 1.38 2002/01/09 13:24:14 grosbois Exp $ -* -* Class: Quantizer -* -* Description: An abstract class for quantizers -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.encoder; -using CSJ2K.j2k.image; -using CSJ2K.j2k.wavelet; -using CSJ2K.j2k.wavelet.analysis; -namespace CSJ2K.j2k.quantization.quantizer -{ - - /// This abstract class provides the general interface for quantizers. The - /// input of a quantizer is the output of a wavelet transform. The output of - /// the quantizer is the set of quantized wavelet coefficients represented in - /// sign-magnitude notation (see below). - /// - ///

    This class provides default implementation for most of the methods - /// (wherever it makes sense), under the assumption that the image, component - /// dimensions, and the tiles, are not modifed by the quantizer. If it is not - /// the case for a particular implementation, then the methods should be - /// overriden.

    - /// - ///

    Sign magnitude representation is used (instead of two's complement) for - /// the output data. The most significant bit is used for the sign (0 if - /// positive, 1 if negative). Then the magnitude of the quantized coefficient - /// is stored in the next M most significat bits. The rest of the bits (least - /// significant bits) can contain a fractional value of the quantized - /// coefficient. This fractional value is not to be coded by the entropy - /// coder. However, it can be used to compute rate-distortion measures with - /// greater precision.

    - /// - ///

    The value of M is determined for each subband as the sum of the number - /// of guard bits G and the nominal range of quantized wavelet coefficients in - /// the corresponding subband (Rq), minus 1:

    - /// - ///

    M = G + Rq -1

    - /// - ///

    The value of G should be the same for all subbands. The value of Rq - /// depends on the quantization step size, the nominal range of the component - /// before the wavelet transform and the analysis gain of the subband (see - /// Subband).

    - /// - ///

    The blocks of data that are requested should not cross subband - /// boundaries.

    - /// - ///

    NOTE: At the moment only quantizers that implement the - /// 'CBlkQuantDataSrcEnc' interface are supported.

    - /// - ///
    - /// - /// - /// - public abstract class Quantizer : ImgDataAdapter, CBlkQuantDataSrcEnc - { - /// Returns the horizontal offset of the code-block partition. Allowable - /// values are 0 and 1, nothing else. - /// - /// - virtual public int CbULX - { - get - { - return src.CbULX; - } - - } - /// Returns the vertical offset of the code-block partition. Allowable - /// values are 0 and 1, nothing else. - /// - /// - virtual public int CbULY - { - get - { - return src.CbULY; - } - - } - /// Returns the parameters that are used in this class and implementing - /// classes. It returns a 2D String array. Each of the 1D arrays is for a - /// different option, and they have 3 elements. The first element is the - /// option name, the second one is the synopsis, the third one is a long - /// description of what the parameter is and the fourth is its default - /// value. The synopsis or description may be 'null', in which case it is - /// assumed that there is no synopsis or description of the option, - /// respectively. Null may be returned if no options are supported. - /// - /// - /// the options name, their synopsis and their explanation, - /// or null if no options are supported. - /// - /// - public static System.String[][] ParameterInfo - { - get - { - return pinfo; - } - - } - - /// The prefix for quantizer options: 'Q' - public const char OPT_PREFIX = 'Q'; - - /// The list of parameters that is accepted for quantization. Options - /// for quantization start with 'Q'. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'pinfo'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly System.String[][] pinfo = new System.String[][] { new System.String[] { "Qtype", "[] " + "[ [] ...]", "Specifies which quantization type to use for specified " + "tile-component. The default type is either 'reversible' or " + "'expounded' depending on whether or not the '-lossless' option " + " is specified.\n" + " : see general note.\n" + ": Supported quantization types specification are : " + "'reversible' " + "(no quantization), 'derived' (derived quantization step size) and " + "'expounded'.\n" + "Example: -Qtype reversible or -Qtype t2,4-8 c2 reversible t9 " + "derived.", null }, new System.String[] { "Qstep", "[] " + "[ [] ...]", "This option specifies the base normalized quantization step " + "size (bnss) for tile-components. It is normalized to a " + "dynamic range of 1 in the image domain. This parameter is " + "ignored in reversible coding. The default value is '1/128'" + " (i.e. 0.0078125).", "0.0078125" }, new System.String[] { "Qguard_bits", "[] " + "[ [] ...]", "The number of bits used for each tile-component in the quantizer" + " to avoid overflow (gb).", "2" } }; - - /// The source of wavelet transform coefficients - protected internal CBlkWTDataSrc src; - - /// Initializes the source of wavelet transform coefficients. - /// - /// - /// The source of wavelet transform coefficients. - /// - /// - public Quantizer(CBlkWTDataSrc src) : base(src) - { - this.src = src; - } - - /// Returns the number of guard bits used by this quantizer in the - /// given tile-component. - /// - /// - /// Tile index - /// - /// - /// Component index - /// - /// - /// The number of guard bits - /// - /// - public abstract int getNumGuardBits(int t, int c); - - /// Returns true if the quantizer of given tile-component uses derived - /// quantization step sizes. - /// - /// - /// Tile index - /// - /// - /// Component index - /// - /// - /// True if derived quantization is used. - /// - /// - public abstract bool isDerived(int t, int c); - - /// Calculates the parameters of the SubbandAn objects that depend on the - /// Quantizer. The 'stepWMSE' field is calculated for each subband which is - /// a leaf in the tree rooted at 'sb', for the specified component. The - /// subband tree 'sb' must be the one for the component 'n'. - /// - /// - /// The root of the subband tree. - /// - /// - /// The component index. - /// - /// - /// - /// - /// - protected internal abstract void calcSbParams(SubbandAn sb, int n); - - /// Returns a reference to the subband tree structure representing the - /// subband decomposition for the specified tile-component. - /// - ///

    This method gets the subband tree from the source and then - /// calculates the magnitude bits for each leaf using the method - /// calcSbParams(). - /// - ///

    - /// The index of the tile. - /// - /// - /// The index of the component. - /// - /// - /// The subband tree structure, see SubbandAn. - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - public virtual SubbandAn getAnSubbandTree(int t, int c) - { - SubbandAn sbba; - - // Ask for the wavelet tree of the source - sbba = src.getAnSubbandTree(t, c); - // Calculate the stepWMSE - calcSbParams(sbba, c); - return sbba; - } - - /// Creates a Quantizer object for the appropriate type of quantization - /// specified in the options in the parameter list 'pl', and having 'src' - /// as the source of data to be quantized. The 'rev' flag indicates if the - /// quantization should be reversible. - /// - /// NOTE: At the moment only sources of wavelet data that implement the - /// 'CBlkWTDataSrc' interface are supported. - /// - /// - /// The source of data to be quantized - /// - /// - /// Encoder specifications - /// - /// - /// If an error occurs while parsing - /// the options in 'pl' - /// - /// - public static Quantizer createInstance(CBlkWTDataSrc src, EncoderSpecs encSpec) - { - // Instantiate quantizer - return new StdQuantizer(src, encSpec); - } - - /// Returns the maximum number of magnitude bits in any subband in the - /// current tile. - /// - /// - /// the component number - /// - /// - /// The maximum number of magnitude bits in all subbands of the - /// current tile. - /// - /// - public abstract int getMaxMagBits(int c); - public abstract CSJ2K.j2k.wavelet.analysis.CBlkWTData getNextInternCodeBlock(int param1, CSJ2K.j2k.wavelet.analysis.CBlkWTData param2); - public abstract CSJ2K.j2k.wavelet.analysis.CBlkWTData getNextCodeBlock(int param1, CSJ2K.j2k.wavelet.analysis.CBlkWTData param2); - public abstract bool isReversible(int param1, int param2); - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/quantization/quantizer/StdQuantizer.cs b/CSJ2K/j2k/quantization/quantizer/StdQuantizer.cs deleted file mode 100644 index 8a0a8c2a..00000000 --- a/CSJ2K/j2k/quantization/quantizer/StdQuantizer.cs +++ /dev/null @@ -1,725 +0,0 @@ -/* -* CVS identifier: -* -* $Id: StdQuantizer.java,v 1.14 2001/09/20 12:41:52 grosbois Exp $ -* -* Class: StdQuantizer -* -* Description: Scalar deadzone quantizer of integer or float -* data. -* -* Mergerd from StdQuantizerInt and -* StdQuantizerFloat from Joel Askelof. -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.encoder; -using CSJ2K.j2k.image; -using CSJ2K.j2k.wavelet; -using CSJ2K.j2k.wavelet.analysis; -namespace CSJ2K.j2k.quantization.quantizer -{ - - /// This class implements scalar quantization of integer or floating-point - /// valued source data. The source data is the wavelet transformed image data - /// and the output is the quantized wavelet coefficients represented in - /// sign-magnitude (see below). - /// - ///

    Sign magnitude representation is used (instead of two's complement) for - /// the output data. The most significant bit is used for the sign (0 if - /// positive, 1 if negative). Then the magnitude of the quantized coefficient - /// is stored in the next M most significat bits. The rest of the bits (least - /// significant bits) can contain a fractional value of the quantized - /// coefficient. This fractional value is not to be coded by the entropy - /// coder. However, it can be used to compute rate-distortion measures with - /// greater precision.

    - /// - ///

    The value of M is determined for each subband as the sum of the number - /// of guard bits G and the nominal range of quantized wavelet coefficients in - /// the corresponding subband (Rq), minus 1:

    - /// - ///

    M = G + Rq -1

    - /// - ///

    The value of G should be the same for all subbands. The value of Rq - /// depends on the quantization step size, the nominal range of the component - /// before the wavelet transform and the analysis gain of the subband (see - /// Subband).

    - /// - ///

    The blocks of data that are requested should not cross subband - /// boundaries.

    - /// - ///
    - /// - /// - /// - /// - /// - /// - public class StdQuantizer : Quantizer - { - /// Returns the quantization type spec object associated to the quantizer. - /// - /// - /// The quantization type spec - /// - /// - virtual public QuantTypeSpec QuantTypeSpec - { - get - { - return qts; - } - - } - - /// The number of mantissa bits for the quantization steps - public const int QSTEP_MANTISSA_BITS = 11; - - /// The number of exponent bits for the quantization steps - // NOTE: formulas in 'convertFromExpMantissa()' and - // 'convertToExpMantissa()' methods do not support more than 5 bits. - public const int QSTEP_EXPONENT_BITS = 5; - - /// The maximum value of the mantissa for the quantization steps - //UPGRADE_NOTE: Final was removed from the declaration of 'QSTEP_MAX_MANTISSA '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly int QSTEP_MAX_MANTISSA = (1 << QSTEP_MANTISSA_BITS) - 1; - - /// The maximum value of the exponent for the quantization steps - //UPGRADE_NOTE: Final was removed from the declaration of 'QSTEP_MAX_EXPONENT '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly int QSTEP_MAX_EXPONENT = (1 << QSTEP_EXPONENT_BITS) - 1; - - /// Natural log of 2, used as a convenience variable - private static double log2 = System.Math.Log(2); - - /// The quantization type specifications - private QuantTypeSpec qts; - - /// The quantization step size specifications - private QuantStepSizeSpec qsss; - - /// The guard bits specifications - private GuardBitsSpec gbs; - - /// The 'CBlkWTDataFloat' object used to request data, used when - /// quantizing floating-point data. - /// - // This variable makes the class thread unsafe, but it avoids allocating - // new objects for code-block that is quantized. - private CBlkWTDataFloat infblk; - - /// Initializes the source of wavelet transform coefficients. The - /// constructor takes information on whether the quantizer is in - /// reversible, derived or expounded mode. If the quantizer is reversible - /// the value of 'derived' is ignored. If the source data is not integer - /// (int) then the quantizer can not be reversible. - /// - ///

    After initializing member attributes, getAnSubbandTree is called for - /// all components setting the 'stepWMSE' for all subbands in the current - /// tile.

    - /// - ///
    - /// The source of wavelet transform coefficients. - /// - /// - /// The encoder specifications - /// - /// - public StdQuantizer(CBlkWTDataSrc src, EncoderSpecs encSpec) : base(src) - { - qts = encSpec.qts; - qsss = encSpec.qsss; - gbs = encSpec.gbs; - } - - /// Returns the number of guard bits used by this quantizer in the given - /// tile-component. - /// - /// - /// Tile index - /// - /// - /// Component index - /// - /// - /// The number of guard bits - /// - /// - public override int getNumGuardBits(int t, int c) - { - return ((System.Int32)gbs.getTileCompVal(t, c)); - } - - /// Returns true if the quantized data is reversible, for the specified - /// tile-component. For the quantized data to be reversible it is necessary - /// and sufficient that the quantization is reversible. - /// - /// - /// The tile to test for reversibility - /// - /// - /// The component to test for reversibility - /// - /// - /// True if the quantized data is reversible, false if not. - /// - /// - public override bool isReversible(int t, int c) - { - return qts.isReversible(t, c); - } - - /// Returns true if given tile-component uses derived quantization step - /// sizes. - /// - /// - /// Tile index - /// - /// - /// Component index - /// - /// - /// True if derived - /// - /// - public override bool isDerived(int t, int c) - { - return qts.isDerived(t, c); - } - - /// Returns the next code-block in the current tile for the specified - /// component, as a copy (see below). The order in which code-blocks are - /// returned is not specified. However each code-block is returned only - /// once and all code-blocks will be returned if the method is called 'N' - /// times, where 'N' is the number of code-blocks in the tile. After all - /// the code-blocks have been returned for the current tile calls to this - /// method will return 'null'. - /// - ///

    When changing the current tile (through 'setTile()' or 'nextTile()') - /// this method will always return the first code-block, as if this method - /// was never called before for the new current tile.

    - /// - ///

    The data returned by this method is always a copy of the - /// data. Therfore it can be modified "in place" without any problems after - /// being returned. The 'offset' of the returned data is 0, and the 'scanw' - /// is the same as the code-block width. See the 'CBlkWTData' class.

    - /// - ///

    The 'ulx' and 'uly' members of the returned 'CBlkWTData' object - /// contain the coordinates of the top-left corner of the block, with - /// respect to the tile, not the subband.

    - /// - ///
    - /// The component for which to return the next code-block. - /// - /// - /// If non-null this object will be used to return the new - /// code-block. If null a new one will be allocated and returned. If the - /// "data" array of the object is non-null it will be reused, if possible, - /// to return the data. - /// - /// - /// The next code-block in the current tile for component 'n', or - /// null if all code-blocks for the current tile have been returned. - /// - /// - /// - /// - /// - public override CBlkWTData getNextCodeBlock(int c, CBlkWTData cblk) - { - return getNextInternCodeBlock(c, cblk); - } - - /// Returns the next code-block in the current tile for the specified - /// component. The order in which code-blocks are returned is not - /// specified. However each code-block is returned only once and all - /// code-blocks will be returned if the method is called 'N' times, where - /// 'N' is the number of code-blocks in the tile. After all the code-blocks - /// have been returned for the current tile calls to this method will - /// return 'null'. - /// - ///

    When changing the current tile (through 'setTile()' or 'nextTile()') - /// this method will always return the first code-block, as if this method - /// was never called before for the new current tile.

    - /// - ///

    The data returned by this method can be the data in the internal - /// buffer of this object, if any, and thus can not be modified by the - /// caller. The 'offset' and 'scanw' of the returned data can be - /// arbitrary. See the 'CBlkWTData' class.

    - /// - ///

    The 'ulx' and 'uly' members of the returned 'CBlkWTData' object - /// contain the coordinates of the top-left corner of the block, with - /// respect to the tile, not the subband.

    - /// - ///
    - /// The component for which to return the next code-block. - /// - /// - /// If non-null this object will be used to return the new - /// code-block. If null a new one will be allocated and returned. If the - /// "data" array of the object is non-null it will be reused, if possible, - /// to return the data. - /// - /// - /// The next code-block in the current tile for component 'n', or - /// null if all code-blocks for the current tile have been returned. - /// - /// - /// - /// - /// - public override CBlkWTData getNextInternCodeBlock(int c, CBlkWTData cblk) - { - // NOTE: this method is declared final since getNextCodeBlock() relies - // on this particular implementation - int k, j; - int tmp, shiftBits, jmin; - int w, h; - int[] outarr; - float[] infarr = null; - CBlkWTDataFloat infblk; - float invstep; // The inverse of the quantization step size - bool intq; // flag for quantizig ints - SubbandAn sb; - float stepUDR; // The quantization step size (for a dynamic - // range of 1, or unit) - int g = ((System.Int32)gbs.getTileCompVal(tIdx, c)); - - // Are we quantizing ints or floats? - intq = (src.getDataType(tIdx, c) == DataBlk.TYPE_INT); - - // Check that we have an output object - if (cblk == null) - { - cblk = new CBlkWTDataInt(); - } - - // Cache input float code-block - infblk = this.infblk; - - // Get data to quantize. When quantizing int data 'cblk' is used to - // get the data to quantize and to return the quantized data as well, - // that's why 'getNextCodeBlock()' is used. This can not be done when - // quantizing float data because of the different data types, that's - // why 'getNextInternCodeBlock()' is used in that case. - if (intq) - { - // Source data is int - cblk = src.getNextCodeBlock(c, cblk); - if (cblk == null) - { - return null; // No more code-blocks in current tile for comp. - } - // Input and output arrays are the same (for "in place" quant.) - outarr = (int[])cblk.Data; - } - else - { - // Source data is float - // Can not use 'cblk' to get float data, use 'infblk' - infblk = (CBlkWTDataFloat)src.getNextInternCodeBlock(c, infblk); - if (infblk == null) - { - // Release buffer from infblk: this enables to garbage collect - // the big buffer when we are done with last code-block of - // component. - this.infblk.Data = null; - return null; // No more code-blocks in current tile for comp. - } - this.infblk = infblk; // Save local cache - infarr = (float[])infblk.Data; - // Get output data array and check that there is memory to put the - // quantized coeffs in - outarr = (int[])cblk.Data; - if (outarr == null || outarr.Length < infblk.w * infblk.h) - { - outarr = new int[infblk.w * infblk.h]; - cblk.Data = outarr; - } - cblk.m = infblk.m; - cblk.n = infblk.n; - cblk.sb = infblk.sb; - cblk.ulx = infblk.ulx; - cblk.uly = infblk.uly; - cblk.w = infblk.w; - cblk.h = infblk.h; - cblk.wmseScaling = infblk.wmseScaling; - cblk.offset = 0; - cblk.scanw = cblk.w; - } - - // Cache width, height and subband of code-block - w = cblk.w; - h = cblk.h; - sb = cblk.sb; - - if (isReversible(tIdx, c)) - { - // Reversible only for int data - cblk.magbits = g - 1 + src.getNomRangeBits(c) + sb.anGainExp; - shiftBits = 31 - cblk.magbits; - - // Update the convertFactor field - cblk.convertFactor = (1 << shiftBits); - - // Since we used getNextCodeBlock() to get the int data then - // 'offset' is 0 and 'scanw' is the width of the code-block The - // input and output arrays are the same (i.e. "in place") - for (j = w * h - 1; j >= 0; j--) - { - tmp = (outarr[j] << shiftBits); - outarr[j] = ((tmp < 0) ? (1 << 31) | (-tmp) : tmp); - } - } - else - { - // Non-reversible, use step size - //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Float.floatValue' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" - float baseStep = (float)((System.Single)qsss.getTileCompVal(tIdx, c)); - - // Calculate magnitude bits and quantization step size - if (isDerived(tIdx, c)) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - cblk.magbits = g - 1 + sb.level - (int)System.Math.Floor(System.Math.Log(baseStep) / log2); - stepUDR = baseStep / (1 << sb.level); - } - else - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - cblk.magbits = g - 1 - (int)System.Math.Floor(System.Math.Log(baseStep / (sb.l2Norm * (1 << sb.anGainExp))) / log2); - stepUDR = baseStep / (sb.l2Norm * (1 << sb.anGainExp)); - } - shiftBits = 31 - cblk.magbits; - // Calculate step that decoder will get and use that one. - stepUDR = convertFromExpMantissa(convertToExpMantissa(stepUDR)); - invstep = 1.0f / ((1L << (src.getNomRangeBits(c) + sb.anGainExp)) * stepUDR); - // Normalize to magnitude bits (output fractional point) - invstep *= (1 << (shiftBits - src.getFixedPoint(c))); - - // Update convertFactor and stepSize fields - cblk.convertFactor = invstep; - cblk.stepSize = ((1L << (src.getNomRangeBits(c) + sb.anGainExp)) * stepUDR); - - if (intq) - { - // Quantizing int data - // Since we used getNextCodeBlock() to get the int data then - // 'offset' is 0 and 'scanw' is the width of the code-block - // The input and output arrays are the same (i.e. "in place") - for (j = w * h - 1; j >= 0; j--) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - tmp = (int)(outarr[j] * invstep); - outarr[j] = ((tmp < 0) ? (1 << 31) | (-tmp) : tmp); - } - } - else - { - // Quantizing float data - for (j = w * h - 1, k = infblk.offset + (h - 1) * infblk.scanw + w - 1, jmin = w * (h - 1); j >= 0; jmin -= w) - { - for (; j >= jmin; k--, j--) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - tmp = (int)(infarr[k] * invstep); - outarr[j] = ((tmp < 0) ? (1 << 31) | (-tmp) : tmp); - } - // Jump to beggining of previous line in input - k -= (infblk.scanw - w); - } - } - } - // Return the quantized code-block - return cblk; - } - - /// Calculates the parameters of the SubbandAn objects that depend on the - /// Quantizer. The 'stepWMSE' field is calculated for each subband which is - /// a leaf in the tree rooted at 'sb', for the specified component. The - /// subband tree 'sb' must be the one for the component 'n'. - /// - /// - /// The root of the subband tree. - /// - /// - /// The component index - /// - /// - /// - /// - /// - protected internal override void calcSbParams(SubbandAn sb, int c) - { - float baseStep; - - if (sb.stepWMSE > 0f) - // parameters already calculated - return; - if (!sb.isNode) - { - if (isReversible(tIdx, c)) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - sb.stepWMSE = (float)System.Math.Pow(2, -(src.getNomRangeBits(c) << 1)) * sb.l2Norm * sb.l2Norm; - } - else - { - //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Float.floatValue' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" - baseStep = (float)((System.Single)qsss.getTileCompVal(tIdx, c)); - if (isDerived(tIdx, c)) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - sb.stepWMSE = baseStep * baseStep * (float)System.Math.Pow(2, (sb.anGainExp - sb.level) << 1) * sb.l2Norm * sb.l2Norm; - } - else - { - sb.stepWMSE = baseStep * baseStep; - } - } - } - else - { - calcSbParams((SubbandAn)sb.LL, c); - calcSbParams((SubbandAn)sb.HL, c); - calcSbParams((SubbandAn)sb.LH, c); - calcSbParams((SubbandAn)sb.HH, c); - sb.stepWMSE = 1f; // Signal that we already calculated this branch - } - } - - /// Converts the floating point value to its exponent-mantissa - /// representation. The mantissa occupies the 11 least significant bits - /// (bits 10-0), and the exponent the previous 5 bits (bits 15-11). - /// - /// - /// The quantization step, normalized to a dynamic range of 1. - /// - /// - /// The exponent mantissa representation of the step. - /// - /// - public static int convertToExpMantissa(float step) - { - int exp; - - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - exp = (int)System.Math.Ceiling((-System.Math.Log(step)) / log2); - if (exp > QSTEP_MAX_EXPONENT) - { - // If step size is too small for exponent representation, use the - // minimum, which is exponent QSTEP_MAX_EXPONENT and mantissa 0. - return (QSTEP_MAX_EXPONENT << QSTEP_MANTISSA_BITS); - } - // NOTE: this formula does not support more than 5 bits for the - // exponent, otherwise (-1< Converts the exponent-mantissa representation to its floating-point - /// value. The mantissa occupies the 11 least significant bits (bits 10-0), - /// and the exponent the previous 5 bits (bits 15-11). - /// - /// - /// The exponent-mantissa representation of the step. - /// - /// - /// The floating point representation of the step, normalized to a - /// dynamic range of 1. - /// - /// - private static float convertFromExpMantissa(int ems) - { - // NOTE: this formula does not support more than 5 bits for the - // exponent, otherwise (-1<> QSTEP_MANTISSA_BITS) & QSTEP_MAX_EXPONENT)); - } - - /// Returns the maximum number of magnitude bits in any subband of the - /// current tile. - /// - /// - /// the component number - /// - /// - /// The maximum number of magnitude bits in all subbands of the - /// current tile. - /// - /// - public override int getMaxMagBits(int c) - { - Subband sb = getAnSubbandTree(tIdx, c); - if (isReversible(tIdx, c)) - { - return getMaxMagBitsRev(sb, c); - } - else - { - if (isDerived(tIdx, c)) - { - return getMaxMagBitsDerived(sb, tIdx, c); - } - else - { - return getMaxMagBitsExpounded(sb, tIdx, c); - } - } - } - - - /// Returns the maximum number of magnitude bits in any subband of the - /// current tile if reversible quantization is used - /// - /// - /// The root of the subband tree of the current tile - /// - /// - /// the component number - /// - /// - /// The highest number of magnitude bit-planes - /// - /// - private int getMaxMagBitsRev(Subband sb, int c) - { - int tmp, max = 0; - int g = ((System.Int32)gbs.getTileCompVal(tIdx, c)); - - if (!sb.isNode) - return g - 1 + src.getNomRangeBits(c) + sb.anGainExp; - - max = getMaxMagBitsRev(sb.LL, c); - tmp = getMaxMagBitsRev(sb.LH, c); - if (tmp > max) - max = tmp; - tmp = getMaxMagBitsRev(sb.HL, c); - if (tmp > max) - max = tmp; - tmp = getMaxMagBitsRev(sb.HH, c); - if (tmp > max) - max = tmp; - - return max; - } - - /// Returns the maximum number of magnitude bits in any subband in the - /// given tile-component if derived quantization is used - /// - /// - /// The root of the subband tree of the tile-component - /// - /// - /// Tile index - /// - /// - /// Component index - /// - /// - /// The highest number of magnitude bit-planes - /// - /// - private int getMaxMagBitsDerived(Subband sb, int t, int c) - { - int tmp, max = 0; - int g = ((System.Int32)gbs.getTileCompVal(t, c)); - - if (!sb.isNode) - { - //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Float.floatValue' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" - float baseStep = (float)((System.Single)qsss.getTileCompVal(t, c)); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - return g - 1 + sb.level - (int)System.Math.Floor(System.Math.Log(baseStep) / log2); - } - - max = getMaxMagBitsDerived(sb.LL, t, c); - tmp = getMaxMagBitsDerived(sb.LH, t, c); - if (tmp > max) - max = tmp; - tmp = getMaxMagBitsDerived(sb.HL, t, c); - if (tmp > max) - max = tmp; - tmp = getMaxMagBitsDerived(sb.HH, t, c); - if (tmp > max) - max = tmp; - - return max; - } - - - /// Returns the maximum number of magnitude bits in any subband in the - /// given tile-component if expounded quantization is used - /// - /// - /// The root of the subband tree of the tile-component - /// - /// - /// Tile index - /// - /// - /// Component index - /// - /// - /// The highest number of magnitude bit-planes - /// - /// - private int getMaxMagBitsExpounded(Subband sb, int t, int c) - { - int tmp, max = 0; - int g = ((System.Int32)gbs.getTileCompVal(t, c)); - - if (!sb.isNode) - { - //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Float.floatValue' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" - float baseStep = (float)((System.Single)qsss.getTileCompVal(t, c)); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - return g - 1 - (int)System.Math.Floor(System.Math.Log(baseStep / (((SubbandAn)sb).l2Norm * (1 << sb.anGainExp))) / log2); - } - - max = getMaxMagBitsExpounded(sb.LL, t, c); - tmp = getMaxMagBitsExpounded(sb.LH, t, c); - if (tmp > max) - max = tmp; - tmp = getMaxMagBitsExpounded(sb.HL, t, c); - if (tmp > max) - max = tmp; - tmp = getMaxMagBitsExpounded(sb.HH, t, c); - if (tmp > max) - max = tmp; - - return max; - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/roi/MaxShiftSpec.cs b/CSJ2K/j2k/roi/MaxShiftSpec.cs deleted file mode 100644 index 0f4ba01a..00000000 --- a/CSJ2K/j2k/roi/MaxShiftSpec.cs +++ /dev/null @@ -1,73 +0,0 @@ -/* -* CVS identifier: -* -* $Id: MaxShiftSpec.java,v 1.10 2000/11/27 15:00:45 grosbois Exp $ -* -* Class: MaxShiftSpec -* -* Description: Generic class for storing module specs -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -*/ -namespace CSJ2K.j2k.roi -{ - - /// This class contains the maxshift scaling value for each tile-component. - /// The scaling values used are calculated in the ROIScaler class - /// - /// - - public class MaxShiftSpec : ModuleSpec - { - - /// Constructs a 'ModuleSpec' object, initializing all the components and - /// tiles to the 'SPEC_DEF' spec type, for the specified number of - /// components and tiles. - /// - /// - /// The number of tiles - /// - /// - /// The number of components - /// - /// - /// the type of the specification module i.e. tile specific, - /// component specific or both. - /// - /// - public MaxShiftSpec(int nt, int nc, byte type) : base(nt, nc, type) - { - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/roi/ROIDeScaler.cs b/CSJ2K/j2k/roi/ROIDeScaler.cs deleted file mode 100644 index 38bdd1cf..00000000 --- a/CSJ2K/j2k/roi/ROIDeScaler.cs +++ /dev/null @@ -1,375 +0,0 @@ -/* -* CVS identifier: -* -* $Id: ROIDeScaler.java,v 1.39 2001/10/24 12:02:51 grosbois Exp $ -* -* -* Class: ROIDeScaler -* -* Description: The class taking care of de-scaling ROI coeffs. -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.decoder; -using CSJ2K.j2k.image; -using CSJ2K.j2k.quantization.dequantizer; -using CSJ2K.j2k.util; -using CSJ2K.j2k.wavelet.synthesis; -namespace CSJ2K.j2k.roi -{ - - /// This class takes care of the de-scaling of ROI coefficients. The de-scaler - /// works on a tile basis and any mask that is generated is for the current - /// mask only - /// - ///

    Default implementations of the methods in 'MultiResImgData' are provided - /// through the 'MultiResImgDataAdapter' abstract class.

    - /// - ///

    Sign-magnitude representation is used (instead of two's complement) for - /// the output data. The most significant bit is used for the sign (0 if - /// positive, 1 if negative). Then the magnitude of the quantized coefficient - /// is stored in the next most significat bits. The most significant magnitude - /// bit corresponds to the most significant bit-plane and so on.

    - /// - ///
    - public class ROIDeScaler : MultiResImgDataAdapter, CBlkQuantDataSrcDec - { - /// Returns the horizontal code-block partition origin. Allowable values - /// are 0 and 1, nothing else. - /// - /// - virtual public int CbULX - { - get - { - return src.CbULX; - } - - } - /// Returns the vertical code-block partition origin. Allowable values are - /// 0 and 1, nothing else. - /// - /// - virtual public int CbULY - { - get - { - return src.CbULY; - } - - } - /// Returns the parameters that are used in this class and implementing - /// classes. It returns a 2D String array. Each of the 1D arrays is for a - /// different option, and they have 3 elements. The first element is the - /// option name, the second one is the synopsis and the third one is a long - /// description of what the parameter is. The synopsis or description may - /// be 'null', in which case it is assumed that there is no synopsis or - /// description of the option, respectively. Null may be returned if no - /// options are supported. - /// - /// - /// the options name, their synopsis and their explanation, or null - /// if no options are supported. - /// - /// - public static System.String[][] ParameterInfo - { - get - { - return pinfo; - } - - } - - /// The MaxShiftSpec containing the scaling values for all tile-components - /// - /// - private MaxShiftSpec mss; - - /// The prefix for ROI decoder options: 'R' - public const char OPT_PREFIX = 'R'; - - /// The list of parameters that is accepted by the entropy decoders. They - /// start with 'R'. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'pinfo'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly System.String[][] pinfo = new System.String[][] { new System.String[] { "Rno_roi", null, "This argument makes sure that the no ROI de-scaling is performed. " + "Decompression is done like there is no ROI in the image", null } }; - - /// The entropy decoder from where to get the compressed data (the source) - /// - /// - private CBlkQuantDataSrcDec src; - - /// Constructor of the ROI descaler, takes EntropyDEcoder as source of data - /// to de-scale. - /// - /// - /// The EntropyDecoder that is the source of data. - /// - /// - /// The MaxShiftSpec containing the scaling values for all - /// tile-components - /// - /// - public ROIDeScaler(CBlkQuantDataSrcDec src, MaxShiftSpec mss) : base(src) - { - this.src = src; - this.mss = mss; - } - - /// Returns the subband tree, for the specified tile-component. This method - /// returns the root element of the subband tree structure, see Subband and - /// SubbandSyn. The tree comprises all the available resolution levels. - /// - ///

    The number of magnitude bits ('magBits' member variable) for each - /// subband is not initialized. - /// - ///

    - /// The index of the tile, from 0 to T-1. - /// - /// - /// The index of the component, from 0 to C-1. - /// - /// - /// The root of the tree structure. - /// - /// - public override SubbandSyn getSynSubbandTree(int t, int c) - { - return src.getSynSubbandTree(t, c); - } - - /// Returns the specified code-block in the current tile for the specified - /// component, as a copy (see below). - /// - ///

    The returned code-block may be progressive, which is indicated by - /// the 'progressive' variable of the returned 'DataBlk' object. If a - /// code-block is progressive it means that in a later request to this - /// method for the same code-block it is possible to retrieve data which is - /// a better approximation, since meanwhile more data to decode for the - /// code-block could have been received. If the code-block is not - /// progressive then later calls to this method for the same code-block - /// will return the exact same data values.

    - /// - ///

    The data returned by this method is always a copy of the internal - /// data of this object, if any, and it can be modified "in place" without - /// any problems after being returned. The 'offset' of the returned data is - /// 0, and the 'scanw' is the same as the code-block width. See the - /// 'DataBlk' class.

    - /// - ///

    The 'ulx' and 'uly' members of the returned 'DataBlk' object contain - /// the coordinates of the top-left corner of the block, with respect to - /// the tile, not the subband.

    - /// - ///
    - /// The component for which to return the next code-block. - /// - /// - /// The vertical index of the code-block to return, in the - /// specified subband. - /// - /// - /// The horizontal index of the code-block to return, in the - /// specified subband. - /// - /// - /// The subband in which the code-block to return is. - /// - /// - /// If non-null this object will be used to return the new - /// code-block. If null a new one will be allocated and returned. If the - /// "data" array of the object is non-null it will be reused, if possible, - /// to return the data. - /// - /// - /// The next code-block in the current tile for component 'c', or - /// null if all code-blocks for the current tile have been returned. - /// - /// - /// - /// - /// - public virtual DataBlk getCodeBlock(int c, int m, int n, SubbandSyn sb, DataBlk cblk) - { - return getInternCodeBlock(c, m, n, sb, cblk); - } - - /// Returns the specified code-block in the current tile for the specified - /// component (as a reference or copy). - /// - ///

    The returned code-block may be progressive, which is indicated by - /// the 'progressive' variable of the returned 'DataBlk' object. If a - /// code-block is progressive it means that in a later request to this - /// method for the same code-block it is possible to retrieve data which is - /// a better approximation, since meanwhile more data to decode for the - /// code-block could have been received. If the code-block is not - /// progressive then later calls to this method for the same code-block - /// will return the exact same data values.

    - /// - ///

    The data returned by this method can be the data in the internal - /// buffer of this object, if any, and thus can not be modified by the - /// caller. The 'offset' and 'scanw' of the returned data can be - /// arbitrary. See the 'DataBlk' class.

    - /// - ///

    The 'ulx' and 'uly' members of the returned 'DataBlk' object contain - /// the coordinates of the top-left corner of the block, with respect to - /// the tile, not the subband.

    - /// - ///
    - /// The component for which to return the next code-block. - /// - /// - /// The vertical index of the code-block to return, in the - /// specified subband. - /// - /// - /// The horizontal index of the code-block to return, in the - /// specified subband. - /// - /// - /// The subband in which the code-block to return is. - /// - /// - /// If non-null this object will be used to return the new - /// code-block. If null a new one will be allocated and returned. If the - /// "data" array of the object is non-null it will be reused, if possible, - /// to return the data. - /// - /// - /// The requested code-block in the current tile for component 'c'. - /// - /// - /// - /// - /// - public virtual DataBlk getInternCodeBlock(int c, int m, int n, SubbandSyn sb, DataBlk cblk) - { - int i, j, k, wrap; // mi removed - int ulx, uly, w, h; - int[] data; // local copy of quantized data - int tmp; - //int limit; - - // Get data block from entropy decoder - cblk = src.getInternCodeBlock(c, m, n, sb, cblk); - - // If there are no ROIs in the tile, Or if we already got all blocks - bool noRoiInTile = false; - if (mss == null || mss.getTileCompVal(TileIdx, c) == null) - noRoiInTile = true; - - if (noRoiInTile || cblk == null) - { - return cblk; - } - data = (int[])cblk.Data; - ulx = cblk.ulx; - uly = cblk.uly; - w = cblk.w; - h = cblk.h; - - // Scale coefficients according to magnitude. If the magnitude of a - // coefficient is lower than 2 pow 31-magbits then it is a background - // coeff and should be up-scaled - int boost = ((System.Int32)mss.getTileCompVal(TileIdx, c)); - int mask = ((1 << sb.magbits) - 1) << (31 - sb.magbits); - int mask2 = (~mask) & 0x7FFFFFFF; - - wrap = cblk.scanw - w; - i = cblk.offset + cblk.scanw * (h - 1) + w - 1; - for (j = h; j > 0; j--) - { - for (k = w; k > 0; k--, i--) - { - tmp = data[i]; - if ((tmp & mask) == 0) - { - // BG - data[i] = (tmp & unchecked((int)0x80000000)) | (tmp << boost); - } - else - { - // ROI - if ((tmp & mask2) != 0) - { - // decoded more than magbits bit-planes, set - // quantization mid-interval approx. bit just after - // the magbits. - data[i] = (tmp & (~mask2)) | (1 << (30 - sb.magbits)); - } - } - } - i -= wrap; - } - return cblk; - } - - /// Creates a ROIDeScaler object. The information needed to create the - /// object is the Entropy decoder used and the parameters. - /// - /// - /// The source of data that is to be descaled - /// - /// - /// The parameter list (or options). - /// - /// - /// The decoding specifications - /// - /// - /// If an error occurs while parsing - /// the options in 'pl' - /// - /// - public static ROIDeScaler createInstance(CBlkQuantDataSrcDec src, ParameterList pl, DecoderSpecs decSpec) - { - System.String noRoi; - //int i; - - // Check parameters - pl.checkList(OPT_PREFIX, CSJ2K.j2k.util.ParameterList.toNameArray(pinfo)); - - // Check if no_roi specified in command line or no roi signalled - // in bit stream - noRoi = pl.getParameter("Rno_roi"); - if (noRoi != null || decSpec.rois == null) - { - // no_roi specified in commandline! - return new ROIDeScaler(src, null); - } - - return new ROIDeScaler(src, decSpec.rois); - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/roi/encoder/ArbROIMaskGenerator.cs b/CSJ2K/j2k/roi/encoder/ArbROIMaskGenerator.cs deleted file mode 100644 index 7eef4d11..00000000 --- a/CSJ2K/j2k/roi/encoder/ArbROIMaskGenerator.cs +++ /dev/null @@ -1,619 +0,0 @@ -/* -* CVS identifier: -* -* $Id: ArbROIMaskGenerator.java,v 1.4 2001/01/03 15:10:21 qtxjoas Exp $ -* -* Class: ArbROIMaskGenerator -* -* Description: Generates masks when only rectangular ROIs exist -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.image; -using CSJ2K.j2k.image.input; -using CSJ2K.j2k.quantization.quantizer; -using CSJ2K.j2k.wavelet; -namespace CSJ2K.j2k.roi.encoder -{ - - /// This class generates the ROI bit-mask when, at least, one ROI is not - /// rectangular. In this case, the fast ROI bit-mask algorithm generation can - /// not be used. - /// - ///

    The values are calculated from the scaling factors of the ROIs. The - /// values with which to scale are equal to u-umin where umin is the lowest - /// scaling factor within the block. The umin value is sent to the entropy - /// coder to be used for scaling the distortion values. - /// - ///

    - /// - /// - /// - /// - /// - /// - public class ArbROIMaskGenerator : ROIMaskGenerator - { - - /// The source of quantized wavelet transform coefficients - private Quantizer src; - - /// The ROI mask for the current tile for all components - private int[][] roiMask; - - /// The low frequency part of a mask line - private int[] maskLineLow; - - /// The High frequency part of a mask line - private int[] maskLineHigh; - - /// A line or column of the mask with padding - private int[] paddedMaskLine; - - /// Flag indicating if any ROI was found to be in this tile - new private bool roiInTile; - - /// The constructor of the arbitrary mask generator - /// - /// - /// The ROI info. - /// - /// - /// The number of components - /// - /// - /// The quantizer module - /// - /// - public ArbROIMaskGenerator(ROI[] rois, int nrc, Quantizer src) : base(rois, nrc) - { - roiMask = new int[nrc][]; - this.src = src; - } - - /// This functions gets a DataBlk the size of the current code-block an - /// fills this block with the ROI mask. - /// - ///

    In order to get the mask for a particular Subband, the subband tree - /// is traversed and at each decomposition, the ROI masks are computed. - /// - ///

    The widths of the synthesis filters corresponding to the wavelet - /// filters used in the wavelet transform are used to expand the ROI masks - /// in the decompositions. - /// - ///

    - /// The data block that is to be filled with the mask - /// - /// - /// The root of the subband tree to which db belongs - /// - /// - /// The max number of magnitude bits in any code-block - /// - /// - /// The number of the component - /// - /// - /// Whether or not a mask was needed for this tile - /// - /// - public override bool getROIMask(DataBlkInt db, Subband sb, int magbits, int c) - { - int x = db.ulx; - int y = db.uly; - int w = db.w; - int h = db.h; - int tilew = sb.w; - int tileh = sb.h; - int[] maskData = (int[])db.Data; - int i, j, k, bi, wrap; - - // If the ROI mask has not been calculated for this tile and - // component, do so now. - if (!tileMaskMade[c]) - { - makeMask(sb, magbits, c); - tileMaskMade[c] = true; - } - if (!roiInTile) - return false; - - int[] mask = roiMask[c]; // local copy - - // Copy relevant part of the ROI mask to the datablock - i = (y + h - 1) * tilew + x + w - 1; - bi = w * h - 1; - wrap = tilew - w; - for (j = h; j > 0; j--) - { - for (k = w; k > 0; k--, i--, bi--) - { - maskData[bi] = mask[i]; - } - i -= wrap; - } - return true; - } - - /// This function returns the relevant data of the mask generator - /// - /// - public override System.String ToString() - { - return ("Fast rectangular ROI mask generator"); - } - - /// This function generates the ROI mask for one tile-component. - /// - ///

    Once the mask is generated in the pixel domain. it is decomposed - /// following the same decomposition scheme as the wavelet transform. - /// - ///

    - /// The root of the subband tree used in the decomposition - /// - /// - /// The max number of magnitude bits in any code-block - /// - /// - /// component number - /// - public override void makeMask(Subband sb, int magbits, int c) - { - int[] mask; // local copy - ROI[] rois = this.roi_array; // local copy - int i, j, k, r, maxj; // mink, minj removed - int lrx, lry; - int x, y, w, h; - int cx, cy, rad; - int wrap; - int curScalVal; - int tileulx = sb.ulcx; - int tileuly = sb.ulcy; - int tilew = sb.w; - int tileh = sb.h; - int lineLen = (tilew > tileh) ? tilew : tileh; - - // Make sure there is a sufficiently large mask buffer - if (roiMask[c] == null || (roiMask[c].Length < (tilew * tileh))) - { - roiMask[c] = new int[tilew * tileh]; - mask = roiMask[c]; - } - else - { - mask = roiMask[c]; - for (i = tilew * tileh - 1; i >= 0; i--) - mask[i] = 0; - } - - // Make sure there are sufficiently large line buffers - if (maskLineLow == null || (maskLineLow.Length < (lineLen + 1) / 2)) - maskLineLow = new int[(lineLen + 1) / 2]; - if (maskLineHigh == null || (maskLineHigh.Length < (lineLen + 1) / 2)) - maskLineHigh = new int[(lineLen + 1) / 2]; - - roiInTile = false; - // Generate ROIs in pixel domain: - for (r = rois.Length - 1; r >= 0; r--) - { - if (rois[r].comp == c) - { - curScalVal = magbits; - - if (rois[r].arbShape) - { - ImgReaderPGM maskPGM = rois[r].maskPGM; // Local copy - - if ((src.ImgWidth != maskPGM.ImgWidth) || (src.ImgHeight != maskPGM.ImgHeight)) - throw new System.ArgumentException("Input image and" + " ROI mask must " + "have the same " + "size"); - x = src.ImgULX; - y = src.ImgULY; - lrx = x + src.ImgWidth - 1; - lry = y + src.ImgHeight - 1; - if ((x > tileulx + tilew) || (y > tileuly + tileh) || (lrx < tileulx) || (lry < tileuly)) - // Roi not in tile - continue; - - // Check bounds - x -= tileulx; - lrx -= tileulx; - y -= tileuly; - lry -= tileuly; - - int offx = 0; - int offy = 0; - if (x < 0) - { - offx = -x; - x = 0; - } - if (y < 0) - { - offy = -y; - y = 0; - } - w = (lrx > (tilew - 1)) ? tilew - x : lrx + 1 - x; - h = (lry > (tileh - 1)) ? tileh - y : lry + 1 - y; - - - // Get shape line by line to reduce memory - DataBlkInt srcblk = new DataBlkInt(); - int mDcOff = -ImgReaderPGM.DC_OFFSET; - int nROIcoeff = 0; - int[] src_data; - srcblk.ulx = offx; - srcblk.w = w; - srcblk.h = 1; - - i = (y + h - 1) * tilew + x + w - 1; - maxj = w; - wrap = tilew - maxj; - for (k = h; k > 0; k--) - { - srcblk.uly = offy + k - 1; - srcblk = (DataBlkInt)maskPGM.getInternCompData(srcblk, 0); - src_data = srcblk.DataInt; - - for (j = maxj; j > 0; j--, i--) - { - if (src_data[j - 1] != mDcOff) - { - mask[i] = curScalVal; - nROIcoeff++; - } - } - i -= wrap; - } - - if (nROIcoeff != 0) - { - roiInTile = true; - } - } - else if (rois[r].rect) - { - // Rectangular ROI - x = rois[r].ulx; - y = rois[r].uly; - lrx = rois[r].w + x - 1; - lry = rois[r].h + y - 1; - - if ((x > tileulx + tilew) || (y > tileuly + tileh) || (lrx < tileulx) || (lry < tileuly)) - // Roi not in tile - continue; - - roiInTile = true; - - // Check bounds - x -= tileulx; - lrx -= tileulx; - y -= tileuly; - lry -= tileuly; - - x = (x < 0) ? 0 : x; - y = (y < 0) ? 0 : y; - w = (lrx > (tilew - 1)) ? tilew - x : lrx + 1 - x; - h = (lry > (tileh - 1)) ? tileh - y : lry + 1 - y; - - i = (y + h - 1) * tilew + x + w - 1; - maxj = w; - wrap = tilew - maxj; - for (k = h; k > 0; k--) - { - for (j = maxj; j > 0; j--, i--) - { - mask[i] = curScalVal; - } - i -= wrap; - } - } - else - { - // Non-rectangular ROI. So far only circular case - cx = rois[r].x - tileulx; - cy = rois[r].y - tileuly; - rad = rois[r].r; - i = tileh * tilew - 1; - for (k = tileh - 1; k >= 0; k--) - { - for (j = tilew - 1; j >= 0; j--, i--) - { - if (((j - cx) * (j - cx) + (k - cy) * (k - cy) < rad * rad)) - { - mask[i] = curScalVal; - roiInTile = true; - } - } - } - } - } - } - - // If wavelet transform is used - if (sb.isNode) - { - // Decompose the mask according to the subband tree - // Calculate size of padded line buffer - WaveletFilter vFilter = sb.VerWFilter; - WaveletFilter hFilter = sb.HorWFilter; - int lvsup = vFilter.SynLowNegSupport + vFilter.SynLowPosSupport; - int hvsup = vFilter.SynHighNegSupport + vFilter.SynHighPosSupport; - int lhsup = hFilter.SynLowNegSupport + hFilter.SynLowPosSupport; - int hhsup = hFilter.SynHighNegSupport + hFilter.SynHighPosSupport; - lvsup = (lvsup > hvsup) ? lvsup : hvsup; - lhsup = (lhsup > hhsup) ? lhsup : hhsup; - lvsup = (lvsup > lhsup) ? lvsup : lhsup; - paddedMaskLine = new int[lineLen + lvsup]; - - if (roiInTile) - decomp(sb, tilew, tileh, c); - } - } - - /// This function decomposes the mask for a node in the subband tree. - /// after the mask is decomposed for a node, this function is called for - /// the children of the subband. The decomposition is done line by line - /// and column by column - /// - /// - /// The subband that is to be used for the decomposition - /// - /// - /// The width of the current tile - /// - /// - /// The height of the current tile - /// - /// - /// component number - /// - private void decomp(Subband sb, int tilew, int tileh, int c) - { - int ulx = sb.ulx; - int uly = sb.uly; - int w = sb.w; - int h = sb.h; - int scalVal, maxVal = 0; - int j, k, s, mi = 0, pin; // i, hi, li removed - int hmax, lmax; // smax removed - int lineoffs; // wrap, lastlow removed - int[] mask = roiMask[c]; // local copy - int[] low = maskLineLow; // local copy - int[] high = maskLineHigh; // local copy - int[] padLine = paddedMaskLine; // local copy - int highFirst = 0; - int lastpin; - - - if (!sb.isNode) - return; - - // HORIZONTAL DECOMPOSITION - - // Calculate number of high and low samples after decomposition - // and get support for low and high filters - WaveletFilter filter = sb.HorWFilter; - int lnSup = filter.SynLowNegSupport; - int hnSup = filter.SynHighNegSupport; - int lpSup = filter.SynLowPosSupport; - int hpSup = filter.SynHighPosSupport; - int lsup = lnSup + lpSup + 1; - int hsup = hnSup + hpSup + 1; - - // Calculate number of high/low coeffis in subbands - highFirst = sb.ulcx % 2; - if (sb.w % 2 == 0) - { - lmax = w / 2 - 1; - hmax = lmax; - } - else - { - if (highFirst == 0) - { - lmax = (w + 1) / 2 - 1; - hmax = w / 2 - 1; - } - else - { - hmax = (w + 1) / 2 - 1; - lmax = w / 2 - 1; - } - } - - int maxnSup = (lnSup > hnSup) ? lnSup : hnSup; // Maximum negative support - int maxpSup = (lpSup > hpSup) ? lpSup : hpSup; // Maximum positive support - - - // Set padding to 0 - for (pin = maxnSup - 1; pin >= 0; pin--) - padLine[pin] = 0; - for (pin = maxnSup + w - 1 + maxpSup; pin >= w; pin--) - padLine[pin] = 0; - - // Do decomposition of all lines - lineoffs = (uly + h) * tilew + ulx + w - 1; - for (j = h - 1; j >= 0; j--) - { - lineoffs -= tilew; - // Get the line to transform from the mask - mi = lineoffs; - for (k = w, pin = w - 1 + maxnSup; k > 0; k--, mi--, pin--) - { - padLine[pin] = mask[mi]; - } - - lastpin = maxnSup + highFirst + 2 * lmax + lpSup; - for (k = lmax; k >= 0; k--, lastpin -= 2) - { - // Low frequency samples - pin = lastpin; - for (s = lsup; s > 0; s--, pin--) - { - scalVal = padLine[pin]; - if (scalVal > maxVal) - maxVal = scalVal; - } - low[k] = maxVal; - maxVal = 0; - } - lastpin = maxnSup - highFirst + 2 * hmax + 1 + hpSup; - for (k = hmax; k >= 0; k--, lastpin -= 2) - { - // High frequency samples - pin = lastpin; - for (s = hsup; s > 0; s--, pin--) - { - scalVal = padLine[pin]; - if (scalVal > maxVal) - maxVal = scalVal; - } - high[k] = maxVal; - maxVal = 0; - } - // Put the lows and highs back - mi = lineoffs; - for (k = hmax; k >= 0; k--, mi--) - { - mask[mi] = high[k]; - } - for (k = lmax; k >= 0; k--, mi--) - { - mask[mi] = low[k]; - } - } - - // VERTICAL DECOMPOSITION - - // Calculate number of high and low samples after decomposition - // and get support for low and high filters - filter = sb.VerWFilter; - lnSup = filter.SynLowNegSupport; - hnSup = filter.SynHighNegSupport; - lpSup = filter.SynLowPosSupport; - hpSup = filter.SynHighPosSupport; - lsup = lnSup + lpSup + 1; - hsup = hnSup + hpSup + 1; - - // Calculate number of high/low coeffs in subbands - highFirst = sb.ulcy % 2; - if (sb.h % 2 == 0) - { - lmax = h / 2 - 1; - hmax = lmax; - } - else - { - if (sb.ulcy % 2 == 0) - { - lmax = (h + 1) / 2 - 1; - hmax = h / 2 - 1; - } - else - { - hmax = (h + 1) / 2 - 1; - lmax = h / 2 - 1; - } - } - - maxnSup = (lnSup > hnSup) ? lnSup : hnSup; // Maximum negative support - maxpSup = (lpSup > hpSup) ? lpSup : hpSup; // Maximum positive support - - // Set padding to 0 - for (pin = maxnSup - 1; pin >= 0; pin--) - padLine[pin] = 0; - for (pin = maxnSup + h - 1 + maxpSup; pin >= h; pin--) - padLine[pin] = 0; - - // Do decomposition of all columns - lineoffs = (uly + h - 1) * tilew + ulx + w; - for (j = w - 1; j >= 0; j--) - { - lineoffs--; - // Get the line to transform from the mask - mi = lineoffs; - for (k = h, pin = k - 1 + maxnSup; k > 0; k--, mi -= tilew, pin--) - { - padLine[pin] = mask[mi]; - } - lastpin = maxnSup + highFirst + 2 * lmax + lpSup; - for (k = lmax; k >= 0; k--, lastpin -= 2) - { - // Low frequency samples - pin = lastpin; - for (s = lsup; s > 0; s--, pin--) - { - scalVal = padLine[pin]; - if (scalVal > maxVal) - maxVal = scalVal; - } - low[k] = maxVal; - maxVal = 0; - } - lastpin = maxnSup - highFirst + 2 * hmax + 1 + hpSup; - for (k = hmax; k >= 0; k--, lastpin -= 2) - { - // High frequency samples - pin = lastpin; - for (s = hsup; s > 0; s--, pin--) - { - scalVal = padLine[pin]; - if (scalVal > maxVal) - maxVal = scalVal; - } - high[k] = maxVal; - maxVal = 0; - } - // Put the lows and highs back - mi = lineoffs; - for (k = hmax; k >= 0; k--, mi -= tilew) - { - mask[mi] = high[k]; - } - for (k = lmax; k >= 0; k--, mi -= tilew) - { - mask[mi] = low[k]; - } - } - - if (sb.isNode) - { - decomp(sb.HH, tilew, tileh, c); - decomp(sb.LH, tilew, tileh, c); - decomp(sb.HL, tilew, tileh, c); - decomp(sb.LL, tilew, tileh, c); - } - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/roi/encoder/ROI.cs b/CSJ2K/j2k/roi/encoder/ROI.cs deleted file mode 100644 index ba61a1fb..00000000 --- a/CSJ2K/j2k/roi/encoder/ROI.cs +++ /dev/null @@ -1,170 +0,0 @@ -/* -* CVS identifier: -* -* $Id: ROI.java,v 1.3 2001/01/03 15:08:15 qtxjoas Exp $ -* -* Class: ROI -* -* Description: This class describes a single ROI -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -*/ -using CSJ2K.j2k.image.input; -namespace CSJ2K.j2k.roi.encoder -{ - - /// This class contains the shape of a single ROI. In the current - /// implementation only rectangles and circles are supported. - /// - /// - /// - /// - public class ROI - { - - /// ImgReaderPGM object with the arbrtrary ROI - public ImgReaderPGM maskPGM = null; - - /// Where or not the ROI shape is arbitrary - public bool arbShape; - - /// Flag indicating whether the ROI is rectangular or not - public bool rect; - - /// The components for which the ROI is relevant - public int comp; - - /// x coordinate of upper left corner of rectangular ROI - public int ulx; - - /// y coordinate of upper left corner of rectangular ROI - public int uly; - - /// width of rectangular ROI - public int w; - - /// height of rectangular ROI - public int h; - - /// x coordinate of center of circular ROI - public int x; - - /// y coordinate of center of circular ROI - public int y; - - /// radius of circular ROI - public int r; - - - /// Constructor for ROI with arbitrary shape - /// - /// - /// The component the ROI belongs to - /// - /// - /// ImgReaderPGM containing the ROI - /// - public ROI(int comp, ImgReaderPGM maskPGM) - { - arbShape = true; - rect = false; - this.comp = comp; - this.maskPGM = maskPGM; - } - - /// Constructor for rectangular ROIs - /// - /// - /// The component the ROI belongs to - /// - /// - /// x-coordinate of upper left corner of ROI - /// - /// - /// y-coordinate of upper left corner of ROI - /// - /// - /// width of ROI - /// - /// - /// height of ROI - /// - public ROI(int comp, int ulx, int uly, int w, int h) - { - arbShape = false; - this.comp = comp; - this.ulx = ulx; - this.uly = uly; - this.w = w; - this.h = h; - rect = true; - } - - /// Constructor for circular ROIs - /// - /// - /// The component the ROI belongs to - /// - /// - /// x-coordinate of center of ROI - /// - /// - /// y-coordinate of center of ROI - /// - /// - /// radius of ROI - /// - public ROI(int comp, int x, int y, int rad) - { - arbShape = false; - this.comp = comp; - this.x = x; - this.y = y; - this.r = rad; - } - - /// This function prints all relevant data for the ROI - public override System.String ToString() - { - if (arbShape) - { - return "ROI with arbitrary shape, PGM file= " + maskPGM; - } - else if (rect) - return "Rectangular ROI, comp=" + comp + " ulx=" + ulx + " uly=" + uly + " w=" + w + " h=" + h; - else - return "Circular ROI, comp=" + comp + " x=" + x + " y=" + y + " radius=" + r; - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/roi/encoder/ROIMaskGenerator.cs b/CSJ2K/j2k/roi/encoder/ROIMaskGenerator.cs deleted file mode 100644 index 5519dd63..00000000 --- a/CSJ2K/j2k/roi/encoder/ROIMaskGenerator.cs +++ /dev/null @@ -1,152 +0,0 @@ -/* -* CVS identifier: -* -* $Id: ROIMaskGenerator.java,v 1.2 2000/11/27 15:03:51 grosbois Exp $ -* -* Class: ROIMaskGenerator -* -* Description: This class describes generators of ROI masks -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -*/ -using CSJ2K.j2k.image; -using CSJ2K.j2k.wavelet; -namespace CSJ2K.j2k.roi.encoder -{ - - /// This class generates the ROI masks for the ROIScaler.It gives the scaler - /// the ROI mask for the current code-block. - /// - ///

    The values are calculated from the scaling factors of the ROIs. The - /// values with which to scale are equal to u-umin where umin is the lowest - /// scaling factor within the block. The umin value is sent to the entropy - /// coder to be used for scaling the distortion values. - /// - ///

    - /// - /// - /// - /// - /// - /// - public abstract class ROIMaskGenerator - { - /// This function returns the ROIs in the image - /// - /// - /// The ROIs in the image - /// - virtual public ROI[] ROIs - { - get - { - return roi_array; - } - - } - - /// Array containing the ROIs - protected internal ROI[] roi_array; - - /// Number of components - protected internal int nrc; - - /// Flag indicating whether a mask has been made for the current tile - protected internal bool[] tileMaskMade; - - /* Flag indicating whether there are any ROIs in this tile */ - protected internal bool roiInTile; - - /// The constructor of the mask generator - /// - /// - /// The ROIs in the image - /// - /// - /// The number of components - /// - public ROIMaskGenerator(ROI[] rois, int nrc) - { - this.roi_array = rois; - this.nrc = nrc; - tileMaskMade = new bool[nrc]; - } - - /// This functions gets a DataBlk with the size of the current code-block - /// and fills it with the ROI mask. The lowest scaling value in the mask - /// for this code-block is returned by the function to be used for - /// modifying the rate distortion estimations. - /// - /// - /// The data block that is to be filled with the mask - /// - /// - /// The root of the current subband tree - /// - /// - /// The number of magnitude bits in this code-block - /// - /// - /// Component number - /// - /// - /// Whether or not a mask was needed for this tile - /// - public abstract bool getROIMask(DataBlkInt db, Subband sb, int magbits, int c); - - /// This function generates the ROI mask for the entire tile. The mask is - /// generated for one component. This method is called once for each tile - /// and component. - /// - /// - /// The root of the subband tree used in the decomposition - /// - /// - /// The max number of magnitude bits in any code-block - /// - /// - /// component number - /// - public abstract void makeMask(Subband sb, int magbits, int n); - - /// This function is called every time the tile is changed to indicate - /// that there is need to make a new mask - /// - public virtual void tileChanged() - { - for (int i = 0; i < nrc; i++) - tileMaskMade[i] = false; - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/roi/encoder/ROIScaler.cs b/CSJ2K/j2k/roi/encoder/ROIScaler.cs deleted file mode 100644 index 70ee3c99..00000000 --- a/CSJ2K/j2k/roi/encoder/ROIScaler.cs +++ /dev/null @@ -1,809 +0,0 @@ -/* -* CVS identifier: -* -* $Id: ROIScaler.java,v 1.11 2001/09/20 12:42:20 grosbois Exp $ -* -* Class: ROIScaler -* -* Description: This class takes care of the scaling of the -* samples -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.encoder; -using CSJ2K.j2k.image; -using CSJ2K.j2k.image.input; -using CSJ2K.j2k.quantization.quantizer; -using CSJ2K.j2k.util; -using CSJ2K.j2k.wavelet; -using CSJ2K.j2k.wavelet.analysis; -namespace CSJ2K.j2k.roi.encoder -{ - - /// This class deals with the ROI functionality. - /// - ///

    The ROI method is the Maxshift method. The ROIScaler works by scaling - /// the quantized wavelet coefficients that do not affect the ROI (i.e - /// background coefficients) so that these samples get a lower significance - /// than the ROI ones. By scaling the coefficients sufficiently, the ROI - /// coefficients can be recognized by their amplitude alone and no ROI mask - /// needs to be generated at the decoder side. - /// - ///

    The source module must be a quantizer and code-block's data is exchange - /// with thanks to CBlkWTData instances. - /// - ///

    - /// - /// - /// - /// - /// - public class ROIScaler : ImgDataAdapter, CBlkQuantDataSrcEnc - { - /// Returns the horizontal offset of the code-block partition. Allowable - /// values are 0 and 1, nothing else. - /// - /// - virtual public int CbULX - { - get - { - return src.CbULX; - } - - } - /// Returns the vertical offset of the code-block partition. Allowable - /// values are 0 and 1, nothing else. - /// - /// - virtual public int CbULY - { - get - { - return src.CbULY; - } - - } - /// This function returns the ROI mask generator. - /// - /// - /// The roi mask generator - /// - virtual public ROIMaskGenerator ROIMaskGenerator - { - get - { - return mg; - } - - } - /// This function returns the blockAligned flag - /// - /// - /// Flag indicating whether the ROIs were block aligned - /// - virtual public bool BlockAligned - { - get - { - return blockAligned; - } - - } - /// Returns the parameters that are used in this class and - /// implementing classes. It returns a 2D String array. Each of the - /// 1D arrays is for a different option, and they have 3 - /// elements. The first element is the option name, the second one - /// is the synopsis, the third one is a long description of what - /// the parameter is and the fourth is its default value. The - /// synopsis or description may be 'null', in which case it is - /// assumed that there is no synopsis or description of the option, - /// respectively. Null may be returned if no options are supported. - /// - /// - /// the options name, their synopsis and their explanation, - /// or null if no options are supported. - /// - /// - public static System.String[][] ParameterInfo - { - get - { - return pinfo; - } - - } - - /// The prefix for ROI Scaler options: 'R' - public const char OPT_PREFIX = 'R'; - - /// The list of parameters that are accepted for ROI coding. Options - /// for ROI Scaler start with 'R'. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'pinfo'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly System.String[][] pinfo = new System.String[][] { new System.String[] { "Rroi", "[] R " + " or [] C " + " or [] A ", "Specifies ROIs shape and location. The shape can be either " + "rectangular 'R', or circular 'C' or arbitrary 'A'. " + "Each new occurrence of an 'R', a 'C' or an 'A' is a new ROI. " + "For circular and rectangular ROIs, all values are " + "given as their pixel values relative to the canvas origin. " + "Arbitrary shapes must be included in a PGM file where non 0 " + "values correspond to ROI coefficients. The PGM file must have " + "the size as the image. " + "The component idx specifies which components " + "contain the ROI. The component index is specified as described " + "by points 3 and 4 in the general comment on tile-component idx. " + "If this option is used, the codestream is layer progressive by " + "default unless it is overridden by the 'Aptype' option.", null }, new System.String[] { "Ralign", "[on|off]", "By specifying this argument, the ROI mask will be " + "limited to covering only entire code-blocks. The ROI coding can " + "then be performed without any actual scaling of the coefficients " + "but by instead scaling the distortion estimates.", "off" }, new System.String[] { "Rstart_level", "", "This argument forces the lowest resolution levels to " + "belong to the ROI. By doing this, it is possible to avoid only " + "getting information for the ROI at an early stage of " + "transmission. = 0 means the lowest resolution level " + "belongs to the ROI, 1 means the two lowest etc. (-1 deactivates" + " the option)", "-1" }, new System.String[] { "Rno_rect", "[on|off]", "This argument makes sure that the ROI mask generation is not done " + "using the fast ROI mask generation for rectangular ROIs " + "regardless of whether the specified ROIs are rectangular or not", "off" } }; - - /// The maximum number of magnitude bit-planes in any subband. One value - /// for each tile-component - /// - private int[][] maxMagBits; - - /// Flag indicating the presence of ROIs - private bool roi; - - /// Flag indicating if block aligned ROIs are used - private bool blockAligned; - - /// Number of resolution levels to include in ROI mask - private int useStartLevel; - - /// The class generating the ROI mask - private ROIMaskGenerator mg; - - /// The ROI mask - private DataBlkInt roiMask; - - /// The source of quantized wavelet transform coefficients - private Quantizer src; - - /// Constructor of the ROI scaler, takes a Quantizer as source of data to - /// scale. - /// - /// - /// The quantizer that is the source of data. - /// - /// - /// The mask generator that will be used for all components - /// - /// - /// Flag indicating whether there are rois specified. - /// - /// - /// The resolution levels that belong entirely to ROI - /// - /// - /// Flag indicating whether block aligning is used. - /// - /// - /// The encoder specifications for addition of roi specs - /// - /// - public ROIScaler(Quantizer src, ROIMaskGenerator mg, bool roi, int sLev, bool uba, EncoderSpecs encSpec) : base(src) - { - this.src = src; - this.roi = roi; - this.useStartLevel = sLev; - if (roi) - { - // If there is no ROI, no need to do this - this.mg = mg; - roiMask = new DataBlkInt(); - calcMaxMagBits(encSpec); - blockAligned = uba; - } - } - - /// Since ROI scaling is always a reversible operation, it calls - /// isReversible() method of it source (the quantizer module). - /// - /// - /// The tile to test for reversibility - /// - /// - /// The component to test for reversibility - /// - /// - /// True if the quantized data is reversible, false if not. - /// - /// - public virtual bool isReversible(int t, int c) - { - return src.isReversible(t, c); - } - - /// Returns a reference to the subband tree structure representing the - /// subband decomposition for the specified tile-component. - /// - /// - /// The index of the tile. - /// - /// - /// The index of the component. - /// - /// - /// The subband tree structure, see SubbandAn. - /// - /// - /// - /// - /// - /// - /// - /// - public virtual SubbandAn getAnSubbandTree(int t, int c) - { - return src.getAnSubbandTree(t, c); - } - - /// Creates a ROIScaler object. The Quantizer is the source of data to - /// scale. - /// - ///

    The ROI Scaler creates a ROIMaskGenerator depending on what ROI - /// information is in the ParameterList. If only rectangular ROI are used, - /// the fast mask generator for rectangular ROI can be used.

    - /// - ///
    - /// The source of data to scale - /// - /// - /// The parameter list (or options). - /// - /// - /// The encoder specifications for addition of roi specs - /// - /// - /// If an error occurs while parsing - /// the options in 'pl' - /// - /// - public static ROIScaler createInstance(Quantizer src, ParameterList pl, EncoderSpecs encSpec) - { - System.Collections.ArrayList roiVector = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); - ROIMaskGenerator maskGen = null; - - // Check parameters - pl.checkList(OPT_PREFIX, CSJ2K.j2k.util.ParameterList.toNameArray(pinfo)); - - // Get parameters and check if there are and ROIs specified - System.String roiopt = pl.getParameter("Rroi"); - if (roiopt == null) - { - // No ROIs specified! Create ROIScaler with no mask generator - return new ROIScaler(src, null, false, -1, false, encSpec); - } - - // Check if the lowest resolution levels should belong to the ROI - int sLev = pl.getIntParameter("Rstart_level"); - - // Check if the ROIs are block-aligned - bool useBlockAligned = pl.getBooleanParameter("Ralign"); - - // Check if generic mask generation is specified - bool onlyRect = !pl.getBooleanParameter("Rno_rect"); - - // Parse the ROIs - parseROIs(roiopt, src.NumComps, roiVector); - ROI[] roiArray = new ROI[roiVector.Count]; - roiVector.CopyTo(roiArray); - - // If onlyRect has been forced, check if there are any non-rectangular - // ROIs specified. Currently, only the presence of circular ROIs will - // make this false - if (onlyRect) - { - for (int i = roiArray.Length - 1; i >= 0; i--) - if (!roiArray[i].rect) - { - onlyRect = false; - break; - } - } - - if (onlyRect) - { - // It's possible to use the fast ROI mask generation when only - // rectangular ROIs are specified. - maskGen = new RectROIMaskGenerator(roiArray, src.NumComps); - } - else - { - // It's necessary to use the generic mask generation - maskGen = new ArbROIMaskGenerator(roiArray, src.NumComps, src); - } - return new ROIScaler(src, maskGen, true, sLev, useBlockAligned, encSpec); - } - - /// This function parses the values given for the ROIs with the argument - /// -Rroi. Currently only circular and rectangular ROIs are supported. - /// - ///

    A rectangular ROI is indicated by a 'R' followed the coordinates for - /// the upper left corner of the ROI and then its width and height.

    - /// - ///

    A circular ROI is indicated by a 'C' followed by the coordinates of - /// the circle center and then the radius.

    - /// - ///

    Before the R and C values, the component that are affected by the - /// ROI are indicated.

    - /// - ///
    - /// The info on the ROIs - /// - /// - /// number of components - /// - /// - /// The vcector containing the ROI parsed from the cmd line - /// - /// - /// The ROIs specified in roiopt - /// - /// - protected internal static System.Collections.ArrayList parseROIs(System.String roiopt, int nc, System.Collections.ArrayList roiVector) - { - //ROI[] ROIs; - ROI roi; - SupportClass.Tokenizer stok; - //char tok; - int nrOfROIs = 0; - //char c; - int ulx, uly, w, h, x, y, rad; // comp removed - bool[] roiInComp = null; - - stok = new SupportClass.Tokenizer(roiopt); - - System.String word; - while (stok.HasMoreTokens()) - { - word = stok.NextToken(); - - switch (word[0]) - { - - case 'c': // Components specification - roiInComp = ModuleSpec.parseIdx(word, nc); - break; - - case 'R': // Rectangular ROI to be read - nrOfROIs++; - try - { - word = stok.NextToken(); - ulx = (System.Int32.Parse(word)); - word = stok.NextToken(); - uly = (System.Int32.Parse(word)); - word = stok.NextToken(); - w = (System.Int32.Parse(word)); - word = stok.NextToken(); - h = (System.Int32.Parse(word)); - } - catch (System.FormatException) - { - throw new System.ArgumentException("Bad parameter for " + "'-Rroi R' option : " + word); - } - catch (System.ArgumentOutOfRangeException) - { - throw new System.ArgumentException("Wrong number of " + "parameters for " + "h'-Rroi R' option."); - } - - // If the ROI is component-specific, check which comps. - if (roiInComp != null) - for (int i = 0; i < nc; i++) - { - if (roiInComp[i]) - { - roi = new ROI(i, ulx, uly, w, h); - roiVector.Add(roi); - } - } - else - { - // Otherwise add ROI for all components - for (int i = 0; i < nc; i++) - { - roi = new ROI(i, ulx, uly, w, h); - roiVector.Add(roi); - } - } - break; - - case 'C': // Circular ROI to be read - nrOfROIs++; - - try - { - word = stok.NextToken(); - x = (System.Int32.Parse(word)); - word = stok.NextToken(); - y = (System.Int32.Parse(word)); - word = stok.NextToken(); - rad = (System.Int32.Parse(word)); - } - catch (System.FormatException) - { - throw new System.ArgumentException("Bad parameter for " + "'-Rroi C' option : " + word); - } - catch (System.ArgumentOutOfRangeException) - { - throw new System.ArgumentException("Wrong number of " + "parameters for " + "'-Rroi C' option."); - } - - // If the ROI is component-specific, check which comps. - if (roiInComp != null) - for (int i = 0; i < nc; i++) - { - if (roiInComp[i]) - { - roi = new ROI(i, x, y, rad); - roiVector.Add(roi); - } - } - else - { - // Otherwise add ROI for all components - for (int i = 0; i < nc; i++) - { - roi = new ROI(i, x, y, rad); - roiVector.Add(roi); - } - } - break; - - case 'A': // ROI wth arbitrary shape - nrOfROIs++; - - System.String filename; - ImgReaderPGM maskPGM = null; - - try - { - filename = stok.NextToken(); - } - catch (System.ArgumentOutOfRangeException) - { - throw new System.ArgumentException("Wrong number of " + "parameters for " + "'-Rroi A' option."); - } - try - { - maskPGM = new ImgReaderPGM(filename); - } - catch (System.IO.IOException) - { - throw new System.ApplicationException("Cannot read PGM file with ROI"); - } - - // If the ROI is component-specific, check which comps. - if (roiInComp != null) - for (int i = 0; i < nc; i++) - { - if (roiInComp[i]) - { - roi = new ROI(i, maskPGM); - roiVector.Add(roi); - } - } - else - { - // Otherwise add ROI for all components - for (int i = 0; i < nc; i++) - { - roi = new ROI(i, maskPGM); - roiVector.Add(roi); - } - } - break; - - default: - throw new System.ApplicationException("Bad parameters for ROI nr " + roiVector.Count); - - } - } - - return roiVector; - } - - /// This function gets a datablk from the entropy coder. The sample sin the - /// block, which consists of the quantized coefficients from the quantizer, - /// are scaled by the values given for any ROIs specified. - /// - ///

    The function calls on a ROIMaskGenerator to get the mask for scaling - /// the coefficients in the current block.

    - /// - ///

    The data returned by this method is a copy of the orignal - /// data. Therfore it can be modified "in place" without any problems after - /// being returned. The 'offset' of the returned data is 0, and the 'scanw' - /// is the same as the code-block width. See the 'CBlkWTData' class.

    - /// - ///
    - /// The component for which to return the next code-block. - /// - /// - /// If non-null this object will be used to return the new - /// code-block. If null a new one will be allocated and returned. If the - /// "data" array of the object is non-null it will be reused, if possible, - /// to return the data. - /// - /// - /// The next code-block in the current tile for component 'n', or - /// null if all code-blocks for the current tile have been returned. - /// - /// - /// - /// - /// - public virtual CBlkWTData getNextCodeBlock(int c, CBlkWTData cblk) - { - return getNextInternCodeBlock(c, cblk); - } - - /// This function gets a datablk from the entropy coder. The sample sin the - /// block, which consists of the quantized coefficients from the quantizer, - /// are scaled by the values given for any ROIs specified. - /// - ///

    The function calls on a ROIMaskGenerator to get the mask for scaling - /// the coefficients in the current block.

    - /// - ///
    - /// The component for which to return the next code-block. - /// - /// - /// If non-null this object will be used to return the new - /// code-block. If null a new one will be allocated and returned. If the - /// "data" array of the object is non-null it will be reused, if possible, - /// to return the data. - /// - /// - /// The next code-block in the current tile for component 'n', or - /// null if all code-blocks for the current tile have been returned. - /// - /// - /// - /// - /// - public virtual CBlkWTData getNextInternCodeBlock(int c, CBlkWTData cblk) - { - int mi, i, j, k, wrap; - int ulx, uly, w, h; - DataBlkInt mask = roiMask; // local copy of mask - int[] maskData; // local copy of mask data - int[] data; // local copy of quantized data - int tmp; - int bitMask = 0x7FFFFFFF; - SubbandAn root, sb; - int maxBits = 0; // local copy - bool roiInTile; - bool sbInMask; - int nROIcoeff = 0; - - // Get codeblock's data from quantizer - cblk = src.getNextCodeBlock(c, cblk); - - // If there is no ROI in the image, or if we already got all - // code-blocks - if (!roi || cblk == null) - { - return cblk; - } - - data = (int[])cblk.Data; - sb = cblk.sb; - ulx = cblk.ulx; - uly = cblk.uly; - w = cblk.w; - h = cblk.h; - sbInMask = (sb.resLvl <= useStartLevel); - - // Check that there is an array for the mask and set it to zero - maskData = mask.DataInt; // local copy of mask data - if (maskData == null || w * h > maskData.Length) - { - maskData = new int[w * h]; - mask.DataInt = maskData; - } - else - { - for (i = w * h - 1; i >= 0; i--) - maskData[i] = 0; - } - mask.ulx = ulx; - mask.uly = uly; - mask.w = w; - mask.h = h; - - // Get ROI mask from generator - root = src.getAnSubbandTree(tIdx, c); - maxBits = maxMagBits[tIdx][c]; - roiInTile = mg.getROIMask(mask, root, maxBits, c); - - // If there is no ROI in this tile, return the code-block untouched - if (!roiInTile && (!sbInMask)) - { - cblk.nROIbp = 0; - return cblk; - } - - // Update field containing the number of ROI magnitude bit-planes - cblk.nROIbp = cblk.magbits; - - // If the entire subband belongs to the ROI mask, The code-block is - // set to belong entirely to the ROI with the highest scaling value - if (sbInMask) - { - // Scale the wmse so that instead of scaling the coefficients, the - // wmse is scaled. - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - cblk.wmseScaling *= (float)(1 << (maxBits << 1)); - cblk.nROIcoeff = w * h; - return cblk; - } - - // In 'block aligned' mode, the code-block is set to belong entirely - // to the ROI with the highest scaling value if one coefficient, at - // least, belongs to the ROI - if (blockAligned) - { - wrap = cblk.scanw - w; - mi = h * w - 1; - i = cblk.offset + cblk.scanw * (h - 1) + w - 1; - int nroicoeff = 0; - for (j = h; j > 0; j--) - { - for (k = w - 1; k >= 0; k--, i--, mi--) - { - if (maskData[mi] != 0) - { - nroicoeff++; - } - } - i -= wrap; - } - if (nroicoeff != 0) - { - // Include the subband - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - cblk.wmseScaling *= (float)(1 << (maxBits << 1)); - cblk.nROIcoeff = w * h; - } - return cblk; - } - - // Scale background coefficients - bitMask = (((1 << cblk.magbits) - 1) << (31 - cblk.magbits)); - wrap = cblk.scanw - w; - mi = h * w - 1; - i = cblk.offset + cblk.scanw * (h - 1) + w - 1; - for (j = h; j > 0; j--) - { - for (k = w; k > 0; k--, i--, mi--) - { - tmp = data[i]; - if (maskData[mi] != 0) - { - // ROI coeff. We need to erase fractional bits to ensure - // that they do not conflict with BG coeffs. This is only - // strictly necessary for ROI coeffs. which non-fractional - // magnitude is zero, but much better BG quality can be - // achieved if done if reset to zero since coding zeros is - // much more efficient (the entropy coder knows nothing - // about ROI and cannot avoid coding the ROI fractional - // bits, otherwise this would not be necessary). - data[i] = (unchecked((int)0x80000000) & tmp) | (tmp & bitMask); - nROIcoeff++; - } - else - { - // BG coeff. it is not necessary to erase fractional bits - data[i] = (unchecked((int)0x80000000) & tmp) | ((tmp & 0x7FFFFFFF) >> maxBits); - } - } - i -= wrap; - } - - // Modify the number of significant bit-planes in the code-block - cblk.magbits += maxBits; - - // Store the number of ROI coefficients present in the code-block - cblk.nROIcoeff = nROIcoeff; - - return cblk; - } - - /// This function returns the flag indicating if any ROI functionality used - /// - /// - /// Flag indicating whether there are ROIs in the image - /// - public virtual bool useRoi() - { - return roi; - } - - /// Changes the current tile, given the new indexes. An - /// IllegalArgumentException is thrown if the indexes do not - /// correspond to a valid tile. - /// - /// - /// The horizontal index of the tile. - /// - /// - /// The vertical index of the new tile. - /// - /// - public override void setTile(int x, int y) - { - base.setTile(x, y); - if (roi) - mg.tileChanged(); - } - - /// Advances to the next tile, in standard scan-line order (by rows then - /// columns). An NoNextElementException is thrown if the current tile is - /// the last one (i.e. there is no next tile). - /// - /// - public override void nextTile() - { - base.nextTile(); - if (roi) - mg.tileChanged(); - } - - /// Calculates the maximum amount of magnitude bits for each - /// tile-component, and stores it in the 'maxMagBits' array. This is called - /// by the constructor - /// - /// - /// The encoder specifications for addition of roi specs - /// - /// - private void calcMaxMagBits(EncoderSpecs encSpec) - { - int tmp; - MaxShiftSpec rois = encSpec.rois; - - int nt = src.getNumTiles(); - int nc = src.NumComps; - - maxMagBits = new int[nt][]; - for (int i = 0; i < nt; i++) - { - maxMagBits[i] = new int[nc]; - } - - src.setTile(0, 0); - for (int t = 0; t < nt; t++) - { - for (int c = nc - 1; c >= 0; c--) - { - tmp = src.getMaxMagBits(c); - maxMagBits[t][c] = tmp; - rois.setTileCompVal(t, c, (System.Object)tmp); - } - if (t < nt - 1) - src.nextTile(); - } - // Reset to current initial tile position - src.setTile(0, 0); - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/roi/encoder/RectROIMaskGenerator.cs b/CSJ2K/j2k/roi/encoder/RectROIMaskGenerator.cs deleted file mode 100644 index 7e254113..00000000 --- a/CSJ2K/j2k/roi/encoder/RectROIMaskGenerator.cs +++ /dev/null @@ -1,325 +0,0 @@ -/* -* CVS identifier: -* -* $Id: RectROIMaskGenerator.java,v 1.4 2001/02/28 15:33:44 grosbois Exp $ -* -* Class: RectROIMaskGenerator -* -* Description: Generates masks when only rectangular ROIs exist -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.image; -using CSJ2K.j2k.wavelet; -namespace CSJ2K.j2k.roi.encoder -{ - - /// This class generates the ROI masks when there are only rectangular ROIs in - /// the image. The ROI mask generation can then be simplified by only - /// calculating the boundaries of the ROI mask in the particular subbands - /// - ///

    The values are calculated from the scaling factors of the ROIs. The - /// values with which to scale are equal to u-umin where umin is the lowest - /// scaling factor within the block. The umin value is sent to the entropy - /// coder to be used for scaling the distortion values. - /// - ///

    To generate and to store the boundaries of the ROIs, the class - /// SubbandRectROIMask is used. There is one tree of SubbandMasks for each - /// component. - /// - ///

    - /// - /// - /// - /// - /// - /// - /// - /// - /// - public class RectROIMaskGenerator : ROIMaskGenerator - { - - /// The upper left xs of the ROIs - private int[] ulxs; - - /// The upper left ys of the ROIs - private int[] ulys; - - /// The lower right xs of the ROIs - private int[] lrxs; - - /// The lower right ys of the ROIs - private int[] lrys; - - /// Number of ROIs - private int[] nrROIs; - - /// The tree of subbandmask. One for each component - private SubbandRectROIMask[] sMasks; - - - /// The constructor of the mask generator. The constructor is called with - /// the ROI data. This data is stored in arrays that are used to generate - /// the SubbandRectROIMask trees for each component. - /// - /// - /// The ROI info. - /// - /// - /// The flag indicating use of Maxshift method. - /// - /// - /// number of components. - /// - /// - public RectROIMaskGenerator(ROI[] ROIs, int nrc) : base(ROIs, nrc) - { - int nr = ROIs.Length; - int r; // c removed - nrROIs = new int[nrc]; - sMasks = new SubbandRectROIMask[nrc]; - - // Count number of ROIs per component - for (r = nr - 1; r >= 0; r--) - { - nrROIs[ROIs[r].comp]++; - } - } - - - /// This functions gets a DataBlk the size of the current code-block and - /// fills this block with the ROI mask. - /// - ///

    In order to get the mask for a particular Subband, the subband tree - /// is traversed and at each decomposition, the ROI masks are computed. The - /// roi bondaries for each subband are stored in the SubbandRectROIMask - /// tree. - /// - ///

    - /// The data block that is to be filled with the mask - /// - /// - /// The root of the subband tree to which db belongs - /// - /// - /// The max number of magnitude bits in any code-block - /// - /// - /// The component for which to get the mask - /// - /// - /// Whether or not a mask was needed for this tile - /// - /// - public override bool getROIMask(DataBlkInt db, Subband sb, int magbits, int c) - { - int x = db.ulx; - int y = db.uly; - int w = db.w; - int h = db.h; - int[] mask = db.DataInt; - int i, j, k, r, maxk, maxj; // mink, minj removed - int ulx = 0, uly = 0, lrx = 0, lry = 0; - int wrap; - int maxROI; - int[] culxs; - int[] culys; - int[] clrxs; - int[] clrys; - SubbandRectROIMask srm; - - // If the ROI bounds have not been calculated for this tile and - // component, do so now. - if (!tileMaskMade[c]) - { - makeMask(sb, magbits, c); - tileMaskMade[c] = true; - } - - if (!roiInTile) - { - return false; - } - - // Find relevant subband mask and get ROI bounds - srm = (SubbandRectROIMask)sMasks[c].getSubbandRectROIMask(x, y); - culxs = srm.ulxs; - culys = srm.ulys; - clrxs = srm.lrxs; - clrys = srm.lrys; - maxROI = culxs.Length - 1; - // Make sure that only parts of ROIs within the code-block are used - // and make the bounds local to this block the LR bounds are counted - // as the distance from the lower right corner of the block - x -= srm.ulx; - y -= srm.uly; - for (r = maxROI; r >= 0; r--) - { - ulx = culxs[r] - x; - if (ulx < 0) - { - ulx = 0; - } - else if (ulx >= w) - { - ulx = w; - } - - uly = culys[r] - y; - if (uly < 0) - { - uly = 0; - } - else if (uly >= h) - { - uly = h; - } - - lrx = clrxs[r] - x; - if (lrx < 0) - { - lrx = -1; - } - else if (lrx >= w) - { - lrx = w - 1; - } - - lry = clrys[r] - y; - if (lry < 0) - { - lry = -1; - } - else if (lry >= h) - { - lry = h - 1; - } - - // Add the masks of the ROI - i = w * lry + lrx; - maxj = (lrx - ulx); - wrap = w - maxj - 1; - maxk = lry - uly; - - for (k = maxk; k >= 0; k--) - { - for (j = maxj; j >= 0; j--, i--) - mask[i] = magbits; - i -= wrap; - } - } - return true; - } - - /// This function returns the relevant data of the mask generator - /// - /// - public override System.String ToString() - { - return ("Fast rectangular ROI mask generator"); - } - - /// This function generates the ROI mask for the entire tile. The mask is - /// generated for one component. This method is called once for each tile - /// and component. - /// - /// - /// The root of the subband tree used in the decomposition - /// - /// - /// component number - /// - /// - public override void makeMask(Subband sb, int magbits, int n) - { - int nr = nrROIs[n]; - int r; - int ulx, uly, lrx, lry; - int tileulx = sb.ulcx; - int tileuly = sb.ulcy; - int tilew = sb.w; - int tileh = sb.h; - ROI[] ROIs = roi_array; // local copy - - ulxs = new int[nr]; - ulys = new int[nr]; - lrxs = new int[nr]; - lrys = new int[nr]; - - nr = 0; - - for (r = ROIs.Length - 1; r >= 0; r--) - { - if (ROIs[r].comp == n) - { - ulx = ROIs[r].ulx; - uly = ROIs[r].uly; - lrx = ROIs[r].w + ulx - 1; - lry = ROIs[r].h + uly - 1; - - if (ulx > (tileulx + tilew - 1) || uly > (tileuly + tileh - 1) || lrx < tileulx || lry < tileuly) - // no part of ROI in tile - continue; - - // Check bounds - ulx -= tileulx; - lrx -= tileulx; - uly -= tileuly; - lry -= tileuly; - - ulx = (ulx < 0) ? 0 : ulx; - uly = (uly < 0) ? 0 : uly; - lrx = (lrx > (tilew - 1)) ? tilew - 1 : lrx; - lry = (lry > (tileh - 1)) ? tileh - 1 : lry; - - ulxs[nr] = ulx; - ulys[nr] = uly; - lrxs[nr] = lrx; - lrys[nr] = lry; - nr++; - } - } - if (nr == 0) - { - roiInTile = false; - } - else - { - roiInTile = true; - } - sMasks[n] = new SubbandRectROIMask(sb, ulxs, ulys, lrxs, lrys, nr); - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/roi/encoder/SubbandROIMask.cs b/CSJ2K/j2k/roi/encoder/SubbandROIMask.cs deleted file mode 100644 index 619d1866..00000000 --- a/CSJ2K/j2k/roi/encoder/SubbandROIMask.cs +++ /dev/null @@ -1,164 +0,0 @@ -/* -* CVS identifier: -* -* $Id: SubbandROIMask.java,v 1.2 2001/02/28 15:12:44 grosbois Exp $ -* -* Class: ROI -* -* Description: This class describes the ROI mask for a subband -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -namespace CSJ2K.j2k.roi.encoder -{ - - /// This abstract class describes the ROI mask for a single subband. Each - /// object of the class contains the mask for a particular subband and also has - /// references to the masks of the children subbands of the subband - /// corresponding to this mask. - /// - public abstract class SubbandROIMask - { - - /// The subband masks of the child LL - protected internal SubbandROIMask ll; - - /// The subband masks of the child LH - protected internal SubbandROIMask lh; - - /// The subband masks of the child HL - protected internal SubbandROIMask hl; - - /// The subband masks of the child HH - protected internal SubbandROIMask hh; - - /// Flag indicating whether this subband mask is a node or not - protected internal bool isNode; - - /// Horizontal uper-left coordinate of the subband mask - public int ulx; - - /// Vertical uper-left coordinate of the subband mask - public int uly; - - /// Width of the subband mask - public int w; - - /// Height of the subband mask - public int h; - - /// The constructor of the SubbandROIMask takes the dimensions of the - /// subband as parameters - /// - /// - /// The upper left x coordinate of corresponding subband - /// - /// - /// The upper left y coordinate of corresponding subband - /// - /// - /// The width of corresponding subband - /// - /// - /// The height of corresponding subband - /// - /// - public SubbandROIMask(int ulx, int uly, int w, int h) - { - this.ulx = ulx; - this.uly = uly; - this.w = w; - this.h = h; - } - - /// Returns a reference to the Subband mask element to which the specified - /// point belongs. The specified point must be inside this (i.e. the one - /// defined by this object) subband mask. This method searches through the - /// tree. - /// - /// - /// horizontal coordinate of the specified point. - /// - /// - /// horizontal coordinate of the specified point. - /// - /// - public virtual SubbandROIMask getSubbandRectROIMask(int x, int y) - { - SubbandROIMask cur, hhs; - - // Check that we are inside this subband - if (x < ulx || y < uly || x >= ulx + w || y >= uly + h) - { - throw new System.ArgumentException(); - } - - cur = this; - while (cur.isNode) - { - hhs = cur.hh; - // While we are still at a node -> continue - if (x < hhs.ulx) - { - // Is the result of horizontal low-pass - if (y < hhs.uly) - { - // Vertical low-pass - cur = cur.ll; - } - else - { - // Vertical high-pass - cur = cur.lh; - } - } - else - { - // Is the result of horizontal high-pass - if (y < hhs.uly) - { - // Vertical low-pass - cur = cur.hl; - } - else - { - // Vertical high-pass - cur = cur.hh; - } - } - } - return cur; - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/roi/encoder/SubbandRectROIMask.cs b/CSJ2K/j2k/roi/encoder/SubbandRectROIMask.cs deleted file mode 100644 index 02f81f62..00000000 --- a/CSJ2K/j2k/roi/encoder/SubbandRectROIMask.cs +++ /dev/null @@ -1,192 +0,0 @@ -/* -* CVS identifier: -* -* $Id: SubbandRectROIMask.java,v 1.3 2001/02/28 14:53:12 grosbois Exp $ -* -* Class: ROI -* -* Description: This class describes the ROI mask for a subband -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.wavelet; -namespace CSJ2K.j2k.roi.encoder -{ - - /// This class describes the ROI mask for a single subband. Each object of the - /// class contains the mask for a particular subband and also has references to - /// the masks of the children subbands of the subband corresponding to this - /// mask. This class describes subband masks for images containing only - /// rectangular ROIS - /// - /// - public class SubbandRectROIMask : SubbandROIMask - { - - /// The upper left x coordinates of the applicable ROIs - public int[] ulxs; - - /// The upper left y coordinates of the applicable ROIs - public int[] ulys; - - /// The lower right x coordinates of the applicable ROIs - public int[] lrxs; - - /// The lower right y coordinates of the applicable ROIs - public int[] lrys; - - /// The constructor of the SubbandROIMask takes the dimensions of the - /// subband as parameters. A tree of masks is generated from the subband - /// sb. Each Subband contains the boundaries of each ROI. - /// - /// - /// The subband corresponding to this Subband Mask - /// - /// - /// The upper left x coordinates of the ROIs - /// - /// - /// The upper left y coordinates of the ROIs - /// - /// - /// The lower right x coordinates of the ROIs - /// - /// - /// The lower right y coordinates of the ROIs - /// - /// - /// The lower right y coordinates of the ROIs - /// - /// - /// Number of ROIs that affect this tile - /// - /// - public SubbandRectROIMask(Subband sb, int[] ulxs, int[] ulys, int[] lrxs, int[] lrys, int nr) : base(sb.ulx, sb.uly, sb.w, sb.h) - { - this.ulxs = ulxs; - this.ulys = ulys; - this.lrxs = lrxs; - this.lrys = lrys; - int r; - - if (sb.isNode) - { - isNode = true; - // determine odd/even - high/low filters - int horEvenLow = sb.ulcx % 2; - int verEvenLow = sb.ulcy % 2; - - // Get filter support lengths - WaveletFilter hFilter = sb.HorWFilter; - WaveletFilter vFilter = sb.VerWFilter; - int hlnSup = hFilter.SynLowNegSupport; - int hhnSup = hFilter.SynHighNegSupport; - int hlpSup = hFilter.SynLowPosSupport; - int hhpSup = hFilter.SynHighPosSupport; - int vlnSup = vFilter.SynLowNegSupport; - int vhnSup = vFilter.SynHighNegSupport; - int vlpSup = vFilter.SynLowPosSupport; - int vhpSup = vFilter.SynHighPosSupport; - - // Generate arrays for children - int x, y; - int[] lulxs = new int[nr]; - int[] lulys = new int[nr]; - int[] llrxs = new int[nr]; - int[] llrys = new int[nr]; - int[] hulxs = new int[nr]; - int[] hulys = new int[nr]; - int[] hlrxs = new int[nr]; - int[] hlrys = new int[nr]; - for (r = nr - 1; r >= 0; r--) - { - // For all ROI calculate ... - // Upper left x for all children - x = ulxs[r]; - if (horEvenLow == 0) - { - lulxs[r] = (x + 1 - hlnSup) / 2; - hulxs[r] = (x - hhnSup) / 2; - } - else - { - lulxs[r] = (x - hlnSup) / 2; - hulxs[r] = (x + 1 - hhnSup) / 2; - } - // Upper left y for all children - y = ulys[r]; - if (verEvenLow == 0) - { - lulys[r] = (y + 1 - vlnSup) / 2; - hulys[r] = (y - vhnSup) / 2; - } - else - { - lulys[r] = (y - vlnSup) / 2; - hulys[r] = (y + 1 - vhnSup) / 2; - } - // lower right x for all children - x = lrxs[r]; - if (horEvenLow == 0) - { - llrxs[r] = (x + hlpSup) / 2; - hlrxs[r] = (x - 1 + hhpSup) / 2; - } - else - { - llrxs[r] = (x - 1 + hlpSup) / 2; - hlrxs[r] = (x + hhpSup) / 2; - } - // lower right y for all children - y = lrys[r]; - if (verEvenLow == 0) - { - llrys[r] = (y + vlpSup) / 2; - hlrys[r] = (y - 1 + vhpSup) / 2; - } - else - { - llrys[r] = (y - 1 + vlpSup) / 2; - hlrys[r] = (y + vhpSup) / 2; - } - } - // Create children - hh = new SubbandRectROIMask(sb.HH, hulxs, hulys, hlrxs, hlrys, nr); - lh = new SubbandRectROIMask(sb.LH, lulxs, hulys, llrxs, hlrys, nr); - hl = new SubbandRectROIMask(sb.HL, hulxs, lulys, hlrxs, llrys, nr); - ll = new SubbandRectROIMask(sb.LL, lulxs, lulys, llrxs, llrys, nr); - } - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/util/ArrayUtil.cs b/CSJ2K/j2k/util/ArrayUtil.cs deleted file mode 100644 index 1ce3cc59..00000000 --- a/CSJ2K/j2k/util/ArrayUtil.cs +++ /dev/null @@ -1,168 +0,0 @@ -/* -* CVS identifier: -* -* $Id: ArrayUtil.java,v 1.10 2000/09/05 09:25:15 grosbois Exp $ -* -* Class: ArrayUtil -* -* Description: Utillities for arrays. -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* -* -* -*/ -using System; -namespace CSJ2K.j2k.util -{ - - /// This class contains a colleaction of utility static methods for arrays. - /// - /// - public class ArrayUtil - { - - /// The maximum array size to do element by element copying, larger - /// arrays are copyied in a n optimized way. - /// - public const int MAX_EL_COPYING = 8; - - /// The number of elements to copy initially in an optimized array copy - public const int INIT_EL_COPYING = 4; - - /// Reinitializes an int array to the given value in an optimized way. If - /// the length of the array is less than MAX_EL_COPYING, then the array - /// is set element by element in the normal way, otherwise the first - /// INIT_EL_COPYING elements are set element by element and then - /// System.arraycopy is used to set the other parts of the array. - /// - /// - /// The array to set. - /// - /// - /// The value to set the array to. - /// - /// - /// - /// - public static void intArraySet(int[] arr, int val) - { - int i, len, len2; - - len = arr.Length; - // Set array to 'val' in an optimized way - if (len < MAX_EL_COPYING) - { - // Not worth doing optimized way - for (i = len - 1; i >= 0; i--) - { - // Set elements - arr[i] = val; - } - } - else - { - // Do in optimized way - len2 = len >> 1; - for (i = 0; i < INIT_EL_COPYING; i++) - { - // Set first elements - arr[i] = val; - } - for (; i <= len2; i <<= 1) - { - // Copy values doubling size each time - Array.Copy(arr, 0, arr, i, i); - } - if (i < len) - { - // Copy values to end - Array.Copy(arr, 0, arr, i, len - i); - } - } - } - - /// Reinitializes a byte array to the given value in an optimized way. If - /// the length of the array is less than MAX_EL_COPYING, then the array - /// is set element by element in the normal way, otherwise the first - /// INIT_EL_COPYING elements are set element by element and then - /// System.arraycopy is used to set the other parts of the array. - /// - /// - /// The array to set. - /// - /// - /// The value to set the array to. - /// - /// - /// - /// - public static void byteArraySet(byte[] arr, byte val) - { - int i, len, len2; - - len = arr.Length; - // Set array to 'val' in an optimized way - if (len < MAX_EL_COPYING) - { - // Not worth doing optimized way - for (i = len - 1; i >= 0; i--) - { - // Set elements - arr[i] = val; - } - } - else - { - // Do in optimized way - len2 = len >> 1; - for (i = 0; i < INIT_EL_COPYING; i++) - { - // Set first elements - arr[i] = val; - } - for (; i <= len2; i <<= 1) - { - // Copy values doubling size each time - Array.Copy(arr, 0, arr, i, i); - } - if (i < len) - { - // Copy values to end - Array.Copy(arr, 0, arr, i, len - i); - } - } - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/util/CodestreamManipulator.cs b/CSJ2K/j2k/util/CodestreamManipulator.cs deleted file mode 100644 index 358f7610..00000000 --- a/CSJ2K/j2k/util/CodestreamManipulator.cs +++ /dev/null @@ -1,763 +0,0 @@ -/* -* CVS identifier: -* -* $Id: CodestreamManipulator.java,v 1.17 2001/05/16 13:58:09 qtxjoas Exp $ -* -* Class: CodestreamManipulator -* -* Description: Manipulates codestream to create tile-parts etc -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.io; -namespace CSJ2K.j2k.util -{ - - /// This class takes a legal JPEG 2000 codestream and performs some - /// manipulation on it. Currently the manipulations supported are: Tile-parts - /// - /// - public class CodestreamManipulator - { - private void InitBlock() - { - ppt = new int[nt]; - } - - /// Flag indicating whether packed packet headers in main header is used - /// - /// - private bool ppmUsed; - - /// Flag indicating whether packed packet headers in tile headers is used - /// - /// - private bool pptUsed; - - /// Flag indicating whether SOP marker was only intended for parsing in - /// This class and should be removed - /// - private bool tempSop; - - /// Flag indicating whether EPH marker was only intended for parsing in - /// This class and should be removed - /// - private bool tempEph; - - /// The number of tiles in the image - private int nt; - - /// The number of packets per tile-part - private int pptp; - - /// The name of the outfile - private System.String outname; - - /// The length of a SOT plus a SOD marker - private static int TP_HEAD_LEN = 14; - - /// The maximum number of a tile part index (TPsot) - //private static int MAX_TPSOT = 16; - - /// The maximum number of tile parts in any tile - private int maxtp; - - /// The number of packets per tile - //UPGRADE_NOTE: The initialization of 'ppt' was moved to method 'InitBlock'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1005'" - private int[] ppt; - - /// The positions of the SOT, SOP and EPH markers - private System.Int32[] positions; - - /// The main header - private byte[] mainHeader; - - /// Buffers containing the tile parts - private byte[][][] tileParts; - - /// Buffers containing the original tile headers - private byte[][] tileHeaders; - - /// Buffers contaning the packet headers - private byte[][][] packetHeaders; - - /// Buffers containing the packet data - private byte[][][] packetData; - - /// Buffers containing the SOP marker segments - private byte[][][] sopMarkSeg; - - /// Instantiates a codestream manipulator.. - /// - /// - /// The name of the original outfile - /// - /// - /// The number of tiles in the image - /// - /// - /// Packets per tile-part. If zero, no division into tileparts - /// is performed - /// - /// - /// Flag indicating that PPM marker is used - /// - /// - /// Flag indicating that PPT marker is used - /// - /// - /// Flag indicating whether SOP merker should be removed - /// - /// - /// Flag indicating whether EPH merker should be removed - /// - /// - public CodestreamManipulator(System.String outname, int nt, int pptp, bool ppm, bool ppt, bool tempSop, bool tempEph) - { - InitBlock(); - this.outname = outname; - this.nt = nt; - this.pptp = pptp; - this.ppmUsed = ppm; - this.pptUsed = ppt; - this.tempSop = tempSop; - this.tempEph = tempEph; - } - - /// This method performs the actual manipulation of the codestream which is - /// the reparsing for tile parts and packed packet headers - /// - /// - /// The number of bytes that the file has increased by - /// - /// - /// If an I/O error ocurred. - /// - /// - public virtual int doCodestreamManipulation() - { - BEBufferedRandomAccessFile fi; - int addedHeaderBytes = 0; - ppt = new int[nt]; - tileParts = new byte[nt][][]; - tileHeaders = new byte[nt][]; - packetHeaders = new byte[nt][][]; - packetData = new byte[nt][][]; - sopMarkSeg = new byte[nt][][]; - - // If neither packed packet header nor tile parts are used, return 0 - if (ppmUsed == false && pptUsed == false && pptp == 0) - return 0; - - // Open file for reading and writing - fi = new BEBufferedRandomAccessFile(outname, "rw+"); - addedHeaderBytes -= fi.length(); - - // Parse the codestream for SOT, SOP and EPH markers - parseAndFind(fi); - - // Read and buffer the tile headers, packet headers and packet data - readAndBuffer(fi); - - // Close file and overwrite with new file - fi.close(); - fi = new BEBufferedRandomAccessFile(outname, "rw"); - - // Create tile-parts - createTileParts(); - - // Write new codestream - writeNewCodestream(fi); - - // Close file - fi.flush(); - addedHeaderBytes += fi.length(); - fi.close(); - - return addedHeaderBytes; - } - - /// This method parses the codestream for SOT, SOP and EPH markers and - /// removes header header bits signalling SOP and EPH markers if packed - /// packet headers are used - /// - /// - /// The file to parse the markers from - /// - /// - /// If an I/O error ocurred. - /// - /// - private void parseAndFind(BufferedRandomAccessFile fi) - { - int length, pos, i, t, sop = 0, eph = 0; - short marker; - int halfMarker; - int tileEnd; - System.Collections.ArrayList markPos = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); - - // Find position of first SOT marker - marker = (short)fi.readUnsignedShort(); // read SOC marker - marker = (short)fi.readUnsignedShort(); - while (marker != CSJ2K.j2k.codestream.Markers.SOT) - { - pos = fi.Pos; - length = fi.readUnsignedShort(); - - // If SOP and EPH markers were only used for parsing in this - // class remove SOP and EPH markers from Scod field - if (marker == CSJ2K.j2k.codestream.Markers.COD) - { - int scod = fi.readUnsignedByte(); - if (tempSop) - scod &= 0xfd; // Remove bits indicating SOP - if (tempEph) - scod &= 0xfb; // Remove bits indicating SOP - fi.seek(pos + 2); - fi.write(scod); - } - - fi.seek(pos + length); - marker = (short)fi.readUnsignedShort(); - } - pos = fi.Pos; - fi.seek(pos - 2); - - // Find all packet headers, packed data and tile headers - for (t = 0; t < nt; t++) - { - // Read SOT marker - fi.readUnsignedShort(); // Skip SOT - pos = fi.Pos; - markPos.Add((System.Int32)fi.Pos); - fi.readInt(); // Skip Lsot and Isot - length = fi.readInt(); // Read Psot - fi.readUnsignedShort(); // Skip TPsot & TNsot - tileEnd = pos + length - 2; // Last byte of tile - - // Find position of SOD marker - marker = (short)fi.readUnsignedShort(); - while (marker != CSJ2K.j2k.codestream.Markers.SOD) - { - pos = fi.Pos; - length = fi.readUnsignedShort(); - - // If SOP and EPH markers were only used for parsing in this - // class remove SOP and EPH markers from Scod field - if (marker == CSJ2K.j2k.codestream.Markers.COD) - { - int scod = fi.readUnsignedByte(); - if (tempSop) - scod &= 0xfd; // Remove bits indicating SOP - if (tempEph) - scod &= 0xfb; // Remove bits indicating SOP - fi.seek(pos + 2); - fi.write(scod); - } - fi.seek(pos + length); - marker = (short)fi.readUnsignedShort(); - } - - // Find all SOP and EPH markers in tile - sop = 0; - eph = 0; - - i = fi.Pos; - while (i < tileEnd) - { - halfMarker = (short)fi.readUnsignedByte(); - if (halfMarker == (short)0xff) - { - marker = (short)((halfMarker << 8) + fi.readUnsignedByte()); - i++; - if (marker == CSJ2K.j2k.codestream.Markers.SOP) - { - markPos.Add((System.Int32)fi.Pos); - ppt[t]++; - sop++; - fi.skipBytes(4); - i += 4; - } - - if (marker == CSJ2K.j2k.codestream.Markers.EPH) - { - markPos.Add((System.Int32)fi.Pos); - eph++; - } - } - i++; - } - } - markPos.Add((System.Int32)(fi.Pos + 2)); - positions = new System.Int32[markPos.Count]; - markPos.CopyTo(positions); - } - - /// This method reads and buffers the tile headers, packet headers and - /// packet data. - /// - /// - /// The file to read the headers and data from - /// - /// - /// If an I/O error ocurred. - /// - /// - private void readAndBuffer(BufferedRandomAccessFile fi) - { - int p, prem, length, t, markIndex; - - // Buffer main header - fi.seek(0); - length = ((System.Int32)positions[0]) - 2; - mainHeader = new byte[length]; - fi.readFully(mainHeader, 0, length); - markIndex = 0; - - for (t = 0; t < nt; t++) - { - prem = ppt[t]; - - packetHeaders[t] = new byte[prem][]; - packetData[t] = new byte[prem][]; - sopMarkSeg[t] = new byte[prem][]; - - // Read tile header - length = positions[markIndex + 1] - positions[markIndex]; - tileHeaders[t] = new byte[length]; - fi.readFully(tileHeaders[t], 0, length); - markIndex++; - - for (p = 0; p < prem; p++) - { - // Read packet header - length = positions[markIndex + 1] - positions[markIndex]; - - if (tempSop) - { - // SOP marker is skipped - length -= CSJ2K.j2k.codestream.Markers.SOP_LENGTH; - fi.skipBytes(CSJ2K.j2k.codestream.Markers.SOP_LENGTH); - } - else - { - // SOP marker is read and buffered - length -= CSJ2K.j2k.codestream.Markers.SOP_LENGTH; - sopMarkSeg[t][p] = new byte[CSJ2K.j2k.codestream.Markers.SOP_LENGTH]; - fi.readFully(sopMarkSeg[t][p], 0, CSJ2K.j2k.codestream.Markers.SOP_LENGTH); - } - - if (!tempEph) - { - // EPH marker is kept in header - length += CSJ2K.j2k.codestream.Markers.EPH_LENGTH; - } - packetHeaders[t][p] = new byte[length]; - fi.readFully(packetHeaders[t][p], 0, length); - markIndex++; - - // Read packet data - length = positions[markIndex + 1] - positions[markIndex]; - - length -= CSJ2K.j2k.codestream.Markers.EPH_LENGTH; - if (tempEph) - { - // EPH marker is used and is skipped - fi.skipBytes(CSJ2K.j2k.codestream.Markers.EPH_LENGTH); - } - - packetData[t][p] = new byte[length]; - fi.readFully(packetData[t][p], 0, length); - markIndex++; - } - } - } - - /// This method creates the tileparts from the buffered tile headers, - /// packet headers and packet data - /// - /// - /// If an I/O error ocurred. - /// - /// - private void createTileParts() - { - int i, prem, t, length; - int pIndex; // phIndex removed - int tppStart; - int tilePart; - int p, np, nomnp; - int numTileParts; - int numPackets; - System.IO.MemoryStream temp = new System.IO.MemoryStream(); - byte[] tempByteArr; - - // Create tile parts - tileParts = new byte[nt][][]; - maxtp = 0; - - for (t = 0; t < nt; t++) - { - // Calculate number of tile parts. If tileparts are not used, - // put all packets in the first tilepart - if (pptp == 0) - pptp = ppt[t]; - prem = ppt[t]; - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - numTileParts = (int)System.Math.Ceiling(((double)prem) / pptp); - numPackets = packetHeaders[t].Length; - maxtp = (numTileParts > maxtp) ? numTileParts : maxtp; - tileParts[t] = new byte[numTileParts][]; - - // Create all the tile parts for tile t - tppStart = 0; - pIndex = 0; - p = 0; - //phIndex = 0; - - for (tilePart = 0; tilePart < numTileParts; tilePart++) - { - - // Calculate number of packets in this tilepart - nomnp = (pptp > prem) ? prem : pptp; - np = nomnp; - - // Write tile part header - if (tilePart == 0) - { - // Write original tile part header up to SOD marker - temp.Write(tileHeaders[t], 0, tileHeaders[t].Length - 2); - } - else - { - // Write empty header of length TP_HEAD_LEN-2 - temp.Write(new byte[TP_HEAD_LEN - 2], 0, TP_HEAD_LEN - 2); - } - - // Write PPT marker segments if PPT used - if (pptUsed) - { - int pptLength = 3; // Zppt and Lppt - int pptIndex = 0; - int phLength; - - p = pIndex; - while (np > 0) - { - phLength = packetHeaders[t][p].Length; - - // If the total legth of the packet headers is greater - // than MAX_LPPT, several PPT markers are needed - if (pptLength + phLength > CSJ2K.j2k.codestream.Markers.MAX_LPPT) - { - - temp.WriteByte((System.Byte)SupportClass.URShift(CSJ2K.j2k.codestream.Markers.PPT, 8)); - temp.WriteByte((System.Byte)(CSJ2K.j2k.codestream.Markers.PPT & 0x00FF)); - temp.WriteByte((System.Byte)SupportClass.URShift(pptLength, 8)); - temp.WriteByte((System.Byte)pptLength); - temp.WriteByte((System.Byte)pptIndex++); - for (i = pIndex; i < p; i++) - { - temp.Write(packetHeaders[t][i], 0, packetHeaders[t][i].Length); - } - pptLength = 3; // Zppt and Lppt - pIndex = p; - } - pptLength += phLength; - p++; - np--; - } - // Write last PPT marker - temp.WriteByte((System.Byte)SupportClass.URShift(CSJ2K.j2k.codestream.Markers.PPT, 8)); - temp.WriteByte((System.Byte)(CSJ2K.j2k.codestream.Markers.PPT & 0x00FF)); - temp.WriteByte((System.Byte)SupportClass.URShift(pptLength, 8)); - temp.WriteByte((System.Byte)pptLength); - temp.WriteByte((System.Byte)pptIndex); - for (i = pIndex; i < p; i++) - { - - temp.Write(packetHeaders[t][i], 0, packetHeaders[t][i].Length); - } - } - pIndex = p; - np = nomnp; - - // Write SOD marker - temp.WriteByte((System.Byte)SupportClass.URShift(CSJ2K.j2k.codestream.Markers.SOD, 8)); - temp.WriteByte((System.Byte)(CSJ2K.j2k.codestream.Markers.SOD & 0x00FF)); - - // Write packet data and packet headers if PPT and PPM not used - for (p = tppStart; p < tppStart + np; p++) - { - if (!tempSop) - { - temp.Write(sopMarkSeg[t][p], 0, CSJ2K.j2k.codestream.Markers.SOP_LENGTH); - } - - if (!(ppmUsed || pptUsed)) - { - temp.Write(packetHeaders[t][p], 0, packetHeaders[t][p].Length); - } - - temp.Write(packetData[t][p], 0, packetData[t][p].Length); - } - tppStart += np; - - // Edit tile part header - tempByteArr = temp.ToArray(); - tileParts[t][tilePart] = tempByteArr; - length = (int)temp.Length; - - if (tilePart == 0) - { - // Edit first tile part header - tempByteArr[6] = (byte)(SupportClass.URShift(length, 24)); // Psot - tempByteArr[7] = (byte)(SupportClass.URShift(length, 16)); - tempByteArr[8] = (byte)(SupportClass.URShift(length, 8)); - tempByteArr[9] = (byte)(length); - tempByteArr[10] = (byte)SupportClass.Identity((0)); // TPsot - tempByteArr[11] = (byte)(numTileParts); // TNsot - } - else - { - // Edit tile part header - tempByteArr[0] = (byte)(SupportClass.URShift(CSJ2K.j2k.codestream.Markers.SOT, 8)); // SOT - tempByteArr[1] = (byte)(CSJ2K.j2k.codestream.Markers.SOT & 0x00FF); - tempByteArr[2] = (byte)SupportClass.Identity((0)); // Lsot - tempByteArr[3] = (byte)SupportClass.Identity((10)); - tempByteArr[4] = (byte)(SupportClass.URShift(t, 8)); // Isot - tempByteArr[5] = (byte)(t); // - tempByteArr[6] = (byte)(SupportClass.URShift(length, 24)); // Psot - tempByteArr[7] = (byte)(SupportClass.URShift(length, 16)); - tempByteArr[8] = (byte)(SupportClass.URShift(length, 8)); - tempByteArr[9] = (byte)(length); - tempByteArr[10] = (byte)(tilePart); //TPsot - tempByteArr[11] = (byte)(numTileParts); // TNsot - } - //UPGRADE_ISSUE: Method 'java.io.ByteArrayOutputStream.reset' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javaioByteArrayOutputStreamreset'" - //temp.reset(); - temp.SetLength(0); - prem -= np; - } - } - temp.Close(); - } - - /// This method writes the new codestream to the file. - /// - /// - /// The file to write the new codestream to - /// - /// - /// If an I/O error ocurred. - /// - /// - private void writeNewCodestream(BufferedRandomAccessFile fi) - { - int t, p, tp; // i removed - int numTiles = tileParts.Length; - int[][] packetHeaderLengths = new int[numTiles][]; - for (int i2 = 0; i2 < numTiles; i2++) - { - packetHeaderLengths[i2] = new int[maxtp]; - } - byte[] temp; - int length; - - // Write main header up to SOT marker - fi.write(mainHeader, 0, mainHeader.Length); - - // If PPM used write all packet headers in PPM markers - if (ppmUsed) - { - System.IO.MemoryStream ppmMarkerSegment = new System.IO.MemoryStream(); - int numPackets; - int totNumPackets; - int ppmIndex = 0; - int ppmLength; - int pStart, pStop; - int[] prem = new int[numTiles]; - - // Set number of remaining packets - for (t = 0; t < numTiles; t++) - { - prem[t] = packetHeaders[t].Length; - } - - // Calculate Nppm values - for (tp = 0; tp < maxtp; tp++) - { - for (t = 0; t < numTiles; t++) - { - if (tileParts[t].Length > tp) - { - totNumPackets = packetHeaders[t].Length; - // Calculate number of packets in this tilepart - numPackets = (tp == tileParts[t].Length - 1) ? prem[t] : pptp; - - pStart = totNumPackets - prem[t]; - pStop = pStart + numPackets; - - // Calculate number of packet header bytes for this - // tile part - for (p = pStart; p < pStop; p++) - packetHeaderLengths[t][tp] += packetHeaders[t][p].Length; - - prem[t] -= numPackets; - } - } - } - - // Write first PPM marker - ppmMarkerSegment.WriteByte((System.Byte)SupportClass.URShift(CSJ2K.j2k.codestream.Markers.PPM, 8)); - ppmMarkerSegment.WriteByte((System.Byte)(CSJ2K.j2k.codestream.Markers.PPM & 0x00FF)); - ppmMarkerSegment.WriteByte((System.Byte)0); // Temporary Lppm value - ppmMarkerSegment.WriteByte((System.Byte)0); // Temporary Lppm value - ppmMarkerSegment.WriteByte((System.Byte)0); // zppm - ppmLength = 3; - ppmIndex++; - - // Set number of remaining packets - for (t = 0; t < numTiles; t++) - prem[t] = packetHeaders[t].Length; - - // Write all PPM markers and information - for (tp = 0; tp < maxtp; tp++) - { - for (t = 0; t < numTiles; t++) - { - - if (tileParts[t].Length > tp) - { - totNumPackets = packetHeaders[t].Length; - - // Calculate number of packets in this tilepart - numPackets = (tp == tileParts[t].Length - 1) ? prem[t] : pptp; - - pStart = totNumPackets - prem[t]; - pStop = pStart + numPackets; - - // If Nppm value wont fit in current PPM marker segment - // write current PPM marker segment and start new - if (ppmLength + 4 > CSJ2K.j2k.codestream.Markers.MAX_LPPM) - { - // Write current PPM marker - temp = ppmMarkerSegment.ToArray(); - length = temp.Length - 2; - temp[2] = (byte)(SupportClass.URShift(length, 8)); - temp[3] = (byte)length; - fi.write(temp, 0, length + 2); - - // Start new PPM marker segment - //UPGRADE_ISSUE: Method 'java.io.ByteArrayOutputStream.reset' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javaioByteArrayOutputStreamreset'" - //ppmMarkerSegment.reset(); - ppmMarkerSegment.SetLength(0); - ppmMarkerSegment.WriteByte((System.Byte)SupportClass.URShift(CSJ2K.j2k.codestream.Markers.PPM, 8)); - ppmMarkerSegment.WriteByte((System.Byte)(CSJ2K.j2k.codestream.Markers.PPM & 0x00FF)); - ppmMarkerSegment.WriteByte((System.Byte)0); // Temporary Lppm value - ppmMarkerSegment.WriteByte((System.Byte)0); // Temporary Lppm value - ppmMarkerSegment.WriteByte((System.Byte)ppmIndex++); // zppm - ppmLength = 3; - } - - // Write Nppm value - length = packetHeaderLengths[t][tp]; - ppmMarkerSegment.WriteByte((System.Byte)SupportClass.URShift(length, 24)); - ppmMarkerSegment.WriteByte((System.Byte)SupportClass.URShift(length, 16)); - ppmMarkerSegment.WriteByte((System.Byte)SupportClass.URShift(length, 8)); - ppmMarkerSegment.WriteByte((System.Byte)length); - ppmLength += 4; - - // Write packet headers - for (p = pStart; p < pStop; p++) - { - length = packetHeaders[t][p].Length; - - // If next packet header value wont fit in - // current PPM marker segment write current PPM - // marker segment and start new - if (ppmLength + length > CSJ2K.j2k.codestream.Markers.MAX_LPPM) - { - // Write current PPM marker - temp = ppmMarkerSegment.ToArray(); - length = temp.Length - 2; - temp[2] = (byte)(SupportClass.URShift(length, 8)); - temp[3] = (byte)length; - fi.write(temp, 0, length + 2); - - // Start new PPM marker segment - //UPGRADE_ISSUE: Method 'java.io.ByteArrayOutputStream.reset' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javaioByteArrayOutputStreamreset'" - //ppmMarkerSegment.reset(); - ppmMarkerSegment.SetLength(0); - ppmMarkerSegment.WriteByte((System.Byte)SupportClass.URShift(CSJ2K.j2k.codestream.Markers.PPM, 8)); - ppmMarkerSegment.WriteByte((System.Byte)(CSJ2K.j2k.codestream.Markers.PPM & 0x00FF)); - ppmMarkerSegment.WriteByte((System.Byte)0); // Temp Lppm value - ppmMarkerSegment.WriteByte((System.Byte)0); // Temp Lppm value - ppmMarkerSegment.WriteByte((System.Byte)ppmIndex++); // zppm - ppmLength = 3; - } - - // write packet header - ppmMarkerSegment.Write(packetHeaders[t][p], 0, packetHeaders[t][p].Length); - ppmLength += packetHeaders[t][p].Length; - } - prem[t] -= numPackets; - } - } - } - // Write last PPM marker segment - temp = ppmMarkerSegment.ToArray(); - length = temp.Length - 2; - temp[2] = (byte)(SupportClass.URShift(length, 8)); - temp[3] = (byte)length; - fi.write(temp, 0, length + 2); - } - - // Write tile parts interleaved - for (tp = 0; tp < maxtp; tp++) - { - for (t = 0; t < nt; t++) - { - if (tileParts[t].Length > tp) - { - temp = tileParts[t][tp]; - length = temp.Length; - fi.write(temp, 0, length); - } - } - } - fi.writeShort(CSJ2K.j2k.codestream.Markers.EOC); - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/util/FacilityManager.cs b/CSJ2K/j2k/util/FacilityManager.cs deleted file mode 100644 index f90fcdff..00000000 --- a/CSJ2K/j2k/util/FacilityManager.cs +++ /dev/null @@ -1,183 +0,0 @@ -/* -* CVS identifier: -* -* $Id: FacilityManager.java,v 1.12 2002/05/22 15:00:24 grosbois Exp $ -* -* Class: MsgLoggerManager -* -* Description: Manages common facilities across threads -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -namespace CSJ2K.j2k.util -{ - - /// This class manages common facilities for multi-threaded - /// environments, It can register different facilities for each thread, - /// and also a default one, so that they can be referred by static - /// methods, while possibly having different ones for different - /// threads. Also a default facility exists that is used for threads - /// for which no particular facility has been registerd registered. - /// - ///

    Currently the only kind of facilities managed is MsgLogger.

    - /// - ///

    An example use of this class is if 2 instances of a decoder are running - /// in different threads and the messages of the 2 instances should be - /// separated. - /// - ///

    The default MsgLogger is a StreamMsgLogger that uses System.out as - /// the 'out' stream and System.err as the 'err' stream, and a line width of - /// 78. This can be changed using the registerMsgLogger() method. - /// - ///

    - /// - /// - /// - /// - /// - public class FacilityManager - { - /// Returns the ProgressWatch instance registered with the current - /// thread (the thread that calls this method). If the current - /// thread has no registered ProgressWatch, then the default one is used. - /// - /// - public static ProgressWatch ProgressWatch - { - get - { - ProgressWatch pw = (ProgressWatch)watchProgList[SupportClass.ThreadClass.Current()]; - return (pw == null) ? defWatchProg : pw; - } - - } - - /// The loggers associated to different threads - //UPGRADE_NOTE: Final was removed from the declaration of 'loggerList '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly System.Collections.Hashtable loggerList = System.Collections.Hashtable.Synchronized(new System.Collections.Hashtable()); - - /// The default logger, for threads that have none associated with them - private static MsgLogger defMsgLogger = new StreamMsgLogger(System.Console.OpenStandardOutput(), System.Console.OpenStandardError(), 78); - - /// The ProgressWatch instance associated to different threads - //UPGRADE_NOTE: Final was removed from the declaration of 'watchProgList '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly System.Collections.Hashtable watchProgList = System.Collections.Hashtable.Synchronized(new System.Collections.Hashtable()); - - /// The default ProgressWatch for threads that have none - /// associated with them. - /// - private static ProgressWatch defWatchProg = null; - - - internal static void registerProgressWatch(SupportClass.ThreadClass t, ProgressWatch pw) - { - if (pw == null) - { - throw new System.NullReferenceException(); - } - if (t == null) - { - defWatchProg = pw; - } - else - { - watchProgList[t] = pw; - } - } - - /// Registers the MsgLogger 'ml' as the logging facility of the - /// thread 't'. If any other logging facility was registered with - /// the thread 't' it is overriden by 'ml'. If 't' is null then - /// 'ml' is taken as the default message logger that is used for - /// threads that have no MsgLogger registered. - /// - /// - /// The thread to associate with 'ml' - /// - /// - /// The MsgLogger to associate with therad ml - /// - /// - internal static void registerMsgLogger(SupportClass.ThreadClass t, MsgLogger ml) - { - if (ml == null) - { - throw new System.NullReferenceException(); - } - if (t == null) - { - defMsgLogger = ml; - } - else - { - loggerList[t] = ml; - } - } - - /// Returns the MsgLogger registered with the current thread (the - /// thread that calls this method). If the current thread has no - /// registered MsgLogger then the default message logger is - /// returned. - /// - /// - /// The MsgLogger registerd for the current thread, or the - /// default one if there is none registered for it. - /// - /// - public static MsgLogger getMsgLogger() - { - MsgLogger ml = (MsgLogger)loggerList[SupportClass.ThreadClass.Current()]; - return (ml == null) ? defMsgLogger : ml; - } - - /// Returns the MsgLogger registered with the thread 't' (the - /// thread that calls this method). If the thread 't' has no - /// registered MsgLogger then the default message logger is - /// returned. - /// - /// - /// The thread for which to return the MsgLogger - /// - /// - /// The MsgLogger registerd for the current thread, or the - /// default one if there is none registered for it. - /// - /// - internal static MsgLogger getMsgLogger(SupportClass.ThreadClass t) - { - MsgLogger ml = (MsgLogger)loggerList[t]; - return (ml == null) ? defMsgLogger : ml; - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/util/ISRandomAccessIO.cs b/CSJ2K/j2k/util/ISRandomAccessIO.cs deleted file mode 100644 index c13665ef..00000000 --- a/CSJ2K/j2k/util/ISRandomAccessIO.cs +++ /dev/null @@ -1,743 +0,0 @@ -/* -* CVS identifier: -* -* $Id: ISRandomAccessIO.java,v 1.2 2001/04/09 16:58:15 grosbois Exp $ -* -* Class: ISRandomAccessIO -* -* Description: Turns an InsputStream into a read-only -* RandomAccessIO, using buffering. -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.io; -using System; -namespace CSJ2K.j2k.util -{ - - /// This class implements a wrapper to turn an InputStream into a - /// RandomAccessIO. To provide random access, the input data from the - /// InputStream is cached in an in-memory buffer. The in-memory buffer size can - /// be limited to a specified size. The data is read into the cache on a as - /// needed basis, blocking only when necessary. - /// - ///

    The cache grows automatically as necessary. However, if the data length - /// is known prior to the creation of a ISRandomAccessIO object, it is best to - /// specify that as the initial in-memory buffer size. That will minimize data - /// copying and multiple allocation.

    - /// - ///

    Multi-byte data is read in big-endian order. The in-memory buffer - /// storage is released when 'close()' is called. This class can only be used - /// for data input, not output. The wrapped InputStream is closed when all the - /// input data is cached or when 'close()' is called.

    - /// - ///

    If an out of memory condition is encountered when growing the in-memory - /// buffer an IOException is thrown instead of an OutOfMemoryError. The - /// exception message is "Out of memory to cache input data".

    - /// - ///

    This class is intended for use as a "quick and dirty" way to give - /// network connectivity to RandomAccessIO based classes. It is not intended as - /// an efficient means of implementing network connectivity. Doing such - /// requires reimplementing the RandomAccessIO based classes to directly use - /// network connections.

    - /// - ///

    This class does not use temporary files as buffers, because that would - /// preclude the use in unsigned applets.

    - /// - ///
    - public class ISRandomAccessIO : RandomAccessIO - { - /// Returns the current position in the stream, which is the position from - /// where the next byte of data would be read. The first byte in the stream - /// is in position 0. - /// - /// - /// If an I/O error occurred. - /// - /// - virtual public int Pos - { - get - { - return pos; - } - - } - /// Returns the endianess (i.e., byte ordering) of multi-byte I/O - /// operations. Always EndianType.BIG_ENDIAN since this class implements - /// only big-endian. - /// - /// - /// Always EndianType.BIG_ENDIAN. - /// - /// - /// - /// - /// - virtual public int ByteOrdering - { - get - { - return CSJ2K.j2k.io.EndianType_Fields.BIG_ENDIAN; - } - - } - - /// The InputStream that is wrapped - private System.IO.Stream is_Renamed; - - /* Tha maximum size, in bytes, of the in memory buffer. The maximum size - * includes the EOF. */ - private int maxsize; - - /* The increment, in bytes, for the in-memory buffer size */ - private int inc; - - /* The in-memory buffer to cache received data */ - private byte[] buf; - - /* The length of the already received data */ - private int len; - - /* The position of the next byte to be read from the in-memory buffer */ - private int pos; - - /* Flag to indicate if all the data has been received. That is, if the EOF - * has been reached. */ - private bool complete; - - /// Creates a new RandomAccessIO wrapper for the given InputStream - /// 'is'. The internal cache buffer will have size 'size' and will - /// increment by 'inc' each time it is needed. The maximum buffer size is - /// limited to 'maxsize'. - /// - /// - /// The input from where to get the data. - /// - /// - /// The initial size for the cache buffer, in bytes. - /// - /// - /// The size increment for the cache buffer, in bytes. - /// - /// - /// The maximum size for the cache buffer, in bytes. - /// - /// - public ISRandomAccessIO(System.IO.Stream is_Renamed, int size, int inc, int maxsize) - { - if (size < 0 || inc <= 0 || maxsize <= 0 || is_Renamed == null) - { - throw new System.ArgumentException(); - } - this.is_Renamed = is_Renamed; - // Increase size by one to count in EOF - if (size < System.Int32.MaxValue) - size++; - buf = new byte[size]; - this.inc = inc; - // The maximum size is one byte more, to allow reading the EOF. - if (maxsize < System.Int32.MaxValue) - maxsize++; - this.maxsize = maxsize; - pos = 0; - len = 0; - complete = false; - } - - /// Creates a new RandomAccessIO wrapper for the given InputStream - /// 'is'. The internal cache buffer size and increment is to to 256 kB. The - /// maximum buffer size is set to Integer.MAX_VALUE (2 GB). - /// - /// - /// The input from where to get the data. - /// - /// - public ISRandomAccessIO(System.IO.Stream is_Renamed) : this(is_Renamed, 1 << 18, 1 << 18, System.Int32.MaxValue) - { - } - - /// Grows the cache buffer by 'inc', upto a maximum of 'maxsize'. The - /// buffer size will be increased by at least one byte, if no exception is - /// thrown. - /// - /// - /// If the maximum cache size is reached or if not - /// enough memory is available to grow the buffer. - /// - /// - private void growBuffer() - { - byte[] newbuf; - int effinc; // effective increment - - effinc = inc; - if (buf.Length + effinc > maxsize) - effinc = maxsize - buf.Length; - if (effinc <= 0) - { - throw new System.IO.IOException("Reached maximum cache size (" + maxsize + ")"); - } - try - { - newbuf = new byte[buf.Length + inc]; - } - catch (System.OutOfMemoryException) - { - throw new System.IO.IOException("Out of memory to cache input data"); - } - Array.Copy(buf, 0, newbuf, 0, len); - buf = newbuf; - } - - /// Reads data from the wrapped InputStream and places it in the cache - /// buffer. Reads all input data that will not cause it to block, but at - /// least on byte is read (even if it blocks), unless EOF is reached. This - /// method can not be called if EOF has been already reached - /// (i.e. 'complete' is true). The wrapped InputStream is closed if the EOF - /// is reached. - /// - /// - /// An I/O error occurred, out of meory to grow - /// cache or maximum cache size reached. - /// - /// - private void readInput() - { - int n; - //int b; - int k; - - if (complete) - { - throw new System.ArgumentException("Already reached EOF"); - } - long available; - available = is_Renamed.Length - is_Renamed.Position; - n = (int)available; /* how much can we read without blocking? */ - if (n == 0) - n = 1; /* read at least one byte (even if it blocks) */ - while (len + n > buf.Length) - { - /* Ensure buffer size */ - growBuffer(); - } - /* Read the data. Loop to be sure that we do read 'n' bytes */ - do - { - // CONVERSION PROBLEM? OPTIMIZE!!! - k = is_Renamed.Read(buf, len, n); - if (k > 0) - { - /* Some data was read */ - len += k; - n -= k; - } - } - while (n > 0 && k > 0); - if (k <= 0) - { - /* we reached EOF */ - complete = true; - is_Renamed.Close(); - is_Renamed = null; - } - } - - /// Closes this object for reading as well as the wrapped InputStream, if - /// not already closed. The memory used by the cache is released. - /// - /// - /// If an I/O error occurs while closing the - /// underlying InputStream. - /// - /// - public virtual void close() - { - buf = null; - if (!complete) - { - is_Renamed.Close(); - is_Renamed = null; - } - } - - /// Moves the current position for the next read operation to offset. The - /// offset is measured from the beginning of the stream. If the offset is - /// set beyond the currently cached data, the missing data will be read - /// only when a read operation is performed. Setting the offset beyond the - /// end of the data will cause an EOFException only if the data length is - /// currently known, otherwise an IOException will occur when a read - /// operation is attempted at that position. - /// - /// - /// The offset where to move to. - /// - /// - /// If seeking beyond EOF and the data length is - /// known. - /// - /// - /// If an I/O error ocurred. - /// - /// - public virtual void seek(int off) - { - if (complete) - { - /* we know the length, check seek is within length */ - if (off > len) - { - throw new System.IO.EndOfStreamException(); - } - } - pos = off; - } - - /// Returns the length of the stream. This will cause all the data to be - /// read. This method will block until all the data is read, which can be - /// lengthy across the network. - /// - /// - /// The length of the stream, in bytes. - /// - /// - /// If an I/O error ocurred. - /// - /// - public virtual int length() - { - while (!complete) - { - /* read until we reach EOF */ - readInput(); - } - return len; - } - - /// Reads a byte of data from the stream. - /// - /// - /// The byte read, as an int in the range [0-255]. - /// - /// - /// If the end-of file was reached. - /// - /// - /// If an I/O error ocurred. - /// - /// - public virtual byte readByte() { return read(); } - public virtual byte read() - { - if (pos < len) - { - // common, fast case - return buf[pos++]; - } - // general case - while (!complete && pos >= len) - { - readInput(); - } - if (pos == len) - { - throw new System.IO.EndOfStreamException(); - } - else if (pos > len) - { - throw new System.IO.IOException("Position beyond EOF"); - } - return buf[pos++]; - } - - /// Reads 'len' bytes of data from this file into an array of bytes. This - /// method reads repeatedly from the stream until all the bytes are - /// read. This method blocks until all the bytes are read, the end of the - /// stream is detected, or an exception is thrown. - /// - /// - /// The buffer into which the data is to be read. It must be long - /// enough. - /// - /// - /// The index in 'b' where to place the first byte read. - /// - /// - /// The number of bytes to read. - /// - /// - /// If the end-of file was reached before getting - /// all the necessary data. - /// - /// - /// If an I/O error ocurred. - /// - /// - public virtual void readFully(byte[] b, int off, int n) - { - if (pos + n <= len) - { - // common, fast case - Array.Copy(buf, pos, b, off, n); - pos += n; - return; - } - // general case - while (!complete && pos + n > len) - { - readInput(); - } - if (pos + n > len) - { - throw new System.IO.EndOfStreamException(); - } - Array.Copy(buf, pos, b, off, n); - pos += n; - } - - /// Reads an unsigned byte (8 bit) from the input. - /// - /// - /// The next byte-aligned unsigned byte (8 bit) from the input. - /// - /// - /// If the end-of file was reached before getting - /// all the necessary data. - /// - /// - /// If an I/O error ocurred. - /// - /// - public virtual byte readUnsignedByte() - { - if (pos < len) - { - // common, fast case - return buf[pos++]; - } - // general case - return read(); - } - - /// Reads a signed short (16 bit) from the input. - /// - /// - /// The next byte-aligned signed short (16 bit) from the input. - /// - /// - /// If the end-of file was reached before getting - /// all the necessary data. - /// - /// - /// If an I/O error ocurred. - /// - /// - public virtual short readShort() - { - if (pos + 1 < len) - { - // common, fast case - return (short)((buf[pos++] << 8) | (0xFF & buf[pos++])); - } - // general case - return (short)((read() << 8) | read()); - } - - /// Reads an unsigned short (16 bit) from the input. - /// - /// - /// The next byte-aligned unsigned short (16 bit) from the input. - /// - /// - /// If the end-of file was reached before getting - /// all the necessary data. - /// - /// - /// If an I/O error ocurred. - /// - /// - public virtual int readUnsignedShort() - { - if (pos + 1 < len) - { - // common, fast case - return ((0xFF & buf[pos++]) << 8) | (0xFF & buf[pos++]); - } - // general case - return (read() << 8) | read(); - } - - /// Reads a signed int (32 bit) from the input. - /// - /// - /// The next byte-aligned signed int (32 bit) from the - /// input. - /// - /// - /// If the end-of file was reached before getting - /// all the necessary data. - /// - /// - /// If an I/O error ocurred. - /// - /// - public virtual int readInt() - { - if (pos + 3 < len) - { - // common, fast case - return ((buf[pos++] << 24) | ((0xFF & buf[pos++]) << 16) | ((0xFF & buf[pos++]) << 8) | (0xFF & buf[pos++])); - } - // general case - return (read() << 24) | (read() << 16) | (read() << 8) | read(); - } - - /// Reads a unsigned int (32 bit) from the input. - /// - /// - /// The next byte-aligned unsigned int (32 bit) from the input. - /// - /// - /// If the end-of file was reached before getting - /// all the necessary data. - /// - /// - /// If an I/O error ocurred. - /// - /// - public virtual long readUnsignedInt() - { - if (pos + 3 < len) - { - // common, fast case - return (unchecked((int)0xFFFFFFFFL) & (long)((buf[pos++] << 24) | ((0xFF & buf[pos++]) << 16) | ((0xFF & buf[pos++]) << 8) | (0xFF & buf[pos++]))); - } - // general case - return (unchecked((int)0xFFFFFFFFL) & (long)((read() << 24) | (read() << 16) | (read() << 8) | read())); - } - - /// Reads a signed long (64 bit) from the input. - /// - /// - /// The next byte-aligned signed long (64 bit) from the input. - /// - /// - /// If the end-of file was reached before getting - /// all the necessary data. - /// - /// - /// If an I/O error ocurred. - /// - /// - public virtual long readLong() - { - if (pos + 7 < len) - { - // common, fast case - return (((long)buf[pos++] << 56) | ((long)buf[pos++] << 48) | ((long)buf[pos++] << 40) | ((long)buf[pos++] << 32) | ((long)buf[pos++] << 24) | ((long)buf[pos++] << 16) | ((long)buf[pos++] << 8) | (long)buf[pos++]); - } - // general case - return (((long)read() << 56) | ((long)read() << 48) | ((long)read() << 40) | ((long)read() << 32) | ((long)read() << 24) | ((long)read() << 16) | ((long)read() << 8) | (long)read()); - } - - /// Reads an IEEE single precision (i.e., 32 bit) floating-point number - /// from the input. - /// - /// - /// The next byte-aligned IEEE float (32 bit) from the input. - /// - /// - /// If the end-of file was reached before getting - /// all the necessary data. - /// - /// - /// If an I/O error ocurred. - /// - /// - public virtual float readFloat() - { - // CONVERSION PROBLEM? BIGENDIAN - int floatint; - if (pos + 3 < len) - floatint = (buf[pos++] << 24) | ((0xFF & buf[pos++]) << 16) | ((0xFF & buf[pos++]) << 8) | (0xFF & buf[pos++]); - else - floatint = (read() << 24) | (read() << 16) | (read() << 8) | read(); - return BitConverter.ToSingle(BitConverter.GetBytes(floatint), 0); - - /* - if (pos + 3 < len) - { - // common, fast case - //UPGRADE_ISSUE: Method 'java.lang.Float.intBitsToFloat' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javalangFloatintBitsToFloat_int'" - return Float.intBitsToFloat((buf[pos++] << 24) | ((0xFF & buf[pos++]) << 16) | ((0xFF & buf[pos++]) << 8) | (0xFF & buf[pos++])); - } - // general case - //UPGRADE_ISSUE: Method 'java.lang.Float.intBitsToFloat' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javalangFloatintBitsToFloat_int'" - return Float.intBitsToFloat((read() << 24) | (read() << 16) | (read() << 8) | read()); - */ - } - - /// Reads an IEEE double precision (i.e., 64 bit) floating-point number - /// from the input. - /// - /// - /// The next byte-aligned IEEE double (64 bit) from the input. - /// - /// - /// If the end-of file was reached before getting - /// all the necessary data. - /// - /// - /// If an I/O error ocurred. - /// - /// - public virtual double readDouble() - { - // CONVERSION PROBLEM? BIGENDIAN - long doublelong; - if (pos + 7 < len) - doublelong = ((long)buf[pos++] << 56) | ((long)buf[pos++] << 48) | ((long)buf[pos++] << 40) | ((long)buf[pos++] << 32) | ((long)buf[pos++] << 24) | ((long)buf[pos++] << 16) | ((long)buf[pos++] << 8) | (long)buf[pos++]; - else - doublelong = ((long)read() << 56) | ((long)read() << 48) | ((long)read() << 40) | ((long)read() << 32) | ((long)read() << 24) | ((long)read() << 16) | ((long)read() << 8) | (long)read(); - return BitConverter.ToDouble(BitConverter.GetBytes(doublelong), 0); - - /* - if (pos + 7 < len) - { - // common, fast case - //UPGRADE_ISSUE: Method 'java.lang.Double.longBitsToDouble' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javalangDoublelongBitsToDouble_long'" - return Double.longBitsToDouble(((long) buf[pos++] << 56) | ((long) (0xFF & buf[pos++]) << 48) | ((long) (0xFF & buf[pos++]) << 40) | ((long) (0xFF & buf[pos++]) << 32) | ((long) (0xFF & buf[pos++]) << 24) | ((long) (0xFF & buf[pos++]) << 16) | ((long) (0xFF & buf[pos++]) << 8) | (long) (0xFF & buf[pos++])); - } - // general case - //UPGRADE_ISSUE: Method 'java.lang.Double.longBitsToDouble' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javalangDoublelongBitsToDouble_long'" - return Double.longBitsToDouble(((long) read() << 56) | ((long) read() << 48) | ((long) read() << 40) | ((long) read() << 32) | ((long) read() << 24) | ((long) read() << 16) | ((long) read() << 8) | (long) read()); - */ - } - - /// Skips 'n' bytes from the input. - /// - /// - /// The number of bytes to skip - /// - /// - /// Always n. - /// - /// - /// If the end-of file was reached before all the - /// bytes could be skipped. - /// - /// - /// If an I/O error ocurred. - /// - /// - public virtual int skipBytes(int n) - { - if (complete) - { - /* we know the length, check skip is within length */ - if (pos + n > len) - { - throw new System.IO.EndOfStreamException(); - } - } - pos += n; - return n; - } - - /// Does nothing since this class does not implement data output. - /// - /// - public virtual void flush() - { - /* no-op */ - } - - /// Throws an IOException since this class does not implement data output. - /// - /// - public virtual void write(byte b) - { - throw new System.IO.IOException("read-only"); - } - - /// Throws an IOException since this class does not implement data output. - /// - /// - public virtual void writeByte(int v) - { - throw new System.IO.IOException("read-only"); - } - - /// Throws an IOException since this class does not implement data output. - /// - /// - public virtual void writeShort(int v) - { - throw new System.IO.IOException("read-only"); - } - - /// Throws an IOException since this class does not implement data output. - /// - /// - public virtual void writeInt(int v) - { - throw new System.IO.IOException("read-only"); - } - - /// Throws an IOException since this class does not implement data output. - /// - /// - public virtual void writeLong(long v) - { - throw new System.IO.IOException("read-only"); - } - - /// Throws an IOException since this class does not implement data output. - /// - /// - public virtual void writeFloat(float v) - { - throw new System.IO.IOException("read-only"); - } - - /// Throws an IOException since this class does not implement data output. - /// - /// - public virtual void writeDouble(double v) - { - throw new System.IO.IOException("read-only"); - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/util/MathUtil.cs b/CSJ2K/j2k/util/MathUtil.cs deleted file mode 100644 index 85fd55b3..00000000 --- a/CSJ2K/j2k/util/MathUtil.cs +++ /dev/null @@ -1,206 +0,0 @@ -/* -* CVS identifier: -* -* $Id: MathUtil.java,v 1.15 2001/09/14 08:48:51 grosbois Exp $ -* -* Class: MathUtil -* -* Description: Utility mathematical methods -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -namespace CSJ2K.j2k.util -{ - - /// This class contains a collection of utility methods fro mathematical - /// operations. All methods are static. - /// - /// - public class MathUtil - { - - /// Method that calculates the floor of the log, base 2, of 'x'. The - /// calculation is performed in integer arithmetic, therefore, it is exact. - /// - /// - /// The value to calculate log2 on. - /// - /// - /// floor(log(x)/log(2)), calculated in an exact way. - /// - /// - public static int log2(int x) - { - int y, v; - // No log of 0 or negative - if (x <= 0) - { - throw new System.ArgumentException("" + x + " <= 0"); - } - // Calculate log2 (it's actually floor log2) - v = x; - y = -1; - while (v > 0) - { - v >>= 1; - y++; - } - return y; - } - - /// Method that calculates the Least Common Multiple (LCM) of two strictly - /// positive integer numbers. - /// - /// - /// First number - /// - /// - /// Second number - /// - /// - public static int lcm(int x1, int x2) - { - if (x1 <= 0 || x2 <= 0) - { - throw new System.ArgumentException("Cannot compute the least " + "common multiple of two " + "numbers if one, at least," + "is negative."); - } - int max, min; - if (x1 > x2) - { - max = x1; - min = x2; - } - else - { - max = x2; - min = x1; - } - for (int i = 1; i <= min; i++) - { - if ((max * i) % min == 0) - { - return i * max; - } - } - throw new System.ApplicationException("Cannot find the least common multiple of numbers " + x1 + " and " + x2); - } - - /// Method that calculates the Least Common Multiple (LCM) of several - /// positive integer numbers. - /// - /// - /// Array containing the numbers. - /// - /// - public static int lcm(int[] x) - { - if (x.Length < 2) - { - throw new System.ApplicationException("Do not use this method if there are less than" + " two numbers."); - } - int tmp = lcm(x[x.Length - 1], x[x.Length - 2]); - for (int i = x.Length - 3; i >= 0; i--) - { - if (x[i] <= 0) - { - throw new System.ArgumentException("Cannot compute the least " + "common multiple of " + "several numbers where " + "one, at least," + "is negative."); - } - tmp = lcm(tmp, x[i]); - } - return tmp; - } - - /// Method that calculates the Greatest Common Divisor (GCD) of two - /// positive integer numbers. - /// - /// - public static int gcd(int x1, int x2) - { - if (x1 < 0 || x2 < 0) - { - throw new System.ArgumentException("Cannot compute the GCD " + "if one integer is negative."); - } - int a, b, g, z; - - if (x1 > x2) - { - a = x1; - b = x2; - } - else - { - a = x2; - b = x1; - } - - if (b == 0) - return 0; - - g = b; - - while (g != 0) - { - z = a % g; - a = g; - g = z; - } - return a; - } - - /// Method that calculates the Greatest Common Divisor (GCD) of several - /// positive integer numbers. - /// - /// - /// Array containing the numbers. - /// - /// - public static int gcd(int[] x) - { - if (x.Length < 2) - { - throw new System.ApplicationException("Do not use this method if there are less than" + " two numbers."); - } - int tmp = gcd(x[x.Length - 1], x[x.Length - 2]); - for (int i = x.Length - 3; i >= 0; i--) - { - if (x[i] < 0) - { - throw new System.ArgumentException("Cannot compute the least " + "common multiple of " + "several numbers where " + "one, at least," + "is negative."); - } - tmp = gcd(tmp, x[i]); - } - return tmp; - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/util/MsgLogger.cs b/CSJ2K/j2k/util/MsgLogger.cs deleted file mode 100644 index 2e5b6ee8..00000000 --- a/CSJ2K/j2k/util/MsgLogger.cs +++ /dev/null @@ -1,135 +0,0 @@ -/* -* CVS identifier: -* -* $Id: MsgLogger.java,v 1.7 2001/08/17 16:24:51 grosbois Exp $ -* -* Class: MsgLogger -* -* Description: Facility to log messages (abstract) -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -namespace CSJ2K.j2k.util -{ - - /// This class provides a simple common abstraction of a facility that logs - /// and/or displays messages or simple strings. The underlying facility can be - /// a terminal, text file, text area in a GUI display, dialog boxes in a GUI - /// display, etc., or a combination of those. - /// - /// <>Messages are short strings (a couple of lines) that indicate some state - /// of the program, and that have a severity code associated with them (see - /// below). Simple strings is text (can be long) that has no severity code - /// associated with it. Typical use of simple strings is to display help - /// texts.

    - /// - ///

    Each message has a severity code, which can be one of the following: - /// LOG, INFO, WARNING, ERROR. Each implementation should treat each severity - /// code in a way which corresponds to the type of diplay used.

    - /// - ///

    Messages are printed via the 'printmsg()' method. Simple strings are - /// printed via the 'print()', 'println()' and 'flush()' methods, each simple - /// string is considered to be terminated once the 'flush()' method has been - /// called. The 'printmsg()' method should never be called before a previous - /// simple string has been terminated.

    - /// - ///
    - public struct MsgLogger_Fields - { - /// Severity of message. LOG messages are just for bookkeeping and do not - /// need to be displayed in the majority of cases - /// - public const int LOG = 0; - /// Severity of message. INFO messages should be displayed just for user - /// feedback. - /// - public const int INFO = 1; - /// Severity of message. WARNING messages denote that an unexpected state - /// has been reached and should be given as feedback to the user. - /// - public const int WARNING = 2; - /// Severity of message. ERROR messages denote that something has gone - /// wrong and probably that execution has ended. They should be definetely - /// displayed to the user. - /// - public const int ERROR = 3; - } - public interface MsgLogger - { - //UPGRADE_NOTE: Members of interface 'MsgLogger' were extracted into structure 'MsgLogger_Fields'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1045'" - - /// Prints the message 'msg' to the output device, appending a newline, - /// with severity 'sev'. Some implementations where the appended newline is - /// irrelevant may not append the newline. Depending on the implementation - /// the severity of the message may be added to it. The message is - /// reformatted as appropriate for the output devic, but any newline - /// characters are respected. - /// - /// - /// The message severity (LOG, INFO, etc.) - /// - /// - /// The message to display - /// - /// - void printmsg(int sev, System.String msg); - - /// Prints the string 'str' to the output device, appending a line - /// return. The message is reformatted as appropriate to the particular - /// diplaying device, where 'flind' and 'ind' are used as hints for - /// performing that operation. However, any newlines appearing in 'str' are - /// respected. The output device may not display the string until flush() - /// is called. Some implementations may automatically flush when this - /// method is called. This method just prints the string, the string does - /// not make part of a "message" in the sense that no severity is - /// associated to it. - /// - /// - /// The string to print - /// - /// - /// Indentation of the first line - /// - /// - /// Indentation of any other lines. - /// - /// - void println(System.String str, int flind, int ind); - - /// Writes any buffered data from the println() method to the device. - /// - /// - void flush(); - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/util/MsgPrinter.cs b/CSJ2K/j2k/util/MsgPrinter.cs deleted file mode 100644 index b3ab3a18..00000000 --- a/CSJ2K/j2k/util/MsgPrinter.cs +++ /dev/null @@ -1,321 +0,0 @@ -/* -* CVS identifier: -* -* $Id: MsgPrinter.java,v 1.6 2000/09/05 09:25:24 grosbois Exp $ -* -* Class: MsgPrinter -* -* Description: Prints messages formatted for a specific -* line width. -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* -* -* -*/ -namespace CSJ2K.j2k.util -{ - - /// This utility class formats messages to the specified line width, by - /// inserting line-breaks between words, and printing the resulting - /// lines. - /// - /// - public class MsgPrinter - { - //UPGRADE_NOTE: Respective javadoc comments were merged. It should be changed in order to comply with .NET documentation conventions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1199'" - /// Returns the line width that is used for formatting. - /// - /// - /// The line width used for formatting - /// - /// - /// - /// - /// Sets the line width to the specified value. This new value will - /// be used in subsequent calls to the print() message. - /// - /// - /// The new line width to use (in cahracters) - /// - /// - /// - /// - virtual public int LineWidth - { - get - { - return lw; - } - - set - { - if (value < 1) - { - throw new System.ArgumentException(); - } - lw = value; - } - - } - - /// The line width to use - public int lw; - - /// Signals that a newline was found - private const int IS_NEWLINE = -2; - - /// Signals that the end-of-string was reached - private const int IS_EOS = -1; - - /// Creates a new message printer with the specified line width and - /// with the default locale. - /// - /// - /// The line width for which to format (in - /// characters) - /// - /// - /// - /// - public MsgPrinter(int linewidth) - { - lw = linewidth; - } - - /// Formats the message to print in the current line width, by - /// breaking the message into lines between words. The number of - /// spaces to indent the first line is specified by 'flind' and the - /// number of spaces to indent each of the following lines is - /// specified by 'ind'. Newlines in 'msg' are respected. A newline is - /// always printed at the end. - /// - /// - /// Where to print the message. - /// - /// - /// The indentation for the first line. - /// - /// - /// The indentation for the other lines. - /// - /// - /// The message to format and print. - /// - /// - /// - /// - public virtual void print(System.IO.StreamWriter out_Renamed, int flind, int ind, System.String msg) - { - int start, end, pend, efflw, lind, i; - - start = 0; - end = 0; - pend = 0; - efflw = lw - flind; - lind = flind; - while ((end = nextLineEnd(msg, pend)) != IS_EOS) - { - if (end == IS_NEWLINE) - { - // Forced line break - for (i = 0; i < lind; i++) - { - out_Renamed.Write(" "); - } - //UPGRADE_TODO: Method 'java.io.PrintWriter.println' was converted to 'System.IO.TextWriter.WriteLine' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioPrintWriterprintln_javalangString'" - out_Renamed.WriteLine(msg.Substring(start, (pend) - (start))); - if (nextWord(msg, pend) == msg.Length) - { - // Traling newline => print it and done - //UPGRADE_TODO: Method 'java.io.PrintWriter.println' was converted to 'System.IO.TextWriter.WriteLine' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioPrintWriterprintln_javalangString'" - out_Renamed.WriteLine(""); - start = pend; - break; - } - } - else - { - if (efflw > end - pend) - { - // Room left on current line - efflw -= (end - pend); - pend = end; - continue; - } - else - { - // Filled-up current line => print it - for (i = 0; i < lind; i++) - { - out_Renamed.Write(" "); - } - if (start == pend) - { - // Word larger than line width - // Print anyways - //UPGRADE_TODO: Method 'java.io.PrintWriter.println' was converted to 'System.IO.TextWriter.WriteLine' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioPrintWriterprintln_javalangString'" - out_Renamed.WriteLine(msg.Substring(start, (end) - (start))); - pend = end; - } - else - { - //UPGRADE_TODO: Method 'java.io.PrintWriter.println' was converted to 'System.IO.TextWriter.WriteLine' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioPrintWriterprintln_javalangString'" - out_Renamed.WriteLine(msg.Substring(start, (pend) - (start))); - } - } - } - // Initialize for next line - lind = ind; - efflw = lw - ind; - start = nextWord(msg, pend); - pend = start; - if (start == IS_EOS) - { - break; // Did all the string - } - } - if (pend != start) - { - // Part of a line left => print it - for (i = 0; i < lind; i++) - { - out_Renamed.Write(" "); - } - //UPGRADE_TODO: Method 'java.io.PrintWriter.println' was converted to 'System.IO.TextWriter.WriteLine' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioPrintWriterprintln_javalangString'" - out_Renamed.WriteLine(msg.Substring(start, (pend) - (start))); - } - } - - /// Returns the index of the last character of the next word, plus 1, or - /// IS_NEWLINE if a newline character is encountered before the next word, - /// or IS_EOS if the end of the string is ecnounterd before the next - /// word. The method first skips all whitespace characters at or after - /// 'from', except newlines. If a newline is found IS_NEWLINE is - /// returned. Then it skips all non-whitespace characters and returns the - /// position of the last non-whitespace character, plus 1. The returned - /// index may be greater than the last valid index in the tsring, but it is - /// always suitable to be used in the String.substring() method. - /// - ///

    Non-whitespace characters are defined as in the - /// Character.isWhitespace method (that method is used). - /// - ///

    - /// The string to parse - /// - /// - /// The index of the first position to search from - /// - /// - /// The index of the last character in the next word, plus 1, - /// IS_NEWLINE, or IS_EOS if there are no more words. - /// - /// - /// - /// - private int nextLineEnd(System.String str, int from) - { - //UPGRADE_NOTE: Final was removed from the declaration of 'len '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - int len = str.Length; - char c = '\x0000'; - // First skip all whitespace, except new line - while (from < len && (c = str[from]) != '\n' && System.Char.IsWhiteSpace(c)) - { - from++; - } - if (c == '\n') - { - return IS_NEWLINE; - } - if (from >= len) - { - return IS_EOS; - } - // Now skip word characters - while (from < len && !System.Char.IsWhiteSpace(str[from])) - { - from++; - } - return from; - } - - /// Returns the position of the first character in the next word, starting - /// from 'from', if a newline is encountered first then the index of the - /// newline character plus 1 is returned. If the end of the string is - /// encountered then IS_EOS is returned. Words are defined as any - /// concatenation of 1 or more characters which are not - /// whitespace. Whitespace characters are those for which - /// Character.isWhitespace() returns true (that method is used). - /// - ///

    Non-whitespace characters are defined as in the - /// Character.isWhitespace method (that method is used). - /// - ///

    - /// The string to parse - /// - /// - /// The index where to start parsing - /// - /// - /// The index of the first character of the next word, or the index - /// of the newline plus 1, or IS_EOS. - /// - /// - /// - /// - private int nextWord(System.String str, int from) - { - //UPGRADE_NOTE: Final was removed from the declaration of 'len '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - int len = str.Length; - char c = '\x0000'; - // First skip all whitespace, but new lines - while (from < len && (c = str[from]) != '\n' && System.Char.IsWhiteSpace(c)) - { - from++; - } - if (from >= len) - { - return IS_EOS; - } - else if (c == '\n') - { - return from + 1; - } - else - { - return from; - } - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/util/ParameterList.cs b/CSJ2K/j2k/util/ParameterList.cs deleted file mode 100644 index 03903829..00000000 --- a/CSJ2K/j2k/util/ParameterList.cs +++ /dev/null @@ -1,578 +0,0 @@ -/* -* CVS identifier: -* -* $Id: ParameterList.java,v 1.18 2001/07/17 16:21:35 grosbois Exp $ -* -* Class: ParameterList -* -* Description: Class to hold parameters. -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using System; -namespace CSJ2K.j2k.util -{ - - /// This class holds modules options and parameters as they are provided to the - /// encoder or the decoder. Each option and its associated parameters are - /// stored as strings. - /// - ///

    This class is built on the standard Java Properties class. Consequently, - /// it offers facilities to load and write parameters from/to a file. In the - /// meantime, a ParameterList object can also handle default parameters for - /// each option.

    - /// - ///

    Each parameter can be retrieved as a string or as an specific primitive - /// type (int, float, etc).

    - /// - ///

    For more details see the Properties class.

    - /// - ///

    Note that this class does not support multiple occurrences of parameters - /// (for a parameter name, only one value is possible). Also there is no - /// particular order of the parameters.

    - /// - ///
    - /// - /// - /// - //UPGRADE_ISSUE: Class hierarchy differences between 'java.util.Properties' and 'System.Collections.Specialized.NameValueCollection' may cause compilation errors. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1186'" - [Serializable] - public class ParameterList : System.Collections.Specialized.NameValueCollection - { - // COVNERSION PROBLEM? - private ParameterList defaults; - - /// Returns the default ParameterList. - /// - /// - /// Default ParameterList - /// - /// - virtual public ParameterList DefaultParameterList - { - get - { - //UPGRADE_ISSUE: Field 'java.util.Properties.defaults' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javautilPropertiesdefaults_f'" - return (ParameterList)defaults; - } - - } - - /// Constructs an empty ParameterList object. It can be later completed by - /// adding elements one by one, by loading them from a file, or by - /// initializing them from an argument string. - /// - /// - //UPGRADE_TODO: Format of property file may need to be changed. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1089'" - //UPGRADE_ISSUE: Class hierarchy differences between 'java.util.Properties' and 'System.Collections.Specialized.NameValueCollection' may cause compilation errors. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1186'" - public ParameterList() : base() - { - } - - /// Constructs an empty ParameterList object with the provided default - /// parameters. The list can be later updated by adding elements one by - /// one, by loading them from a file, or by initializing them from an - /// argument string. - /// - /// - /// The defaults parameters - /// - /// - //UPGRADE_TODO: Format of property file may need to be changed. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1089'" - //UPGRADE_ISSUE: Class hierarchy differences between 'java.util.Properties' and 'System.Collections.Specialized.NameValueCollection' may cause compilation errors. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1186'" - public ParameterList(ParameterList def) : base() - { - defaults = def; - } - - /// Parses the parameters from an argument list, such as as the one in the - /// command line, and integrates them in this parameter list. - /// - ///

    All options must be preceded by '-' and then followed by one or more - /// words, which constitues the values. The name of the options constitute - /// the name of the parameters. The only exception is for boolean options, - /// in which case if they are preceded by '-' they will be turned on, and - /// if preceded by '+' they will be turned off. The string value of a - /// boolean option is "on" or "off". Note that the '-' and '+' characters - /// can not precede any word which would be a value for an option unless - /// they are numeric values (otherwise it would be considered as a boolean - /// option). Note also that the name of an option can not start with a - /// number.

    - /// - ///

    No option can appear more than once. If so happens an exception is - /// thrown.

    - /// - ///

    For instance the string: - /// - /// "-Ffilters w5x3 -Wlev 5 -Qtype reversible - /// - ///

    will create the following parameter list: - /// - ///

    -        /// Ffilers  w5x3
    -        /// Wlev     5
    -        /// Qtype    reversible
    -        /// 

    - /// - ///
    - /// The argument list. - /// - /// - /// if there are invalid arguments in - /// 'argv' - /// - /// - public virtual void parseArgs(System.String[] argv) - { - int k; - char c, c2; - System.String pname; - System.Text.StringBuilder pvalue; - - // Read options - k = -1; - // Skip empty arguments - do - { - k++; - if (k >= argv.Length) - { - // Nothing to put in parameters - return; - } - } - while (argv[k].Length <= 0); - - // Check that we start with an option and that its is not a number - c = argv[k][0]; - if (c != '-' && c != '+') - { - // It's not an option - throw new StringFormatException("Argument list does not" + " start with an option: " + argv[k]); - } - if (argv[k].Length >= 2 && System.Char.IsDigit(argv[k][1])) - { - throw new StringFormatException("Numeric option name: " + argv[k]); - } - pvalue = new System.Text.StringBuilder(); - while (k < argv.Length) - { - // Read parameter name - if (argv[k].Length <= 1) - { - throw new StringFormatException("Option \"" + argv[k] + "\" is too short."); - } - c = argv[k][0]; - pname = argv[k++]; - pvalue.Length = 0; - // Are there any more arguments? - if (k >= argv.Length) - { - // No more words in argument list => must be boolean - pvalue.Append((c == '-') ? "on" : "off"); - } - else - { - c2 = argv[k][0]; - // Is next word an option or a value? - if (c2 == '-' || c2 == '+') - { - // Next word could be an option - if (argv[k].Length <= 1) - { - throw new StringFormatException("Option or argument \"" + argv[k] + "\" too short"); - } - if (!System.Char.IsDigit(argv[k][1])) - { - // Not a number => we have a boolean option in pname - pvalue.Append((c == '-') ? "on" : "off"); - } - } - if (pvalue.Length == 0) - { - // No value yet - // It should not a boolean option, read the values - if (c == '+') - { - throw new StringFormatException("Boolean option \"" + pname + "\" has a value"); - } - // We have at least one value - pvalue.Append(argv[k++]); - while (k < argv.Length) - { - // If empty string skip it - if (argv[k].Length == 0) - { - k++; - continue; - } - c = argv[k][0]; - if (c == '-' || c == '+') - { - // Next word could be an option - if (argv[k].Length <= 1) - { - throw new StringFormatException("Option or " + "argument \"" + argv[k] + "\" too short"); - } - if (!System.Char.IsDigit(argv[k][1])) - { - // It's an option => stop - break; - } - } - pvalue.Append(' '); // Add a space - pvalue.Append(argv[k++]); - } - } - } - // Now put parameter and value in the list - /* - if (this[(System.String) pname.Substring(1)] != null) - { - // Option is repeated => ERROR - throw new StringFormatException("Option \"" + pname + "\" appears more than once"); - } - */ - System.Object tempObject; - //UPGRADE_WARNING: At least one expression was used more than once in the target code. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1181'" - tempObject = this[(System.String)pname.Substring(1)]; - this[(System.String)pname.Substring(1)] = (System.String)pvalue.ToString(); - System.Object generatedAux4 = tempObject; - } - } - - /// Returns the value of the named parameter, as a string. The value can - /// come from teh defaults, if there are. - /// - /// - /// The parameter name. - /// - /// - /// the value of the parameter as a string, or null if there is no - /// parameter with the name 'pname'. - /// - /// - public virtual System.String getParameter(System.String pname) - { - System.String pval; - - pval = ((System.String)this[(System.String)pname]); - //UPGRADE_ISSUE: Field 'java.util.Properties.defaults' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javautilPropertiesdefaults_f'" - if (pval == null && defaults != null) - { - // if parameter is not there - // Look in defaults - //UPGRADE_ISSUE: Field 'java.util.Properties.defaults' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javautilPropertiesdefaults_f'" - pval = defaults.Get(pname); - } - return pval; - } - - /// Returns the value of the named parameter as a boolean. The value "on" - /// is interpreted as 'true', while the value "off" is interpreted as - /// 'false'. If the parameter has another value then an - /// StringFormatException is thrown. If the parameter 'pname' is not in the - /// parameter list, an IllegalArgumentException is thrown. - /// - /// - /// The parameter name. - /// - /// - /// the value of the parameter as a boolean. - /// - /// - /// If the parameter has a value which is - /// neither "on" nor "off". - /// - /// - /// If there is no parameter with the - /// name 'pname' in the parameter list. - /// - /// - public virtual bool getBooleanParameter(System.String pname) - { - System.String s = (System.String)getParameter(pname); - - if (s == null) - { - throw new System.ArgumentException("No parameter with name " + pname); - } - else if (s.Equals("on")) - { - return true; - } - else if (s.Equals("off")) - { - return false; - } - else - { - throw new StringFormatException("Parameter \"" + pname + "\" is not boolean: " + s); - } - } - - /// Returns the value of the named parameter as an int. If the parameter - /// has a non-numeric value a NumberFormatException is thrown. If the - /// parameter has a multiple word value than the first word is returned as - /// an int, others are ignored. If the parameter 'pname' is not in the - /// parameter list, an IllegalArgumentException is thrown. - /// - /// - /// The parameter name. - /// - /// - /// the value of the parameter as an int. - /// - /// - /// If the parameter has a non-numeric - /// value. - /// - /// - /// If there is no parameter with the - /// name 'pname' in the parameter list. - /// - /// - public virtual int getIntParameter(System.String pname) - { - System.String s = (System.String)getParameter(pname); - - if (s == null) - { - throw new System.ArgumentException("No parameter with name " + pname); - } - else - { - try - { - return System.Int32.Parse(s); - } - catch (System.FormatException e) - { - //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Throwable.getMessage' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" - throw new System.FormatException("Parameter \"" + pname + "\" is not integer: " + e.Message); - } - } - } - - /// Returns the value of the named parameter as a float. If the parameter - /// has a non-numeric value a NumberFormatException is thrown. If the - /// parameter has a multiple word value than the first word is returned as - /// an int, others are ignored. If the parameter 'pname' is not in the - /// parameter list, an IllegalArgumentException is thrown. - /// - /// - /// The parameter name. - /// - /// - /// If the parameter has a non-numeric - /// value. - /// - /// - /// If there is no parameter with the - /// name 'pname' in the parameter list. - /// - /// - /// the value of the parameter as a float. - /// - /// - public virtual float getFloatParameter(System.String pname) - { - System.String s = (System.String)getParameter(pname); - - if (s == null) - { - throw new System.ArgumentException("No parameter with name " + pname); - } - else - { - try - { - // Unfortunately there is no method to convert from a string - // directly to a float - //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Float.floatValue' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - return (float)(System.Single.Parse(s)); - } - catch (System.FormatException e) - { - //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Throwable.getMessage' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" - throw new System.FormatException("Parameter \"" + pname + "\" is not floating-point: " + e.Message); - } - } - } - - /// Checks if the parameters which name starts with the prefix 'prfx' in - /// the parameter list are all in the list of valid parameter names - /// 'plist'. If there is a parameter that is not in 'plist' an - /// IllegalArgumentException is thrown with an explanation message. The - /// default parameters are also included in the check. - /// - /// - /// The prefix of parameters to check. - /// - /// - /// The list of valid parameter names for the 'prfx' - /// prefix. If null it is considered that no names are valid. - /// - /// - /// If there's a parameter name - /// starting with 'prfx' which is not in the valid list of parameter names. - /// - /// - public virtual void checkList(char prfx, System.String[] plist) - { - System.Collections.IEnumerator args; - System.String val; - int i; - bool isvalid; - - args = Keys.GetEnumerator(); - - //UPGRADE_TODO: Method 'java.util.Enumeration.hasMoreElements' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationhasMoreElements'" - while (args.MoveNext()) - { - //UPGRADE_TODO: Method 'java.util.Enumeration.nextElement' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationnextElement'" - val = ((System.String)args.Current); - if (val.Length > 0 && val[0] == prfx) - { - isvalid = false; - if (plist != null) - { - for (i = plist.Length - 1; i >= 0; i--) - { - if (val.Equals(plist[i])) - { - isvalid = true; - break; - } - } - } - if (!isvalid) - { - // Did not find valid flag - throw new System.ArgumentException("Option '" + val + "' is " + "not a valid one."); - } - } - } - } - - /// Checks if the parameters which names do not start with any of the - /// prefixes in 'prfxs' in this ParameterList are all in the list of valid - /// parameter names 'plist'. If there is a parameter that is not in 'plist' - /// an IllegalArgumentException is thrown with an explanation message. The - /// default parameters are also included in the check. - /// - /// - /// The prefixes of parameters to ignore. - /// - /// - /// The list of valid parameter names. If null it is - /// considered that no names are valid. - /// - /// - /// If there's a parameter name not - /// starting with 'prfx' which is not in the valid list of parameter names. - /// - /// - public virtual void checkList(char[] prfxs, System.String[] plist) - { - System.Collections.IEnumerator args; - System.String val, strprfxs; - int i; - bool isvalid; - - args = Keys.GetEnumerator(); - strprfxs = new System.String(prfxs); - - //UPGRADE_TODO: Method 'java.util.Enumeration.hasMoreElements' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationhasMoreElements'" - while (args.MoveNext()) - { - //UPGRADE_TODO: Method 'java.util.Enumeration.nextElement' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationnextElement'" - val = ((System.String)args.Current); - if (val.Length > 0 && strprfxs.IndexOf((System.Char)val[0]) == -1) - { - isvalid = false; - if (plist != null) - { - for (i = plist.Length - 1; i >= 0; i--) - { - if (val.Equals(plist[i])) - { - isvalid = true; - break; - } - } - } - if (!isvalid) - { - throw new System.ArgumentException("Option '" + val + "' is " + "not a valid one."); - } - } - } - } - - /// Converts the usage information to a list of parameter names in a single - /// array. The usage information appears in a 2D array of String. The first - /// dimensions contains the different options, the second dimension - /// contains the name of the option (first element), the synopsis and the - /// explanation. This method takes the names of the different options in - /// 'pinfo' and returns them in a single array of String. - /// - /// - /// The list of options and their usage info (see above). - /// - /// - /// An array with the names of the options in pinfo. If pinfo is - /// null, null is returned. - /// - /// - public static System.String[] toNameArray(System.String[][] pinfo) - { - System.String[] pnames; - - if (pinfo == null) - { - return null; - } - - pnames = new System.String[pinfo.Length]; - - for (int i = pinfo.Length - 1; i >= 0; i--) - { - pnames[i] = pinfo[i][0]; - } - return pnames; - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/util/ProgressWatch.cs b/CSJ2K/j2k/util/ProgressWatch.cs deleted file mode 100644 index 137024de..00000000 --- a/CSJ2K/j2k/util/ProgressWatch.cs +++ /dev/null @@ -1,61 +0,0 @@ -/* -* CVS identifier: -* -* $Id: ProgressWatch.java,v 1.1 2002/05/22 16:19:28 grosbois Exp $ -* -* Class: ProgressWatch -* -* Description: Interface defining methods for ProgressWatch objects. -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -namespace CSJ2K.j2k.util -{ - - public interface ProgressWatch - { - /// Initialize the progress watching process - /// - /// - void initProgressWatch(int min, int max, System.String info); - - /// Update the progress watching process to the specified value - /// - /// - void updateProgressWatch(int val, System.String info); - - /// Terminate the progress watch process - /// - /// - void terminateProgressWatch(); - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/util/StreamMsgLogger.cs b/CSJ2K/j2k/util/StreamMsgLogger.cs deleted file mode 100644 index e793352d..00000000 --- a/CSJ2K/j2k/util/StreamMsgLogger.cs +++ /dev/null @@ -1,243 +0,0 @@ -/* -* CVS identifier: -* -* $Id: StreamMsgLogger.java,v 1.11 2000/09/05 09:25:30 grosbois Exp $ -* -* Class: StreamMsgLogger -* -* Description: Implementation of MsgLogger for streams -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* -* -* -*/ -namespace CSJ2K.j2k.util -{ - - /// This class implements the MsgLogger interface for streams. Streams can - /// be simple files, terminals, stdout, stderr, etc. The messages or simple - /// strings are formatted using the linewidth given to the constructor. - /// - ///

    Messages are printed to the 'err' stream if they are of severity WARNING - /// or ERROR, otherwise they are printed to the 'out' stream. Simple strings - /// are always printed the 'out' stream. - /// - ///

    - public class StreamMsgLogger : MsgLogger - { - - /// The 'out' stream - private System.IO.StreamWriter out_Renamed; - - /// The 'err' stream - private System.IO.StreamWriter err; - - /// The printer that formats the text - private MsgPrinter mp; - - /// Constructs a StreamMsgLogger that uses 'outstr' as the 'out' stream, - /// and 'errstr' as the 'err' stream. Note that 'outstr' and 'errstr' can - /// be System.out and System.err. - /// - /// - /// Where to print simple strings and LOG and INFO messages. - /// - /// - /// Where to print WARNING and ERROR messages - /// - /// - /// The line width to use in formatting - /// - /// - /// - /// - public StreamMsgLogger(System.IO.Stream outstr, System.IO.Stream errstr, int lw) - { - System.IO.StreamWriter temp_writer; - temp_writer = new System.IO.StreamWriter(outstr, System.Text.Encoding.Default); - temp_writer.AutoFlush = true; - out_Renamed = temp_writer; - System.IO.StreamWriter temp_writer2; - temp_writer2 = new System.IO.StreamWriter(errstr, System.Text.Encoding.Default); - temp_writer2.AutoFlush = true; - err = temp_writer2; - mp = new MsgPrinter(lw); - } - - /// Constructs a StreamMsgLogger that uses 'outstr' as the 'out' stream, - /// and 'errstr' as the 'err' stream. Note that 'outstr' and 'errstr' can - /// be System.out and System.err. - /// - /// - /// Where to print simple strings and LOG and INFO messages. - /// - /// - /// Where to print WARNING and ERROR messages - /// - /// - /// The line width to use in formatting - /// - /// - /// - /// - //UPGRADE_ISSUE: Class hierarchy differences between 'java.io.Writer' and 'System.IO.StreamWriter' may cause compilation errors. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1186'" - public StreamMsgLogger(System.IO.StreamWriter outstr, System.IO.StreamWriter errstr, int lw) - { - System.IO.StreamWriter temp_writer; - temp_writer = new System.IO.StreamWriter(outstr.BaseStream, outstr.Encoding); - temp_writer.AutoFlush = true; - out_Renamed = temp_writer; - System.IO.StreamWriter temp_writer2; - temp_writer2 = new System.IO.StreamWriter(errstr.BaseStream, errstr.Encoding); - temp_writer2.AutoFlush = true; - err = temp_writer2; - mp = new MsgPrinter(lw); - } - - /// Constructs a StreamMsgLogger that uses 'outstr' as the 'out' stream, - /// and 'errstr' as the 'err' stream. Note that 'outstr' and 'errstr' can - /// be System.out and System.err. - /// - /// - /// Where to print simple strings and LOG and INFO messages. - /// - /// - /// Where to print WARNING and ERROR messages - /// - /// - /// The line width to use in formatting - /// - /// - /// - /// - /// - /* - public StreamMsgLogger(System.IO.StreamWriter outstr, System.IO.StreamWriter errstr, int lw) - { - out_Renamed = outstr; - err = errstr; - mp = new MsgPrinter(lw); - } - */ - /// Prints the message 'msg' to the output device, appending a newline, - /// with severity 'sev'. The severity of the message is prepended to the - /// message. - /// - /// - /// The message severity (LOG, INFO, etc.) - /// - /// - /// The message to display - /// - /// - /// - /// - public virtual void printmsg(int sev, System.String msg) - { - System.IO.StreamWriter lout; - //int ind; - System.String prefix; - - switch (sev) - { - - case CSJ2K.j2k.util.MsgLogger_Fields.LOG: - prefix = "[LOG]: "; - lout = out_Renamed; - break; - - case CSJ2K.j2k.util.MsgLogger_Fields.INFO: - prefix = "[INFO]: "; - lout = out_Renamed; - break; - - case CSJ2K.j2k.util.MsgLogger_Fields.WARNING: - prefix = "[WARNING]: "; - lout = err; - break; - - case CSJ2K.j2k.util.MsgLogger_Fields.ERROR: - prefix = "[ERROR]: "; - lout = err; - break; - - default: - throw new System.ArgumentException("Severity " + sev + " not valid."); - - } - - mp.print(lout, 0, prefix.Length, prefix + msg); - lout.Flush(); - } - - /// Prints the string 'str' to the 'out' stream, appending a newline. The - /// message is reformatted to the line width given to the constructors and - /// using 'flind' characters to indent the first line and 'ind' characters - /// to indent the second line. However, any newlines appearing in 'str' are - /// respected. The output device may or may not display the string until - /// flush() is called, depending on the autoflush state of the PrintWriter, - /// to be sure flush() should be called to write the string to the - /// device. This method just prints the string, the string does not make - /// part of a "message" in the sense that noe severity is associated to it. - /// - /// - /// The string to print - /// - /// - /// Indentation of the first line - /// - /// - /// Indentation of any other lines. - /// - /// - /// - /// - public virtual void println(System.String str, int flind, int ind) - { - mp.print(out_Renamed, flind, ind, str); - } - - /// Writes any buffered data from the print() and println() methods to the - /// device. - /// - /// - /// - /// - public virtual void flush() - { - out_Renamed.Flush(); - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/util/StringFormatException.cs b/CSJ2K/j2k/util/StringFormatException.cs deleted file mode 100644 index c09391e1..00000000 --- a/CSJ2K/j2k/util/StringFormatException.cs +++ /dev/null @@ -1,80 +0,0 @@ -/* -* CVS identifier: -* -* $Id: StringFormatException.java,v 1.9 2000/09/05 09:25:31 grosbois Exp $ -* -* Class: ArgumentFormatException -* -* Description: Exception for badly formatted string -* argument exceptions. -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* -* -* -*/ -using System; -namespace CSJ2K.j2k.util -{ - - /// Thrown to indicate that the application has attempted to parse a - /// badly formatted string. - /// - /// - [Serializable] - public class StringFormatException : System.ArgumentException - { - - /// Creates the exception with an empty messgage. - /// - /// - /// - /// - public StringFormatException() : base() - { - } - - /// Creates the exception with the specified detail message. - /// - /// - /// The detail message - /// - /// - /// - /// - public StringFormatException(System.String s) : base(s) - { - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/util/ThreadPool.cs b/CSJ2K/j2k/util/ThreadPool.cs deleted file mode 100644 index fdcc3602..00000000 --- a/CSJ2K/j2k/util/ThreadPool.cs +++ /dev/null @@ -1,647 +0,0 @@ -/* -* CVS identifier: -* -* $Id: ThreadPool.java,v 1.9 2002/05/22 15:00:55 grosbois Exp $ -* -* Class: ThreadPool -* -* Description: A pool of threads -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -namespace CSJ2K.j2k.util -{ - - /// This class implements a thread pool. The thread pool contains a set of - /// threads which can be given work to do. - /// - ///

    If the Java Virtual Machine (JVM) uses native threads, then the - /// different threads will be able to execute in different processors in - /// parallel on multiprocessors machines. However, under some JVMs and - /// operating systems using native threads is not sufficient to allow the JVM - /// access to multiple processors. This is the case when native threads are - /// implemented using POSIX threads on lightweight processes - /// (i.e. PTHREAD_SCOPE_PROCESS sopce scheduling), which is the case on most - /// UNIX operating systems. In order to do provide access to multiple - /// processors it is necessary to set the concurrency level to the number of - /// processors or slightly higher. This can be achieved by setting the Java - /// system property with the name defined by CONCURRENCY_PROP_NAME to some - /// non-negative number. This will make use of the 'NativeServices' class and - /// supporting native libraries. See 'NativeServices' for details. See - /// 'CONCURRENCY_PROP_NAME' for the name of the property. - /// - ///

    Initially the thread pool contains a user specified number of idle - /// threads. Idle threads can be given a target which is run. While running the - /// target the thread temporarily leaves the idle list. When the target - /// finishes, it joins the idle list again, waiting for a new target. When a - /// target is finished a thread can be notified on a particular object that is - /// given as a lock. - /// - ///

    Jobs can be submitted using Runnable interfaces, using the 'runTarget()' - /// methods. When the job is submitted, an idle thread will be obtained, the - /// 'run()' method of the 'Runnable' interface will be executed and when it - /// completes the thread will be returned to the idle list. In general the - /// 'run()' method should complete in a rather short time, so that the threds - /// of the pool are not starved. - /// - ///

    If using the non-asynchronous calls to 'runTarget()', it is important - /// that any target's 'run()' method, or any method called from it, does not - /// use non-asynchronous calls to 'runTarget()' on the same thread pool where - /// it was started. Otherwise this could create a dead-lock when there are not - /// enough idle threads. - /// - ///

    The pool also has a global error and runtime exception condition (one - /// for 'Error' and one for 'RuntimeException'). If a target's 'run()' method - /// throws an 'Error' or 'RuntimeException' the corresponding exception - /// condition is set and the exception object saved. In any subsequent call to - /// 'checkTargetErrors()' the saved exception object is thrown. Likewise, if a - /// target's 'run()' method throws any other subclass of 'Throwable' a new - /// 'RuntimeException' is created and saved. It will be thrown on a subsequent - /// call to 'checkTargetErrors()'. If more than one exception occurs between - /// calls to 'checkTargetErrors()' only the last one is saved. Any 'Error' - /// condition has precedence on all 'RuntimeException' conditions. The threads - /// in the pool are unaffected by any exceptions thrown by targets. - /// - ///

    The only exception to the above is the 'ThreadDeath' exception. If a - /// target's 'run()' method throws the 'ThreadDeath' exception a warning - /// message is printed and the exception is propagated, which will terminate - /// the thread in which it occurs. This could lead to instabilities of the - /// pool. The 'ThreadDeath' exception should never be thrown by the program. It - /// is thrown by the Java(TM) Virtual Machine when Thread.stop() is - /// called. This method is deprecated and should never be called. - /// - ///

    All the threads in the pool are "daemon" threads and will automatically - /// terminate when no daemon threads are running. - /// - ///

    - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - public class ThreadPool - { - /// Returns the size of the pool. That is the number of threads in this - /// pool (idle + busy). - /// - /// - /// The pool's size. - /// - /// - /// - virtual public int Size - { - get - { - return idle.Length; - } - - } - - /// The name of the property that sets the concurrency level: - /// jj2000.j2k.util.ThreadPool.concurrency - /// - public const System.String CONCURRENCY_PROP_NAME = "jj2000.j2k.util.ThreadPool.concurrency"; - - /// The array of idle threads and the lock for the manipulation of the - /// idle thread list. - /// - private ThreadPoolThread[] idle; - - /// The number of idle threads - private int nidle; - - /// The name of the pool - private System.String poolName; - - /// The priority for the pool - private int poolPriority; - - /// The last error thrown by a target. Null if none - // NOTE: needs to be volatile, so that only one copy exits in memory - private volatile System.ApplicationException targetE; - - /// The last runtime exception thrown by a target. Null if none - // NOTE: needs to be volatile, so that only one copy exits in memory - private volatile System.SystemException targetRE; - - //UPGRADE_NOTE: Field 'EnclosingInstance' was added to class 'ThreadPoolThread' to access its enclosing instance. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1019'" - /// The threads that are managed by the pool. - /// - /// - internal class ThreadPoolThread : SupportClass.ThreadClass - { - private void InitBlock(ThreadPool enclosingInstance) - { - this.enclosingInstance = enclosingInstance; - } - private ThreadPool enclosingInstance; - public ThreadPool Enclosing_Instance - { - get - { - return enclosingInstance; - } - - } - private IThreadRunnable target; - private System.Object lock_Renamed; - private bool doNotifyAll; - - /// Creates a ThreadPoolThread object, setting its name according to - /// the given 'idx', daemon type and the priority to the one of the - /// pool. - /// - /// - /// The index of this thread in the pool - /// - /// - /// The name of the thread - /// - /// - public ThreadPoolThread(ThreadPool enclosingInstance, int idx, System.String name) : base(name) - { - InitBlock(enclosingInstance); - IsBackground = true; - //UPGRADE_TODO: The differences in the type of parameters for method 'java.lang.Thread.setPriority' may cause compilation errors. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1092'" - Priority = (System.Threading.ThreadPriority)Enclosing_Instance.poolPriority; - } - - /// The method that is run by the thread. This method first joins the - /// idle state in the pool and then enters an infinite loop. In this - /// loop it waits until a target to run exists and runs it. Once the - /// target's run() method is done it re-joins the idle state and - /// notifies the waiting lock object, if one exists. - /// - ///

    An interrupt on this thread has no effect other than forcing a - /// check on the target. Normally the target is checked every time the - /// thread is woken up by notify, no interrupts should be done. - /// - ///

    Any exception thrown by the target's 'run()' method is catched - /// and this thread is not affected, except for 'ThreadDeath'. If a - /// 'ThreadDeath' exception is catched a warning message is printed by - /// the 'FacilityManager' and the exception is propagated up. For - /// exceptions which are subclasses of 'Error' or 'RuntimeException' - /// the corresponding error condition is set and this thread is not - /// affected. For any other exceptions a new 'RuntimeException' is - /// created and the error condition is set, this thread is not affected. - /// - ///

    - override public void Run() - { - // Join the idle threads list - Enclosing_Instance.putInIdleList(this); - // Permanently lock the object while running so that target can - // not be changed until we are waiting again. While waiting for a - // target the lock is released. - lock (this) - { - while (true) - { - // Wait until we get a target - while (target == null) - { - try - { - System.Threading.Monitor.Wait(this); - } - catch (System.Threading.ThreadInterruptedException) - { - } - } - // Run the target and catch all possible errors - try - { - target.Run(); - } - //UPGRADE_NOTE: Exception 'java.lang.ThreadDeath' was converted to 'System.ApplicationException' which has different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1100'" - catch (System.Threading.ThreadAbortException td) - { - // We have been instructed to abruptly terminate - // the thread, which should never be done. This can - // cause another thread, or the system, to lock. - FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.WARNING, "Thread.stop() called on a ThreadPool " + "thread or ThreadDeath thrown. This is " + "deprecated. Lock-up might occur."); - throw td; - } - catch (System.ApplicationException e) - { - Enclosing_Instance.targetE = e; - } - catch (System.SystemException re) - { - Enclosing_Instance.targetRE = re; - } - //UPGRADE_NOTE: Exception 'java.lang.Throwable' was converted to 'System.Exception' which has different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1100'" - catch (System.Exception) - { - // A totally unexpected error has occurred - // (Thread.stop(Throwable) has been used, which should - // never be. - Enclosing_Instance.targetRE = new System.SystemException("Unchecked exception " + "thrown by target's " + "run() method in pool " + Enclosing_Instance.poolName + "."); - } - // Join idle threads - Enclosing_Instance.putInIdleList(this); - // Release the target and notify lock (i.e. wakeup) - target = null; - if (lock_Renamed != null) - { - lock (lock_Renamed) - { - if (doNotifyAll) - { - System.Threading.Monitor.PulseAll(lock_Renamed); - } - else - { - System.Threading.Monitor.Pulse(lock_Renamed); - } - } - } - } - } - } - - /// Assigns a target to this thread, with an optional notify lock and a - /// notify mode. The another target is currently running the method - /// will block until it terminates. After setting the new target the - /// runner thread will be wakenup and execytion will start. - /// - /// - /// The runnable object containing the 'run()' method to - /// run. - /// - /// - /// An object on which notify will be called once the - /// target's run method has finished. A thread to be notified should be - /// waiting on that object. If null no thread is notified. - /// - /// - /// If true 'notifyAll()', instead of 'notify()', will - /// be called on tghe lock. - /// - /// - //UPGRADE_NOTE: Synchronized keyword was removed from method 'setTarget'. Lock expression was added. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1027'" - internal virtual void setTarget(IThreadRunnable target, System.Object lock_Renamed, bool notifyAll) - { - lock (this) - { - // Set the target - this.target = target; - this.lock_Renamed = lock_Renamed; - doNotifyAll = notifyAll; - // Wakeup the thread - System.Threading.Monitor.Pulse(this); - } - } - } - - /// Creates a new thread pool of the given size, thread priority and pool - /// name. - /// - ///

    If the Java system property of the name defined by - /// 'CONCURRENCY_PROP_NAME' is set, then an attempt will be made to load - /// the library that supports concurrency setting (see - /// 'NativeServices'). If that succeds the concurrency level will be set to - /// the specified value. Otherwise a warning is printed. - /// - ///

    - /// The size of the pool (number of threads to create in the - /// pool). - /// - /// - /// The priority to give to the threads in the pool. If - /// less than 'Thread.MIN_PRIORITY' it will be the same as the priority of - /// the calling thread. - /// - /// - /// The name of the pool. If null a default generic name is - /// chosen. - /// - /// - /// - /// - /// - /// - /// - /// - public ThreadPool(int size, int priority, System.String name) - { - int i; - ThreadPoolThread t; - //System.String prop; - //int clevel; - - // Initialize variables checking for special cases - if (size <= 0) - { - throw new System.ArgumentException("Pool must be of positive size"); - } - if (priority < (int)System.Threading.ThreadPriority.Lowest) - { - poolPriority = (System.Int32)SupportClass.ThreadClass.Current().Priority; - } - else - { - poolPriority = (priority < (int)System.Threading.ThreadPriority.Highest) ? priority : (int)System.Threading.ThreadPriority.Highest; - } - if (name == null) - { - poolName = "Anonymous ThreadPool"; - } - else - { - poolName = name; - } - - // Allocate internal variables - idle = new ThreadPoolThread[size]; - nidle = 0; - - // Create and start the threads - for (i = 0; i < size; i++) - { - t = new ThreadPoolThread(this, i, poolName + "-" + i); - t.Start(); - } - } - - /// Runs the run method of the specified target in an idle thread of this - /// pool. When the target's run method completes, the thread waiting on the - /// lock object is notified, if any. If there is currently no idle thread - /// the method will block until a thread of the pool becomes idle or the - /// calling thread is interrupted. - /// - ///

    This method is the same as runTarget(t,l,true,false). - /// - ///

    - /// The target. The 'run()' method of this object will be run in - /// an idle thread of the pool. - /// - /// - /// The lock object. A thread waiting on the lock of the 'l' - /// object will be notified, through the 'notify()' call, when the target's - /// run method completes. If null no thread is notified. - /// - /// - /// True if the target was submitted to some thread. False if no - /// idle thread could be found and the target was not submitted for - /// execution. - /// - /// - /// - public virtual bool runTarget(IThreadRunnable t, System.Object l) - { - return runTarget(t, l, false, false); - } - - /// Runs the run method of the specified target in an idle thread of this - /// pool. When the target's run method completes, the thread waiting on the - /// lock object is notified, if any. If there is currently no idle thread - /// and the asynchronous mode is not used the method will block until a - /// thread of the pool becomes idle or the calling thread is - /// interrupted. If the asynchronous mode is used then the method will not - /// block and will return false. - /// - ///

    This method is the same as runTarget(t,l,async,false). - /// - ///

    - /// The target. The 'run()' method of this object will be run in - /// an idle thread of the pool. - /// - /// - /// The lock object. A thread waiting on the lock of the 'l' - /// object will be notified, through the 'notify()' call, when the target's - /// run method completes. If null no thread is notified. - /// - /// - /// If true the asynchronous mode will be used. - /// - /// - /// True if the target was submitted to some thread. False if no - /// idle thread could be found and the target was not submitted for - /// execution. - /// - /// - /// - public virtual bool runTarget(IThreadRunnable t, System.Object l, bool async) - { - return runTarget(t, l, async, false); - } - - /// Runs the run method of the specified target in an idle thread of this - /// pool. When the target's run method completes, the thread waiting on the - /// lock object is notified, if any. If there is currently no idle thread - /// and the asynchronous mode is not used the method will block until a - /// thread of the pool becomes idle or the calling thread is - /// interrupted. If the asynchronous mode is used then the method will not - /// block and will return false. - /// - /// - /// The target. The 'run()' method of this object will be run in - /// an idle thread of the pool. - /// - /// - /// The lock object. A thread waiting on the lock of the 'l' - /// object will be notified, through the 'notify()' call, when the target's - /// run method completes. If null no thread is notified. - /// - /// - /// If true the asynchronous mode will be used. - /// - /// - /// If true, threads waiting on the lock of the 'l' object - /// will be notified trough the 'notifyAll()' instead of the normal - /// 'notify()' call. This is not normally needed. - /// - /// - /// True if the target was submitted to some thread. False if no - /// idle thread could be found and the target was not submitted for - /// execution. - /// - /// - /// - public virtual bool runTarget(IThreadRunnable t, System.Object l, bool async, bool notifyAll) - { - ThreadPoolThread runner; // The thread to run the target - - // Get a thread to run - runner = getIdle(async); - // If no runner return failure - if (runner == null) - return false; - // Set the runner - runner.setTarget(t, l, notifyAll); - return true; - } - - /// Checks that no error or runtime exception in any target have occurred - /// so far. If an error or runtime exception has occurred in a target's run - /// method they are thrown by this method. - /// - /// - /// If an error condition has been thrown by a target - /// 'run()' method. - /// - /// - /// If a runtime exception has been thrown by a - /// target 'run()' method. - /// - /// - public virtual void checkTargetErrors() - { - // Check for Error - if (targetE != null) - throw targetE; - // Check for RuntimeException - if (targetRE != null) - throw targetRE; - } - - /// Clears the current target error conditions, if any. Note that a thread - /// in the pool might have set the error conditions since the last check - /// and that those error conditions will be lost. Likewise, before - /// returning from this method another thread might set the error - /// conditions. There is no guarantee that no error conditions exist when - /// returning from this method. - /// - ///

    In order to ensure that no error conditions exist when returning - /// from this method cooperation from the targets and the thread using this - /// pool is necessary (i.e. currently no targets running or waiting to - /// run). - /// - ///

    - public virtual void clearTargetErrors() - { - // Clear the error and runtime exception conditions - targetE = null; - targetRE = null; - } - - /// Puts the thread 't' in the idle list. The thread 't' should be in fact - /// idle and ready to accept a new target when it joins the idle list. - /// - ///

    An idle thread that is already in the list should never add itself - /// to the list before it is removed. For efficiency reasons there is no - /// check to see if the thread is already in the list of idle threads. - /// - ///

    If the idle list was empty 'notify()' will be called on the 'idle' - /// array, to wake up a thread that might be waiting (within the - /// 'getIdle()' method) on an idle thread to become available. - /// - ///

    - /// The thread to put in the idle list. - /// - /// - private void putInIdleList(ThreadPoolThread t) - { - // NOTE: if already in idle => catastrophe! (should be OK since // - // this is private method) - // Lock the idle array to avoid races with 'getIdle()' - lock (idle) - { - idle[nidle] = t; - nidle++; - // If idle array was empty wakeup any waiting threads. - if (nidle == 1) - System.Threading.Monitor.Pulse(idle); - } - } - - /// Returns and idle thread and removes it from the list of idle - /// threads. In asynchronous mode it will immediately return an idle - /// thread, or null if none is available. In non-asynchronous mode it will - /// block until a thread of the pool becomes idle or the calling thread is - /// interrupted. - /// - ///

    If in non-asynchronous mode and there are currently no idle threads - /// available the calling thread will wait on the 'idle' array lock, until - /// notified by 'putInIdleList()' that an idle thread might have become - /// available. - /// - ///

    - /// If true asynchronous mode is used. - /// - /// - /// An idle thread of the pool, that has been removed from the idle - /// list, or null if none is available. - /// - /// - private ThreadPoolThread getIdle(bool async) - { - // Lock the idle array to avoid races with 'putInIdleList()' - lock (idle) - { - if (async) - { - // In asynchronous mode just return null if no idle thread - if (nidle == 0) - return null; - } - else - { - // In synchronous mode wait until a thread becomes idle - while (nidle == 0) - { - try - { - System.Threading.Monitor.Wait(idle); - } - catch (System.Threading.ThreadInterruptedException) - { - // If we were interrupted just return null - return null; - } - } - } - // Decrease the idle count and return one of the idle threads - nidle--; - return idle[nidle]; - } - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/wavelet/FilterTypes.cs b/CSJ2K/j2k/wavelet/FilterTypes.cs deleted file mode 100644 index cb6a1323..00000000 --- a/CSJ2K/j2k/wavelet/FilterTypes.cs +++ /dev/null @@ -1,67 +0,0 @@ -/* -* CVS identifier: -* -* $Id: FilterTypes.java,v 1.12 2001/05/08 16:14:28 grosbois Exp $ -* -* Class: FilterTypes -* -* Description: Defines the interface for Filter types -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -namespace CSJ2K.j2k.wavelet -{ - - /// This interface defines the identifiers for the different types of filters - /// that are supported. - /// - ///

    The identifier values are the same as those used in the codestream - /// syntax, for the filters that are defined in the standard.

    - /// - ///
    - public struct FilterTypes_Fields - { - /// W7x9 filter: 0x00 - public const int W9X7 = 0; - /// W5x3 filter: 0x01 - public const int W5X3 = 1; - /// User-defined filter: -1 - public const int CUSTOM = -1; - } - public interface FilterTypes - { - //UPGRADE_NOTE: Members of interface 'FilterTypes' were extracted into structure 'FilterTypes_Fields'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1045'" - - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/wavelet/Subband.cs b/CSJ2K/j2k/wavelet/Subband.cs deleted file mode 100644 index d859b300..00000000 --- a/CSJ2K/j2k/wavelet/Subband.cs +++ /dev/null @@ -1,642 +0,0 @@ -/* -* CVS identifier: -* -* $Id: Subband.java,v 1.47 2001/10/18 14:27:14 grosbois Exp $ -* -* Class: Subband -* -* Description: Asbtract element for a tree strcuture for -* a description of subbands. -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.image; -namespace CSJ2K.j2k.wavelet -{ - - /// This abstract class represents a subband in a bidirectional tree structure - /// that describes the subband decomposition for a wavelet transform. This - /// class is implemented by the SubbandAn and SubbandSyn classes, which are for - /// the analysis and synthesis sides respectively. - /// - ///

    The element can be either a node or a leaf of the tree. If it is a node, - /// it has 4 descendants (LL, HL, LH and HH). If it is a leaf, it has no - /// descendant.

    - /// - ///

    The tree is bidirectional. Each element in the tree structure has a - /// "parent", which is the subband from which the element was obtained by - /// decomposition. The only exception is the root element which, for obvious - /// reasons, has no parent (i.e. it is null).

    - /// - ///
    - /// - /// - /// - /// - /// - public abstract class Subband - { - /// Returns the parent of this subband. The parent of a subband is the - /// subband from which this one was obtained by decomposition. The root - /// element has no parent subband (null). - /// - /// - /// The parent subband, or null for the root one. - /// - /// - public abstract Subband Parent { get; } - /// Returns the LL child subband of this subband. - /// - /// - /// The LL child subband, or null if there are no childs. - /// - /// - public abstract Subband LL { get; } - /// Returns the HL (horizontal high-pass) child subband of this subband. - /// - /// - /// The HL child subband, or null if there are no childs. - /// - /// - public abstract Subband HL { get; } - /// Returns the LH (vertical high-pass) child subband of this subband. - /// - /// - /// The LH child subband, or null if there are no childs. - /// - /// - public abstract Subband LH { get; } - /// Returns the HH child subband of this subband. - /// - /// - /// The HH child subband, or null if there are no childs. - /// - /// - public abstract Subband HH { get; } - /// Returns the first leaf subband element in the next higher resolution - /// level. - /// - /// - /// The first leaf element in the next higher resolution level, or - /// null if there is no higher resolution level. - /// - /// - virtual public Subband NextResLevel - { - get - { - Subband sb; - - if (level == 0) - { - // No higher res. level - return null; - } - // Go up until we get to a different resolution level - sb = this; - do - { - sb = sb.Parent; - if (sb == null) - { - // No higher resolution level - return null; - } - } - while (sb.resLvl == resLvl); - // Now go down to HL, which is in next higher resolution level - sb = sb.HL; - // Now go down LL until get to a leaf - while (sb.isNode) - { - sb = sb.LL; - } - return sb; - } - - } - /// This function returns the horizontal wavelet filter relevant to this - /// subband - /// - /// - /// The horizontal wavelet filter - /// - /// - public abstract WaveletFilter HorWFilter { get; } - /// This function returns the vertical wavelet filter relevant to this - /// subband - /// - /// - /// The vertical wavelet filter - /// - /// - public abstract WaveletFilter VerWFilter { get; } - - /// The ID for the LL orientation - public const int WT_ORIENT_LL = 0; - - /// The ID for the HL (horizontal high-pass) orientation - public const int WT_ORIENT_HL = 1; - - /// The ID for the LH (vertical high-pass) orientation - public const int WT_ORIENT_LH = 2; - - /// The ID for the HH orientation - public const int WT_ORIENT_HH = 3; - - /// True if it is a node in the tree, false if it is a leaf. - public bool isNode; - - /// The orientation of this subband (WT_ORIENT_LL, WT_ORIENT_HL, - /// WT_ORIENT_LH, WT_ORIENT_HH). - /// - public int orientation; - - /// The level in the tree to which this subband belongs, which is the - /// number of performed wavelet decompositions to get this subband. It is 0 - /// for the top-level (i.e. root) node. - /// - public int level; - - /// The resolution level to which this subband contributes. 0 is the - /// smallest resolution level (the one with the lowest frequency LL - /// subband). - /// - public int resLvl; - - /// The number of code-blocks (in both directions) contained in this - /// subband. - /// - public Coord numCb = null; - - /// The base 2 exponent of the analysis gain of the subband. The analysis - /// gain of a subband is defined as the gain of the previous subband - /// (i.e. the one from which this one was obtained) multiplied by the line - /// gain and by the column gain. The line (column) gain is the gain of the - /// line (column) filter that was used to obtain it, which is the DC gain - /// for a low-pass filter and the Nyquist gain for a high-pass filter. It - /// is 0 by default. - /// - ///

    Using the base 2 exponent of the value contrains the possible gains - /// to powers of 2. However this is perfectly compatible to the filter - /// normalization policy assumed here. See the split() method for more - /// details.

    - /// - ///
    - /// - /// - /// - public int anGainExp; - - /// The subband index within its resolution level. This value uniquely - /// identifies a subband within a resolution level and a decomposition - /// level within it. Note that only leaf elements represent "real" - /// subbands, while node elements represent only intermediate stages. - /// - ///

    It is defined recursively. The root node gets a value of 0. For a - /// given node, with a subband index 'b', its LL descendant gets 4*b, its - /// HL descendant 4*b+1, its LH descendant 4*b+2, and its HH descendant - /// 4*b+3, for their subband indexes.

    - /// - ///
    - public int sbandIdx = 0; - - /// The horizontal coordinate of the upper-left corner of the subband, with - /// respect to the canvas origin, in the component's grid and subband's - /// decomposition level. This is the real horizontal index of the first - /// column of this subband. If even the horizontal decomposition of this - /// subband should be done with the low-pass-first convention. If odd it - /// should be done with the high-pass-first convention. - /// - /// - public int ulcx; - - /// The vertical coordinate of the upper-left corner of the subband, with - /// respect to the canvas origin, in the component's grid and subband's - /// decomposition level. This is the real vertical index of the first - /// column of this subband. If even the vertical decomposition of this - /// subband should be done with the low-pass-first convention. If odd it - /// should be done with the high-pass-first convention. - /// - /// - public int ulcy; - - /// The horizontal coordinate of the upper-left corner of the subband - public int ulx; - - /// The vertical coordinate of the upper-left corner of the subband - public int uly; - - /// The width of the subband - public int w; - - /// The height of the subband - public int h; - - /// The nominal code-block width - public int nomCBlkW; - - /// The nominal code-block height - public int nomCBlkH; - - /// Splits the current subband in its four subbands. This creates the four - /// childs (LL, HL, LH and HH) and converts the leaf in a node. - /// - /// - /// The horizontal wavelet filter used to decompose this - /// subband. - /// - /// - /// The vertical wavelet filter used to decompose this - /// subband. - /// - /// - /// A reference to the LL leaf (getLL()). - /// - /// - protected internal abstract Subband split(WaveletFilter hfilter, WaveletFilter vfilter); - - /// Initializes the childs of this node with the correct values. The sizes - /// of the child subbands are calculated by taking into account the - /// position of the subband in the canvas. - /// - ///

    For the analysis subband gain calculation it is assumed that - /// analysis filters are normalized with a DC gain of 1 and a Nyquist gain - /// of 2.

    - /// - ///
    - protected internal virtual void initChilds() - { - Subband subb_LL = LL; - Subband subb_HL = HL; - Subband subb_LH = LH; - Subband subb_HH = HH; - - // LL subband - subb_LL.level = level + 1; - subb_LL.ulcx = (ulcx + 1) >> 1; - subb_LL.ulcy = (ulcy + 1) >> 1; - subb_LL.ulx = ulx; - subb_LL.uly = uly; - subb_LL.w = ((ulcx + w + 1) >> 1) - subb_LL.ulcx; - subb_LL.h = ((ulcy + h + 1) >> 1) - subb_LL.ulcy; - // If this subband in in the all LL path (i.e. it's global orientation - // is LL) then child LL band contributes to a lower resolution level. - subb_LL.resLvl = (orientation == WT_ORIENT_LL) ? resLvl - 1 : resLvl; - subb_LL.anGainExp = anGainExp; - subb_LL.sbandIdx = (sbandIdx << 2); - // HL subband - subb_HL.orientation = WT_ORIENT_HL; - subb_HL.level = subb_LL.level; - subb_HL.ulcx = ulcx >> 1; - subb_HL.ulcy = subb_LL.ulcy; - subb_HL.ulx = ulx + subb_LL.w; - subb_HL.uly = uly; - subb_HL.w = ((ulcx + w) >> 1) - subb_HL.ulcx; - subb_HL.h = subb_LL.h; - subb_HL.resLvl = resLvl; - subb_HL.anGainExp = anGainExp + 1; - subb_HL.sbandIdx = (sbandIdx << 2) + 1; - // LH subband - subb_LH.orientation = WT_ORIENT_LH; - subb_LH.level = subb_LL.level; - subb_LH.ulcx = subb_LL.ulcx; - subb_LH.ulcy = ulcy >> 1; - subb_LH.ulx = ulx; - subb_LH.uly = uly + subb_LL.h; - subb_LH.w = subb_LL.w; - subb_LH.h = ((ulcy + h) >> 1) - subb_LH.ulcy; - subb_LH.resLvl = resLvl; - subb_LH.anGainExp = anGainExp + 1; - subb_LH.sbandIdx = (sbandIdx << 2) + 2; - // HH subband - subb_HH.orientation = WT_ORIENT_HH; - subb_HH.level = subb_LL.level; - subb_HH.ulcx = subb_HL.ulcx; - subb_HH.ulcy = subb_LH.ulcy; - subb_HH.ulx = subb_HL.ulx; - subb_HH.uly = subb_LH.uly; - subb_HH.w = subb_HL.w; - subb_HH.h = subb_LH.h; - subb_HH.resLvl = resLvl; - subb_HH.anGainExp = anGainExp + 2; - subb_HH.sbandIdx = (sbandIdx << 2) + 3; - } - - /// Creates a Subband element with all the default values. The dimensions - /// are (0,0), the upper left corner is (0,0) and the upper-left corner - /// with respect to the canvas is (0,0) too. - /// - /// - public Subband() - { - } - - /// Creates the top-level node and the entire subband tree, with the - /// top-level dimensions, the number of decompositions, and the - /// decomposition tree as specified. - /// - ///

    For the analysis subband gain calculation it is assumed that - /// analysis filters are normalized with a DC gain of 1 and a Nyquist gain - /// of 2.

    - /// - ///

    This constructor does not initialize the value of the magBits member - /// variable. This variable is normally initialized by the quantizer, on - /// the encoder side, or the bit stream reader, on the decoder side.

    - /// - ///
    - /// The top-level width - /// - /// - /// The top-level height - /// - /// - /// The horizontal coordinate of the upper-left corner with - /// respect to the canvas origin, in the component grid. - /// - /// - /// The vertical coordinate of the upper-left corner with - /// respect to the canvas origin, in the component grid. - /// - /// - /// The number of levels (or LL decompositions) in the tree. - /// - /// - /// The horizontal wavelet filters (analysis or synthesis) - /// for each resolution level, starting at resolution level 0. If there are - /// less elements in the array than there are resolution levels, the last - /// element is used for the remaining resolution levels. - /// - /// - /// The vertical wavelet filters (analysis or synthesis) - /// for each resolution level, starting at resolution level 0. If there are - /// less elements in the array than there are resolution levels, the last - /// element is used for the remaining resolution levels. - /// - /// - /// - /// - /// - public Subband(int w, int h, int ulcx, int ulcy, int lvls, WaveletFilter[] hfilters, WaveletFilter[] vfilters) - { - int i, hi, vi; - Subband cur; // The current subband - - // Initialize top-level node - this.w = w; - this.h = h; - this.ulcx = ulcx; - this.ulcy = ulcy; - this.resLvl = lvls; - // First create dyadic decomposition. - cur = this; - for (i = 0; i < lvls; i++) - { - hi = (cur.resLvl <= hfilters.Length) ? cur.resLvl - 1 : hfilters.Length - 1; - vi = (cur.resLvl <= vfilters.Length) ? cur.resLvl - 1 : vfilters.Length - 1; - cur = cur.split(hfilters[hi], vfilters[vi]); - } - } - - /// Returns the next subband in the same resolution level, following the - /// subband index order. If already at the last subband then null is - /// returned. If this subband is not a leaf an IllegalArgumentException is - /// thrown. - /// - /// - /// The next subband in the same resolution level, following the - /// subband index order, or null if already at last subband. - /// - /// - public virtual Subband nextSubband() - { - Subband sb; - - if (isNode) - { - throw new System.ArgumentException(); - } - - switch (orientation) - { - - case WT_ORIENT_LL: - sb = Parent; - if (sb == null || sb.resLvl != resLvl) - { - // Already at top-level or last subband in res. level - return null; - } - else - { - return sb.HL; - } - //goto case WT_ORIENT_HL; - - case WT_ORIENT_HL: - return Parent.LH; - - case WT_ORIENT_LH: - return Parent.HH; - - case WT_ORIENT_HH: - // This is the complicated one - sb = this; - while (sb.orientation == WT_ORIENT_HH) - { - sb = sb.Parent; - } - switch (sb.orientation) - { - - case WT_ORIENT_LL: - sb = sb.Parent; - if (sb == null || sb.resLvl != resLvl) - { - // Already at top-level or last subband in res. level - return null; - } - else - { - sb = sb.HL; - } - break; - - case WT_ORIENT_HL: - sb = sb.Parent.LH; - break; - - case WT_ORIENT_LH: - sb = sb.Parent.HH; - break; - - default: - throw new System.ApplicationException("You have found a bug in JJ2000"); - - } - while (sb.isNode) - { - sb = sb.LL; - } - return sb; - - default: - throw new System.ApplicationException("You have found a bug in JJ2000"); - - } - } - - /// Returns a subband element in the tree, given its resolution level and - /// subband index. This method searches through the tree. - /// - /// - /// The resolution level. - /// - /// - /// The subband index, within the resolution level. - /// - /// - public virtual Subband getSubbandByIdx(int rl, int sbi) - { - Subband sb = this; - - // Find the root subband for the resolution level - if (rl > sb.resLvl || rl < 0) - { - throw new System.ArgumentException("Resolution level index " + "out of range"); - } - - // Returns directly if it is itself - if (rl == sb.resLvl && sbi == sb.sbandIdx) - return sb; - - if (sb.sbandIdx != 0) - sb = sb.Parent; - - while (sb.resLvl > rl) - sb = sb.LL; - while (sb.resLvl < rl) - sb = sb.Parent; - - switch (sbi) - { - - case 0: - default: - return sb; - - case 1: - return sb.HL; - - case 2: - return sb.LH; - - case 3: - return sb.HH; - } - } - - /// Returns a reference to the Subband element to which the specified point - /// belongs. The specified point must be inside this (i.e. the one defined - /// by this object) subband. This method searches through the tree. - /// - /// - /// horizontal coordinate of the specified point. - /// - /// - /// horizontal coordinate of the specified point. - /// - /// - public virtual Subband getSubband(int x, int y) - { - Subband cur, hhs; - - // Check that we are inside this subband - if (x < ulx || y < uly || x >= ulx + w || y >= uly + h) - { - throw new System.ArgumentException(); - } - - cur = this; - while (cur.isNode) - { - hhs = cur.HH; - // While we are still at a node -> continue - if (x < hhs.ulx) - { - // Is the result of horizontal low-pass - if (y < hhs.uly) - { - // Vertical low-pass - cur = cur.LL; - } - else - { - // Vertical high-pass - cur = cur.LH; - } - } - else - { - // Is the result of horizontal high-pass - if (y < hhs.uly) - { - // Vertical low-pass - cur = cur.HL; - } - else - { - // Vertical high-pass - cur = cur.HH; - } - } - } - - return cur; - } - - /// Returns subband informations in a string. - /// - /// - /// Subband informations - /// - /// - public override System.String ToString() - { - System.String string_Renamed = "w=" + w + ",h=" + h + ",ulx=" + ulx + ",uly=" + uly + ",ulcx=" + ulcx + ",ulcy=" + ulcy + ",idx=" + sbandIdx + ",orient=" + orientation + ",node=" + isNode + ",level=" + level + ",resLvl=" + resLvl + ",nomCBlkW=" + nomCBlkW + ",nomCBlkH=" + nomCBlkH + ",numCb=" + numCb; - - return string_Renamed; - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/wavelet/WTDecompSpec.cs b/CSJ2K/j2k/wavelet/WTDecompSpec.cs deleted file mode 100644 index dd7aaff4..00000000 --- a/CSJ2K/j2k/wavelet/WTDecompSpec.cs +++ /dev/null @@ -1,320 +0,0 @@ -/* -* CVS identifier: -* -* $Id: WTDecompSpec.java,v 1.9 2000/09/05 09:26:06 grosbois Exp $ -* -* Class: WTDecompSpec -* -* Description: -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* -* -* -*/ -using System; -namespace CSJ2K.j2k.wavelet -{ - - /// This class holds the decomposition type to be used in each part of the - /// image; the default one, the component specific ones, the tile default ones - /// and the component-tile specific ones. - /// - ///

    The decomposition type identifiers values are the same as in the - /// codestream. - /// - ///

    The hierarchy is:
    - /// - Tile and component specific decomposition
    - /// - Tile specific default decomposition
    - /// - Component main default decomposition
    - /// - Main default decomposition
    - /// - ///

    At the moment tiles are not supported by this class. - /// - ///

    - public class WTDecompSpec - { - /// Returns the main default decomposition type. - /// - /// - /// The main default decomposition type. - /// - /// - /// - /// - virtual public int MainDefDecompType - { - get - { - return mainDefDecompType; - } - - } - /// Returns the main default decomposition number of levels. - /// - /// - /// The main default decomposition number of levels. - /// - /// - /// - /// - virtual public int MainDefLevels - { - get - { - return mainDefLevels; - } - - } - /// ID for the dyadic wavelet tree decomposition (also called - /// "Mallat" in JPEG 2000): 0x00. - /// - public const int WT_DECOMP_DYADIC = 0; - - /// ID for the SPACL (as defined in JPEG 2000) wavelet tree - /// decomposition (1 level of decomposition in the high bands and - /// some specified number for the lowest LL band): 0x02. - /// - public const int WT_DECOMP_SPACL = 2; - - /// ID for the PACKET (as defined in JPEG 2000) wavelet tree - /// decomposition (2 levels of decomposition in the high bands and - /// some specified number for the lowest LL band): 0x01. - /// - public const int WT_DECOMP_PACKET = 1; - - /// The identifier for "main default" specified decomposition - public const byte DEC_SPEC_MAIN_DEF = 0; - - /// The identifier for "component default" specified decomposition - public const byte DEC_SPEC_COMP_DEF = 1; - - /// The identifier for "tile specific default" specified decomposition - public const byte DEC_SPEC_TILE_DEF = 2; - - /// The identifier for "tile and component specific" specified - /// decomposition - /// - public const byte DEC_SPEC_TILE_COMP = 3; - - /// The spec type for each tile and component. The first index is the - /// component index, the second is the tile index. NOTE: The tile specific - /// things are not supported yet. - /// - // Use byte to save memory (no need for speed here). - private byte[] specValType; - - /// The main default decomposition - private int mainDefDecompType; - - /// The main default number of decomposition levels - private int mainDefLevels; - - /// The component main default decomposition, for each component. - private int[] compMainDefDecompType; - - /// The component main default decomposition levels, for each component - private int[] compMainDefLevels; - - /// Constructs a new 'WTDecompSpec' for the specified number of components - /// and tiles, with the given main default decomposition type and number of - /// levels. - /// - ///

    NOTE: The tile specific things are not supported yet - /// - ///

    - /// The number of components - /// - /// - /// The number of tiles - /// - /// - /// The main default decomposition type - /// - /// - /// The main default number of decomposition levels - /// - /// - /// - /// - public WTDecompSpec(int nc, int dec, int lev) - { - mainDefDecompType = dec; - mainDefLevels = lev; - specValType = new byte[nc]; - } - - /// Sets the "component main default" decomposition type and number of - /// levels for the specified component. Both 'dec' and 'lev' can not be - /// negative at the same time. - /// - /// - /// The component index - /// - /// - /// The decomposition type. If negative then the main default is - /// used. - /// - /// - /// The number of levels. If negative then the main defaul is - /// used. - /// - /// - /// - /// - public virtual void setMainCompDefDecompType(int n, int dec, int lev) - { - if (dec < 0 && lev < 0) - { - throw new System.ArgumentException(); - } - // Set spec type and decomp - specValType[n] = DEC_SPEC_COMP_DEF; - if (compMainDefDecompType == null) - { - compMainDefDecompType = new int[specValType.Length]; - compMainDefLevels = new int[specValType.Length]; - } - compMainDefDecompType[n] = (dec >= 0) ? dec : mainDefDecompType; - compMainDefLevels[n] = (lev >= 0) ? lev : mainDefLevels; - // For the moment disable it since other parts of JJ2000 do not - // support this - throw new NotImplementedException("Currently, in JJ2000, all components " + "and tiles must have the same " + "decomposition type and number of " + "levels"); - } - - /// Returns the type of specification for the decomposition in the - /// specified component and tile. The specification type is one of: - /// 'DEC_SPEC_MAIN_DEF', 'DEC_SPEC_COMP_DEF', 'DEC_SPEC_TILE_DEF', - /// 'DEC_SPEC_TILE_COMP'. - /// - ///

    NOTE: The tile specific things are not supported yet - /// - ///

    - /// The component index - /// - /// - /// The tile index, in raster scan order. - /// - /// - /// The specification type for component 'n' and tile 't'. - /// - /// - /// - /// - public virtual byte getDecSpecType(int n) - { - return specValType[n]; - } - - /// Returns the decomposition type to be used in component 'n' and tile - /// 't'. - /// - ///

    NOTE: The tile specific things are not supported yet - /// - ///

    - /// The component index. - /// - /// - /// The tile index, in raster scan order - /// - /// - /// The decomposition type to be used. - /// - /// - /// - /// - public virtual int getDecompType(int n) - { - switch (specValType[n]) - { - - case DEC_SPEC_MAIN_DEF: - return mainDefDecompType; - - case DEC_SPEC_COMP_DEF: - return compMainDefDecompType[n]; - - case DEC_SPEC_TILE_DEF: - throw new NotImplementedException(); - - case DEC_SPEC_TILE_COMP: - throw new NotImplementedException(); - - default: - throw new System.ApplicationException("Internal JJ2000 error"); - - } - } - - /// Returns the decomposition number of levels in component 'n' and tile - /// 't'. - /// - ///

    NOTE: The tile specific things are not supported yet - /// - ///

    - /// The component index. - /// - /// - /// The tile index, in raster scan order - /// - /// - /// The decomposition number of levels. - /// - /// - /// - /// - public virtual int getLevels(int n) - { - switch (specValType[n]) - { - - case DEC_SPEC_MAIN_DEF: - return mainDefLevels; - - case DEC_SPEC_COMP_DEF: - return compMainDefLevels[n]; - - case DEC_SPEC_TILE_DEF: - throw new NotImplementedException(); - - case DEC_SPEC_TILE_COMP: - throw new NotImplementedException(); - - default: - throw new System.ApplicationException("Internal JJ2000 error"); - - } - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/wavelet/WTFilterSpec.cs b/CSJ2K/j2k/wavelet/WTFilterSpec.cs deleted file mode 100644 index 339a20ba..00000000 --- a/CSJ2K/j2k/wavelet/WTFilterSpec.cs +++ /dev/null @@ -1,149 +0,0 @@ -/* -* CVS identifier: -* -* $Id: WTFilterSpec.java,v 1.10 2000/09/05 09:26:08 grosbois Exp $ -* -* Class: WTFilterSpec -* -* Description: Generic class for storing wavelet filter specs -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* -* -* -*/ -namespace CSJ2K.j2k.wavelet -{ - - /// This is the generic class from which the ones that hold the analysis or - /// synthesis filters to be used in each part of the image derive. See - /// AnWTFilterSpec and SynWTFilterSpec. - /// - ///

    The filters to use are defined by a hierarchy. The hierarchy is: - /// - ///

    - Tile and component specific filters
    - /// - Tile specific default filters
    - /// - Component main default filters
    - /// - Main default filters
    - /// - ///

    At the moment tiles are not supported by this class. - /// - ///

    - /// - /// - /// - /// - /// - /// - - public abstract class WTFilterSpec - { - /// Returns the data type used by the filters in this object, as defined in - /// the 'DataBlk' interface. - /// - /// - /// The data type of the filters in this object - /// - /// - /// - /// - /// - /// - /// - public abstract int WTDataType { get; } - - /// The identifier for "main default" specified filters - public const byte FILTER_SPEC_MAIN_DEF = 0; - - /// The identifier for "component default" specified filters - public const byte FILTER_SPEC_COMP_DEF = 1; - - /// The identifier for "tile specific default" specified filters - public const byte FILTER_SPEC_TILE_DEF = 2; - - /// The identifier for "tile and component specific" specified filters - public const byte FILTER_SPEC_TILE_COMP = 3; - - /// The spec type for each tile and component. The first index is the - /// component index, the second is the tile index. NOTE: The tile specific - /// things are not supported yet. - /// - // Use byte to save memory (no need for speed here). - protected internal byte[] specValType; - - /// Constructs a 'WTFilterSpec' object, initializing all the components and - /// tiles to the 'FILTER_SPEC_MAIN_DEF' spec type, for the specified number - /// of components and tiles. - /// - ///

    NOTE: The tile specific things are not supported yet - /// - ///

    - /// The number of components - /// - /// - /// The number of tiles - /// - /// - /// - /// - protected internal WTFilterSpec(int nc) - { - specValType = new byte[nc]; - } - - /// Returns the type of specification for the filters in the specified - /// component and tile. The specification type is one of: - /// 'FILTER_SPEC_MAIN_DEF', 'FILTER_SPEC_COMP_DEF', 'FILTER_SPEC_TILE_DEF', - /// 'FILTER_SPEC_TILE_COMP'. - /// - ///

    NOTE: The tile specific things are not supported yet - /// - ///

    - /// The component index - /// - /// - /// The tile index, in raster scan order. - /// - /// - /// The specification type for component 'n' and tile 't'. - /// - /// - /// - /// - public virtual byte getKerSpecType(int n) - { - return specValType[n]; - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/wavelet/WaveletFilter.cs b/CSJ2K/j2k/wavelet/WaveletFilter.cs deleted file mode 100644 index e347339f..00000000 --- a/CSJ2K/j2k/wavelet/WaveletFilter.cs +++ /dev/null @@ -1,244 +0,0 @@ -/* -* CVS identifier: -* -* $Id: WaveletFilter.java,v 1.13 2001/08/02 11:11:16 grosbois Exp $ -* -* Class: WaveletFilter -* -* Description: Defines the interface for WT filters (analysis -* and synthesis) -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -*/ -namespace CSJ2K.j2k.wavelet -{ - - /// This interface defines how a wavelet filter implementation should present - /// itself. This interface defines only the commonalities between the analysis - /// and synthesis filters. The AnWTFilter and SynWTFilter classes provide the - /// specifics of analysis and synthesis filters. - /// - ///

    Both analysis and filters must be able to return the extent of the - /// negative and positive support for both synthesis and analysis sides. This - /// simplifies the sue of some functionalities that need extra information - /// about the filters.

    - /// - ///
    - /// - /// - /// - /// - /// - /// - public struct WaveletFilter_Fields - { - /// The ID for integer lifting spteps implementations - public readonly static int WT_FILTER_INT_LIFT = 0; - /// The ID for floating-point lifting spteps implementations - public readonly static int WT_FILTER_FLOAT_LIFT = 1; - /// The ID for floatring-poitn convolution implementations - public readonly static int WT_FILTER_FLOAT_CONVOL = 2; - } - public interface WaveletFilter - { - //UPGRADE_NOTE: Members of interface 'WaveletFilter' were extracted into structure 'WaveletFilter_Fields'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1045'" - /// Returns the negative support of the low-pass analysis filter. That is - /// the number of taps of the filter in the negative direction. - /// - /// - /// The number of taps of the low-pass analysis filter in the - /// negative direction - /// - int AnLowNegSupport - { - get; - - } - /// Returns the positive support of the low-pass analysis filter. That is - /// the number of taps of the filter in the negative direction. - /// - /// - /// The number of taps of the low-pass analysis filter in the - /// positive direction - /// - int AnLowPosSupport - { - get; - - } - /// Returns the negative support of the high-pass analysis filter. That is - /// the number of taps of the filter in the negative direction. - /// - /// - /// The number of taps of the high-pass analysis filter in the - /// negative direction - /// - int AnHighNegSupport - { - get; - - } - /// Returns the positive support of the high-pass analysis filter. That is - /// the number of taps of the filter in the negative direction. - /// - /// - /// The number of taps of the high-pass analysis filter in - /// the positive direction - /// - int AnHighPosSupport - { - get; - - } - /// Returns the negative support of the low-pass synthesis filter. That is - /// the number of taps of the filter in the negative direction. - /// - /// - /// The number of taps of the low-pass synthesis filter in the - /// negative direction - /// - int SynLowNegSupport - { - get; - - } - /// Returns the positive support of the low-pass synthesis filter. That is - /// the number of taps of the filter in the negative direction. - /// - /// - /// The number of taps of the low-pass synthesis filter in the - /// positive direction - /// - int SynLowPosSupport - { - get; - - } - /// Returns the negative support of the high-pass synthesis filter. That is - /// the number of taps of the filter in the negative direction. - /// - /// - /// The number of taps of the high-pass synthesis filter in the - /// negative direction - /// - int SynHighNegSupport - { - get; - - } - /// Returns the positive support of the high-pass synthesis filter. That is - /// the number of taps of the filter in the negative direction. - /// - /// - /// The number of taps of the high-pass synthesis filter in the - /// positive direction - /// - int SynHighPosSupport - { - get; - - } - /// Returns the implementation type of this filter, as defined in this - /// class, such as WT_FILTER_INT_LIFT, WT_FILTER_FLOAT_LIFT, - /// WT_FILTER_FLOAT_CONVOL. - /// - /// - /// The implementation type of this filter: WT_FILTER_INT_LIFT, - /// WT_FILTER_FLOAT_LIFT, WT_FILTER_FLOAT_CONVOL. - /// - int ImplType - { - get; - - } - /// Returns the type of data on which this filter works, as defined in the - /// DataBlk interface. - /// - /// - /// The type of data as defined in the DataBlk interface. - /// - /// - /// - /// - int DataType - { - get; - - } - /// Returns the reversibility of the filter. A filter is considered - /// reversible if it is suitable for lossless coding. - /// - /// - /// true if the filter is reversible, false otherwise. - /// - /// - bool Reversible - { - get; - - } - - /// Returns true if the wavelet filter computes or uses the same "inner" - /// subband coefficient as the full frame wavelet transform, and false - /// otherwise. In particular, for block based transforms with reduced - /// overlap, this method should return false. The term "inner" indicates - /// that this applies only with respect to the coefficient that are not - /// affected by image boundaries processings such as symmetric extension, - /// since there is not reference method for this. - /// - ///

    The result depends on the length of the allowed overlap when - /// compared to the overlap required by the wavelet filter. It also depends - /// on how overlap processing is implemented in the wavelet filter.

    - /// - ///
    - /// This is the number of samples in the input signal - /// before the first sample to filter that can be used for overlap. - /// - /// - /// This is the number of samples in the input signal - /// after the last sample to filter that can be used for overlap. - /// - /// - /// This is the lenght of the input signal to filter.The - /// required number of samples in the input signal after the last sample - /// depends on the length of the input signal. - /// - /// - /// true if the overlaps are large enough and correct processing is - /// performed, false otherwise. - /// - /// - bool isSameAsFullWT(int tailOvrlp, int headOvrlp, int inLen); - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/wavelet/WaveletTransform.cs b/CSJ2K/j2k/wavelet/WaveletTransform.cs deleted file mode 100644 index c72f0e8b..00000000 --- a/CSJ2K/j2k/wavelet/WaveletTransform.cs +++ /dev/null @@ -1,109 +0,0 @@ -/* -* CVS identifier: -* -* $Id: WaveletTransform.java,v 1.18 2001/10/24 12:02:35 grosbois Exp $ -* -* Class: WaveletTransform -* -* Description: Interface that defines how a forward or -* inverse wavelet transform should present -* itself. -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.image; -namespace CSJ2K.j2k.wavelet -{ - - /// This interface defines how a forward or inverse wavelet transform should - /// present itself. As specified in the ImgData interface, from which this - /// class inherits, all operations are confined to the current tile, and all - /// coordinates are relative to it. - /// - ///

    The definition of the methods in this interface allows for different - /// types of implementation, reversibility and levels of decompositions for - /// each component and each tile. An implementation of this interface does not - /// need to support all this flexibility (e.g., it may provide the same - /// implementation type and decomposition levels for all tiles and - /// components).

    - /// - ///
    - public struct WaveletTransform_Fields - { - /// ID for line based implementations of wavelet transforms. - /// - /// - public readonly static int WT_IMPL_LINE = 0; - /// ID for full-page based implementations of wavelet transforms. Full-page - /// based implementations should be avoided since they require large - /// amounts of memory. - /// - /// - public readonly static int WT_IMPL_FULL = 2; - } - public interface WaveletTransform : ImgData - { - //UPGRADE_NOTE: Members of interface 'WaveletTransform' were extracted into structure 'WaveletTransform_Fields'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1045'" - - - /// Returns the reversibility of the wavelet transform for the specified - /// component and tile. A wavelet transform is reversible when it is - /// suitable for lossless and lossy-to-lossless compression. - /// - /// - /// The index of the tile. - /// - /// - /// The index of the component. - /// - /// - /// true is the wavelet transform is reversible, false if not. - /// - /// - bool isReversible(int t, int c); - - /// Returns the implementation type of this wavelet transform (WT_IMPL_LINE - /// or WT_IMPL_FRAME) for the specified component, in the current tile. - /// - /// - /// The index of the component. - /// - /// - /// WT_IMPL_LINE or WT_IMPL_FULL for line, block or full-page based - /// transforms. - /// - /// - int getImplementationType(int c); - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/wavelet/analysis/AnWTFilter.cs b/CSJ2K/j2k/wavelet/analysis/AnWTFilter.cs deleted file mode 100644 index fb2775f9..00000000 --- a/CSJ2K/j2k/wavelet/analysis/AnWTFilter.cs +++ /dev/null @@ -1,488 +0,0 @@ -/* -* CVS identifier: -* -* $Id: AnWTFilter.java,v 1.15 2001/05/08 16:14:52 grosbois Exp $ -* -* Class: AnWTFilter -* -* Description: The abstract class for all analysis wavelet filters -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -namespace CSJ2K.j2k.wavelet.analysis -{ - - ///

    This abstract class defines the methods of all analysis wavelet - /// filters. Specialized abstract classes that work on particular data types - /// (int, float) provide more specific method calls while retaining the - /// generality of this one. See the AnWTFilterInt and AnWTFilterFloat - /// classes. Implementations of analysis filters should inherit from one of - /// those classes.

    - /// - /// All analysis wavelet filters should follow the following conventions: - /// - ///
      - ///
    • The first sample to filter is the low-pass one. As a consequence, if - /// the input signal is of odd-length then the low-pass output signal is one - /// sample longer than the high-pass output one. Therefore, if the length of - /// input signal is N, the low-pass output signal is of length N/2 if N is even - /// and N/2+1/2 if N is odd, while the high-pass output signal is of length N/2 - /// if N is even and N/2-1/2 if N is odd.
    • - /// - ///
    • The normalization is 1 for the DC gain and 2 for the Nyquist gain (Type - /// I normalization), for both reversible and non-reversible filters.
    • - /// - ///
    • If the length of input signal is N, the low-pass output signal is of - /// length N/2 if N is even and N/2+1/2 if N is odd, while the high-pass output - /// sample is of length N/2 if N is even and N/2-1/2 if N is odd.
    • - /// - ///
    • The analyze method may seem very complicated, but is designed to - /// minimize the amount of data copying and redundant calculations when used - /// for block-based or line-based wavelet transform implementations, while - /// being applicable to full-frame transforms as well.
    • - /// - ///
    • All filters should implement the equals() method of the Object - /// class. The call x.equals(y) should test if the 'x' and 'y' filters are the - /// same or not, in what concerns the bit stream header syntax (two filters are - /// the same if the same filter code should be output to the bit stream).
    • - ///
    - /// - ///
    - /// - /// - /// - /// - /// - public abstract class AnWTFilter : WaveletFilter - { - /// Returns the type of filter used according to the FilterTypes interface. - /// - /// - /// - /// - /// - /// The filter type. - /// - /// - public abstract int FilterType { get; } - /// Returns the parameters that are used in this class and implementing - /// classes. It returns a 2D String array. Each of the 1D arrays is for a - /// different option, and they have 3 elements. The first element is the - /// option name, the second one is the synopsis, the third one is a long - /// description of what the parameter is and the fourth is its default - /// value. The synopsis or description may be 'null', in which case it is - /// assumed that there is no synopsis or description of the option, - /// respectively. Null may be returned if no options are supported. - /// - /// - /// the options name, their synopsis and their explanation, or null - /// if no options are supported. - /// - /// - public static System.String[][] ParameterInfo - { - get - { - return pinfo; - } - - } - public abstract int AnHighPosSupport { get; } - public abstract int AnLowNegSupport { get; } - public abstract int AnLowPosSupport { get; } - public abstract bool Reversible { get; } - public abstract int ImplType { get; } - public abstract int SynHighNegSupport { get; } - public abstract int SynHighPosSupport { get; } - public abstract int AnHighNegSupport { get; } - public abstract int DataType { get; } - public abstract int SynLowNegSupport { get; } - public abstract int SynLowPosSupport { get; } - - /// The prefix for wavelet filter options: 'F' - public const char OPT_PREFIX = 'F'; - - /// The list of parameters that is accepted for wavelet filters. Options - /// for wavelet filters start with a 'F'. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'pinfo'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly System.String[][] pinfo = new System.String[][] { new System.String[] { "Ffilters", "[] " + "[ [] ...]", "Specifies which filters to use for specified tile-component. " + "If this option is not used, the encoder choses the filters " + " of the tile-components according to their quantization type." + " If this option is used, a component transformation is applied " + "to the three first components.\n" + ": see general note\n" + ": ',' separates horizontal and vertical filters, ':' separates" + " decomposition levels filters. JPEG 2000 part 1 only supports w5x3" + " and w9x7 filters.", null } }; - - /// Filters the input signal by this analysis filter, decomposing it in a - /// low-pass and a high-pass signal. This method performs the filtering and - /// the subsampling with the low pass first filtering convention. - /// - ///

    The input signal resides in the inSig array. The index of the first - /// sample to filter (i.e. that will generate the first low-pass output - /// sample) is given by inOff. The number of samples to filter is given by - /// inLen. This array must be of the same type as the one for which the - /// particular implementation works with (which is returned by the - /// getDataType() method).

    - /// - ///

    The input signal can be interleaved with other signals in the same - /// inSig array, and this is determined by the inStep argument. This means - /// that the first sample of the input signal is inSig[inOff], the second - /// is inSig[inOff+inStep], the third is inSig[inOff+2*inStep], and so - /// on. Therefore if inStep is 1 there is no interleaving. This feature - /// allows to filter columns of a 2-D signal, when it is stored in a line - /// by line order in inSig, without having to copy the data, in this case - /// the inStep argument should be the line width.

    - /// - ///

    This method also allows to apply the analysis wavelet filter by - /// parts in the input signal using an overlap and thus producing the same - /// coefficients at the output. The tailOvrlp argument specifies how many - /// samples in the input signal, before the first one to be filtered, can - /// be used for overlap. Then, the filter instead of extending the input - /// signal will use those samples to calculate the first output - /// samples. The argument tailOvrlp can be 0 for no overlap, or some value - /// that provides partial or full overlap. There should be enough samples - /// in the input signal, before the first sample to be filtered, to support - /// the overlap. The headOvrlp provides the same functionality but at the - /// end of the input signal. The inStep argument also applies to samples - /// used for overlap. This overlap feature can be used for line-based - /// wavelet transforms (in which case it will only be used when filtering - /// the columns) or for overlapping block-based wavelet transforms (in - /// which case it will be used when filtering lines and columns).

    - /// - ///

    The low-pass output signal is placed in the lowSig array. The lowOff - /// and lowStep arguments are analogous to the inOff and inStep ones, but - /// they apply to the lowSig array. The lowSig array must be long enough to - /// hold the low-pass output signal.

    - /// - ///

    The high-pass output signal is placed in the highSig array. The - /// highOff and highStep arguments are analogous to the inOff and inStep - /// ones, but they apply to the highSig array. The highSig array must be - /// long enough to hold the high-pass output signal.

    - /// - ///
    - /// This is the array that contains the input signal. It must - /// be of the correct type (e.g., it must be int[] if getDataType() returns - /// TYPE_INT). - /// - /// - /// This is the index in inSig of the first sample to filter. - /// - /// - /// This is the number of samples in the input signal to - /// filter. - /// - /// - /// This is the step, or interleave factor, of the input - /// signal samples in the inSig array. See above. - /// - /// - /// This is the number of samples in the input signal - /// before the first sample to filter that can be used for overlap. See - /// above. - /// - /// - /// This is the number of samples in the input signal - /// after the last sample to filter that can be used for overlap. See - /// above. - /// - /// - /// This is the array where the low-pass output signal is - /// placed. It must be of the same type as inSig and it should be long - /// enough to contain the output signal. - /// - /// - /// This is the index in lowSig of the element where to put - /// the first low-pass output sample. - /// - /// - /// This is the step, or interleave factor, of the low-pass - /// output samples in the lowSig array. See above. - /// - /// - /// This is the array where the high-pass output signal is - /// placed. It must be of the same type as inSig and it should be long - /// enough to contain the output signal. - /// - /// - /// This is the index in highSig of the element where to put - /// the first high-pass output sample. - /// - /// - /// This is the step, or interleave factor, of the - /// high-pass output samples in the highSig array. See above. - /// - /// - /// - /// - /// - public abstract void analyze_lpf(System.Object inSig, int inOff, int inLen, int inStep, System.Object lowSig, int lowOff, int lowStep, System.Object highSig, int highOff, int highStep); - - /// Filters the input signal by this analysis filter, decomposing it in a - /// low-pass and a high-pass signal. This method performs the filtering and - /// the subsampling with the high pass first filtering convention. - /// - ///

    The input signal resides in the inSig array. The index of the first - /// sample to filter (i.e. that will generate the first high-pass output - /// sample) is given by inOff. The number of samples to filter is given by - /// inLen. This array must be of the same type as the one for which the - /// particular implementation works with (which is returned by the - /// getDataType() method).

    - /// - ///

    The input signal can be interleaved with other signals in the same - /// inSig array, and this is determined by the inStep argument. This means - /// that the first sample of the input signal is inSig[inOff], the second - /// is inSig[inOff+inStep], the third is inSig[inOff+2*inStep], and so - /// on. Therefore if inStep is 1 there is no interleaving. This feature - /// allows to filter columns of a 2-D signal, when it is stored in a line - /// by line order in inSig, without having to copy the data, in this case - /// the inStep argument should be the line width.

    - /// - ///

    The low-pass output signal is placed in the lowSig array. The lowOff - /// and lowStep arguments are analogous to the inOff and inStep ones, but - /// they apply to the lowSig array. The lowSig array must be long enough to - /// hold the low-pass output signal.

    - /// - ///

    The high-pass output signal is placed in the highSig array. The - /// highOff and highStep arguments are analogous to the inOff and inStep - /// ones, but they apply to the highSig array. The highSig array must be - /// long enough to hold the high-pass output signal.

    - /// - ///
    - /// This is the array that contains the input signal. It must - /// be of the correct type (e.g., it must be int[] if getDataType() returns - /// TYPE_INT). - /// - /// - /// This is the index in inSig of the first sample to filter. - /// - /// - /// This is the number of samples in the input signal to - /// filter. - /// - /// - /// This is the step, or interleave factor, of the input - /// signal samples in the inSig array. See above. - /// - /// - /// This is the array where the low-pass output signal is - /// placed. It must be of the same type as inSig and it should be long - /// enough to contain the output signal. - /// - /// - /// This is the index in lowSig of the element where to put - /// the first low-pass output sample. - /// - /// - /// This is the step, or interleave factor, of the low-pass - /// output samples in the lowSig array. See above. - /// - /// - /// This is the array where the high-pass output signal is - /// placed. It must be of the same type as inSig and it should be long - /// enough to contain the output signal. - /// - /// - /// This is the index in highSig of the element where to put - /// the first high-pass output sample. - /// - /// - /// This is the step, or interleave factor, of the - /// high-pass output samples in the highSig array. See above. - /// - /// - /// - /// - /// - public abstract void analyze_hpf(System.Object inSig, int inOff, int inLen, int inStep, System.Object lowSig, int lowOff, int lowStep, System.Object highSig, int highOff, int highStep); - - /// Returns the time-reversed low-pass synthesis waveform of the filter, - /// which is the low-pass filter. This is the time-reversed impulse - /// response of the low-pass synthesis filter. It is used to calculate the - /// L2-norm of the synthesis basis functions for a particular subband (also - /// called energy weight). - /// - ///

    The returned array may not be modified (i.e. a reference to the - /// internal array may be returned by the implementation of this - /// method).

    - /// - ///
    - /// The time-reversed low-pass synthesis waveform of the filter. - /// - /// - public abstract float[] getLPSynthesisFilter(); - - /// Returns the time-reversed high-pass synthesis waveform of the filter, - /// which is the high-pass filter. This is the time-reversed impulse - /// response of the high-pass synthesis filter. It is used to calculate the - /// L2-norm of the synthesis basis functions for a particular subband (also - /// called energy weight). - /// - ///

    The returned array may not be modified (i.e. a reference to the - /// internal array may be returned by the implementation of this - /// method).

    - /// - ///
    - /// The time-reversed high-pass synthesis waveform of the filter. - /// - /// - public abstract float[] getHPSynthesisFilter(); - - /// Returns the equivalent low-pass synthesis waveform of a cascade of - /// filters, given the syhthesis waveform of the previous stage. This is - /// the result of upsampling 'in' by 2, and concolving it with the low-pass - /// synthesis waveform of the filter. The length of the returned signal is - /// 2*in_l+lp_l-2, where in_l is the length of 'in' and 'lp_l' is the - /// lengthg of the low-pass synthesis filter. - /// - ///

    The length of the low-pass synthesis filter is - /// getSynLowNegSupport()+getSynLowPosSupport().

    - /// - ///
    - /// The synthesis waveform of the previous stage. - /// - /// - /// If non-null this array is used to store the resulting - /// signal. It must be long enough, or an IndexOutOfBoundsException is - /// thrown. - /// - /// - /// - /// - /// - /// - /// - public virtual float[] getLPSynWaveForm(float[] in_Renamed, float[] out_Renamed) - { - return upsampleAndConvolve(in_Renamed, getLPSynthesisFilter(), out_Renamed); - } - - /// Returns the equivalent high-pass synthesis waveform of a cascade of - /// filters, given the syhthesis waveform of the previous stage. This is - /// the result of upsampling 'in' by 2, and concolving it with the - /// high-pass synthesis waveform of the filter. The length of the returned - /// signal is 2*in_l+hp_l-2, where in_l is the length of 'in' and 'hp_l' is - /// the lengthg of the high-pass synthesis filter. - /// - ///

    The length of the high-pass synthesis filter is - /// getSynHighNegSupport()+getSynHighPosSupport().

    - /// - ///
    - /// The synthesis waveform of the previous stage. - /// - /// - /// If non-null this array is used to store the resulting - /// signal. It must be long enough, or an IndexOutOfBoundsException is - /// thrown. - /// - /// - /// - /// - /// - /// - /// - public virtual float[] getHPSynWaveForm(float[] in_Renamed, float[] out_Renamed) - { - return upsampleAndConvolve(in_Renamed, getHPSynthesisFilter(), out_Renamed); - } - - /// Returns the signal resulting of upsampling (by 2) the input signal 'in' - /// and then convolving it with the time-reversed signal 'wf'. The returned - /// signal is of length l_in*2+l_wf-2, where l_in is the length of 'in', - /// and l_wf is the length of 'wf'. - /// - ///

    The 'wf' signal has to be already time-reversed, therefore only a - /// dot-product is performed (instead of a convolution). This is equivalent - /// to convolving with the non-time-reversed 'wf' signal.

    - /// - ///
    - /// The signal to upsample and filter. If null it is considered - /// to be a dirac. - /// - /// - /// The time-reversed impulse response used for filtering. - /// - /// - /// If non-null this array is used to store the resulting - /// signal, it must be of length in.length*2+wf.length-2 at least. An - /// IndexOutOfBoundsException is thrown if this is not the case. - /// - /// - /// The resulting signal, of length in.length*2+wf.length-2 - /// - /// - private static float[] upsampleAndConvolve(float[] in_Renamed, float[] wf, float[] out_Renamed) - { - // NOTE: the effective length of the signal 'in' upsampled by - // 2 is 2*in.length-1 (not 2*in.length), so the resulting signal - // (after convolution) is of length 2*in.length-1+wf.length-1, - // which is 2*in.length+wf.length-2 - - int i, k, j; - float tmp; - int maxi, maxk; - - // If in null, then simulate dirac - if (in_Renamed == null) - { - in_Renamed = new float[1]; - in_Renamed[0] = 1.0f; - } - - // Get output buffer if necessary - if (out_Renamed == null) - { - out_Renamed = new float[in_Renamed.Length * 2 + wf.Length - 2]; - } - // Convolve the signals - for (i = 0, maxi = in_Renamed.Length * 2 + wf.Length - 2; i < maxi; i++) - { - tmp = 0.0f; - - // Calculate limits of loop below - k = (i - wf.Length + 2) / 2; - if (k < 0) - k = 0; - maxk = i / 2 + 1; - if (maxk > in_Renamed.Length) - maxk = in_Renamed.Length; - - // Calculate dot-product with upsampling of 'in' by 2. - for (j = 2 * k - i + wf.Length - 1; k < maxk; k++, j += 2) - { - tmp += in_Renamed[k] * wf[j]; - } - // Store result - out_Renamed[i] = tmp; - } - - return out_Renamed; - } - public abstract bool isSameAsFullWT(int param1, int param2, int param3); - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/wavelet/analysis/AnWTFilterFloat.cs b/CSJ2K/j2k/wavelet/analysis/AnWTFilterFloat.cs deleted file mode 100644 index 68a48b98..00000000 --- a/CSJ2K/j2k/wavelet/analysis/AnWTFilterFloat.cs +++ /dev/null @@ -1,310 +0,0 @@ -/* -* CVS identifier: -* -* $Id: AnWTFilterFloat.java,v 1.7 2000/09/05 09:25:37 grosbois Exp $ -* -* Class: AnWTFilterFloat -* -* Description: A specialized wavelet filter interface that -* works on float data. -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* -* -* -*/ -using CSJ2K.j2k.image; -namespace CSJ2K.j2k.wavelet.analysis -{ - - /// This extends the analysis wavelet filter general definitions of - /// AnWTFilter by adding methods that work for float data - /// specifically. Implementations that work on float data should inherit - /// from this class. - /// - ///

    See the AnWTFilter class for details such as - /// normalization, how to split odd-length signals, etc. - /// - ///

    The advantage of using the specialized method is that no casts - /// are performed. - /// - ///

    - /// - /// - /// - public abstract class AnWTFilterFloat : AnWTFilter - { - /// Returns the type of data on which this filter works, as defined - /// in the DataBlk interface, which is always TYPE_FLOAT for this - /// class. - /// - /// - /// The type of data as defined in the DataBlk interface. - /// - /// - /// - /// - /// - /// - /// - override public int DataType - { - get - { - return DataBlk.TYPE_FLOAT; - } - - } - - /// A specific version of the analyze_lpf() method that works on int - /// data. See the general description of the analyze_lpf() method in - /// the AnWTFilter class for more details. - /// - /// - /// This is the array that contains the input - /// signal. - /// - /// - /// This is the index in inSig of the first sample to - /// filter. - /// - /// - /// This is the number of samples in the input signal - /// to filter. - /// - /// - /// This is the step, or interleave factor, of the - /// input signal samples in the inSig array. - /// - /// - /// This is the array where the low-pass output - /// signal is placed. - /// - /// - /// This is the index in lowSig of the element where - /// to put the first low-pass output sample. - /// - /// - /// This is the step, or interleave factor, of the - /// low-pass output samples in the lowSig array. - /// - /// - /// This is the array where the high-pass output - /// signal is placed. - /// - /// - /// This is the index in highSig of the element where - /// to put the first high-pass output sample. - /// - /// - /// This is the step, or interleave factor, of the - /// high-pass output samples in the highSig array. - /// - /// - /// - /// - /// - /// - /// - /// - /// - public abstract void analyze_lpf(float[] inSig, int inOff, int inLen, int inStep, float[] lowSig, int lowOff, int lowStep, float[] highSig, int highOff, int highStep); - - /// The general version of the analyze_lpf() method, it just calls the - /// specialized version. See the description of the analyze_lpf() - /// method of the AnWTFilter class for more details. - /// - /// - /// This is the array that contains the input - /// signal. It must be an float[]. - /// - /// - /// This is the index in inSig of the first sample to - /// filter. - /// - /// - /// This is the number of samples in the input signal - /// to filter. - /// - /// - /// This is the step, or interleave factor, of the - /// input signal samples in the inSig array. - /// - /// - /// This is the array where the low-pass output - /// signal is placed. It must be an float[]. - /// - /// - /// This is the index in lowSig of the element where - /// to put the first low-pass output sample. - /// - /// - /// This is the step, or interleave factor, of the - /// low-pass output samples in the lowSig array. - /// - /// - /// This is the array where the high-pass output - /// signal is placed. It must be an float[]. - /// - /// - /// This is the index in highSig of the element where - /// to put the first high-pass output sample. - /// - /// - /// This is the step, or interleave factor, of the - /// high-pass output samples in the highSig array. - /// - /// - /// - /// - /// - /// - /// - public override void analyze_lpf(System.Object inSig, int inOff, int inLen, int inStep, System.Object lowSig, int lowOff, int lowStep, System.Object highSig, int highOff, int highStep) - { - - analyze_lpf((float[])inSig, inOff, inLen, inStep, (float[])lowSig, lowOff, lowStep, (float[])highSig, highOff, highStep); - } - - /// A specific version of the analyze_hpf() method that works on int - /// data. See the general description of the analyze_hpf() method in the - /// AnWTFilter class for more details. - /// - /// - /// This is the array that contains the input - /// signal. - /// - /// - /// This is the index in inSig of the first sample to - /// filter. - /// - /// - /// This is the number of samples in the input signal - /// to filter. - /// - /// - /// This is the step, or interleave factor, of the - /// input signal samples in the inSig array. - /// - /// - /// This is the array where the low-pass output - /// signal is placed. - /// - /// - /// This is the index in lowSig of the element where - /// to put the first low-pass output sample. - /// - /// - /// This is the step, or interleave factor, of the - /// low-pass output samples in the lowSig array. - /// - /// - /// This is the array where the high-pass output - /// signal is placed. - /// - /// - /// This is the index in highSig of the element where - /// to put the first high-pass output sample. - /// - /// - /// This is the step, or interleave factor, of the - /// high-pass output samples in the highSig array. - /// - /// - /// - /// - /// - /// - /// - public abstract void analyze_hpf(float[] inSig, int inOff, int inLen, int inStep, float[] lowSig, int lowOff, int lowStep, float[] highSig, int highOff, int highStep); - - - - /// The general version of the analyze_hpf() method, it just calls the - /// specialized version. See the description of the analyze_hpf() - /// method of the AnWTFilter class for more details. - /// - /// - /// This is the array that contains the input - /// signal. It must be an float[]. - /// - /// - /// This is the index in inSig of the first sample to - /// filter. - /// - /// - /// This is the number of samples in the input signal - /// to filter. - /// - /// - /// This is the step, or interleave factor, of the - /// input signal samples in the inSig array. - /// - /// - /// This is the array where the low-pass output - /// signal is placed. It must be an float[]. - /// - /// - /// This is the index in lowSig of the element where - /// to put the first low-pass output sample. - /// - /// - /// This is the step, or interleave factor, of the - /// low-pass output samples in the lowSig array. - /// - /// - /// This is the array where the high-pass output - /// signal is placed. It must be an float[]. - /// - /// - /// This is the index in highSig of the element where - /// to put the first high-pass output sample. - /// - /// - /// This is the step, or interleave factor, of the - /// high-pass output samples in the highSig array. - /// - /// - /// - /// - /// - /// - /// - public override void analyze_hpf(System.Object inSig, int inOff, int inLen, int inStep, System.Object lowSig, int lowOff, int lowStep, System.Object highSig, int highOff, int highStep) - { - - analyze_hpf((float[])inSig, inOff, inLen, inStep, (float[])lowSig, lowOff, lowStep, (float[])highSig, highOff, highStep); - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/wavelet/analysis/AnWTFilterFloatLift9x7.cs b/CSJ2K/j2k/wavelet/analysis/AnWTFilterFloatLift9x7.cs deleted file mode 100644 index 59cf28c8..00000000 --- a/CSJ2K/j2k/wavelet/analysis/AnWTFilterFloatLift9x7.cs +++ /dev/null @@ -1,803 +0,0 @@ -/* -* CVS identifier: -* -* $Id: AnWTFilterFloatLift9x7.java,v 1.18 2002/01/22 13:31:31 grosbois Exp $ -* -* Class: AnWTFilterFloatLift9x7 -* -* Description: An analyzing wavelet filter implementing the -* lifting 9x7 transform. -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -namespace CSJ2K.j2k.wavelet.analysis -{ - - /// This class inherits from the analysis wavelet filter definition - /// for int data. It implements the forward wavelet transform - /// specifically for the 9x7 filter. The implementation is based on - /// the lifting scheme. - /// - ///

    See the AnWTFilter class for details such as - /// normalization, how to split odd-length signals, etc. In particular, - /// this method assumes that the low-pass coefficient is computed first. - /// - ///

    - /// - /// - /// - /// - /// - public class AnWTFilterFloatLift9x7 : AnWTFilterFloat - { - /// Returns the negative support of the low-pass analysis - /// filter. That is the number of taps of the filter in the - /// negative direction. - /// - /// - /// 2 - /// - /// - override public int AnLowNegSupport - { - get - { - return 4; - } - - } - /// Returns the positive support of the low-pass analysis - /// filter. That is the number of taps of the filter in the - /// negative direction. - /// - /// - /// The number of taps of the low-pass analysis filter in - /// the positive direction - /// - /// - override public int AnLowPosSupport - { - get - { - return 4; - } - - } - /// Returns the negative support of the high-pass analysis - /// filter. That is the number of taps of the filter in the - /// negative direction. - /// - /// - /// The number of taps of the high-pass analysis filter in - /// the negative direction - /// - /// - override public int AnHighNegSupport - { - get - { - return 3; - } - - } - /// Returns the positive support of the high-pass analysis - /// filter. That is the number of taps of the filter in the - /// negative direction. - /// - /// - /// The number of taps of the high-pass analysis filter in - /// the positive direction - /// - /// - override public int AnHighPosSupport - { - get - { - return 3; - } - - } - /// Returns the negative support of the low-pass synthesis - /// filter. That is the number of taps of the filter in the - /// negative direction. - /// - ///

    A MORE PRECISE DEFINITION IS NEEDED - /// - ///

    - /// The number of taps of the low-pass synthesis filter in - /// the negative direction - /// - /// - override public int SynLowNegSupport - { - get - { - return 3; - } - - } - /// Returns the positive support of the low-pass synthesis - /// filter. That is the number of taps of the filter in the - /// negative direction. - /// - ///

    A MORE PRECISE DEFINITION IS NEEDED - /// - ///

    - /// The number of taps of the low-pass synthesis filter in - /// the positive direction - /// - /// - override public int SynLowPosSupport - { - get - { - return 3; - } - - } - /// Returns the negative support of the high-pass synthesis - /// filter. That is the number of taps of the filter in the - /// negative direction. - /// - ///

    A MORE PRECISE DEFINITION IS NEEDED - /// - ///

    - /// The number of taps of the high-pass synthesis filter in - /// the negative direction - /// - /// - override public int SynHighNegSupport - { - get - { - return 4; - } - - } - /// Returns the positive support of the high-pass synthesis - /// filter. That is the number of taps of the filter in the - /// negative direction. - /// - ///

    A MORE PRECISE DEFINITION IS NEEDED - /// - ///

    - /// The number of taps of the high-pass synthesis filter in - /// the positive direction - /// - /// - override public int SynHighPosSupport - { - get - { - return 4; - } - - } - /// Returns the implementation type of this filter, as defined in - /// this class, such as WT_FILTER_INT_LIFT, WT_FILTER_FLOAT_LIFT, - /// WT_FILTER_FLOAT_CONVOL. - /// - /// - /// WT_FILTER_INT_LIFT. - /// - /// - override public int ImplType - { - get - { - return CSJ2K.j2k.wavelet.WaveletFilter_Fields.WT_FILTER_FLOAT_LIFT; - } - - } - /// Returns the reversibility of the filter. A filter is considered - /// reversible if it is suitable for lossless coding. - /// - /// - /// true since the 9x7 is reversible, provided the appropriate - /// rounding is performed. - /// - /// - override public bool Reversible - { - get - { - return false; - } - - } - /// Returns the type of filter used according to the FilterTypes - /// interface(W9x7). - /// - /// - /// - /// - /// - /// The filter type. - /// - /// - override public int FilterType - { - get - { - return CSJ2K.j2k.wavelet.FilterTypes_Fields.W9X7; - } - - } - - /// The low-pass synthesis filter of the 9x7 wavelet transform - //UPGRADE_NOTE: Final was removed from the declaration of 'LPSynthesisFilter'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly float[] LPSynthesisFilter = new float[] { -0.091272f, -0.057544f, 0.591272f, 1.115087f, 0.591272f, -0.057544f, -0.091272f }; - - /// The high-pass synthesis filter of the 9x7 wavelet transform - //UPGRADE_NOTE: Final was removed from the declaration of 'HPSynthesisFilter'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly float[] HPSynthesisFilter = new float[] { 0.026749f, 0.016864f, -0.078223f, -0.266864f, 0.602949f, -0.266864f, -0.078223f, 0.016864f, 0.026749f }; - - /// The value of the first lifting step coefficient - public const float ALPHA = -1.586134342f; - - /// The value of the second lifting step coefficient - public const float BETA = -0.05298011854f; - - /// The value of the third lifting step coefficient - public const float GAMMA = 0.8829110762f; - - /// The value of the fourth lifting step coefficient - public const float DELTA = 0.4435068522f; - - /// The value of the low-pass subband normalization factor - public const float KL = 0.8128930655f; - - /// The value of the high-pass subband normalization factor - public const float KH = 1.230174106f; - - /// An implementation of the analyze_lpf() method that works on int - /// data, for the forward 9x7 wavelet transform using the - /// lifting scheme. See the general description of the analyze_lpf() - /// method in the AnWTFilter class for more details. - /// - ///

    The coefficients of the first lifting step are [ALPHA 1 ALPHA]. - /// - ///

    The coefficients of the second lifting step are [BETA 1 BETA]. - /// - ///

    The coefficients of the third lifting step are [GAMMA 1 GAMMA]. - /// - ///

    The coefficients of the fourth lifting step are [DELTA 1 DELTA]. - /// - ///

    The low-pass and high-pass subbands are normalized by respectively - /// a factor of KL and a factor of KH - /// - ///

    - /// This is the array that contains the input - /// signal. - /// - /// - /// This is the index in inSig of the first sample to - /// filter. - /// - /// - /// This is the number of samples in the input signal - /// to filter. - /// - /// - /// This is the step, or interleave factor, of the - /// input signal samples in the inSig array. - /// - /// - /// This is the array where the low-pass output - /// signal is placed. - /// - /// - /// This is the index in lowSig of the element where - /// to put the first low-pass output sample. - /// - /// - /// This is the step, or interleave factor, of the - /// low-pass output samples in the lowSig array. - /// - /// - /// This is the array where the high-pass output - /// signal is placed. - /// - /// - /// This is the index in highSig of the element where - /// to put the first high-pass output sample. - /// - /// - /// This is the step, or interleave factor, of the - /// high-pass output samples in the highSig array. - /// - /// - public override void analyze_lpf(float[] inSig, int inOff, int inLen, int inStep, float[] lowSig, int lowOff, int lowStep, float[] highSig, int highOff, int highStep) - { - int i, maxi; - int iStep = 2 * inStep; //Subsampling in inSig - int ik; //Indexing inSig - int lk; //Indexing lowSig - int hk; //Indexing highSig - - // Generate intermediate high frequency subband - - //Initialize counters - ik = inOff + inStep; - lk = lowOff; - hk = highOff; - - //Apply first lifting step to each "inner" sample - for (i = 1, maxi = inLen - 1; i < maxi; i += 2) - { - highSig[hk] = inSig[ik] + ALPHA * (inSig[ik - inStep] + inSig[ik + inStep]); - - ik += iStep; - hk += highStep; - } - - //Handle head boundary effect if input signal has even length - if (inLen % 2 == 0) - { - highSig[hk] = inSig[ik] + 2 * ALPHA * inSig[ik - inStep]; - } - - // Generate intermediate low frequency subband - - //Initialize counters - ik = inOff; - lk = lowOff; - hk = highOff; - - if (inLen > 1) - { - lowSig[lk] = inSig[ik] + 2 * BETA * highSig[hk]; - } - else - { - lowSig[lk] = inSig[ik]; - } - - ik += iStep; - lk += lowStep; - hk += highStep; - - //Apply lifting step to each "inner" sample - for (i = 2, maxi = inLen - 1; i < maxi; i += 2) - { - lowSig[lk] = inSig[ik] + BETA * (highSig[hk - highStep] + highSig[hk]); - - ik += iStep; - lk += lowStep; - hk += highStep; - } - - //Handle head boundary effect if input signal has odd length - if ((inLen % 2 == 1) && (inLen > 2)) - { - lowSig[lk] = inSig[ik] + 2 * BETA * highSig[hk - highStep]; - } - - // Generate high frequency subband - - //Initialize counters - lk = lowOff; - hk = highOff; - - //Apply first lifting step to each "inner" sample - for (i = 1, maxi = inLen - 1; i < maxi; i += 2) - { - highSig[hk] += GAMMA * (lowSig[lk] + lowSig[lk + lowStep]); - - lk += lowStep; - hk += highStep; - } - - //Handle head boundary effect if input signal has even length - if (inLen % 2 == 0) - { - highSig[hk] += 2 * GAMMA * lowSig[lk]; - } - - // Generate low frequency subband - - //Initialize counters - lk = lowOff; - hk = highOff; - - //Handle tail boundary effect - //If access the overlap then perform the lifting step - if (inLen > 1) - { - lowSig[lk] += 2 * DELTA * highSig[hk]; - } - - lk += lowStep; - hk += highStep; - - //Apply lifting step to each "inner" sample - for (i = 2, maxi = inLen - 1; i < maxi; i += 2) - { - lowSig[lk] += DELTA * (highSig[hk - highStep] + highSig[hk]); - - lk += lowStep; - hk += highStep; - } - - //Handle head boundary effect if input signal has odd length - if ((inLen % 2 == 1) && (inLen > 2)) - { - lowSig[lk] += 2 * DELTA * highSig[hk - highStep]; - } - - // Normalize low and high frequency subbands - - //Re-initialize counters - lk = lowOff; - hk = highOff; - - //Normalize each sample - for (i = 0; i < (inLen >> 1); i++) - { - lowSig[lk] *= KL; - highSig[hk] *= KH; - lk += lowStep; - hk += highStep; - } - //If the input signal has odd length then normalize the last low-pass - //coefficient (if input signal is length one filter is identity) - if (inLen % 2 == 1 && inLen != 1) - { - lowSig[lk] *= KL; - } - } - - /// An implementation of the analyze_hpf() method that works on int - /// data, for the forward 9x7 wavelet transform using the - /// lifting scheme. See the general description of the analyze_hpf() method - /// in the AnWTFilter class for more details. - /// - ///

    The coefficients of the first lifting step are [ALPHA 1 ALPHA]. - /// - ///

    The coefficients of the second lifting step are [BETA 1 BETA]. - /// - ///

    The coefficients of the third lifting step are [GAMMA 1 GAMMA]. - /// - ///

    The coefficients of the fourth lifting step are [DELTA 1 DELTA]. - /// - ///

    The low-pass and high-pass subbands are normalized by respectively - /// a factor of KL and a factor of KH - /// - ///

    - /// This is the array that contains the input - /// signal. - /// - /// - /// This is the index in inSig of the first sample to - /// filter. - /// - /// - /// This is the number of samples in the input signal - /// to filter. - /// - /// - /// This is the step, or interleave factor, of the - /// input signal samples in the inSig array. - /// - /// - /// This is the array where the low-pass output - /// signal is placed. - /// - /// - /// This is the index in lowSig of the element where - /// to put the first low-pass output sample. - /// - /// - /// This is the step, or interleave factor, of the - /// low-pass output samples in the lowSig array. - /// - /// - /// This is the array where the high-pass output - /// signal is placed. - /// - /// - /// This is the index in highSig of the element where - /// to put the first high-pass output sample. - /// - /// - /// This is the step, or interleave factor, of the - /// high-pass output samples in the highSig array. - /// - /// - /// - /// - /// - public override void analyze_hpf(float[] inSig, int inOff, int inLen, int inStep, float[] lowSig, int lowOff, int lowStep, float[] highSig, int highOff, int highStep) - { - - int i; // maxi removed - int iStep = 2 * inStep; //Subsampling in inSig - int ik; //Indexing inSig - int lk; //Indexing lowSig - int hk; //Indexing highSig - - // Generate intermediate high frequency subband - - //Initialize counters - ik = inOff; - lk = lowOff; - hk = highOff; - - if (inLen > 1) - { - // apply symmetric extension. - highSig[hk] = inSig[ik] + 2 * ALPHA * inSig[ik + inStep]; - } - else - { - // Normalize for Nyquist gain - highSig[hk] = inSig[ik] * 2; - } - - ik += iStep; - hk += highStep; - - //Apply first lifting step to each "inner" sample - for (i = 2; i < inLen - 1; i += 2) - { - highSig[hk] = inSig[ik] + ALPHA * (inSig[ik - inStep] + inSig[ik + inStep]); - ik += iStep; - hk += highStep; - } - - //If input signal has odd length then we perform the lifting step - // i.e. apply a symmetric extension. - if ((inLen % 2 == 1) && (inLen > 1)) - { - highSig[hk] = inSig[ik] + 2 * ALPHA * inSig[ik - inStep]; - } - - // Generate intermediate low frequency subband - - //Initialize counters - //ik = inOff + inStep; - ik = inOff + inStep; - lk = lowOff; - hk = highOff; - - //Apply lifting step to each "inner" sample - // we are at the component boundary - for (i = 1; i < inLen - 1; i += 2) - { - lowSig[lk] = inSig[ik] + BETA * (highSig[hk] + highSig[hk + highStep]); - - ik += iStep; - lk += lowStep; - hk += highStep; - } - if (inLen > 1 && inLen % 2 == 0) - { - // symetric extension - lowSig[lk] = inSig[ik] + 2 * BETA * highSig[hk]; - } - - // Generate high frequency subband - - //Initialize counters - lk = lowOff; - hk = highOff; - - if (inLen > 1) - { - // symmetric extension. - highSig[hk] += GAMMA * 2 * lowSig[lk]; - } - //lk += lowStep; - hk += highStep; - - //Apply first lifting step to each "inner" sample - for (i = 2; i < inLen - 1; i += 2) - { - highSig[hk] += GAMMA * (lowSig[lk] + lowSig[lk + lowStep]); - lk += lowStep; - hk += highStep; - } - - //Handle head boundary effect - if (inLen > 1 && inLen % 2 == 1) - { - // symmetric extension. - highSig[hk] += GAMMA * 2 * lowSig[lk]; - } - - // Generate low frequency subband - - //Initialize counters - lk = lowOff; - hk = highOff; - - // we are at the component boundary - for (i = 1; i < inLen - 1; i += 2) - { - lowSig[lk] += DELTA * (highSig[hk] + highSig[hk + highStep]); - lk += lowStep; - hk += highStep; - } - - if (inLen > 1 && inLen % 2 == 0) - { - lowSig[lk] += DELTA * 2 * highSig[hk]; - } - - // Normalize low and high frequency subbands - - //Re-initialize counters - lk = lowOff; - hk = highOff; - - //Normalize each sample - for (i = 0; i < (inLen >> 1); i++) - { - lowSig[lk] *= KL; - highSig[hk] *= KH; - lk += lowStep; - hk += highStep; - } - //If the input signal has odd length then normalize the last high-pass - //coefficient (if input signal is length one filter is identity) - if (inLen % 2 == 1 && inLen != 1) - { - highSig[hk] *= KH; - } - } - - /// Returns the time-reversed low-pass synthesis waveform of the - /// filter, which is the low-pass filter. This is the time-reversed - /// impulse response of the low-pass synthesis filter. It is used - /// to calculate the L2-norm of the synthesis basis functions for a - /// particular subband (also called energy weight). - /// - ///

    The returned array may not be modified (i.e. a reference to - /// the internal array may be returned by the implementation of - /// this method). - /// - ///

    - /// The time-reversed low-pass synthesis waveform of the - /// filter. - /// - /// - public override float[] getLPSynthesisFilter() - { - return LPSynthesisFilter; - } - - /// Returns the time-reversed high-pass synthesis waveform of the - /// filter, which is the high-pass filter. This is the - /// time-reversed impulse response of the high-pass synthesis - /// filter. It is used to calculate the L2-norm of the synthesis - /// basis functions for a particular subband (also called energy - /// weight). - /// - ///

    The returned array may not be modified (i.e. a reference to - /// the internal array may be returned by the implementation of - /// this method). - /// - ///

    - /// The time-reversed high-pass synthesis waveform of the - /// filter. - /// - /// - public override float[] getHPSynthesisFilter() - { - return HPSynthesisFilter; - } - - /// Returns true if the wavelet filter computes or uses the - /// same "inner" subband coefficient as the full frame wavelet transform, - /// and false otherwise. In particular, for block based transforms with - /// reduced overlap, this method should return false. The term "inner" - /// indicates that this applies only with respect to the coefficient that - /// are not affected by image boundaries processings such as symmetric - /// extension, since there is not reference method for this. - /// - ///

    The result depends on the length of the allowed overlap when - /// compared to the overlap required by the wavelet filter. It also - /// depends on how overlap processing is implemented in the wavelet - /// filter. - /// - ///

    - /// This is the number of samples in the input - /// signal before the first sample to filter that can be used for - /// overlap. - /// - /// - /// This is the number of samples in the input - /// signal after the last sample to filter that can be used for - /// overlap. - /// - /// - /// This is the lenght of the input signal to filter.The - /// required number of samples in the input signal after the last sample - /// depends on the length of the input signal. - /// - /// - /// true if both overlaps are greater than 2, and correct - /// processing is applied in the analyze() method. - /// - /// - public override bool isSameAsFullWT(int tailOvrlp, int headOvrlp, int inLen) - { - - //If the input signal has even length. - if (inLen % 2 == 0) - { - if (tailOvrlp >= 4 && headOvrlp >= 3) - return true; - else - return false; - } - //Else if the input signal has odd length. - else - { - if (tailOvrlp >= 4 && headOvrlp >= 4) - return true; - else - return false; - } - } - - /// Tests if the 'obj' object is the same filter as this one. Two filters - /// are the same if the same filter code should be output for both filters - /// by the encodeFilterCode() method. - /// - ///

    Currently the implementation of this method only tests if 'obj' is - /// also of the class AnWTFilterFloatLift9x7 - /// - ///

    - /// object against which to test inequality. - /// - /// - public override bool Equals(System.Object obj) - { - // To spped up test, first test for reference equality - return obj == this || obj is AnWTFilterFloatLift9x7; - } - - /// Debugging method - public override System.String ToString() - { - return "w9x7"; - } - //UPGRADE_NOTE: The following method implementation was automatically added to preserve functionality. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1306'" - public override int GetHashCode() - { - return base.GetHashCode(); - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/wavelet/analysis/AnWTFilterInt.cs b/CSJ2K/j2k/wavelet/analysis/AnWTFilterInt.cs deleted file mode 100644 index 25567cca..00000000 --- a/CSJ2K/j2k/wavelet/analysis/AnWTFilterInt.cs +++ /dev/null @@ -1,315 +0,0 @@ -/* -* CVS identifier: -* -* $Id: AnWTFilterInt.java,v 1.7 2000/09/05 09:25:42 grosbois Exp $ -* -* Class: AnWTFilterInt -* -* Description: A specialized wavelet filter interface that -* works on int data. -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* -* -* -*/ -using CSJ2K.j2k.image; -namespace CSJ2K.j2k.wavelet.analysis -{ - - /// This extends the analysis wavelet filter general definitions of - /// AnWTFilter by adding methods that work for int data - /// specifically. Implementations that work on int data should inherit - /// from this class. - /// - ///

    See the AnWTFilter class for details such as - /// normalization, how to split odd-length signals, etc. - /// - ///

    The advantage of using the specialized method is that no casts - /// are performed. - /// - ///

    - /// - /// - /// - public abstract class AnWTFilterInt : AnWTFilter - { - /// Returns the type of data on which this filter works, as defined - /// in the DataBlk interface, which is always TYPE_INT for this - /// class. - /// - /// - /// The type of data as defined in the DataBlk interface. - /// - /// - /// - /// - /// - /// - /// - override public int DataType - { - get - { - return DataBlk.TYPE_INT; - } - - } - - /// A specific version of the analyze_lpf() method that works on int - /// data. See the general description of the analyze_lpf() method in - /// the AnWTFilter class for more details. - /// - /// - /// This is the array that contains the input - /// signal. - /// - /// - /// This is the index in inSig of the first sample to - /// filter. - /// - /// - /// This is the number of samples in the input signal - /// to filter. - /// - /// - /// This is the step, or interleave factor, of the - /// input signal samples in the inSig array. - /// - /// - /// This is the array where the low-pass output - /// signal is placed. - /// - /// - /// This is the index in lowSig of the element where - /// to put the first low-pass output sample. - /// - /// - /// This is the step, or interleave factor, of the - /// low-pass output samples in the lowSig array. - /// - /// - /// This is the array where the high-pass output - /// signal is placed. - /// - /// - /// This is the index in highSig of the element where - /// to put the first high-pass output sample. - /// - /// - /// This is the step, or interleave factor, of the - /// high-pass output samples in the highSig array. - /// - /// - /// - /// - /// - /// - /// - /// - /// - public abstract void analyze_lpf(int[] inSig, int inOff, int inLen, int inStep, int[] lowSig, int lowOff, int lowStep, int[] highSig, int highOff, int highStep); - - /// The general version of the analyze_lpf() method, it just calls the - /// specialized version. See the description of the analyze_lpf() - /// method of the AnWTFilter class for more details. - /// - /// - /// This is the array that contains the input - /// signal. It must be an int[]. - /// - /// - /// This is the index in inSig of the first sample to - /// filter. - /// - /// - /// This is the number of samples in the input signal - /// to filter. - /// - /// - /// This is the step, or interleave factor, of the - /// input signal samples in the inSig array. - /// - /// - /// This is the array where the low-pass output - /// signal is placed. It must be an int[]. - /// - /// - /// This is the index in lowSig of the element where - /// to put the first low-pass output sample. - /// - /// - /// This is the step, or interleave factor, of the - /// low-pass output samples in the lowSig array. - /// - /// - /// This is the array where the high-pass output - /// signal is placed. It must be an int[]. - /// - /// - /// This is the index in highSig of the element where - /// to put the first high-pass output sample. - /// - /// - /// This is the step, or interleave factor, of the - /// high-pass output samples in the highSig array. - /// - /// - /// - /// - /// - /// - /// - /// - /// - - public override void analyze_lpf(System.Object inSig, int inOff, int inLen, int inStep, System.Object lowSig, int lowOff, int lowStep, System.Object highSig, int highOff, int highStep) - { - - analyze_lpf((int[])inSig, inOff, inLen, inStep, (int[])lowSig, lowOff, lowStep, (int[])highSig, highOff, highStep); - } - - /// A specific version of the analyze_hpf() method that works on int - /// data. See the general description of the analyze_hpf() method in - /// the AnWTFilter class for more details. - /// - /// - /// This is the array that contains the input - /// signal. - /// - /// - /// This is the index in inSig of the first sample to - /// filter. - /// - /// - /// This is the number of samples in the input signal - /// to filter. - /// - /// - /// This is the step, or interleave factor, of the - /// input signal samples in the inSig array. - /// - /// - /// This is the array where the low-pass output - /// signal is placed. - /// - /// - /// This is the index in lowSig of the element where - /// to put the first low-pass output sample. - /// - /// - /// This is the step, or interleave factor, of the - /// low-pass output samples in the lowSig array. - /// - /// - /// This is the array where the high-pass output - /// signal is placed. - /// - /// - /// This is the index in highSig of the element where - /// to put the first high-pass output sample. - /// - /// - /// This is the step, or interleave factor, of the - /// high-pass output samples in the highSig array. - /// - /// - /// - /// - /// - /// - /// - /// - /// - public abstract void analyze_hpf(int[] inSig, int inOff, int inLen, int inStep, int[] lowSig, int lowOff, int lowStep, int[] highSig, int highOff, int highStep); - /// The general version of the analyze_hpf() method, it just calls the - /// specialized version. See the description of the analyze_hpf() - /// method of the AnWTFilter class for more details. - /// - /// - /// This is the array that contains the input - /// signal. It must be an int[]. - /// - /// - /// This is the index in inSig of the first sample to - /// filter. - /// - /// - /// This is the number of samples in the input signal - /// to filter. - /// - /// - /// This is the step, or interleave factor, of the - /// input signal samples in the inSig array. - /// - /// - /// This is the array where the low-pass output - /// signal is placed. It must be an int[]. - /// - /// - /// This is the index in lowSig of the element where - /// to put the first low-pass output sample. - /// - /// - /// This is the step, or interleave factor, of the - /// low-pass output samples in the lowSig array. - /// - /// - /// This is the array where the high-pass output - /// signal is placed. It must be an int[]. - /// - /// - /// This is the index in highSig of the element where - /// to put the first high-pass output sample. - /// - /// - /// This is the step, or interleave factor, of the - /// high-pass output samples in the highSig array. - /// - /// - /// - /// - /// - /// - /// - /// - /// - - public override void analyze_hpf(System.Object inSig, int inOff, int inLen, int inStep, System.Object lowSig, int lowOff, int lowStep, System.Object highSig, int highOff, int highStep) - { - - analyze_hpf((int[])inSig, inOff, inLen, inStep, (int[])lowSig, lowOff, lowStep, (int[])highSig, highOff, highStep); - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/wavelet/analysis/AnWTFilterIntLift5x3.cs b/CSJ2K/j2k/wavelet/analysis/AnWTFilterIntLift5x3.cs deleted file mode 100644 index ef481338..00000000 --- a/CSJ2K/j2k/wavelet/analysis/AnWTFilterIntLift5x3.cs +++ /dev/null @@ -1,604 +0,0 @@ -/* -* CVS identifier: -* -* $Id: AnWTFilterIntLift5x3.java,v 1.15 2001/08/02 11:19:27 grosbois Exp $ -* -* Class: AnWTFilterIntLift5x3 -* -* Description: An analyzing wavelet filter implementing the -* lifting 5x3 transform. -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -namespace CSJ2K.j2k.wavelet.analysis -{ - - /// This class inherits from the analysis wavelet filter definition for int - /// data. It implements the forward wavelet transform specifically for the 5x3 - /// filter. The implementation is based on the lifting scheme. - /// - ///

    See the AnWTFilter class for details such as normalization, how to split - /// odd-length signals, etc. In particular, this method assumes that the - /// low-pass coefficient is computed first.

    - /// - ///
    - /// - /// - /// - /// - /// - public class AnWTFilterIntLift5x3 : AnWTFilterInt - { - /// Returns the negative support of the low-pass analysis filter. That is - /// the number of taps of the filter in the negative direction. - /// - /// - /// 2 - /// - /// - override public int AnLowNegSupport - { - get - { - return 2; - } - - } - /// Returns the positive support of the low-pass analysis filter. That is - /// the number of taps of the filter in the negative direction. - /// - /// - /// The number of taps of the low-pass analysis filter in the - /// positive direction - /// - /// - override public int AnLowPosSupport - { - get - { - return 2; - } - - } - /// Returns the negative support of the high-pass analysis filter. That is - /// the number of taps of the filter in the negative direction. - /// - /// - /// The number of taps of the high-pass analysis filter in - /// the negative direction - /// - /// - override public int AnHighNegSupport - { - get - { - return 1; - } - - } - /// Returns the positive support of the high-pass analysis filter. That is - /// the number of taps of the filter in the negative direction. - /// - /// - /// The number of taps of the high-pass analysis filter in the - /// positive direction - /// - /// - override public int AnHighPosSupport - { - get - { - return 1; - } - - } - /// Returns the negative support of the low-pass synthesis filter. That is - /// the number of taps of the filter in the negative direction. - /// - /// - /// The number of taps of the low-pass synthesis filter in the - /// negative direction - /// - /// - override public int SynLowNegSupport - { - get - { - return 1; - } - - } - /// Returns the positive support of the low-pass synthesis filter. That is - /// the number of taps of the filter in the negative direction. - /// - /// - /// The number of taps of the low-pass synthesis filter in - /// the positive direction - /// - /// - override public int SynLowPosSupport - { - get - { - return 1; - } - - } - /// Returns the negative support of the high-pass synthesis filter. That is - /// the number of taps of the filter in the negative direction. - /// - /// - /// The number of taps of the high-pass synthesis filter in the - /// negative direction - /// - /// - override public int SynHighNegSupport - { - get - { - return 2; - } - - } - /// Returns the positive support of the high-pass synthesis filter. That is - /// the number of taps of the filter in the negative direction. - /// - /// - /// The number of taps of the high-pass synthesis filter in the - /// positive direction - /// - /// - override public int SynHighPosSupport - { - get - { - return 2; - } - - } - /// Returns the implementation type of this filter, as defined in this - /// class, such as WT_FILTER_INT_LIFT, WT_FILTER_FLOAT_LIFT, - /// WT_FILTER_FLOAT_CONVOL. - /// - /// - /// WT_FILTER_INT_LIFT. - /// - /// - override public int ImplType - { - get - { - return CSJ2K.j2k.wavelet.WaveletFilter_Fields.WT_FILTER_INT_LIFT; - } - - } - /// Returns the reversibility of the filter. A filter is considered - /// reversible if it is suitable for lossless coding. - /// - /// - /// true since the 5x3 is reversible, provided the appropriate - /// rounding is performed. - /// - /// - override public bool Reversible - { - get - { - return true; - } - - } - /// Returns the type of filter used according to the FilterTypes interface - /// (W5x3). - /// - /// - /// - /// - /// - /// The filter type. - /// - /// - override public int FilterType - { - get - { - return CSJ2K.j2k.wavelet.FilterTypes_Fields.W5X3; - } - - } - - /// The low-pass synthesis filter of the 5x3 wavelet transform - //UPGRADE_NOTE: Final was removed from the declaration of 'LPSynthesisFilter'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly float[] LPSynthesisFilter = new float[] { 0.5f, 1f, 0.5f }; - - /// The high-pass synthesis filter of the 5x3 wavelet transform - //UPGRADE_NOTE: Final was removed from the declaration of 'HPSynthesisFilter'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly float[] HPSynthesisFilter = new float[] { -0.125f, -0.25f, 0.75f, -0.25f, -0.125f }; - - /// An implementation of the analyze_lpf() method that works on int data, - /// for the forward 5x3 wavelet transform using the lifting scheme. See the - /// general description of the analyze_lpf() method in the AnWTFilter class - /// for more details. - /// - ///

    The coefficients of the first lifting step are [-1/2 1 -1/2].

    - /// - ///

    The coefficients of the second lifting step are [1/4 1 1/4].

    - /// - ///
    - /// This is the array that contains the input signal. - /// - /// - /// This is the index in inSig of the first sample to filter. - /// - /// - /// This is the number of samples in the input signal to - /// filter. - /// - /// - /// This is the step, or interleave factor, of the input - /// signal samples in the inSig array. - /// - /// - /// This is the array where the low-pass output signal is - /// placed. - /// - /// - /// This is the index in lowSig of the element where to put - /// the first low-pass output sample. - /// - /// - /// This is the step, or interleave factor, of the low-pass - /// output samples in the lowSig array. - /// - /// - /// This is the array where the high-pass output signal is - /// placed. - /// - /// - /// This is the index in highSig of the element where to put - /// the first high-pass output sample. - /// - /// - /// This is the step, or interleave factor, of the - /// high-pass output samples in the highSig array. - /// - /// - public override void analyze_lpf(int[] inSig, int inOff, int inLen, int inStep, int[] lowSig, int lowOff, int lowStep, int[] highSig, int highOff, int highStep) - { - int i; - int iStep = 2 * inStep; //Subsampling in inSig - int ik; //Indexing inSig - int lk; //Indexing lowSig - int hk; //Indexing highSig - - /* Generate high frequency subband */ - - //Initialize counters - ik = inOff + inStep; - hk = highOff; - - //Apply first lifting step to each "inner" sample. - for (i = 1; i < inLen - 1; i += 2) - { - highSig[hk] = inSig[ik] - ((inSig[ik - inStep] + inSig[ik + inStep]) >> 1); - - ik += iStep; - hk += highStep; - } - - //Handle head boundary effect if input signal has even length. - if (inLen % 2 == 0) - { - highSig[hk] = inSig[ik] - ((2 * inSig[ik - inStep]) >> 1); - } - - /* Generate low frequency subband */ - - //Initialize counters - ik = inOff; - lk = lowOff; - hk = highOff; - - if (inLen > 1) - { - lowSig[lk] = inSig[ik] + ((highSig[hk] + 1) >> 1); - } - else - { - lowSig[lk] = inSig[ik]; - } - - ik += iStep; - lk += lowStep; - hk += highStep; - - //Apply lifting step to each "inner" sample. - for (i = 2; i < inLen - 1; i += 2) - { - lowSig[lk] = inSig[ik] + ((highSig[hk - highStep] + highSig[hk] + 2) >> 2); - - ik += iStep; - lk += lowStep; - hk += highStep; - } - - //Handle head boundary effect if input signal has odd length. - if (inLen % 2 == 1) - { - if (inLen > 2) - { - lowSig[lk] = inSig[ik] + ((2 * highSig[hk - highStep] + 2) >> 2); - } - } - } - - /// An implementation of the analyze_hpf() method that works on int data, - /// for the forward 5x3 wavelet transform using the lifting scheme. See the - /// general description of the analyze_hpf() method in the AnWTFilter class - /// for more details. - /// - ///

    The coefficients of the first lifting step are [-1/2 1 -1/2].

    - /// - ///

    The coefficients of the second lifting step are [1/4 1 1/4].

    - /// - ///
    - /// This is the array that contains the input signal. - /// - /// - /// This is the index in inSig of the first sample to filter. - /// - /// - /// This is the number of samples in the input signal to - /// filter. - /// - /// - /// This is the step, or interleave factor, of the input - /// signal samples in the inSig array. - /// - /// - /// This is the array where the low-pass output signal is - /// placed. - /// - /// - /// This is the index in lowSig of the element where to put - /// the first low-pass output sample. - /// - /// - /// This is the step, or interleave factor, of the low-pass - /// output samples in the lowSig array. - /// - /// - /// This is the array where the high-pass output signal is - /// placed. - /// - /// - /// This is the index in highSig of the element where to put - /// the first high-pass output sample. - /// - /// - /// This is the step, or interleave factor, of the - /// high-pass output samples in the highSig array. - /// - /// - /// - /// - /// - public override void analyze_hpf(int[] inSig, int inOff, int inLen, int inStep, int[] lowSig, int lowOff, int lowStep, int[] highSig, int highOff, int highStep) - { - int i; - int iStep = 2 * inStep; //Subsampling in inSig - int ik; //Indexing inSig - int lk; //Indexing lowSig - int hk; //Indexing highSig - - /* Generate high frequency subband */ - - //Initialize counters - ik = inOff; - hk = highOff; - - if (inLen > 1) - { - // apply a symmetric extension. - highSig[hk] = inSig[ik] - inSig[ik + inStep]; - } - else - { - // Normalize for Nyquist gain - highSig[hk] = inSig[ik] << 1; - } - - ik += iStep; - hk += highStep; - - //Apply first lifting step to each "inner" sample. - if (inLen > 3) - { - for (i = 2; i < inLen - 1; i += 2) - { - highSig[hk] = inSig[ik] - ((inSig[ik - inStep] + inSig[ik + inStep]) >> 1); - ik += iStep; - hk += highStep; - } - } - - //If input signal has odd length then we perform the lifting step - //i.e. apply a symmetric extension. - if (inLen % 2 == 1 && inLen > 1) - { - highSig[hk] = inSig[ik] - inSig[ik - inStep]; - } - - /* Generate low frequency subband */ - - //Initialize counters - ik = inOff + inStep; - lk = lowOff; - hk = highOff; - - for (i = 1; i < inLen - 1; i += 2) - { - - lowSig[lk] = inSig[ik] + ((highSig[hk] + highSig[hk + highStep] + 2) >> 2); - - ik += iStep; - lk += lowStep; - hk += highStep; - } - - if (inLen > 1 && inLen % 2 == 0) - { - // apply a symmetric extension. - lowSig[lk] = inSig[ik] + ((2 * highSig[hk] + 2) >> 2); - } - } - - /// Returns the time-reversed low-pass synthesis waveform of the filter, - /// which is the low-pass filter. This is the time-reversed impulse - /// response of the low-pass synthesis filter. It is used to calculate the - /// L2-norm of the synthesis basis functions for a particular subband (also - /// called energy weight). - /// - ///

    The returned array may not be modified (i.e. a reference to the - /// internal array may be returned by the implementation of this - /// method).

    - /// - ///
    - /// The time-reversed low-pass synthesis waveform of the filter. - /// - /// - public override float[] getLPSynthesisFilter() - { - return LPSynthesisFilter; - } - - /// Returns the time-reversed high-pass synthesis waveform of the filter, - /// which is the high-pass filter. This is the time-reversed impulse - /// response of the high-pass synthesis filter. It is used to calculate the - /// L2-norm of the synthesis basis functions for a particular subband (also - /// called energy weight). - /// - ///

    The returned array may not be modified (i.e. a reference to the - /// internal array may be returned by the implementation of this - /// method).

    - /// - ///
    - /// The time-reversed high-pass synthesis waveform of the filter. - /// - /// - public override float[] getHPSynthesisFilter() - { - return HPSynthesisFilter; - } - - /// Returns true if the wavelet filter computes or uses the same "inner" - /// subband coefficient as the full frame wavelet transform, and false - /// otherwise. In particular, for block based transforms with reduced - /// overlap, this method should return false. The term "inner" indicates - /// that this applies only with respect to the coefficient that are not - /// affected by image boundaries processings such as symmetric extension, - /// since there is not reference method for this. - /// - ///

    The result depends on the length of the allowed overlap when - /// compared to the overlap required by the wavelet filter. It also depends - /// on how overlap processing is implemented in the wavelet filter.

    - /// - ///
    - /// This is the number of samples in the input signal - /// before the first sample to filter that can be used for overlap. - /// - /// - /// This is the number of samples in the input signal - /// after the last sample to filter that can be used for overlap. - /// - /// - /// This is the lenght of the input signal to filter.The - /// required number of samples in the input signal after the last sample - /// depends on the length of the input signal. - /// - /// - /// true if both overlaps are greater than 2, and correct - /// processing is applied in the analyze() method. - /// - /// - public override bool isSameAsFullWT(int tailOvrlp, int headOvrlp, int inLen) - { - - //If the input signal has even length. - if (inLen % 2 == 0) - { - if (tailOvrlp >= 2 && headOvrlp >= 1) - return true; - else - return false; - } - //Else if the input signal has odd length. - else - { - if (tailOvrlp >= 2 && headOvrlp >= 2) - return true; - else - return false; - } - } - - /// Tests if the 'obj' object is the same filter as this one. Two filters - /// are the same if the same filter code should be output for both filters - /// by the encodeFilterCode() method. - /// - ///

    Currently the implementation of this method only tests if 'obj' is - /// also of the class AnWTFilterIntLift5x3.

    - /// - ///
    - /// object against which to test inequality. - /// - /// - public override bool Equals(System.Object obj) - { - // To speed up test, first test for reference equality - return obj == this || obj is AnWTFilterIntLift5x3; - } - - /// Debugging method - public override System.String ToString() - { - return "w5x3"; - } - //UPGRADE_NOTE: The following method implementation was automatically added to preserve functionality. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1306'" - public override int GetHashCode() - { - return base.GetHashCode(); - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/wavelet/analysis/AnWTFilterSpec.cs b/CSJ2K/j2k/wavelet/analysis/AnWTFilterSpec.cs deleted file mode 100644 index ecc6ddf7..00000000 --- a/CSJ2K/j2k/wavelet/analysis/AnWTFilterSpec.cs +++ /dev/null @@ -1,554 +0,0 @@ -/* -* CVS identifier: -* -* $Id: AnWTFilterSpec.java,v 1.27 2001/05/08 16:11:37 grosbois Exp $ -* -* Class: AnWTFilterSpec -* -* Description: Analysis filters specification -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.quantization; -using CSJ2K.j2k.util; -namespace CSJ2K.j2k.wavelet.analysis -{ - - /// This class extends ModuleSpec class for analysis filters specification - /// holding purpose. - /// - /// - /// - /// - /// - public class AnWTFilterSpec : ModuleSpec - { - - /// The reversible default filter - private const System.String REV_FILTER_STR = "w5x3"; - - /// The non-reversible default filter - private const System.String NON_REV_FILTER_STR = "w9x7"; - - /// Constructs a new 'AnWTFilterSpec' for the specified number of - /// components and tiles. - /// - /// - /// The number of tiles - /// - /// - /// The number of components - /// - /// - /// the type of the specification module i.e. tile specific, - /// component specific or both. - /// - /// - /// Quantization specifications - /// - /// - /// The ParameterList - /// - /// - public AnWTFilterSpec(int nt, int nc, byte type, QuantTypeSpec qts, ParameterList pl) : base(nt, nc, type) - { - - // Check parameters - pl.checkList(AnWTFilter.OPT_PREFIX, CSJ2K.j2k.util.ParameterList.toNameArray(AnWTFilter.ParameterInfo)); - - System.String param = pl.getParameter("Ffilters"); - bool isFilterSpecified = true; - - // No parameter specified - if (param == null) - { - isFilterSpecified = false; - - // If lossless compression, uses the reversible filters in each - // tile-components - if (pl.getBooleanParameter("lossless")) - { - setDefault(parseFilters(REV_FILTER_STR)); - return; - } - - // If no filter is specified through the command-line, use - // REV_FILTER_STR or NON_REV_FILTER_STR according to the - // quantization type - for (int t = nt - 1; t >= 0; t--) - { - for (int c = nc - 1; c >= 0; c--) - { - switch (qts.getSpecValType(t, c)) - { - - case SPEC_DEF: - if (getDefault() == null) - { - if (pl.getBooleanParameter("lossless")) - setDefault(parseFilters(REV_FILTER_STR)); - if (((System.String)qts.getDefault()).Equals("reversible")) - { - setDefault(parseFilters(REV_FILTER_STR)); - } - else - { - setDefault(parseFilters(NON_REV_FILTER_STR)); - } - } - specValType[t][c] = SPEC_DEF; - break; - - case SPEC_COMP_DEF: - if (!isCompSpecified(c)) - { - if (((System.String)qts.getCompDef(c)).Equals("reversible")) - { - setCompDef(c, parseFilters(REV_FILTER_STR)); - } - else - { - setCompDef(c, parseFilters(NON_REV_FILTER_STR)); - } - } - specValType[t][c] = SPEC_COMP_DEF; - break; - - case SPEC_TILE_DEF: - if (!isTileSpecified(t)) - { - if (((System.String)qts.getTileDef(t)).Equals("reversible")) - { - setTileDef(t, parseFilters(REV_FILTER_STR)); - } - else - { - setTileDef(t, parseFilters(NON_REV_FILTER_STR)); - } - } - specValType[t][c] = SPEC_TILE_DEF; - break; - - case SPEC_TILE_COMP: - if (!isTileCompSpecified(t, c)) - { - if (((System.String)qts.getTileCompVal(t, c)).Equals("reversible")) - { - setTileCompVal(t, c, parseFilters(REV_FILTER_STR)); - } - else - { - setTileCompVal(t, c, parseFilters(NON_REV_FILTER_STR)); - } - } - specValType[t][c] = SPEC_TILE_COMP; - break; - - default: - throw new System.ArgumentException("Unsupported " + "specification " + "type"); - - } - } - } - return; - } - - // Parse argument - SupportClass.Tokenizer stk = new SupportClass.Tokenizer(param); - System.String word; // current word - byte curSpecType = SPEC_DEF; // Specification type of the - // current parameter - bool[] tileSpec = null; // Tiles concerned by the specification - bool[] compSpec = null; // Components concerned by the specification - AnWTFilter[][] filter; - - while (stk.HasMoreTokens()) - { - word = stk.NextToken(); - - switch (word[0]) - { - - case 't': - // Tiles specification - case 'T': // Tiles specification - tileSpec = parseIdx(word, nTiles); - if (curSpecType == SPEC_COMP_DEF) - curSpecType = SPEC_TILE_COMP; - else - curSpecType = SPEC_TILE_DEF; - break; - - case 'c': - // Components specification - case 'C': // Components specification - compSpec = parseIdx(word, nComp); - if (curSpecType == SPEC_TILE_DEF) - curSpecType = SPEC_TILE_COMP; - else - curSpecType = SPEC_COMP_DEF; - break; - - case 'w': - // WT filters specification - case 'W': // WT filters specification - if (pl.getBooleanParameter("lossless") && word.ToUpper().Equals("w9x7".ToUpper())) - { - throw new System.ArgumentException("Cannot use non " + "reversible " + "wavelet transform with" + " '-lossless' option"); - } - - filter = parseFilters(word); - if (curSpecType == SPEC_DEF) - { - setDefault(filter); - } - else if (curSpecType == SPEC_TILE_DEF) - { - for (int i = tileSpec.Length - 1; i >= 0; i--) - if (tileSpec[i]) - { - setTileDef(i, filter); - } - } - else if (curSpecType == SPEC_COMP_DEF) - { - for (int i = compSpec.Length - 1; i >= 0; i--) - if (compSpec[i]) - { - setCompDef(i, filter); - } - } - else - { - for (int i = tileSpec.Length - 1; i >= 0; i--) - { - for (int j = compSpec.Length - 1; j >= 0; j--) - { - if (tileSpec[i] && compSpec[j]) - { - setTileCompVal(i, j, filter); - } - } - } - } - - // Re-initialize - curSpecType = SPEC_DEF; - tileSpec = null; - compSpec = null; - break; - - - default: - throw new System.ArgumentException("Bad construction for " + "parameter: " + word); - - } - } - - // Check that default value has been specified - if (getDefault() == null) - { - int ndefspec = 0; - for (int t = nt - 1; t >= 0; t--) - { - for (int c = nc - 1; c >= 0; c--) - { - if (specValType[t][c] == SPEC_DEF) - { - ndefspec++; - } - } - } - - // If some tile-component have received no specification, it takes - // the default value defined in ParameterList - if (ndefspec != 0) - { - if (((System.String)qts.getDefault()).Equals("reversible")) - setDefault(parseFilters(REV_FILTER_STR)); - else - setDefault(parseFilters(NON_REV_FILTER_STR)); - } - else - { - // All tile-component have been specified, takes the first - // tile-component value as default. - setDefault(getTileCompVal(0, 0)); - switch (specValType[0][0]) - { - - case SPEC_TILE_DEF: - for (int c = nc - 1; c >= 0; c--) - { - if (specValType[0][c] == SPEC_TILE_DEF) - specValType[0][c] = SPEC_DEF; - } - tileDef[0] = null; - break; - - case SPEC_COMP_DEF: - for (int t = nt - 1; t >= 0; t--) - { - if (specValType[t][0] == SPEC_COMP_DEF) - specValType[t][0] = SPEC_DEF; - } - compDef[0] = null; - break; - - case SPEC_TILE_COMP: - specValType[0][0] = SPEC_DEF; - tileCompVal["t0c0"] = null; - break; - } - } - } - - // Check consistency between filter and quantization type - // specification - for (int t = nt - 1; t >= 0; t--) - { - for (int c = nc - 1; c >= 0; c--) - { - // Reversible quantization - if (((System.String)qts.getTileCompVal(t, c)).Equals("reversible")) - { - // If filter is reversible, it is OK - if (isReversible(t, c)) - continue; - - // If no filter has been defined, use reversible filter - if (!isFilterSpecified) - { - setTileCompVal(t, c, parseFilters(REV_FILTER_STR)); - } - else - { - // Non reversible filter specified -> Error - throw new System.ArgumentException("Filter of " + "tile-component" + " (" + t + "," + c + ") does" + " not allow " + "reversible " + "quantization. " + "Specify '-Qtype " + "expounded' or " + "'-Qtype derived'" + "in " + "the command line."); - } - } - else - { - // No reversible quantization - // No reversible filter -> OK - if (!isReversible(t, c)) - continue; - - // If no filter has been specified, use non-reversible - // filter - if (!isFilterSpecified) - { - setTileCompVal(t, c, parseFilters(NON_REV_FILTER_STR)); - } - else - { - // Reversible filter specified -> Error - throw new System.ArgumentException("Filter of " + "tile-component" + " (" + t + "," + c + ") does" + " not allow " + "non-reversible " + "quantization. " + "Specify '-Qtype " + "reversible' in " + "the command line"); - } - } - } - } - } - - /// Parse filters from the given word - /// - /// - /// String to parse - /// - /// - /// Analysis wavelet filter (first dimension: by direction, - /// second dimension: by decomposition levels) - /// - private AnWTFilter[][] parseFilters(System.String word) - { - AnWTFilter[][] filt = new AnWTFilter[2][]; - for (int i = 0; i < 2; i++) - { - filt[i] = new AnWTFilter[1]; - } - if (word.ToUpper().Equals("w5x3".ToUpper())) - { - filt[0][0] = new AnWTFilterIntLift5x3(); - filt[1][0] = new AnWTFilterIntLift5x3(); - return filt; - } - else if (word.ToUpper().Equals("w9x7".ToUpper())) - { - filt[0][0] = new AnWTFilterFloatLift9x7(); - filt[1][0] = new AnWTFilterFloatLift9x7(); - return filt; - } - else - { - throw new System.ArgumentException("Non JPEG 2000 part I filter: " + word); - } - } - - /// Returns the data type used by the filters in this object, as defined in - /// the 'DataBlk' interface for specified tile-component. - /// - /// - /// Tile index - /// - /// - /// Component index - /// - /// - /// The data type of the filters in this object - /// - /// - /// - /// - /// - public virtual int getWTDataType(int t, int c) - { - AnWTFilter[][] an = (AnWTFilter[][])getSpec(t, c); - return an[0][0].DataType; - } - - /// Returns the horizontal analysis filters to be used in component 'n' and - /// tile 't'. - /// - ///

    The horizontal analysis filters are returned in an array of - /// AnWTFilter. Each element contains the horizontal filter for each - /// resolution level starting with resolution level 1 (i.e. the analysis - /// filter to go from resolution level 1 to resolution level 0). If there - /// are less elements than the maximum resolution level, then the last - /// element is assumed to be repeated. - /// - ///

    - /// The tile index, in raster scan order - /// - /// - /// The component index. - /// - /// - /// The array of horizontal analysis filters for component 'n' and - /// tile 't'. - /// - /// - public virtual AnWTFilter[] getHFilters(int t, int c) - { - AnWTFilter[][] an = (AnWTFilter[][])getSpec(t, c); - return an[0]; - } - - /// Returns the vertical analysis filters to be used in component 'n' and - /// tile 't'. - /// - ///

    The vertical analysis filters are returned in an array of - /// AnWTFilter. Each element contains the vertical filter for each - /// resolution level starting with resolution level 1 (i.e. the analysis - /// filter to go from resolution level 1 to resolution level 0). If there - /// are less elements than the maximum resolution level, then the last - /// element is assumed to be repeated. - /// - ///

    - /// The tile index, in raster scan order - /// - /// - /// The component index. - /// - /// - /// The array of horizontal analysis filters for component 'n' and - /// tile 't'. - /// - /// - public virtual AnWTFilter[] getVFilters(int t, int c) - { - AnWTFilter[][] an = (AnWTFilter[][])getSpec(t, c); - return an[1]; - } - - /// Debugging method - public override System.String ToString() - { - System.String str = ""; - AnWTFilter[][] an; - - str += ("nTiles=" + nTiles + "\nnComp=" + nComp + "\n\n"); - - for (int t = 0; t < nTiles; t++) - { - for (int c = 0; c < nComp; c++) - { - an = (AnWTFilter[][])getSpec(t, c); - - str += ("(t:" + t + ",c:" + c + ")\n"); - - // Horizontal filters - str += "\tH:"; - for (int i = 0; i < an[0].Length; i++) - { - //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Object.toString' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" - str += (" " + an[0][i]); - } - // Horizontal filters - str += "\n\tV:"; - for (int i = 0; i < an[1].Length; i++) - { - //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Object.toString' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" - str += (" " + an[1][i]); - } - str += "\n"; - } - } - - return str; - } - - /// Check the reversibility of filters contained is the given - /// tile-component. - /// - /// - /// The index of the tile - /// - /// - /// The index of the component - /// - /// - public virtual bool isReversible(int t, int c) - { - // Note: no need to buffer the result since this method is - // normally called once per tile-component. - AnWTFilter[] hfilter = getHFilters(t, c), vfilter = getVFilters(t, c); - - // As soon as a filter is not reversible, false can be returned - for (int i = hfilter.Length - 1; i >= 0; i--) - if (!hfilter[i].Reversible || !vfilter[i].Reversible) - return false; - return true; - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/wavelet/analysis/CBlkWTData.cs b/CSJ2K/j2k/wavelet/analysis/CBlkWTData.cs deleted file mode 100644 index 3805d4b5..00000000 --- a/CSJ2K/j2k/wavelet/analysis/CBlkWTData.cs +++ /dev/null @@ -1,224 +0,0 @@ -/* -* CVS identifier: -* -* $Id: CBlkWTData.java,v 1.18 2001/08/15 17:15:14 grosbois Exp $ -* -* Class: CBlkWTData -* -* Description: Storage for code-blocks of WT data. -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.image; -namespace CSJ2K.j2k.wavelet.analysis -{ - - /// This is a generic abstract class to store a code-block of wavelet data, - /// quantized or not. This class does not have the notion of - /// components. Therefore, it should be used for data from a single - /// component. Subclasses should implement the different types of storage - /// (int, float, etc.). - /// - ///

    The data is always stored in one array, of the type matching the data - /// type (i.e. for 'int' it's an 'int[]'). The data should be stored in the - /// array in standard scan-line order. That is the samples go from the top-left - /// corner of the code-block to the lower-right corner by line and then - /// column.

    - /// - ///

    The member variable 'offset' gives the index in the array of the first - /// data element (i.e. the top-left coefficient). The member variable 'scanw' - /// gives the width of the scan that is used to store the data, that can be - /// different from the width of the block. Element '(x,y)' of the code-block - /// (i.e. '(0,0)' is the top-left coefficient), will appear at position - /// 'offset+y*scanw+x' in the array of data.

    - /// - ///

    The classes CBlkWTDataInt and CBlkWTDataFloat provide - /// implementations for int and float types respectively.

    - /// - ///

    The types of data are the same as those defined by the 'DataBlk' - /// class.

    - /// - ///
    - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - public abstract class CBlkWTData - { - /// Returns the data type of the CBlkWTData object, as defined in - /// the DataBlk class. - /// - /// - /// The data type of the object, as defined in the DataBlk class. - /// - /// - /// - /// - /// - public abstract int DataType { get; } - //UPGRADE_NOTE: Respective javadoc comments were merged. It should be changed in order to comply with .NET documentation conventions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1199'" - /// Returns the array containing the data, or null if there is no data. The - /// returned array is of the type returned by getDataType() (e.g., - /// for TYPE_INT, it is a int[]). - /// - ///

    Each implementing class should provide a type specific equivalent - /// method (e.g., getDataInt() in DataBlkInt) which - /// returns an array of the correct type explicitely and not through an - /// Object.

    - /// - ///
    - /// The array containing the data, or null if there is no - /// data. - /// - /// - /// - /// - /// - /// Sets the data array to the specified one. The type of the specified - /// data array must match the one returned by getDataType() (e.g., - /// for TYPE_INT, it should be a int[]). If the wrong - /// type of array is given a ClassCastException will be thrown. - /// - ///

    The size of the array is not necessarily checked for consistency - /// with w and h or any other fields.

    - /// - ///

    Each implementing class should provide a type specific equivalent - /// method (e.g., setDataInt() in DataBlkInt) which takes - /// an array of the correct type explicetely and not through an - /// Object.

    - /// - ///
    - /// The new data array to use - /// - /// - /// - /// - /// - public abstract System.Object Data { get; set; } - - /// The horizontal coordinate of the upper-left corner of the code-block - public int ulx; - - /// The vertical coordinate of the upper left corner of the code-block - public int uly; - - /// The horizontal index of the code-block, within the subband - public int n; - - /// The vertical index of the code-block, within the subband - public int m; - - /// The subband in which this code-block is found - public SubbandAn sb; - - /// The width of the code-block - public int w; - - /// The height of the code-block - public int h; - - /// The offset in the array of the top-left coefficient - public int offset; - - /// The width of the scanlines used to store the data in the array - public int scanw; - - /// The number of magnitude bits in the integer representation. This is - /// only used for quantized wavelet data. - /// - public int magbits; - - /// The WMSE scaling factor (multiplicative) to apply to the distortion - /// measures of the data of this code-block. By default it is 1. - /// - public float wmseScaling = 1f; - - /// The value by which the absolute value of the data has to be divided in - /// order to get the real absolute value. This value is useful to obtain - /// the complement of 2 representation of a coefficient that is currently - /// using the sign-magnitude representation. - /// - public double convertFactor = 1.0; - - /// The quantization step size of the code-block. The value is updated by - /// the quantizer module - /// - public double stepSize = 1.0; - - /// Number of ROI coefficients in the code-block - public int nROIcoeff = 0; - - /// Number of ROI magnitude bit-planes - public int nROIbp = 0; - - /// Returns a string of informations about the DataBlk - /// - /// - /// Block dimensions and progressiveness in a string - /// - /// - public override System.String ToString() - { - System.String typeString = ""; - switch (DataType) - { - - case DataBlk.TYPE_BYTE: - typeString = "Unsigned Byte"; - break; - - case DataBlk.TYPE_SHORT: - typeString = "Short"; - break; - - case DataBlk.TYPE_INT: - typeString = "Integer"; - break; - - case DataBlk.TYPE_FLOAT: - typeString = "Float"; - break; - } - - return "ulx=" + ulx + ", uly=" + uly + ", idx=(" + m + "," + n + "), w=" + w + ", h=" + h + ", off=" + offset + ", scanw=" + scanw + ", wmseScaling=" + wmseScaling + ", convertFactor=" + convertFactor + ", stepSize=" + stepSize + ", type=" + typeString + ", magbits=" + magbits + ", nROIcoeff=" + nROIcoeff + ", nROIbp=" + nROIbp; - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/wavelet/analysis/CBlkWTDataFloat.cs b/CSJ2K/j2k/wavelet/analysis/CBlkWTDataFloat.cs deleted file mode 100644 index 75065a18..00000000 --- a/CSJ2K/j2k/wavelet/analysis/CBlkWTDataFloat.cs +++ /dev/null @@ -1,139 +0,0 @@ -/* -* CVS identifier: -* -* $Id: CBlkWTDataFloat.java,v 1.11 2001/08/15 17:18:43 grosbois Exp $ -* -* Class: CBlkWTDataFloat -* -* Description: Implementation of CBlkWTData for 'float' data -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.image; -namespace CSJ2K.j2k.wavelet.analysis -{ - - /// This is an implementation of the 'CBlkWTData' abstract class for 32 bit - /// floating point data (float). - /// - ///

    The methods in this class are declared final, so that they can be - /// inlined by inlining compilers.

    - /// - ///
    - /// - /// - /// - public class CBlkWTDataFloat : CBlkWTData - { - /// Returns the identifier of this data type, TYPE_FLOAT, as - /// defined in DataBlk. - /// - /// - /// The type of data stored. Always DataBlk.TYPE_FLOAT - /// - /// - /// - /// - /// - override public int DataType - { - get - { - return DataBlk.TYPE_FLOAT; - } - - } - //UPGRADE_NOTE: Respective javadoc comments were merged. It should be changed in order to comply with .NET documentation conventions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1199'" - /// Returns the array containing the data, or null if there is no data - /// array. The returned array is a float array. - /// - /// - /// The array of data (a float[]) or null if there is no data. - /// - /// - /// Sets the data array to the specified one. The provided array must be a - /// float array, otherwise a ClassCastException is thrown. The size of the - /// array is not checked for consistency with the code-block dimensions. - /// - /// - /// The data array to use. Must be a float array. - /// - /// - override public System.Object Data - { - get - { - return data; - } - - set - { - data = (float[])value; - } - - } - //UPGRADE_NOTE: Respective javadoc comments were merged. It should be changed in order to comply with .NET documentation conventions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1199'" - /// Returns the array containing the data, or null if there is no data - /// array. - /// - /// - /// The array of data or null if there is no data. - /// - /// - /// Sets the data array to the specified one. The size of the array is not - /// checked for consistency with the code-block dimensions. This method is - /// more efficient than 'setData()'. - /// - /// - /// The data array to use. - /// - /// - virtual public float[] DataFloat - { - get - { - return data; - } - - set - { - data = value; - } - - } - - /// The array where the data is stored - private float[] data; - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/wavelet/analysis/CBlkWTDataInt.cs b/CSJ2K/j2k/wavelet/analysis/CBlkWTDataInt.cs deleted file mode 100644 index 43fc30db..00000000 --- a/CSJ2K/j2k/wavelet/analysis/CBlkWTDataInt.cs +++ /dev/null @@ -1,135 +0,0 @@ -/* -* CVS identifier: -* -* $Id: CBlkWTDataInt.java,v 1.10 2001/08/15 17:18:51 grosbois Exp $ -* -* Class: CBlkWTDataInt -* -* Description: Implementation of CBlkWTData for 'int' data -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.image; -namespace CSJ2K.j2k.wavelet.analysis -{ - - /// This is an implementation of the 'CBlkWTData' abstract class for signed 32 - /// bit integer data. - /// - ///

    The methods in this class are declared final, so that they can be - /// inlined by inlining compilers.

    - /// - ///
    - /// - /// - /// - public class CBlkWTDataInt : CBlkWTData - { - /// Returns the data type of this object, always DataBlk.TYPE_INT. - /// - /// - /// The data type of the object, always DataBlk.TYPE_INT - /// - /// - override public int DataType - { - get - { - return DataBlk.TYPE_INT; - } - - } - //UPGRADE_NOTE: Respective javadoc comments were merged. It should be changed in order to comply with .NET documentation conventions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1199'" - /// Returns the array containing the data, or null if there is no data - /// array. The returned array is an int array. - /// - /// - /// The array of data (a int[]) or null if there is no data. - /// - /// - /// Sets the data array to the specified one. The provided array must be a - /// int array, otherwise a ClassCastException is thrown. The size of the - /// array is not checked for consistency with the code-block dimensions. - /// - /// - /// The data array to use. Must be an int array. - /// - /// - override public System.Object Data - { - get - { - return data_array; - } - - set - { - data_array = (int[])value; - } - - } - //UPGRADE_NOTE: Respective javadoc comments were merged. It should be changed in order to comply with .NET documentation conventions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1199'" - /// Returns the array containing the data, or null if there is no data - /// array. - /// - /// - /// The array of data or null if there is no data. - /// - /// - /// Sets the data array to the specified one. The size of the array is not - /// checked for consistency with the code-block dimensions. This method is - /// more efficient than 'setData()'. - /// - /// - /// The data array to use. - /// - /// - virtual public int[] DataInt - { - get - { - return data_array; - } - - set - { - data_array = value; - } - - } - - /// The array where the data is stored - public int[] data_array; - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/wavelet/analysis/CBlkWTDataSrc.cs b/CSJ2K/j2k/wavelet/analysis/CBlkWTDataSrc.cs deleted file mode 100644 index b879f9b6..00000000 --- a/CSJ2K/j2k/wavelet/analysis/CBlkWTDataSrc.cs +++ /dev/null @@ -1,191 +0,0 @@ -/* -* CVS identifier: -* -* $Id: CBlkWTDataSrc.java,v 1.18 2001/09/14 08:45:25 grosbois Exp $ -* -* Class: CBlkWTDataSrc -* -* Description: Interface that define methods for transfer of WT -* data in a code-block basis. -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -namespace CSJ2K.j2k.wavelet.analysis -{ - - /// This abstract class defines methods to transfer wavelet data in a - /// code-block by code-block basis. In each call to 'getNextCodeBlock()' or - /// 'getNextInternCodeBlock()' a new code-block is returned. The code-blocks - /// are returned in no specific order. - /// - ///

    This class is the source of data for the quantizer. See the 'Quantizer' - /// class.

    - /// - ///

    Note that no more of one object may request data, otherwise one object - /// would get some of the data and another one another part, in no defined - /// manner.

    - /// - ///
    - /// - /// - /// - /// - /// - /// - /// - /// - /// - public interface CBlkWTDataSrc : ForwWTDataProps - { - - /// Returns the position of the fixed point in the specified component, or - /// equivalently the number of fractional bits. This is the position of the - /// least significant integral (i.e. non-fractional) bit, which is - /// equivalent to the number of fractional bits. For instance, for - /// fixed-point values with 2 fractional bits, 2 is returned. For - /// floating-point data this value does not apply and 0 should be - /// returned. Position 0 is the position of the least significant bit in - /// the data. - /// - /// - /// The index of the component. - /// - /// - /// The position of the fixed-point, which is the same as the - /// number of fractional bits. For floating-point data 0 is returned. - /// - /// - int getFixedPoint(int c); - - /// Return the data type of this CBlkWTDataSrc for the given component in - /// the current tile. Its value should be either DataBlk.TYPE_INT or - /// DataBlk.TYPE_FLOAT but can change according to the current - /// tile-component. - /// - /// - /// Tile index - /// - /// - /// Component index - /// - /// - /// Current data type - /// - /// - int getDataType(int t, int c); - - /// Returns the next code-block in the current tile for the specified - /// component, as a copy (see below). The order in which code-blocks are - /// returned is not specified. However each code-block is returned only - /// once and all code-blocks will be returned if the method is called 'N' - /// times, where 'N' is the number of code-blocks in the tile. After all - /// the code-blocks have been returned for the current tile calls to this - /// method will return 'null'. - /// - ///

    When changing the current tile (through 'setTile()' or 'nextTile()') - /// this method will always return the first code-block, as if this method - /// was never called before for the new current tile.

    - /// - ///

    The data returned by this method is always a copy of the internal - /// data of this object, if any, and it can be modified "in place" without - /// any problems after being returned. The 'offset' of the returned data is - /// 0, and the 'scanw' is the same as the code-block width. The 'magbits' - /// of the returned data is not set by this method and should be - /// ignored. See the 'CBlkWTData' class.

    - /// - ///

    The 'ulx' and 'uly' members of the returned 'CBlkWTData' object - /// contain the coordinates of the top-left corner of the block, with - /// respect to the tile, not the subband.

    - /// - ///
    - /// The component for which to return the next code-block. - /// - /// - /// If non-null this object will be used to return the new - /// code-block. If null a new one will be allocated and returned. If the - /// "data" array of the object is non-null it will be reused, if possible, - /// to return the data. - /// - /// - /// The next code-block in the current tile for component 'c', or - /// null if all code-blocks for the current tile have been returned. - /// - /// - /// - /// - /// - CBlkWTData getNextCodeBlock(int c, CBlkWTData cblk); - - /// Returns the next code-block in the current tile for the specified - /// component. The order in which code-blocks are returned is not - /// specified. However each code-block is returned only once and all - /// code-blocks will be returned if the method is called 'N' times, where - /// 'N' is the number of code-blocks in the tile. After all the code-blocks - /// have been returned for the current tile calls to this method will - /// return 'null'. - /// - ///

    When changing the current tile (through 'setTile()' or 'nextTile()') - /// this method will always return the first code-block, as if this method - /// was never called before for the new current tile.

    - /// - ///

    The data returned by this method can be the data in the internal - /// buffer of this object, if any, and thus can not be modified by the - /// caller. The 'offset' and 'scanw' of the returned data can be - /// arbitrary. The 'magbits' of the returned data is not set by this method - /// and should be ignored. See the 'CBlkWTData' class.

    - /// - ///

    The 'ulx' and 'uly' members of the returned 'CBlkWTData' object - /// contain the coordinates of the top-left corner of the block, with - /// respect to the tile, not the subband.

    - /// - ///
    - /// The component for which to return the next code-block. - /// - /// - /// If non-null this object will be used to return the new - /// code-block. If null a new one will be allocated and returned. If the - /// "data" array of the object is non-null it will be reused, if possible, - /// to return the data. - /// - /// - /// The next code-block in the current tile for component 'n', or - /// null if all code-blocks for the current tile have been returned. - /// - /// - /// - /// - /// - CBlkWTData getNextInternCodeBlock(int c, CBlkWTData cblk); - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/wavelet/analysis/ForwWT.cs b/CSJ2K/j2k/wavelet/analysis/ForwWT.cs deleted file mode 100644 index 653c212b..00000000 --- a/CSJ2K/j2k/wavelet/analysis/ForwWT.cs +++ /dev/null @@ -1,145 +0,0 @@ -/* -* CVS identifier: -* -* $Id: ForwWT.java,v 1.9 2001/10/24 12:02:13 grosbois Exp $ -* -* Class: ForwWT -* -* Description: The interface for implementations of a forward -* wavelet transform. -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -namespace CSJ2K.j2k.wavelet.analysis -{ - - /// This interface extends the WaveletTransform with the specifics of forward - /// wavelet transforms. Classes that implement forward wavelet transfoms should - /// implement this interface. - /// - ///

    This class does not define the methods to transfer data, just the - /// specifics to forward wavelet transform. Different data transfer methods are - /// evisageable for different transforms.

    - /// - ///
    - public interface ForwWT : WaveletTransform, ForwWTDataProps - { - - /// Returns the horizontal analysis wavelet filters used in each level, for - /// the specified tile-component. The first element in the array is the - /// filter used to obtain the lowest resolution (resolution level 0) - /// subbands (i.e. lowest frequency LL subband), the second element is the - /// one used to generate the resolution level 1 subbands, and so on. If - /// there are less elements in the array than the number of resolution - /// levels, then the last one is assumed to repeat itself. - /// - ///

    The returned filters are applicable only to the specified component - /// and in the current tile.

    - /// - ///

    The resolution level of a subband is the resolution level to which a - /// subband contributes, which is different from its decomposition - /// level.

    - /// - ///
    - /// The index of the tile for which to return the filters. - /// - /// - /// The index of the component for which to return the filters. - /// - /// - /// The horizontal analysis wavelet filters used in each level. - /// - /// - AnWTFilter[] getHorAnWaveletFilters(int t, int c); - - /// Returns the vertical analysis wavelet filters used in each level, for - /// the specified tile-component. The first element in the array is the - /// filter used to obtain the lowest resolution (resolution level 0) - /// subbands (i.e. lowest frequency LL subband), the second element is the - /// one used to generate the resolution level 1 subbands, and so on. If - /// there are less elements in the array than the number of resolution - /// levels, then the last one is assumed to repeat itself. - /// - ///

    The returned filters are applicable only to the specified component - /// and in the current tile.

    - /// - ///

    The resolution level of a subband is the resolution level to which a - /// subband contributes, which is different from its decomposition - /// level.

    - /// - ///
    - /// The index of the tile for which to return the filters. - /// - /// - /// The index of the component for which to return the filters. - /// - /// - /// The vertical analysis wavelet filters used in each level. - /// - /// - AnWTFilter[] getVertAnWaveletFilters(int t, int c); - - /// Returns the number of decomposition levels that are applied to obtain - /// the LL band, in the specified tile-component. A value of 0 means that - /// no wavelet transform is applied. - /// - /// - /// The tile index - /// - /// - /// The index of the component. - /// - /// - /// The number of decompositions applied to obtain the LL subband - /// (0 for no wavelet transform). - /// - /// - int getDecompLevels(int t, int c); - - /// Returns the wavelet tree decomposition. Only WT_DECOMP_DYADIC is - /// supported by JPEG 2000 part I. - /// - /// - /// The tile index - /// - /// - /// The index of the component. - /// - /// - /// The wavelet decomposition. - /// - /// - int getDecomp(int t, int c); - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/wavelet/analysis/ForwWTDataProps.cs b/CSJ2K/j2k/wavelet/analysis/ForwWTDataProps.cs deleted file mode 100644 index 17805998..00000000 --- a/CSJ2K/j2k/wavelet/analysis/ForwWTDataProps.cs +++ /dev/null @@ -1,110 +0,0 @@ -/* -* CVS identifier: -* -* $Id: ForwWTDataProps.java,v 1.10 2001/09/20 12:42:42 grosbois Exp $ -* -* Class: ForwWTDataProps -* -* Description: Extends ImgData with forward wavelet specific -* things. -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.image; -namespace CSJ2K.j2k.wavelet.analysis -{ - - /// This interface extends the ImgData interface with methods that are - /// necessary for forward wavelet data (i.e. data that is produced by a forward - /// wavelet transform). - /// - public interface ForwWTDataProps : ImgData - { - /// Returns the horizontal offset of the code-block partition. Allowable - /// values are 0 and 1, nothing else. - /// - /// - int CbULX - { - get; - - } - /// Returns the vertical offset of the code-block partition. Allowable - /// values are 0 and 1, nothing else. - /// - /// - int CbULY - { - get; - - } - - /// Returns the reversibility of the given tile-component. Data is - /// reversible when it is suitable for lossless and lossy-to-lossless - /// compression. - /// - /// - /// Tile index - /// - /// - /// Component index - /// - /// - /// true is the data is reversible, false if not. - /// - /// - bool isReversible(int t, int c); - - /// Returns a reference to the root of subband tree structure representing - /// the subband decomposition for the specified tile-component. - /// - /// - /// The index of the tile. - /// - /// - /// The index of the component. - /// - /// - /// The root of the subband tree structure, see Subband. - /// - /// - /// - /// - /// - /// - /// - /// - SubbandAn getAnSubbandTree(int t, int c); - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/wavelet/analysis/ForwWTFull.cs b/CSJ2K/j2k/wavelet/analysis/ForwWTFull.cs deleted file mode 100644 index cd4eeb99..00000000 --- a/CSJ2K/j2k/wavelet/analysis/ForwWTFull.cs +++ /dev/null @@ -1,1225 +0,0 @@ -/* -* CVS identifier: -* -* $Id: ForwWTFull.java,v 1.30 2001/09/20 12:42:59 grosbois Exp $ -* -* Class: ForwWTFull -* -* Description: This class implements the full page -* forward wavelet transform for both integer -* and floating point implementations. -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.encoder; -using CSJ2K.j2k.entropy; -using CSJ2K.j2k.image; -using CSJ2K.j2k.util; -using System; -namespace CSJ2K.j2k.wavelet.analysis -{ - - /// This class implements the ForwardWT abstract class with the full-page - /// approach to be used either with integer or floating-point filters - /// - /// - /// - /// - /// - public class ForwWTFull : ForwardWT - { - /// Returns the horizontal offset of the code-block partition. Allowable - /// values are 0 and 1, nothing else. - /// - /// - override public int CbULX - { - get - { - return cb0x; - } - - } - /// Returns the vertical offset of the code-block partition. Allowable - /// values are 0 and 1, nothing else. - /// - /// - override public int CbULY - { - get - { - return cb0y; - } - - } - - /// Boolean to know if one are currently dealing with int or float data. - private bool intData; - - /// The subband trees of each tile-component. The array is allocated by the - /// constructor of this class and updated by the getAnSubbandTree() method - /// when needed. The first index is the tile index (in lexicographical - /// order) and the second index is the component index. - /// - ///

    The subband tree for a component in the current tile is created on - /// the first call to getAnSubbandTree() for that component, in the current - /// tile. Before that, the element in 'subbTrees' is null.

    - /// - ///
    - private SubbandAn[][] subbTrees; - - /// The source of image data - private BlkImgDataSrc src; - - /// The horizontal coordinate of the code-block partition origin on the - /// reference grid - /// - private int cb0x; - - /// The vertical coordinate of the code-block partition on the reference - /// grid - /// - private int cb0y; - - /// The number of decomposition levels specification - private IntegerSpec dls; - - /// Wavelet filters for all components and tiles - private AnWTFilterSpec filters; - - /// The code-block size specifications - private CBlkSizeSpec cblks; - - /// The precinct partition specifications - private PrecinctSizeSpec pss; - - /// Block storing the full band decomposition for each component. - private DataBlk[] decomposedComps; - - /// The horizontal index of the last "sent" code-block in the current - /// subband in each component. It should be -1 if none have been sent yet. - /// - /// - private int[] lastn; - - /// The vertical index of the last "sent" code-block in the current - /// subband in each component. It should be 0 if none have been sent yet. - /// - /// - private int[] lastm; - - /// The subband being dealt with in each component - internal SubbandAn[] currentSubband; - - /// Cache object to avoid excessive allocation/desallocation. This - /// variable makes the class inheritently thread unsafe. - /// - internal Coord ncblks; - - /// Initializes this object with the given source of image data and with - /// all the decompositon parameters - /// - /// - /// From where the image data should be obtained. - /// - /// - /// The encoder specifications - /// - /// - /// The horizontal coordinate of the code-block partition - /// origin on the reference grid. - /// - /// - /// The vertical coordinate of the code-block partition origin - /// on the reference grid. - /// - /// - /// - /// - /// - public ForwWTFull(BlkImgDataSrc src, EncoderSpecs encSpec, int cb0x, int cb0y) : base(src) - { - this.src = src; - this.cb0x = cb0x; - this.cb0y = cb0y; - this.dls = encSpec.dls; - this.filters = encSpec.wfs; - this.cblks = encSpec.cblks; - this.pss = encSpec.pss; - - int ncomp = src.NumComps; - int ntiles = src.getNumTiles(); - - currentSubband = new SubbandAn[ncomp]; - decomposedComps = new DataBlk[ncomp]; - subbTrees = new SubbandAn[ntiles][]; - for (int i = 0; i < ntiles; i++) - { - subbTrees[i] = new SubbandAn[ncomp]; - } - lastn = new int[ncomp]; - lastm = new int[ncomp]; - } - - /// Returns the implementation type of this wavelet transform, WT_IMPL_FULL - /// (full-page based transform). All components return the same. - /// - /// - /// The index of the component. - /// - /// - /// WT_IMPL_FULL - /// - /// - public override int getImplementationType(int c) - { - return CSJ2K.j2k.wavelet.WaveletTransform_Fields.WT_IMPL_FULL; - } - - /// Returns the number of decomposition levels that are applied to the LL - /// band, in the specified tile-component. A value of 0 means that no - /// wavelet transform is applied. - /// - /// - /// The tile index - /// - /// - /// The index of the component. - /// - /// - /// The number of decompositions applied to the LL band (0 for no - /// wavelet transform). - /// - /// - public override int getDecompLevels(int t, int c) - { - return ((System.Int32)dls.getTileCompVal(t, c)); - } - - /// Returns the wavelet tree decomposition. Actually JPEG 2000 part 1 only - /// supports WT_DECOMP_DYADIC decomposition. - /// - /// - /// The tile-index - /// - /// - /// The index of the component. - /// - /// - /// The wavelet decomposition. - /// - /// - public override int getDecomp(int t, int c) - { - return WT_DECOMP_DYADIC; - } - - /// Returns the horizontal analysis wavelet filters used in each level, for - /// the specified component and tile. The first element in the array is the - /// filter used to obtain the lowest resolution (resolution level 0) - /// subbands (i.e. lowest frequency LL subband), the second element is the - /// one used to generate the resolution level 1 subbands, and so on. If - /// there are less elements in the array than the number of resolution - /// levels, then the last one is assumed to repeat itself. - /// - ///

    The returned filters are applicable only to the specified component - /// and in the current tile.

    - /// - ///

    The resolution level of a subband is the resolution level to which a - /// subband contributes, which is different from its decomposition - /// level.

    - /// - ///
    - /// The index of the tile for which to return the filters. - /// - /// - /// The index of the component for which to return the filters. - /// - /// - /// The horizontal analysis wavelet filters used in each level. - /// - /// - public override AnWTFilter[] getHorAnWaveletFilters(int t, int c) - { - return filters.getHFilters(t, c); - } - - /// Returns the vertical analysis wavelet filters used in each level, for - /// the specified component and tile. The first element in the array is the - /// filter used to obtain the lowest resolution (resolution level 0) - /// subbands (i.e. lowest frequency LL subband), the second element is the - /// one used to generate the resolution level 1 subbands, and so on. If - /// there are less elements in the array than the number of resolution - /// levels, then the last one is assumed to repeat itself. - /// - ///

    The returned filters are applicable only to the specified component - /// and in the current tile.

    - /// - ///

    The resolution level of a subband is the resolution level to which a - /// subband contributes, which is different from its decomposition - /// level.

    - /// - ///
    - /// The index of the tile for which to return the filters. - /// - /// - /// The index of the component for which to return the filters. - /// - /// - /// The vertical analysis wavelet filters used in each level. - /// - /// - public override AnWTFilter[] getVertAnWaveletFilters(int t, int c) - { - return filters.getVFilters(t, c); - } - - /// Returns the reversibility of the wavelet transform for the specified - /// component and tile. A wavelet transform is reversible when it is - /// suitable for lossless and lossy-to-lossless compression. - /// - /// - /// The index of the tile. - /// - /// - /// The index of the component. - /// - /// - /// true is the wavelet transform is reversible, false if not. - /// - /// - public override bool isReversible(int t, int c) - { - return filters.isReversible(t, c); - } - - /// Returns the position of the fixed point in the specified - /// component. This is the position of the least significant integral - /// (i.e. non-fractional) bit, which is equivalent to the number of - /// fractional bits. For instance, for fixed-point values with 2 fractional - /// bits, 2 is returned. For floating-point data this value does not apply - /// and 0 should be returned. Position 0 is the position of the least - /// significant bit in the data. - /// - /// - /// The index of the component. - /// - /// - /// The position of the fixed-point, which is the same as the - /// number of fractional bits. For floating-point data 0 is returned. - /// - /// - public override int getFixedPoint(int c) - { - return src.getFixedPoint(c); - } - - /// Returns the next code-block in the current tile for the specified - /// component. The order in which code-blocks are returned is not - /// specified. However each code-block is returned only once and all - /// code-blocks will be returned if the method is called 'N' times, where - /// 'N' is the number of code-blocks in the tile. After all the code-blocks - /// have been returned for the current tile calls to this method will - /// return 'null'. - /// - ///

    When changing the current tile (through 'setTile()' or 'nextTile()') - /// this method will always return the first code-block, as if this method - /// was never called before for the new current tile.

    - /// - ///

    The data returned by this method is the data in the internal buffer - /// of this object, and thus can not be modified by the caller. The - /// 'offset' and 'scanw' of the returned data have, in general, some - /// non-zero value. The 'magbits' of the returned data is not set by this - /// method and should be ignored. See the 'CBlkWTData' class.

    - /// - ///

    The 'ulx' and 'uly' members of the returned 'CBlkWTData' object - /// contain the coordinates of the top-left corner of the block, with - /// respect to the tile, not the subband.

    - /// - ///
    - /// The component for which to return the next code-block. - /// - /// - /// If non-null this object will be used to return the new - /// code-block. If null a new one will be allocated and returned. - /// - /// - /// The next code-block in the current tile for component 'n', or - /// null if all code-blocks for the current tile have been returned. - /// - /// - /// - /// - /// - public override CBlkWTData getNextInternCodeBlock(int c, CBlkWTData cblk) - { - int cbm, cbn, cn, cm; - int acb0x, acb0y; - SubbandAn sb; - intData = (filters.getWTDataType(tIdx, c) == DataBlk.TYPE_INT); - - //If the source image has not been decomposed - if (decomposedComps[c] == null) - { - int k, w, h; - DataBlk bufblk; - System.Object dst_data; - - w = getTileCompWidth(tIdx, c); - h = getTileCompHeight(tIdx, c); - - //Get the source image data - if (intData) - { - decomposedComps[c] = new DataBlkInt(0, 0, w, h); - bufblk = new DataBlkInt(); - } - else - { - decomposedComps[c] = new DataBlkFloat(0, 0, w, h); - bufblk = new DataBlkFloat(); - } - - // Get data from source line by line (this diminishes the memory - // requirements on the data source) - dst_data = decomposedComps[c].Data; - int lstart = getCompULX(c); - bufblk.ulx = lstart; - bufblk.w = w; - bufblk.h = 1; - int kk = getCompULY(c); - for (k = 0; k < h; k++, kk++) - { - bufblk.uly = kk; - bufblk.ulx = lstart; - bufblk = src.getInternCompData(bufblk, c); - // CONVERSION PROBLEM? - Array.Copy((System.Array)bufblk.Data, bufblk.offset, (System.Array)dst_data, k * w, w); - } - - //Decompose source image - waveletTreeDecomposition(decomposedComps[c], getAnSubbandTree(tIdx, c), c); - - // Make the first subband the current one - currentSubband[c] = getNextSubband(c); - - lastn[c] = -1; - lastm[c] = 0; - } - - // Get the next code-block to "send" - do - { - // Calculate number of code-blocks in current subband - ncblks = currentSubband[c].numCb; - // Goto next code-block - lastn[c]++; - if (lastn[c] == ncblks.x) - { - // Got to end of this row of - // code-blocks - lastn[c] = 0; - lastm[c]++; - } - if (lastm[c] < ncblks.y) - { - // Not past the last code-block in the subband, we can return - // this code-block - break; - } - // If we get here we already sent all code-blocks in this subband, - // goto next subband - currentSubband[c] = getNextSubband(c); - lastn[c] = -1; - lastm[c] = 0; - if (currentSubband[c] == null) - { - // We don't need the transformed data any more (a priori) - decomposedComps[c] = null; - // All code-blocks from all subbands in the current - // tile have been returned so we return a null - // reference - return null; - } - // Loop to find the next code-block - } - while (true); - - - // Project code-block partition origin to subband. Since the origin is - // always 0 or 1, it projects to the low-pass side (throught the ceil - // operator) as itself (i.e. no change) and to the high-pass side - // (through the floor operator) as 0, always. - acb0x = cb0x; - acb0y = cb0y; - switch (currentSubband[c].sbandIdx) - { - - case Subband.WT_ORIENT_LL: - // No need to project since all low-pass => nothing to do - break; - - case Subband.WT_ORIENT_HL: - acb0x = 0; - break; - - case Subband.WT_ORIENT_LH: - acb0y = 0; - break; - - case Subband.WT_ORIENT_HH: - acb0x = 0; - acb0y = 0; - break; - - default: - throw new System.ApplicationException("Internal JJ2000 error"); - - } - - // Initialize output code-block - if (cblk == null) - { - if (intData) - { - cblk = new CBlkWTDataInt(); - } - else - { - cblk = new CBlkWTDataFloat(); - } - } - cbn = lastn[c]; - cbm = lastm[c]; - sb = currentSubband[c]; - cblk.n = cbn; - cblk.m = cbm; - cblk.sb = sb; - // Calculate the indexes of first code-block in subband with respect - // to the partitioning origin, to then calculate the position and size - // NOTE: when calculating "floor()" by integer division the dividend - // and divisor must be positive, we ensure that by adding the divisor - // to the dividend and then substracting 1 to the result of the - // division - cn = (sb.ulcx - acb0x + sb.nomCBlkW) / sb.nomCBlkW - 1; - cm = (sb.ulcy - acb0y + sb.nomCBlkH) / sb.nomCBlkH - 1; - if (cbn == 0) - { - // Left-most code-block, starts where subband starts - cblk.ulx = sb.ulx; - } - else - { - // Calculate starting canvas coordinate and convert to subb. coords - cblk.ulx = (cn + cbn) * sb.nomCBlkW - (sb.ulcx - acb0x) + sb.ulx; - } - if (cbm == 0) - { - // Bottom-most code-block, starts where subband starts - cblk.uly = sb.uly; - } - else - { - cblk.uly = (cm + cbm) * sb.nomCBlkH - (sb.ulcy - acb0y) + sb.uly; - } - if (cbn < ncblks.x - 1) - { - // Calculate where next code-block starts => width - cblk.w = (cn + cbn + 1) * sb.nomCBlkW - (sb.ulcx - acb0x) + sb.ulx - cblk.ulx; - } - else - { - // Right-most code-block, ends where subband ends - cblk.w = sb.ulx + sb.w - cblk.ulx; - } - if (cbm < ncblks.y - 1) - { - // Calculate where next code-block starts => height - cblk.h = (cm + cbm + 1) * sb.nomCBlkH - (sb.ulcy - acb0y) + sb.uly - cblk.uly; - } - else - { - // Bottom-most code-block, ends where subband ends - cblk.h = sb.uly + sb.h - cblk.uly; - } - cblk.wmseScaling = 1f; - - // Since we are in getNextInternCodeBlock() we can return a - // reference to the internal buffer, no need to copy. Just initialize - // the 'offset' and 'scanw' - cblk.offset = cblk.uly * decomposedComps[c].w + cblk.ulx; - cblk.scanw = decomposedComps[c].w; - - // For the data just put a reference to our buffer - cblk.Data = decomposedComps[c].Data; - // Return code-block - return cblk; - } - - /// Returns the next code-block in the current tile for the specified - /// component, as a copy (see below). The order in which code-blocks are - /// returned is not specified. However each code-block is returned only - /// once and all code-blocks will be returned if the method is called 'N' - /// times, where 'N' is the number of code-blocks in the tile. After all - /// the code-blocks have been returned for the current tile calls to this - /// method will return 'null'. - /// - ///

    When changing the current tile (through 'setTile()' or 'nextTile()') - /// this method will always return the first code-block, as if this method - /// was never called before for the new current tile.

    - /// - ///

    The data returned by this method is always a copy of the internal - /// data of this object, and it can be modified "in place" without - /// any problems after being returned. The 'offset' of the returned data is - /// 0, and the 'scanw' is the same as the code-block width. The 'magbits' - /// of the returned data is not set by this method and should be - /// ignored. See the 'CBlkWTData' class.

    - /// - ///

    The 'ulx' and 'uly' members of the returned 'CBlkWTData' object - /// contain the coordinates of the top-left corner of the block, with - /// respect to the tile, not the subband.

    - /// - ///
    - /// The component for which to return the next code-block. - /// - /// - /// If non-null this object will be used to return the new - /// code-block. If null a new one will be allocated and returned. If the - /// "data" array of the object is non-null it will be reused, if possible, - /// to return the data. - /// - /// - /// The next code-block in the current tile for component 'c', or - /// null if all code-blocks for the current tile have been returned. - /// - /// - /// - /// - /// - public override CBlkWTData getNextCodeBlock(int c, CBlkWTData cblk) - { - // We can not directly use getNextInternCodeBlock() since that returns - // a reference to the internal buffer, we have to copy that data - - int j, k; - int w; - System.Object dst_data; // a int[] or float[] object - int[] dst_data_int; - float[] dst_data_float; - System.Object src_data; // a int[] or float[] object - - intData = (filters.getWTDataType(tIdx, c) == DataBlk.TYPE_INT); - - dst_data = null; - - // Cache the data array, if any - if (cblk != null) - { - dst_data = cblk.Data; - } - - // Get the next code-block - cblk = getNextInternCodeBlock(c, cblk); - - if (cblk == null) - { - return null; // No more code-blocks in current tile for component - // c - } - - // Ensure size of output buffer - if (intData) - { - // int data - dst_data_int = (int[])dst_data; - if (dst_data_int == null || dst_data_int.Length < cblk.w * cblk.h) - { - dst_data = new int[cblk.w * cblk.h]; - } - } - else - { - // float data - dst_data_float = (float[])dst_data; - if (dst_data_float == null || dst_data_float.Length < cblk.w * cblk.h) - { - dst_data = new float[cblk.w * cblk.h]; - } - } - - // Copy data line by line - src_data = cblk.Data; - w = cblk.w; - for (j = w * (cblk.h - 1), k = cblk.offset + (cblk.h - 1) * cblk.scanw; j >= 0; j -= w, k -= cblk.scanw) - { - // CONVERSION PROBLEM? - Array.Copy((System.Array)src_data, k, (System.Array)dst_data, j, w); - } - cblk.Data = dst_data; - cblk.offset = 0; - cblk.scanw = w; - - return cblk; - } - - /// Return the data type of this CBlkWTDataSrc. Its value should be either - /// DataBlk.TYPE_INT or DataBlk.TYPE_FLOAT but can change according to the - /// current tile-component. - /// - /// - /// The index of the tile for which to return the data type. - /// - /// - /// The index of the component for which to return the data type. - /// - /// - /// Current data type - /// - /// - public override int getDataType(int t, int c) - { - return filters.getWTDataType(t, c); - } - - /// Returns the next subband that will be used to get the next code-block - /// to return by the getNext[Intern]CodeBlock method. - /// - /// - /// The component - /// - /// - /// Its returns the next subband that will be used to get the next - /// code-block to return by the getNext[Intern]CodeBlock method. - /// - /// - private SubbandAn getNextSubband(int c) - { - int down = 1; - int up = 0; - int direction = down; - SubbandAn nextsb; - - nextsb = currentSubband[c]; - //If it is the first call to this method - if (nextsb == null) - { - nextsb = getAnSubbandTree(tIdx, c); - //If there is no decomposition level then send the whole image - if (!nextsb.isNode) - { - return nextsb; - } - } - - //Find the next subband to send - do - { - //If the current subband is null then break - if (nextsb == null) - { - break; - } - //If the current subband is a leaf then select the next leaf to - //send or go up in the decomposition tree if the leaf was a LL - //one. - else if (!nextsb.isNode) - { - switch (nextsb.orientation) - { - - case Subband.WT_ORIENT_HH: - nextsb = (SubbandAn)nextsb.Parent.LH; - direction = down; - break; - - case Subband.WT_ORIENT_LH: - nextsb = (SubbandAn)nextsb.Parent.HL; - direction = down; - break; - - case Subband.WT_ORIENT_HL: - nextsb = (SubbandAn)nextsb.Parent.LL; - direction = down; - break; - - case Subband.WT_ORIENT_LL: - nextsb = (SubbandAn)nextsb.Parent; - direction = up; - break; - } - } - //Else if the current subband is a node - else if (nextsb.isNode) - { - //If the direction is down the select the HH subband of the - //current node. - if (direction == down) - { - nextsb = (SubbandAn)nextsb.HH; - } - //Else the direction is up the select the next node to cover - //or still go up in the decomposition tree if the node is a LL - //subband - else if (direction == up) - { - switch (nextsb.orientation) - { - - case Subband.WT_ORIENT_HH: - nextsb = (SubbandAn)nextsb.Parent.LH; - direction = down; - break; - - case Subband.WT_ORIENT_LH: - nextsb = (SubbandAn)nextsb.Parent.HL; - direction = down; - break; - - case Subband.WT_ORIENT_HL: - nextsb = (SubbandAn)nextsb.Parent.LL; - direction = down; - break; - - case Subband.WT_ORIENT_LL: - nextsb = (SubbandAn)nextsb.Parent; - direction = up; - break; - } - } - } - - if (nextsb == null) - { - break; - } - } - while (nextsb.isNode); - return nextsb; - } - - /// Performs the forward wavelet transform on the whole band. It - /// iteratively decomposes the subbands from the top node to the leaves. - /// - /// - /// The band containing the float data to decompose - /// - /// - /// The structure containing the coordinates of the current - /// subband in the whole band to decompose. - /// - /// - /// The index of the current component to decompose - /// - /// - private void waveletTreeDecomposition(DataBlk band, SubbandAn subband, int c) - { - - //If the current subband is a leaf then nothing to be done (a leaf is - //not decomposed). - if (!subband.isNode) - { - return; - } - else - { - //Perform the 2D wavelet decomposition of the current subband - wavelet2DDecomposition(band, (SubbandAn)subband, c); - - //Perform the decomposition of the four resulting subbands - waveletTreeDecomposition(band, (SubbandAn)subband.HH, c); - waveletTreeDecomposition(band, (SubbandAn)subband.LH, c); - waveletTreeDecomposition(band, (SubbandAn)subband.HL, c); - waveletTreeDecomposition(band, (SubbandAn)subband.LL, c); - } - } - - /// Performs the 2D forward wavelet transform on a subband of the initial - /// band. This method will successively perform 1D filtering steps on all - /// lines and then all columns of the subband. In this class only filters - /// with floating point implementations can be used. - /// - /// - /// The band containing the float data to decompose - /// - /// - /// The structure containing the coordinates of the subband - /// in the whole band to decompose. - /// - /// - /// The index of the current component to decompose - /// - /// - private void wavelet2DDecomposition(DataBlk band, SubbandAn subband, int c) - { - - int ulx, uly, w, h; - int band_w, band_h; - - // If subband is empty (i.e. zero size) nothing to do - if (subband.w == 0 || subband.h == 0) - { - return; - } - - ulx = subband.ulx; - uly = subband.uly; - w = subband.w; - h = subband.h; - band_w = getTileCompWidth(tIdx, c); - band_h = getTileCompHeight(tIdx, c); - - if (intData) - { - //Perform the decompositions if the filter is implemented with an - //integer arithmetic. - int i, j; - int offset; - int[] tmpVector = new int[System.Math.Max(w, h)]; - int[] data = ((DataBlkInt)band).DataInt; - - //Perform the vertical decomposition - if (subband.ulcy % 2 == 0) - { - // Even start index => use LPF - for (j = 0; j < w; j++) - { - offset = uly * band_w + ulx + j; - for (i = 0; i < h; i++) - tmpVector[i] = data[offset + (i * band_w)]; - subband.vFilter.analyze_lpf(tmpVector, 0, h, 1, data, offset, band_w, data, offset + ((h + 1) / 2) * band_w, band_w); - } - } - else - { - // Odd start index => use HPF - for (j = 0; j < w; j++) - { - offset = uly * band_w + ulx + j; - for (i = 0; i < h; i++) - tmpVector[i] = data[offset + (i * band_w)]; - subband.vFilter.analyze_hpf(tmpVector, 0, h, 1, data, offset, band_w, data, offset + (h / 2) * band_w, band_w); - } - } - - //Perform the horizontal decomposition. - if (subband.ulcx % 2 == 0) - { - // Even start index => use LPF - for (i = 0; i < h; i++) - { - offset = (uly + i) * band_w + ulx; - for (j = 0; j < w; j++) - tmpVector[j] = data[offset + j]; - subband.hFilter.analyze_lpf(tmpVector, 0, w, 1, data, offset, 1, data, offset + (w + 1) / 2, 1); - } - } - else - { - // Odd start index => use HPF - for (i = 0; i < h; i++) - { - offset = (uly + i) * band_w + ulx; - for (j = 0; j < w; j++) - tmpVector[j] = data[offset + j]; - subband.hFilter.analyze_hpf(tmpVector, 0, w, 1, data, offset, 1, data, offset + w / 2, 1); - } - } - } - else - { - //Perform the decompositions if the filter is implemented with a - //float arithmetic. - int i, j; - int offset; - float[] tmpVector = new float[System.Math.Max(w, h)]; - float[] data = ((DataBlkFloat)band).DataFloat; - - //Perform the vertical decomposition. - if (subband.ulcy % 2 == 0) - { - // Even start index => use LPF - for (j = 0; j < w; j++) - { - offset = uly * band_w + ulx + j; - for (i = 0; i < h; i++) - tmpVector[i] = data[offset + (i * band_w)]; - subband.vFilter.analyze_lpf(tmpVector, 0, h, 1, data, offset, band_w, data, offset + ((h + 1) / 2) * band_w, band_w); - } - } - else - { - // Odd start index => use HPF - for (j = 0; j < w; j++) - { - offset = uly * band_w + ulx + j; - for (i = 0; i < h; i++) - tmpVector[i] = data[offset + (i * band_w)]; - subband.vFilter.analyze_hpf(tmpVector, 0, h, 1, data, offset, band_w, data, offset + (h / 2) * band_w, band_w); - } - } - //Perform the horizontal decomposition. - if (subband.ulcx % 2 == 0) - { - // Even start index => use LPF - for (i = 0; i < h; i++) - { - offset = (uly + i) * band_w + ulx; - for (j = 0; j < w; j++) - tmpVector[j] = data[offset + j]; - subband.hFilter.analyze_lpf(tmpVector, 0, w, 1, data, offset, 1, data, offset + (w + 1) / 2, 1); - } - } - else - { - // Odd start index => use HPF - for (i = 0; i < h; i++) - { - offset = (uly + i) * band_w + ulx; - for (j = 0; j < w; j++) - tmpVector[j] = data[offset + j]; - subband.hFilter.analyze_hpf(tmpVector, 0, w, 1, data, offset, 1, data, offset + w / 2, 1); - } - } - } - } - - /// Changes the current tile, given the new coordinates. - /// - ///

    This method resets the 'subbTrees' array, and recalculates the - /// values of the 'reversible' array. It also resets the decomposed - /// component buffers.

    - /// - ///
    - /// The horizontal coordinate of the tile. - /// - /// - /// The vertical coordinate of the new tile. - /// - /// - public override void setTile(int x, int y) - { - int i; - - // Change tile - base.setTile(x, y); - - // Reset the decomposed component buffers. - if (decomposedComps != null) - { - for (i = decomposedComps.Length - 1; i >= 0; i--) - { - decomposedComps[i] = null; - currentSubband[i] = null; - } - } - } - - /// Advances to the next tile, in standard scan-line order (by rows then - /// columns). An NoNextElementException is thrown if the current tile is - /// the last one (i.e. there is no next tile). - /// - ///

    This method resets the 'subbTrees' array, and recalculates the - /// values of the 'reversible' array. It also resets the decomposed - /// component buffers.

    - /// - ///
    - public override void nextTile() - { - int i; - - // Change tile - base.nextTile(); - // Reset the decomposed component buffers - if (decomposedComps != null) - { - for (i = decomposedComps.Length - 1; i >= 0; i--) - { - decomposedComps[i] = null; - currentSubband[i] = null; - } - } - } - - /// Returns a reference to the subband tree structure representing the - /// subband decomposition for the specified tile-component of the source. - /// - /// - /// The index of the tile. - /// - /// - /// The index of the component. - /// - /// - /// The subband tree structure, see Subband. - /// - /// - /// - /// - /// - /// - /// - public override SubbandAn getAnSubbandTree(int t, int c) - { - if (subbTrees[t][c] == null) - { - subbTrees[t][c] = new SubbandAn(getTileCompWidth(t, c), getTileCompHeight(t, c), getCompULX(c), getCompULY(c), getDecompLevels(t, c), getHorAnWaveletFilters(t, c), getVertAnWaveletFilters(t, c)); - initSubbandsFields(t, c, subbTrees[t][c]); - } - return subbTrees[t][c]; - } - - /// Initialises subbands fields, such as number of code-blocks and - /// code-blocks dimension, in the subband tree. The nominal code-block - /// width/height depends on the precincts dimensions if used. - /// - /// - /// The tile index of the subband - /// - /// - /// The component index - /// - /// - /// The subband tree to be initialised. - /// - /// - private void initSubbandsFields(int t, int c, Subband sb) - { - int cbw = cblks.getCBlkWidth(ModuleSpec.SPEC_TILE_COMP, t, c); - int cbh = cblks.getCBlkHeight(ModuleSpec.SPEC_TILE_COMP, t, c); - - if (!sb.isNode) - { - // Code-blocks dimension - int ppx, ppy; - int ppxExp, ppyExp, cbwExp, cbhExp; - ppx = pss.getPPX(t, c, sb.resLvl); - ppy = pss.getPPY(t, c, sb.resLvl); - - if (ppx != CSJ2K.j2k.codestream.Markers.PRECINCT_PARTITION_DEF_SIZE || ppy != CSJ2K.j2k.codestream.Markers.PRECINCT_PARTITION_DEF_SIZE) - { - - ppxExp = MathUtil.log2(ppx); - ppyExp = MathUtil.log2(ppy); - cbwExp = MathUtil.log2(cbw); - cbhExp = MathUtil.log2(cbh); - - // Precinct partition is used - switch (sb.resLvl) - { - - case 0: - sb.nomCBlkW = (cbwExp < ppxExp ? (1 << cbwExp) : (1 << ppxExp)); - sb.nomCBlkH = (cbhExp < ppyExp ? (1 << cbhExp) : (1 << ppyExp)); - break; - - - default: - sb.nomCBlkW = (cbwExp < ppxExp - 1 ? (1 << cbwExp) : (1 << (ppxExp - 1))); - sb.nomCBlkH = (cbhExp < ppyExp - 1 ? (1 << cbhExp) : (1 << (ppyExp - 1))); - break; - - } - } - else - { - sb.nomCBlkW = cbw; - sb.nomCBlkH = cbh; - } - - // Number of code-blocks - if (sb.numCb == null) - sb.numCb = new Coord(); - if (sb.w != 0 && sb.h != 0) - { - int acb0x = cb0x; - int acb0y = cb0y; - int tmp; - - // Project code-block partition origin to subband. Since the - // origin is always 0 or 1, it projects to the low-pass side - // (throught the ceil operator) as itself (i.e. no change) and - // to the high-pass side (through the floor operator) as 0, - // always. - switch (sb.sbandIdx) - { - - case Subband.WT_ORIENT_LL: - // No need to project since all low-pass => nothing to do - break; - - case Subband.WT_ORIENT_HL: - acb0x = 0; - break; - - case Subband.WT_ORIENT_LH: - acb0y = 0; - break; - - case Subband.WT_ORIENT_HH: - acb0x = 0; - acb0y = 0; - break; - - default: - throw new System.ApplicationException("Internal JJ2000 error"); - - } - if (sb.ulcx - acb0x < 0 || sb.ulcy - acb0y < 0) - { - throw new System.ArgumentException("Invalid code-blocks " + "partition origin or " + "image offset in the " + "reference grid."); - } - // NOTE: when calculating "floor()" by integer division the - // dividend and divisor must be positive, we ensure that by - // adding the divisor to the dividend and then substracting 1 - // to the result of the division - tmp = sb.ulcx - acb0x + sb.nomCBlkW; - sb.numCb.x = (tmp + sb.w - 1) / sb.nomCBlkW - (tmp / sb.nomCBlkW - 1); - tmp = sb.ulcy - acb0y + sb.nomCBlkH; - sb.numCb.y = (tmp + sb.h - 1) / sb.nomCBlkH - (tmp / sb.nomCBlkH - 1); - } - else - { - sb.numCb.x = sb.numCb.y = 0; - } - } - else - { - initSubbandsFields(t, c, sb.LL); - initSubbandsFields(t, c, sb.HL); - initSubbandsFields(t, c, sb.LH); - initSubbandsFields(t, c, sb.HH); - } - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/wavelet/analysis/ForwardWT.cs b/CSJ2K/j2k/wavelet/analysis/ForwardWT.cs deleted file mode 100644 index 21a23794..00000000 --- a/CSJ2K/j2k/wavelet/analysis/ForwardWT.cs +++ /dev/null @@ -1,209 +0,0 @@ -/* -* CVS identifier: -* -* $Id: ForwardWT.java,v 1.60 2001/09/14 09:54:53 grosbois Exp $ -* -* Class: ForwardWT -* -* Description: This interface defines the specifics -* of forward wavelet transforms -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.encoder; -using CSJ2K.j2k.image; -using CSJ2K.j2k.util; -namespace CSJ2K.j2k.wavelet.analysis -{ - - /// This abstract class represents the forward wavelet transform functional - /// block. The functional block may actually be comprised of several classes - /// linked together, but a subclass of this abstract class is the one that is - /// returned as the functional block that performs the forward wavelet - /// transform. - /// - ///

    This class assumes that data is transferred in code-blocks, as defined - /// by the 'CBlkWTDataSrc' interface. The internal calculation of the wavelet - /// transform may be done differently but a buffering class should convert to - /// that type of transfer.

    - /// - ///
    - public abstract class ForwardWT : ImgDataAdapter, ForwWT, CBlkWTDataSrc - { - /// Returns the parameters that are used in this class and implementing - /// classes. It returns a 2D String array. Each of the 1D arrays is for a - /// different option, and they have 3 elements. The first element is the - /// option name, the second one is the synopsis and the third one is a long - /// description of what the parameter is. The synopsis or description may - /// be 'null', in which case it is assumed that there is no synopsis or - /// description of the option, respectively. Null may be returned if no - /// options are supported. - /// - /// - /// the options name, their synopsis and their explanation, or null - /// if no options are supported. - /// - /// - public static System.String[][] ParameterInfo - { - get - { - return pinfo; - } - - } - public abstract int CbULY { get; } - public abstract int CbULX { get; } - - /// ID for the dyadic wavelet tree decomposition (also called "Mallat" in - /// JPEG 2000): 0x00. - /// - /// - public const int WT_DECOMP_DYADIC = 0; - - /// The prefix for wavelet transform options: 'W' - public const char OPT_PREFIX = 'W'; - - /// The list of parameters that is accepted for wavelet transform. Options - /// for the wavelet transform start with 'W'. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'pinfo'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly System.String[][] pinfo = new System.String[][] { new System.String[] { "Wlev", "", "Specifies the number of wavelet decomposition levels to apply to " + "the image. If 0 no wavelet transform is performed. All components " + "and all tiles have the same number of decomposition levels.", "5" }, new System.String[] { "Wwt", "[full]", "Specifies the wavelet transform to be used. Possible value is: " + "'full' (full page). The value 'full' performs a normal DWT.", "full" }, new System.String[] { "Wcboff", "", "Code-blocks partition offset in the reference grid. Allowed for " + " and are 0 and 1.\n" + "Note: This option is defined in JPEG 2000 part 2 and may not" + " be supported by all JPEG 2000 decoders.", "0 0" } }; - - /// Initializes this object for the specified number of tiles 'nt' and - /// components 'nc'. - /// - /// - /// The source of ImgData - /// - /// - protected internal ForwardWT(ImgData src) : base(src) - { - } - - /// Creates a ForwardWT object with the specified filters, and with other - /// options specified in the parameter list 'pl'. - /// - /// - /// The source of data to be transformed - /// - /// - /// The parameter list (or options). - /// - /// - /// The encoder specifications. - /// - /// - /// A new ForwardWT object with the specified filters and options - /// from 'pl'. - /// - /// - /// If mandatory parameters are missing - /// or if invalid values are given. - /// - /// - public static ForwardWT createInstance(BlkImgDataSrc src, ParameterList pl, EncoderSpecs encSpec) - { - int deflev; // defdec removed - //System.String decompstr; - //System.String wtstr; - //System.String pstr; - //SupportClass.StreamTokenizerSupport stok; - //SupportClass.Tokenizer strtok; - //int prefx, prefy; // Partitioning reference point coordinates - - // Check parameters - pl.checkList(OPT_PREFIX, CSJ2K.j2k.util.ParameterList.toNameArray(pinfo)); - - deflev = ((System.Int32)encSpec.dls.getDefault()); - - // Code-block partition origin - System.String str = ""; - if (pl.getParameter("Wcboff") == null) - { - throw new System.ApplicationException("You must specify an argument to the '-Wcboff' " + "option. See usage with the '-u' option"); - } - SupportClass.Tokenizer stk = new SupportClass.Tokenizer(pl.getParameter("Wcboff")); - if (stk.Count != 2) - { - throw new System.ArgumentException("'-Wcboff' option needs two" + " arguments. See usage with " + "the '-u' option."); - } - int cb0x = 0; - str = stk.NextToken(); - try - { - cb0x = (System.Int32.Parse(str)); - } - catch (System.FormatException) - { - throw new System.ArgumentException("Bad first parameter for the " + "'-Wcboff' option: " + str); - } - if (cb0x < 0 || cb0x > 1) - { - throw new System.ArgumentException("Invalid horizontal " + "code-block partition origin."); - } - int cb0y = 0; - str = stk.NextToken(); - try - { - cb0y = (System.Int32.Parse(str)); - } - catch (System.FormatException) - { - throw new System.ArgumentException("Bad second parameter for the " + "'-Wcboff' option: " + str); - } - if (cb0y < 0 || cb0y > 1) - { - throw new System.ArgumentException("Invalid vertical " + "code-block partition origin."); - } - if (cb0x != 0 || cb0y != 0) - { - FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.WARNING, "Code-blocks partition origin is " + "different from (0,0). This is defined in JPEG 2000" + " part 2 and may be not supported by all JPEG 2000 " + "decoders."); - } - - return new ForwWTFull(src, encSpec, cb0x, cb0y); - } - public abstract bool isReversible(int param1, int param2); - public abstract CSJ2K.j2k.wavelet.analysis.CBlkWTData getNextInternCodeBlock(int param1, CSJ2K.j2k.wavelet.analysis.CBlkWTData param2); - public abstract int getFixedPoint(int param1); - public abstract CSJ2K.j2k.wavelet.analysis.AnWTFilter[] getHorAnWaveletFilters(int param1, int param2); - public abstract CSJ2K.j2k.wavelet.analysis.AnWTFilter[] getVertAnWaveletFilters(int param1, int param2); - public abstract CSJ2K.j2k.wavelet.analysis.SubbandAn getAnSubbandTree(int param1, int param2); - public abstract int getDecompLevels(int param1, int param2); - public abstract CSJ2K.j2k.wavelet.analysis.CBlkWTData getNextCodeBlock(int param1, CSJ2K.j2k.wavelet.analysis.CBlkWTData param2); - public abstract int getImplementationType(int param1); - public abstract int getDataType(int param1, int param2); - public abstract int getDecomp(int param1, int param2); - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/wavelet/analysis/SubbandAn.cs b/CSJ2K/j2k/wavelet/analysis/SubbandAn.cs deleted file mode 100644 index c0a9a6c6..00000000 --- a/CSJ2K/j2k/wavelet/analysis/SubbandAn.cs +++ /dev/null @@ -1,513 +0,0 @@ -/* -* CVS identifier: -* -* $Id: SubbandAn.java,v 1.30 2001/08/02 09:13:53 grosbois Exp $ -* -* Class: SubbandAn -* -* Description: Element for a tree structure for a descripotion -* of subbands on the anslysis side. -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -namespace CSJ2K.j2k.wavelet.analysis -{ - - /// This class represents a subband in a bidirectional tree structure that - /// describes the subband decomposition for a wavelet transform, specifically - /// for the analysis side. - /// - ///

    The element can be either a node or a leaf of the tree. If it is a node - /// then ther are 4 descendants (LL, HL, LH and HH). If it is a leaf there are - /// no descendants.

    - /// - ///

    The tree is bidirectional. Each element in the tree structure has a - /// "parent", which is the subband from which the element was obtained by - /// decomposition. The only exception is the root element which has no parent - /// (i.e.it's null), for obvious reasons.

    - /// - ///
    - public class SubbandAn : Subband - { - /// Returns the parent of this subband. The parent of a subband is the - /// subband from which this one was obtained by decomposition. The root - /// element has no parent subband (null). - /// - /// - /// The parent subband, or null for the root one. - /// - /// - override public Subband Parent - { - get - { - return parentband; - } - - } - /// Returns the LL child subband of this subband. - /// - /// - /// The LL child subband, or null if there are no childs. - /// - /// - override public Subband LL - { - get - { - return subb_LL; - } - - } - /// Returns the HL (horizontal high-pass) child subband of this subband. - /// - /// - /// The HL child subband, or null if there are no childs. - /// - /// - override public Subband HL - { - get - { - return subb_HL; - } - - } - /// Returns the LH (vertical high-pass) child subband of this subband. - /// - /// - /// The LH child subband, or null if there are no childs. - /// - /// - override public Subband LH - { - get - { - return subb_LH; - } - - } - /// Returns the HH child subband of this subband. - /// - /// - /// The HH child subband, or null if there are no childs. - /// - /// - override public Subband HH - { - get - { - return subb_HH; - } - - } - /// This function returns the horizontal wavelet filter relevant to this - /// subband - /// - /// - /// The horizontal wavelet filter - /// - /// - override public WaveletFilter HorWFilter - { - get - { - return hFilter; - } - - } - /// This function returns the vertical wavelet filter relevant to this - /// subband - /// - /// - /// The vertical wavelet filter - /// - /// - override public WaveletFilter VerWFilter - { - get - { - return hFilter; - } - - } - - /// The reference to the parent of this subband. It is null for the root - /// element. It is null by default. - /// - public SubbandAn parentband = null; - - /// The reference to the LL subband resulting from the decomposition of - /// this subband. It is null by default. - /// - public SubbandAn subb_LL; - - /// The reference to the HL subband (horizontal high-pass) resulting from - /// the decomposition of this subband. It is null by default. - /// - public SubbandAn subb_HL; - - /// The reference to the LH subband (vertical high-pass) resulting from - /// the decomposition of this subband. It is null by default. - /// - /// - public SubbandAn subb_LH; - - /// The reference to the HH subband resulting from the decomposition of - /// this subband. It is null by default. - /// - public SubbandAn subb_HH; - - /// The horizontal analysis filter used to decompose this subband. This is - /// applicable to "node" elements only. The default value is null. - /// - public AnWTFilter hFilter; - - /// The vertical analysis filter used to decompose this subband. This is - /// applicable to "node" elements only. The default value is null. - /// - public AnWTFilter vFilter; - - /// The L2-norm of the synthesis basis waveform of this subband, - /// applicable to "leafs" only. By default it is -1 (i.e. not calculated - /// yet). - /// - /// - public float l2Norm = -1.0f; - - /// The contribution to the MSE or WMSE error that would result in the - /// image if there was an error of exactly one quantization step size in - /// the sample of the subband. This value is expressed relative to a - /// nominal dynamic range in the image domain of exactly 1.0. This field - /// contains valid data only after quantization 9See Quantizer). - /// - /// - /// - /// - /// - public float stepWMSE; - - /// Creates a SubbandAn element with all the default values. The dimensions - /// are (0,0) and the upper left corner is (0,0). - /// - /// - public SubbandAn() - { - } - - /// Creates the top-level node and the entire subband tree, with the - /// top-level dimensions, the number of decompositions, and the - /// decomposition tree as specified. - /// - ///

    This constructor just calls the same constructor of the super class, - /// and then calculates the L2-norm (or energy weight) of each leaf.

    - /// - ///

    This constructor does not initialize the value of the magBits or - /// stepWMSE member variables. This variables are normally initialized by - /// the quantizer (see Quantizer).

    - /// - ///
    - /// The top-level width - /// - /// - /// The top-level height - /// - /// - /// The horizontal coordinate of the upper-left corner with - /// respect to the canvas origin, in the component grid. - /// - /// - /// The vertical coordinate of the upper-left corner with - /// respect to the canvas origin, in the component grid. - /// - /// - /// The number of levels (or LL decompositions) in the tree. - /// - /// - /// The horizontal wavelet analysis filters for each - /// resolution level, starting at resolution level 0. - /// - /// - /// The vertical wavelet analysis filters for each - /// resolution level, starting at resolution level 0. - /// - /// - /// - /// WaveletFilter[],WaveletFilter[]) - /// - /// - /// - /// - /// - public SubbandAn(int w, int h, int ulcx, int ulcy, int lvls, WaveletFilter[] hfilters, WaveletFilter[] vfilters) : base(w, h, ulcx, ulcy, lvls, hfilters, vfilters) - { - // Caculate the L2-norms - calcL2Norms(); - } - - /// Splits the current subband in its four subbands. It changes the status - /// of this element (from a leaf to a node, and sets the filters), creates - /// the childs and initializes them. An IllegalArgumentException is thrown - /// if this subband is not a leaf. - /// - ///

    It uses the initChilds() method to initialize the childs.

    - /// - ///
    - /// The horizontal wavelet filter used to decompose this - /// subband. It has to be a AnWTFilter object. - /// - /// - /// The vertical wavelet filter used to decompose this - /// subband. It has to be a AnWTFilter object. - /// - /// - /// A reference to the LL leaf (subb_LL). - /// - /// - /// - /// - /// - protected internal override Subband split(WaveletFilter hfilter, WaveletFilter vfilter) - { - // Test that this is a node - if (isNode) - { - throw new System.ArgumentException(); - } - - // Modify this element into a node and set the filters - isNode = true; - this.hFilter = (AnWTFilter)hfilter; - this.vFilter = (AnWTFilter)vfilter; - - // Create childs - subb_LL = new SubbandAn(); - subb_LH = new SubbandAn(); - subb_HL = new SubbandAn(); - subb_HH = new SubbandAn(); - - // Assign parent - subb_LL.parentband = this; - subb_HL.parentband = this; - subb_LH.parentband = this; - subb_HH.parentband = this; - - // Initialize childs - initChilds(); - - // Return reference to LL subband - return subb_LL; - } - - /// Calculates the basis waveform of the first leaf for which the L2-norm - /// has not been calculated yet. This method searches recursively for the - /// first leaf for which the value has not been calculated yet, and then - /// calculates the L2-norm on the return path. - /// - ///

    The wfs argument should be a size 2 array of float arrays (i.e. 2D - /// array) and it must be of length 2 (or more). When returning, wfs[0] - /// will contain the line waveform, and wfs[1] will contain the column - /// waveform.

    - /// - ///

    This method can not be called on an element that ahs a non-negative - /// value in l2Norm, since that means that we are done.

    - /// - ///
    - /// An size 2 array where the line and column waveforms will be - /// returned. - /// - /// - private void calcBasisWaveForms(float[][] wfs) - { - if (l2Norm < 0) - { - // We are not finished with this element yet - if (isNode) - { - // We are on a node => search on childs - if (subb_LL.l2Norm < 0f) - { - subb_LL.calcBasisWaveForms(wfs); - wfs[0] = hFilter.getLPSynWaveForm(wfs[0], null); - wfs[1] = vFilter.getLPSynWaveForm(wfs[1], null); - } - else if (subb_HL.l2Norm < 0f) - { - subb_HL.calcBasisWaveForms(wfs); - wfs[0] = hFilter.getHPSynWaveForm(wfs[0], null); - wfs[1] = vFilter.getLPSynWaveForm(wfs[1], null); - } - else if (subb_LH.l2Norm < 0f) - { - subb_LH.calcBasisWaveForms(wfs); - wfs[0] = hFilter.getLPSynWaveForm(wfs[0], null); - wfs[1] = vFilter.getHPSynWaveForm(wfs[1], null); - } - else if (subb_HH.l2Norm < 0f) - { - subb_HH.calcBasisWaveForms(wfs); - wfs[0] = hFilter.getHPSynWaveForm(wfs[0], null); - wfs[1] = vFilter.getHPSynWaveForm(wfs[1], null); - } - else - { - // There is an error! If all childs have non-negative - // l2norm, then this node should have non-negative l2norm - throw new System.ApplicationException("You have found a bug in JJ2000!"); - } - } - else - { - // This is a leaf, just use diracs (null is equivalent to - // dirac) - wfs[0] = new float[1]; - wfs[0][0] = 1.0f; - wfs[1] = new float[1]; - wfs[1][0] = 1.0f; - } - } - else - { - // This is an error! The calcBasisWaveForms() method is never - // called on an element with non-negative l2norm - throw new System.ApplicationException("You have found a bug in JJ2000!"); - } - } - - /// Assigns the given L2-norm to the first leaf that does not have an - /// L2-norm value yet (i.e. l2norm is negative). The search is done - /// recursively and in the same order as that of the calcBasisWaveForms() - /// method, so that this method is used to assigne the l2norm of the - /// previously computed waveforms. - /// - ///

    This method can not be called on an element that ahs a non-negative - /// value in l2Norm, since that means that we are done.

    - /// - ///
    - /// The L2-norm to assign. - /// - /// - private void assignL2Norm(float l2n) - { - if (l2Norm < 0) - { - // We are not finished with this element yet - if (isNode) - { - // We are on a node => search on childs - if (subb_LL.l2Norm < 0f) - { - subb_LL.assignL2Norm(l2n); - } - else if (subb_HL.l2Norm < 0f) - { - subb_HL.assignL2Norm(l2n); - } - else if (subb_LH.l2Norm < 0f) - { - subb_LH.assignL2Norm(l2n); - } - else if (subb_HH.l2Norm < 0f) - { - subb_HH.assignL2Norm(l2n); - // If child now is done, we are done - if (subb_HH.l2Norm >= 0f) - { - l2Norm = 0f; // We are on a node, any non-neg value OK - } - } - else - { - // There is an error! If all childs have non-negative - // l2norm, then this node should have non-negative l2norm - throw new System.ApplicationException("You have found a bug in JJ2000!"); - } - } - else - { - // This is a leaf, assign the L2-norm - l2Norm = l2n; - } - } - else - { - // This is an error! The assignL2Norm() method is never called on - // an element with non-negative l2norm - throw new System.ApplicationException("You have found a bug in JJ2000!"); - } - } - - - /// Calculates the L2-norm of the sythesis waveforms of every leaf in the - /// tree. This method should only be called on the root element. - /// - /// - private void calcL2Norms() - { - int i; - float[][] wfs = new float[2][]; - double acc; - float l2n; - - // While we are not done on the root element, compute basis functions - // and assign L2-norm - while (l2Norm < 0f) - { - calcBasisWaveForms(wfs); - // Compute line L2-norm, which is the product of the line - // and column L2-norms - acc = 0.0; - for (i = wfs[0].Length - 1; i >= 0; i--) - { - acc += wfs[0][i] * wfs[0][i]; - } - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - l2n = (float)System.Math.Sqrt(acc); - // Compute column L2-norm - acc = 0.0; - for (i = wfs[1].Length - 1; i >= 0; i--) - { - acc += wfs[1][i] * wfs[1][i]; - } - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - l2n *= (float)System.Math.Sqrt(acc); - // Release waveforms - wfs[0] = null; - wfs[1] = null; - // Assign the value - assignL2Norm(l2n); - } - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/wavelet/synthesis/CBlkWTDataSrcDec.cs b/CSJ2K/j2k/wavelet/synthesis/CBlkWTDataSrcDec.cs deleted file mode 100644 index 5aec3e4c..00000000 --- a/CSJ2K/j2k/wavelet/synthesis/CBlkWTDataSrcDec.cs +++ /dev/null @@ -1,212 +0,0 @@ -/* -* CVS identifier: -* -* $Id: CBlkWTDataSrcDec.java,v 1.19 2001/09/20 12:46:31 grosbois Exp $ -* -* Class: CBlkWTDataSrcDec -* -* Description: Interface that define methods for trasnfer of WT -* data in a code-block basis (decoder side). -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.image; -namespace CSJ2K.j2k.wavelet.synthesis -{ - - /// This abstract class defines methods to transfer wavelet data in a - /// code-block by code-block basis, for the decoder side. In each call to - /// 'getCodeBlock()' or 'getInternCodeBlock()' a new code-block is - /// returned. The code-blocks are returned in no specific order. - /// - ///

    This class is the source of data, in general, for the inverse wavelet - /// transforms. See the 'InverseWT' class.

    - /// - ///
    - /// - /// - /// - /// - /// - /// - /// - /// - /// - public interface CBlkWTDataSrcDec : InvWTData - { - - /// Returns the number of bits, referred to as the "range bits", - /// corresponding to the nominal range of the data in the specified - /// component. - /// - ///

    The returned value corresponds to the nominal dynamic range of the - /// reconstructed image data, not of the wavelet coefficients - /// themselves. This is because different subbands have different gains and - /// thus different nominal ranges. To have an idea of the nominal range in - /// each subband the subband analysis gain value from the subband tree - /// structure, returned by the 'getSynSubbandTree()' method, can be - /// used. See the 'Subband' class for more details.

    - /// - ///

    If this number is b then for unsigned data the nominal range - /// is between 0 and 2^b-1, and for signed data it is between -2^(b-1) and - /// 2^(b-1)-1.

    - /// - ///
    - /// The index of the component. - /// - /// - /// The number of bits corresponding to the nominal range of the - /// data. - /// - /// - /// - /// - /// - int getNomRangeBits(int c); - - /// Returns the position of the fixed point in the specified component, or - /// equivalently the number of fractional bits. This is the position of the - /// least significant integral (i.e. non-fractional) bit, which is - /// equivalent to the number of fractional bits. For instance, for - /// fixed-point values with 2 fractional bits, 2 is returned. For - /// floating-point data this value does not apply and 0 should be - /// returned. Position 0 is the position of the least significant bit in - /// the data. - /// - /// - /// The index of the component. - /// - /// - /// The position of the fixed-point, which is the same as the - /// number of fractional bits. For floating-point data 0 is returned. - /// - /// - int getFixedPoint(int c); - - /// Returns the specified code-block in the current tile for the specified - /// component, as a copy (see below). - /// - ///

    The returned code-block may be progressive, which is indicated by - /// the 'progressive' variable of the returned 'DataBlk' object. If a - /// code-block is progressive it means that in a later request to this - /// method for the same code-block it is possible to retrieve data which is - /// a better approximation, since meanwhile more data to decode for the - /// code-block could have been received. If the code-block is not - /// progressive then later calls to this method for the same code-block - /// will return the exact same data values.

    - /// - ///

    The data returned by this method is always a copy of the internal - /// data of this object, if any, and it can be modified "in place" without - /// any problems after being returned. The 'offset' of the returned data is - /// 0, and the 'scanw' is the same as the code-block width. See the - /// 'DataBlk' class.

    - /// - ///
    - /// The component for which to return the next code-block. - /// - /// - /// The vertical index of the code-block to return, - /// in the specified subband. - /// - /// - /// The horizontal index of the code-block to return, - /// in the specified subband. - /// - /// - /// The subband in which the code-block to return is. - /// - /// - /// If non-null this object will be used to return the new - /// code-block. If null a new one will be allocated and returned. If the - /// "data" array of the object is non-null it will be reused, if possible, - /// to return the data. - /// - /// - /// The next code-block in the current tile for component 'n', or - /// null if all code-blocks for the current tile have been returned. - /// - /// - /// - /// - /// - DataBlk getCodeBlock(int c, int m, int n, SubbandSyn sb, DataBlk cblk); - - /// Returns the specified code-block in the current tile for the specified - /// component (as a reference or copy). - /// - ///

    The returned code-block may be progressive, which is indicated by - /// the 'progressive' variable of the returned 'DataBlk' object. If a - /// code-block is progressive it means that in a later request to this - /// method for the same code-block it is possible to retrieve data which is - /// a better approximation, since meanwhile more data to decode for the - /// code-block could have been received. If the code-block is not - /// progressive then later calls to this method for the same code-block - /// will return the exact same data values.

    - /// - ///

    The data returned by this method can be the data in the internal - /// buffer of this object, if any, and thus can not be modified by the - /// caller. The 'offset' and 'scanw' of the returned data can be - /// arbitrary. See the 'DataBlk' class.

    - /// - ///
    - /// The component for which to return the next code-block. - /// - /// - /// The vertical index of the code-block to return, in the - /// specified subband. - /// - /// - /// The horizontal index of the code-block to return, in the - /// specified subband. - /// - /// - /// The subband in which the code-block to return is. - /// - /// - /// If non-null this object will be used to return the new - /// code-block. If null a new one will be allocated and returned. If the - /// "data" array of the object is non-null it will be reused, if possible, - /// to return the data. - /// - /// - /// The next code-block in the current tile for component 'n', or - /// null if all code-blocks for the current tile have been returned. - /// - /// - /// - /// - /// - DataBlk getInternCodeBlock(int c, int m, int n, SubbandSyn sb, DataBlk cblk); - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/wavelet/synthesis/InvWT.cs b/CSJ2K/j2k/wavelet/synthesis/InvWT.cs deleted file mode 100644 index c4de4ec1..00000000 --- a/CSJ2K/j2k/wavelet/synthesis/InvWT.cs +++ /dev/null @@ -1,86 +0,0 @@ -/* -* CVS identifier: -* -* $Id: -* -* Class: InvWT -* -* Description: The interface for implementations of a inverse -* wavelet transform. -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -namespace CSJ2K.j2k.wavelet.synthesis -{ - - /// This interface extends the WaveletTransform with the specifics of inverse - /// wavelet transforms. Classes that implement inverse wavelet transfoms should - /// implement this interface. - /// - ///

    This class does not define the methods to transfer data, just the - /// specifics to inverse wavelet transform. Different data transfer methods are - /// envisageable for different transforms.

    - /// - ///
    - public interface InvWT : WaveletTransform - { - /// Sets the image reconstruction resolution level. A value of 0 means - /// reconstruction of an image with the lowest resolution (dimension) - /// available. - /// - ///

    Note: Image resolution level indexes may differ from tile-component - /// resolution index. They are indeed indexed starting from the lowest - /// number of decomposition levels of each component of each tile.

    - /// - ///

    Example: For an image (1 tile) with 2 components (component 0 having - /// 2 decomposition levels and component 1 having 3 decomposition levels), - /// the first (tile-) component has 3 resolution levels and the second one - /// has 4 resolution levels, whereas the image has only 3 resolution levels - /// available.

    - /// - ///
    - /// The image resolution level. - /// - /// - /// The vertical coordinate of the image origin in the canvas - /// system, on the reference grid. - /// - /// - int ImgResLevel - { - set; - - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/wavelet/synthesis/InvWTAdapter.cs b/CSJ2K/j2k/wavelet/synthesis/InvWTAdapter.cs deleted file mode 100644 index f3713e7f..00000000 --- a/CSJ2K/j2k/wavelet/synthesis/InvWTAdapter.cs +++ /dev/null @@ -1,592 +0,0 @@ -/* -* CVS identifier: -* -* $Id: InvWTAdapter.java,v 1.14 2002/07/25 15:11:03 grosbois Exp $ -* -* Class: InvWTAdapter -* -* Description: -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.decoder; -using CSJ2K.j2k.image; -namespace CSJ2K.j2k.wavelet.synthesis -{ - - /// This class provides default implementation of the methods in the 'InvWT' - /// interface. The source is always a 'MultiResImgData', which is a - /// multi-resolution image. The default implementation is just to return the - /// value of the source at the current image resolution level, which is set by - /// the 'setImgResLevel()' method. - /// - ///

    This abstract class can be used to facilitate the development of other - /// classes that implement the 'InvWT' interface, because most of the trivial - /// methods are already implemented.

    - /// - ///

    If the default implementation of a method provided in this class does - /// not suit a particular implementation of the 'InvWT' interface, the method - /// can be overriden to implement the proper behaviour.

    - /// - ///

    If the 'setImgResLevel()' method is overriden then it is very important - /// that the one of this class is called from the overriding method, so that - /// the other methods in this class return the correct values.

    - /// - ///
    - /// - /// - /// - public abstract class InvWTAdapter : InvWT - { - /// Sets the image reconstruction resolution level. A value of 0 means - /// reconstruction of an image with the lowest resolution (dimension) - /// available. - /// - ///

    Note: Image resolution level indexes may differ from tile-component - /// resolution index. They are indeed indexed starting from the lowest - /// number of decomposition levels of each component of each tile.

    - /// - ///

    Example: For an image (1 tile) with 2 components (component 0 having - /// 2 decomposition levels and component 1 having 3 decomposition levels), - /// the first (tile-) component has 3 resolution levels and the second one - /// has 4 resolution levels, whereas the image has only 3 resolution levels - /// available.

    - /// - ///
    - /// The image resolution level. - /// - /// - /// The vertical coordinate of the image origin in the canvas - /// system, on the reference grid. - /// - /// - virtual public int ImgResLevel - { - set - { - if (value < 0) - { - throw new System.ArgumentException("Resolution level index " + "cannot be negative."); - } - reslvl = value; - } - - } - /// Returns the overall width of the current tile in pixels. This is the - /// tile's width without accounting for any component subsampling. This is - /// also referred as the reference grid width in the current tile. - /// - ///

    This default implementation returns the value of the source at the - /// current reconstruction resolution level.

    - /// - ///
    - /// The total current tile's width in pixels. - /// - /// - virtual public int TileWidth - { - get - { - // Retrieves the tile maximum resolution level index and request the - // width from the source module. - int tIdx = TileIdx; - int rl = 10000; - int mrl; - int nc = mressrc.NumComps; - for (int c = 0; c < nc; c++) - { - mrl = mressrc.getSynSubbandTree(tIdx, c).resLvl; - if (mrl < rl) - rl = mrl; - } - return mressrc.getTileWidth(rl); - } - - } - /// Returns the overall height of the current tile in pixels. This - /// is the tile's height without accounting for any component - /// subsampling. This is also referred as the reference grid height - /// in the current tile. - /// - ///

    This default implementation returns the value of the source at the - /// current reconstruction resolution level.

    - /// - ///
    - /// The total current tile's height in pixels. - /// - /// - virtual public int TileHeight - { - get - { - // Retrieves the tile maximum resolution level index and request the - // height from the source module. - int tIdx = TileIdx; - int rl = 10000; - int mrl; - int nc = mressrc.NumComps; - for (int c = 0; c < nc; c++) - { - mrl = mressrc.getSynSubbandTree(tIdx, c).resLvl; - if (mrl < rl) - rl = mrl; - } - return mressrc.getTileHeight(rl); - } - - } - /// Returns the nominal width of tiles - virtual public int NomTileWidth - { - get - { - return mressrc.NomTileWidth; - } - - } - /// Returns the nominal height of tiles - virtual public int NomTileHeight - { - get - { - return mressrc.NomTileHeight; - } - - } - /// Returns the overall width of the image in pixels. This is the - /// image's width without accounting for any component subsampling - /// or tiling. - /// - /// - /// The total image's width in pixels. - /// - /// - virtual public int ImgWidth - { - get - { - return mressrc.getImgWidth(reslvl); - } - - } - /// Returns the overall height of the image in pixels. This is the - /// image's height without accounting for any component subsampling - /// or tiling. - /// - /// - /// The total image's height in pixels. - /// - /// - virtual public int ImgHeight - { - get - { - return mressrc.getImgHeight(reslvl); - } - - } - /// Returns the number of components in the image. - /// - /// - /// The number of components in the image. - /// - /// - virtual public int NumComps - { - get - { - return mressrc.NumComps; - } - - } - /// Returns the index of the current tile, relative to a standard scan-line - /// order. - /// - ///

    This default implementation returns the value of the source.

    - /// - ///
    - /// The current tile's index (starts at 0). - /// - /// - virtual public int TileIdx - { - get - { - return mressrc.TileIdx; - } - - } - /// Returns the horizontal coordinate of the image origin, the top-left - /// corner, in the canvas system, on the reference grid. - /// - ///

    This default implementation returns the value of the source at the - /// current reconstruction resolution level.

    - /// - ///
    - /// The horizontal coordinate of the image origin in the canvas - /// system, on the reference grid. - /// - /// - virtual public int ImgULX - { - get - { - return mressrc.getImgULX(reslvl); - } - - } - /// Returns the vertical coordinate of the image origin, the top-left - /// corner, in the canvas system, on the reference grid. - /// - ///

    This default implementation returns the value of the source at the - /// current reconstruction resolution level.

    - /// - ///
    - /// The vertical coordinate of the image origin in the canvas - /// system, on the reference grid. - /// - /// - virtual public int ImgULY - { - get - { - return mressrc.getImgULY(reslvl); - } - - } - /// Returns the horizontal tile partition offset in the reference grid - virtual public int TilePartULX - { - get - { - return mressrc.TilePartULX; - } - - } - /// Returns the vertical tile partition offset in the reference grid - virtual public int TilePartULY - { - get - { - return mressrc.TilePartULY; - } - - } - - /// The decoder specifications - protected internal DecoderSpecs decSpec; - - /// The 'MultiResImgData' source - protected internal MultiResImgData mressrc; - - /// The resquested image resolution level for reconstruction. - protected internal int reslvl; - - /// The maximum available image resolution level - protected internal int maxImgRes; - - /// Instantiates the 'InvWTAdapter' object using the specified - /// 'MultiResImgData' source. The reconstruction resolution level is set to - /// full resolution (i.e. the maximum resolution level). - /// - /// - /// From where to obtain the values to return - /// - /// - /// The decoder specifications - /// - /// - protected internal InvWTAdapter(MultiResImgData src, DecoderSpecs decSpec) - { - mressrc = src; - this.decSpec = decSpec; - maxImgRes = decSpec.dls.Min; - } - - /// Returns the component subsampling factor in the horizontal - /// direction, for the specified component. This is, approximately, - /// the ratio of dimensions between the reference grid and the - /// component itself, see the 'ImgData' interface desription for - /// details. - /// - /// - /// The index of the component (between 0 and N-1). - /// - /// - /// The horizontal subsampling factor of component 'c'. - /// - /// - /// - /// - /// - public virtual int getCompSubsX(int c) - { - return mressrc.getCompSubsX(c); - } - - /// Returns the component subsampling factor in the vertical - /// direction, for the specified component. This is, approximately, - /// the ratio of dimensions between the reference grid and the - /// component itself, see the 'ImgData' interface desription for - /// details. - /// - /// - /// The index of the component (between 0 and N-1). - /// - /// - /// The vertical subsampling factor of component 'c'. - /// - /// - /// - /// - /// - public virtual int getCompSubsY(int c) - { - return mressrc.getCompSubsY(c); - } - - /// Returns the width in pixels of the specified tile-component - /// - /// - /// Tile index - /// - /// - /// The index of the component, from 0 to N-1. - /// - /// - /// The width in pixels of component n in tile t. - /// - /// - public virtual int getTileCompWidth(int t, int c) - { - // Retrieves the tile-component maximum resolution index and gets the - // width from the source. - int rl = mressrc.getSynSubbandTree(t, c).resLvl; - return mressrc.getTileCompWidth(t, c, rl); - } - - /// Returns the height in pixels of the specified tile-component. - /// - ///

    This default implementation returns the value of the source at the - /// current reconstruction resolution level.

    - /// - ///
    - /// The tile index. - /// - /// - /// The index of the component, from 0 to N-1. - /// - /// - /// The height in pixels of component n in tile - /// t. - /// - /// - public virtual int getTileCompHeight(int t, int c) - { - // Retrieves the tile-component maximum resolution index and gets the - // height from the source. - int rl = mressrc.getSynSubbandTree(t, c).resLvl; - return mressrc.getTileCompHeight(t, c, rl); - } - - /// Returns the width in pixels of the specified component in the overall - /// image. - /// - /// - /// The index of the component, from 0 to N-1. - /// - /// - /// The width in pixels of component c in the overall - /// image. - /// - /// - public virtual int getCompImgWidth(int c) - { - // Retrieves the component maximum resolution index and gets the width - // from the source module. - int rl = decSpec.dls.getMinInComp(c); - return mressrc.getCompImgWidth(c, rl); - } - - /// Returns the height in pixels of the specified component in the overall - /// image. - /// - ///

    This default implementation returns the value of the source at the - /// current reconstruction resolution level.

    - /// - ///
    - /// The index of the component, from 0 to N-1. - /// - /// - /// The height in pixels of component n in the overall - /// image. - /// - /// - public virtual int getCompImgHeight(int c) - { - // Retrieves the component maximum resolution index and gets the - // height from the source module. - int rl = decSpec.dls.getMinInComp(c); - return mressrc.getCompImgHeight(c, rl); - } - - /// Changes the current tile, given the new indices. An - /// IllegalArgumentException is thrown if the coordinates do not correspond - /// to a valid tile. - /// - ///

    This default implementation calls the same method on the source.

    - /// - ///
    - /// The horizontal index of the tile. - /// - /// - /// The vertical index of the new tile. - /// - /// - public virtual void setTile(int x, int y) - { - mressrc.setTile(x, y); - } - - /// Advances to the next tile, in standard scan-line order (by rows then - /// columns). An NoNextElementException is thrown if the current tile is - /// the last one (i.e. there is no next tile). - /// - ///

    This default implementation calls the same method on the source.

    - /// - ///
    - public virtual void nextTile() - { - mressrc.nextTile(); - } - - /// Returns the indixes of the current tile. These are the horizontal and - /// vertical indexes of the current tile. - /// - ///

    This default implementation returns the value of the source.

    - /// - ///
    - /// If not null this object is used to return the information. If - /// null a new one is created and returned. - /// - /// - /// The current tile's indices (vertical and horizontal indexes). - /// - /// - public virtual Coord getTile(Coord co) - { - return mressrc.getTile(co); - } - - /// Returns the horizontal coordinate of the upper-left corner of the - /// specified component in the current tile. - /// - /// - /// The component index. - /// - /// - public virtual int getCompULX(int c) - { - // Find tile-component maximum resolution index and gets information - // from the source module. - int tIdx = TileIdx; - int rl = mressrc.getSynSubbandTree(tIdx, c).resLvl; - return mressrc.getResULX(c, rl); - } - - /// Returns the vertical coordinate of the upper-left corner of the - /// specified component in the current tile. - /// - /// - /// The component index. - /// - /// - public virtual int getCompULY(int c) - { - // Find tile-component maximum resolution index and gets information - // from the source module. - int tIdx = TileIdx; - int rl = mressrc.getSynSubbandTree(tIdx, c).resLvl; - return mressrc.getResULY(c, rl); - } - - /// Returns the number of tiles in the horizontal and vertical directions. - /// - ///

    This default implementation returns the value of the source.

    - /// - ///
    - /// If not null this object is used to return the information. If - /// null a new one is created and returned. - /// - /// - /// The number of tiles in the horizontal (Coord.x) and vertical - /// (Coord.y) directions. - /// - /// - public virtual Coord getNumTiles(Coord co) - { - return mressrc.getNumTiles(co); - } - - /// Returns the total number of tiles in the image. - /// - ///

    This default implementation returns the value of the source.

    - /// - ///
    - /// The total number of tiles in the image. - /// - /// - public virtual int getNumTiles() - { - return mressrc.getNumTiles(); - } - - /// Returns the specified synthesis subband tree - /// - /// - /// Tile index. - /// - /// - /// Component index. - /// - /// - public virtual SubbandSyn getSynSubbandTree(int t, int c) - { - return mressrc.getSynSubbandTree(t, c); - } - public abstract bool isReversible(int param1, int param2); - public abstract int getNomRangeBits(int param1); - public abstract int getImplementationType(int param1); - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/wavelet/synthesis/InvWTData.cs b/CSJ2K/j2k/wavelet/synthesis/InvWTData.cs deleted file mode 100644 index 446cf810..00000000 --- a/CSJ2K/j2k/wavelet/synthesis/InvWTData.cs +++ /dev/null @@ -1,89 +0,0 @@ -/* -* CVS identifier: -* -* $Id: InvWTData.java,v 1.15 2001/09/20 13:07:09 grosbois Exp $ -* -* Class: InvWTData -* -* Description: -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -namespace CSJ2K.j2k.wavelet.synthesis -{ - - /// This interface extends the MultiResImgData interface with the methods that - /// are necessary for inverse wavelet data (i.e. data that is the source to an - /// inverse wavlet trasnform). - /// - /// - public interface InvWTData : MultiResImgData - { - /// Returns the horizontal code-block partition origin. Allowable values - /// are 0 and 1, nothing else. - /// - /// - int CbULX - { - get; - - } - /// Returns the vertical code-block partition origin Allowable values are 0 - /// and 1, nothing else. - /// - /// - int CbULY - { - get; - - } - - /// Returns the subband tree, for the specified tile-component. This method - /// returns the root element of the subband tree structure, see 'Subband' - /// and 'SubbandSyn'. The tree comprises all the available resolution - /// levels. - /// - /// - /// The index of the tile, from 0 to T-1. - /// - /// - /// The index of the component, from 0 to C-1. - /// - /// - /// The root of the tree structure. - /// - /// - new SubbandSyn getSynSubbandTree(int t, int c); - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/wavelet/synthesis/InvWTFull.cs b/CSJ2K/j2k/wavelet/synthesis/InvWTFull.cs deleted file mode 100644 index 2a8a1140..00000000 --- a/CSJ2K/j2k/wavelet/synthesis/InvWTFull.cs +++ /dev/null @@ -1,738 +0,0 @@ -/* -* CVS identifier: -* -* $Id: InvWTFull.java,v 1.20 2002/05/22 15:01:32 grosbois Exp $ -* -* Class: InvWTFull -* -* Description: This class implements a full page inverse DWT for -* int and float data. -* -* the InvWTFullInt and InvWTFullFloat -* classes by Bertrand Berthelot, Apr-19-1999 -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.decoder; -using CSJ2K.j2k.image; -using CSJ2K.j2k.util; -using System; -using System.Collections.Generic; -namespace CSJ2K.j2k.wavelet.synthesis -{ - - /// This class implements the InverseWT with the full-page approach for int and - /// float data. - /// - ///

    The image can be reconstructed at different (image) resolution levels - /// indexed from the lowest resolution available for each tile-component. This - /// is controlled by the setImgResLevel() method.

    - /// - ///

    Note: Image resolution level indexes may differ from tile-component - /// resolution index. They are indeed indexed starting from the lowest number - /// of decomposition levels of each component of each tile.

    - /// - ///

    Example: For an image (1 tile) with 2 components (component 0 having 2 - /// decomposition levels and component 1 having 3 decomposition levels), the - /// first (tile-) component has 3 resolution levels and the second one has 4 - /// resolution levels, whereas the image has only 3 resolution levels - /// available.

    - /// - ///

    This implementation does not support progressive data: Data is - /// considered to be non-progressive (i.e. "final" data) and the 'progressive' - /// attribute of the 'DataBlk' class is always set to false, see the 'DataBlk' - /// class.

    - /// - ///
    - /// - /// - /// - public class InvWTFull : InverseWT - { - - /// Reference to the ProgressWatch instance if any - private ProgressWatch pw = null; - - /// The total number of code-blocks to decode - private int cblkToDecode = 0; - - /// The number of already decoded code-blocks - private int nDecCblk = 0; - - /// the code-block buffer's source i.e. the quantizer - private CBlkWTDataSrcDec src; - - /// Current data type - private int dtype; - - /// Block storing the reconstructed image for each component - private DataBlk[] reconstructedComps; - - /// Number of decomposition levels in each component - private int[] ndl; - - /// The reversible flag for each component in each tile. The first index is - /// the tile index, the second one is the component index. The - /// reversibility of the components for each tile are calculated on a as - /// needed basis. - /// - /// - private Dictionary reversible = new Dictionary(); - //private bool[][] reversible; - - /// Initializes this object with the given source of wavelet - /// coefficients. It initializes the resolution level for full resolutioin - /// reconstruction. - /// - /// - /// from where the wavelet coefficinets should be obtained. - /// - /// - /// The decoder specifications - /// - /// - public InvWTFull(CBlkWTDataSrcDec src, DecoderSpecs decSpec) : base(src, decSpec) - { - this.src = src; - int nc = src.NumComps; - reconstructedComps = new DataBlk[nc]; - ndl = new int[nc]; - pw = FacilityManager.ProgressWatch; - } - - /// Returns the reversibility of the current subband. It computes - /// iteratively the reversibility of the child subbands. For each subband - /// it tests the reversibility of the horizontal and vertical synthesis - /// filters used to reconstruct this subband. - /// - /// - /// The current subband. - /// - /// - /// true if all the filters used to reconstruct the current - /// subband are reversible - /// - /// - private bool isSubbandReversible(Subband subband) - { - if (subband.isNode) - { - // It's reversible if the filters to obtain the 4 subbands are - // reversible and the ones for this one are reversible too. - return isSubbandReversible(subband.LL) && isSubbandReversible(subband.HL) && isSubbandReversible(subband.LH) && isSubbandReversible(subband.HH) && ((SubbandSyn)subband).hFilter.Reversible && ((SubbandSyn)subband).vFilter.Reversible; - } - else - { - // Leaf subband. Reversibility of data depends on source, so say - // it's true - return true; - } - } - - /// Returns the reversibility of the wavelet transform for the specified - /// component, in the current tile. A wavelet transform is reversible when - /// it is suitable for lossless and lossy-to-lossless compression. - /// - /// - /// The index of the tile. - /// - /// - /// The index of the component. - /// - /// - /// true is the wavelet transform is reversible, false if not. - /// - /// - public override bool isReversible(int t, int c) - { - if (reversible[t] == null) - { - // Reversibility not yet calculated for this tile - reversible[t] = new bool[NumComps]; - for (int i = reversible[t].Length - 1; i >= 0; i--) - { - reversible[t][i] = isSubbandReversible(src.getSynSubbandTree(t, i)); - } - } - return reversible[t][c]; - } - - /// Returns the number of bits, referred to as the "range bits", - /// corresponding to the nominal range of the data in the specified - /// component. - /// - ///

    The returned value corresponds to the nominal dynamic range of the - /// reconstructed image data, as long as the getNomRangeBits() method of - /// the source returns a value corresponding to the nominal dynamic range - /// of the image data and not not of the wavelet coefficients.

    - /// - ///

    If this number is b then for unsigned data the nominal range - /// is between 0 and 2^b-1, and for signed data it is between -2^(b-1) and - /// 2^(b-1)-1.

    - /// - ///
    - /// The index of the component. - /// - /// - /// The number of bits corresponding to the nominal range of the - /// data. - /// - /// - public override int getNomRangeBits(int c) - { - return src.getNomRangeBits(c); - } - - /// Returns the position of the fixed point in the specified - /// component. This is the position of the least significant integral - /// (i.e. non-fractional) bit, which is equivalent to the number of - /// fractional bits. For instance, for fixed-point values with 2 fractional - /// bits, 2 is returned. For floating-point data this value does not apply - /// and 0 should be returned. Position 0 is the position of the least - /// significant bit in the data. - /// - ///

    This default implementation assumes that the wavelet transform does - /// not modify the fixed point. If that were the case this method should be - /// overriden.

    - /// - ///
    - /// The index of the component. - /// - /// - /// The position of the fixed-point, which is the same as the - /// number of fractional bits. For floating-point data 0 is returned. - /// - /// - public override int getFixedPoint(int c) - { - return src.getFixedPoint(c); - } - - /// Returns a block of image data containing the specifed rectangular area, - /// in the specified component, as a reference to the internal buffer (see - /// below). The rectangular area is specified by the coordinates and - /// dimensions of the 'blk' object. - /// - ///

    The area to return is specified by the 'ulx', 'uly', 'w' and 'h' - /// members of the 'blk' argument. These members are not modified by this - /// method.

    - /// - ///

    The data returned by this method can be the data in the internal - /// buffer of this object, if any, and thus can not be modified by the - /// caller. The 'offset' and 'scanw' of the returned data can be - /// arbitrary. See the 'DataBlk' class.

    - /// - ///

    The returned data has its 'progressive' attribute unset - /// (i.e. false).

    - /// - ///
    - /// Its coordinates and dimensions specify the area to return. - /// - /// - /// The index of the component from which to get the data. - /// - /// - /// The requested DataBlk - /// - /// - /// - /// - /// - public override DataBlk getInternCompData(DataBlk blk, int c) - { - int tIdx = TileIdx; - if (src.getSynSubbandTree(tIdx, c).HorWFilter == null) - { - dtype = DataBlk.TYPE_INT; - } - else - { - dtype = src.getSynSubbandTree(tIdx, c).HorWFilter.DataType; - } - - //If the source image has not been decomposed - if (reconstructedComps[c] == null) - { - //Allocate component data buffer - switch (dtype) - { - - case DataBlk.TYPE_FLOAT: - reconstructedComps[c] = new DataBlkFloat(0, 0, getTileCompWidth(tIdx, c), getTileCompHeight(tIdx, c)); - break; - - case DataBlk.TYPE_INT: - reconstructedComps[c] = new DataBlkInt(0, 0, getTileCompWidth(tIdx, c), getTileCompHeight(tIdx, c)); - break; - } - //Reconstruct source image - waveletTreeReconstruction(reconstructedComps[c], src.getSynSubbandTree(tIdx, c), c); - if (pw != null && c == src.NumComps - 1) - { - pw.terminateProgressWatch(); - } - } - - if (blk.DataType != dtype) - { - if (dtype == DataBlk.TYPE_INT) - { - blk = new DataBlkInt(blk.ulx, blk.uly, blk.w, blk.h); - } - else - { - blk = new DataBlkFloat(blk.ulx, blk.uly, blk.w, blk.h); - } - } - // Set the reference to the internal buffer - blk.Data = reconstructedComps[c].Data; - blk.offset = reconstructedComps[c].w * blk.uly + blk.ulx; - blk.scanw = reconstructedComps[c].w; - blk.progressive = false; - return blk; - } - - /// Returns a block of image data containing the specifed rectangular area, - /// in the specified component, as a copy (see below). The rectangular area - /// is specified by the coordinates and dimensions of the 'blk' object. - /// - ///

    The area to return is specified by the 'ulx', 'uly', 'w' and 'h' - /// members of the 'blk' argument. These members are not modified by this - /// method.

    - /// - ///

    The data returned by this method is always a copy of the internal - /// data of this object, if any, and it can be modified "in place" without - /// any problems after being returned. The 'offset' of the returned data is - /// 0, and the 'scanw' is the same as the block's width. See the 'DataBlk' - /// class.

    - /// - ///

    If the data array in 'blk' is null, then a new one is - /// created. If the data array is not null then it must be big - /// enough to contain the requested area.

    - /// - ///

    The returned data always has its 'progressive' attribute unset (i.e - /// false)

    - /// - ///
    - /// Its coordinates and dimensions specify the area to - /// return. If it contains a non-null data array, then it must be large - /// enough. If it contains a null data array a new one is created. The - /// fields in this object are modified to return the data. - /// - /// - /// The index of the component from which to get the data. - /// - /// - /// The requested DataBlk - /// - /// - /// - /// - /// - public override DataBlk getCompData(DataBlk blk, int c) - { - //int j; - System.Object dst_data; // src_data removed - int[] dst_data_int; // src_data_int removed - float[] dst_data_float; // src_data_float removed - - // To keep compiler happy - dst_data = null; - - // Ensure output buffer - switch (blk.DataType) - { - - case DataBlk.TYPE_INT: - dst_data_int = (int[])blk.Data; - if (dst_data_int == null || dst_data_int.Length < blk.w * blk.h) - { - dst_data_int = new int[blk.w * blk.h]; - } - dst_data = dst_data_int; - break; - - case DataBlk.TYPE_FLOAT: - dst_data_float = (float[])blk.Data; - if (dst_data_float == null || dst_data_float.Length < blk.w * blk.h) - { - dst_data_float = new float[blk.w * blk.h]; - } - dst_data = dst_data_float; - break; - } - - // Use getInternCompData() to get the data, since getInternCompData() - // returns reference to internal buffer, we must copy it. - blk = getInternCompData(blk, c); - - // Copy the data - blk.Data = dst_data; - blk.offset = 0; - blk.scanw = blk.w; - return blk; - } - - /// Performs the 2D inverse wavelet transform on a subband of the image, on - /// the specified component. This method will successively perform 1D - /// filtering steps on all columns and then all lines of the subband. - /// - /// - /// the buffer for the image/wavelet data. - /// - /// - /// The subband to reconstruct. - /// - /// - /// The index of the component to reconstruct - /// - /// - private void wavelet2DReconstruction(DataBlk db, SubbandSyn sb, int c) - { - System.Object data; - System.Object buf; - int ulx, uly, w, h; - int i, j, k; - int offset; - - // If subband is empty (i.e. zero size) nothing to do - if (sb.w == 0 || sb.h == 0) - { - return; - } - - data = db.Data; - - ulx = sb.ulx; - uly = sb.uly; - w = sb.w; - h = sb.h; - - buf = null; // To keep compiler happy - - switch (sb.HorWFilter.DataType) - { - - case DataBlk.TYPE_INT: - buf = new int[(w >= h) ? w : h]; - break; - - case DataBlk.TYPE_FLOAT: - buf = new float[(w >= h) ? w : h]; - break; - } - - //Perform the horizontal reconstruction - offset = (uly - db.uly) * db.w + ulx - db.ulx; - if (sb.ulcx % 2 == 0) - { - // start index is even => use LPF - for (i = 0; i < h; i++, offset += db.w) - { - // CONVERSION PROBLEM? - Array.Copy((System.Array)data, offset, (System.Array)buf, 0, w); - sb.hFilter.synthetize_lpf(buf, 0, (w + 1) / 2, 1, buf, (w + 1) / 2, w / 2, 1, data, offset, 1); - } - } - else - { - // start index is odd => use HPF - for (i = 0; i < h; i++, offset += db.w) - { - // CONVERSION PROBLEM? - Array.Copy((System.Array)data, offset, (System.Array)buf, 0, w); - sb.hFilter.synthetize_hpf(buf, 0, w / 2, 1, buf, w / 2, (w + 1) / 2, 1, data, offset, 1); - } - } - - //Perform the vertical reconstruction - offset = (uly - db.uly) * db.w + ulx - db.ulx; - switch (sb.VerWFilter.DataType) - { - - case DataBlk.TYPE_INT: - int[] data_int, buf_int; - data_int = (int[])data; - buf_int = (int[])buf; - if (sb.ulcy % 2 == 0) - { - // start index is even => use LPF - for (j = 0; j < w; j++, offset++) - { - for (i = h - 1, k = offset + i * db.w; i >= 0; i--, k -= db.w) - buf_int[i] = data_int[k]; - sb.vFilter.synthetize_lpf(buf, 0, (h + 1) / 2, 1, buf, (h + 1) / 2, h / 2, 1, data, offset, db.w); - } - } - else - { - // start index is odd => use HPF - for (j = 0; j < w; j++, offset++) - { - for (i = h - 1, k = offset + i * db.w; i >= 0; i--, k -= db.w) - buf_int[i] = data_int[k]; - sb.vFilter.synthetize_hpf(buf, 0, h / 2, 1, buf, h / 2, (h + 1) / 2, 1, data, offset, db.w); - } - } - break; - - case DataBlk.TYPE_FLOAT: - float[] data_float, buf_float; - data_float = (float[])data; - buf_float = (float[])buf; - if (sb.ulcy % 2 == 0) - { - // start index is even => use LPF - for (j = 0; j < w; j++, offset++) - { - for (i = h - 1, k = offset + i * db.w; i >= 0; i--, k -= db.w) - buf_float[i] = data_float[k]; - sb.vFilter.synthetize_lpf(buf, 0, (h + 1) / 2, 1, buf, (h + 1) / 2, h / 2, 1, data, offset, db.w); - } - } - else - { - // start index is odd => use HPF - for (j = 0; j < w; j++, offset++) - { - for (i = h - 1, k = offset + i * db.w; i >= 0; i--, k -= db.w) - buf_float[i] = data_float[k]; - sb.vFilter.synthetize_hpf(buf, 0, h / 2, 1, buf, h / 2, (h + 1) / 2, 1, data, offset, db.w); - } - } - break; - } - } - - /// Performs the inverse wavelet transform on the whole component. It - /// iteratively reconstructs the subbands from leaves up to the root - /// node. This method is recursive, the first call to it the 'sb' must be - /// the root of the subband tree. The method will then process the entire - /// subband tree by calling itslef recursively. - /// - /// - /// The buffer for the image/wavelet data. - /// - /// - /// The subband to reconstruct. - /// - /// - /// The index of the component to reconstruct - /// - /// - private void waveletTreeReconstruction(DataBlk img, SubbandSyn sb, int c) - { - - DataBlk subbData; - - // If the current subband is a leaf then get the data from the source - if (!sb.isNode) - { - int i, m, n; - System.Object src_data, dst_data; - Coord ncblks; - - if (sb.w == 0 || sb.h == 0) - { - return; // If empty subband do nothing - } - - // Get all code-blocks in subband - if (dtype == DataBlk.TYPE_INT) - { - subbData = new DataBlkInt(); - } - else - { - subbData = new DataBlkFloat(); - } - ncblks = sb.numCb; - dst_data = img.Data; - for (m = 0; m < ncblks.y; m++) - { - for (n = 0; n < ncblks.x; n++) - { - subbData = src.getInternCodeBlock(c, m, n, sb, subbData); - src_data = subbData.Data; - if (pw != null) - { - nDecCblk++; - pw.updateProgressWatch(nDecCblk, null); - } - // Copy the data line by line - for (i = subbData.h - 1; i >= 0; i--) - { - // CONVERSION PROBLEM - Array.Copy((System.Array)src_data, subbData.offset + i * subbData.scanw, (System.Array)dst_data, (subbData.uly + i) * img.w + subbData.ulx, subbData.w); - } - } - } - } - else if (sb.isNode) - { - // Reconstruct the lower resolution levels if the current subbands - // is a node - - //Perform the reconstruction of the LL subband - waveletTreeReconstruction(img, (SubbandSyn)sb.LL, c); - - if (sb.resLvl <= reslvl - maxImgRes + ndl[c]) - { - //Reconstruct the other subbands - waveletTreeReconstruction(img, (SubbandSyn)sb.HL, c); - waveletTreeReconstruction(img, (SubbandSyn)sb.LH, c); - waveletTreeReconstruction(img, (SubbandSyn)sb.HH, c); - - //Perform the 2D wavelet decomposition of the current subband - wavelet2DReconstruction(img, (SubbandSyn)sb, c); - } - } - } - - /// Returns the implementation type of this wavelet transform, WT_IMPL_FULL - /// (full-page based transform). All components return the same. - /// - /// - /// The index of the component. - /// - /// - /// WT_IMPL_FULL - /// - /// - /// - /// - /// - public override int getImplementationType(int c) - { - return CSJ2K.j2k.wavelet.WaveletTransform_Fields.WT_IMPL_FULL; - } - - /// Changes the current tile, given the new indexes. An - /// IllegalArgumentException is thrown if the indexes do not correspond to - /// a valid tile. - /// - /// - /// The horizontal index of the tile. - /// - /// - /// The vertical index of the new tile. - /// - /// - public override void setTile(int x, int y) - { - int i; - - // Change tile - base.setTile(x, y); - - int nc = src.NumComps; - int tIdx = src.TileIdx; - for (int c = 0; c < nc; c++) - { - ndl[c] = src.getSynSubbandTree(tIdx, c).resLvl; - } - - // Reset the decomposed component buffers. - if (reconstructedComps != null) - { - for (i = reconstructedComps.Length - 1; i >= 0; i--) - { - reconstructedComps[i] = null; - } - } - - cblkToDecode = 0; - SubbandSyn root, sb; - for (int c = 0; c < nc; c++) - { - root = src.getSynSubbandTree(tIdx, c); - for (int r = 0; r <= reslvl - maxImgRes + root.resLvl; r++) - { - if (r == 0) - { - sb = (SubbandSyn)root.getSubbandByIdx(0, 0); - if (sb != null) - cblkToDecode += sb.numCb.x * sb.numCb.y; - } - else - { - sb = (SubbandSyn)root.getSubbandByIdx(r, 1); - if (sb != null) - cblkToDecode += sb.numCb.x * sb.numCb.y; - sb = (SubbandSyn)root.getSubbandByIdx(r, 2); - if (sb != null) - cblkToDecode += sb.numCb.x * sb.numCb.y; - sb = (SubbandSyn)root.getSubbandByIdx(r, 3); - if (sb != null) - cblkToDecode += sb.numCb.x * sb.numCb.y; - } - } // Loop on resolution levels - } // Loop on components - nDecCblk = 0; - - if (pw != null) - { - pw.initProgressWatch(0, cblkToDecode, "Decoding tile " + tIdx + "..."); - } - } - - /// Advances to the next tile, in standard scan-line order (by rows then - /// columns). An 'NoNextElementException' is thrown if the current tile is - /// the last one (i.e. there is no next tile). - /// - /// - public override void nextTile() - { - int i; - - // Change tile - base.nextTile(); - - int nc = src.NumComps; - int tIdx = src.TileIdx; - for (int c = 0; c < nc; c++) - { - ndl[c] = src.getSynSubbandTree(tIdx, c).resLvl; - } - - // Reset the decomposed component buffers. - if (reconstructedComps != null) - { - for (i = reconstructedComps.Length - 1; i >= 0; i--) - { - reconstructedComps[i] = null; - } - } - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/wavelet/synthesis/InverseWT.cs b/CSJ2K/j2k/wavelet/synthesis/InverseWT.cs deleted file mode 100644 index 398e400d..00000000 --- a/CSJ2K/j2k/wavelet/synthesis/InverseWT.cs +++ /dev/null @@ -1,114 +0,0 @@ -/* -* CVS identifier: -* -* $Id: InverseWT.java,v 1.34 2001/10/09 12:52:55 grosbois Exp $ -* -* Class: InverseWT -* -* Description: This interface defines the specifics -* of inverse wavelet transforms. -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.decoder; -using CSJ2K.j2k.image; -namespace CSJ2K.j2k.wavelet.synthesis -{ - - /// This abstract class extends the WaveletTransform one with the specifics of - /// inverse wavelet transforms. - /// - ///

    The image can be reconstructed at different resolution levels. This is - /// controlled by the setResLevel() method. All the image, tile and component - /// dimensions are relative the the resolution level being used. The number of - /// resolution levels indicates the number of wavelet recompositions that will - /// be used, if it is equal as the number of decomposition levels then the full - /// resolution image is reconstructed.

    - /// - ///

    It is assumed in this class that all tiles and components the same - /// reconstruction resolution level. If that where not the case the - /// implementing class should have additional data structures to store those - /// values for each tile. However, the 'recResLvl' member variable always - /// contain the values applicable to the current tile, since many methods - /// implemented here rely on them.

    - /// - ///
    - public abstract class InverseWT : InvWTAdapter, BlkImgDataSrc - { - - /// Initializes this object with the given source of wavelet - /// coefficients. It initializes the resolution level for full resolutioin - /// reconstruction (i.e. the maximum resolution available from the 'src' - /// source). - /// - ///

    It is assumed here that all tiles and components have the same - /// reconstruction resolution level. If that was not the case it should be - /// the value for the current tile of the source.

    - /// - ///
    - /// from where the wavelet coefficinets should be obtained. - /// - /// - /// The decoder specifications - /// - /// - public InverseWT(MultiResImgData src, DecoderSpecs decSpec) : base(src, decSpec) - { - } - - /// Creates an InverseWT object that works on the data type of the source, - /// with the special additional parameters from the parameter - /// list. Currently the parameter list is ignored since no special - /// parameters can be specified for the inverse wavelet transform yet. - /// - /// - /// The source of data for the inverse wavelet - /// transform. - /// - /// - /// The parameter list containing parameters applicable to the - /// inverse wavelet transform (other parameters can also be present). - /// - /// - public static InverseWT createInstance(CBlkWTDataSrcDec src, DecoderSpecs decSpec) - { - - // full page wavelet transform - return new InvWTFull(src, decSpec); - } - public abstract int getFixedPoint(int param1); - public abstract CSJ2K.j2k.image.DataBlk getInternCompData(CSJ2K.j2k.image.DataBlk param1, int param2); - public abstract CSJ2K.j2k.image.DataBlk getCompData(CSJ2K.j2k.image.DataBlk param1, int param2); - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/wavelet/synthesis/MultiResImgData.cs b/CSJ2K/j2k/wavelet/synthesis/MultiResImgData.cs deleted file mode 100644 index 7fac6e4f..00000000 --- a/CSJ2K/j2k/wavelet/synthesis/MultiResImgData.cs +++ /dev/null @@ -1,417 +0,0 @@ -/* -* CVS identifier: -* -* $Id: MultiResImgData.java,v 1.11 2002/07/25 15:11:33 grosbois Exp $ -* -* Class: MultiResImgData -* -* Description: The interface for classes that provide -* multi-resolution image data. -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.image; -namespace CSJ2K.j2k.wavelet.synthesis -{ - - /// This interface defines methods to access image attributes (width, height, - /// number of components, etc.) of multiresolution images, such as those - /// resulting from an inverse wavelet transform. The image can be tiled or not - /// (i.e. if the image is not tiled then there is only 1 tile). It should be - /// implemented by all classes that provide multi-resolution image data, such - /// as entropy decoders, dequantizers, etc. This interface, however, does not - /// define methods to transfer image data (i.e. pixel data), that is defined by - /// other interfaces, such as 'CBlkQuantDataSrcDec'. - /// - ///

    This interface is very similar to the 'ImgData' one. It differs only by - /// the fact that it handles multiple resolutions.

    - /// - ///

    Resolution levels are counted from 0 to L. Resolution level 0 is the - /// lower resolution, while L is the maximum resolution level, or full - /// resolution, which is returned by 'getMaxResLvl()'. Note that there are L+1 - /// resolution levels available.

    - /// - ///

    As in the 'ImgData' interface a multi-resolution image lies on top of a - /// canvas. The canvas coordinates are mapped from the full resolution - /// reference grid (i.e. resolution level 'L' reference grid) to a resolution - /// level 'l' reference grid by '(x_l,y_l) = - /// (ceil(x_l/2^(L-l)),ceil(y_l/2^(L-l)))', where '(x,y)' are the full - /// resolution reference grid coordinates and '(x_l,y_l)' are the level 'l' - /// reference grid coordinates.

    - /// - ///

    For details on the canvas system and its implications consult the - /// 'ImgData' interface.

    - /// - ///

    Note that tile sizes may not be obtained by simply dividing the tile - /// size in the reference grid by the subsampling factor.

    - /// - ///
    - /// - /// - /// - /// - /// - /// - public interface MultiResImgData - { - /// Returns the nominal tiles width - int NomTileWidth - { - get; - - } - /// Returns the nominal tiles height - int NomTileHeight - { - get; - - } - /// Returns the number of components in the image. - /// - /// - /// The number of components in the image. - /// - /// - int NumComps - { - get; - - } - /// Returns the index of the current tile, relative to a standard scan-line - /// order. - /// - /// - /// The current tile's index (starts at 0). - /// - /// - int TileIdx - { - get; - - } - /// Returns the horizontal tile partition offset in the reference grid - int TilePartULX - { - get; - - } - /// Returns the vertical tile partition offset in the reference grid - int TilePartULY - { - get; - - } - - /// Returns the overall width of the current tile in pixels for the given - /// resolution level. This is the tile's width without accounting for any - /// component subsampling. The resolution level is indexed from the lowest - /// number of resolution levels of all components of the current tile. - /// - /// - /// The resolution level, from 0 to L. - /// - /// - /// The total current tile's width in pixels. - /// - /// - int getTileWidth(int rl); - - /// Returns the overall height of the current tile in pixels, for the given - /// resolution level. This is the tile's height without accounting for any - /// component subsampling. The resolution level is indexed from the lowest - /// number of resolution levels of all components of the current tile. - /// - /// - /// The resolution level, from 0 to L. - /// - /// - /// The total current tile's height in pixels. - /// - /// - int getTileHeight(int rl); - - /// Returns the overall width of the image in pixels, for the given - /// resolution level. This is the image's width without accounting for any - /// component subsampling or tiling. The resolution level is indexed from - /// the lowest number of resolution levels of all components of the current - /// tile. - /// - /// - /// The resolution level, from 0 to L. - /// - /// - /// The total image's width in pixels. - /// - /// - int getImgWidth(int rl); - - /// Returns the overall height of the image in pixels, for the given - /// resolution level. This is the image's height without accounting for any - /// component subsampling or tiling. The resolution level is indexed from - /// the lowest number of resolution levels of all components of the current - /// tile. - /// - /// - /// The resolution level, from 0 to L. - /// - /// - /// The total image's height in pixels. - /// - /// - int getImgHeight(int rl); - - /// Returns the component subsampling factor in the horizontal direction, - /// for the specified component. This is, approximately, the ratio of - /// dimensions between the reference grid and the component itself, see the - /// 'ImgData' interface desription for details. - /// - /// - /// The index of the component (between 0 and N-1) - /// - /// - /// The horizontal subsampling factor of component 'c' - /// - /// - /// - /// - /// - int getCompSubsX(int c); - - /// Returns the component subsampling factor in the vertical direction, for - /// the specified component. This is, approximately, the ratio of - /// dimensions between the reference grid and the component itself, see the - /// 'ImgData' interface desription for details. - /// - /// - /// The index of the component (between 0 and N-1) - /// - /// - /// The vertical subsampling factor of component 'c' - /// - /// - /// - /// - /// - int getCompSubsY(int c); - - /// Returns the width in pixels of the specified tile-component for the - /// given resolution level. - /// - /// - /// Tile index - /// - /// - /// The index of the component, from 0 to N-1. - /// - /// - /// The resolution level, from 0 to L. - /// - /// - /// The width in pixels of component c in tile t - /// for resolution rl. - /// - /// - int getTileCompWidth(int t, int c, int rl); - - /// Returns the height in pixels of the specified tile-component for the - /// given resolution level. - /// - /// - /// The tile index. - /// - /// - /// The index of the component, from 0 to N-1. - /// - /// - /// The resolution level, from 0 to L. - /// - /// - /// The height in pixels of component c in tile - /// t. - /// - /// - int getTileCompHeight(int t, int c, int rl); - - /// Returns the width in pixels of the specified component in the overall - /// image, for the given resolution level. - /// - /// - /// The index of the component, from 0 to N-1. - /// - /// - /// The resolution level, from 0 to L. - /// - /// - /// The width in pixels of component c in the overall - /// image. - /// - /// - int getCompImgWidth(int c, int rl); - - /// Returns the height in pixels of the specified component in the overall - /// image, for the given resolution level. - /// - /// - /// The index of the component, from 0 to N-1. - /// - /// - /// The resolution level, from 0 to L. - /// - /// - /// The height in pixels of component n in the overall - /// image. - /// - /// - int getCompImgHeight(int n, int rl); - - /// Changes the current tile, given the new indexes. An - /// IllegalArgumentException is thrown if the indexes do not correspond to - /// a valid tile. - /// - /// - /// The horizontal indexes the tile. - /// - /// - /// The vertical indexes of the new tile. - /// - /// - void setTile(int x, int y); - - /// Advances to the next tile, in standard scan-line order (by rows then - /// columns). An NoNextElementException is thrown if the current tile is - /// the last one (i.e. there is no next tile). - /// - /// - void nextTile(); - - /// Returns the indexes of the current tile. These are the horizontal and - /// vertical indexes of the current tile. - /// - /// - /// If not null this object is used to return the information. If - /// null a new one is created and returned. - /// - /// - /// The current tile's indexes (vertical and horizontal indexes). - /// - /// - Coord getTile(Coord co); - - /// Returns the horizontal coordinate of the upper-left corner of the - /// specified resolution in the given component of the current tile. - /// - /// - /// The component index. - /// - /// - /// The resolution level index. - /// - /// - int getResULX(int c, int rl); - - /// Returns the vertical coordinate of the upper-left corner of the - /// specified resolution in the given component of the current tile. - /// - /// - /// The component index. - /// - /// - /// The resolution level index. - /// - /// - int getResULY(int c, int rl); - - /// Returns the horizontal coordinate of the image origin, the top-left - /// corner, in the canvas system, on the reference grid at the specified - /// resolution level. The resolution level is indexed from the lowest - /// number of resolution levels of all components of the current tile. - /// - /// - /// The resolution level, from 0 to L. - /// - /// - /// The horizontal coordinate of the image origin in the canvas - /// system, on the reference grid. - /// - /// - int getImgULX(int rl); - - /// Returns the vertical coordinate of the image origin, the top-left - /// corner, in the canvas system, on the reference grid at the specified - /// resolution level. The resolution level is indexed from the lowest - /// number of resolution levels of all components of the current tile. - /// - /// - /// The resolution level, from 0 to L. - /// - /// - /// The vertical coordinate of the image origin in the canvas - /// system, on the reference grid. - /// - /// - int getImgULY(int rl); - - /// Returns the number of tiles in the horizontal and vertical directions. - /// - /// - /// If not null this object is used to return the information. If - /// null a new one is created and returned. - /// - /// - /// The number of tiles in the horizontal (Coord.x) and vertical - /// (Coord.y) directions. - /// - /// - Coord getNumTiles(Coord co); - - /// Returns the total number of tiles in the image. - /// - /// - /// The total number of tiles in the image. - /// - /// - int getNumTiles(); - - /// Returns the specified synthesis subband tree - /// - /// - /// Tile index. - /// - /// - /// Component index. - /// - /// - SubbandSyn getSynSubbandTree(int t, int c); - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/wavelet/synthesis/MultiResImgDataAdapter.cs b/CSJ2K/j2k/wavelet/synthesis/MultiResImgDataAdapter.cs deleted file mode 100644 index 42a43dd9..00000000 --- a/CSJ2K/j2k/wavelet/synthesis/MultiResImgDataAdapter.cs +++ /dev/null @@ -1,517 +0,0 @@ -/* -* CVS identifier: -* -* $Id: MultiResImgDataAdapter.java,v 1.10 2002/07/25 15:11:55 grosbois Exp $ -* -* Class: MultiResImgDataAdapter -* -* Description: A default implementation of the MultiResImgData -* interface that has and MultiResImgData source -* and just returns the values of the source. -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -using CSJ2K.j2k.image; -namespace CSJ2K.j2k.wavelet.synthesis -{ - - /// This class provides a default implementation for the methods of the - /// 'MultiResImgData' interface. The default implementation consists just in - /// returning the value of the source, where the source is another - /// 'MultiResImgData' object. - /// - ///

    This abstract class can be used to facilitate the development of other - /// classes that implement 'MultiResImgData'. For example a dequantizer can - /// inherit from this class and all the trivial methods do not have to be - /// reimplemented.

    - /// - ///

    If the default implementation of a method provided in this class does - /// not suit a particular implementation of the 'MultiResImgData' interface, - /// the method can be overriden to implement the proper behaviour.

    - /// - ///
    - /// - /// - /// - public abstract class MultiResImgDataAdapter : MultiResImgData - { - /// Returns the nominal tiles width - virtual public int NomTileWidth - { - get - { - return mressrc.NomTileWidth; - } - - } - /// Returns the nominal tiles height - virtual public int NomTileHeight - { - get - { - return mressrc.NomTileHeight; - } - - } - /// Returns the number of components in the image. - /// - ///

    This default implementation returns the value of the source.

    - /// - ///
    - /// The number of components in the image. - /// - /// - virtual public int NumComps - { - get - { - return mressrc.NumComps; - } - - } - /// Returns the index of the current tile, relative to a standard scan-line - /// order. - /// - ///

    This default implementation returns the value of the source.

    - /// - ///
    - /// The current tile's index (starts at 0). - /// - /// - virtual public int TileIdx - { - get - { - return mressrc.TileIdx; - } - - } - /// Returns the horizontal tile partition offset in the reference grid - virtual public int TilePartULX - { - get - { - return mressrc.TilePartULX; - } - - } - /// Returns the vertical tile partition offset in the reference grid - virtual public int TilePartULY - { - get - { - return mressrc.TilePartULY; - } - - } - - /// Index of the current tile - protected internal int tIdx = 0; - - /// The MultiResImgData source - protected internal MultiResImgData mressrc; - - /// Instantiates the MultiResImgDataAdapter object specifying the - /// MultiResImgData source. - /// - /// - /// From where to obrtain the MultiResImgData values. - /// - /// - protected internal MultiResImgDataAdapter(MultiResImgData src) - { - mressrc = src; - } - - /// Returns the overall width of the current tile in pixels, for the given - /// resolution level. This is the tile's width without accounting for any - /// component subsampling. - /// - ///

    This default implementation returns the value of the source.

    - /// - ///
    - /// The resolution level, from 0 to L. - /// - /// - /// The total current tile's width in pixels. - /// - /// - public virtual int getTileWidth(int rl) - { - return mressrc.getTileWidth(rl); - } - - /// Returns the overall height of the current tile in pixels, for the given - /// resolution level. This is the tile's height without accounting for any - /// component subsampling. - /// - ///

    This default implementation returns the value of the source.

    - /// - ///
    - /// The resolution level, from 0 to L. - /// - /// - /// The total current tile's height in pixels. - /// - /// - public virtual int getTileHeight(int rl) - { - return mressrc.getTileHeight(rl); - } - - /// Returns the overall width of the image in pixels, for the given - /// resolution level. This is the image's width without accounting for any - /// component subsampling or tiling. - /// - ///

    This default implementation returns the value of the source.

    - /// - ///
    - /// The resolution level, from 0 to L. - /// - /// - /// The total image's width in pixels. - /// - /// - public virtual int getImgWidth(int rl) - { - return mressrc.getImgWidth(rl); - } - - /// Returns the overall height of the image in pixels, for the given - /// resolution level. This is the image's height without accounting for any - /// component subsampling or tiling. - /// - ///

    This default implementation returns the value of the source.

    - /// - ///
    - /// The resolution level, from 0 to L. - /// - /// - /// The total image's height in pixels. - /// - /// - public virtual int getImgHeight(int rl) - { - return mressrc.getImgHeight(rl); - } - - /// Returns the component subsampling factor in the horizontal direction, - /// for the specified component. This is, approximately, the ratio of - /// dimensions between the reference grid and the component itself, see the - /// 'ImgData' interface desription for details. - /// - ///

    This default implementation returns the value of the source.

    - /// - ///
    - /// The index of the component (between 0 and N-1) - /// - /// - /// The horizontal subsampling factor of component 'c' - /// - /// - /// - /// - /// - public virtual int getCompSubsX(int c) - { - return mressrc.getCompSubsX(c); - } - - /// Returns the component subsampling factor in the vertical direction, for - /// the specified component. This is, approximately, the ratio of - /// dimensions between the reference grid and the component itself, see the - /// 'ImgData' interface desription for details. - /// - ///

    This default implementation returns the value of the source.

    - /// - ///
    - /// The index of the component (between 0 and N-1) - /// - /// - /// The vertical subsampling factor of component 'c' - /// - /// - /// - /// - /// - public virtual int getCompSubsY(int c) - { - return mressrc.getCompSubsY(c); - } - - /// Returns the width in pixels of the specified tile-component for the - /// given resolution level. - /// - ///

    This default implementation returns the value of the source.

    - /// - ///
    - /// Tile index. - /// - /// - /// The index of the component, from 0 to N-1. - /// - /// - /// The resolution level, from 0 to L. - /// - /// - /// The width in pixels of component c in tile t - /// for resolution level rl. - /// - /// - public virtual int getTileCompWidth(int t, int c, int rl) - { - return mressrc.getTileCompWidth(t, c, rl); - } - - /// Returns the height in pixels of the specified tile-component for the - /// given resolution level. - /// - ///

    This default implementation returns the value of the source.

    - /// - ///
    - /// The tile index. - /// - /// - /// The index of the component, from 0 to N-1. - /// - /// - /// The resolution level, from 0 to L. - /// - /// - /// The height in pixels of component c in tile - /// t. - /// - /// - public virtual int getTileCompHeight(int t, int c, int rl) - { - return mressrc.getTileCompHeight(t, c, rl); - } - - /// Returns the width in pixels of the specified component in the overall - /// image, for the given resolution level. - /// - ///

    This default implementation returns the value of the source.

    - /// - ///
    - /// The index of the component, from 0 to N-1. - /// - /// - /// The resolution level, from 0 to L. - /// - /// - /// The width in pixels of component c in the overall - /// image. - /// - /// - public virtual int getCompImgWidth(int c, int rl) - { - return mressrc.getCompImgWidth(c, rl); - } - - /// Returns the height in pixels of the specified component in the overall - /// image, for the given resolution level. - /// - ///

    This default implementation returns the value of the source. - /// - ///

    - /// The index of the component, from 0 to N-1. - /// - /// - /// The resolution level, from 0 to L. - /// - /// - /// The height in pixels of component c in the overall - /// image. - /// - /// - public virtual int getCompImgHeight(int c, int rl) - { - return mressrc.getCompImgHeight(c, rl); - } - - /// Changes the current tile, given the new indexes. An - /// IllegalArgumentException is thrown if the indexes do not correspond to - /// a valid tile. - /// - ///

    This default implementation just changes the tile in the source.

    - /// - ///
    - /// The horizontal indexes the tile. - /// - /// - /// The vertical indexes of the new tile. - /// - /// - public virtual void setTile(int x, int y) - { - mressrc.setTile(x, y); - tIdx = TileIdx; - } - - /// Advances to the next tile, in standard scan-line order (by rows then - /// columns). An NoNextElementException is thrown if the current tile is - /// the last one (i.e. there is no next tile). - /// - ///

    This default implementation just changes the tile in the source.

    - /// - ///
    - public virtual void nextTile() - { - mressrc.nextTile(); - tIdx = TileIdx; - } - - /// Returns the indexes of the current tile. These are the horizontal and - /// vertical indexes of the current tile. - /// - ///

    This default implementation returns the value of the source.

    - /// - ///
    - /// If not null this object is used to return the information. If - /// null a new one is created and returned. - /// - /// - /// The current tile's indexes (vertical and horizontal indexes). - /// - /// - public virtual Coord getTile(Coord co) - { - return mressrc.getTile(co); - } - - /// Returns the horizontal coordinate of the upper-left corner of the - /// specified resolution level in the given component of the current tile. - /// - ///

    This default implementation returns the value of the source.

    - /// - ///
    - /// The component index. - /// - /// - /// The resolution level index. - /// - /// - public virtual int getResULX(int c, int rl) - { - return mressrc.getResULX(c, rl); - } - - /// Returns the vertical coordinate of the upper-left corner of the - /// specified resolution in the given component of the current tile. - /// - ///

    This default implementation returns the value of the source.

    - /// - ///
    - /// The component index. - /// - /// - /// The resolution level index. - /// - /// - public virtual int getResULY(int c, int rl) - { - return mressrc.getResULY(c, rl); - } - - /// Returns the horizontal coordinate of the image origin, the top-left - /// corner, in the canvas system, on the reference grid at the specified - /// resolution level. - /// - ///

    This default implementation returns the value of the source.

    - /// - ///
    - /// The resolution level, from 0 to L. - /// - /// - /// The horizontal coordinate of the image origin in the canvas - /// system, on the reference grid. - /// - /// - public virtual int getImgULX(int rl) - { - return mressrc.getImgULX(rl); - } - - /// Returns the vertical coordinate of the image origin, the top-left - /// corner, in the canvas system, on the reference grid at the specified - /// resolution level. - /// - ///

    This default implementation returns the value of the source.

    - /// - ///
    - /// The resolution level, from 0 to L. - /// - /// - /// The vertical coordinate of the image origin in the canvas - /// system, on the reference grid. - /// - /// - public virtual int getImgULY(int rl) - { - return mressrc.getImgULY(rl); - } - - /// Returns the number of tiles in the horizontal and vertical directions. - /// - ///

    This default implementation returns the value of the source.

    - /// - ///
    - /// If not null this object is used to return the information. If - /// null a new one is created and returned. - /// - /// - /// The number of tiles in the horizontal (Coord.x) and vertical - /// (Coord.y) directions. - /// - /// - public virtual Coord getNumTiles(Coord co) - { - return mressrc.getNumTiles(co); - } - - /// Returns the total number of tiles in the image. - /// - ///

    This default implementation returns the value of the source.

    - /// - ///
    - /// The total number of tiles in the image. - /// - /// - public virtual int getNumTiles() - { - return mressrc.getNumTiles(); - } - public abstract CSJ2K.j2k.wavelet.synthesis.SubbandSyn getSynSubbandTree(int param1, int param2); - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/wavelet/synthesis/SubbandSyn.cs b/CSJ2K/j2k/wavelet/synthesis/SubbandSyn.cs deleted file mode 100644 index 20e7d64f..00000000 --- a/CSJ2K/j2k/wavelet/synthesis/SubbandSyn.cs +++ /dev/null @@ -1,310 +0,0 @@ -/* -* CVS identifier: -* -* $Id: SubbandSyn.java,v 1.25 2001/07/26 08:54:59 grosbois Exp $ -* -* Class: SubbandSyn -* -* Description: Element for a tree structure for a description -* of subband for the synthesis side. -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -namespace CSJ2K.j2k.wavelet.synthesis -{ - - /// This class represents a subband in a tree structure that describes the - /// subband decomposition for a wavelet transform, specifically for the - /// syhthesis side. - /// - ///

    The element can be either a node or a leaf of the tree. If it is a node - /// then ther are 4 descendants (LL, HL, LH and HH). If it is a leaf there are - /// no descendants.

    - /// - ///

    The tree is bidirectional. Each element in the tree structure has a - /// "parent", which is the subband from which the element was obtained by - /// decomposition. The only exception is the root element which has no parent - /// (i.e.it's null), for obvious reasons.

    - /// - ///
    - public class SubbandSyn : Subband - { - /// Returns the parent of this subband. The parent of a subband is the - /// subband from which this one was obtained by decomposition. The root - /// element has no parent subband (null). - /// - /// - /// The parent subband, or null for the root one. - /// - /// - override public Subband Parent - { - get - { - return parent; - } - - } - /// Returns the LL child subband of this subband. - /// - /// - /// The LL child subband, or null if there are no childs. - /// - /// - override public Subband LL - { - get - { - return subb_LL; - } - - } - /// Returns the HL (horizontal high-pass) child subband of this subband. - /// - /// - /// The HL child subband, or null if there are no childs. - /// - /// - override public Subband HL - { - get - { - return subb_HL; - } - - } - /// Returns the LH (vertical high-pass) child subband of this subband. - /// - /// - /// The LH child subband, or null if there are no childs. - /// - /// - override public Subband LH - { - get - { - return subb_LH; - } - - } - /// Returns the HH child subband of this subband. - /// - /// - /// The HH child subband, or null if there are no childs. - /// - /// - override public Subband HH - { - get - { - return subb_HH; - } - - } - /// This function returns the horizontal wavelet filter relevant to this - /// subband - /// - /// - /// The horizontal wavelet filter - /// - /// - override public WaveletFilter HorWFilter - { - get - { - return hFilter; - } - - } - /// This function returns the vertical wavelet filter relevant to this - /// subband - /// - /// - /// The vertical wavelet filter - /// - /// - override public WaveletFilter VerWFilter - { - get - { - return hFilter; - } - - } - - /// The reference to the parent of this subband. It is null for the root - /// element. It is null by default. - /// - private SubbandSyn parent; - - /// The reference to the LL subband resulting from the decomposition of - /// this subband. It is null by default. - /// - private SubbandSyn subb_LL; - - /// The reference to the HL subband (horizontal high-pass) resulting from - /// the decomposition of this subband. It is null by default. - /// - private SubbandSyn subb_HL; - - /// The reference to the LH subband (vertical high-pass) resulting from - /// the decomposition of this subband. It is null by default. - /// - /// - private SubbandSyn subb_LH; - - /// The reference to the HH subband resulting from the decomposition of - /// this subband. It is null by default. - /// - private SubbandSyn subb_HH; - - /// The horizontal analysis filter used to recompose this subband, from - /// its childs. This is applicable to "node" elements only. The default - /// value is null. - /// - public SynWTFilter hFilter; - - /// The vertical analysis filter used to decompose this subband, from its - /// childs. This is applicable to "node" elements only. The default value - /// is null. - /// - public SynWTFilter vFilter; - - /// The number of magnitude bits - public int magbits = 0; - - /// Creates a SubbandSyn element with all the default values. The - /// dimensions are (0,0) and the upper left corner is (0,0). - /// - /// - public SubbandSyn() - { - } - - /// Creates the top-level node and the entire subband tree, with the - /// top-level dimensions, the number of decompositions, and the - /// decomposition tree as specified. - /// - ///

    This constructor just calls the same constructor of the super - /// class.

    - /// - ///
    - /// The top-level width - /// - /// - /// The top-level height - /// - /// - /// The horizontal coordinate of the upper-left corner with - /// respect to the canvas origin, in the component grid. - /// - /// - /// The vertical coordinate of the upper-left corner with - /// respect to the canvas origin, in the component grid. - /// - /// - /// The number of levels (or LL decompositions) in the tree. - /// - /// - /// The horizontal wavelet synthesis filters for each - /// resolution level, starting at resolution level 0. - /// - /// - /// The vertical wavelet synthesis filters for each - /// resolution level, starting at resolution level 0. - /// - /// - /// - /// WaveletFilter[],WaveletFilter[]) - /// - /// - public SubbandSyn(int w, int h, int ulcx, int ulcy, int lvls, WaveletFilter[] hfilters, WaveletFilter[] vfilters) : base(w, h, ulcx, ulcy, lvls, hfilters, vfilters) - { - } - - /// Splits the current subband in its four subbands. It changes the status - /// of this element (from a leaf to a node, and sets the filters), creates - /// the childs and initializes them. An IllegalArgumentException is thrown - /// if this subband is not a leaf. - /// - ///

    It uses the initChilds() method to initialize the childs.

    - /// - ///
    - /// The horizontal wavelet filter used to decompose this - /// subband. It has to be a SynWTFilter object. - /// - /// - /// The vertical wavelet filter used to decompose this - /// subband. It has to be a SynWTFilter object. - /// - /// - /// A reference to the LL leaf (subb_LL). - /// - /// - /// - /// - /// - protected internal override Subband split(WaveletFilter hfilter, WaveletFilter vfilter) - { - // Test that this is a node - if (isNode) - { - throw new System.ArgumentException(); - } - - // Modify this element into a node and set the filters - isNode = true; - this.hFilter = (SynWTFilter)hfilter; - this.vFilter = (SynWTFilter)vfilter; - - // Create childs - subb_LL = new SubbandSyn(); - subb_LH = new SubbandSyn(); - subb_HL = new SubbandSyn(); - subb_HH = new SubbandSyn(); - - // Assign parent - subb_LL.parent = this; - subb_HL.parent = this; - subb_LH.parent = this; - subb_HH.parent = this; - - // Initialize childs - initChilds(); - - // Return reference to LL subband - return subb_LL; - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/wavelet/synthesis/SynWTFilter.cs b/CSJ2K/j2k/wavelet/synthesis/SynWTFilter.cs deleted file mode 100644 index 262b2187..00000000 --- a/CSJ2K/j2k/wavelet/synthesis/SynWTFilter.cs +++ /dev/null @@ -1,262 +0,0 @@ -/* -* CVS identifier: -* -* $Id: SynWTFilter.java,v 1.9 2001/08/02 10:05:58 grosbois Exp $ -* -* Class: SynWTFilter -* -* Description: The abstract class for all synthesis wavelet -* filters. -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -namespace CSJ2K.j2k.wavelet.synthesis -{ - - /// This abstract class defines the methods of all synthesis wavelet - /// filters. Specialized abstract classes that work on particular data types - /// (int, float) provide more specific method calls while retaining the - /// generality of this one. See the SynWTFilterInt and SynWTFilterFloat - /// classes. Implementations of snythesis filters should inherit from one of - /// those classes. - /// - ///

    The length of the output signal is always the sum of the length of the - /// low-pass and high-pass input signals.

    - /// - ///

    All synthesis wavelet filters should follow the following conventions: - /// - ///

      - /// - ///
    • The first sample of the output corresponds to the low-pass one. As a - /// consequence, if the output signal is of odd-length then the low-pass input - /// signal is one sample longer than the high-pass input one. Therefore, if the - /// length of output signal is N, the low-pass input signal is of length N/2 if - /// N is even and N/2+1/2 if N is odd, while the high-pass input signal is of - /// length N/2 if N is even and N/2-1/2 if N is odd.
    • - /// - ///
    • The normalization of the analysis filters is 1 for the DC gain and 2 - /// for the Nyquist gain (Type I normalization), for both reversible and - /// non-reversible filters. The normalization of the synthesis filters should - /// ensure prefect reconstruction according to this normalization of the - /// analysis wavelet filters.
    • - /// - ///
    - /// - ///

    The synthetize method may seem very complicated, but is designed to - /// minimize the amount of data copying and redundant calculations when used - /// for block-based or line-based wavelet transform implementations, while - /// being applicable to full-frame transforms as well.

    - /// - ///
    - /// - /// - /// - /// - /// - public abstract class SynWTFilter : WaveletFilter - { - public abstract int AnHighPosSupport { get; } - public abstract int AnLowNegSupport { get; } - public abstract int AnLowPosSupport { get; } - public abstract bool Reversible { get; } - public abstract int ImplType { get; } - public abstract int SynHighNegSupport { get; } - public abstract int SynHighPosSupport { get; } - public abstract int AnHighNegSupport { get; } - public abstract int DataType { get; } - public abstract int SynLowNegSupport { get; } - public abstract int SynLowPosSupport { get; } - - /// Reconstructs the output signal by the synthesis filter, recomposing the - /// low-pass and high-pass input signals in one output signal. This method - /// performs the upsampling and fitering with the low pass first filtering - /// convention. - /// - ///

    The input low-pass (high-pass) signal resides in the lowSig - /// array. The index of the first sample to filter (i.e. that will generate - /// the first (second) output sample). is given by lowOff (highOff). This - /// array must be of the same type as the one for which the particular - /// implementation works with (which is returned by the getDataType() - /// method).

    - /// - ///

    The low-pass (high-pass) input signal can be interleaved with other - /// signals in the same lowSig (highSig) array, and this is determined by - /// the lowStep (highStep) argument. This means that the first sample of - /// the low-pass (high-pass) input signal is lowSig[lowOff] - /// (highSig[highOff]), the second is lowSig[lowOff+lowStep] - /// (highSig[highOff+highStep]), the third is lowSig[lowOff+2*lowStep] - /// (highSig[highOff+2*highStep]), and so on. Therefore if lowStep - /// (highStep) is 1 there is no interleaving. This feature allows to filter - /// columns of a 2-D signal, when it is stored in a line by line order in - /// lowSig (highSig), without having to copy the data, in this case the - /// lowStep (highStep) argument should be the line width of the low-pass - /// (high-pass) signal.

    - /// - ///

    The output signal is placed in the outSig array. The outOff and - /// outStep arguments are analogous to the lowOff and lowStep ones, but - /// they apply to the outSig array. The outSig array must be long enough to - /// hold the low-pass output signal.

    - /// - ///
    - /// This is the array that contains the low-pass input - /// signal. It must be of the correct type (e.g., it must be int[] if - /// getDataType() returns TYPE_INT). - /// - /// - /// This is the index in lowSig of the first sample to - /// filter. - /// - /// - /// This is the number of samples in the low-pass input - /// signal to filter. - /// - /// - /// This is the step, or interleave factor, of the low-pass - /// input signal samples in the lowSig array. See above. - /// - /// - /// This is the array that contains the high-pass input - /// signal. It must be of the correct type (e.g., it must be int[] if - /// getDataType() returns TYPE_INT). - /// - /// - /// This is the index in highSig of the first sample to - /// filter. - /// - /// - /// This is the number of samples in the high-pass input - /// signal to filter. - /// - /// - /// This is the step, or interleave factor, of the - /// high-pass input signal samples in the highSig array. See above. - /// - /// - /// This is the array where the output signal is placed. It - /// must be of the same type as lowSig and it should be long enough to - /// contain the output signal. - /// - /// - /// This is the index in outSig of the element where to put - /// the first output sample. - /// - /// - /// This is the step, or interleave factor, of the output - /// samples in the outSig array. See above. - /// - /// - public abstract void synthetize_lpf(System.Object lowSig, int lowOff, int lowLen, int lowStep, System.Object highSig, int highOff, int highLen, int highStep, System.Object outSig, int outOff, int outStep); - - /// Reconstructs the output signal by the synthesis filter, recomposing the - /// low-pass and high-pass input signals in one output signal. This method - /// performs the upsampling and fitering with the high pass first filtering - /// convention. - /// - ///

    The input low-pass (high-pass) signal resides in the lowSig - /// array. The index of the first sample to filter (i.e. that will generate - /// the first (second) output sample). is given by lowOff (highOff). This - /// array must be of the same type as the one for which the particular - /// implementation works with (which is returned by the getDataType() - /// method).

    - /// - ///

    The low-pass (high-pass) input signal can be interleaved with other - /// signals in the same lowSig (highSig) array, and this is determined by - /// the lowStep (highStep) argument. This means that the first sample of - /// the low-pass (high-pass) input signal is lowSig[lowOff] - /// (highSig[highOff]), the second is lowSig[lowOff+lowStep] - /// (highSig[highOff+highStep]), the third is lowSig[lowOff+2*lowStep] - /// (highSig[highOff+2*highStep]), and so on. Therefore if lowStep - /// (highStep) is 1 there is no interleaving. This feature allows to filter - /// columns of a 2-D signal, when it is stored in a line by line order in - /// lowSig (highSig), without having to copy the data, in this case the - /// lowStep (highStep) argument should be the line width of the low-pass - /// (high-pass) signal.

    - /// - ///

    The output signal is placed in the outSig array. The outOff and - /// outStep arguments are analogous to the lowOff and lowStep ones, but - /// they apply to the outSig array. The outSig array must be long enough to - /// hold the low-pass output signal.

    - /// - ///
    - /// This is the array that contains the low-pass input - /// signal. It must be of the correct type (e.g., it must be int[] if - /// getDataType() returns TYPE_INT). - /// - /// - /// This is the index in lowSig of the first sample to - /// filter. - /// - /// - /// This is the number of samples in the low-pass input - /// signal to filter. - /// - /// - /// This is the step, or interleave factor, of the low-pass - /// input signal samples in the lowSig array. See above. - /// - /// - /// This is the array that contains the high-pass input - /// signal. It must be of the correct type (e.g., it must be int[] if - /// getDataType() returns TYPE_INT). - /// - /// - /// This is the index in highSig of the first sample to - /// filter. - /// - /// - /// This is the number of samples in the high-pass input - /// signal to filter. - /// - /// - /// This is the step, or interleave factor, of the - /// high-pass input signal samples in the highSig array. See above. - /// - /// - /// This is the array where the output signal is placed. It - /// must be of the same type as lowSig and it should be long enough to - /// contain the output signal. - /// - /// - /// This is the index in outSig of the element where to put - /// the first output sample. - /// - /// - /// This is the step, or interleave factor, of the output - /// samples in the outSig array. See above. - /// - /// - public abstract void synthetize_hpf(System.Object lowSig, int lowOff, int lowLen, int lowStep, System.Object highSig, int highOff, int highLen, int highStep, System.Object outSig, int outOff, int outStep); - public abstract bool isSameAsFullWT(int param1, int param2, int param3); - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/wavelet/synthesis/SynWTFilterFloat.cs b/CSJ2K/j2k/wavelet/synthesis/SynWTFilterFloat.cs deleted file mode 100644 index cedcf4fd..00000000 --- a/CSJ2K/j2k/wavelet/synthesis/SynWTFilterFloat.cs +++ /dev/null @@ -1,332 +0,0 @@ -/* -* CVS identifier: -* -* $Id: SynWTFilterFloat.java,v 1.7 2000/09/05 09:26:32 grosbois Exp $ -* -* Class: SynWTFilterFloat -* -* Description: A specialized synthesis wavelet filter interface -* that works on float data. -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* -* -* -*/ -using CSJ2K.j2k.image; -namespace CSJ2K.j2k.wavelet.synthesis -{ - - /// This extends the synthesis wavelet filter general definitions of - /// SynWTFilter by adding methods that work for float data - /// specifically. Implementations that work on float data should inherit - /// from this class. - /// - ///

    See the SynWTFilter class for details such as - /// normalization, how to split odd-length signals, etc. - /// - ///

    The advantage of using the specialized method is that no casts - /// are performed. - /// - ///

    - /// - /// - /// - public abstract class SynWTFilterFloat : SynWTFilter - { - /// Returns the type of data on which this filter works, as defined - /// in the DataBlk interface, which is always TYPE_FLOAT for this - /// class. - /// - /// - /// The type of data as defined in the DataBlk interface. - /// - /// - /// - /// - /// - /// - /// - override public int DataType - { - get - { - return DataBlk.TYPE_FLOAT; - } - - } - - /// A specific version of the synthetize_lpf() method that works on float - /// data. See the general description of the synthetize_lpf() method in the - /// SynWTFilter class for more details. - /// - /// - /// This is the array that contains the low-pass - /// input signal. - /// - /// - /// This is the index in lowSig of the first sample to - /// filter. - /// - /// - /// This is the number of samples in the low-pass - /// input signal to filter. - /// - /// - /// This is the step, or interleave factor, of the - /// low-pass input signal samples in the lowSig array. - /// - /// - /// This is the array that contains the high-pass - /// input signal. - /// - /// - /// This is the index in highSig of the first sample to - /// filter. - /// - /// - /// This is the number of samples in the high-pass - /// input signal to filter. - /// - /// - /// This is the step, or interleave factor, of the - /// high-pass input signal samples in the highSig array. - /// - /// - /// This is the array where the output signal is - /// placed. It should be long enough to contain the output signal. - /// - /// - /// This is the index in outSig of the element where - /// to put the first output sample. - /// - /// - /// This is the step, or interleave factor, of the - /// output samples in the outSig array. - /// - /// - /// - /// - /// - /// - /// - /// - /// - public abstract void synthetize_lpf(float[] lowSig, int lowOff, int lowLen, int lowStep, float[] highSig, int highOff, int highLen, int highStep, float[] outSig, int outOff, int outStep); - - /// The general version of the synthetize_lpf() method, it just calls - /// the specialized version. See the description of the synthetize_lpf() - /// method of the SynWTFilter class for more details. - /// - /// - /// This is the array that contains the low-pass - /// input signal. It must be an float[]. - /// - /// - /// This is the index in lowSig of the first sample to - /// filter. - /// - /// - /// This is the number of samples in the low-pass - /// input signal to filter. - /// - /// - /// This is the step, or interleave factor, of the - /// low-pass input signal samples in the lowSig array. - /// - /// - /// This is the array that contains the high-pass - /// input signal. It must be an float[]. - /// - /// - /// This is the index in highSig of the first sample to - /// filter. - /// - /// - /// This is the number of samples in the high-pass - /// input signal to filter. - /// - /// - /// This is the step, or interleave factor, of the - /// high-pass input signal samples in the highSig array. - /// - /// - /// This is the array where the output signal is - /// placed. It should be and float[] and long enough to contain the - /// output signal. - /// - /// - /// This is the index in outSig of the element where - /// to put the first output sample. - /// - /// - /// This is the step, or interleave factor, of the - /// output samples in the outSig array. - /// - /// - /// - /// - /// - /// - /// - /// - /// - public override void synthetize_lpf(System.Object lowSig, int lowOff, int lowLen, int lowStep, System.Object highSig, int highOff, int highLen, int highStep, System.Object outSig, int outOff, int outStep) - { - - synthetize_lpf((float[])lowSig, lowOff, lowLen, lowStep, (float[])highSig, highOff, highLen, highStep, (float[])outSig, outOff, outStep); - } - - /// A specific version of the synthetize_hpf() method that works on float - /// data. See the general description of the synthetize_hpf() method in the - /// SynWTFilter class for more details. - /// - /// - /// This is the array that contains the low-pass - /// input signal. - /// - /// - /// This is the index in lowSig of the first sample to - /// filter. - /// - /// - /// This is the number of samples in the low-pass - /// input signal to filter. - /// - /// - /// This is the step, or interleave factor, of the - /// low-pass input signal samples in the lowSig array. - /// - /// - /// This is the array that contains the high-pass - /// input signal. - /// - /// - /// This is the index in highSig of the first sample to - /// filter. - /// - /// - /// This is the number of samples in the high-pass - /// input signal to filter. - /// - /// - /// This is the step, or interleave factor, of the - /// high-pass input signal samples in the highSig array. - /// - /// - /// This is the array where the output signal is - /// placed. It should be long enough to contain the output signal. - /// - /// - /// This is the index in outSig of the element where - /// to put the first output sample. - /// - /// - /// This is the step, or interleave factor, of the - /// output samples in the outSig array. - /// - /// - /// - /// - /// - /// - /// - /// - /// - public abstract void synthetize_hpf(float[] lowSig, int lowOff, int lowLen, int lowStep, float[] highSig, int highOff, int highLen, int highStep, float[] outSig, int outOff, int outStep); - - /// The general version of the synthetize_hpf() method, it just calls - /// the specialized version. See the description of the synthetize_hpf() - /// method of the SynWTFilter class for more details. - /// - /// - /// This is the array that contains the low-pass - /// input signal. It must be an float[]. - /// - /// - /// This is the index in lowSig of the first sample to - /// filter. - /// - /// - /// This is the number of samples in the low-pass - /// input signal to filter. - /// - /// - /// This is the step, or interleave factor, of the - /// low-pass input signal samples in the lowSig array. - /// - /// - /// This is the array that contains the high-pass - /// input signal. It must be an float[]. - /// - /// - /// This is the index in highSig of the first sample to - /// filter. - /// - /// - /// This is the number of samples in the high-pass - /// input signal to filter. - /// - /// - /// This is the step, or interleave factor, of the - /// high-pass input signal samples in the highSig array. - /// - /// - /// This is the array where the output signal is - /// placed. It should be and float[] and long enough to contain the - /// output signal. - /// - /// - /// This is the index in outSig of the element where - /// to put the first output sample. - /// - /// - /// This is the step, or interleave factor, of the - /// output samples in the outSig array. - /// - /// - /// - /// - /// - /// - /// - /// - /// - public override void synthetize_hpf(System.Object lowSig, int lowOff, int lowLen, int lowStep, System.Object highSig, int highOff, int highLen, int highStep, System.Object outSig, int outOff, int outStep) - { - - synthetize_hpf((float[])lowSig, lowOff, lowLen, lowStep, (float[])highSig, highOff, highLen, highStep, (float[])outSig, outOff, outStep); - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/wavelet/synthesis/SynWTFilterFloatLift9x7.cs b/CSJ2K/j2k/wavelet/synthesis/SynWTFilterFloatLift9x7.cs deleted file mode 100644 index 7adf53b8..00000000 --- a/CSJ2K/j2k/wavelet/synthesis/SynWTFilterFloatLift9x7.cs +++ /dev/null @@ -1,691 +0,0 @@ -/* -* CVS identifier: -* -* $Id: SynWTFilterFloatLift9x7.java,v 1.15 2002/05/22 15:01:56 grosbois Exp $ -* -* Class: SynWTFilterFloatLift9x7 -* -* Description: A synthetizing wavelet filter implementing the -* lifting 9x7 transform. -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -namespace CSJ2K.j2k.wavelet.synthesis -{ - - /// This class inherits from the synthesis wavelet filter definition for int - /// data. It implements the inverse wavelet transform specifically for the 9x7 - /// filter. The implementation is based on the lifting scheme. - /// - ///

    See the SynWTFilter class for details such as normalization, how to - /// split odd-length signals, etc. In particular, this method assumes that the - /// low-pass coefficient is computed first. - /// - ///

    - /// - /// - /// - /// - /// - public class SynWTFilterFloatLift9x7 : SynWTFilterFloat - { - /// Returns the negative support of the low-pass analysis filter. That is - /// the number of taps of the filter in the negative direction. - /// - /// - /// 2 - /// - /// - override public int AnLowNegSupport - { - get - { - return 4; - } - - } - /// Returns the positive support of the low-pass analysis filter. That is - /// the number of taps of the filter in the negative direction. - /// - /// - /// The number of taps of the low-pass analysis filter in the - /// positive direction - /// - /// - override public int AnLowPosSupport - { - get - { - return 4; - } - - } - /// Returns the negative support of the high-pass analysis filter. That is - /// the number of taps of the filter in the negative direction. - /// - /// - /// The number of taps of the high-pass analysis filter in - /// the negative direction - /// - /// - override public int AnHighNegSupport - { - get - { - return 3; - } - - } - /// Returns the positive support of the high-pass analysis filter. That is - /// the number of taps of the filter in the negative direction. - /// - /// - /// The number of taps of the high-pass analysis filter in the - /// positive direction - /// - /// - override public int AnHighPosSupport - { - get - { - return 3; - } - - } - /// Returns the negative support of the low-pass synthesis filter. That is - /// the number of taps of the filter in the negative direction. - /// - ///

    A MORE PRECISE DEFINITION IS NEEDED - /// - ///

    - /// The number of taps of the low-pass synthesis filter in the - /// negative direction - /// - /// - override public int SynLowNegSupport - { - get - { - return 3; - } - - } - /// Returns the positive support of the low-pass synthesis filter. That is - /// the number of taps of the filter in the negative direction. - /// - ///

    A MORE PRECISE DEFINITION IS NEEDED - /// - ///

    - /// The number of taps of the low-pass synthesis filter in the - /// positive direction - /// - /// - override public int SynLowPosSupport - { - get - { - return 3; - } - - } - /// Returns the negative support of the high-pass synthesis filter. That is - /// the number of taps of the filter in the negative direction. - /// - ///

    A MORE PRECISE DEFINITION IS NEEDED - /// - ///

    - /// The number of taps of the high-pass synthesis filter in the - /// negative direction - /// - /// - override public int SynHighNegSupport - { - get - { - return 4; - } - - } - /// Returns the positive support of the high-pass synthesis filter. That is - /// the number of taps of the filter in the negative direction. - /// - ///

    A MORE PRECISE DEFINITION IS NEEDED - /// - ///

    - /// The number of taps of the high-pass synthesis filter in the - /// positive direction - /// - /// - override public int SynHighPosSupport - { - get - { - return 4; - } - - } - /// Returns the implementation type of this filter, as defined in this - /// class, such as WT_FILTER_INT_LIFT, WT_FILTER_FLOAT_LIFT, - /// WT_FILTER_FLOAT_CONVOL. - /// - /// - /// WT_FILTER_INT_LIFT. - /// - /// - override public int ImplType - { - get - { - return CSJ2K.j2k.wavelet.WaveletFilter_Fields.WT_FILTER_FLOAT_LIFT; - } - - } - /// Returns the reversibility of the filter. A filter is considered - /// reversible if it is suitable for lossless coding. - /// - /// - /// true since the 9x7 is reversible, provided the appropriate - /// rounding is performed. - /// - /// - override public bool Reversible - { - get - { - return false; - } - - } - - /// The value of the first lifting step coefficient - public const float ALPHA = -1.586134342f; - - /// The value of the second lifting step coefficient - public const float BETA = -0.05298011854f; - - /// The value of the third lifting step coefficient - public const float GAMMA = 0.8829110762f; - - /// The value of the fourth lifting step coefficient - public const float DELTA = 0.4435068522f; - - /// The value of the low-pass subband normalization factor - public const float KL = 0.8128930655f; - - /// The value of the high-pass subband normalization factor - public const float KH = 1.230174106f; - - /// An implementation of the synthetize_lpf() method that works on int - /// data, for the inverse 9x7 wavelet transform using the lifting - /// scheme. See the general description of the synthetize_lpf() method in - /// the SynWTFilter class for more details. - /// - ///

    The low-pass and high-pass subbands are normalized by respectively a - /// factor of 1/KL and a factor of 1/KH - /// - ///

    The coefficients of the first lifting step are [-DELTA 1 -DELTA]. - /// - ///

    The coefficients of the second lifting step are [-GAMMA 1 -GAMMA]. - /// - ///

    The coefficients of the third lifting step are [-BETA 1 -BETA]. - /// - ///

    The coefficients of the fourth lifting step are [-ALPHA 1 -ALPHA]. - /// - ///

    - /// This is the array that contains the low-pass input - /// signal. - /// - /// - /// This is the index in lowSig of the first sample to - /// filter. - /// - /// - /// This is the number of samples in the low-pass input - /// signal to filter. - /// - /// - /// This is the step, or interleave factor, of the low-pass - /// input signal samples in the lowSig array. - /// - /// - /// This is the array that contains the high-pass input - /// signal. - /// - /// - /// This is the index in highSig of the first sample to - /// filter. - /// - /// - /// This is the number of samples in the high-pass input - /// signal to filter. - /// - /// - /// This is the step, or interleave factor, of the - /// high-pass input signal samples in the highSig array. - /// - /// - /// This is the array where the output signal is placed. It - /// should be long enough to contain the output signal. - /// - /// - /// This is the index in outSig of the element where to put - /// the first output sample. - /// - /// - /// This is the step, or interleave factor, of the output - /// samples in the outSig array. - /// - /// - /// - /// - /// - public override void synthetize_lpf(float[] lowSig, int lowOff, int lowLen, int lowStep, float[] highSig, int highOff, int highLen, int highStep, float[] outSig, int outOff, int outStep) - { - - int i; - int outLen = lowLen + highLen; //Length of the output signal - int iStep = 2 * outStep; //Upsampling in outSig - int ik; //Indexing outSig - int lk; //Indexing lowSig - int hk; //Indexing highSig - - // Generate intermediate low frequency subband - //float sample = 0; - - //Initialize counters - lk = lowOff; - hk = highOff; - ik = outOff; - - //Handle tail boundary effect. Use symmetric extension - if (outLen > 1) - { - outSig[ik] = lowSig[lk] / KL - 2 * DELTA * highSig[hk] / KH; - } - else - { - outSig[ik] = lowSig[lk]; - } - - lk += lowStep; - hk += highStep; - ik += iStep; - - //Apply lifting step to each "inner" sample - for (i = 2; i < outLen - 1; i += 2, ik += iStep, lk += lowStep, hk += highStep) - { - outSig[ik] = lowSig[lk] / KL - DELTA * (highSig[hk - highStep] + highSig[hk]) / KH; - } - - //Handle head boundary effect if input signal has odd length - if (outLen % 2 == 1) - { - if (outLen > 2) - { - outSig[ik] = lowSig[lk] / KL - 2 * DELTA * highSig[hk - highStep] / KH; - } - } - - // Generate intermediate high frequency subband - - //Initialize counters - lk = lowOff; - hk = highOff; - ik = outOff + outStep; - - //Apply lifting step to each "inner" sample - for (i = 1; i < outLen - 1; i += 2, ik += iStep, hk += highStep, lk += lowStep) - { - outSig[ik] = highSig[hk] / KH - GAMMA * (outSig[ik - outStep] + outSig[ik + outStep]); - } - - //Handle head boundary effect if output signal has even length - if (outLen % 2 == 0) - { - outSig[ik] = highSig[hk] / KH - 2 * GAMMA * outSig[ik - outStep]; - } - - // Generate even samples (inverse low-pass filter) - - //Initialize counters - ik = outOff; - - //Handle tail boundary effect - //If access the overlap then perform the lifting step. - if (outLen > 1) - { - outSig[ik] -= 2 * BETA * outSig[ik + outStep]; - } - ik += iStep; - - //Apply lifting step to each "inner" sample - for (i = 2; i < outLen - 1; i += 2, ik += iStep) - { - outSig[ik] -= BETA * (outSig[ik - outStep] + outSig[ik + outStep]); - } - - //Handle head boundary effect if input signal has odd length - if (outLen % 2 == 1 && outLen > 2) - { - outSig[ik] -= 2 * BETA * outSig[ik - outStep]; - } - - // Generate odd samples (inverse high pass-filter) - - //Initialize counters - ik = outOff + outStep; - - //Apply first lifting step to each "inner" sample - for (i = 1; i < outLen - 1; i += 2, ik += iStep) - { - outSig[ik] -= ALPHA * (outSig[ik - outStep] + outSig[ik + outStep]); - } - - //Handle head boundary effect if input signal has even length - if (outLen % 2 == 0) - { - outSig[ik] -= 2 * ALPHA * outSig[ik - outStep]; - } - } - - /// An implementation of the synthetize_hpf() method that works on int - /// data, for the inverse 9x7 wavelet transform using the lifting - /// scheme. See the general description of the synthetize_hpf() method in - /// the SynWTFilter class for more details. - /// - ///

    The low-pass and high-pass subbands are normalized by respectively - /// a factor of 1/KL and a factor of 1/KH - /// - ///

    The coefficients of the first lifting step are [-DELTA 1 -DELTA]. - /// - ///

    The coefficients of the second lifting step are [-GAMMA 1 -GAMMA]. - /// - ///

    The coefficients of the third lifting step are [-BETA 1 -BETA]. - /// - ///

    The coefficients of the fourth lifting step are [-ALPHA 1 -ALPHA]. - /// - ///

    - /// This is the array that contains the low-pass - /// input signal. - /// - /// - /// This is the index in lowSig of the first sample to - /// filter. - /// - /// - /// This is the number of samples in the low-pass input - /// signal to filter. - /// - /// - /// This is the step, or interleave factor, of the low-pass - /// input signal samples in the lowSig array. - /// - /// - /// This is the array that contains the high-pass input - /// signal. - /// - /// - /// This is the index in highSig of the first sample to - /// filter. - /// - /// - /// This is the number of samples in the high-pass input - /// signal to filter. - /// - /// - /// This is the step, or interleave factor, of the - /// high-pass input signal samples in the highSig array. - /// - /// - /// This is the array where the output signal is placed. It - /// should be long enough to contain the output signal. - /// - /// - /// This is the index in outSig of the element where to put - /// the first output sample. - /// - /// - /// This is the step, or interleave factor, of the output - /// samples in the outSig array. - /// - /// - /// - /// - /// - public override void synthetize_hpf(float[] lowSig, int lowOff, int lowLen, int lowStep, float[] highSig, int highOff, int highLen, int highStep, float[] outSig, int outOff, int outStep) - { - - int i; - int outLen = lowLen + highLen; //Length of the output signal - int iStep = 2 * outStep; //Upsampling in outSig - int ik; //Indexing outSig - int lk; //Indexing lowSig - int hk; //Indexing highSig - - // Initialize counters - lk = lowOff; - hk = highOff; - - if (outLen != 1) - { - int outLen2 = outLen >> 1; - // "Inverse normalize" each sample - for (i = 0; i < outLen2; i++) - { - lowSig[lk] /= KL; - highSig[hk] /= KH; - lk += lowStep; - hk += highStep; - } - // "Inverse normalise" last high pass coefficient - if (outLen % 2 == 1) - { - highSig[hk] /= KH; - } - } - else - { - // Normalize for Nyquist gain - highSig[highOff] /= 2; - } - - // Generate intermediate low frequency subband - - //Initialize counters - lk = lowOff; - hk = highOff; - ik = outOff + outStep; - - //Apply lifting step to each "inner" sample - for (i = 1; i < outLen - 1; i += 2) - { - outSig[ik] = lowSig[lk] - DELTA * (highSig[hk] + highSig[hk + highStep]); - ik += iStep; - lk += lowStep; - hk += highStep; - } - - if (outLen % 2 == 0 && outLen > 1) - { - //Use symmetric extension - outSig[ik] = lowSig[lk] - 2 * DELTA * highSig[hk]; - } - - // Generate intermediate high frequency subband - - //Initialize counters - hk = highOff; - ik = outOff; - - if (outLen > 1) - { - outSig[ik] = highSig[hk] - 2 * GAMMA * outSig[ik + outStep]; - } - else - { - outSig[ik] = highSig[hk]; - } - - ik += iStep; - hk += highStep; - - //Apply lifting step to each "inner" sample - for (i = 2; i < outLen - 1; i += 2) - { - outSig[ik] = highSig[hk] - GAMMA * (outSig[ik - outStep] + outSig[ik + outStep]); - ik += iStep; - hk += highStep; - } - - //Handle head boundary effect if output signal has even length - if (outLen % 2 == 1 && outLen > 1) - { - //Use symmetric extension - outSig[ik] = highSig[hk] - 2 * GAMMA * outSig[ik - outStep]; - } - - // Generate even samples (inverse low-pass filter) - - //Initialize counters - ik = outOff + outStep; - - //Apply lifting step to each "inner" sample - for (i = 1; i < outLen - 1; i += 2) - { - outSig[ik] -= BETA * (outSig[ik - outStep] + outSig[ik + outStep]); - ik += iStep; - } - - if (outLen % 2 == 0 && outLen > 1) - { - // symmetric extension. - outSig[ik] -= 2 * BETA * outSig[ik - outStep]; - } - - // Generate odd samples (inverse high pass-filter) - - //Initialize counters - ik = outOff; - - if (outLen > 1) - { - // symmetric extension. - outSig[ik] -= 2 * ALPHA * outSig[ik + outStep]; - } - ik += iStep; - - //Apply first lifting step to each "inner" sample - for (i = 2; i < outLen - 1; i += 2) - { - outSig[ik] -= ALPHA * (outSig[ik - outStep] + outSig[ik + outStep]); - ik += iStep; - } - - //Handle head boundary effect if input signal has even length - if ((outLen % 2 == 1) && (outLen > 1)) - { - //Use symmetric extension - outSig[ik] -= 2 * ALPHA * outSig[ik - outStep]; - } - } - - /// Returns true if the wavelet filter computes or uses the - /// same "inner" subband coefficient as the full frame wavelet transform, - /// and false otherwise. In particular, for block based transforms with - /// reduced overlap, this method should return false. The term "inner" - /// indicates that this applies only with respect to the coefficient that - /// are not affected by image boundaries processings such as symmetric - /// extension, since there is not reference method for this. - /// - ///

    The result depends on the length of the allowed overlap when - /// compared to the overlap required by the wavelet filter. It also - /// depends on how overlap processing is implemented in the wavelet - /// filter. - /// - ///

    - /// This is the number of samples in the input - /// signal before the first sample to filter that can be used for - /// overlap. - /// - /// - /// This is the number of samples in the input - /// signal after the last sample to filter that can be used for - /// overlap. - /// - /// - /// This is the lenght of the input signal to filter.The - /// required number of samples in the input signal after the last sample - /// depends on the length of the input signal. - /// - /// - /// true if both overlaps are greater than 2, and correct - /// processing is applied in the analyze() method. - /// - /// - /// - /// - public override bool isSameAsFullWT(int tailOvrlp, int headOvrlp, int inLen) - { - - //If the input signal has even length. - if (inLen % 2 == 0) - { - if (tailOvrlp >= 2 && headOvrlp >= 1) - return true; - else - return false; - } - //Else if the input signal has odd length. - else - { - if (tailOvrlp >= 2 && headOvrlp >= 2) - return true; - else - return false; - } - } - - /// Returns a string of information about the synthesis wavelet filter - /// - /// - /// wavelet filter type. - /// - /// - /// - public override System.String ToString() - { - return "w9x7 (lifting)"; - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/wavelet/synthesis/SynWTFilterInt.cs b/CSJ2K/j2k/wavelet/synthesis/SynWTFilterInt.cs deleted file mode 100644 index 7dbd24d0..00000000 --- a/CSJ2K/j2k/wavelet/synthesis/SynWTFilterInt.cs +++ /dev/null @@ -1,334 +0,0 @@ -/* -* CVS identifier: -* -* $Id: SynWTFilterInt.java,v 1.7 2000/09/05 09:26:35 grosbois Exp $ -* -* Class: SynWTFilterInt -* -* Description: A specialized synthesis wavelet filter interface -* that works on int data. -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* -* -* -*/ -using CSJ2K.j2k.image; -namespace CSJ2K.j2k.wavelet.synthesis -{ - - /// This extends the synthesis wavelet filter general definitions of - /// SynWTFilter by adding methods that work for int data - /// specifically. Implementations that work on int data should inherit - /// from this class. - /// - ///

    See the SynWTFilter class for details such as - /// normalization, how to split odd-length signals, etc. - /// - ///

    The advantage of using the specialized method is that no casts - /// are performed. - /// - ///

    - /// - /// - /// - public abstract class SynWTFilterInt : SynWTFilter - { - /// Returns the type of data on which this filter works, as defined - /// in the DataBlk interface, which is always TYPE_INT for this - /// class. - /// - /// - /// The type of data as defined in the DataBlk interface. - /// - /// - /// - /// - /// - /// - /// - override public int DataType - { - get - { - return DataBlk.TYPE_INT; - } - - } - - /// A specific version of the synthetize_lpf() method that works on int - /// data. See the general description of the synthetize_lpf() method in the - /// SynWTFilter class for more details. - /// - /// - /// This is the array that contains the low-pass - /// input signal. - /// - /// - /// This is the index in lowSig of the first sample to - /// filter. - /// - /// - /// This is the number of samples in the low-pass - /// input signal to filter. - /// - /// - /// This is the step, or interleave factor, of the - /// low-pass input signal samples in the lowSig array. - /// - /// - /// This is the array that contains the high-pass - /// input signal. - /// - /// - /// This is the index in highSig of the first sample to - /// filter. - /// - /// - /// This is the number of samples in the high-pass - /// input signal to filter. - /// - /// - /// This is the step, or interleave factor, of the - /// high-pass input signal samples in the highSig array. - /// - /// - /// This is the array where the output signal is - /// placed. It should be long enough to contain the output signal. - /// - /// - /// This is the index in outSig of the element where - /// to put the first output sample. - /// - /// - /// This is the step, or interleave factor, of the - /// output samples in the outSig array. - /// - /// - /// - /// - /// - /// - /// - /// - /// - public abstract void synthetize_lpf(int[] lowSig, int lowOff, int lowLen, int lowStep, int[] highSig, int highOff, int highLen, int highStep, int[] outSig, int outOff, int outStep); - - /// The general version of the synthetize_lpf() method, it just calls - /// the specialized version. See the description of the synthetize_lpf() - /// method of the SynWTFilter class for more details. - /// - /// - /// This is the array that contains the low-pass - /// input signal. It must be an int[]. - /// - /// - /// This is the index in lowSig of the first sample to - /// filter. - /// - /// - /// This is the number of samples in the low-pass - /// input signal to filter. - /// - /// - /// This is the step, or interleave factor, of the - /// low-pass input signal samples in the lowSig array. - /// - /// - /// This is the array that contains the high-pass - /// input signal. Itmust be an int[]. - /// - /// - /// This is the index in highSig of the first sample to - /// filter. - /// - /// - /// This is the number of samples in the high-pass - /// input signal to filter. - /// - /// - /// This is the step, or interleave factor, of the - /// high-pass input signal samples in the highSig array. - /// - /// - /// This is the array where the output signal is - /// placed. It should be and int[] and long enough to contain the - /// output signal. - /// - /// - /// This is the index in outSig of the element where - /// to put the first output sample. - /// - /// - /// This is the step, or interleave factor, of the - /// output samples in the outSig array. - /// - /// - /// - /// - /// - /// - /// - /// - /// - public override void synthetize_lpf(System.Object lowSig, int lowOff, int lowLen, int lowStep, System.Object highSig, int highOff, int highLen, int highStep, System.Object outSig, int outOff, int outStep) - { - - synthetize_lpf((int[])lowSig, lowOff, lowLen, lowStep, (int[])highSig, highOff, highLen, highStep, (int[])outSig, outOff, outStep); - } - - /// A specific version of the synthetize_hpf() method that works on int - /// data. See the general description of the synthetize_hpf() method in the - /// SynWTFilter class for more details. - /// - /// - /// This is the array that contains the low-pass - /// input signal. - /// - /// - /// This is the index in lowSig of the first sample to - /// filter. - /// - /// - /// This is the number of samples in the low-pass - /// input signal to filter. - /// - /// - /// This is the step, or interleave factor, of the - /// low-pass input signal samples in the lowSig array. - /// - /// - /// This is the array that contains the high-pass - /// input signal. - /// - /// - /// This is the index in highSig of the first sample to - /// filter. - /// - /// - /// This is the number of samples in the high-pass - /// input signal to filter. - /// - /// - /// This is the step, or interleave factor, of the - /// high-pass input signal samples in the highSig array. - /// - /// - /// This is the array where the output signal is - /// placed. It should be long enough to contain the output signal. - /// - /// - /// This is the index in outSig of the element where - /// to put the first output sample. - /// - /// - /// This is the step, or interleave factor, of the - /// output samples in the outSig array. - /// - /// - /// - /// - /// - /// - /// - /// - /// - public abstract void synthetize_hpf(int[] lowSig, int lowOff, int lowLen, int lowStep, int[] highSig, int highOff, int highLen, int highStep, int[] outSig, int outOff, int outStep); - - - - /// The general version of the synthetize_hpf() method, it just calls - /// the specialized version. See the description of the synthetize_hpf() - /// method of the SynWTFilter class for more details. - /// - /// - /// This is the array that contains the low-pass - /// input signal. It must be an int[]. - /// - /// - /// This is the index in lowSig of the first sample to - /// filter. - /// - /// - /// This is the number of samples in the low-pass - /// input signal to filter. - /// - /// - /// This is the step, or interleave factor, of the - /// low-pass input signal samples in the lowSig array. - /// - /// - /// This is the array that contains the high-pass - /// input signal. Itmust be an int[]. - /// - /// - /// This is the index in highSig of the first sample to - /// filter. - /// - /// - /// This is the number of samples in the high-pass - /// input signal to filter. - /// - /// - /// This is the step, or interleave factor, of the - /// high-pass input signal samples in the highSig array. - /// - /// - /// This is the array where the output signal is - /// placed. It should be and int[] and long enough to contain the - /// output signal. - /// - /// - /// This is the index in outSig of the element where - /// to put the first output sample. - /// - /// - /// This is the step, or interleave factor, of the - /// output samples in the outSig array. - /// - /// - /// - /// - /// - /// - /// - /// - /// - public override void synthetize_hpf(System.Object lowSig, int lowOff, int lowLen, int lowStep, System.Object highSig, int highOff, int highLen, int highStep, System.Object outSig, int outOff, int outStep) - { - - synthetize_hpf((int[])lowSig, lowOff, lowLen, lowStep, (int[])highSig, highOff, highLen, highStep, (int[])outSig, outOff, outStep); - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/wavelet/synthesis/SynWTFilterIntLift5x3.cs b/CSJ2K/j2k/wavelet/synthesis/SynWTFilterIntLift5x3.cs deleted file mode 100644 index 93381d0c..00000000 --- a/CSJ2K/j2k/wavelet/synthesis/SynWTFilterIntLift5x3.cs +++ /dev/null @@ -1,538 +0,0 @@ -/* -* CVS identifier: -* -* $Id: SynWTFilterIntLift5x3.java,v 1.11 2001/08/02 11:24:23 grosbois Exp $ -* -* Class: SynWTFilterIntLift5x3 -* -* Description: A synthetizing wavelet filter implementing the -* lifting 5x3 transform. -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -namespace CSJ2K.j2k.wavelet.synthesis -{ - - /// This class inherits from the synthesis wavelet filter definition for int - /// data. It implements the inverse wavelet transform specifically for the 5x3 - /// filter. The implementation is based on the lifting scheme. - /// - ///

    See the SynWTFilter class for details such as normalization, how to - /// split odd-length signals, etc. In particular, this method assumes that the - /// low-pass coefficient is computed first.

    - /// - ///
    - /// - /// - /// - /// - /// - public class SynWTFilterIntLift5x3 : SynWTFilterInt - { - /// Returns the negative support of the low-pass analysis filter. That is - /// the number of taps of the filter in the negative direction. - /// - /// - /// 2 - /// - /// - override public int AnLowNegSupport - { - get - { - return 2; - } - - } - /// Returns the positive support of the low-pass analysis filter. That is - /// the number of taps of the filter in the negative direction. - /// - /// - /// The number of taps of the low-pass analysis filter in the - /// positive direction - /// - /// - override public int AnLowPosSupport - { - get - { - return 2; - } - - } - /// Returns the negative support of the high-pass analysis filter. That is - /// the number of taps of the filter in the negative direction. - /// - /// - /// The number of taps of the high-pass analysis filter in the - /// negative direction - /// - /// - override public int AnHighNegSupport - { - get - { - return 1; - } - - } - /// Returns the positive support of the high-pass analysis filter. That is - /// the number of taps of the filter in the negative direction. - /// - /// - /// The number of taps of the high-pass analysis filter in the - /// positive direction - /// - /// - override public int AnHighPosSupport - { - get - { - return 1; - } - - } - /// Returns the negative support of the low-pass synthesis filter. That is - /// the number of taps of the filter in the negative direction. - /// - /// - /// The number of taps of the low-pass synthesis filter in the - /// negative direction - /// - /// - override public int SynLowNegSupport - { - get - { - return 1; - } - - } - /// Returns the positive support of the low-pass synthesis filter. That is - /// the number of taps of the filter in the negative direction. - /// - /// - /// The number of taps of the low-pass synthesis filter in the - /// positive direction - /// - /// - override public int SynLowPosSupport - { - get - { - return 1; - } - - } - /// Returns the negative support of the high-pass synthesis filter. That is - /// the number of taps of the filter in the negative direction. - /// - /// - /// The number of taps of the high-pass synthesis filter in the - /// negative direction - /// - /// - override public int SynHighNegSupport - { - get - { - return 2; - } - - } - /// Returns the positive support of the high-pass synthesis filter. That is - /// the number of taps of the filter in the negative direction. - /// - /// - /// The number of taps of the high-pass synthesis filter in the - /// positive direction - /// - /// - override public int SynHighPosSupport - { - get - { - return 2; - } - - } - /// Returns the implementation type of this filter, as defined in this - /// class, such as WT_FILTER_INT_LIFT, WT_FILTER_FLOAT_LIFT, - /// WT_FILTER_FLOAT_CONVOL. - /// - /// - /// WT_FILTER_INT_LIFT. - /// - /// - override public int ImplType - { - get - { - return CSJ2K.j2k.wavelet.WaveletFilter_Fields.WT_FILTER_INT_LIFT; - } - - } - /// Returns the reversibility of the filter. A filter is considered - /// reversible if it is suitable for lossless coding. - /// - /// - /// true since the 5x3 is reversible, provided the appropriate - /// rounding is performed. - /// - /// - override public bool Reversible - { - get - { - return true; - } - - } - - /// An implementation of the synthetize_lpf() method that works on int - /// data, for the inverse 5x3 wavelet transform using the lifting - /// scheme. See the general description of the synthetize_lpf() method in - /// the SynWTFilter class for more details. - /// - ///

    The coefficients of the first lifting step are [-1/4 1 -1/4].

    - /// - ///

    The coefficients of the second lifting step are [1/2 1 1/2].

    - /// - ///
    - /// This is the array that contains the low-pass input - /// signal. - /// - /// - /// This is the index in lowSig of the first sample to - /// filter. - /// - /// - /// This is the number of samples in the low-pass input - /// signal to filter. - /// - /// - /// This is the step, or interleave factor, of the low-pass - /// input signal samples in the lowSig array. - /// - /// - /// This is the array that contains the high-pass input - /// signal. - /// - /// - /// This is the index in highSig of the first sample to - /// filter. - /// - /// - /// This is the number of samples in the high-pass input - /// signal to filter. - /// - /// - /// This is the step, or interleave factor, of the - /// high-pass input signal samples in the highSig array. - /// - /// - /// This is the array where the output signal is placed. It - /// should be long enough to contain the output signal. - /// - /// - /// This is the index in outSig of the element where to put - /// the first output sample. - /// - /// - /// This is the step, or interleave factor, of the output - /// samples in the outSig array. - /// - /// - /// - /// - /// - public override void synthetize_lpf(int[] lowSig, int lowOff, int lowLen, int lowStep, int[] highSig, int highOff, int highLen, int highStep, int[] outSig, int outOff, int outStep) - { - - int i; - int outLen = lowLen + highLen; //Length of the output signal - int iStep = 2 * outStep; //Upsampling in outSig - int ik; //Indexing outSig - int lk; //Indexing lowSig - int hk; //Indexing highSig - - /* Generate even samples (inverse low-pass filter) */ - - //Initialize counters - lk = lowOff; - hk = highOff; - ik = outOff; - - //Handle tail boundary effect. Use symmetric extension. - if (outLen > 1) - { - outSig[ik] = lowSig[lk] - ((highSig[hk] + 1) >> 1); - } - else - { - outSig[ik] = lowSig[lk]; - } - - lk += lowStep; - hk += highStep; - ik += iStep; - - //Apply lifting step to each "inner" sample. - for (i = 2; i < outLen - 1; i += 2) - { - outSig[ik] = lowSig[lk] - ((highSig[hk - highStep] + highSig[hk] + 2) >> 2); - - lk += lowStep; - hk += highStep; - ik += iStep; - } - - //Handle head boundary effect if input signal has odd length. - if ((outLen % 2 == 1) && (outLen > 2)) - { - outSig[ik] = lowSig[lk] - ((2 * highSig[hk - highStep] + 2) >> 2); - } - - /* Generate odd samples (inverse high pass-filter) */ - - //Initialize counters - hk = highOff; - ik = outOff + outStep; - - //Apply first lifting step to each "inner" sample. - for (i = 1; i < outLen - 1; i += 2) - { - // Since signs are inversed (add instead of substract) - // the +1 rounding dissapears. - outSig[ik] = highSig[hk] + ((outSig[ik - outStep] + outSig[ik + outStep]) >> 1); - - hk += highStep; - ik += iStep; - } - - //Handle head boundary effect if input signal has even length. - if (outLen % 2 == 0 && outLen > 1) - { - outSig[ik] = highSig[hk] + outSig[ik - outStep]; - } - } - - /// An implementation of the synthetize_hpf() method that works on int - /// data, for the inverse 5x3 wavelet transform using thelifting - /// scheme. See the general description of the synthetize_hpf() method in - /// the SynWTFilter class for more details. - /// - ///

    The coefficients of the first lifting step are [-1/4 1 -1/4].

    - /// - ///

    The coefficients of the second lifting step are [1/2 1 1/2].

    - /// - ///
    - /// This is the array that contains the low-pass input - /// signal. - /// - /// - /// This is the index in lowSig of the first sample to - /// filter. - /// - /// - /// This is the number of samples in the low-pass input - /// signal to filter. - /// - /// - /// This is the step, or interleave factor, of the low-pass - /// input signal samples in the lowSig array. - /// - /// - /// This is the array that contains the high-pass input - /// signal. - /// - /// - /// This is the index in highSig of the first sample to - /// filter. - /// - /// - /// This is the number of samples in the high-pass input - /// signal to filter. - /// - /// - /// This is the step, or interleave factor, of the - /// high-pass input signal samples in the highSig array. - /// - /// - /// This is the array where the output signal is placed. It - /// should be long enough to contain the output signal. - /// - /// - /// This is the index in outSig of the element where to put - /// the first output sample. - /// - /// - /// This is the step, or interleave factor, of the output - /// samples in the outSig array. - /// - /// - /// - /// - /// - public override void synthetize_hpf(int[] lowSig, int lowOff, int lowLen, int lowStep, int[] highSig, int highOff, int highLen, int highStep, int[] outSig, int outOff, int outStep) - { - - int i; - int outLen = lowLen + highLen; //Length of the output signal - int iStep = 2 * outStep; //Upsampling in outSig - int ik; //Indexing outSig - int lk; //Indexing lowSig - int hk; //Indexing highSig - - /* Generate even samples (inverse low-pass filter) */ - - //Initialize counters - lk = lowOff; - hk = highOff; - ik = outOff + outStep; - - //Apply lifting step to each "inner" sample. - for (i = 1; i < outLen - 1; i += 2) - { - outSig[ik] = lowSig[lk] - ((highSig[hk] + highSig[hk + highStep] + 2) >> 2); - - lk += lowStep; - hk += highStep; - ik += iStep; - } - - if ((outLen > 1) && (outLen % 2 == 0)) - { - // symmetric extension. - outSig[ik] = lowSig[lk] - ((2 * highSig[hk] + 2) >> 2); - } - /* Generate odd samples (inverse high pass-filter) */ - - //Initialize counters - hk = highOff; - ik = outOff; - - if (outLen > 1) - { - outSig[ik] = highSig[hk] + outSig[ik + outStep]; - } - else - { - // Normalize for Nyquist gain - outSig[ik] = highSig[hk] >> 1; - } - - hk += highStep; - ik += iStep; - - //Apply first lifting step to each "inner" sample. - for (i = 2; i < outLen - 1; i += 2) - { - // Since signs are inversed (add instead of substract) - // the +1 rounding dissapears. - outSig[ik] = highSig[hk] + ((outSig[ik - outStep] + outSig[ik + outStep]) >> 1); - hk += highStep; - ik += iStep; - } - - //Handle head boundary effect if input signal has odd length. - if (outLen % 2 == 1 && outLen > 1) - { - outSig[ik] = highSig[hk] + outSig[ik - outStep]; - } - } - - /// Returns true if the wavelet filter computes or uses the same "inner" - /// subband coefficient as the full frame wavelet transform, and false - /// otherwise. In particular, for block based transforms with reduced - /// overlap, this method should return false. The term "inner" indicates - /// that this applies only with respect to the coefficient that are not - /// affected by image boundaries processings such as symmetric extension, - /// since there is not reference method for this. - /// - ///

    The result depends on the length of the allowed overlap when - /// compared to the overlap required by the wavelet filter. It also depends - /// on how overlap processing is implemented in the wavelet filter.

    - /// - ///
    - /// This is the number of samples in the input signal - /// before the first sample to filter that can be used for overlap. - /// - /// - /// This is the number of samples in the input signal - /// after the last sample to filter that can be used for overlap. - /// - /// - /// This is the lenght of the input signal to filter.The - /// required number of samples in the input signal after the last sample - /// depends on the length of the input signal. - /// - /// - /// true if both overlaps are greater than 2, and correct - /// processing is applied in the analyze() method. - /// - /// - public override bool isSameAsFullWT(int tailOvrlp, int headOvrlp, int inLen) - { - - //If the input signal has even length. - if (inLen % 2 == 0) - { - if (tailOvrlp >= 2 && headOvrlp >= 1) - return true; - else - return false; - } - //Else if the input signal has odd length. - else - { - if (tailOvrlp >= 2 && headOvrlp >= 2) - return true; - else - return false; - } - } - - /// Returns a string of information about the synthesis wavelet filter - /// - /// - /// wavelet filter type. - /// - /// - public override System.String ToString() - { - return "w5x3 (lifting)"; - } - } -} \ No newline at end of file diff --git a/CSJ2K/j2k/wavelet/synthesis/SynWTFilterSpec.cs b/CSJ2K/j2k/wavelet/synthesis/SynWTFilterSpec.cs deleted file mode 100644 index b9a6f9c3..00000000 --- a/CSJ2K/j2k/wavelet/synthesis/SynWTFilterSpec.cs +++ /dev/null @@ -1,210 +0,0 @@ -/* -* CVS identifier: -* -* $Id: SynWTFilterSpec.java,v 1.15 2001/08/02 10:01:30 grosbois Exp $ -* -* Class: SynWTFilterSpec -* -* Description: Synthesis filters specification -* -* -* -* COPYRIGHT: -* -* This software module was originally developed by Raphaël Grosbois and -* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel -* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David -* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research -* Centre France S.A) in the course of development of the JPEG2000 -* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This -* software module is an implementation of a part of the JPEG 2000 -* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio -* Systems AB and Canon Research Centre France S.A (collectively JJ2000 -* Partners) agree not to assert against ISO/IEC and users of the JPEG -* 2000 Standard (Users) any of their rights under the copyright, not -* including other intellectual property rights, for this software module -* with respect to the usage by ISO/IEC and Users of this software module -* or modifications thereof for use in hardware or software products -* claiming conformance to the JPEG 2000 Standard. Those intending to use -* this software module in hardware or software products are advised that -* their use may infringe existing patents. The original developers of -* this software module, JJ2000 Partners and ISO/IEC assume no liability -* for use of this software module or modifications thereof. No license -* or right to this software module is granted for non JPEG 2000 Standard -* conforming products. JJ2000 Partners have full right to use this -* software module for his/her own purpose, assign or donate this -* software module to any third party and to inhibit third parties from -* using this software module for non JPEG 2000 Standard conforming -* products. This copyright notice must be included in all copies or -* derivative works of this software module. -* -* Copyright (c) 1999/2000 JJ2000 Partners. -* */ -namespace CSJ2K.j2k.wavelet.synthesis -{ - - /// This class extends ModuleSpec class for synthesis filters specification - /// holding purpose. - /// - /// - /// - /// - /// - public class SynWTFilterSpec : ModuleSpec - { - - /// Constructs a new 'SynWTFilterSpec' for the specified number of - /// components and tiles. - /// - /// - /// The number of tiles - /// - /// - /// The number of components - /// - /// - /// the type of the specification module i.e. tile specific, - /// component specific or both. - /// - /// - public SynWTFilterSpec(int nt, int nc, byte type) : base(nt, nc, type) - { - } - - /// Returns the data type used by the filters in this object, as defined in - /// the 'DataBlk' interface for specified tile-component. - /// - /// - /// Tile index - /// - /// - /// Component index - /// - /// - /// The data type of the filters in this object - /// - /// - /// - /// - /// - public virtual int getWTDataType(int t, int c) - { - SynWTFilter[][] an = (SynWTFilter[][])getSpec(t, c); - return an[0][0].DataType; - } - - /// Returns the horizontal analysis filters to be used in component 'n' and - /// tile 't'. - /// - ///

    The horizontal analysis filters are returned in an array of - /// SynWTFilter. Each element contains the horizontal filter for each - /// resolution level starting with resolution level 1 (i.e. the analysis - /// filter to go from resolution level 1 to resolution level 0). If there - /// are less elements than the maximum resolution level, then the last - /// element is assumed to be repeated.

    - /// - ///
    - /// The tile index, in raster scan order - /// - /// - /// The component index. - /// - /// - /// The array of horizontal analysis filters for component 'n' and - /// tile 't'. - /// - /// - public virtual SynWTFilter[] getHFilters(int t, int c) - { - SynWTFilter[][] an = (SynWTFilter[][])getSpec(t, c); - return an[0]; - } - - /// Returns the vertical analysis filters to be used in component 'n' and - /// tile 't'. - /// - ///

    The vertical analysis filters are returned in an array of - /// SynWTFilter. Each element contains the vertical filter for each - /// resolution level starting with resolution level 1 (i.e. the analysis - /// filter to go from resolution level 1 to resolution level 0). If there - /// are less elements than the maximum resolution level, then the last - /// element is assumed to be repeated.

    - /// - ///
    - /// The tile index, in raster scan order - /// - /// - /// The component index. - /// - /// - /// The array of horizontal analysis filters for component 'n' and - /// tile 't'. - /// - /// - public virtual SynWTFilter[] getVFilters(int t, int c) - { - SynWTFilter[][] an = (SynWTFilter[][])getSpec(t, c); - return an[1]; - } - - /// Debugging method - public override System.String ToString() - { - System.String str = ""; - SynWTFilter[][] an; - - str += ("nTiles=" + nTiles + "\nnComp=" + nComp + "\n\n"); - - for (int t = 0; t < nTiles; t++) - { - for (int c = 0; c < nComp; c++) - { - an = (SynWTFilter[][])getSpec(t, c); - - str += ("(t:" + t + ",c:" + c + ")\n"); - - // Horizontal filters - str += "\tH:"; - for (int i = 0; i < an[0].Length; i++) - { - //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Object.toString' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" - str += (" " + an[0][i]); - } - // Horizontal filters - str += "\n\tV:"; - for (int i = 0; i < an[1].Length; i++) - { - //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Object.toString' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" - str += (" " + an[1][i]); - } - str += "\n"; - } - } - - return str; - } - - /// Check the reversibility of filters contained is the given - /// tile-component. - /// - /// - /// The index of the tile - /// - /// - /// The index of the component - /// - /// - public virtual bool isReversible(int t, int c) - { - // Note: no need to buffer the result since this method is normally - // called once per tile-component. - SynWTFilter[] hfilter = getHFilters(t, c), vfilter = getVFilters(t, c); - - // As soon as a filter is not reversible, false can be returned - for (int i = hfilter.Length - 1; i >= 0; i--) - if (!hfilter[i].Reversible || !vfilter[i].Reversible) - return false; - return true; - } - } -} \ No newline at end of file diff --git a/Directory.Build.props b/Directory.Build.props index 1c8a703b..e080a9ee 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,11 +1,33 @@ - - 1.1.6 - 1.1.6 - 1.1.6 - $(SolutionDir)\obj\$(Configuration)\$(MSBuildProjectName)\ - $(SolutionDir)\obj\$(Configuration)\$(MSBuildProjectName)\ - $(SolutionDir)\bin\$(Configuration)\$(AssemblyName)\ - $(OutputPath) - + + OpenMetaverse + Utopa Skye LLC, OpenMetaverse Developers + Utopia Skye LLC + net8.0 + enable + disable + + + + all + 3.9.50 + + + + BSD-3-Clause + https://github.com/OpenSim-NGC/libopenmetaverse + false + OMV OpenMetaverse OpenSim Halcyon OpenMetaverseFoundation VirtualWorld VirtualReality 3D SecondLife + https://github.com/OpenSim-NGC/libopenmetaverse.git + git + master + + + + true + snupkg + + true + true + diff --git a/LICENSE.txt b/LICENSE.txt index 43b484b2..426f81ff 100644 --- a/LICENSE.txt +++ b/LICENSE.txt @@ -1,4 +1,7 @@ + Copyright (c) Opensimulator, http://opensimulator.org/ + All rights reserved. + Copyright (c) 2006-2016, openmetaverse.co All rights reserved. diff --git a/OpenMetaverse.GUI/AvatarList.cs b/OpenMetaverse.GUI/AvatarList.cs index 0276b7c0..6423d0c1 100644 --- a/OpenMetaverse.GUI/AvatarList.cs +++ b/OpenMetaverse.GUI/AvatarList.cs @@ -97,10 +97,10 @@ public AvatarList() this.ListViewItemSorter = _ColumnSorter; EventHandler clickHandler = new EventHandler(defaultMenuItem_Click); - this.ContextMenu = new ContextMenu(); - this.ContextMenu.MenuItems.Add("Offer Teleport", clickHandler); - this.ContextMenu.MenuItems.Add("Teleport To", clickHandler); - this.ContextMenu.MenuItems.Add("Walk To", clickHandler); + this.ContextMenuStrip = new ContextMenuStrip(); + this.ContextMenuStrip.Items.Add("Offer Teleport", null, clickHandler); + this.ContextMenuStrip.Items.Add("Teleport To", null, clickHandler); + this.ContextMenuStrip.Items.Add("Walk To", null, clickHandler); this.DoubleBuffered = true; this.ListViewItemSorter = _ColumnSorter; @@ -360,7 +360,7 @@ private void UpdateCoarseInfo(Simulator sim, List newEntries, List r private void defaultMenuItem_Click(object sender, EventArgs e) { - MenuItem menuItem = (MenuItem)sender; + ToolStripItem menuItem = (ToolStripItem)sender; switch (menuItem.Text) { diff --git a/OpenMetaverse.GUI/InventoryTree.cs b/OpenMetaverse.GUI/InventoryTree.cs index 12e1352d..cf2cc9a9 100644 --- a/OpenMetaverse.GUI/InventoryTree.cs +++ b/OpenMetaverse.GUI/InventoryTree.cs @@ -1,226 +1,226 @@ -/* - * Copyright (c) 2006-2016, openmetaverse.co - * All rights reserved. - * - * - Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, this - * list of conditions and the following disclaimer. - * - Neither the name of the openmetaverse.co nor the names - * of its contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections.Generic; -using System.Drawing; -using System.Windows.Forms; - -namespace OpenMetaverse.GUI -{ - - /// - /// TreeView GUI component for browsing a client's inventory - /// - public class InventoryTree : TreeView - { - private GridClient _Client; - private ContextMenu _ContextMenu; - private UUID _SelectedItemID; - - /// - /// Gets or sets the context menu associated with this control - /// - public ContextMenu Menu - { - get { return _ContextMenu; } - set { _ContextMenu = value; } - } - - /// - /// Gets or sets the GridClient associated with this control - /// - public GridClient Client - { - get { return _Client; } - set { if (value != null) InitializeClient(value); } - } - - /// - /// TreeView control for an unspecified client's inventory - /// - public InventoryTree() - { - EventHandler clickHandler = new EventHandler(defaultMenuItem_Click); - _ContextMenu = new ContextMenu(); - _ContextMenu.MenuItems.Add("Wear", clickHandler); - _ContextMenu.MenuItems.Add("Detach", clickHandler); - - this.NodeMouseClick += new TreeNodeMouseClickEventHandler(InventoryTree_NodeMouseClick); - this.BeforeExpand += new TreeViewCancelEventHandler(InventoryTree_BeforeExpand); - } - - /// - /// TreeView control for the specified client's inventory - /// - /// - public InventoryTree(GridClient client) : this() - { - InitializeClient(client); - } - - /// - /// Thread-safe method for clearing the TreeView control - /// - public void ClearNodes() - { - if (this.InvokeRequired) this.BeginInvoke((MethodInvoker)delegate { ClearNodes(); }); - else this.Nodes.Clear(); - } - - /// - /// Thread-safe method for collapsing a TreeNode in the control - /// - /// - public void CollapseNode(TreeNode node) - { - if (this.InvokeRequired) this.BeginInvoke((MethodInvoker)delegate { CollapseNode(node); }); - else if (!node.IsExpanded) node.Collapse(); - } - - /// - /// Thread-safe method for expanding a TreeNode in the control - /// - /// - public void ExpandNode(TreeNode node) - { - if (this.InvokeRequired) this.BeginInvoke((MethodInvoker)delegate { ExpandNode(node); }); - else if (!node.IsExpanded) node.Expand(); - } - - /// - /// Thread-safe method for updating the contents of the specified folder UUID - /// - /// - public void UpdateFolder(UUID folderID) - { - if (this.InvokeRequired) this.BeginInvoke((MethodInvoker)delegate { UpdateFolder(folderID); }); - else - { - TreeNode node = null; - TreeNodeCollection children; - - if (folderID != Client.Inventory.Store.RootFolder.UUID) - { - TreeNode[] found = Nodes.Find(folderID.ToString(), true); - if (found.Length > 0) - { - node = found[0]; - children = node.Nodes; - } - else - { - Logger.Log("Received update for unknown TreeView node " + folderID, Helpers.LogLevel.Warning); - return; - } - } - else children = this.Nodes; - - children.Clear(); - - List contents = Client.Inventory.Store.GetContents(folderID); - if (contents.Count == 0) - { - TreeNode add = children.Add(null, "(empty)"); - add.ForeColor = Color.FromKnownColor(KnownColor.GrayText); - } - else - { - foreach (InventoryBase inv in contents) - { - string key = inv.UUID.ToString(); - - children.Add(key, inv.Name); - if (inv is InventoryFolder) - { - children[key].Nodes.Add(null, "(loading...)").ForeColor = Color.FromKnownColor(KnownColor.GrayText); - } - } - } - } - } - - private void InitializeClient(GridClient client) - { - _Client = client; - _Client.Inventory.FolderUpdated += Inventory_OnFolderUpdated; - _Client.Network.LoginProgress += Network_OnLogin; - } - - private void defaultMenuItem_Click(object sender, EventArgs e) - { - MenuItem menuItem = (MenuItem)sender; - - InventoryItem item = (InventoryItem)Client.Inventory.Store[_SelectedItemID]; - - switch (menuItem.Text) - { - case "Wear": - { - Client.Appearance.Attach(item, AttachmentPoint.Default); - break; - } - case "Detach": - { - Client.Appearance.Detach(item); - break; - } - } - } - - void Network_OnLogin(object sender, LoginProgressEventArgs e) - { - if (e.Status == LoginStatus.Success) - { - if (Client.Inventory.Store != null) - UpdateFolder(Client.Inventory.Store.RootFolder.UUID); - } - } - - private void Inventory_OnFolderUpdated(object sender, FolderUpdatedEventArgs e) - { - UpdateFolder(e.FolderID); - } - - void InventoryTree_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e) - { - if (e.Button == MouseButtons.Right) - { - _SelectedItemID = new UUID(e.Node.Name); - _ContextMenu.Show(this, e.Location); - } - } - - private void InventoryTree_BeforeExpand(object sender, TreeViewCancelEventArgs e) - { - InventoryFolder folder = (InventoryFolder)Client.Inventory.Store[new UUID(e.Node.Name)]; - Client.Inventory.RequestFolderContents(folder.UUID, _Client.Self.AgentID, true, true, InventorySortOrder.ByDate | InventorySortOrder.FoldersByName); - } - - } - -} - +/* + * Copyright (c) 2006-2016, openmetaverse.co + * All rights reserved. + * + * - Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * - Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * - Neither the name of the openmetaverse.co nor the names + * of its contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Windows.Forms; + +namespace OpenMetaverse.GUI +{ + + /// + /// TreeView GUI component for browsing a client's inventory + /// + public class InventoryTree : TreeView + { + private GridClient _Client; + private ContextMenuStrip _ContextMenu; + private UUID _SelectedItemID; + + /// + /// Gets or sets the context menu associated with this control + /// + public ContextMenuStrip Menu + { + get { return _ContextMenu; } + set { _ContextMenu = value; } + } + + /// + /// Gets or sets the GridClient associated with this control + /// + public GridClient Client + { + get { return _Client; } + set { if (value != null) InitializeClient(value); } + } + + /// + /// TreeView control for an unspecified client's inventory + /// + public InventoryTree() + { + EventHandler clickHandler = new EventHandler(defaultMenuItem_Click); + _ContextMenu = new ContextMenuStrip(); + _ContextMenu.Items.Add("Wear", null, clickHandler); + _ContextMenu.Items.Add("Detach", null, clickHandler); + + this.NodeMouseClick += new TreeNodeMouseClickEventHandler(InventoryTree_NodeMouseClick); + this.BeforeExpand += new TreeViewCancelEventHandler(InventoryTree_BeforeExpand); + } + + /// + /// TreeView control for the specified client's inventory + /// + /// + public InventoryTree(GridClient client) : this () + { + InitializeClient(client); + } + + /// + /// Thread-safe method for clearing the TreeView control + /// + public void ClearNodes() + { + if (this.InvokeRequired) this.BeginInvoke((MethodInvoker)delegate { ClearNodes(); }); + else this.Nodes.Clear(); + } + + /// + /// Thread-safe method for collapsing a TreeNode in the control + /// + /// + public void CollapseNode(TreeNode node) + { + if (this.InvokeRequired) this.BeginInvoke((MethodInvoker)delegate { CollapseNode(node); }); + else if (!node.IsExpanded) node.Collapse(); + } + + /// + /// Thread-safe method for expanding a TreeNode in the control + /// + /// + public void ExpandNode(TreeNode node) + { + if (this.InvokeRequired) this.BeginInvoke((MethodInvoker)delegate { ExpandNode(node); }); + else if (!node.IsExpanded) node.Expand(); + } + + /// + /// Thread-safe method for updating the contents of the specified folder UUID + /// + /// + public void UpdateFolder(UUID folderID) + { + if (this.InvokeRequired) this.BeginInvoke((MethodInvoker)delegate { UpdateFolder(folderID); }); + else + { + TreeNode node = null; + TreeNodeCollection children; + + if (folderID != Client.Inventory.Store.RootFolder.UUID) + { + TreeNode[] found = Nodes.Find(folderID.ToString(), true); + if (found.Length > 0) + { + node = found[0]; + children = node.Nodes; + } + else + { + Logger.Log("Received update for unknown TreeView node " + folderID, Helpers.LogLevel.Warning); + return; + } + } + else children = this.Nodes; + + children.Clear(); + + List contents = Client.Inventory.Store.GetContents(folderID); + if (contents.Count == 0) + { + TreeNode add = children.Add(null, "(empty)"); + add.ForeColor = Color.FromKnownColor(KnownColor.GrayText); + } + else + { + foreach (InventoryBase inv in contents) + { + string key = inv.UUID.ToString(); + + children.Add(key, inv.Name); + if (inv is InventoryFolder) + { + children[key].Nodes.Add(null, "(loading...)").ForeColor = Color.FromKnownColor(KnownColor.GrayText); + } + } + } + } + } + + private void InitializeClient(GridClient client) + { + _Client = client; + _Client.Inventory.FolderUpdated += Inventory_OnFolderUpdated; + _Client.Network.LoginProgress += Network_OnLogin; + } + + private void defaultMenuItem_Click(object sender, EventArgs e) + { + ToolStripItem menuItem = (ToolStripItem)sender; + + InventoryItem item = (InventoryItem)Client.Inventory.Store[_SelectedItemID]; + + switch(menuItem.Text) + { + case "Wear": + { + Client.Appearance.Attach(item, AttachmentPoint.Default); + break; + } + case "Detach": + { + Client.Appearance.Detach(item); + break; + } + } + } + + void Network_OnLogin(object sender, LoginProgressEventArgs e) + { + if (e.Status == LoginStatus.Success) + { + if (Client.Inventory.Store != null) + UpdateFolder(Client.Inventory.Store.RootFolder.UUID); + } + } + + private void Inventory_OnFolderUpdated(object sender, FolderUpdatedEventArgs e) + { + UpdateFolder(e.FolderID); + } + + void InventoryTree_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e) + { + if (e.Button == MouseButtons.Right) + { + _SelectedItemID = new UUID(e.Node.Name); + _ContextMenu.Show(this, e.Location); + } + } + + private void InventoryTree_BeforeExpand(object sender, TreeViewCancelEventArgs e) + { + InventoryFolder folder = (InventoryFolder)Client.Inventory.Store[new UUID(e.Node.Name)]; + Client.Inventory.RequestFolderContents(folder.UUID, _Client.Self.AgentID, true, true, InventorySortOrder.ByDate | InventorySortOrder.FoldersByName); + } + + } + +} + diff --git a/OpenMetaverse.GUI/MiniMap.cs b/OpenMetaverse.GUI/MiniMap.cs index 5f7b628d..9f9d129f 100644 --- a/OpenMetaverse.GUI/MiniMap.cs +++ b/OpenMetaverse.GUI/MiniMap.cs @@ -28,7 +28,9 @@ using OpenMetaverse.Imaging; using System.Collections.Generic; using System.Drawing; +using System.IO; using System.Windows.Forms; +using SkiaSharp; namespace OpenMetaverse.GUI { @@ -216,10 +218,23 @@ void Network_OnCurrentSimChanged(object sender, SimChangedEventArgs e) delegate (TextureRequestState state, AssetTexture asset) { if (state == TextureRequestState.Finished) - OpenJPEG.DecodeToImage(asset.AssetData, out nullImage, out _MapLayer); + { + SKBitmap skMapLayer; + OpenJPEG.DecodeToImage(asset.AssetData, out nullImage, out skMapLayer); + _MapLayer = skMapLayer != null ? ConvertToBitmap(skMapLayer) : null; + } }); } } + private static Bitmap ConvertToBitmap(SKBitmap skBitmap) + { + using SKImage image = SKImage.FromBitmap(skBitmap); + using SKData data = image.Encode(SKEncodedImageFormat.Png, 100); + using MemoryStream stream = new MemoryStream(data.ToArray()); + using Bitmap tmp = new Bitmap(stream); + return new Bitmap(tmp); + } + } } diff --git a/OpenMetaverse.GUI/OpenMetaverse.GUI.csproj b/OpenMetaverse.GUI/OpenMetaverse.GUI.csproj index 5f61070c..13728e9e 100644 --- a/OpenMetaverse.GUI/OpenMetaverse.GUI.csproj +++ b/OpenMetaverse.GUI/OpenMetaverse.GUI.csproj @@ -1,12 +1,14 @@  Local - net48 - 1591,1574,0419,0618 + Library True + net8.0-windows + true + true - + @@ -17,15 +19,4 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/OpenMetaverse.PrimMesher/OpenMetaverse.PrimMesher.csproj b/OpenMetaverse.PrimMesher/OpenMetaverse.PrimMesher.csproj deleted file mode 100644 index b18c3b3a..00000000 --- a/OpenMetaverse.PrimMesher/OpenMetaverse.PrimMesher.csproj +++ /dev/null @@ -1,20 +0,0 @@ - - - net48 - Dhalia Trimble, OpenSim Contributors, Cinder Roxley - OpenMetaverse.PrimMesher - OpenMetaverse.PrimMesher - true - - - full - TRACE;DEBUG;VERTEX_INDEXER - - - pdbonly - TRACE;VERTEX_INDEXER - - - - - \ No newline at end of file diff --git a/OpenMetaverse.PrimMesher/PrimMesher.cs b/OpenMetaverse.PrimMesher/PrimMesher.cs deleted file mode 100644 index f5a5490e..00000000 --- a/OpenMetaverse.PrimMesher/PrimMesher.cs +++ /dev/null @@ -1,2327 +0,0 @@ -/* - * Copyright (c) Contributors - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``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 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. - */ - -using System; -using System.Collections.Generic; -using System.IO; - -namespace OpenMetaverse.PrimMesher -{ - public struct Quat - { - /// X value - public float X; - - /// Y value - public float Y; - - /// Z value - public float Z; - - /// W value - public float W; - - public Quat(float x, float y, float z, float w) - { - X = x; - Y = y; - Z = z; - W = w; - } - - public Quat(Coord axis, float angle) - { - axis = axis.Normalize(); - - angle *= 0.5f; - var c = (float) Math.Cos(angle); - var s = (float) Math.Sin(angle); - - X = axis.X * s; - Y = axis.Y * s; - Z = axis.Z * s; - W = c; - - Normalize(); - } - - public float Length() - { - return (float) Math.Sqrt(X * X + Y * Y + Z * Z + W * W); - } - - public Quat Normalize() - { - const float MAG_THRESHOLD = 0.0000001f; - var mag = Length(); - - // Catch very small rounding errors when normalizing - if (mag > MAG_THRESHOLD) - { - var oomag = 1f / mag; - X *= oomag; - Y *= oomag; - Z *= oomag; - W *= oomag; - } - else - { - X = 0f; - Y = 0f; - Z = 0f; - W = 1f; - } - - return this; - } - - public static Quat operator *(Quat q1, Quat q2) - { - var x = q1.W * q2.X + q1.X * q2.W + q1.Y * q2.Z - q1.Z * q2.Y; - var y = q1.W * q2.Y - q1.X * q2.Z + q1.Y * q2.W + q1.Z * q2.X; - var z = q1.W * q2.Z + q1.X * q2.Y - q1.Y * q2.X + q1.Z * q2.W; - var w = q1.W * q2.W - q1.X * q2.X - q1.Y * q2.Y - q1.Z * q2.Z; - return new Quat(x, y, z, w); - } - - public override string ToString() - { - return "< X: " + X + ", Y: " + Y + ", Z: " + Z + ", W: " + W + ">"; - } - } - - public struct Coord - { - public float X; - public float Y; - public float Z; - - public Coord(float x, float y, float z) - { - X = x; - Y = y; - Z = z; - } - - public float Length() - { - return (float) Math.Sqrt(X * X + Y * Y + Z * Z); - } - - public Coord Invert() - { - X = -X; - Y = -Y; - Z = -Z; - - return this; - } - - public Coord Normalize() - { - const float MAG_THRESHOLD = 0.0000001f; - var mag = Length(); - - // Catch very small rounding errors when normalizing - if (mag > MAG_THRESHOLD) - { - var oomag = 1.0f / mag; - X *= oomag; - Y *= oomag; - Z *= oomag; - } - else - { - X = 0.0f; - Y = 0.0f; - Z = 0.0f; - } - - return this; - } - - public override string ToString() - { - return X + " " + Y + " " + Z; - } - - public static Coord Cross(Coord c1, Coord c2) - { - return new Coord( - c1.Y * c2.Z - c2.Y * c1.Z, - c1.Z * c2.X - c2.Z * c1.X, - c1.X * c2.Y - c2.X * c1.Y - ); - } - - public static Coord operator +(Coord v, Coord a) - { - return new Coord(v.X + a.X, v.Y + a.Y, v.Z + a.Z); - } - - public static Coord operator *(Coord v, Coord m) - { - return new Coord(v.X * m.X, v.Y * m.Y, v.Z * m.Z); - } - - public static Coord operator *(Coord v, Quat q) - { - // From http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/transforms/ - - var c2 = new Coord(0.0f, 0.0f, 0.0f); - - c2.X = q.W * q.W * v.X + - 2f * q.Y * q.W * v.Z - - 2f * q.Z * q.W * v.Y + - q.X * q.X * v.X + - 2f * q.Y * q.X * v.Y + - 2f * q.Z * q.X * v.Z - - q.Z * q.Z * v.X - - q.Y * q.Y * v.X; - - c2.Y = - 2f * q.X * q.Y * v.X + - q.Y * q.Y * v.Y + - 2f * q.Z * q.Y * v.Z + - 2f * q.W * q.Z * v.X - - q.Z * q.Z * v.Y + - q.W * q.W * v.Y - - 2f * q.X * q.W * v.Z - - q.X * q.X * v.Y; - - c2.Z = - 2f * q.X * q.Z * v.X + - 2f * q.Y * q.Z * v.Y + - q.Z * q.Z * v.Z - - 2f * q.W * q.Y * v.X - - q.Y * q.Y * v.Z + - 2f * q.W * q.X * v.Y - - q.X * q.X * v.Z + - q.W * q.W * v.Z; - - return c2; - } - } - - public struct UVCoord - { - public float U; - public float V; - - - public UVCoord(float u, float v) - { - U = u; - V = v; - } - - public UVCoord Flip() - { - U = 1.0f - U; - V = 1.0f - V; - return this; - } - } - - public struct Face - { - public int primFace; - - // vertices - public int v1; - - public int v2; - public int v3; - - //normals - public int n1; - - public int n2; - public int n3; - - // uvs - public int uv1; - - public int uv2; - public int uv3; - - public Face(int v1, int v2, int v3) - { - primFace = 0; - - this.v1 = v1; - this.v2 = v2; - this.v3 = v3; - - n1 = 0; - n2 = 0; - n3 = 0; - - uv1 = 0; - uv2 = 0; - uv3 = 0; - } - - public Face(int v1, int v2, int v3, int n1, int n2, int n3) - { - primFace = 0; - - this.v1 = v1; - this.v2 = v2; - this.v3 = v3; - - this.n1 = n1; - this.n2 = n2; - this.n3 = n3; - - uv1 = 0; - uv2 = 0; - uv3 = 0; - } - - public Coord SurfaceNormal(List coordList) - { - var c1 = coordList[v1]; - var c2 = coordList[v2]; - var c3 = coordList[v3]; - - var edge1 = new Coord(c2.X - c1.X, c2.Y - c1.Y, c2.Z - c1.Z); - var edge2 = new Coord(c3.X - c1.X, c3.Y - c1.Y, c3.Z - c1.Z); - - return Coord.Cross(edge1, edge2).Normalize(); - } - } - - public struct ViewerFace - { - public int primFaceNumber; - - public Coord v1; - public Coord v2; - public Coord v3; - - public int coordIndex1; - public int coordIndex2; - public int coordIndex3; - - public Coord n1; - public Coord n2; - public Coord n3; - - public UVCoord uv1; - public UVCoord uv2; - public UVCoord uv3; - - public ViewerFace(int primFaceNumber) - { - this.primFaceNumber = primFaceNumber; - - v1 = new Coord(); - v2 = new Coord(); - v3 = new Coord(); - - coordIndex1 = coordIndex2 = coordIndex3 = -1; // -1 means not assigned yet - - n1 = new Coord(); - n2 = new Coord(); - n3 = new Coord(); - - uv1 = new UVCoord(); - uv2 = new UVCoord(); - uv3 = new UVCoord(); - } - - public void Scale(float x, float y, float z) - { - v1.X *= x; - v1.Y *= y; - v1.Z *= z; - - v2.X *= x; - v2.Y *= y; - v2.Z *= z; - - v3.X *= x; - v3.Y *= y; - v3.Z *= z; - } - - public void AddPos(float x, float y, float z) - { - v1.X += x; - v2.X += x; - v3.X += x; - - v1.Y += y; - v2.Y += y; - v3.Y += y; - - v1.Z += z; - v2.Z += z; - v3.Z += z; - } - - public void AddRot(Quat q) - { - v1 *= q; - v2 *= q; - v3 *= q; - - n1 *= q; - n2 *= q; - n3 *= q; - } - - public void CalcSurfaceNormal() - { - var edge1 = new Coord(v2.X - v1.X, v2.Y - v1.Y, v2.Z - v1.Z); - var edge2 = new Coord(v3.X - v1.X, v3.Y - v1.Y, v3.Z - v1.Z); - - n1 = n2 = n3 = Coord.Cross(edge1, edge2).Normalize(); - } - } - - internal struct Angle - { - internal float angle; - internal float X; - internal float Y; - - internal Angle(float angle, float x, float y) - { - this.angle = angle; - X = x; - Y = y; - } - } - - internal class AngleList - { - private static readonly Angle[] angles3 = - { - new Angle(0.0f, 1.0f, 0.0f), - new Angle(0.33333333333333333f, -0.5f, 0.86602540378443871f), - new Angle(0.66666666666666667f, -0.5f, -0.86602540378443837f), - new Angle(1.0f, 1.0f, 0.0f) - }; - - private static readonly Coord[] normals3 = - { - new Coord(0.25f, 0.4330127019f, 0.0f).Normalize(), - new Coord(-0.5f, 0.0f, 0.0f).Normalize(), - new Coord(0.25f, -0.4330127019f, 0.0f).Normalize(), - new Coord(0.25f, 0.4330127019f, 0.0f).Normalize() - }; - - private static readonly Angle[] angles4 = - { - new Angle(0.0f, 1.0f, 0.0f), - new Angle(0.25f, 0.0f, 1.0f), - new Angle(0.5f, -1.0f, 0.0f), - new Angle(0.75f, 0.0f, -1.0f), - new Angle(1.0f, 1.0f, 0.0f) - }; - - private static readonly Coord[] normals4 = - { - new Coord(0.5f, 0.5f, 0.0f).Normalize(), - new Coord(-0.5f, 0.5f, 0.0f).Normalize(), - new Coord(-0.5f, -0.5f, 0.0f).Normalize(), - new Coord(0.5f, -0.5f, 0.0f).Normalize(), - new Coord(0.5f, 0.5f, 0.0f).Normalize() - }; - - private static readonly Angle[] angles24 = - { - new Angle(0.0f, 1.0f, 0.0f), - new Angle(0.041666666666666664f, 0.96592582628906831f, 0.25881904510252074f), - new Angle(0.083333333333333329f, 0.86602540378443871f, 0.5f), - new Angle(0.125f, 0.70710678118654757f, 0.70710678118654746f), - new Angle(0.16666666666666667f, 0.5f, 0.8660254037844386f), - new Angle(0.20833333333333331f, 0.25881904510252096f, 0.9659258262890682f), - new Angle(0.25f, 0.0f, 1.0f), - new Angle(0.29166666666666663f, -0.25881904510252063f, 0.96592582628906831f), - new Angle(0.33333333333333333f, -0.5f, 0.86602540378443871f), - new Angle(0.375f, -0.70710678118654746f, 0.70710678118654757f), - new Angle(0.41666666666666663f, -0.86602540378443849f, 0.5f), - new Angle(0.45833333333333331f, -0.9659258262890682f, 0.25881904510252102f), - new Angle(0.5f, -1.0f, 0.0f), - new Angle(0.54166666666666663f, -0.96592582628906842f, -0.25881904510252035f), - new Angle(0.58333333333333326f, -0.86602540378443882f, -0.5f), - new Angle(0.62499999999999989f, -0.70710678118654791f, -0.70710678118654713f), - new Angle(0.66666666666666667f, -0.5f, -0.86602540378443837f), - new Angle(0.70833333333333326f, -0.25881904510252152f, -0.96592582628906809f), - new Angle(0.75f, 0.0f, -1.0f), - new Angle(0.79166666666666663f, 0.2588190451025203f, -0.96592582628906842f), - new Angle(0.83333333333333326f, 0.5f, -0.86602540378443904f), - new Angle(0.875f, 0.70710678118654735f, -0.70710678118654768f), - new Angle(0.91666666666666663f, 0.86602540378443837f, -0.5f), - new Angle(0.95833333333333326f, 0.96592582628906809f, -0.25881904510252157f), - new Angle(1.0f, 1.0f, 0.0f) - }; - - internal List angles; - private float iX, iY; // intersection point - internal List normals; - - private Angle interpolatePoints(float newPoint, Angle p1, Angle p2) - { - var m = (newPoint - p1.angle) / (p2.angle - p1.angle); - return new Angle(newPoint, p1.X + m * (p2.X - p1.X), p1.Y + m * (p2.Y - p1.Y)); - } - - private void intersection(double x1, double y1, double x2, double y2, double x3, double y3, double x4, - double y4) - { - // ref: http://local.wasp.uwa.edu.au/~pbourke/geometry/lineline2d/ - var denom = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1); - var uaNumerator = (x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3); - - if (denom != 0.0) - { - var ua = uaNumerator / denom; - iX = (float) (x1 + ua * (x2 - x1)); - iY = (float) (y1 + ua * (y2 - y1)); - } - } - - internal void makeAngles(int sides, float startAngle, float stopAngle) - { - angles = new List(); - normals = new List(); - - var twoPi = Math.PI * 2.0; - var twoPiInv = 1.0f / (float) twoPi; - - if (sides < 1) - throw new Exception("number of sides not greater than zero"); - if (stopAngle <= startAngle) - throw new Exception("stopAngle not greater than startAngle"); - - if (sides == 3 || sides == 4 || sides == 24) - { - startAngle *= twoPiInv; - stopAngle *= twoPiInv; - - Angle[] sourceAngles; - if (sides == 3) - sourceAngles = angles3; - else if (sides == 4) - sourceAngles = angles4; - else sourceAngles = angles24; - - var startAngleIndex = (int) (startAngle * sides); - var endAngleIndex = sourceAngles.Length - 1; - if (stopAngle < 1.0f) - endAngleIndex = (int) (stopAngle * sides) + 1; - if (endAngleIndex == startAngleIndex) - endAngleIndex++; - - for (var angleIndex = startAngleIndex; angleIndex < endAngleIndex + 1; angleIndex++) - { - angles.Add(sourceAngles[angleIndex]); - if (sides == 3) - normals.Add(normals3[angleIndex]); - else if (sides == 4) - normals.Add(normals4[angleIndex]); - } - - if (startAngle > 0.0f) - angles[0] = interpolatePoints(startAngle, angles[0], angles[1]); - - if (stopAngle < 1.0f) - { - var lastAngleIndex = angles.Count - 1; - angles[lastAngleIndex] = - interpolatePoints(stopAngle, angles[lastAngleIndex - 1], angles[lastAngleIndex]); - } - } - else - { - var stepSize = twoPi / sides; - - var startStep = (int) (startAngle / stepSize); - var angle = stepSize * startStep; - var step = startStep; - double stopAngleTest = stopAngle; - if (stopAngle < twoPi) - { - stopAngleTest = stepSize * ((int) (stopAngle / stepSize) + 1); - if (stopAngleTest < stopAngle) - stopAngleTest += stepSize; - if (stopAngleTest > twoPi) - stopAngleTest = twoPi; - } - - while (angle <= stopAngleTest) - { - Angle newAngle; - newAngle.angle = (float) angle; - newAngle.X = (float) Math.Cos(angle); - newAngle.Y = (float) Math.Sin(angle); - angles.Add(newAngle); - step += 1; - angle = stepSize * step; - } - - if (startAngle > angles[0].angle) - { - Angle newAngle; - intersection(angles[0].X, angles[0].Y, angles[1].X, angles[1].Y, 0.0f, 0.0f, - (float) Math.Cos(startAngle), (float) Math.Sin(startAngle)); - newAngle.angle = startAngle; - newAngle.X = iX; - newAngle.Y = iY; - angles[0] = newAngle; - } - - var index = angles.Count - 1; - if (stopAngle < angles[index].angle) - { - Angle newAngle; - intersection(angles[index - 1].X, angles[index - 1].Y, angles[index].X, angles[index].Y, 0.0f, 0.0f, - (float) Math.Cos(stopAngle), (float) Math.Sin(stopAngle)); - newAngle.angle = stopAngle; - newAngle.X = iX; - newAngle.Y = iY; - angles[index] = newAngle; - } - } - } - } - - /// - /// generates a profile for extrusion - /// - public class Profile - { - private const float twoPi = 2.0f * (float) Math.PI; - public int bottomFaceNumber; - - public bool calcVertexNormals; - - public List coords; - public List cut1CoordIndices; - public List cut2CoordIndices; - public Coord cutNormal1; - public Coord cutNormal2; - - public string errorMessage; - - public Coord faceNormal = new Coord(0.0f, 0.0f, 1.0f); - public List faceNumbers; - public List faces; - public List faceUVs; - public List hollowCoordIndices; - public int hollowFaceNumber = -1; - public int numHollowVerts; - - public int numOuterVerts; - public int numPrimFaces; - - // use these for making individual meshes for each prim face - public List outerCoordIndices; - - public int outerFaceNumber = -1; - public List us; - public List vertexNormals; - - public Profile() - { - coords = new List(); - faces = new List(); - vertexNormals = new List(); - us = new List(); - faceUVs = new List(); - faceNumbers = new List(); - } - - public Profile(int sides, float profileStart, float profileEnd, float hollow, int hollowSides, bool createFaces, - bool calcVertexNormals) - { - this.calcVertexNormals = calcVertexNormals; - coords = new List(); - faces = new List(); - vertexNormals = new List(); - us = new List(); - faceUVs = new List(); - faceNumbers = new List(); - - var center = new Coord(0.0f, 0.0f, 0.0f); - - var hollowCoords = new List(); - var hollowNormals = new List(); - var hollowUs = new List(); - - if (calcVertexNormals) - { - outerCoordIndices = new List(); - hollowCoordIndices = new List(); - cut1CoordIndices = new List(); - cut2CoordIndices = new List(); - } - - var hasHollow = hollow > 0.0f; - - var hasProfileCut = profileStart > 0.0f || profileEnd < 1.0f; - - var angles = new AngleList(); - var hollowAngles = new AngleList(); - - var xScale = 0.5f; - var yScale = 0.5f; - if (sides == 4) // corners of a square are sqrt(2) from center - { - xScale = 0.707107f; - yScale = 0.707107f; - } - - var startAngle = profileStart * twoPi; - var stopAngle = profileEnd * twoPi; - - try - { - angles.makeAngles(sides, startAngle, stopAngle); - } - catch (Exception ex) - { - errorMessage = "makeAngles failed: Exception: " + ex - + "\nsides: " + sides + " startAngle: " + startAngle + " stopAngle: " + stopAngle; - - return; - } - - numOuterVerts = angles.angles.Count; - - // flag to create as few triangles as possible for 3 or 4 side profile - var simpleFace = sides < 5 && !hasHollow && !hasProfileCut; - - if (hasHollow) - { - if (sides == hollowSides) - hollowAngles = angles; - else - try - { - hollowAngles.makeAngles(hollowSides, startAngle, stopAngle); - } - catch (Exception ex) - { - errorMessage = "makeAngles failed: Exception: " + ex - + "\nsides: " + sides + " startAngle: " + startAngle + " stopAngle: " + - stopAngle; - - return; - } - numHollowVerts = hollowAngles.angles.Count; - } - else if (!simpleFace) - { - coords.Add(center); - if (this.calcVertexNormals) - vertexNormals.Add(new Coord(0.0f, 0.0f, 1.0f)); - us.Add(0.0f); - } - - var z = 0.0f; - - Angle angle; - var newVert = new Coord(); - if (hasHollow && hollowSides != sides) - { - var numHollowAngles = hollowAngles.angles.Count; - for (var i = 0; i < numHollowAngles; i++) - { - angle = hollowAngles.angles[i]; - newVert.X = hollow * xScale * angle.X; - newVert.Y = hollow * yScale * angle.Y; - newVert.Z = z; - - hollowCoords.Add(newVert); - if (this.calcVertexNormals) - { - hollowNormals.Add(hollowSides < 5 - ? hollowAngles.normals[i].Invert() - : new Coord(-angle.X, -angle.Y, 0.0f)); - - if (hollowSides == 4) - hollowUs.Add(angle.angle * hollow * 0.707107f); - else - hollowUs.Add(angle.angle * hollow); - } - } - } - - var index = 0; - var numAngles = angles.angles.Count; - - for (var i = 0; i < numAngles; i++) - { - angle = angles.angles[i]; - newVert.X = angle.X * xScale; - newVert.Y = angle.Y * yScale; - newVert.Z = z; - coords.Add(newVert); - if (this.calcVertexNormals) - { - outerCoordIndices.Add(coords.Count - 1); - - if (sides < 5) - { - vertexNormals.Add(angles.normals[i]); - var u = angle.angle; - us.Add(u); - } - else - { - vertexNormals.Add(new Coord(angle.X, angle.Y, 0.0f)); - us.Add(angle.angle); - } - } - - if (hasHollow) - { - if (hollowSides == sides) - { - newVert.X *= hollow; - newVert.Y *= hollow; - newVert.Z = z; - hollowCoords.Add(newVert); - if (this.calcVertexNormals) - { - hollowNormals.Add(sides < 5 - ? angles.normals[i].Invert() - : new Coord(-angle.X, -angle.Y, 0.0f)); - - hollowUs.Add(angle.angle * hollow); - } - } - } - else if (!simpleFace && createFaces && angle.angle > 0.0001f) - { - var newFace = new Face - { - v1 = 0, - v2 = index, - v3 = index + 1 - }; - - faces.Add(newFace); - } - index += 1; - } - - if (hasHollow) - { - hollowCoords.Reverse(); - if (this.calcVertexNormals) - { - hollowNormals.Reverse(); - hollowUs.Reverse(); - } - - if (createFaces) - { - var numTotalVerts = numOuterVerts + numHollowVerts; - - if (numOuterVerts == numHollowVerts) - { - var newFace = new Face(); - - for (var coordIndex = 0; coordIndex < numOuterVerts - 1; coordIndex++) - { - newFace.v1 = coordIndex; - newFace.v2 = coordIndex + 1; - newFace.v3 = numTotalVerts - coordIndex - 1; - faces.Add(newFace); - - newFace.v1 = coordIndex + 1; - newFace.v2 = numTotalVerts - coordIndex - 2; - newFace.v3 = numTotalVerts - coordIndex - 1; - faces.Add(newFace); - } - } - else - { - if (numOuterVerts < numHollowVerts) - { - var newFace = new Face(); - var j = 0; // j is the index for outer vertices - var maxJ = numOuterVerts - 1; - for (var i = 0; i < numHollowVerts; i++) // i is the index for inner vertices - { - if (j < maxJ) - if (angles.angles[j + 1].angle - hollowAngles.angles[i].angle < - hollowAngles.angles[i].angle - angles.angles[j].angle + 0.000001f) - { - newFace.v1 = numTotalVerts - i - 1; - newFace.v2 = j; - newFace.v3 = j + 1; - - faces.Add(newFace); - j += 1; - } - - newFace.v1 = j; - newFace.v2 = numTotalVerts - i - 2; - newFace.v3 = numTotalVerts - i - 1; - - faces.Add(newFace); - } - } - else // numHollowVerts < numOuterVerts - { - var newFace = new Face(); - var j = 0; // j is the index for inner vertices - var maxJ = numHollowVerts - 1; - for (var i = 0; i < numOuterVerts; i++) - { - if (j < maxJ) - if (hollowAngles.angles[j + 1].angle - angles.angles[i].angle < - angles.angles[i].angle - hollowAngles.angles[j].angle + 0.000001f) - { - newFace.v1 = i; - newFace.v2 = numTotalVerts - j - 2; - newFace.v3 = numTotalVerts - j - 1; - - faces.Add(newFace); - j += 1; - } - - newFace.v1 = numTotalVerts - j - 1; - newFace.v2 = i; - newFace.v3 = i + 1; - - faces.Add(newFace); - } - } - } - } - - if (calcVertexNormals) - foreach (var hc in hollowCoords) - { - coords.Add(hc); - hollowCoordIndices.Add(coords.Count - 1); - } - else - coords.AddRange(hollowCoords); - - if (this.calcVertexNormals) - { - vertexNormals.AddRange(hollowNormals); - us.AddRange(hollowUs); - } - } - - if (simpleFace && createFaces) - if (sides == 3) - { - faces.Add(new Face(0, 1, 2)); - } - else if (sides == 4) - { - faces.Add(new Face(0, 1, 2)); - faces.Add(new Face(0, 2, 3)); - } - - if (calcVertexNormals && hasProfileCut) - { - var lastOuterVertIndex = numOuterVerts - 1; - - if (hasHollow) - { - cut1CoordIndices.Add(0); - cut1CoordIndices.Add(coords.Count - 1); - - cut2CoordIndices.Add(lastOuterVertIndex + 1); - cut2CoordIndices.Add(lastOuterVertIndex); - - cutNormal1.X = coords[0].Y - coords[coords.Count - 1].Y; - cutNormal1.Y = -(coords[0].X - coords[coords.Count - 1].X); - - cutNormal2.X = coords[lastOuterVertIndex + 1].Y - coords[lastOuterVertIndex].Y; - cutNormal2.Y = -(coords[lastOuterVertIndex + 1].X - coords[lastOuterVertIndex].X); - } - - else - { - cut1CoordIndices.Add(0); - cut1CoordIndices.Add(1); - - cut2CoordIndices.Add(lastOuterVertIndex); - cut2CoordIndices.Add(0); - - cutNormal1.X = vertexNormals[1].Y; - cutNormal1.Y = -vertexNormals[1].X; - - cutNormal2.X = -vertexNormals[vertexNormals.Count - 2].Y; - cutNormal2.Y = vertexNormals[vertexNormals.Count - 2].X; - } - cutNormal1.Normalize(); - cutNormal2.Normalize(); - } - - MakeFaceUVs(); - - hollowCoords = null; - hollowNormals = null; - hollowUs = null; - - if (calcVertexNormals) - { - // calculate prim face numbers - - // face number order is top, outer, hollow, bottom, start cut, end cut - // I know it's ugly but so is the whole concept of prim face numbers - - var faceNum = 1; // start with outer faces - outerFaceNumber = faceNum; - - var startVert = hasProfileCut && !hasHollow ? 1 : 0; - if (startVert > 0) - faceNumbers.Add(-1); - for (var i = 0; i < numOuterVerts - 1; i++) - faceNumbers.Add(sides < 5 && i <= sides ? faceNum++ : faceNum); - - faceNumbers.Add(hasProfileCut ? -1 : faceNum++); - - if (sides > 4 && (hasHollow || hasProfileCut)) - faceNum++; - - if (sides < 5 && (hasHollow || hasProfileCut) && numOuterVerts < sides) - faceNum++; - - if (hasHollow) - { - for (var i = 0; i < numHollowVerts; i++) - faceNumbers.Add(faceNum); - - hollowFaceNumber = faceNum++; - } - - bottomFaceNumber = faceNum++; - - if (hasHollow && hasProfileCut) - faceNumbers.Add(faceNum++); - - for (var i = 0; i < faceNumbers.Count; i++) - if (faceNumbers[i] == -1) - faceNumbers[i] = faceNum++; - - numPrimFaces = faceNum; - } - } - - public void MakeFaceUVs() - { - faceUVs = new List(); - foreach (var c in coords) - faceUVs.Add(new UVCoord(1.0f - (0.5f + c.X), 1.0f - (0.5f - c.Y))); - } - - public Profile Copy() - { - return Copy(true); - } - - public Profile Copy(bool needFaces) - { - var copy = new Profile(); - - copy.coords.AddRange(coords); - copy.faceUVs.AddRange(faceUVs); - - if (needFaces) - copy.faces.AddRange(faces); - if (copy.calcVertexNormals = calcVertexNormals) - { - copy.vertexNormals.AddRange(vertexNormals); - copy.faceNormal = faceNormal; - copy.cutNormal1 = cutNormal1; - copy.cutNormal2 = cutNormal2; - copy.us.AddRange(us); - copy.faceNumbers.AddRange(faceNumbers); - - copy.cut1CoordIndices = new List(cut1CoordIndices); - copy.cut2CoordIndices = new List(cut2CoordIndices); - copy.hollowCoordIndices = new List(hollowCoordIndices); - copy.outerCoordIndices = new List(outerCoordIndices); - } - copy.numOuterVerts = numOuterVerts; - copy.numHollowVerts = numHollowVerts; - - return copy; - } - - public void AddPos(Coord v) - { - AddPos(v.X, v.Y, v.Z); - } - - public void AddPos(float x, float y, float z) - { - int i; - var numVerts = coords.Count; - Coord vert; - - for (i = 0; i < numVerts; i++) - { - vert = coords[i]; - vert.X += x; - vert.Y += y; - vert.Z += z; - coords[i] = vert; - } - } - - public void AddRot(Quat q) - { - int i; - var numVerts = coords.Count; - - for (i = 0; i < numVerts; i++) - coords[i] *= q; - - if (calcVertexNormals) - { - var numNormals = vertexNormals.Count; - for (i = 0; i < numNormals; i++) - vertexNormals[i] *= q; - - faceNormal *= q; - cutNormal1 *= q; - cutNormal2 *= q; - } - } - - public void Scale(float x, float y) - { - int i; - var numVerts = coords.Count; - Coord vert; - - for (i = 0; i < numVerts; i++) - { - vert = coords[i]; - vert.X *= x; - vert.Y *= y; - coords[i] = vert; - } - } - - /// - /// Changes order of the vertex indices and negates the center vertex normal. Does not alter vertex normals of radial - /// vertices - /// - public void FlipNormals() - { - int i; - var numFaces = faces.Count; - Face tmpFace; - int tmp; - - for (i = 0; i < numFaces; i++) - { - tmpFace = faces[i]; - tmp = tmpFace.v3; - tmpFace.v3 = tmpFace.v1; - tmpFace.v1 = tmp; - faces[i] = tmpFace; - } - - if (calcVertexNormals) - { - var normalCount = vertexNormals.Count; - if (normalCount > 0) - { - var n = vertexNormals[normalCount - 1]; - n.Z = -n.Z; - vertexNormals[normalCount - 1] = n; - } - } - - faceNormal.X = -faceNormal.X; - faceNormal.Y = -faceNormal.Y; - faceNormal.Z = -faceNormal.Z; - - var numfaceUVs = faceUVs.Count; - for (i = 0; i < numfaceUVs; i++) - { - var uv = faceUVs[i]; - uv.V = 1.0f - uv.V; - faceUVs[i] = uv; - } - } - - public void AddValue2FaceVertexIndices(int num) - { - var numFaces = faces.Count; - Face tmpFace; - for (var i = 0; i < numFaces; i++) - { - tmpFace = faces[i]; - tmpFace.v1 += num; - tmpFace.v2 += num; - tmpFace.v3 += num; - - faces[i] = tmpFace; - } - } - - public void AddValue2FaceNormalIndices(int num) - { - if (calcVertexNormals) - { - var numFaces = faces.Count; - Face tmpFace; - for (var i = 0; i < numFaces; i++) - { - tmpFace = faces[i]; - tmpFace.n1 += num; - tmpFace.n2 += num; - tmpFace.n3 += num; - - faces[i] = tmpFace; - } - } - } - - public void DumpRaw(string path, string name, string title) - { - if (path == null) - return; - var fileName = name + "_" + title + ".raw"; - var completePath = System.IO.Path.Combine(path, fileName); - var sw = new StreamWriter(completePath); - - for (var i = 0; i < faces.Count; i++) - { - var s = coords[faces[i].v1].ToString(); - s += " " + coords[faces[i].v2]; - s += " " + coords[faces[i].v3]; - - sw.WriteLine(s); - } - - sw.Close(); - } - } - - public struct PathNode - { - public Coord position; - public Quat rotation; - public float xScale; - public float yScale; - public float percentOfPath; - } - - public enum PathType - { - Linear = 0, - Circular = 1, - Flexible = 2 - } - - public class Path - { - private const float twoPi = 2.0f * (float) Math.PI; - public float dimpleBegin; - public float dimpleEnd = 1.0f; - public float holeSizeX = 1.0f; // called pathScaleX in pbs - public float holeSizeY = 0.25f; - public float pathCutBegin; - public float pathCutEnd = 1.0f; - public List pathNodes = new List(); - public float radius; - public float revolutions = 1.0f; - public float skew; - public int stepsPerRevolution = 24; - public float taperX; - public float taperY; - public float topShearX; - public float topShearY; - - public float twistBegin; - public float twistEnd; - - public void Create(PathType pathType, int steps) - { - if (taperX > 0.999f) - taperX = 0.999f; - if (taperX < -0.999f) - taperX = -0.999f; - if (taperY > 0.999f) - taperY = 0.999f; - if (taperY < -0.999f) - taperY = -0.999f; - - if (pathType == PathType.Linear || pathType == PathType.Flexible) - { - var step = 0; - - var length = pathCutEnd - pathCutBegin; - var twistTotal = twistEnd - twistBegin; - var twistTotalAbs = Math.Abs(twistTotal); - if (twistTotalAbs > 0.01f) - steps += (int) (twistTotalAbs * 3.66); // dahlia's magic number - - var start = -0.5f; - var stepSize = length / steps; - var percentOfPathMultiplier = stepSize * 0.999999f; - var xOffset = topShearX * pathCutBegin; - var yOffset = topShearY * pathCutBegin; - var zOffset = start; - var xOffsetStepIncrement = topShearX * length / steps; - var yOffsetStepIncrement = topShearY * length / steps; - - var percentOfPath = pathCutBegin; - zOffset += percentOfPath; - - // sanity checks - - var done = false; - - while (!done) - { - var newNode = new PathNode {xScale = 1.0f}; - - if (taperX == 0.0f) - newNode.xScale = 1.0f; - else if (taperX > 0.0f) - newNode.xScale = 1.0f - percentOfPath * taperX; - else newNode.xScale = 1.0f + (1.0f - percentOfPath) * taperX; - - newNode.yScale = 1.0f; - if (taperY == 0.0f) - newNode.yScale = 1.0f; - else if (taperY > 0.0f) - newNode.yScale = 1.0f - percentOfPath * taperY; - else newNode.yScale = 1.0f + (1.0f - percentOfPath) * taperY; - - var twist = twistBegin + twistTotal * percentOfPath; - - newNode.rotation = new Quat(new Coord(0.0f, 0.0f, 1.0f), twist); - newNode.position = new Coord(xOffset, yOffset, zOffset); - newNode.percentOfPath = percentOfPath; - - pathNodes.Add(newNode); - - if (step < steps) - { - step += 1; - percentOfPath += percentOfPathMultiplier; - xOffset += xOffsetStepIncrement; - yOffset += yOffsetStepIncrement; - zOffset += stepSize; - if (percentOfPath > pathCutEnd) - done = true; - } - else - { - done = true; - } - } - } // end of linear path code - - else // pathType == Circular - { - var twistTotal = twistEnd - twistBegin; - - // if the profile has a lot of twist, add more layers otherwise the layers may overlap - // and the resulting mesh may be quite inaccurate. This method is arbitrary and doesn't - // accurately match the viewer - var twistTotalAbs = Math.Abs(twistTotal); - if (twistTotalAbs > 0.01f) - { - if (twistTotalAbs > Math.PI * 1.5f) - steps *= 2; - if (twistTotalAbs > Math.PI * 3.0f) - steps *= 2; - } - - var yPathScale = holeSizeY * 0.5f; - var pathLength = pathCutEnd - pathCutBegin; - var totalSkew = skew * 2.0f * pathLength; - var skewStart = pathCutBegin * 2.0f * skew - skew; - var xOffsetTopShearXFactor = topShearX * (0.25f + 0.5f * (0.5f - holeSizeY)); - var yShearCompensation = 1.0f + Math.Abs(topShearY) * 0.25f; - - // It's not quite clear what pushY (Y top shear) does, but subtracting it from the start and end - // angles appears to approximate it's effects on path cut. Likewise, adding it to the angle used - // to calculate the sine for generating the path radius appears to approximate it's effects there - // too, but there are some subtle differences in the radius which are noticeable as the prim size - // increases and it may affect megaprims quite a bit. The effect of the Y top shear parameter on - // the meshes generated with this technique appear nearly identical in shape to the same prims when - // displayed by the viewer. - - var startAngle = twoPi * pathCutBegin * revolutions - topShearY * 0.9f; - var endAngle = twoPi * pathCutEnd * revolutions - topShearY * 0.9f; - var stepSize = twoPi / stepsPerRevolution; - - var step = (int) (startAngle / stepSize); - var angle = startAngle; - - var done = false; - while (!done) // loop through the length of the path and add the layers - { - var newNode = new PathNode(); - - var xProfileScale = (1.0f - Math.Abs(skew)) * holeSizeX; - var yProfileScale = holeSizeY; - - var percentOfPath = angle / (twoPi * revolutions); - var percentOfAngles = (angle - startAngle) / (endAngle - startAngle); - - if (taperX > 0.01f) - xProfileScale *= 1.0f - percentOfPath * taperX; - else if (taperX < -0.01f) - xProfileScale *= 1.0f + (1.0f - percentOfPath) * taperX; - - if (taperY > 0.01f) - yProfileScale *= 1.0f - percentOfPath * taperY; - else if (taperY < -0.01f) - yProfileScale *= 1.0f + (1.0f - percentOfPath) * taperY; - - newNode.xScale = xProfileScale; - newNode.yScale = yProfileScale; - - var radiusScale = 1.0f; - if (radius > 0.001f) - radiusScale = 1.0f - radius * percentOfPath; - else if (radius < 0.001f) - radiusScale = 1.0f + radius * (1.0f - percentOfPath); - - var twist = twistBegin + twistTotal * percentOfPath; - - var xOffset = 0.5f * (skewStart + totalSkew * percentOfAngles); - xOffset += (float) Math.Sin(angle) * xOffsetTopShearXFactor; - - var yOffset = yShearCompensation * (float) Math.Cos(angle) * (0.5f - yPathScale) * radiusScale; - - var zOffset = (float) Math.Sin(angle + topShearY) * (0.5f - yPathScale) * radiusScale; - - newNode.position = new Coord(xOffset, yOffset, zOffset); - - // now orient the rotation of the profile layer relative to it's position on the path - // adding taperY to the angle used to generate the quat appears to approximate the viewer - - newNode.rotation = new Quat(new Coord(1.0f, 0.0f, 0.0f), angle + topShearY); - - // next apply twist rotation to the profile layer - if (twistTotal != 0.0f || twistBegin != 0.0f) - newNode.rotation *= new Quat(new Coord(0.0f, 0.0f, 1.0f), twist); - - newNode.percentOfPath = percentOfPath; - - pathNodes.Add(newNode); - - // calculate terms for next iteration - // calculate the angle for the next iteration of the loop - - if (angle >= endAngle - 0.01) - { - done = true; - } - else - { - step += 1; - angle = stepSize * step; - if (angle > endAngle) - angle = endAngle; - } - } - } - } - } - - public class PrimMesh - { - private const float twoPi = 2.0f * (float) Math.PI; - public bool calcVertexNormals; - - public List coords; - public float dimpleBegin; - public float dimpleEnd = 1.0f; - public string errorMessage = ""; - public List faces; - - public float holeSizeX = 1.0f; // called pathScaleX in pbs - public float holeSizeY = 0.25f; - private readonly float hollow; - private readonly int hollowSides = 4; - public List normals; - private bool normalsProcessed; - - public int numPrimFaces; - public float pathCutBegin; - public float pathCutEnd = 1.0f; - private readonly float profileEnd = 1.0f; - - private readonly float profileStart; - public float radius; - public float revolutions = 1.0f; - - private readonly int sides = 4; - public float skew; - public bool sphereMode = false; - public int stepsPerRevolution = 24; - public float taperX; - public float taperY; - public float topShearX; - public float topShearY; - public int twistBegin; - public int twistEnd; - - public List viewerFaces; - public bool viewerMode; - - - /// - /// Constructs a PrimMesh object and creates the profile for extrusion. - /// - /// - /// - /// - /// - /// - public PrimMesh(int sides, float profileStart, float profileEnd, float hollow, int hollowSides) - { - coords = new List(); - faces = new List(); - - this.sides = sides; - this.profileStart = profileStart; - this.profileEnd = profileEnd; - this.hollow = hollow; - this.hollowSides = hollowSides; - - if (sides < 3) - this.sides = 3; - if (hollowSides < 3) - this.hollowSides = 3; - if (profileStart < 0.0f) - this.profileStart = 0.0f; - if (profileEnd > 1.0f) - this.profileEnd = 1.0f; - if (profileEnd < 0.02f) - this.profileEnd = 0.02f; - if (profileStart >= profileEnd) - this.profileStart = profileEnd - 0.02f; - if (hollow > 0.99f) - this.hollow = 0.99f; - if (hollow < 0.0f) - this.hollow = 0.0f; - } - - public int ProfileOuterFaceNumber { get; private set; } = -1; - - public int ProfileHollowFaceNumber { get; private set; } = -1; - - public bool HasProfileCut { get; private set; } - - public bool HasHollow { get; private set; } - - /// - /// Human readable string representation of the parameters used to create a mesh. - /// - /// - public string ParamsToDisplayString() - { - var s = ""; - s += "sides..................: " + sides; - s += "\nhollowSides..........: " + hollowSides; - s += "\nprofileStart.........: " + profileStart; - s += "\nprofileEnd...........: " + profileEnd; - s += "\nhollow...............: " + hollow; - s += "\ntwistBegin...........: " + twistBegin; - s += "\ntwistEnd.............: " + twistEnd; - s += "\ntopShearX............: " + topShearX; - s += "\ntopShearY............: " + topShearY; - s += "\npathCutBegin.........: " + pathCutBegin; - s += "\npathCutEnd...........: " + pathCutEnd; - s += "\ndimpleBegin..........: " + dimpleBegin; - s += "\ndimpleEnd............: " + dimpleEnd; - s += "\nskew.................: " + skew; - s += "\nholeSizeX............: " + holeSizeX; - s += "\nholeSizeY............: " + holeSizeY; - s += "\ntaperX...............: " + taperX; - s += "\ntaperY...............: " + taperY; - s += "\nradius...............: " + radius; - s += "\nrevolutions..........: " + revolutions; - s += "\nstepsPerRevolution...: " + stepsPerRevolution; - s += "\nsphereMode...........: " + sphereMode; - s += "\nhasProfileCut........: " + HasProfileCut; - s += "\nhasHollow............: " + HasHollow; - s += "\nviewerMode...........: " + viewerMode; - - return s; - } - - /// - /// Extrudes a profile along a path. - /// - public void Extrude(PathType pathType) - { - var needEndFaces = false; - - coords = new List(); - this.faces = new List(); - - if (viewerMode) - { - viewerFaces = new List(); - calcVertexNormals = true; - } - - if (calcVertexNormals) - normals = new List(); - - var steps = 1; - - var length = pathCutEnd - pathCutBegin; - normalsProcessed = false; - - if (viewerMode && sides == 3) - if (Math.Abs(taperX) > 0.01 || Math.Abs(taperY) > 0.01) - steps = (int) (steps * 4.5 * length); - - if (sphereMode) - HasProfileCut = profileEnd - profileStart < 0.4999f; - else - HasProfileCut = profileEnd - profileStart < 0.9999f; - HasHollow = this.hollow > 0.001f; - - var twistBegin = this.twistBegin / 360.0f * twoPi; - var twistEnd = this.twistEnd / 360.0f * twoPi; - var twistTotal = twistEnd - twistBegin; - var twistTotalAbs = Math.Abs(twistTotal); - if (twistTotalAbs > 0.01f) - steps += (int) (twistTotalAbs * 3.66); // dahlia's magic number - - var hollow = this.hollow; - - if (pathType == PathType.Circular) - { - needEndFaces = false; - if (pathCutBegin != 0.0f || pathCutEnd != 1.0f) - needEndFaces = true; - else if (taperX != 0.0f || taperY != 0.0f) - needEndFaces = true; - else if (skew != 0.0f) - needEndFaces = true; - else if (twistTotal != 0.0f) - needEndFaces = true; - else if (radius != 0.0f) - needEndFaces = true; - } - else - { - needEndFaces = true; - } - - // sanity checks - var initialProfileRot = 0.0f; - if (pathType == PathType.Circular) - { - switch (sides) - { - case 3: - initialProfileRot = (float) Math.PI; - if (hollowSides == 4) - { - if (hollow > 0.7f) - hollow = 0.7f; - hollow *= 0.707f; - } - else - { - hollow *= 0.5f; - } - break; - case 4: - initialProfileRot = 0.25f * (float) Math.PI; - if (hollowSides != 4) - hollow *= 0.707f; - break; - default: - if (sides > 4) - { - initialProfileRot = (float) Math.PI; - if (hollowSides == 4) - { - if (hollow > 0.7f) - hollow = 0.7f; - hollow /= 0.7f; - } - } - break; - } - } - else - { - switch (sides) - { - case 3: - if (hollowSides == 4) - { - if (hollow > 0.7f) - hollow = 0.7f; - hollow *= 0.707f; - } - else - { - hollow *= 0.5f; - } - break; - case 4: - initialProfileRot = 1.25f * (float) Math.PI; - if (hollowSides != 4) - hollow *= 0.707f; - break; - case 24 when hollowSides == 4: - hollow *= 1.414f; - break; - } - } - - var profile = new Profile(sides, profileStart, profileEnd, hollow, hollowSides, true, calcVertexNormals); - errorMessage = profile.errorMessage; - - numPrimFaces = profile.numPrimFaces; - - var cut1FaceNumber = profile.bottomFaceNumber + 1; - var cut2FaceNumber = cut1FaceNumber + 1; - if (!needEndFaces) - { - cut1FaceNumber -= 2; - cut2FaceNumber -= 2; - } - - ProfileOuterFaceNumber = profile.outerFaceNumber; - if (!needEndFaces) - ProfileOuterFaceNumber--; - - if (HasHollow) - { - ProfileHollowFaceNumber = profile.hollowFaceNumber; - if (!needEndFaces) - ProfileHollowFaceNumber--; - } - - var cut1Vert = -1; - var cut2Vert = -1; - if (HasProfileCut) - { - cut1Vert = HasHollow ? profile.coords.Count - 1 : 0; - cut2Vert = HasHollow ? profile.numOuterVerts - 1 : profile.numOuterVerts; - } - - if (initialProfileRot != 0.0f) - { - profile.AddRot(new Quat(new Coord(0.0f, 0.0f, 1.0f), initialProfileRot)); - if (viewerMode) - profile.MakeFaceUVs(); - } - - var lastCutNormal1 = new Coord(); - var lastCutNormal2 = new Coord(); - var thisV = 0.0f; - var lastV = 0.0f; - - var path = new Path - { - twistBegin = twistBegin, - twistEnd = twistEnd, - topShearX = topShearX, - topShearY = topShearY, - pathCutBegin = pathCutBegin, - pathCutEnd = pathCutEnd, - dimpleBegin = dimpleBegin, - dimpleEnd = dimpleEnd, - skew = skew, - holeSizeX = holeSizeX, - holeSizeY = holeSizeY, - taperX = taperX, - taperY = taperY, - radius = radius, - revolutions = revolutions, - stepsPerRevolution = stepsPerRevolution - }; - - path.Create(pathType, steps); - - for (var nodeIndex = 0; nodeIndex < path.pathNodes.Count; nodeIndex++) - { - var node = path.pathNodes[nodeIndex]; - var newLayer = profile.Copy(); - newLayer.Scale(node.xScale, node.yScale); - - newLayer.AddRot(node.rotation); - newLayer.AddPos(node.position); - - if (needEndFaces && nodeIndex == 0) - { - newLayer.FlipNormals(); - - // add the bottom faces to the viewerFaces list - if (viewerMode) - { - var faceNormal = newLayer.faceNormal; - var newViewerFace = new ViewerFace(profile.bottomFaceNumber); - var numFaces = newLayer.faces.Count; - var faces = newLayer.faces; - - for (var i = 0; i < numFaces; i++) - { - var face = faces[i]; - newViewerFace.v1 = newLayer.coords[face.v1]; - newViewerFace.v2 = newLayer.coords[face.v2]; - newViewerFace.v3 = newLayer.coords[face.v3]; - - newViewerFace.coordIndex1 = face.v1; - newViewerFace.coordIndex2 = face.v2; - newViewerFace.coordIndex3 = face.v3; - - newViewerFace.n1 = faceNormal; - newViewerFace.n2 = faceNormal; - newViewerFace.n3 = faceNormal; - - newViewerFace.uv1 = newLayer.faceUVs[face.v1]; - newViewerFace.uv2 = newLayer.faceUVs[face.v2]; - newViewerFace.uv3 = newLayer.faceUVs[face.v3]; - - if (pathType == PathType.Linear) - { - newViewerFace.uv1.Flip(); - newViewerFace.uv2.Flip(); - newViewerFace.uv3.Flip(); - } - - viewerFaces.Add(newViewerFace); - } - } - } // if (nodeIndex == 0) - - // append this layer - - var coordsLen = coords.Count; - newLayer.AddValue2FaceVertexIndices(coordsLen); - - coords.AddRange(newLayer.coords); - - if (calcVertexNormals) - { - newLayer.AddValue2FaceNormalIndices(normals.Count); - normals.AddRange(newLayer.vertexNormals); - } - - if (node.percentOfPath < pathCutBegin + 0.01f || node.percentOfPath > pathCutEnd - 0.01f) - this.faces.AddRange(newLayer.faces); - - // fill faces between layers - - var numVerts = newLayer.coords.Count; - var newFace1 = new Face(); - var newFace2 = new Face(); - - thisV = 1.0f - node.percentOfPath; - - if (nodeIndex > 0) - { - var startVert = coordsLen + 1; - var endVert = coords.Count; - - if (sides < 5 || HasProfileCut || HasHollow) - startVert--; - - for (var i = startVert; i < endVert; i++) - { - var iNext = i + 1; - if (i == endVert - 1) - iNext = startVert; - - var whichVert = i - startVert; - - newFace1.v1 = i; - newFace1.v2 = i - numVerts; - newFace1.v3 = iNext; - - newFace1.n1 = newFace1.v1; - newFace1.n2 = newFace1.v2; - newFace1.n3 = newFace1.v3; - faces.Add(newFace1); - - newFace2.v1 = iNext; - newFace2.v2 = i - numVerts; - newFace2.v3 = iNext - numVerts; - - newFace2.n1 = newFace2.v1; - newFace2.n2 = newFace2.v2; - newFace2.n3 = newFace2.v3; - faces.Add(newFace2); - - if (viewerMode) - { - // add the side faces to the list of viewerFaces here - - var primFaceNum = profile.faceNumbers[whichVert]; - if (!needEndFaces) - primFaceNum -= 1; - - var newViewerFace1 = new ViewerFace(primFaceNum); - var newViewerFace2 = new ViewerFace(primFaceNum); - - var uIndex = whichVert; - if (!HasHollow && sides > 4 && uIndex < newLayer.us.Count - 1) - uIndex++; - - var u1 = newLayer.us[uIndex]; - var u2 = 1.0f; - if (uIndex < newLayer.us.Count - 1) - u2 = newLayer.us[uIndex + 1]; - - if (whichVert == cut1Vert || whichVert == cut2Vert) - { - u1 = 0.0f; - u2 = 1.0f; - } - else if (sides < 5) - { - if (whichVert < profile.numOuterVerts) - { - // boxes and prisms have one texture face per side of the prim, so the U values have to be scaled - // to reflect the entire texture width - u1 *= sides; - u2 *= sides; - u2 -= (int) u1; - u1 -= (int) u1; - if (u2 < 0.1f) - u2 = 1.0f; - } - } - - if (sphereMode) - if (whichVert != cut1Vert && whichVert != cut2Vert) - { - u1 = u1 * 2.0f - 1.0f; - u2 = u2 * 2.0f - 1.0f; - - if (whichVert >= newLayer.numOuterVerts) - { - u1 -= hollow; - u2 -= hollow; - } - } - - newViewerFace1.uv1.U = u1; - newViewerFace1.uv2.U = u1; - newViewerFace1.uv3.U = u2; - - newViewerFace1.uv1.V = thisV; - newViewerFace1.uv2.V = lastV; - newViewerFace1.uv3.V = thisV; - - newViewerFace2.uv1.U = u2; - newViewerFace2.uv2.U = u1; - newViewerFace2.uv3.U = u2; - - newViewerFace2.uv1.V = thisV; - newViewerFace2.uv2.V = lastV; - newViewerFace2.uv3.V = lastV; - - newViewerFace1.v1 = coords[newFace1.v1]; - newViewerFace1.v2 = coords[newFace1.v2]; - newViewerFace1.v3 = coords[newFace1.v3]; - - newViewerFace2.v1 = coords[newFace2.v1]; - newViewerFace2.v2 = coords[newFace2.v2]; - newViewerFace2.v3 = coords[newFace2.v3]; - - newViewerFace1.coordIndex1 = newFace1.v1; - newViewerFace1.coordIndex2 = newFace1.v2; - newViewerFace1.coordIndex3 = newFace1.v3; - - newViewerFace2.coordIndex1 = newFace2.v1; - newViewerFace2.coordIndex2 = newFace2.v2; - newViewerFace2.coordIndex3 = newFace2.v3; - - // profile cut faces - if (whichVert == cut1Vert) - { - newViewerFace1.primFaceNumber = cut1FaceNumber; - newViewerFace2.primFaceNumber = cut1FaceNumber; - newViewerFace1.n1 = newLayer.cutNormal1; - newViewerFace1.n2 = newViewerFace1.n3 = lastCutNormal1; - - newViewerFace2.n1 = newViewerFace2.n3 = newLayer.cutNormal1; - newViewerFace2.n2 = lastCutNormal1; - } - else if (whichVert == cut2Vert) - { - newViewerFace1.primFaceNumber = cut2FaceNumber; - newViewerFace2.primFaceNumber = cut2FaceNumber; - newViewerFace1.n1 = newLayer.cutNormal2; - newViewerFace1.n2 = lastCutNormal2; - newViewerFace1.n3 = lastCutNormal2; - - newViewerFace2.n1 = newLayer.cutNormal2; - newViewerFace2.n3 = newLayer.cutNormal2; - newViewerFace2.n2 = lastCutNormal2; - } - - else // outer and hollow faces - { - if (sides < 5 && whichVert < newLayer.numOuterVerts || - hollowSides < 5 && whichVert >= newLayer.numOuterVerts) - { - // looks terrible when path is twisted... need vertex normals here - newViewerFace1.CalcSurfaceNormal(); - newViewerFace2.CalcSurfaceNormal(); - } - else - { - newViewerFace1.n1 = normals[newFace1.n1]; - newViewerFace1.n2 = normals[newFace1.n2]; - newViewerFace1.n3 = normals[newFace1.n3]; - - newViewerFace2.n1 = normals[newFace2.n1]; - newViewerFace2.n2 = normals[newFace2.n2]; - newViewerFace2.n3 = normals[newFace2.n3]; - } - } - - viewerFaces.Add(newViewerFace1); - viewerFaces.Add(newViewerFace2); - } - } - } - - lastCutNormal1 = newLayer.cutNormal1; - lastCutNormal2 = newLayer.cutNormal2; - lastV = thisV; - - if (needEndFaces && nodeIndex == path.pathNodes.Count - 1 && viewerMode) - { - // add the top faces to the viewerFaces list here - var faceNormal = newLayer.faceNormal; - var newViewerFace = new ViewerFace(0); - var numFaces = newLayer.faces.Count; - var faces = newLayer.faces; - - for (var i = 0; i < numFaces; i++) - { - var face = faces[i]; - newViewerFace.v1 = newLayer.coords[face.v1 - coordsLen]; - newViewerFace.v2 = newLayer.coords[face.v2 - coordsLen]; - newViewerFace.v3 = newLayer.coords[face.v3 - coordsLen]; - - newViewerFace.coordIndex1 = face.v1 - coordsLen; - newViewerFace.coordIndex2 = face.v2 - coordsLen; - newViewerFace.coordIndex3 = face.v3 - coordsLen; - - newViewerFace.n1 = faceNormal; - newViewerFace.n2 = faceNormal; - newViewerFace.n3 = faceNormal; - - newViewerFace.uv1 = newLayer.faceUVs[face.v1 - coordsLen]; - newViewerFace.uv2 = newLayer.faceUVs[face.v2 - coordsLen]; - newViewerFace.uv3 = newLayer.faceUVs[face.v3 - coordsLen]; - - if (pathType == PathType.Linear) - { - newViewerFace.uv1.Flip(); - newViewerFace.uv2.Flip(); - newViewerFace.uv3.Flip(); - } - - viewerFaces.Add(newViewerFace); - } - } - } // for (int nodeIndex = 0; nodeIndex < path.pathNodes.Count; nodeIndex++) - } - - - /// - /// DEPRICATED - use Extrude(PathType.Linear) instead - /// Extrudes a profile along a straight line path. Used for prim types box, cylinder, and prism. - /// - public void ExtrudeLinear() - { - Extrude(PathType.Linear); - } - - - /// - /// DEPRICATED - use Extrude(PathType.Circular) instead - /// Extrude a profile into a circular path prim mesh. Used for prim types torus, tube, and ring. - /// - public void ExtrudeCircular() - { - Extrude(PathType.Circular); - } - - - private Coord SurfaceNormal(Coord c1, Coord c2, Coord c3) - { - var edge1 = new Coord(c2.X - c1.X, c2.Y - c1.Y, c2.Z - c1.Z); - var edge2 = new Coord(c3.X - c1.X, c3.Y - c1.Y, c3.Z - c1.Z); - - var normal = Coord.Cross(edge1, edge2); - - normal.Normalize(); - - return normal; - } - - private Coord SurfaceNormal(Face face) - { - return SurfaceNormal(coords[face.v1], coords[face.v2], coords[face.v3]); - } - - /// - /// Calculate the surface normal for a face in the list of faces - /// - /// - /// - public Coord SurfaceNormal(int faceIndex) - { - var numFaces = faces.Count; - if (faceIndex < 0 || faceIndex >= numFaces) - throw new Exception("faceIndex out of range"); - - return SurfaceNormal(faces[faceIndex]); - } - - /// - /// Duplicates a PrimMesh object. All object properties are copied by value, including lists. - /// - /// - public PrimMesh Copy() - { - var copy = new PrimMesh(sides, profileStart, profileEnd, hollow, hollowSides) - { - twistBegin = twistBegin, - twistEnd = twistEnd, - topShearX = topShearX, - topShearY = topShearY, - pathCutBegin = pathCutBegin, - pathCutEnd = pathCutEnd, - dimpleBegin = dimpleBegin, - dimpleEnd = dimpleEnd, - skew = skew, - holeSizeX = holeSizeX, - holeSizeY = holeSizeY, - taperX = taperX, - taperY = taperY, - radius = radius, - revolutions = revolutions, - stepsPerRevolution = stepsPerRevolution, - calcVertexNormals = calcVertexNormals, - normalsProcessed = normalsProcessed, - viewerMode = viewerMode, - numPrimFaces = numPrimFaces, - errorMessage = errorMessage, - coords = new List(coords), - faces = new List(faces), - viewerFaces = new List(viewerFaces), - normals = new List(normals) - }; - - - return copy; - } - - /// - /// Calculate surface normals for all of the faces in the list of faces in this mesh - /// - public void CalcNormals() - { - if (normalsProcessed) - return; - - normalsProcessed = true; - - var numFaces = faces.Count; - - if (!calcVertexNormals) - normals = new List(); - - for (var i = 0; i < numFaces; i++) - { - var face = faces[i]; - - normals.Add(SurfaceNormal(i).Normalize()); - - var normIndex = normals.Count - 1; - face.n1 = normIndex; - face.n2 = normIndex; - face.n3 = normIndex; - - faces[i] = face; - } - } - - /// - /// Adds a value to each XYZ vertex coordinate in the mesh - /// - /// - /// - /// - public void AddPos(float x, float y, float z) - { - int i; - var numVerts = coords.Count; - Coord vert; - - for (i = 0; i < numVerts; i++) - { - vert = coords[i]; - vert.X += x; - vert.Y += y; - vert.Z += z; - coords[i] = vert; - } - - if (viewerFaces != null) - { - var numViewerFaces = viewerFaces.Count; - - for (i = 0; i < numViewerFaces; i++) - { - var v = viewerFaces[i]; - v.AddPos(x, y, z); - viewerFaces[i] = v; - } - } - } - - /// - /// Rotates the mesh - /// - /// - public void AddRot(Quat q) - { - int i; - var numVerts = coords.Count; - - for (i = 0; i < numVerts; i++) - coords[i] *= q; - - if (normals != null) - { - var numNormals = normals.Count; - for (i = 0; i < numNormals; i++) - normals[i] *= q; - } - - if (viewerFaces != null) - { - var numViewerFaces = viewerFaces.Count; - - for (i = 0; i < numViewerFaces; i++) - { - var v = viewerFaces[i]; - v.v1 *= q; - v.v2 *= q; - v.v3 *= q; - - v.n1 *= q; - v.n2 *= q; - v.n3 *= q; - viewerFaces[i] = v; - } - } - } - -#if VERTEX_INDEXER - public VertexIndexer GetVertexIndexer() - { - if (viewerMode && viewerFaces.Count > 0) - return new VertexIndexer(this); - return null; - } -#endif - - /// - /// Scales the mesh - /// - /// - /// - /// - public void Scale(float x, float y, float z) - { - int i; - var numVerts = coords.Count; - //Coord vert; - - var m = new Coord(x, y, z); - for (i = 0; i < numVerts; i++) - coords[i] *= m; - - if (viewerFaces != null) - { - var numViewerFaces = viewerFaces.Count; - for (i = 0; i < numViewerFaces; i++) - { - var v = viewerFaces[i]; - v.v1 *= m; - v.v2 *= m; - v.v3 *= m; - viewerFaces[i] = v; - } - } - } - - /// - /// Dumps the mesh to a Blender compatible "Raw" format file - /// - /// - /// - /// - public void DumpRaw(string path, string name, string title) - { - if (path == null) - return; - var fileName = name + "_" + title + ".raw"; - var completePath = System.IO.Path.Combine(path, fileName); - var sw = new StreamWriter(completePath); - - for (var i = 0; i < faces.Count; i++) - { - var s = coords[faces[i].v1].ToString(); - s += " " + coords[faces[i].v2]; - s += " " + coords[faces[i].v3]; - - sw.WriteLine(s); - } - - sw.Close(); - } - } -} \ No newline at end of file diff --git a/OpenMetaverse.Rendering.Meshmerizer/MeshmerizerR.cs b/OpenMetaverse.Rendering.Meshmerizer/MeshmerizerR.cs index d2a32cc8..1ee46ee3 100644 --- a/OpenMetaverse.Rendering.Meshmerizer/MeshmerizerR.cs +++ b/OpenMetaverse.Rendering.Meshmerizer/MeshmerizerR.cs @@ -31,12 +31,9 @@ * using PrimMesher (http://forge.opensimulator.org/projects/primmesher). */ -using System; -using System.Collections.Generic; -using System.Drawing; - using OMV = OpenMetaverse; using OMVR = OpenMetaverse.Rendering; +using SkiaSharp; namespace OpenMetaverse.Rendering { @@ -44,7 +41,7 @@ namespace OpenMetaverse.Rendering /// Meshing code based on the Idealist Viewer (20081213). /// [RendererName("MeshmerizerR")] - public class MeshmerizerR : IRendering + public class MeshmerizerR : OMVR.IRendering { /// /// Generates a basic mesh structure from a primitive @@ -58,16 +55,15 @@ public OMVR.SimpleMesh GenerateSimpleMesh(Primitive prim, OMVR.DetailLevel lod) if (newPrim == null) return null; - SimpleMesh mesh = new SimpleMesh(); - mesh.Path = new Path(); - mesh.Prim = prim; - mesh.Profile = new Profile(); - mesh.Vertices = new List(newPrim.coords.Count); - for (int i = 0; i < newPrim.coords.Count; i++) + SimpleMesh mesh = new() { - PrimMesher.Coord c = newPrim.coords[i]; - mesh.Vertices.Add(new Vertex { Position = new Vector3(c.X, c.Y, c.Z) }); - } + Path = new Path(), + Prim = prim, + Profile = new Profile(), + Vertices = new List(newPrim.coords.Count) + }; + for (int i = 0; i < newPrim.coords.Count; i++) + mesh.Vertices.Add(new Vertex { Position = newPrim.coords[i] }); mesh.Indices = new List(newPrim.faces.Count * 3); for (int i = 0; i < newPrim.faces.Count; i++) @@ -88,7 +84,7 @@ public OMVR.SimpleMesh GenerateSimpleMesh(Primitive prim, OMVR.DetailLevel lod) /// Sculpt texture /// Level of detail to generate the mesh at /// The generated mesh or null on failure - public OMVR.SimpleMesh GenerateSimpleSculptMesh(OMV.Primitive prim, Bitmap sculptTexture, OMVR.DetailLevel lod) + public OMVR.SimpleMesh GenerateSimpleSculptMesh(OMV.Primitive prim, SKBitmap sculptTexture, OMVR.DetailLevel lod) { OMVR.FacetedMesh faceted = GenerateFacetedSculptMesh(prim, sculptTexture, lod); @@ -110,6 +106,97 @@ public OMVR.SimpleMesh GenerateSimpleSculptMesh(OMV.Primitive prim, Bitmap sculp return null; } + public static FacetedMesh m_BasicBoxMesh = null; + private static readonly object m_BasicBoxMeshLock = new(); + public static List m_indexs_012023 = [0, 1, 2, 0, 2, 3]; + public static List m_indexs_012213 = [0, 1, 2, 2, 1, 3]; + public static List m_indexs_012302 = [0, 1, 2, 3, 0, 2]; + public static FacetedMesh GetBasicBoxMesh() + { + if(m_BasicBoxMesh == null) + { + lock (m_BasicBoxMeshLock) + { + m_BasicBoxMesh ??= new() + { + Faces = + [ + new Face() + { + Vertices = + [ + new() { Position = new(-0.5f, -0.5f, 0.5f), Normal = Vector3.UnitZ, TexCoord = new(0f, 0f)}, + new() { Position = new( 0.5f, -0.5f, 0.5f), Normal = Vector3.UnitZ, TexCoord = new(1f, 0f)}, + new() { Position = new( 0.5f, 0.5f, 0.5f), Normal = Vector3.UnitZ, TexCoord = new(1f, 1f)}, + new() { Position = new(-0.5f, 0.5f, 0.5f), Normal = Vector3.UnitZ, TexCoord = new(0f, 1f)}, + ], + Indices = m_indexs_012023, + }, + new Face() + { + Vertices = + [ + new() { Position = new(-0.5f, -0.5f, 0.5f), Normal = -Vector3.UnitY, TexCoord = new(0f, 1f)}, + new() { Position = new(-0.5f, -0.5f, -0.5f), Normal = -Vector3.UnitY, TexCoord = new(0f, 0f)}, + new() { Position = new( 0.5f, -0.5f, 0.5f), Normal = -Vector3.UnitY, TexCoord = new(1f, 1f)}, + new() { Position = new( 0.5f, -0.5f, -0.5f), Normal = -Vector3.UnitY, TexCoord = new(1f, 0f)}, + ], + Indices = m_indexs_012213, + }, + new Face() + { + Vertices = + [ + new() { Position = new( 0.5f, -0.5f, 0.5f), Normal = Vector3.UnitX, TexCoord = new(0f, 1f)}, + new() { Position = new( 0.5f, -0.5f, -0.5f), Normal = Vector3.UnitX, TexCoord = new(0f, 0f)}, + new() { Position = new( 0.5f, 0.5f, 0.5f), Normal = Vector3.UnitX, TexCoord = new(1f, 1f)}, + new() { Position = new( 0.5f, 0.5f, -0.5f), Normal = Vector3.UnitX, TexCoord = new(1f, 0f)}, + ], + Indices = m_indexs_012213, + }, + new Face() + { + Vertices = + [ + new() { Position = new( 0.5f, 0.5f, 0.5f), Normal = Vector3.UnitY, TexCoord = new(0f, 1f)}, + new() { Position = new( 0.5f, 0.5f, -0.5f), Normal = Vector3.UnitY, TexCoord = new(0f, 0f)}, + new() { Position = new( -0.5f, 0.5f, 0.5f), Normal = Vector3.UnitY, TexCoord = new(1f, 1f)}, + new() { Position = new( -0.5f, 0.5f, -0.5f), Normal = Vector3.UnitY, TexCoord = new(1f, 0f)}, + ], + Indices = m_indexs_012213, + }, + new Face() + { + Vertices = + [ + new() { Position = new( -0.5f, 0.5f, 0.5f), Normal = -Vector3.UnitX, TexCoord = new(0f, 1f)}, + new() { Position = new( -0.5f, 0.5f, -0.5f), Normal = -Vector3.UnitX, TexCoord = new(0f, 0f)}, + new() { Position = new( -0.5f, -0.5f, 0.5f), Normal = -Vector3.UnitX, TexCoord = new(1f, 1f)}, + new() { Position = new( -0.5f, -0.5f, -0.5f), Normal = -Vector3.UnitX, TexCoord = new(1f, 0f)}, + ], + Indices = m_indexs_012213, + }, + new Face() + { + Vertices = + [ + new() { Position = new( 0.5f, 0.5f, -0.5f), Normal = -Vector3.UnitZ, TexCoord = new(1f, 0f)}, + new() { Position = new( 0.5f, -0.5f, -0.5f), Normal = -Vector3.UnitZ, TexCoord = new(1f, 1f)}, + new() { Position = new( -0.5f, -0.5f, -0.5f), Normal = -Vector3.UnitZ, TexCoord = new(0f, 1f)}, + new() { Position = new( -0.5f, 0.5f, -0.5f), Normal = -Vector3.UnitZ, TexCoord = new(0f, 0f)}, + ], + Indices = m_indexs_012302, + }, + ] + }; + } + } + + return m_BasicBoxMesh; + } + + + /// /// Generates a a series of faces, each face containing a mesh and /// metadata @@ -119,35 +206,52 @@ public OMVR.SimpleMesh GenerateSimpleSculptMesh(OMV.Primitive prim, Bitmap sculp /// The generated mesh public OMVR.FacetedMesh GenerateFacetedMesh(OMV.Primitive prim, OMVR.DetailLevel lod) { - bool isSphere = ((OMV.ProfileCurve)(prim.PrimData.profileCurve & 0x07) == OMV.ProfileCurve.HalfCircle); + OMV.ProfileCurve profileCurve = (OMV.ProfileCurve)(prim.PrimData.profileCurve & 0x07); + + if ( profileCurve == OMV.ProfileCurve.Square && prim.PrimData.PathCurve == OMV.PathCurve.Line) + { + if( prim.PrimData.ProfileHole == 0 && + prim.PrimData.ProfileBegin == 0f && prim.PrimData.ProfileEnd == 1f && + prim.PrimData.PathBegin == 0f && prim.PrimData.PathEnd == 1f && + prim.PrimData.PathScaleX == 1f && prim.PrimData.PathScaleY == 1f && + prim.PrimData.PathShearX == 0 && prim.PrimData.PathShearY == 0 && + prim.PrimData.PathRevolutions == 1f + ) + { + return GetBasicBoxMesh(); + } + } + PrimMesher.PrimMesh newPrim = GeneratePrimMesh(prim, lod, true); if (newPrim == null) return null; // copy the vertex information into OMVR.IRendering structures - OMVR.FacetedMesh omvrmesh = new OMVR.FacetedMesh(); - omvrmesh.Faces = new List(); - omvrmesh.Prim = prim; - omvrmesh.Profile = new OMVR.Profile(); - omvrmesh.Profile.Faces = new List(); - omvrmesh.Profile.Positions = new List(); - omvrmesh.Path = new OMVR.Path(); - omvrmesh.Path.Points = new List(); + OMVR.FacetedMesh omvrmesh = new() + { + Faces = [], + Prim = prim, + Profile = new() { Faces = [], Positions = [] }, + Path = new() { Points = [] } + }; + var indexer = newPrim.GetVertexIndexer(); for (int i = 0; i < indexer.numPrimFaces; i++) { - OMVR.Face oface = new OMVR.Face(); - oface.Vertices = new List(); - oface.Indices = new List(); - oface.TextureFace = prim.Textures.GetFace((uint)i); + OMVR.Face oface = new() + { + Vertices = [], + Indices = [], + TextureFace = prim.Textures.GetFace((uint)i) + }; for (int j = 0; j < indexer.viewerVertices[i].Count; j++) { var vert = new OMVR.Vertex(); var m = indexer.viewerVertices[i][j]; - vert.Position = new Vector3(m.v.X, m.v.Y, m.v.Z); - vert.Normal = new Vector3(m.n.X, m.n.Y, m.n.Z); + vert.Position = m.v; + vert.Normal = m.n; vert.TexCoord = new OMV.Vector2(m.uv.U, 1.0f - m.uv.V); oface.Vertices.Add(vert); } @@ -173,7 +277,7 @@ public OMVR.FacetedMesh GenerateFacetedMesh(OMV.Primitive prim, OMVR.DetailLevel /// routine since all the context for finding teh texture is elsewhere. /// /// The faceted mesh or null if can't do it - public OMVR.FacetedMesh GenerateFacetedSculptMesh(OMV.Primitive prim, Bitmap scupltTexture, OMVR.DetailLevel lod) + public OMVR.FacetedMesh GenerateFacetedSculptMesh(OMV.Primitive prim, SKBitmap scupltTexture, OMVR.DetailLevel lod) { PrimMesher.SculptMesh.SculptType smSculptType; switch (prim.Sculpt.Type) @@ -327,16 +431,16 @@ public void TransformTexCoords(List vertices, OMV.Vector3 center, O private PrimMesher.PrimMesh GeneratePrimMesh(Primitive prim, DetailLevel lod, bool viewerMode) { - OMV.Primitive.ConstructionData primData = prim.PrimData; int sides = 4; int hollowsides = 4; - float profileBegin = primData.ProfileBegin; - float profileEnd = primData.ProfileEnd; + float profileBegin = prim.PrimData.ProfileBegin; + float profileEnd = prim.PrimData.ProfileEnd; bool isSphere = false; - if ((OMV.ProfileCurve)(primData.profileCurve & 0x07) == OMV.ProfileCurve.Circle) + OMV.ProfileCurve profileCurve = (OMV.ProfileCurve)(prim.PrimData.profileCurve & 0x07); + if (profileCurve == OMV.ProfileCurve.Circle) { switch (lod) { @@ -351,9 +455,9 @@ private PrimMesher.PrimMesh GeneratePrimMesh(Primitive prim, DetailLevel lod, bo break; } } - else if ((OMV.ProfileCurve)(primData.profileCurve & 0x07) == OMV.ProfileCurve.EqualTriangle) + else if (profileCurve == OMV.ProfileCurve.EqualTriangle) sides = 3; - else if ((OMV.ProfileCurve)(primData.profileCurve & 0x07) == OMV.ProfileCurve.HalfCircle) + else if (profileCurve == OMV.ProfileCurve.HalfCircle) { // half circle, prim is a sphere isSphere = true; @@ -373,9 +477,9 @@ private PrimMesher.PrimMesh GeneratePrimMesh(Primitive prim, DetailLevel lod, bo profileEnd = 0.5f * profileEnd + 0.5f; } - if ((OMV.HoleType)primData.ProfileHole == OMV.HoleType.Same) + if ((OMV.HoleType)prim.PrimData.ProfileHole == OMV.HoleType.Same) hollowsides = sides; - else if ((OMV.HoleType)primData.ProfileHole == OMV.HoleType.Circle) + else if (prim.PrimData.ProfileHole == OMV.HoleType.Circle) { switch (lod) { @@ -390,21 +494,21 @@ private PrimMesher.PrimMesh GeneratePrimMesh(Primitive prim, DetailLevel lod, bo break; } } - else if ((OMV.HoleType)primData.ProfileHole == OMV.HoleType.Triangle) + else if (prim.PrimData.ProfileHole == OMV.HoleType.Triangle) hollowsides = 3; - PrimMesher.PrimMesh newPrim = new PrimMesher.PrimMesh(sides, profileBegin, profileEnd, (float)primData.ProfileHollow, hollowsides); + PrimMesher.PrimMesh newPrim = new(sides, profileBegin, profileEnd, prim.PrimData.ProfileHollow, hollowsides); newPrim.viewerMode = viewerMode; newPrim.sphereMode = isSphere; - newPrim.holeSizeX = primData.PathScaleX; - newPrim.holeSizeY = primData.PathScaleY; - newPrim.pathCutBegin = primData.PathBegin; - newPrim.pathCutEnd = primData.PathEnd; - newPrim.topShearX = primData.PathShearX; - newPrim.topShearY = primData.PathShearY; - newPrim.radius = primData.PathRadiusOffset; - newPrim.revolutions = primData.PathRevolutions; - newPrim.skew = primData.PathSkew; + newPrim.holeSizeX = prim.PrimData.PathScaleX; + newPrim.holeSizeY = prim.PrimData.PathScaleY; + newPrim.pathCutBegin = prim.PrimData.PathBegin; + newPrim.pathCutEnd = prim.PrimData.PathEnd; + newPrim.topShearX = prim.PrimData.PathShearX; + newPrim.topShearY = prim.PrimData.PathShearY; + newPrim.radius = prim.PrimData.PathRadiusOffset; + newPrim.revolutions = prim.PrimData.PathRevolutions; + newPrim.skew = prim.PrimData.PathSkew; switch (lod) { case OMVR.DetailLevel.Low: @@ -418,20 +522,20 @@ private PrimMesher.PrimMesh GeneratePrimMesh(Primitive prim, DetailLevel lod, bo break; } - if ((primData.PathCurve == OMV.PathCurve.Line) || (primData.PathCurve == OMV.PathCurve.Flexible)) + if ((prim.PrimData.PathCurve == OMV.PathCurve.Line) || (prim.PrimData.PathCurve == OMV.PathCurve.Flexible)) { - newPrim.taperX = 1.0f - primData.PathScaleX; - newPrim.taperY = 1.0f - primData.PathScaleY; - newPrim.twistBegin = (int)(180 * primData.PathTwistBegin); - newPrim.twistEnd = (int)(180 * primData.PathTwist); + newPrim.taperX = 1.0f - prim.PrimData.PathScaleX; + newPrim.taperY = 1.0f - prim.PrimData.PathScaleY; + newPrim.twistBegin = (int)(180 * prim.PrimData.PathTwistBegin); + newPrim.twistEnd = (int)(180 * prim.PrimData.PathTwist); newPrim.ExtrudeLinear(); } else { - newPrim.taperX = primData.PathTaperX; - newPrim.taperY = primData.PathTaperY; - newPrim.twistBegin = (int)(360 * primData.PathTwistBegin); - newPrim.twistEnd = (int)(360 * primData.PathTwist); + newPrim.taperX = prim.PrimData.PathTaperX; + newPrim.taperY = prim.PrimData.PathTaperY; + newPrim.twistBegin = (int)(360 * prim.PrimData.PathTwistBegin); + newPrim.twistEnd = (int)(360 * prim.PrimData.PathTwist); newPrim.ExtrudeCircular(); } diff --git a/OpenMetaverse.Rendering.Meshmerizer/OpenMetaverse.Rendering.Meshmerizer.csproj b/OpenMetaverse.Rendering.Meshmerizer/OpenMetaverse.Rendering.Meshmerizer.csproj index f3b90a4c..2efdd8d8 100644 --- a/OpenMetaverse.Rendering.Meshmerizer/OpenMetaverse.Rendering.Meshmerizer.csproj +++ b/OpenMetaverse.Rendering.Meshmerizer/OpenMetaverse.Rendering.Meshmerizer.csproj @@ -1,19 +1,23 @@  Local - net48 + Library + OpenMetaverse.Rendering.Meshmerizer + Full primitive and sculpt mesh renderer using the Meshmerizer engine for the OpenMetaverse library. True - 1591,1574,0419,0618 true - - - - + + + + + + + \ No newline at end of file diff --git a/OpenMetaverse.Rendering.Simple/OpenMetaverse.Rendering.Simple.csproj b/OpenMetaverse.Rendering.Simple/OpenMetaverse.Rendering.Simple.csproj index 030e6b5d..5724560c 100644 --- a/OpenMetaverse.Rendering.Simple/OpenMetaverse.Rendering.Simple.csproj +++ b/OpenMetaverse.Rendering.Simple/OpenMetaverse.Rendering.Simple.csproj @@ -1,14 +1,12 @@  Local - net48 + Library + OpenMetaverse.Rendering.Simple + Simple faceted primitive mesh renderer for the OpenMetaverse library. True - 1591,1574,0419,0618 true - - - diff --git a/OpenMetaverse.Rendering.Simple/SimpleRenderer.cs b/OpenMetaverse.Rendering.Simple/SimpleRenderer.cs index 370487c0..85eb0709 100644 --- a/OpenMetaverse.Rendering.Simple/SimpleRenderer.cs +++ b/OpenMetaverse.Rendering.Simple/SimpleRenderer.cs @@ -25,6 +25,7 @@ */ using System.Collections.Generic; +using SkiaSharp; namespace OpenMetaverse.Rendering { @@ -46,7 +47,7 @@ public SimpleMesh GenerateSimpleMesh(Primitive prim, DetailLevel lod) return mesh; } - public SimpleMesh GenerateSimpleSculptMesh(Primitive prim, System.Drawing.Bitmap sculptTexture, DetailLevel lod) + public SimpleMesh GenerateSimpleSculptMesh(Primitive prim, SKBitmap sculptTexture, DetailLevel lod) { return GenerateSimpleMesh(prim, lod); } @@ -65,7 +66,7 @@ public FacetedMesh GenerateFacetedMesh(Primitive prim, DetailLevel lod) return mesh; } - public FacetedMesh GenerateFacetedSculptMesh(Primitive prim, System.Drawing.Bitmap sculptTexture, DetailLevel lod) + public FacetedMesh GenerateFacetedSculptMesh(Primitive prim, SKBitmap sculptTexture, DetailLevel lod) { return GenerateFacetedMesh(prim, lod); } diff --git a/OpenMetaverse.StructuredData/JSON/JsonData.cs b/OpenMetaverse.StructuredData/JSON/JsonData.cs index d96712b9..e2a8446e 100644 --- a/OpenMetaverse.StructuredData/JSON/JsonData.cs +++ b/OpenMetaverse.StructuredData/JSON/JsonData.cs @@ -36,7 +36,6 @@ public class JsonData : IJsonWrapper, IEquatable private IList> object_list; #endregion - #region Properties public int Count { @@ -136,8 +135,7 @@ ICollection IDictionary.Keys EnsureDictionary(); IList keys = new List(); - foreach (KeyValuePair entry in - object_list) + foreach (KeyValuePair entry in object_list) { keys.Add(entry.Key); } @@ -153,8 +151,7 @@ ICollection IDictionary.Values EnsureDictionary(); IList values = new List(); - foreach (KeyValuePair entry in - object_list) + foreach (KeyValuePair entry in object_list) { values.Add(entry.Value); } @@ -263,8 +260,7 @@ object IOrderedDictionary.this[int idx] inst_object[old_entry.Key] = data; - KeyValuePair entry = - new KeyValuePair(old_entry.Key, data); + KeyValuePair entry = new KeyValuePair(old_entry.Key, data); object_list[idx] = entry; } @@ -304,8 +300,7 @@ public JsonData this[string prop_name] { EnsureDictionary(); - KeyValuePair entry = - new KeyValuePair(prop_name, value); + KeyValuePair entry = new KeyValuePair(prop_name, value); if (inst_object.ContainsKey(prop_name)) { @@ -348,8 +343,7 @@ public JsonData this[int index] else { KeyValuePair entry = object_list[index]; - KeyValuePair new_entry = - new KeyValuePair(entry.Key, value); + KeyValuePair new_entry = new KeyValuePair(entry.Key, value); object_list[index] = new_entry; inst_object[entry.Key] = value; @@ -497,11 +491,11 @@ public static explicit operator Int32(JsonData data) public static explicit operator Int64(JsonData data) { - if (data.type != JsonType.Long) + if (data.type != JsonType.Long && data.type != JsonType.Int) throw new InvalidCastException( "Instance of JsonData doesn't hold an int"); - return data.inst_long; + return (data.type == JsonType.Long) ? data.inst_long : data.inst_int; } public static explicit operator String(JsonData data) @@ -530,8 +524,7 @@ void IDictionary.Add(object key, object value) EnsureDictionary().Add(key, data); - KeyValuePair entry = - new KeyValuePair((string)key, data); + KeyValuePair entry = new KeyValuePair((string)key, data); object_list.Add(entry); json = null; diff --git a/OpenMetaverse.StructuredData/JSON/JsonException.cs b/OpenMetaverse.StructuredData/JSON/JsonException.cs index 509fb253..cc44377e 100644 --- a/OpenMetaverse.StructuredData/JSON/JsonException.cs +++ b/OpenMetaverse.StructuredData/JSON/JsonException.cs @@ -21,29 +21,22 @@ public JsonException() : base() } internal JsonException(ParserToken token) : - base(String.Format( - "Invalid token '{0}' in input string", token)) + base(String.Format("Invalid token '{0}' in input string", token)) { } - internal JsonException(ParserToken token, - Exception inner_exception) : - base(String.Format( - "Invalid token '{0}' in input string", token), - inner_exception) + internal JsonException(ParserToken token, Exception inner_exception) : + base(String.Format("Invalid token '{0}' in input string", token), inner_exception) { } internal JsonException(int c) : - base(String.Format( - "Invalid character '{0}' in input string", (char)c)) + base(String.Format("Invalid character '{0}' in input string", (char)c)) { } internal JsonException(int c, Exception inner_exception) : - base(String.Format( - "Invalid character '{0}' in input string", (char)c), - inner_exception) + base(String.Format("Invalid character '{0}' in input string", (char)c), inner_exception) { } diff --git a/OpenMetaverse.StructuredData/JSON/JsonMapper.cs b/OpenMetaverse.StructuredData/JSON/JsonMapper.cs index b4241930..3c6614f8 100644 --- a/OpenMetaverse.StructuredData/JSON/JsonMapper.cs +++ b/OpenMetaverse.StructuredData/JSON/JsonMapper.cs @@ -26,14 +26,12 @@ internal struct PropertyMetadata public Type Type; } - internal struct ArrayMetadata { private Type element_type; private bool is_array; private bool is_list; - public Type ElementType { get @@ -60,7 +58,6 @@ public bool IsList } } - internal struct ObjectMetadata { private Type element_type; @@ -68,7 +65,6 @@ internal struct ObjectMetadata private IDictionary properties; - public Type ElementType { get @@ -95,7 +91,6 @@ public IDictionary Properties } } - internal delegate void ExporterFunc(object obj, JsonWriter writer); public delegate void ExporterFunc(T obj, JsonWriter writer); @@ -104,7 +99,6 @@ public IDictionary Properties public delegate IJsonWrapper WrapperFactory(); - public class JsonMapper { #region Fields @@ -115,30 +109,25 @@ public class JsonMapper private static IDictionary base_exporters_table; private static IDictionary custom_exporters_table; - private static IDictionary> base_importers_table; - private static IDictionary> custom_importers_table; + private static IDictionary> base_importers_table; + private static IDictionary> custom_importers_table; private static IDictionary array_metadata; - private static readonly object array_metadata_lock = new Object(); + private static readonly object array_metadata_lock = new object(); - private static IDictionary> conv_ops; - private static readonly object conv_ops_lock = new Object(); + private static IDictionary> conv_ops; + private static readonly object conv_ops_lock = new object(); private static IDictionary object_metadata; - private static readonly object object_metadata_lock = new Object(); + private static readonly object object_metadata_lock = new object(); - private static IDictionary> type_properties; - private static readonly object type_properties_lock = new Object(); + private static IDictionary> type_properties; + private static readonly object type_properties_lock = new object(); private static JsonWriter static_writer; - private static readonly object static_writer_lock = new Object(); + private static readonly object static_writer_lock = new object(); #endregion - #region Constructors static JsonMapper() { @@ -147,8 +136,7 @@ static JsonMapper() array_metadata = new Dictionary(); conv_ops = new Dictionary>(); object_metadata = new Dictionary(); - type_properties = new Dictionary>(); + type_properties = new Dictionary>(); static_writer = new JsonWriter(); @@ -157,17 +145,14 @@ static JsonMapper() base_exporters_table = new Dictionary(); custom_exporters_table = new Dictionary(); - base_importers_table = new Dictionary>(); - custom_importers_table = new Dictionary>(); + base_importers_table = new Dictionary>(); + custom_importers_table = new Dictionary>(); RegisterBaseExporters(); RegisterBaseImporters(); } #endregion - #region Private Methods private static void AddArrayMetadata(Type type) { @@ -316,8 +301,7 @@ private static MethodInfo GetConvOp(Type t1, Type t2) if (conv_ops[t1].ContainsKey(t2)) return conv_ops[t1][t2]; - MethodInfo op = t1.GetMethod( - "op_Implicit", new Type[] { t2 }); + MethodInfo op = t1.GetMethod("op_Implicit", new Type[] { t2 }); lock (conv_ops_lock) { @@ -362,7 +346,6 @@ private static object ReadValue(Type inst_type, JsonReader reader) reader.Token == JsonToken.String || reader.Token == JsonToken.Boolean) { - Type json_type = reader.Value.GetType(); if (value_type.IsAssignableFrom(json_type)) @@ -370,25 +353,17 @@ private static object ReadValue(Type inst_type, JsonReader reader) // If there's a custom importer that fits, use it if (custom_importers_table.ContainsKey(json_type) && - custom_importers_table[json_type].ContainsKey( - value_type)) + custom_importers_table[json_type].ContainsKey(value_type)) { - - ImporterFunc importer = - custom_importers_table[json_type][value_type]; - + ImporterFunc importer = custom_importers_table[json_type][value_type]; return importer(reader.Value); } // Maybe there's a base importer that works if (base_importers_table.ContainsKey(json_type) && - base_importers_table[json_type].ContainsKey( - value_type)) + base_importers_table[json_type].ContainsKey(value_type)) { - - ImporterFunc importer = - base_importers_table[json_type][value_type]; - + ImporterFunc importer = base_importers_table[json_type][value_type]; return importer(reader.Value); } @@ -400,8 +375,7 @@ private static object ReadValue(Type inst_type, JsonReader reader) MethodInfo conv_op = GetConvOp(value_type, json_type); if (conv_op != null) - return conv_op.Invoke(null, - new object[] { reader.Value }); + return conv_op.Invoke(null, new object[] { reader.Value }); // No luck throw new JsonException(String.Format( @@ -413,7 +387,6 @@ private static object ReadValue(Type inst_type, JsonReader reader) if (reader.Token == JsonToken.ArrayStart) { - AddArrayMetadata(inst_type); ArrayMetadata t_data = array_metadata[inst_type]; @@ -475,8 +448,7 @@ private static object ReadValue(Type inst_type, JsonReader reader) if (t_data.Properties.ContainsKey(property)) { - PropertyMetadata prop_data = - t_data.Properties[property]; + PropertyMetadata prop_data = t_data.Properties[property]; if (prop_data.IsField) { @@ -485,14 +457,10 @@ private static object ReadValue(Type inst_type, JsonReader reader) } else { - PropertyInfo p_info = - (PropertyInfo)prop_data.Info; + PropertyInfo p_info = (PropertyInfo)prop_data.Info; if (p_info.CanWrite) - p_info.SetValue( - instance, - ReadValue(prop_data.Type, reader), - null); + p_info.SetValue(instance, ReadValue(prop_data.Type, reader), null); else ReadValue(prop_data.Type, reader); } @@ -517,25 +485,19 @@ private static object ReadValue(Type inst_type, JsonReader reader) } } - ((IDictionary)instance).Add( - property, ReadValue( - t_data.ElementType, reader)); + ((IDictionary)instance).Add( property, ReadValue(t_data.ElementType, reader)); } - } - } return instance; } - private static IJsonWrapper ReadValue(WrapperFactory factory, - JsonReader reader) + private static IJsonWrapper ReadValue(WrapperFactory factory, JsonReader reader) { reader.Read(); - if (reader.Token == JsonToken.ArrayEnd || - reader.Token == JsonToken.Null) + if (reader.Token == JsonToken.ArrayEnd || reader.Token == JsonToken.Null) return null; IJsonWrapper instance = factory(); @@ -607,8 +569,7 @@ private static IJsonWrapper ReadValue(WrapperFactory factory, private static void ReadSkip(JsonReader reader) { - ToWrapper( - delegate { return new JsonMockWrapper(); }, reader); + ToWrapper(delegate { return new JsonMockWrapper(); }, reader); } private static void RegisterBaseExporters() diff --git a/OpenMetaverse.StructuredData/JSON/JsonOSUTF8Writer.cs b/OpenMetaverse.StructuredData/JSON/JsonOSUTF8Writer.cs new file mode 100644 index 00000000..d5359524 --- /dev/null +++ b/OpenMetaverse.StructuredData/JSON/JsonOSUTF8Writer.cs @@ -0,0 +1,440 @@ + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Text; +using OpenMetaverse; + +namespace LitJson +{ + public class JsonOSUTF8Writer + { + #region Fields + private static NumberFormatInfo number_format; + + private WriterContext context; + private Stack ctx_stack; + private bool has_reached_end; + private byte[] hex_seq; + private int indentation; + private int indent_value; + private osUTF8 sb; + private bool ownsb; + private bool pretty_print; + private bool validate; + + #endregion + + #region Properties + public int IndentValue + { + get { return indent_value; } + set + { + indentation = (indentation / indent_value) * value; + indent_value = value; + } + } + + public bool PrettyPrint + { + get { return pretty_print; } + set { pretty_print = value; } + } + + public bool Validate + { + get { return validate; } + set { validate = value; } + } + #endregion + + #region Constructors + static JsonOSUTF8Writer() + { + number_format = NumberFormatInfo.InvariantInfo; + } + + public JsonOSUTF8Writer() + { + sb = OSUTF8Cached.Acquire(); + ownsb = true; + Init(); + } + + public JsonOSUTF8Writer(osUTF8 sb) + { + this.sb = sb; + ownsb = false; + Init(); + } + #endregion + + + #region Private Methods + private void DoValidation(Condition cond) + { + if (!context.ExpectingValue) + context.Count++; + + if (!validate) + return; + + if (has_reached_end) + throw new JsonException( + "A complete JSON symbol has already been written"); + + switch (cond) + { + case Condition.InArray: + if (!context.InArray) + throw new JsonException( + "Can't close an array here"); + break; + + case Condition.InObject: + if (!context.InObject || context.ExpectingValue) + throw new JsonException( + "Can't close an object here"); + break; + + case Condition.NotAProperty: + if (context.InObject && !context.ExpectingValue) + throw new JsonException( + "Expected a property"); + break; + + case Condition.Property: + if (!context.InObject || context.ExpectingValue) + throw new JsonException( + "Can't add a property here"); + break; + + case Condition.Value: + if (!context.InArray && + (!context.InObject || !context.ExpectingValue)) + throw new JsonException( + "Can't add a value here"); + + break; + } + } + + private void Init() + { + has_reached_end = false; + hex_seq = new byte[4]; + indentation = 0; + indent_value = 4; + pretty_print = false; + validate = true; + + ctx_stack = new Stack(); + context = new WriterContext(); + ctx_stack.Push(context); + } + + private void Indent() + { + if (pretty_print) + indentation += indent_value; + } + + + private void Put(string str) + { + if (pretty_print && !context.ExpectingValue) + for (int i = 0; i < indentation; i++) + sb.AppendASCII(' '); + + sb.AppendASCII(str); + } + + private void Put(char c) + { + if (pretty_print && !context.ExpectingValue) + for (int i = 0; i < indentation; i++) + sb.AppendASCII(' '); + + sb.AppendASCII(c); + } + + private void PutNewline() + { + PutNewline(true); + } + + private void PutNewline(bool add_comma) + { + if (add_comma && !context.ExpectingValue && + context.Count > 1) + sb.AppendASCII(','); + + if (pretty_print && !context.ExpectingValue) + sb.AppendASCII('\n'); + } + + private void PutString(string str) + { + if (pretty_print && !context.ExpectingValue) + for (int i = 0; i < indentation; i++) + sb.AppendASCII(' '); + + sb.AppendASCII('"'); + for (int i = 0; i < str.Length; i++) + { + char c = str[i]; + switch (c) + { + case '\n': + sb.AppendASCII("\\n"); + break; + + case '\r': + sb.AppendASCII("\\r"); + break; + + case '\t': + sb.AppendASCII("\\t"); + break; + + case '"': + case '\\': + sb.AppendASCII('\\'); + sb.AppendASCII(c); + break; + + case '\f': + sb.AppendASCII("\\f"); + break; + + case '\b': + sb.AppendASCII("\\b"); + break; + + default: + // Default, turn into a \uXXXX sequence + if (c >= 32 && c <= 126) + sb.AppendASCII(c); + else + { + sb.AppendASCII("\\u"); + sb.Append(Utils.NibbleToHexUpper((byte)(c >> 12))); + sb.Append(Utils.NibbleToHexUpper((byte)(c >> 8))); + sb.Append(Utils.NibbleToHexUpper((byte)(c >> 4))); + sb.Append(Utils.NibbleToHexUpper((byte)c)); + } + break; + } + } + sb.AppendASCII('"'); + } + + private void Unindent() + { + if (pretty_print) + indentation -= indent_value; + } + #endregion + + public override string ToString() + { + if (sb == null) + return String.Empty; + if (ownsb) + { + string ret = sb.ToString(); + OSUTF8Cached.Release(sb); + return ret; + } + return sb.ToString(); + } + + public byte[] ToBytes() + { + if (sb == null) + return new byte[0]; + if (ownsb) + return OSUTF8Cached.GetArrayAndRelease(sb); + return sb.ToArray(); + } + + public void Reset() + { + has_reached_end = false; + + ctx_stack.Clear(); + context = new WriterContext(); + ctx_stack.Push(context); + + if (sb != null) + sb.Clear(); + } + + public void Write(bool boolean) + { + DoValidation(Condition.Value); + PutNewline(); + + Put(boolean ? "true" : "false"); + + context.ExpectingValue = false; + } + + public void Write(decimal number) + { + DoValidation(Condition.Value); + PutNewline(); + + Put(Convert.ToString(number, number_format)); + + context.ExpectingValue = false; + } + + public void Write(double number) + { + DoValidation(Condition.Value); + PutNewline(); + + string str = Convert.ToString(number, number_format); + Put(str); + + if (str.IndexOfAny(new char[] { '.', 'E' }) == -1) + sb.AppendASCII(".0"); + + context.ExpectingValue = false; + } + + public void Write(int number) + { + DoValidation(Condition.Value); + PutNewline(); + + Put(Convert.ToString(number, number_format)); + + context.ExpectingValue = false; + } + + public void Write(long number) + { + DoValidation(Condition.Value); + PutNewline(); + + Put(Convert.ToString(number, number_format)); + + context.ExpectingValue = false; + } + + public void Write(string str) + { + DoValidation(Condition.Value); + PutNewline(); + + if (str == null) + Put("null"); + else + PutString(str); + + context.ExpectingValue = false; + } + + public void Write(ulong number) + { + DoValidation(Condition.Value); + PutNewline(); + + Put(Convert.ToString(number, number_format)); + + context.ExpectingValue = false; + } + + public void WriteArrayEnd() + { + DoValidation(Condition.InArray); + PutNewline(false); + + ctx_stack.Pop(); + if (ctx_stack.Count == 1) + has_reached_end = true; + else + { + context = ctx_stack.Peek(); + context.ExpectingValue = false; + } + + Unindent(); + Put(']'); + } + + public void WriteArrayStart() + { + DoValidation(Condition.NotAProperty); + PutNewline(); + + Put('['); + + context = new WriterContext(); + context.InArray = true; + ctx_stack.Push(context); + + Indent(); + } + + public void WriteObjectEnd() + { + DoValidation(Condition.InObject); + PutNewline(false); + + ctx_stack.Pop(); + if (ctx_stack.Count == 1) + has_reached_end = true; + else + { + context = ctx_stack.Peek(); + context.ExpectingValue = false; + } + + Unindent(); + Put('}'); + } + + public void WriteObjectStart() + { + DoValidation(Condition.NotAProperty); + PutNewline(); + + Put('{'); + + context = new WriterContext(); + context.InObject = true; + ctx_stack.Push(context); + + Indent(); + } + + public void WritePropertyName(string property_name) + { + DoValidation(Condition.Property); + PutNewline(); + + PutString(property_name); + + if (pretty_print) + { + if (property_name.Length > context.Padding) + context.Padding = property_name.Length; + + for (int i = context.Padding - property_name.Length; + i >= 0; i--) + sb.AppendASCII(' '); + + sb.AppendASCII(": "); + } + else + sb.AppendASCII(':'); + + context.ExpectingValue = true; + } + } +} diff --git a/OpenMetaverse.StructuredData/JSON/JsonReader.cs b/OpenMetaverse.StructuredData/JSON/JsonReader.cs index 00549e01..cafd3ee0 100644 --- a/OpenMetaverse.StructuredData/JSON/JsonReader.cs +++ b/OpenMetaverse.StructuredData/JSON/JsonReader.cs @@ -13,7 +13,6 @@ using System.Collections.Generic; using System.IO; - namespace LitJson { public enum JsonToken @@ -59,7 +58,6 @@ public class JsonReader private JsonToken token; #endregion - #region Public Properties public bool AllowComments { @@ -263,17 +261,12 @@ private static void TableAddRow(ParserToken rule) } #endregion - #region Private Methods private void ProcessNumber(string number) { - if (number.IndexOf('.') != -1 || - number.IndexOf('e') != -1 || - number.IndexOf('E') != -1) + if (number.IndexOfAny(['.','e','E']) >= 0) { - - double n_double; - if (Double.TryParse(number, out n_double)) + if (double.TryParse(number, out double n_double)) { token = JsonToken.Double; token_value = n_double; @@ -282,26 +275,23 @@ private void ProcessNumber(string number) } } - int n_int32; - if (Int32.TryParse(number, out n_int32)) + if (long.TryParse(number, out long n_int64)) + { + if(n_int64 >= int.MinValue && n_int64 <= int.MaxValue) { token = JsonToken.Int; - token_value = n_int32; - - return; + token_value = (int)n_int64; } - - long n_int64; - if (Int64.TryParse(number, out n_int64)) + else { token = JsonToken.Long; token_value = n_int64; + } return; } - ulong n_uint64; - if (UInt64.TryParse(number, out n_uint64)) + if (ulong.TryParse(number, out ulong n_uint64)) { token = JsonToken.Long; token_value = n_uint64; diff --git a/OpenMetaverse.StructuredData/JSON/JsonWriter.cs b/OpenMetaverse.StructuredData/JSON/JsonWriter.cs index 262c0924..1bbbe00a 100644 --- a/OpenMetaverse.StructuredData/JSON/JsonWriter.cs +++ b/OpenMetaverse.StructuredData/JSON/JsonWriter.cs @@ -14,7 +14,7 @@ using System.Globalization; using System.IO; using System.Text; - +using OpenMetaverse; namespace LitJson { @@ -125,40 +125,34 @@ private void DoValidation(Condition cond) return; if (has_reached_end) - throw new JsonException( - "A complete JSON symbol has already been written"); + throw new JsonException("A complete JSON symbol has already been written"); switch (cond) { case Condition.InArray: if (!context.InArray) - throw new JsonException( - "Can't close an array here"); + throw new JsonException("Can't close an array here"); break; case Condition.InObject: if (!context.InObject || context.ExpectingValue) - throw new JsonException( - "Can't close an object here"); + throw new JsonException("Can't close an object here"); break; case Condition.NotAProperty: if (context.InObject && !context.ExpectingValue) - throw new JsonException( - "Expected a property"); + throw new JsonException("Expected a property"); break; case Condition.Property: if (!context.InObject || context.ExpectingValue) - throw new JsonException( - "Can't add a property here"); + throw new JsonException("Can't add a property here"); break; case Condition.Value: if (!context.InArray && (!context.InObject || !context.ExpectingValue)) - throw new JsonException( - "Can't add a value here"); + throw new JsonException("Can't add a value here"); break; } @@ -178,23 +172,6 @@ private void Init() ctx_stack.Push(context); } - private static void IntToHex(int n, char[] hex) - { - int num; - - for (int i = 0; i < 4; i++) - { - num = n % 16; - - if (num < 10) - hex[3 - i] = (char)('0' + num); - else - hex[3 - i] = (char)('A' + (num - 10)); - - n >>= 4; - } - } - private void Indent() { if (pretty_print) @@ -218,8 +195,7 @@ private void PutNewline() private void PutNewline(bool add_comma) { - if (add_comma && !context.ExpectingValue && - context.Count > 1) + if (add_comma && !context.ExpectingValue && context.Count > 1) writer.Write(','); if (pretty_print && !context.ExpectingValue) @@ -228,52 +204,57 @@ private void PutNewline(bool add_comma) private void PutString(string str) { - Put(String.Empty); + Put(string.Empty); writer.Write('"'); - - int n = str.Length; - for (int i = 0; i < n; i++) + for (int i = 0; i < str.Length; i++) { - switch (str[i]) + char c = str[i]; + switch (c) { case '\n': writer.Write("\\n"); - continue; + break; case '\r': writer.Write("\\r"); - continue; + break; case '\t': writer.Write("\\t"); - continue; + break; case '"': case '\\': + //case '/': writer.Write('\\'); - writer.Write(str[i]); - continue; + writer.Write(c); + break; case '\f': writer.Write("\\f"); - continue; + break; case '\b': writer.Write("\\b"); - continue; + break; + + default: + // Default, turn into a \uXXXX sequence + if (c >= 32 && c <= 126) + { + writer.Write(c); + } + else + { + writer.Write("\\u"); + writer.Write(Utils.charNibbleToHexUpper((byte)(c >> 12))); + writer.Write(Utils.charNibbleToHexUpper((byte)(c >> 8))); + writer.Write(Utils.charNibbleToHexUpper((byte)(c >> 4))); + writer.Write(Utils.charNibbleToHexUpper((byte)c)); + } + break; } - - if ((int)str[i] >= 32 && (int)str[i] <= 126) - { - writer.Write(str[i]); - continue; - } - - // Default, turn into a \uXXXX sequence - IntToHex((int)str[i], hex_seq); - writer.Write("\\u"); - writer.Write(hex_seq); } writer.Write('"'); @@ -286,7 +267,6 @@ private void Unindent() } #endregion - public override string ToString() { if (inst_string_builder == null) @@ -304,7 +284,7 @@ public void Reset() ctx_stack.Push(context); if (inst_string_builder != null) - inst_string_builder.Remove(0, inst_string_builder.Length); + inst_string_builder.Clear(); } public void Write(bool boolean) @@ -335,8 +315,7 @@ public void Write(double number) string str = Convert.ToString(number, number_format); Put(str); - if (str.IndexOf('.') == -1 && - str.IndexOf('E') == -1) + if (str.IndexOfAny(['.', 'e' ,'E']) < 0) writer.Write(".0"); context.ExpectingValue = false; diff --git a/OpenMetaverse.StructuredData/JSON/OSDJson.cs b/OpenMetaverse.StructuredData/JSON/OSDJson.cs index bcc34b55..b3bee906 100644 --- a/OpenMetaverse.StructuredData/JSON/OSDJson.cs +++ b/OpenMetaverse.StructuredData/JSON/OSDJson.cs @@ -3,8 +3,11 @@ using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; +using System.Globalization; using System.IO; using System.Text; +using LitJson; +using OpenMetaverse; namespace OpenMetaverse.StructuredData { @@ -66,6 +69,7 @@ public static OSD DeserializeJson(JsonData json) } } + /* public static string SerializeJsonString(OSD osd) { return SerializeJson(osd, false).ToJson(); @@ -80,7 +84,7 @@ public static string SerializeJsonString(OSD osd, bool preserveDefaults) { return SerializeJson(osd, preserveDefaults).ToJson(); } - + */ public static void SerializeJsonString(OSD osd, bool preserveDefaults, ref JsonWriter writer) { SerializeJson(osd, preserveDefaults).ToJson(writer); @@ -94,12 +98,16 @@ public static JsonData SerializeJson(OSD osd, bool preserveDefaults) return new JsonData(osd.AsBoolean()); case OSDType.Integer: return new JsonData(osd.AsInteger()); + case OSDType.Long: + return new JsonData(osd.AsLong()); case OSDType.Real: return new JsonData(osd.AsReal()); case OSDType.String: case OSDType.Date: case OSDType.URI: case OSDType.UUID: + case OSDType.OSDUTF8: + case OSDType.LLSDxml: return new JsonData(osd.AsString()); case OSDType.Binary: byte[] binary = osd.AsBinary(); @@ -121,13 +129,7 @@ public static JsonData SerializeJson(OSD osd, bool preserveDefaults) OSDMap map = (OSDMap)osd; foreach (KeyValuePair kvp in map) { - JsonData data; - - if (preserveDefaults) - data = SerializeJson(kvp.Value, preserveDefaults); - else - data = SerializeJsonNoDefaults(kvp.Value); - + JsonData data = preserveDefaults ? SerializeJson(kvp.Value, true) : SerializeJsonNoDefaults(kvp.Value); if (data != null) jsonmap[kvp.Key] = data; } @@ -154,6 +156,10 @@ private static JsonData SerializeJsonNoDefaults(OSD osd) return null; return new JsonData(v); + + case OSDType.Long: + return new JsonData(osd.AsLong()); + case OSDType.Real: double d = osd.AsReal(); if (d == 0.0d) @@ -163,6 +169,8 @@ private static JsonData SerializeJsonNoDefaults(OSD osd) case OSDType.String: case OSDType.Date: case OSDType.URI: + case OSDType.OSDUTF8: + case OSDType.LLSDxml: string str = osd.AsString(); if (String.IsNullOrEmpty(str)) return null; @@ -170,13 +178,13 @@ private static JsonData SerializeJsonNoDefaults(OSD osd) return new JsonData(str); case OSDType.UUID: UUID uuid = osd.AsUUID(); - if (uuid == UUID.Zero) + if (uuid.IsZero()) return null; return new JsonData(uuid.ToString()); case OSDType.Binary: byte[] binary = osd.AsBinary(); - if (binary == Utils.EmptyBytes) + if (binary.Length == 0) return null; JsonData jsonbinarray = new JsonData(); @@ -207,5 +215,437 @@ private static JsonData SerializeJsonNoDefaults(OSD osd) return null; } } + + public static string SerializeJsonString(OSD osd) + { + osUTF8 sb = OSUTF8Cached.Acquire(); + SerializeJson(osd, sb, false); + return OSUTF8Cached.GetStringAndRelease(sb); + } + + public static byte[] SerializeJsonToBytes(OSD osd) + { + osUTF8 sb = OSUTF8Cached.Acquire(); + SerializeJson(osd, sb, false); + return OSUTF8Cached.GetArrayAndRelease(sb); + } + + public static string SerializeJsonString(OSD osd, bool preserveDefaults) + { + osUTF8 sb = OSUTF8Cached.Acquire(); + SerializeJson(osd, sb, preserveDefaults); + return OSUTF8Cached.GetStringAndRelease(sb); + } + + public static void SerializeJson(OSD osd, osUTF8 sb, bool preserveDefaults) + { + int i; + switch (osd.Type) + { + case OSDType.Boolean: + sb.Append(osd.AsBoolean() ? osUTF8Const.OSUTF8true : osUTF8Const.OSUTF8false); + break; + case OSDType.Integer: + sb.AppendInt(osd.AsInteger()); + break; + case OSDType.Long: + sb.AppendInt(osd.AsLong()); + break; + case OSDType.Real: + string str = Convert.ToString(osd.AsReal(), NumberFormatInfo.InvariantInfo); + sb.AppendASCII(str); + + if (str.IndexOfAny(new char[]{'.','E' }) == -1) + sb.AppendASCII(".0"); + break; + case OSDType.String: + case OSDType.URI: + case OSDType.LLSDxml: + appendJsonString(osd.AsString(), sb); + break; + case OSDType.OSDUTF8: + osUTF8 ou8 = ((OSDUTF8)osd).value; + appendJsonOSUTF8(ou8, sb); + break; + case OSDType.UUID: + sb.AppendASCII('"'); + sb.AppendUUID(osd.AsUUID()); + sb.AppendASCII('"'); + break; + case OSDType.Date: + appendJsonString(osd.AsString(), sb); + break; + case OSDType.Binary: + byte[] binary = osd.AsBinary(); + i = 0; + sb.AppendASCII('['); + while (i < binary.Length - 1) + { + sb.AppendInt(binary[i++]); + sb.AppendASCII(','); + } + if (i < binary.Length) + sb.AppendInt(binary[i]); + sb.AppendASCII(']'); + break; + case OSDType.Array: + sb.AppendASCII('['); + OSDArray array = (OSDArray)osd; + i = 0; + while (i < array.Count - 1) + { + SerializeJson(array[i++], sb, preserveDefaults); + sb.AppendASCII(','); + } + if (i < array.Count) + SerializeJson(array[i], sb, preserveDefaults); + sb.AppendASCII(']'); + break; + case OSDType.Map: + sb.AppendASCII('{'); + OSDMap map = (OSDMap)osd; + i = 0; + foreach(KeyValuePair kvp in map) + { + if(preserveDefaults) + { + if (i++ > 0) + sb.AppendASCII(','); + appendJsonString(kvp.Key, sb); + sb.AppendASCII(':'); + SerializeJson(kvp.Value, sb, true); + } + else + SerializeJsonMapNoDefaults(kvp.Key, kvp.Value, ref i, sb); + } + sb.AppendASCII('}'); + break; + case OSDType.Unknown: + default: + sb.Append(osUTF8Const.OSUTF8null); + break; + } + } + + public static void SerializeJsonMapNoDefaults(string name, OSD osd, ref int mapcont, osUTF8 sb) + { + int i; + switch (osd.Type) + { + case OSDType.Boolean: + bool ob = osd.AsBoolean(); + if (ob) + { + if (mapcont++ > 0) + sb.AppendASCII(','); + appendJsonString(name, sb); + sb.AppendASCII(':'); + sb.Append(ob ? osUTF8Const.OSUTF8true : osUTF8Const.OSUTF8false); + } + break; + case OSDType.Integer: + int oi = osd.AsInteger(); + if(oi != 0) + { + if (mapcont++ > 0) + sb.AppendASCII(','); + appendJsonString(name, sb); + sb.AppendASCII(':'); + sb.AppendInt(oi); + } + break; + case OSDType.Long: + long ol = osd.AsLong(); + if(ol != 0) + { + if (mapcont++ > 0) + sb.AppendASCII(','); + appendJsonString(name, sb); + sb.AppendASCII(':'); + sb.AppendInt(ol); + } + break; + + case OSDType.Real: + double od = osd.AsReal(); + if(od != 0) + { + if (mapcont++ > 0) + sb.AppendASCII(','); + appendJsonString(name, sb); + sb.AppendASCII(':'); + string str = Convert.ToString(od, NumberFormatInfo.InvariantInfo); + sb.AppendASCII(str); + + if (str.IndexOfAny(new char[] { '.', 'E' }) == -1) + sb.AppendASCII(".0"); + } + break; + case OSDType.String: + case OSDType.URI: + case OSDType.LLSDxml: + string ostr = osd.AsString(); + if (!string.IsNullOrEmpty(ostr)) + { + if (mapcont++ > 0) + sb.AppendASCII(','); + appendJsonString(name, sb); + sb.AppendASCII(':'); + appendJsonString(ostr, sb); + } + break; + case OSDType.OSDUTF8: + osUTF8 ou8 = ((OSDUTF8)osd).value; + if (ou8 != null && ou8.Length > 0) + { + if (mapcont++ > 0) + sb.AppendASCII(','); + appendJsonString(name, sb); + sb.AppendASCII(':'); + appendJsonOSUTF8(ou8, sb); + } + break; + case OSDType.UUID: + UUID ou = osd.AsUUID(); + if(ou.IsNotZero()) + { + if (mapcont++ > 0) + sb.AppendASCII(','); + appendJsonString(name, sb); + sb.AppendASCII(":\""); + sb.AppendUUID(ou); + sb.AppendASCII('"'); + } + break; + case OSDType.Date: + if (mapcont++ > 0) + sb.AppendASCII(','); + appendJsonString(name, sb); + sb.AppendASCII(':'); + appendJsonString(osd.AsString(), sb); + break; + case OSDType.Binary: + byte[] binary = osd.AsBinary(); + if (mapcont++ > 0) + sb.AppendASCII(','); + appendJsonString(name, sb); + sb.AppendASCII(":["); + if (binary != null && binary.Length > 0) + { + i = 0; + while (i < binary.Length - 1) + { + sb.AppendInt(binary[i++]); + sb.AppendASCII(','); + } + if (i < binary.Length) + sb.AppendInt(binary[i]); + } + sb.AppendASCII(']'); + break; + case OSDType.Array: + if (mapcont++ > 0) + sb.AppendASCII(","); + appendJsonString(name, sb); + sb.AppendASCII(":["); + + OSDArray array = (OSDArray)osd; + if (array != null && array.Count > 0) + { + i = 0; + while (i < array.Count - 1) + { + SerializeJson(array[i++], sb, false); + sb.AppendASCII(','); + } + if (i < array.Count) + SerializeJson(array[i], sb, false); + } + sb.AppendASCII(']'); + break; + case OSDType.Map: + OSDMap map = (OSDMap)osd; + if (map != null && map.Count > 0) + { + if (mapcont++ > 0) + sb.AppendASCII(','); + appendJsonString(name, sb); + sb.AppendASCII(":{"); + + i = 0; + foreach (KeyValuePair kvp in map) + SerializeJsonMapNoDefaults(kvp.Key, kvp.Value, ref i, sb); + sb.AppendASCII('}'); + } + break; + case OSDType.Unknown: + default: + break; + } + } + + public static void appendJsonString(string str, osUTF8 sb) + { + sb.AppendASCII('"'); + for (int i = 0; i < str.Length; i++) + { + char c = str[i]; + switch (c) + { + case '\n': + sb.AppendASCII("\\n"); + break; + + case '\r': + sb.AppendASCII("\\r"); + break; + + case '\t': + sb.AppendASCII("\\t"); + break; + + case '"': + //case '/': + case '\\': + sb.AppendASCII('\\'); + sb.AppendASCII(c); + break; + + case '\f': + sb.AppendASCII("\\f"); + break; + + case '\b': + sb.AppendASCII("\\b"); + break; + + default: + // Default, turn into a \uXXXX sequence + if (c >= 32 && c <= 126) + sb.AppendASCII(c); + else + { + sb.AppendASCII("\\u"); + sb.Append(Utils.NibbleToHexUpper((byte)(c >> 12))); + sb.Append(Utils.NibbleToHexUpper((byte)(c >> 8))); + sb.Append(Utils.NibbleToHexUpper((byte)(c >> 4))); + sb.Append(Utils.NibbleToHexUpper((byte)c)); + } + break; + } + } + sb.AppendASCII('"'); + } + + public static void appendJsonOSUTF8(osUTF8 str, osUTF8 sb) + { + int code; + sb.AppendASCII('"'); + for (int i = 0; i < str.Length; i++) + { + byte c = str[i]; + if (c < 0x80) + { + switch (c) + { + case (byte)'\n': + sb.AppendASCII("\\n"); + break; + + case (byte)'\r': + sb.AppendASCII("\\r"); + break; + + case (byte)'\t': + sb.AppendASCII("\\t"); + break; + + case (byte)'"': + case (byte)'/': + case (byte)'\\': + sb.AppendASCII('\\'); + sb.Append(c); + break; + + case (byte)'\f': + sb.AppendASCII("\\f"); + break; + + case (byte)'\b': + sb.AppendASCII("\\b"); + break; + + default: + // Default, turn into a \uXXXX sequence + if (c >= 32 && c <= 126) + sb.Append(c); + else + { + sb.AppendASCII("\\u00"); + sb.Append(Utils.NibbleToHexUpper((byte)(c >> 4))); + sb.Append(Utils.NibbleToHexUpper((byte)c)); + } + break; + } + } + if(c < 0xc0) + continue; // invalid + if (c < 0xe0) + { + // 2 bytes + if (i + 1 >= str.Length) + return; + + code = (c & 0x1f) << 6; + code |= str[++i] & 0x3f; + + sb.AppendASCII("\\u0"); + sb.Append(Utils.NibbleToHexUpper((byte)(code >> 8))); + sb.Append(Utils.NibbleToHexUpper((byte)(code >> 4))); + sb.Append(Utils.NibbleToHexUpper((byte)code)); + } + else if (c < 0xF0) + { + // 3 bytes + if (i + 2 >= str.Length) + return; + + // 1110aaaa 10bbbbcc 10ccdddd + sb.AppendASCII("\\u"); + sb.Append(Utils.NibbleToHexUpper(c)); + c = str[++i]; + sb.Append(Utils.NibbleToHexUpper((byte)(c >> 2))); + code = (c & 3) << 2; + c = str[++i]; + code |= (c & 0x30) >> 4; + sb.Append(Utils.NibbleToHexUpper((byte)code)); + sb.Append(Utils.NibbleToHexUpper(c)); + } + else if (c < 0xf8 ) + { + if (i + 3 >= str.Length) + return; + + code = (c & 0x07) << 18; + code |= (str[++i] & 0x3f) << 6; + code |= (str[++i] & 0x3f) << 6; + code |= str[++i] & 0x3f; + int a = (code >> 10) + 0xd7c0; + code &= (code & 0x3ff) + 0xdc00; + + sb.AppendASCII("\\u"); + sb.Append(Utils.NibbleToHexUpper((byte)(a >> 12))); + sb.Append(Utils.NibbleToHexUpper((byte)(a >> 8))); + sb.Append(Utils.NibbleToHexUpper((byte)(a >> 4))); + sb.Append(Utils.NibbleToHexUpper((byte)a)); + sb.AppendASCII("\\u"); + sb.Append(Utils.NibbleToHexUpper((byte)(code >> 12))); + sb.Append(Utils.NibbleToHexUpper((byte)(code >> 8))); + sb.Append(Utils.NibbleToHexUpper((byte)(code >> 4))); + sb.Append(Utils.NibbleToHexUpper((byte)code)); + } + } + sb.AppendASCII('"'); + } } } diff --git a/OpenMetaverse.StructuredData/LLSD/BinaryLLSD.cs b/OpenMetaverse.StructuredData/LLSD/BinaryLLSD.cs index 352e9a4c..22a05e3d 100644 --- a/OpenMetaverse.StructuredData/LLSD/BinaryLLSD.cs +++ b/OpenMetaverse.StructuredData/LLSD/BinaryLLSD.cs @@ -184,6 +184,7 @@ private static void SerializeLLSDBinaryElement(MemoryStream stream, OSD osd) stream.Write(stringLengthNetEnd, 0, int32Length); stream.Write(rawString, 0, rawString.Length); break; + case OSDType.Long: case OSDType.Binary: stream.WriteByte(binaryBinaryMarker); byte[] rawBinary = osd.AsBinary(); diff --git a/OpenMetaverse.StructuredData/LLSD/LLSDxmlEncode.cs b/OpenMetaverse.StructuredData/LLSD/LLSDxmlEncode.cs index 26db742f..5bfac35c 100644 --- a/OpenMetaverse.StructuredData/LLSD/LLSDxmlEncode.cs +++ b/OpenMetaverse.StructuredData/LLSD/LLSDxmlEncode.cs @@ -49,7 +49,7 @@ public static void AddStart(osUTF8 sb, bool addxmlversion = false) sb.Append(osUTF8Const.XMLllsdStart); } - public static osUTF8 Start(int size = 4096, bool addxmlversion = false) + public static osUTF8 Start(int size = OSUTF8Cached.MAXDATASIZE, bool addxmlversion = false) { osUTF8 sb = OSUTF8Cached.Acquire(size); if(addxmlversion) @@ -128,7 +128,7 @@ public static void AddEndArrayAndMap(osUTF8 sb) // undefined or null public static void AddUnknownElem(osUTF8 sb) { - sb.Append(osUTF8Const.XMLundef); + sb.Append(""u8); } public static void AddElem(bool e, osUTF8 sb) @@ -315,7 +315,7 @@ public static void AddElem(double e, osUTF8 sb) public static void AddElem(UUID e, osUTF8 sb) { - if(e == UUID.Zero) + if(e.IsZero()) sb.Append(osUTF8Const.XMLuuidEmpty); else { @@ -678,7 +678,7 @@ public static void AddElem(string name, UUID e, osUTF8 sb) sb.AppendASCII(name); sb.Append(osUTF8Const.XMLkeyEnd); - if (e == UUID.Zero) + if (e.IsZero()) sb.Append(osUTF8Const.XMLuuidEmpty); else { @@ -810,7 +810,7 @@ public static void AddElem_name(string s, osUTF8 sb) public static void AddElem_agent_id(UUID e, osUTF8 sb) { - if (e == UUID.Zero) + if (e.IsZero()) sb.Append(osUTF8Const.XMLelement_agent_id_Empty); else { @@ -822,7 +822,7 @@ public static void AddElem_agent_id(UUID e, osUTF8 sb) public static void AddElem_owner_id(UUID e, osUTF8 sb) { - if (e == UUID.Zero) + if (e.IsZero()) sb.Append(osUTF8Const.XMLelement_owner_id_Empty); else { @@ -834,7 +834,7 @@ public static void AddElem_owner_id(UUID e, osUTF8 sb) public static void AddElem_parent_id(UUID e, osUTF8 sb) { - if (e == UUID.Zero) + if (e.IsZero()) sb.Append(osUTF8Const.XMLelement_parent_id_Empty); else { @@ -846,7 +846,7 @@ public static void AddElem_parent_id(UUID e, osUTF8 sb) public static void AddElem_folder_id(UUID e, osUTF8 sb) { - if (e == UUID.Zero) + if (e.IsZero()) sb.Append(osUTF8Const.XMLelement_folder_id_Empty); else { @@ -856,6 +856,93 @@ public static void AddElem_folder_id(UUID e, osUTF8 sb) } } + public static void AddElem_asset_id(UUID e, osUTF8 sb) + { + if (e.IsZero()) + sb.Append(osUTF8Const.XMLelement_asset_id_Empty); + else + { + sb.Append(osUTF8Const.XMLelement_asset_id_Start); + sb.AppendUUID(e); + sb.Append(osUTF8Const.XMLuuidEnd); + } + } + + public static void AddElem_item_id(UUID e, osUTF8 sb) + { + if (e.IsZero()) + sb.Append(osUTF8Const.XMLelement_item_id_Empty); + else + { + sb.Append(osUTF8Const.XMLelement_item_id_Start); + sb.AppendUUID(e); + sb.Append(osUTF8Const.XMLuuidEnd); + } + } + + public static void AddElem_category_id(UUID e, osUTF8 sb) + { + if (e.IsZero()) + sb.Append(osUTF8Const.XMLelement_category_id_Empty); + else + { + sb.Append(osUTF8Const.XMLelement_category_id_Start); + sb.AppendUUID(e); + sb.Append(osUTF8Const.XMLuuidEnd); + } + } + + public static void AddElem_creator_id(UUID e, osUTF8 sb) + { + if (e.IsZero()) + sb.Append(osUTF8Const.XMLelement_creator_id_Empty); + else + { + sb.Append(osUTF8Const.XMLelement_creator_id_Start); + sb.AppendUUID(e); + sb.Append(osUTF8Const.XMLuuidEnd); + } + } + + public static void AddElem_group_id(UUID e, osUTF8 sb) + { + if (e.IsZero()) + sb.Append(osUTF8Const.XMLelement_group_id_Empty); + else + { + sb.Append(osUTF8Const.XMLelement_group_id_Start); + sb.AppendUUID(e); + sb.Append(osUTF8Const.XMLuuidEnd); + } + } + + public static void AddElem_version(int v, osUTF8 sb) + { + if (v == 0) + sb.Append(osUTF8Const.XMLelement_version_Empty); + else + { + sb.Append(osUTF8Const.XMLelement_version_Start); + sb.AppendInt(v); + sb.Append(osUTF8Const.XMLintegerEnd); + } + } + + public static void AddElem_sale_info(int price, byte type, osUTF8 sb) + { + if(price == 0 && type == 0) + sb.Append(osUTF8Const.XMLelement_sale_info_Empty); + else + { + sb.Append(osUTF8Const.XMLelement_sale_info_Start); + sb.AppendInt(price); + sb.Append(osUTF8Const.XMLelement_sale_info_Mid); + sb.AppendInt(type); + sb.Append(osUTF8Const.XMLelement_sale_info_End); + } + } + + public static byte[] ulongToByteArray(ulong uLongValue) { return new byte[8] diff --git a/OpenMetaverse.StructuredData/LLSD/NotationLLSD.cs b/OpenMetaverse.StructuredData/LLSD/NotationLLSD.cs index 812f57b1..834a99f7 100644 --- a/OpenMetaverse.StructuredData/LLSD/NotationLLSD.cs +++ b/OpenMetaverse.StructuredData/LLSD/NotationLLSD.cs @@ -232,7 +232,7 @@ private static OSD DeserializeLLSDNotationElement(TextReader reader) if (reader.Read(uuidBuf, 0, 36) < 36) throw new OSDException("Notation LLSD parsing: Unexpected end of stream in UUID."); UUID lluuid; - if (!UUID.TryParse(new String(uuidBuf), out lluuid)) + if (!UUID.TryParse(new String(uuidBuf).AsSpan(), out lluuid)) throw new OSDException("Notation LLSD parsing: Invalid UUID discovered."); osd = OSD.FromUUID(lluuid); break; @@ -470,6 +470,10 @@ private static void SerializeLLSDNotationElement(TextWriter writer, OSD osd) EscapeCharacter(osd.AsString(), singleQuotesNotationMarker, writer); writer.Write(singleQuotesNotationMarker); break; + case OSDType.LLSDxml: + writer.Write(osd.AsString()); + break; + case OSDType.Long: case OSDType.Binary: writer.Write(binaryNotationMarker); writer.Write("64"); @@ -547,8 +551,7 @@ private static void SerializeLLSDNotationArray(TextWriter writer, OSDArray osdAr { writer.Write(arrayBeginNotationMarker); int lastIndex = osdArray.Count - 1; - - for (int idx = 0; idx <= lastIndex; idx++) + for (int idx = 0; idx < osdArray.Count; idx++) { SerializeLLSDNotationElement(writer, osdArray[idx]); if (idx < lastIndex) @@ -608,6 +611,10 @@ private static void SerializeLLSDNotationElementFormatted(TextWriter writer, str EscapeCharacter(osd.AsString(), singleQuotesNotationMarker, writer); writer.Write(singleQuotesNotationMarker); break; + case OSDType.LLSDxml: + writer.Write(osd.AsString()); + break; + case OSDType.Long: case OSDType.Binary: writer.Write(binaryNotationMarker); writer.Write("64"); @@ -880,7 +887,7 @@ public static int BufferCharactersEqual(TextReader reader, char[] buffer, int of /// /// /// - /// + /// /// public static string UnescapeCharacter(String s, char d) { @@ -959,7 +966,7 @@ public static string UnescapeCharacter(String s, char d) /// /// /// - /// + /// /// public static string EscapeCharacter(String s, char d) { diff --git a/OpenMetaverse.StructuredData/LLSD/XmlLLSD.cs b/OpenMetaverse.StructuredData/LLSD/XmlLLSD.cs index 929bd5d9..e39afffe 100644 --- a/OpenMetaverse.StructuredData/LLSD/XmlLLSD.cs +++ b/OpenMetaverse.StructuredData/LLSD/XmlLLSD.cs @@ -1,1031 +1,870 @@ -/* - * Copyright (c) 2006-2016, openmetaverse.co - * All rights reserved. - * - * - Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, this - * list of conditions and the following disclaimer. - * - Neither the name of the openmetaverse.co nor the names - * of its contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections.Generic; -using System.IO; -using System.Xml; -using System.Xml.Schema; -using System.Text; -using System.Runtime.InteropServices; -using OpenMetaverse; - -namespace OpenMetaverse.StructuredData -{ - /// - /// - /// - public static partial class OSDParser - { - private static XmlSchema XmlSchema; - private static XmlTextReader XmlTextReader; - private static string LastXmlErrors = String.Empty; - private static object XmlValidationLock = new object(); - - /// - /// - /// - /// - /// - public static OSD DeserializeLLSDXml(byte[] xmlData) - { - using (MemoryStream ms = new MemoryStream(xmlData)) - using (XmlTextReader xrd = new XmlTextReader(ms)) - return DeserializeLLSDXml(xrd); - } - - public static OSD DeserializeLLSDXml(Stream xmlStream) - { - using (XmlTextReader xrd = new XmlTextReader(xmlStream)) - return DeserializeLLSDXml(xrd); - } - - /// - /// - /// - /// - /// - public static OSD DeserializeLLSDXml(string xmlData) - { - using (StringReader sr = new StringReader(xmlData)) - using (XmlTextReader xrd = new XmlTextReader(sr)) - return DeserializeLLSDXml(xrd); - } - - /// - /// - /// - /// - /// - public static OSD DeserializeLLSDXml(XmlTextReader xmlData) - { - try - { - xmlData.Read(); - SkipWhitespace(xmlData); - - xmlData.Read(); - OSD ret = ParseLLSDXmlElement(xmlData); - - return ret; - } - catch - { - return new OSD(); - } - } - - public static byte[] SerializeLLSDXmlToBytes(OSD data, bool formal = false) - { - osUTF8 tmp = OSUTF8Cached.Acquire(); - if (formal) - tmp.Append(osUTF8Const.XMLformalHeaderllsdstart); - else - tmp.Append(osUTF8Const.XMLllsdStart); - SerializeLLSDXmlElement(tmp, data, formal); - tmp.Append(osUTF8Const.XMLllsdEnd); - - return OSUTF8Cached.GetArrayAndRelease(tmp); - } - - public static byte[] SerializeLLSDXmlToBytes(OSD data) - { - osUTF8 tmp = OSUTF8Cached.Acquire(); - - tmp.Append(osUTF8Const.XMLllsdStart); - SerializeLLSDXmlElement(tmp, data, false); - tmp.Append(osUTF8Const.XMLllsdEnd); - - return OSUTF8Cached.GetArrayAndRelease(tmp); - } - - public static byte[] SerializeInnerLLSDXmlToBytes(OSD data) - { - osUTF8 tmp = OSUTF8Cached.Acquire(); - SerializeLLSDXmlElement(tmp, data, false); - - return OSUTF8Cached.GetArrayAndRelease(tmp); - } - - public static byte[] SerializeLLSDXmlBytes(OSD data, bool formal = false) - { - return SerializeLLSDXmlToBytes(data, formal); - } - - /// - /// - /// - /// - /// - public static string SerializeLLSDXmlString(OSD data, bool formal = false) - { - StringBuilder sb = osStringBuilderCache.Acquire(); - if (formal) - sb.Append(""); - - sb.Append(""); - SerializeLLSDXmlElement(sb, data, formal); - sb.Append(""); - - return osStringBuilderCache.GetStringAndRelease(sb); - } - - public static string SerializeLLSDInnerXmlString(OSD data, bool formal = false) - { - StringBuilder sb = osStringBuilderCache.Acquire(); - SerializeLLSDXmlElement(sb, data, formal); - - return osStringBuilderCache.GetStringAndRelease(sb); - } - - /// - /// - /// - /// - /// - public static void SerializeLLSDXmlElement(StringBuilder sb, OSD data, bool formal) - { - switch (data.Type) - { - case OSDType.Unknown: - sb.Append(""); - break; - case OSDType.Boolean: - if (data.AsBoolean()) - sb.Append("1"); - else - sb.Append("0"); - break; - case OSDType.Integer: - sb.Append(""); - sb.Append(data.AsString()); - sb.Append(""); - break; - case OSDType.Real: - sb.Append(""); - sb.Append(data.AsString()); - sb.Append(""); - break; - case OSDType.String: - sb.Append(""); - EscapeToXML(data.AsString(), sb); - sb.Append(""); - break; - case OSDType.UUID: - sb.Append(""); - sb.Append(data.AsString()); - sb.Append(""); - break; - case OSDType.Date: - sb.Append(""); - sb.Append(data.AsString()); - sb.Append(""); - break; - case OSDType.URI: - sb.Append(""); - sb.Append(data.AsString()); - sb.Append(""); - break; - case OSDType.Binary: - if (formal) - sb.Append(""); - else - sb.Append(""); - base64Encode(data.AsBinary(), sb); - sb.Append(""); - break; - case OSDType.Map: - OSDMap map = (OSDMap)data; - sb.Append(""); - foreach (KeyValuePair kvp in map) - { - sb.Append(""); - sb.Append(kvp.Key); - sb.Append(""); - - SerializeLLSDXmlElement(sb, kvp.Value, formal); - } - sb.Append(""); - break; - case OSDType.Array: - OSDArray array = (OSDArray)data; - sb.Append(""); - for (int i = 0; i < array.Count; i++) - { - SerializeLLSDXmlElement(sb, array[i], formal); - } - sb.Append(""); - break; - case OSDType.LLSDxml: - sb.Append(data.AsString()); - break; - default: - break; - } - } - - public static void EscapeToXML(string s, StringBuilder sb) - { - char c; - for (int i = 0; i < s.Length; ++i) - { - c = s[i]; - switch (c) - { - case '<': - sb.Append("<"); - break; - case '>': - sb.Append(">"); - break; - case '&': - sb.Append("&"); - break; - case '"': - sb.Append("""); - break; - case '\\': - sb.Append("'"); - break; - default: - sb.Append(c); - break; - } - } - } - - public static void EscapeASCIIToXML(osUTF8 ms, string s) - { - char c; - for (int i = 0; i < s.Length; i++) - { - c = s[i]; - switch (c) - { - case '<': - ms.Append(osUTF8Const.XMLamp_lt); - break; - case '>': - ms.Append(osUTF8Const.XMLamp_gt); - break; - case '&': - ms.Append(osUTF8Const.XMLamp); - break; - case '"': - ms.Append(osUTF8Const.XMLamp_quot); - break; - case '\\': - ms.Append(osUTF8Const.XMLamp_apos); - break; - default: - ms.AppendASCII(c); - break; - } - } - } - - public static void EscapeToXML(osUTF8 ms, string s) - { - char c; - for (int i = 0; i < s.Length; i++) - { - c = s[i]; - switch (c) - { - case '<': - ms.Append(osUTF8Const.XMLamp_lt); - break; - case '>': - ms.Append(osUTF8Const.XMLamp_gt); - break; - case '&': - ms.Append(osUTF8Const.XMLamp); - break; - case '"': - ms.Append(osUTF8Const.XMLamp_quot); - break; - case '\\': - ms.Append(osUTF8Const.XMLamp_apos); - break; - default: - ms.AppendCharBytes(c, ref s, ref i); - break; - } - } - } - - public static void EscapeToXML(osUTF8 ms, osUTF8 s) - { - byte c; - for (int i = 0; i < s.Length; i++) - { - c = s[i]; - switch (c) - { - case (byte)'<': - ms.Append(osUTF8Const.XMLamp_lt); - break; - case (byte)'>': - ms.Append(osUTF8Const.XMLamp_gt); - break; - case (byte)'&': - ms.Append(osUTF8Const.XMLamp); - break; - case (byte)'"': - ms.Append(osUTF8Const.XMLamp_quot); - break; - case (byte)'\\': - ms.Append(osUTF8Const.XMLamp_apos); - break; - default: - ms.Append(c); - break; - } - } - } - - public static void SerializeLLSDXmlElement(osUTF8 mb, OSD data, bool formal) - { - switch (data.Type) - { - case OSDType.Unknown: - mb.Append(osUTF8Const.XMLundef); - break; - case OSDType.Boolean: - if (data.AsBoolean()) - mb.Append(osUTF8Const.XMLfullbooleanOne); - else - mb.Append(osUTF8Const.XMLfullbooleanZero); - break; - case OSDType.Integer: - mb.Append(osUTF8Const.XMLintegerStart); - mb.AppendInt(data.AsInteger()); - mb.Append(osUTF8Const.XMLintegerEnd); - break; - case OSDType.Real: - mb.Append(osUTF8Const.XMLrealStart); - mb.AppendASCII(data.ToString()); - mb.Append(osUTF8Const.XMLrealEnd); - break; - case OSDType.String: - mb.Append(osUTF8Const.XMLstringStart); - EscapeToXML(mb, data); - mb.Append(osUTF8Const.XMLstringEnd); - break; - case OSDType.UUID: - mb.Append(osUTF8Const.XMLuuidStart); - mb.AppendUUID(data.AsUUID()); - mb.Append(osUTF8Const.XMLuuidEnd); - break; - case OSDType.Date: - mb.Append(osUTF8Const.XMLdateStart); - mb.AppendASCII(data.ToString()); - mb.Append(osUTF8Const.XMLdateEnd); - break; - case OSDType.URI: - mb.Append(osUTF8Const.XMLuriStart); - EscapeToXML(mb, data.ToString()); - mb.Append(osUTF8Const.XMLuriEnd); - break; - case OSDType.Binary: - if (formal) - mb.Append(osUTF8Const.XMLformalBinaryStart); - else - mb.Append(osUTF8Const.XMLbinaryStart); - base64Encode(data.AsBinary(), mb); - mb.Append(osUTF8Const.XMLbinaryEnd); - break; - case OSDType.Map: - mb.Append(osUTF8Const.XMLmapStart); - foreach (KeyValuePair kvp in (OSDMap)data) - { - mb.Append(osUTF8Const.XMLkeyStart); - mb.Append(kvp.Key.ToString()); - mb.Append(osUTF8Const.XMLkeyEnd); - - SerializeLLSDXmlElement(mb, kvp.Value, formal); - } - mb.Append(osUTF8Const.XMLmapEnd); - break; - case OSDType.Array: - OSDArray array = (OSDArray)data; - mb.Append(osUTF8Const.XMLarrayStart); - for (int i = 0; i < array.Count; i++) - { - SerializeLLSDXmlElement(mb, array[i], formal); - } - mb.Append(osUTF8Const.XMLarrayEnd); - break; - case OSDType.LLSDxml: - mb.Append(data.AsString()); - break; - default: - break; - } - } - - public static unsafe void base64Encode(byte[] data, osUTF8 mb) - { - int lenMod3 = data.Length % 3; - int len = data.Length - lenMod3; - - mb.CheckCapacity(4 * data.Length / 3); - - fixed (byte* d = data, b64 = osUTF8Const.base64Bytes) - { - int i = 0; - while (i < len) - { - mb.Append(b64[d[i] >> 2]); - mb.Append(b64[((d[i] & 0x03) << 4) | ((d[i + 1] & 0xf0) >> 4)]); - mb.Append(b64[((d[i + 1] & 0x0f) << 2) | ((d[i + 2] & 0xc0) >> 6)]); - mb.Append(b64[d[i + 2] & 0x3f]); - i += 3; - } - - switch (lenMod3) - { - case 2: - { - i = len; - mb.Append(b64[d[i] >> 2]); - mb.Append(b64[((d[i] & 0x03) << 4) | ((d[i + 1] & 0xf0) >> 4)]); - mb.Append(b64[((d[i + 1] & 0x0f) << 2)]); - mb.Append((byte)'='); - break; - } - case 1: - { - i = len; - mb.Append(b64[d[i] >> 2]); - mb.Append(b64[(d[i] & 0x03) << 4]); - mb.Append((byte)'='); - mb.Append((byte)'='); - break; - } - } - } - } - - public static unsafe void base64Encode(byte[] data, int start, int lenght, osUTF8 mb) - { - int lenMod3 = lenght % 3; - int len = lenght - lenMod3; - - fixed (byte* d = &data[start], b64 = osUTF8Const.base64Bytes) - { - int i = 0; - while (i < len) - { - mb.Append(b64[d[i] >> 2]); - mb.Append(b64[((d[i] & 0x03) << 4) | ((d[i + 1] & 0xf0) >> 4)]); - mb.Append(b64[((d[i + 1] & 0x0f) << 2) | ((d[i + 2] & 0xc0) >> 6)]); - mb.Append(b64[d[i + 2] & 0x3f]); - i += 3; - } - - switch (lenMod3) - { - case 2: - { - i = len; - mb.Append(b64[d[i] >> 2]); - mb.Append(b64[((d[i] & 0x03) << 4) | ((d[i + 1] & 0xf0) >> 4)]); - mb.Append(b64[((d[i + 1] & 0x0f) << 2)]); - mb.Append((byte)'='); - break; - } - case 1: - { - i = len; - mb.Append(b64[d[i] >> 2]); - mb.Append(b64[(d[i] & 0x03) << 4]); - mb.Append((byte)'='); - mb.Append((byte)'='); - break; - } - } - } - } - - static readonly char[] base64Chars = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O', - 'P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d', - 'e','f','g','h','i','j','k','l','m','n','o','p','q','r','s', - 't','u','v','w','x','y','z','0','1','2','3','4','5','6','7', - '8','9','+','/'}; - - public static unsafe void base64Encode(byte[] data, StringBuilder sb) - { - int lenMod3 = data.Length % 3; - int len = data.Length - lenMod3; - - fixed (byte* d = data) - { - fixed (char* b64 = base64Chars) - { - int i = 0; - while (i < len) - { - sb.Append(b64[d[i] >> 2]); - sb.Append(b64[((d[i] & 0x03) << 4) | ((d[i + 1] & 0xf0) >> 4)]); - sb.Append(b64[((d[i + 1] & 0x0f) << 2) | ((d[i + 2] & 0xc0) >> 6)]); - sb.Append(b64[d[i + 2] & 0x3f]); - i += 3; - } - - switch (lenMod3) - { - case 2: - { - i = len; - sb.Append(b64[d[i] >> 2]); - sb.Append(b64[((d[i] & 0x03) << 4) | ((d[i + 1] & 0xf0) >> 4)]); - sb.Append(b64[((d[i + 1] & 0x0f) << 2)]); - sb.Append('='); - break; - } - case 1: - { - i = len; - sb.Append(b64[d[i] >> 2]); - sb.Append(b64[(d[i] & 0x03) << 4]); - sb.Append("=="); - break; - } - } - } - } - } - - - /// - /// - /// - /// - /// - /// - public static bool TryValidateLLSDXml(XmlTextReader xmlData, out string error) - { - lock (XmlValidationLock) - { - LastXmlErrors = String.Empty; - XmlTextReader = xmlData; - - CreateLLSDXmlSchema(); - - XmlReaderSettings readerSettings = new XmlReaderSettings(); - readerSettings.ValidationType = ValidationType.Schema; - readerSettings.Schemas.Add(XmlSchema); - readerSettings.ValidationEventHandler += new ValidationEventHandler(LLSDXmlSchemaValidationHandler); - - using (XmlReader reader = XmlReader.Create(xmlData, readerSettings)) - { - - try - { - while (reader.Read()) { } - } - catch (XmlException) - { - error = LastXmlErrors; - return false; - } - - if (LastXmlErrors == String.Empty) - { - error = null; - return true; - } - else - { - error = LastXmlErrors; - return false; - } - } - } - } - - /// - /// - /// - /// - /// - private static OSD ParseLLSDXmlElement(XmlTextReader reader) - { - SkipWhitespace(reader); - - if (reader.NodeType != XmlNodeType.Element) - throw new OSDException("Expected an element"); - - string type = reader.LocalName; - OSD ret; - - switch (type) - { - case "undef": - if (reader.IsEmptyElement) - { - reader.Read(); - return new OSD(); - } - - reader.Read(); - SkipWhitespace(reader); - ret = new OSD(); - break; - case "boolean": - if (reader.IsEmptyElement) - { - reader.Read(); - return OSD.FromBoolean(false); - } - - if (reader.Read()) - { - string s = reader.ReadString().Trim(); - - if (!String.IsNullOrEmpty(s) && (s == "true" || s == "1")) - { - ret = OSD.FromBoolean(true); - break; - } - } - - ret = OSD.FromBoolean(false); - break; - case "integer": - if (reader.IsEmptyElement) - { - reader.Read(); - return OSD.FromInteger(0); - } - - if (reader.Read()) - { - int value = 0; - Int32.TryParse(reader.ReadString().Trim(), out value); - ret = OSD.FromInteger(value); - break; - } - - ret = OSD.FromInteger(0); - break; - case "real": - if (reader.IsEmptyElement) - { - reader.Read(); - return OSD.FromReal(0d); - } - - if (reader.Read()) - { - double value = 0d; - string str = reader.ReadString().Trim().ToLower(); - - if (str == "nan") - value = Double.NaN; - else - Utils.TryParseDouble(str, out value); - - ret = OSD.FromReal(value); - break; - } - - ret = OSD.FromReal(0d); - break; - case "uuid": - if (reader.IsEmptyElement) - { - reader.Read(); - return OSD.FromUUID(UUID.Zero); - } - - if (reader.Read()) - { - UUID value = UUID.Zero; - UUID.TryParse(reader.ReadString().Trim(), out value); - ret = OSD.FromUUID(value); - break; - } - - ret = OSD.FromUUID(UUID.Zero); - break; - case "date": - if (reader.IsEmptyElement) - { - reader.Read(); - return OSD.FromDate(Utils.Epoch); - } - - if (reader.Read()) - { - DateTime value = Utils.Epoch; - DateTime.TryParse(reader.ReadString().Trim(), out value); - ret = OSD.FromDate(value); - break; - } - - ret = OSD.FromDate(Utils.Epoch); - break; - case "string": - if (reader.IsEmptyElement) - { - reader.Read(); - return OSD.FromString(String.Empty); - } - - if (reader.Read()) - { - ret = OSD.FromString(reader.ReadString()); - break; - } - - ret = OSD.FromString(String.Empty); - break; - case "binary": - if (reader.IsEmptyElement) - { - reader.Read(); - return OSD.FromBinary(Utils.EmptyBytes); - } - - if (reader.GetAttribute("encoding") != null && reader.GetAttribute("encoding") != "base64") - throw new OSDException("Unsupported binary encoding: " + reader.GetAttribute("encoding")); - - if (reader.Read()) - { - try - { - ret = OSD.FromBinary(Convert.FromBase64String(reader.ReadString().Trim())); - break; - } - catch (FormatException ex) - { - throw new OSDException("Binary decoding exception: " + ex.Message); - } - } - - ret = OSD.FromBinary(Utils.EmptyBytes); - break; - case "uri": - if (reader.IsEmptyElement) - { - reader.Read(); - return OSD.FromUri(new Uri(String.Empty, UriKind.RelativeOrAbsolute)); - } - - if (reader.Read()) - { - ret = OSD.FromUri(new Uri(reader.ReadString(), UriKind.RelativeOrAbsolute)); - break; - } - - ret = OSD.FromUri(new Uri(String.Empty, UriKind.RelativeOrAbsolute)); - break; - case "map": - return ParseLLSDXmlMap(reader); - case "array": - return ParseLLSDXmlArray(reader); - default: - reader.Read(); - ret = null; - break; - } - - if (reader.NodeType != XmlNodeType.EndElement || reader.LocalName != type) - { - throw new OSDException("Expected "); - } - else - { - reader.Read(); - return ret; - } - } - - private static OSDMap ParseLLSDXmlMap(XmlTextReader reader) - { - if (reader.NodeType != XmlNodeType.Element || reader.LocalName != "map") - throw new NotImplementedException("Expected "); - - OSDMap map = new OSDMap(); - - if (reader.IsEmptyElement) - { - reader.Read(); - return map; - } - - if (reader.Read()) - { - while (true) - { - SkipWhitespace(reader); - - if (reader.NodeType == XmlNodeType.EndElement && reader.LocalName == "map") - { - reader.Read(); - break; - } - - if (reader.NodeType != XmlNodeType.Element || reader.LocalName != "key") - throw new OSDException("Expected "); - - string key = reader.ReadString(); - - if (reader.NodeType != XmlNodeType.EndElement || reader.LocalName != "key") - throw new OSDException("Expected "); - - if (reader.Read()) - map[key] = ParseLLSDXmlElement(reader); - else - throw new OSDException("Failed to parse a value for key " + key); - } - } - - return map; - } - - private static OSDArray ParseLLSDXmlArray(XmlTextReader reader) - { - if (reader.NodeType != XmlNodeType.Element || reader.LocalName != "array") - throw new OSDException("Expected "); - - OSDArray array = new OSDArray(); - - if (reader.IsEmptyElement) - { - reader.Read(); - return array; - } - - if (reader.Read()) - { - while (true) - { - SkipWhitespace(reader); - - if (reader.NodeType == XmlNodeType.EndElement && reader.LocalName == "array") - { - reader.Read(); - break; - } - - array.Add(ParseLLSDXmlElement(reader)); - } - } - - return array; - } - - private static void SkipWhitespace(XmlTextReader reader) - { - while ( - reader.NodeType == XmlNodeType.Comment || - reader.NodeType == XmlNodeType.Whitespace || - reader.NodeType == XmlNodeType.SignificantWhitespace || - reader.NodeType == XmlNodeType.XmlDeclaration) - { - reader.Read(); - } - } - - private static void CreateLLSDXmlSchema() - { - if (XmlSchema == null) - { - #region XSD - string schemaText = @" - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -"; - #endregion XSD - - XmlSchema = new XmlSchema(); - using (MemoryStream stream = new MemoryStream(Encoding.ASCII.GetBytes(schemaText))) - XmlSchema = XmlSchema.Read(stream, new ValidationEventHandler(LLSDXmlSchemaValidationHandler)); - } - } - - private static void LLSDXmlSchemaValidationHandler(object sender, ValidationEventArgs args) - { - string error = String.Format("Line: {0} - Position: {1} - {2}", XmlTextReader.LineNumber, XmlTextReader.LinePosition, - args.Message); - - if (LastXmlErrors == String.Empty) - LastXmlErrors = error; - else - LastXmlErrors += Environment.NewLine + error; - } - } -} \ No newline at end of file +/* + * Copyright (c) 2006-2016, openmetaverse.co + * Copyright (c) OpenSimulator Contributors, http://opensimulator.org/ + * All rights reserved. + * + * - Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * - Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * - Neither the name of the openmetaverse.co nor the names + * of its contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections.Generic; +using System.IO; +using System.Xml; +using System.Xml.Schema; +using System.Text; +using System.Runtime.InteropServices; +using OpenMetaverse; + +namespace OpenMetaverse.StructuredData +{ + /// + /// + /// + public static partial class OSDParser + { + /// + /// + /// + /// + /// + public static OSD DeserializeLLSDXml(byte[] xmlData) + { + using(MemoryStream ms = new MemoryStream(xmlData)) + using(XmlTextReader xrd = new XmlTextReader(ms)) + return DeserializeLLSDXml(xrd); + } + + public static OSD DeserializeLLSDXml(Stream xmlStream) + { + using(XmlTextReader xrd = new XmlTextReader(xmlStream)) + return DeserializeLLSDXml(xrd); + } + + /// + /// + /// + /// + /// + public static OSD DeserializeLLSDXml(string xmlData) + { + using (StringReader sr = new StringReader(xmlData)) + using(XmlTextReader xrd = new XmlTextReader(sr)) + return DeserializeLLSDXml(xrd); + } + + /// + /// + /// + /// + /// + public static OSD DeserializeLLSDXml(XmlTextReader xmlData) + { + xmlData.DtdProcessing = DtdProcessing.Ignore; + + try + { + xmlData.Read(); + SkipWhitespace(xmlData); + + xmlData.Read(); + OSD ret = ParseLLSDXmlElement(xmlData); + + return ret; + } + catch + { + return new OSD(); + } + } + + public static byte[] SerializeLLSDXmlToBytes(OSD data, bool formal = false) + { + osUTF8 tmp = OSUTF8Cached.Acquire(); + if (formal) + tmp.Append(osUTF8Const.XMLformalHeaderllsdstart); + else + tmp.Append(osUTF8Const.XMLllsdStart); + SerializeLLSDXmlElement(tmp, data, formal); + tmp.Append(osUTF8Const.XMLllsdEnd); + + return OSUTF8Cached.GetArrayAndRelease(tmp); + } + + public static byte[] SerializeLLSDXmlToBytes(OSD data) + { + osUTF8 tmp = OSUTF8Cached.Acquire(); + + tmp.Append(osUTF8Const.XMLllsdStart); + SerializeLLSDXmlElement(tmp, data, false); + tmp.Append(osUTF8Const.XMLllsdEnd); + + return OSUTF8Cached.GetArrayAndRelease(tmp); + } + + public static byte[] SerializeInnerLLSDXmlToBytes(OSD data) + { + osUTF8 tmp = OSUTF8Cached.Acquire(); + SerializeLLSDXmlElement(tmp, data, false); + + return OSUTF8Cached.GetArrayAndRelease(tmp); + } + + public static byte[] SerializeLLSDXmlBytes(OSD data, bool formal = false) + { + return SerializeLLSDXmlToBytes(data, formal); + } + + /// + /// + /// + /// + /// + public static string SerializeLLSDXmlString(OSD data, bool formal = false) + { + StringBuilder sb = osStringBuilderCache.Acquire(); + if(formal) + sb.Append(""); + + sb.Append(""); + SerializeLLSDXmlElement(sb, data, formal); + sb.Append(""); + + return osStringBuilderCache.GetStringAndRelease(sb); + } + + public static string SerializeLLSDInnerXmlString(OSD data, bool formal = false) + { + StringBuilder sb = osStringBuilderCache.Acquire(); + SerializeLLSDXmlElement(sb, data, formal); + + return osStringBuilderCache.GetStringAndRelease(sb); + } + + /// + /// + /// + /// + /// + public static void SerializeLLSDXmlElement(StringBuilder sb, OSD data, bool formal) + { + switch (data.Type) + { + case OSDType.Unknown: + sb.Append(""); + break; + case OSDType.Boolean: + if(data.AsBoolean()) + sb.Append("1"); + else + sb.Append("0"); + break; + case OSDType.Integer: + sb.Append(""); + sb.Append(data.AsString()); + sb.Append(""); + break; + case OSDType.Real: + sb.Append(""); + sb.Append(data.AsString()); + sb.Append(""); + break; + case OSDType.String: + sb.Append(""); + EscapeToXML(data.AsString(), sb); + sb.Append(""); + break; + case OSDType.UUID: + sb.Append(""); + sb.Append(data.AsString()); + sb.Append(""); + break; + case OSDType.Date: + sb.Append(""); + sb.Append(data.AsString()); + sb.Append(""); + break; + case OSDType.URI: + sb.Append(""); + sb.Append(data.AsString()); + sb.Append(""); + break; + case OSDType.Long: + case OSDType.Binary: + if(formal) + sb.Append(""); + else + sb.Append(""); + base64Encode(data.AsBinary(), sb); + sb.Append(""); + break; + case OSDType.Map: + OSDMap map = (OSDMap)data; + sb.Append(""); + foreach (KeyValuePair kvp in map) + { + sb.Append(""); + sb.Append(kvp.Key); + sb.Append(""); + + SerializeLLSDXmlElement(sb, kvp.Value, formal); + } + sb.Append(""); + break; + case OSDType.Array: + OSDArray array = (OSDArray)data; + sb.Append(""); + for (int i = 0; i < array.Count; i++) + { + SerializeLLSDXmlElement(sb, array[i], formal); + } + sb.Append(""); + break; + case OSDType.LLSDxml: + sb.Append(data.AsString()); + break; + default: + break; + } + } + + public static void EscapeToXML(string s, StringBuilder sb) + { + char c; + for (int i = 0; i < s.Length; ++i) + { + c = s[i]; + switch (c) + { + case '<': + sb.Append("<"); + break; + case '>': + sb.Append(">"); + break; + case '&': + sb.Append("&"); + break; + case '"': + sb.Append("""); + break; + case '\'': + sb.Append("'"); + break; + default: + sb.Append(c); + break; + } + } + } + + public static void EscapeASCIIToXML(osUTF8 ms, string s) + { + char c; + for (int i = 0; i < s.Length; i++) + { + c = s[i]; + switch (c) + { + case '<': + ms.Append(osUTF8Const.XMLamp_lt); + break; + case '>': + ms.Append(osUTF8Const.XMLamp_gt); + break; + case '&': + ms.Append(osUTF8Const.XMLamp); + break; + case '"': + ms.Append(osUTF8Const.XMLamp_quot); + break; + case '\'': + ms.Append(osUTF8Const.XMLamp_apos); + break; + default: + ms.AppendASCII(c); + break; + } + } + } + + public static void EscapeToXML(osUTF8 ms, string s) + { + char c; + for (int i = 0; i < s.Length; i++) + { + c = s[i]; + switch (c) + { + case '<': + ms.Append(osUTF8Const.XMLamp_lt); + break; + case '>': + ms.Append(osUTF8Const.XMLamp_gt); + break; + case '&': + ms.Append(osUTF8Const.XMLamp); + break; + case '"': + ms.Append(osUTF8Const.XMLamp_quot); + break; + case '\'': + ms.Append(osUTF8Const.XMLamp_apos); + break; + default: + ms.AppendCharBytes(c, ref s, ref i); + break; + } + } + } + + public static void EscapeToXML(osUTF8 ms, osUTF8 s) + { + byte c; + for (int i = 0; i < s.Length; i++) + { + c = s[i]; + switch (c) + { + case (byte)'<': + ms.Append(osUTF8Const.XMLamp_lt); + break; + case (byte)'>': + ms.Append(osUTF8Const.XMLamp_gt); + break; + case (byte)'&': + ms.Append(osUTF8Const.XMLamp); + break; + case (byte)'"': + ms.Append(osUTF8Const.XMLamp_quot); + break; + case (byte)'\'': + ms.Append(osUTF8Const.XMLamp_apos); + break; + default: + ms.Append(c); + break; + } + } + } + + public static void SerializeLLSDXmlElement(osUTF8 mb, OSD data, bool formal) + { + switch (data.Type) + { + case OSDType.Unknown: + mb.Append(""u8); + break; + case OSDType.Boolean: + if(data.AsBoolean()) + mb.Append(osUTF8Const.XMLfullbooleanOne); + else + mb.Append(osUTF8Const.XMLfullbooleanZero); + break; + case OSDType.Integer: + mb.Append(osUTF8Const.XMLintegerStart); + mb.AppendInt(data.AsInteger()); + mb.Append(osUTF8Const.XMLintegerEnd); + break; + case OSDType.Real: + mb.Append(osUTF8Const.XMLrealStart); + mb.AppendASCII(data.ToString()); + mb.Append(osUTF8Const.XMLrealEnd); + break; + case OSDType.String: + mb.Append(osUTF8Const.XMLstringStart); + EscapeToXML(mb, data); + mb.Append(osUTF8Const.XMLstringEnd); + break; + case OSDType.UUID: + mb.Append(osUTF8Const.XMLuuidStart); + mb.AppendUUID(data.AsUUID()); + mb.Append(osUTF8Const.XMLuuidEnd); + break; + case OSDType.Date: + mb.Append(osUTF8Const.XMLdateStart); + mb.AppendASCII(data.ToString()); + mb.Append(osUTF8Const.XMLdateEnd); + break; + case OSDType.URI: + mb.Append(osUTF8Const.XMLuriStart); + EscapeToXML(mb, data.ToString()); + mb.Append(osUTF8Const.XMLuriEnd); + break; + case OSDType.Long: + case OSDType.Binary: + if (formal) + mb.Append(osUTF8Const.XMLformalBinaryStart); + else + mb.Append(osUTF8Const.XMLbinaryStart); + base64Encode(data.AsBinary(), mb); + mb.Append(osUTF8Const.XMLbinaryEnd); + break; + case OSDType.Map: + mb.Append(osUTF8Const.XMLmapStart); + foreach (KeyValuePair kvp in (OSDMap)data) + { + mb.Append(osUTF8Const.XMLkeyStart); + mb.Append(kvp.Key.ToString()); + mb.Append(osUTF8Const.XMLkeyEnd); + + SerializeLLSDXmlElement(mb, kvp.Value, formal); + } + mb.Append(osUTF8Const.XMLmapEnd); + break; + case OSDType.Array: + OSDArray array = (OSDArray)data; + mb.Append(osUTF8Const.XMLarrayStart); + for (int i = 0; i < array.Count; i++) + { + SerializeLLSDXmlElement(mb, array[i], formal); + } + mb.Append(osUTF8Const.XMLarrayEnd); + break; + case OSDType.LLSDxml: + mb.Append(data.AsString()); + break; + default: + break; + } + } + + public static unsafe void base64Encode(byte[] data, osUTF8 mb) + { + int lenMod3 = data.Length % 3; + int len = data.Length - lenMod3; + + mb.CheckCapacity(((data.Length + 2) / 3) * 4); + + fixed (byte* d = data, b64 = osUTF8Const.base64Bytes) + { + int i = 0; + while (i < len) + { + mb.AppendSafe(b64[d[i] >> 2]); + mb.AppendSafe(b64[((d[i] & 0x03) << 4) | ((d[i + 1] & 0xf0) >> 4)]); + mb.AppendSafe(b64[((d[i + 1] & 0x0f) << 2) | ((d[i + 2] & 0xc0) >> 6)]); + mb.AppendSafe(b64[d[i + 2] & 0x3f]); + i += 3; + } + + switch (lenMod3) + { + case 2: + { + i = len; + mb.AppendSafe(b64[d[i] >> 2]); + mb.AppendSafe(b64[((d[i] & 0x03) << 4) | ((d[i + 1] & 0xf0) >> 4)]); + mb.AppendSafe(b64[((d[i + 1] & 0x0f) << 2)]); + mb.AppendSafe((byte)'='); + break; + } + case 1: + { + i = len; + mb.AppendSafe(b64[d[i] >> 2]); + mb.AppendSafe(b64[(d[i] & 0x03) << 4]); + mb.AppendSafe((byte)'='); + mb.AppendSafe((byte)'='); + break; + } + } + } + } + + public static unsafe void base64Encode(byte[] data, int start, int lenght, osUTF8 mb) + { + int lenMod3 = lenght % 3; + int len = lenght - lenMod3; + + mb.CheckCapacity(((lenght + 2) / 3) * 4); + fixed (byte* d = &data[start], b64 = osUTF8Const.base64Bytes) + { + int i = 0; + while (i < len) + { + mb.AppendSafe(b64[d[i] >> 2]); + mb.AppendSafe(b64[((d[i] & 0x03) << 4) | ((d[i + 1] & 0xf0) >> 4)]); + mb.AppendSafe(b64[((d[i + 1] & 0x0f) << 2) | ((d[i + 2] & 0xc0) >> 6)]); + mb.AppendSafe(b64[d[i + 2] & 0x3f]); + i += 3; + } + + switch (lenMod3) + { + case 2: + { + i = len; + mb.AppendSafe(b64[d[i] >> 2]); + mb.AppendSafe(b64[((d[i] & 0x03) << 4) | ((d[i + 1] & 0xf0) >> 4)]); + mb.AppendSafe(b64[((d[i + 1] & 0x0f) << 2)]); + mb.AppendSafe((byte)'='); + break; + } + case 1: + { + i = len; + mb.AppendSafe(b64[d[i] >> 2]); + mb.AppendSafe(b64[(d[i] & 0x03) << 4]); + mb.AppendSafe((byte)'='); + mb.AppendSafe((byte)'='); + break; + } + } + } + } + + static readonly char[] base64Chars = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O', + 'P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d', + 'e','f','g','h','i','j','k','l','m','n','o','p','q','r','s', + 't','u','v','w','x','y','z','0','1','2','3','4','5','6','7', + '8','9','+','/'}; + + public static unsafe void base64Encode(byte[] data, StringBuilder sb) + { + int lenMod3 = data.Length % 3; + int len = data.Length - lenMod3; + + sb.EnsureCapacity(((data.Length + 2) / 3) * 4); + fixed (byte* d = data) + { + fixed (char* b64 = base64Chars) + { + int i = 0; + while (i < len) + { + sb.Append(b64[d[i] >> 2]); + sb.Append(b64[((d[i] & 0x03) << 4) | ((d[i + 1] & 0xf0) >> 4)]); + sb.Append(b64[((d[i + 1] & 0x0f) << 2) | ((d[i + 2] & 0xc0) >> 6)]); + sb.Append(b64[d[i + 2] & 0x3f]); + i += 3; + } + + switch (lenMod3) + { + case 2: + { + i = len; + sb.Append(b64[d[i] >> 2]); + sb.Append(b64[((d[i] & 0x03) << 4) | ((d[i + 1] & 0xf0) >> 4)]); + sb.Append(b64[((d[i + 1] & 0x0f) << 2)]); + sb.Append('='); + break; + } + case 1: + { + i = len; + sb.Append(b64[d[i] >> 2]); + sb.Append(b64[(d[i] & 0x03) << 4]); + sb.Append("=="); + break; + } + } + } + } + } + + + /// + /// + /// + /// + /// + private static OSD ParseLLSDXmlElement(XmlTextReader reader) + { + SkipWhitespace(reader); + + if (reader.NodeType != XmlNodeType.Element) + throw new OSDException("Expected an element"); + + string type = reader.LocalName; + OSD ret; + + switch (type) + { + case "undef": + if (reader.IsEmptyElement) + { + reader.Read(); + return new OSD(); + } + + reader.Read(); + SkipWhitespace(reader); + ret = new OSD(); + break; + case "boolean": + if (reader.IsEmptyElement) + { + reader.Read(); + return OSD.FromBoolean(false); + } + + if (reader.Read()) + { + string s = reader.ReadString().Trim(); + + if (!String.IsNullOrEmpty(s) && (s == "true" || s == "1")) + { + ret = OSD.FromBoolean(true); + break; + } + } + + ret = OSD.FromBoolean(false); + break; + case "integer": + if (reader.IsEmptyElement) + { + reader.Read(); + return OSD.FromInteger(0); + } + + if (reader.Read()) + { + Int32.TryParse(reader.ReadString().Trim(), out int value); + ret = OSD.FromInteger(value); + break; + } + + ret = OSD.FromInteger(0); + break; + case "real": + if (reader.IsEmptyElement) + { + reader.Read(); + return OSD.FromReal(0d); + } + + if (reader.Read()) + { + double value; + string str = reader.ReadString().Trim().ToLower(); + + if (str == "nan") + value = Double.NaN; + else + Utils.TryParseDouble(str, out value); + + ret = OSD.FromReal(value); + break; + } + + ret = OSD.FromReal(0d); + break; + case "uuid": + if (reader.IsEmptyElement) + { + reader.Read(); + return OSD.FromUUID(UUID.Zero); + } + + if (reader.Read()) + { + UUID.TryParse(reader.ReadString().AsSpan(), out UUID value); + ret = OSD.FromUUID(value); + break; + } + + ret = OSD.FromUUID(UUID.Zero); + break; + case "date": + if (reader.IsEmptyElement) + { + reader.Read(); + return OSD.FromDate(Utils.Epoch); + } + + if (reader.Read()) + { + if(DateTime.TryParse(reader.ReadString().Trim(), out DateTime value)) + ret = OSD.FromDate(value); + else + ret = OSD.FromDate(Utils.Epoch); + break; + } + ret = OSD.FromDate(Utils.Epoch); + break; + case "string": + if (reader.IsEmptyElement) + { + reader.Read(); + return OSD.FromString(String.Empty); + } + + if (reader.Read()) + { + ret = OSD.FromString(reader.ReadString()); + break; + } + + ret = OSD.FromString(String.Empty); + break; + case "binary": + if (reader.IsEmptyElement) + { + reader.Read(); + return OSD.FromBinary(Array.Empty()); + } + + if (reader.GetAttribute("encoding") != null && reader.GetAttribute("encoding") != "base64") + throw new OSDException("Unsupported binary encoding: " + reader.GetAttribute("encoding")); + + if (reader.Read()) + { + try + { + ret = OSD.FromBinary(Convert.FromBase64String(reader.ReadString().Trim())); + break; + } + catch (FormatException ex) + { + throw new OSDException("Binary decoding exception: " + ex.Message); + } + } + + ret = OSD.FromBinary(Array.Empty()); + break; + case "uri": + if (reader.IsEmptyElement) + { + reader.Read(); + return OSD.FromUri(new Uri(String.Empty, UriKind.RelativeOrAbsolute)); + } + + if (reader.Read()) + { + ret = OSD.FromUri(new Uri(reader.ReadString(), UriKind.RelativeOrAbsolute)); + break; + } + + ret = OSD.FromUri(new Uri(String.Empty, UriKind.RelativeOrAbsolute)); + break; + case "map": + return ParseLLSDXmlMap(reader); + case "array": + return ParseLLSDXmlArray(reader); + default: + reader.Read(); + ret = null; + break; + } + + if (reader.NodeType != XmlNodeType.EndElement || reader.LocalName != type) + { + throw new OSDException("Expected "); + } + else + { + reader.Read(); + return ret; + } + } + + private static OSDMap ParseLLSDXmlMap(XmlTextReader reader) + { + if (reader.NodeType != XmlNodeType.Element || reader.LocalName != "map") + throw new NotImplementedException("Expected "); + + OSDMap map = new OSDMap(); + + if (reader.IsEmptyElement) + { + reader.Read(); + return map; + } + + if (reader.Read()) + { + while (true) + { + SkipWhitespace(reader); + + if (reader.NodeType == XmlNodeType.EndElement && reader.LocalName == "map") + { + reader.Read(); + break; + } + + if (reader.NodeType != XmlNodeType.Element || reader.LocalName != "key") + throw new OSDException("Expected "); + + string key = reader.ReadString(); + + if (reader.NodeType != XmlNodeType.EndElement || reader.LocalName != "key") + throw new OSDException("Expected "); + + if (reader.Read()) + map[key] = ParseLLSDXmlElement(reader); + else + throw new OSDException("Failed to parse a value for key " + key); + } + } + + return map; + } + + private static OSDArray ParseLLSDXmlArray(XmlTextReader reader) + { + if (reader.NodeType != XmlNodeType.Element || reader.LocalName != "array") + throw new OSDException("Expected "); + + OSDArray array = new OSDArray(); + + if (reader.IsEmptyElement) + { + reader.Read(); + return array; + } + + if (reader.Read()) + { + while (true) + { + SkipWhitespace(reader); + + if (reader.NodeType == XmlNodeType.EndElement && reader.LocalName == "array") + { + reader.Read(); + break; + } + + array.Add(ParseLLSDXmlElement(reader)); + } + } + + return array; + } + + private static void SkipWhitespace(XmlTextReader reader) + { + while ( + reader.NodeType == XmlNodeType.Comment || + reader.NodeType == XmlNodeType.Whitespace || + reader.NodeType == XmlNodeType.SignificantWhitespace || + reader.NodeType == XmlNodeType.XmlDeclaration) + { + reader.Read(); + } + } + } +} + diff --git a/OpenMetaverse.StructuredData/OpenMetaverse.StructuredData.csproj b/OpenMetaverse.StructuredData/OpenMetaverse.StructuredData.csproj index b2e908fa..bd7d2492 100644 --- a/OpenMetaverse.StructuredData/OpenMetaverse.StructuredData.csproj +++ b/OpenMetaverse.StructuredData/OpenMetaverse.StructuredData.csproj @@ -1,14 +1,12 @@  Local - net48 - 1591,1574,0419,0618 + Library + OpenMetaverse.StructuredData + LLSD/OSD structured data serialization (XML, JSON, binary) for the OpenMetaverse library. true true - - - diff --git a/OpenMetaverse.StructuredData/StructuredData.cs b/OpenMetaverse.StructuredData/StructuredData.cs index 87d7e67d..69d166bf 100644 --- a/OpenMetaverse.StructuredData/StructuredData.cs +++ b/OpenMetaverse.StructuredData/StructuredData.cs @@ -1,2117 +1,2455 @@ -/* - * Copyright (c) 2006-2016, openmetaverse.co - * All rights reserved. - * - * - Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, this - * list of conditions and the following disclaimer. - * - Neither the name of the openmetaverse.co nor the names - * of its contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections; -using System.Collections.Generic; -using System.IO; -using System.Reflection; -using System.Text; - -namespace OpenMetaverse.StructuredData -{ - /// - /// - /// - public enum OSDType:byte - { - /// - Unknown, - /// - Boolean, - /// - Integer, - /// - Real, - /// - String, - /// - UUID, - /// - Date, - /// - URI, - /// - Binary, - /// - Map, - /// - Array, - LLSDxml, - OSDUTF8 - } - - public enum OSDFormat - { - Xml = 0, - Json, - Binary - } - - /// - /// - /// - public class OSDException : Exception - { - public OSDException(string message) : base(message) { } - } - - /// - /// - /// - public partial class OSD - { - protected static readonly byte[] trueBinary = { 0x31 }; - protected static readonly byte[] falseBinary = { 0x30 }; - - public OSDType Type = OSDType.Unknown; - - // .net4.8 64Bit JIT fails polimorphism - public virtual bool AsBoolean() - { - switch (Type) - { - case OSDType.Boolean: - return ((OSDBoolean)this).value; - case OSDType.Integer: - return ((OSDInteger)this).value != 0; - case OSDType.Real: - double d = ((OSDReal)this).value; - return (!Double.IsNaN(d) && d != 0); - case OSDType.String: - string s = ((OSDString)this).value; - if (String.IsNullOrEmpty(s)) - return false; - if (s == "0" || s.ToLower() == "false") - return false; - return true; - case OSDType.UUID: - return (((OSDUUID)this).value == UUID.Zero) ? false : true; - case OSDType.Map: - return ((OSDMap)this).dicvalue.Count > 0; - case OSDType.Array: - return ((OSDArray)this).value.Count > 0; - case OSDType.OSDUTF8: - osUTF8 u = ((OSDUTF8)this).value; - if (osUTF8.IsNullOrEmpty(u)) - return false; - if (u.Equals('0') || u.ACSIILowerEquals("false")) - return false; - return true; - - default: - return false; - } - } - - public virtual int AsInteger() - { - switch (Type) - { - case OSDType.Boolean: - return ((OSDBoolean)this).value ? 1 : 0; - case OSDType.Integer: - return ((OSDInteger)this).value; - case OSDType.Real: - double v = ((OSDReal)this).value; - if (Double.IsNaN(v)) - return 0; - if (v > Int32.MaxValue) - return Int32.MaxValue; - if (v < Int32.MinValue) - return Int32.MinValue; - return (int)Math.Round(v); - case OSDType.String: - string s = ((OSDString)this).value; - double dbl; - if (Double.TryParse(s, out dbl)) - return (int)Math.Floor(dbl); - else - return 0; - case OSDType.OSDUTF8: - string us = ((OSDUTF8)this).value.ToString(); - double udbl; - if (Double.TryParse(us, out udbl)) - return (int)Math.Floor(udbl); - else - return 0; - case OSDType.Binary: - byte[] b = ((OSDBinary)this).value; - if (b.Length < 4) - return 0; - return (b[0] << 24) | (b[1] << 16) | (b[2] << 8) | b[3]; - case OSDType.Array: - List l = ((OSDArray)this).value; - if (l.Count < 4) - return 0; - byte[] by = new byte[4]; - for (int i = 0; i < 4; i++) - by[i] = (byte)l[i].AsInteger(); - return (by[0] << 24) | (by[1] << 16) | (by[2] << 8) | by[3]; - case OSDType.Date: - return (int)Utils.DateTimeToUnixTime(((OSDDate)this).value); - default: - return 0; - } - } - - public virtual uint AsUInteger() - { - switch (Type) - { - case OSDType.Boolean: - return ((OSDBoolean)this).value ? 1U : 0; - case OSDType.Integer: - return (uint)((OSDInteger)this).value; - case OSDType.Real: - double v = ((OSDReal)this).value; - if (Double.IsNaN(v)) - return 0; - if (v > UInt32.MaxValue) - return UInt32.MaxValue; - if (v < UInt32.MinValue) - return UInt32.MinValue; - return (uint)Math.Round(v); - case OSDType.String: - string s = ((OSDString)this).value; - double dbl; - if (Double.TryParse(s, out dbl)) - return (uint)Math.Floor(dbl); - else - return 0; - case OSDType.OSDUTF8: - string us = ((OSDUTF8)this).value.ToString(); - double udbl; - if (Double.TryParse(us, out udbl)) - return (uint)Math.Floor(udbl); - else - return 0; - case OSDType.Date: - return Utils.DateTimeToUnixTime(((OSDDate)this).value); - case OSDType.Binary: - byte[] b = ((OSDBinary)this).value; - if(b.Length < 4) - return 0; - return (uint)( - (b[0] << 24) | (b[1] << 16) | (b[2] << 8) | b[3]); - case OSDType.Array: - List l = ((OSDArray)this).value; - if (l.Count < 4) - return 0; - byte[] by = new byte[4]; - for (int i = 0; i < 4; i++) - by[i] = (byte)l[i].AsInteger(); - return (uint)((by[0] << 24) | (by[1] << 16) | (by[2] << 8) | by[3]); - default: - return 0; - } - } - - public virtual long AsLong() - { - switch (Type) - { - case OSDType.Boolean: - return ((OSDBoolean)this).value ? 1 : 0; - case OSDType.Integer: - return ((OSDInteger)this).value; - case OSDType.Real: - double v = ((OSDReal)this).value; - if (Double.IsNaN(v)) - return 0; - if (v > Int64.MaxValue) - return Int64.MaxValue; - if (v < Int64.MinValue) - return Int64.MinValue; - return (long)Math.Round(v); - case OSDType.String: - string s = ((OSDString)this).value; - double dbl; - if (Double.TryParse(s, out dbl)) - return (long)Math.Floor(dbl); - else - return 0; - case OSDType.OSDUTF8: - string us = ((OSDUTF8)this).value.ToString(); - double udbl; - if (Double.TryParse(us, out udbl)) - return (long)Math.Floor(udbl); - else - return 0; - case OSDType.Date: - return Utils.DateTimeToUnixTime(((OSDDate)this).value); - case OSDType.Binary: - { - byte[] b = ((OSDBinary)this).value; - if(b.Length < 8) - return 0; - return ( - ((long)b[0] << 56) | - ((long)b[1] << 48) | - ((long)b[2] << 40) | - ((long)b[3] << 32) | - ((long)b[4] << 24) | - ((long)b[5] << 16) | - ((long)b[6] << 8) | - b[7]); - } - case OSDType.Array: - { - List l = ((OSDArray)this).value; - if (l.Count < 8) - return 0; - byte[] b = new byte[8]; - for (int i = 0; i < 8; i++) - b[i] = (byte)l[i].AsInteger(); - return ( - ((long)b[0] << 56) | - ((long)b[1] << 48) | - ((long)b[2] << 40) | - ((long)b[3] << 32) | - ((long)b[4] << 24) | - ((long)b[5] << 16) | - ((long)b[6] << 8) | - b[7]); - } - default: - return 0; - } - } - - public virtual ulong AsULong() - { - switch (Type) - { - case OSDType.Boolean: - return ((OSDBoolean)this).value ? 1UL : 0; - case OSDType.Integer: - return (ulong)((OSDInteger)this).value; - case OSDType.Real: - double v = ((OSDReal)this).value; - if (Double.IsNaN(v)) - return 0; - if (v > UInt64.MaxValue) - return UInt64.MaxValue; - if (v < UInt64.MinValue) - return UInt64.MinValue; - return (ulong)Math.Round(v); - case OSDType.String: - string s = ((OSDString)this).value; - double dbl; - if (Double.TryParse(s, out dbl)) - return (ulong)Math.Floor(dbl); - else - return 0; - case OSDType.OSDUTF8: - string us = ((OSDUTF8)this).value.ToString(); - double udbl; - if (Double.TryParse(us, out udbl)) - return (ulong)Math.Floor(udbl); - else - return 0; - case OSDType.Date: - return Utils.DateTimeToUnixTime(((OSDDate)this).value); - case OSDType.Binary: - { - byte[] b = ((OSDBinary)this).value; - if (b.Length < 8) - return 0; - return ( - ((ulong)b[0] << 56) | - ((ulong)b[1] << 48) | - ((ulong)b[2] << 40) | - ((ulong)b[3] << 32) | - ((ulong)b[4] << 24) | - ((ulong)b[5] << 16) | - ((ulong)b[6] << 8) | - b[7]); - } - case OSDType.Array: - { - List l = ((OSDArray)this).value; - if (l.Count < 8) - return 0; - byte[] b = new byte[8]; - for (int i = 0; i < 8; i++) - b[i] = (byte)l[i].AsInteger(); - return ( - ((ulong)b[0] << 56) | - ((ulong)b[1] << 48) | - ((ulong)b[2] << 40) | - ((ulong)b[3] << 32) | - ((ulong)b[4] << 24) | - ((ulong)b[5] << 16) | - ((ulong)b[6] << 8) | - b[7]); - } - default: - return 0; - } - } - - public virtual double AsReal() - { - switch (Type) - { - case OSDType.Boolean: - return ((OSDBoolean)this).value ? 1.0 : 0; - case OSDType.Integer: - return ((OSDInteger)this).value; - case OSDType.Real: - return ((OSDReal)this).value; - case OSDType.String: - string s = ((OSDString)this).value; - double dbl; - if (Double.TryParse(s, out dbl)) - return dbl; - else - return 0; - case OSDType.OSDUTF8: - string us = ((OSDUTF8)this).value.ToString(); - double udbl; - if (Double.TryParse(us, out udbl)) - return udbl; - else - return 0; - default: - return 0; - } - } - - public virtual string AsString() - { - switch (Type) - { - case OSDType.Boolean: - return ((OSDBoolean)this).value ? "1" : "0"; - case OSDType.Integer: - return ((OSDInteger)this).value.ToString(); - case OSDType.Real: - return ((OSDReal)this).value.ToString("r", Utils.EnUsCulture); - case OSDType.String: - return ((OSDString)this).value; - case OSDType.OSDUTF8: - return ((OSDUTF8)this).value.ToString(); - case OSDType.UUID: - return ((OSDUUID)this).value.ToString(); - case OSDType.Date: - string format; - DateTime dt = ((OSDDate)this).value; - if (dt.Millisecond > 0) - format = "yyyy-MM-ddTHH:mm:ss.ffZ"; - else - format = "yyyy-MM-ddTHH:mm:ssZ"; - return dt.ToUniversalTime().ToString(format); - case OSDType.URI: - Uri ur = ((OSDUri)this).value; - if (ur == null) - return string.Empty; - if (ur.IsAbsoluteUri) - return ur.AbsoluteUri; - else - return ur.ToString(); - - case OSDType.Binary: - byte[] b = ((OSDBinary)this).value; - return Convert.ToBase64String(b); - case OSDType.LLSDxml: - return ((OSDllsdxml)this).value; - default: - return String.Empty; - } - } - - public virtual UUID AsUUID() - { - switch (Type) - { - case OSDType.String: - UUID uuid; - if (UUID.TryParse(((OSDString)this).value, out uuid)) - return uuid; - else - return UUID.Zero; - case OSDType.OSDUTF8: - UUID ouuid; - if (UUID.TryParse(((OSDUTF8)this).value.ToString(), out ouuid)) - return ouuid; - else - return UUID.Zero; - case OSDType.UUID: - return ((OSDUUID)this).value; - default: - return UUID.Zero; - } - } - - public virtual DateTime AsDate() - { - switch (Type) - { - case OSDType.String: - DateTime dt; - if (DateTime.TryParse(((OSDString)this).value, out dt)) - return dt; - else - return Utils.Epoch; - case OSDType.OSDUTF8: - DateTime odt; - if (DateTime.TryParse(((OSDUTF8)this).value.ToString(), out odt)) - return odt; - else - return Utils.Epoch; - case OSDType.UUID: - case OSDType.Date: - return ((OSDDate)this).value; - default: - return Utils.Epoch; - } - } - public virtual Uri AsUri() - { - switch (Type) - { - case OSDType.String: - Uri uri; - if (Uri.TryCreate(((OSDString)this).value, UriKind.RelativeOrAbsolute, out uri)) - return uri; - else - return null; - case OSDType.OSDUTF8: - Uri ouri; - if (Uri.TryCreate(((OSDUTF8)this).value.ToString(), UriKind.RelativeOrAbsolute, out ouri)) - return ouri; - else - return null; - case OSDType.URI: - return ((OSDUri)this).value; - default: - return null; - } - } - - public virtual byte[] AsBinary() - { - switch (Type) - { - case OSDType.Boolean: - return ((OSDBoolean)this).value ? trueBinary : falseBinary; - case OSDType.Integer: - return Utils.IntToBytesBig(((OSDInteger)this).value); - case OSDType.Real: - return Utils.DoubleToBytesBig(((OSDReal)this).value); - case OSDType.String: - return Encoding.UTF8.GetBytes(((OSDString)this).value); - case OSDType.OSDUTF8: - return ((OSDUTF8)this).value.ToArray(); - case OSDType.UUID: - return (((OSDUUID)this).value).GetBytes(); - case OSDType.Date: - TimeSpan ts = (((OSDDate)this).value).ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); - return Utils.DoubleToBytes(ts.TotalSeconds); - case OSDType.URI: - return Encoding.UTF8.GetBytes(((OSDUri)this).AsString()); - case OSDType.Binary: - return ((OSDBinary)this).value; - case OSDType.Map: - case OSDType.Array: - List l = ((OSDArray)this).value; - byte[] binary = new byte[l.Count]; - for (int i = 0; i < l.Count; i++) - binary[i] = (byte)l[i].AsInteger(); - return binary; - case OSDType.LLSDxml: - return Encoding.UTF8.GetBytes(((OSDllsdxml)this).value); - default: - return Utils.EmptyBytes; - } - } - - public Vector2 AsVector2() - { - switch (Type) - { - case OSDType.String: - return Vector2.Parse(((OSDString)this).value); - case OSDType.OSDUTF8: - return Vector2.Parse(((OSDUTF8)this).value.ToString()); - case OSDType.Array: - List l = ((OSDArray)this).value; - Vector2 vector = Vector2.Zero; - if (l.Count == 2) - { - vector.X = (float)l[0].AsReal(); - vector.Y = (float)l[1].AsReal(); - } - return vector; - default: - return Vector2.Zero; - } - } - - public Vector3 AsVector3() - { - switch (Type) - { - case OSDType.String: - return Vector3.Parse(((OSDString)this).value); - case OSDType.OSDUTF8: - return Vector3.Parse(((OSDUTF8)this).value.ToString()); - case OSDType.Array: - List l = ((OSDArray)this).value; - Vector3 vector = Vector3.Zero; - if (l.Count == 3) - { - vector.X = (float)l[0].AsReal(); - vector.Y = (float)l[1].AsReal(); - vector.Z = (float)l[2].AsReal(); - } - return vector; - default: - return Vector3.Zero; - } - } - - public Vector3d AsVector3d() - { - switch (Type) - { - case OSDType.String: - return Vector3d.Parse(((OSDString)this).value); - case OSDType.OSDUTF8: - return Vector3d.Parse(((OSDUTF8)this).value.ToString()); - case OSDType.Array: - List l = ((OSDArray)this).value; - Vector3d vector = Vector3d.Zero; - if (l.Count == 3) - { - vector.X = (float)l[0].AsReal(); - vector.Y = (float)l[1].AsReal(); - vector.Z = (float)l[2].AsReal(); - } - return vector; - default: - return Vector3d.Zero; - } - } - - public Vector4 AsVector4() - { - switch (Type) - { - case OSDType.String: - return Vector4.Parse(((OSDString)this).value); - case OSDType.OSDUTF8: - return Vector4.Parse(((OSDUTF8)this).value.ToString()); - case OSDType.Array: - List l = ((OSDArray)this).value; - Vector4 vector = Vector4.Zero; - if (l.Count == 4) - { - vector.X = (float)l[0].AsReal(); - vector.Y = (float)l[1].AsReal(); - vector.Z = (float)l[2].AsReal(); - vector.W = (float)l[3].AsReal(); - } - return vector; - default: - return Vector4.Zero; - } - } - - public Quaternion AsQuaternion() - { - switch (Type) - { - case OSDType.String: - return Quaternion.Parse(((OSDString)this).value); - case OSDType.OSDUTF8: - return Quaternion.Parse(((OSDString)this).value.ToString()); - case OSDType.Array: - List l = ((OSDArray)this).value; - Quaternion q = Quaternion.Identity; - if (l.Count == 4) - { - q.X = (float)l[0].AsReal(); - q.Y = (float)l[1].AsReal(); - q.Z = (float)l[2].AsReal(); - q.W = (float)l[3].AsReal(); - } - return q; - default: - return Quaternion.Identity; - } - } - - public virtual Color4 AsColor4() - { - switch (Type) - { - case OSDType.Array: - List l = ((OSDArray)this).value; - Color4 color = Color4.Black; - if (l.Count == 4) - { - color.R = (float)l[0].AsReal(); - color.G = (float)l[1].AsReal(); - color.B = (float)l[2].AsReal(); - color.A = (float)l[3].AsReal(); - } - return color; - default: - return Color4.Black; - } - } - - public virtual void Clear() { } - - public virtual OSD Copy() - { - switch (Type) - { - case OSDType.Boolean: - return new OSDBoolean(((OSDBoolean)this).value); - case OSDType.Integer: - return new OSDInteger(((OSDInteger)this).value); - case OSDType.Real: - return new OSDReal(((OSDReal)this).value); - case OSDType.String: - return new OSDString(((OSDString)this).value); - case OSDType.OSDUTF8: - return new OSDUTF8(((OSDUTF8)this).value); - case OSDType.UUID: - return new OSDUUID(((OSDUUID)this).value); - case OSDType.Date: - return new OSDDate(((OSDDate)this).value); - case OSDType.URI: - return new OSDUri(((OSDUri)this).value); - case OSDType.Binary: - return new OSDBinary(((OSDBinary)this).value); - case OSDType.Map: - return new OSDMap(((OSDMap)this).dicvalue); - case OSDType.Array: - return new OSDArray(((OSDArray)this).value); - case OSDType.LLSDxml: - return new OSDBoolean(((OSDBoolean)this).value); - default: - return new OSD(); - } - } - - public override string ToString() - { - switch (Type) - { - case OSDType.Boolean: - return ((OSDBoolean)this).value ? "1" : "0"; - case OSDType.Integer: - return ((OSDInteger)this).value.ToString(); - case OSDType.Real: - return ((OSDReal)this).value.ToString("r", Utils.EnUsCulture); - case OSDType.String: - return ((OSDString)this).value; - case OSDType.OSDUTF8: - return ((OSDUTF8)this).value.ToString(); - case OSDType.UUID: - return ((OSDUUID)this).value.ToString(); - case OSDType.Date: - string format; - DateTime dt = ((OSDDate)this).value; - if (dt.Millisecond > 0) - format = "yyyy-MM-ddTHH:mm:ss.ffZ"; - else - format = "yyyy-MM-ddTHH:mm:ssZ"; - return dt.ToUniversalTime().ToString(format); - case OSDType.URI: - Uri ur = ((OSDUri)this).value; - if (ur == null) - return string.Empty; - if (ur.IsAbsoluteUri) - return ur.AbsoluteUri; - else - return ur.ToString(); - case OSDType.Binary: - return Utils.BytesToHexString(((OSDBinary)this).value, null); - case OSDType.LLSDxml: - return ((OSDllsdxml)this).value; - case OSDType.Map: - return OSDParser.SerializeJsonString((OSDMap)this, true); - case OSDType.Array: - return OSDParser.SerializeJsonString((OSDArray)this, true); - default: - return "undef"; - } - } - - public static OSD FromBoolean(bool value) { return new OSDBoolean(value); } - public static OSD FromInteger(int value) { return new OSDInteger(value); } - public static OSD FromInteger(uint value) { return new OSDInteger((int)value); } - public static OSD FromInteger(short value) { return new OSDInteger((int)value); } - public static OSD FromInteger(ushort value) { return new OSDInteger((int)value); } - public static OSD FromInteger(sbyte value) { return new OSDInteger((int)value); } - public static OSD FromInteger(byte value) { return new OSDInteger((int)value); } - public static OSD FromUInteger(uint value) { return new OSDBinary(value); } - public static OSD FromLong(long value) { return new OSDBinary(value); } - public static OSD FromULong(ulong value) { return new OSDBinary(value); } - public static OSD FromReal(double value) { return new OSDReal(value); } - public static OSD FromReal(float value) { return new OSDReal((double)value); } - public static OSD FromString(string value) { return new OSDString(value); } - public static OSD FromUUID(UUID value) { return new OSDUUID(value); } - public static OSD FromDate(DateTime value) { return new OSDDate(value); } - public static OSD FromUri(Uri value) { return new OSDUri(value); } - public static OSD FromBinary(byte[] value) { return new OSDBinary(value); } - - public static OSD FromVector2(Vector2 value) - { - OSDArray array = new OSDArray(); - array.Add(OSD.FromReal(value.X)); - array.Add(OSD.FromReal(value.Y)); - return array; - } - - public static OSD FromVector3(Vector3 value) - { - OSDArray array = new OSDArray(); - array.Add(OSD.FromReal(value.X)); - array.Add(OSD.FromReal(value.Y)); - array.Add(OSD.FromReal(value.Z)); - return array; - } - - public static OSD FromVector3d(Vector3d value) - { - OSDArray array = new OSDArray(); - array.Add(OSD.FromReal(value.X)); - array.Add(OSD.FromReal(value.Y)); - array.Add(OSD.FromReal(value.Z)); - return array; - } - - public static OSD FromVector4(Vector4 value) - { - OSDArray array = new OSDArray(); - array.Add(OSD.FromReal(value.X)); - array.Add(OSD.FromReal(value.Y)); - array.Add(OSD.FromReal(value.Z)); - array.Add(OSD.FromReal(value.W)); - return array; - } - - public static OSD FromQuaternion(Quaternion value) - { - OSDArray array = new OSDArray(); - array.Add(OSD.FromReal(value.X)); - array.Add(OSD.FromReal(value.Y)); - array.Add(OSD.FromReal(value.Z)); - array.Add(OSD.FromReal(value.W)); - return array; - } - - public static OSD FromColor4(Color4 value) - { - OSDArray array = new OSDArray(); - array.Add(OSD.FromReal(value.R)); - array.Add(OSD.FromReal(value.G)); - array.Add(OSD.FromReal(value.B)); - array.Add(OSD.FromReal(value.A)); - return array; - } - - public static OSD FromObject(object value) - { - if (value == null) { return new OSD(); } - else if (value is bool) { return new OSDBoolean((bool)value); } - else if (value is int) { return new OSDInteger((int)value); } - else if (value is uint) { return new OSDBinary((uint)value); } - else if (value is short) { return new OSDInteger((int)(short)value); } - else if (value is ushort) { return new OSDInteger((int)(ushort)value); } - else if (value is sbyte) { return new OSDInteger((int)(sbyte)value); } - else if (value is byte) { return new OSDInteger((int)(byte)value); } - else if (value is double) { return new OSDReal((double)value); } - else if (value is float) { return new OSDReal((double)(float)value); } - else if (value is string) { return new OSDString((string)value); } - else if (value is UUID) { return new OSDUUID((UUID)value); } - else if (value is DateTime) { return new OSDDate((DateTime)value); } - else if (value is Uri) { return new OSDUri((Uri)value); } - else if (value is byte[]) { return new OSDBinary((byte[])value); } - else if (value is long) { return new OSDBinary((long)value); } - else if (value is ulong) { return new OSDBinary((ulong)value); } - else if (value is Vector2) { return FromVector2((Vector2)value); } - else if (value is Vector3) { return FromVector3((Vector3)value); } - else if (value is Vector3d) { return FromVector3d((Vector3d)value); } - else if (value is Vector4) { return FromVector4((Vector4)value); } - else if (value is Quaternion) { return FromQuaternion((Quaternion)value); } - else if (value is Color4) { return FromColor4((Color4)value); } - else return new OSD(); - } - - public static object ToObject(Type type, OSD value) - { - if (type == typeof(ulong)) - { - if (value.Type == OSDType.Binary) - { - byte[] bytes = value.AsBinary(); - return Utils.BytesToUInt64(bytes); - } - else - { - return (ulong)value.AsInteger(); - } - } - else if (type == typeof(uint)) - { - if (value.Type == OSDType.Binary) - { - byte[] bytes = value.AsBinary(); - return Utils.BytesToUInt(bytes); - } - else - { - return (uint)value.AsInteger(); - } - } - else if (type == typeof(ushort)) - { - return (ushort)value.AsInteger(); - } - else if (type == typeof(byte)) - { - return (byte)value.AsInteger(); - } - else if (type == typeof(short)) - { - return (short)value.AsInteger(); - } - else if (type == typeof(string)) - { - return value.AsString(); - } - else if (type == typeof(bool)) - { - return value.AsBoolean(); - } - else if (type == typeof(float)) - { - return (float)value.AsReal(); - } - else if (type == typeof(double)) - { - return value.AsReal(); - } - else if (type == typeof(int)) - { - return value.AsInteger(); - } - else if (type == typeof(UUID)) - { - return value.AsUUID(); - } - else if (type == typeof(Vector3)) - { - if (value.Type == OSDType.Array) - return ((OSDArray)value).AsVector3(); - else - return Vector3.Zero; - } - else if (type == typeof(Vector4)) - { - if (value.Type == OSDType.Array) - return ((OSDArray)value).AsVector4(); - else - return Vector4.Zero; - } - else if (type == typeof(Quaternion)) - { - if (value.Type == OSDType.Array) - return ((OSDArray)value).AsQuaternion(); - else - return Quaternion.Identity; - } - else if (type == typeof(OSDArray)) - { - OSDArray newArray = new OSDArray(); - foreach (OSD o in (OSDArray)value) - newArray.Add(o); - return newArray; - } - else if (type == typeof(OSDMap)) - { - OSDMap newMap = new OSDMap(); - foreach (KeyValuePair o in (OSDMap)value) - newMap.Add(o); - return newMap; - } - else - { - return null; - } - } - - #region Implicit Conversions - - public static implicit operator OSD(bool value) { return new OSDBoolean(value); } - public static implicit operator OSD(int value) { return new OSDInteger(value); } - public static implicit operator OSD(uint value) { return new OSDInteger((int)value); } - public static implicit operator OSD(short value) { return new OSDInteger((int)value); } - public static implicit operator OSD(ushort value) { return new OSDInteger((int)value); } - public static implicit operator OSD(sbyte value) { return new OSDInteger((int)value); } - public static implicit operator OSD(byte value) { return new OSDInteger((int)value); } - public static implicit operator OSD(long value) { return new OSDBinary(value); } - public static implicit operator OSD(ulong value) { return new OSDBinary(value); } - public static implicit operator OSD(double value) { return new OSDReal(value); } - public static implicit operator OSD(float value) { return new OSDReal(value); } - public static implicit operator OSD(string value) { return new OSDString(value); } - public static implicit operator OSD(UUID value) { return new OSDUUID(value); } - public static implicit operator OSD(DateTime value) { return new OSDDate(value); } - public static implicit operator OSD(Uri value) { return new OSDUri(value); } - public static implicit operator OSD(byte[] value) { return new OSDBinary(value); } - public static implicit operator OSD(Vector2 value) { return OSD.FromVector2(value); } - public static implicit operator OSD(Vector3 value) { return OSD.FromVector3(value); } - public static implicit operator OSD(Vector3d value) { return OSD.FromVector3d(value); } - public static implicit operator OSD(Vector4 value) { return OSD.FromVector4(value); } - public static implicit operator OSD(Quaternion value) { return OSD.FromQuaternion(value); } - public static implicit operator OSD(Color4 value) { return OSD.FromColor4(value); } - - public static implicit operator bool(OSD value) { return value.AsBoolean(); } - public static implicit operator int(OSD value) { return value.AsInteger(); } - public static implicit operator uint(OSD value) { return value.AsUInteger(); } - public static implicit operator long(OSD value) { return value.AsLong(); } - public static implicit operator ulong(OSD value) { return value.AsULong(); } - public static implicit operator double(OSD value) { return value.AsReal(); } - public static implicit operator float(OSD value) { return (float)value.AsReal(); } - public static implicit operator string(OSD value) { return value.AsString(); } - public static implicit operator UUID(OSD value) { return value.AsUUID(); } - public static implicit operator DateTime(OSD value) { return value.AsDate(); } - public static implicit operator Uri(OSD value) { return value.AsUri(); } - public static implicit operator byte[](OSD value) { return value.AsBinary(); } - public static implicit operator Vector2(OSD value) { return value.AsVector2(); } - public static implicit operator Vector3(OSD value) { return value.AsVector3(); } - public static implicit operator Vector3d(OSD value) { return value.AsVector3d(); } - public static implicit operator Vector4(OSD value) { return value.AsVector4(); } - public static implicit operator Quaternion(OSD value) { return value.AsQuaternion(); } - public static implicit operator Color4(OSD value) { return value.AsColor4(); } - - #endregion Implicit Conversions - - /// - /// Uses reflection to create an SDMap from all of the SD - /// serializable types in an object - /// - /// Class or struct containing serializable types - /// An SDMap holding the serialized values from the - /// container object - public static OSDMap SerializeMembers(object obj) - { - Type t = obj.GetType(); - FieldInfo[] fields = t.GetFields(); - - OSDMap map = new OSDMap(fields.Length); - - for (int i = 0; i < fields.Length; i++) - { - FieldInfo field = fields[i]; - if (!Attribute.IsDefined(field, typeof(NonSerializedAttribute))) - { - OSD serializedField = OSD.FromObject(field.GetValue(obj)); - - if (serializedField.Type != OSDType.Unknown || field.FieldType == typeof(string) || field.FieldType == typeof(byte[])) - map.Add(field.Name, serializedField); - } - } - - return map; - } - - /// - /// Uses reflection to deserialize member variables in an object from - /// an SDMap - /// - /// Reference to an object to fill with deserialized - /// values - /// Serialized values to put in the target - /// object - public static void DeserializeMembers(ref object obj, OSDMap serialized) - { - Type t = obj.GetType(); - FieldInfo[] fields = t.GetFields(); - - for (int i = 0; i < fields.Length; i++) - { - FieldInfo field = fields[i]; - if (!Attribute.IsDefined(field, typeof(NonSerializedAttribute))) - { - OSD serializedField; - if (serialized.TryGetValue(field.Name, out serializedField)) - field.SetValue(obj, ToObject(field.FieldType, serializedField)); - } - } - } - } - - /// - /// - /// - public sealed class OSDBoolean : OSD - { - public readonly bool value; - - public OSDBoolean(bool value) - { - Type = OSDType.Boolean; - this.value = value; - } - - public override bool AsBoolean() { return value; } - public override int AsInteger() { return value ? 1 : 0; } - public override double AsReal() { return value ? 1d : 0d; } - public override string AsString() { return value ? "1" : "0"; } - public override byte[] AsBinary() { return value ? trueBinary : falseBinary; } - public override OSD Copy() { return new OSDBoolean(value); } - public override string ToString() { return AsString(); } - } - - /// - /// - /// - public sealed class OSDInteger : OSD - { - public readonly int value; - - public OSDInteger(int value) - { - Type = OSDType.Integer; - this.value = value; - } - - public override bool AsBoolean() { return value != 0; } - public override int AsInteger() { return value; } - public override uint AsUInteger() { return (uint)value; } - public override long AsLong() { return value; } - public override ulong AsULong() { return (ulong)value; } - public override double AsReal() { return (double)value; } - public override string AsString() { return value.ToString(); } - public override byte[] AsBinary() { return Utils.IntToBytesBig(value); } - public override OSD Copy() { return new OSDInteger(value); } - public override string ToString() { return AsString(); } - } - - /// - /// - /// - public sealed class OSDReal : OSD - { - public readonly double value; - - public OSDReal(double value) - { - Type = OSDType.Real; - this.value = value; - } - - public override bool AsBoolean() { return (!Double.IsNaN(value) && value != 0d); } - public override OSD Copy() { return new OSDReal(value); } - public override int AsInteger() - { - if (Double.IsNaN(value)) - return 0; - if (value > (double)Int32.MaxValue) - return Int32.MaxValue; - if (value < (double)Int32.MinValue) - return Int32.MinValue; - return (int)Math.Round(value); - } - - public override uint AsUInteger() - { - if (Double.IsNaN(value)) - return 0; - if (value > (double)UInt32.MaxValue) - return UInt32.MaxValue; - if (value < (double)UInt32.MinValue) - return UInt32.MinValue; - return (uint)Math.Round(value); - } - - public override long AsLong() - { - if (Double.IsNaN(value)) - return 0; - if (value > (double)Int64.MaxValue) - return Int64.MaxValue; - if (value < (double)Int64.MinValue) - return Int64.MinValue; - return (long)Math.Round(value); - } - - public override ulong AsULong() - { - if (Double.IsNaN(value)) - return 0; - if (value > (double)UInt64.MaxValue) - return Int32.MaxValue; - if (value < (double)UInt64.MinValue) - return UInt64.MinValue; - return (ulong)Math.Round(value); - } - - public override double AsReal() { return value; } - // "r" ensures the value will correctly round-trip back through Double.TryParse - public override string AsString() { return value.ToString("r", Utils.EnUsCulture); } - public override byte[] AsBinary() { return Utils.DoubleToBytesBig(value); } - public override string ToString() { return AsString(); } - } - - /// - /// - /// - public sealed class OSDllsdxml : OSD - { - public readonly string value; - - public override OSD Copy() { return new OSDllsdxml(value); } - - public OSDllsdxml(string value) - { - Type = OSDType.LLSDxml; - // Refuse to hold null pointers - if (value != null) - this.value = value; - else - this.value = String.Empty; - } - - public override string AsString() { return value; } - public override byte[] AsBinary() { return Encoding.UTF8.GetBytes(value); } - public override string ToString() { return AsString(); } - } - - public sealed class OSDUTF8 : OSD - { - public readonly osUTF8 value; - - public override OSD Copy() { return new OSDUTF8(value.Clone()); } - - public OSDUTF8(osUTF8 value) - { - Type = OSDType.OSDUTF8; - // Refuse to hold null pointers - if (value != null) - this.value = value; - else - this.value = new osUTF8(); - } - - public OSDUTF8(byte[] value) - { - Type = OSDType.OSDUTF8; - // Refuse to hold null pointers - if (value != null) - this.value = new osUTF8(value); - else - this.value = new osUTF8(); - } - - public OSDUTF8(string value) - { - Type = OSDType.OSDUTF8; - // Refuse to hold null pointers - if (value != null) - this.value = new osUTF8(value); - else - this.value = new osUTF8(); - } - - public override bool AsBoolean() - { - if (osUTF8.IsNullOrEmpty(value)) - return false; - - if (value.Equals('0') || value.ACSIILowerEquals("false")) - return false; - - return true; - } - - public override int AsInteger() - { - double dbl; - if (Double.TryParse(value.ToString(), out dbl)) - return (int)Math.Floor(dbl); - else - return 0; - } - - public override uint AsUInteger() - { - double dbl; - if (Double.TryParse(value.ToString(), out dbl)) - return (uint)Math.Floor(dbl); - else - return 0; - } - - public override long AsLong() - { - double dbl; - if (Double.TryParse(value.ToString(), out dbl)) - return (long)Math.Floor(dbl); - else - return 0; - } - - public override ulong AsULong() - { - double dbl; - if (Double.TryParse(value.ToString(), out dbl)) - return (ulong)Math.Floor(dbl); - else - return 0; - } - - public override double AsReal() - { - double dbl; - if (Double.TryParse(value.ToString(), out dbl)) - return dbl; - else - return 0d; - } - - public override string AsString() { return value.ToString(); } - public override byte[] AsBinary() { return value.ToArray(); } - - public override UUID AsUUID() - { - UUID uuid; - if (UUID.TryParse(value.ToString(), out uuid)) - return uuid; - else - return UUID.Zero; - } - - public override DateTime AsDate() - { - DateTime dt; - if (DateTime.TryParse(value.ToString(), out dt)) - return dt; - else - return Utils.Epoch; - } - - public override Uri AsUri() - { - Uri uri; - if (Uri.TryCreate(value.ToString(), UriKind.RelativeOrAbsolute, out uri)) - return uri; - else - return null; - } - - public override string ToString() { return AsString(); } - } - - public sealed class OSDString : OSD - { - public readonly string value; - - public override OSD Copy() { return new OSDString(value); } - - public OSDString(string value) - { - Type = OSDType.String; - // Refuse to hold null pointers - if (value != null) - this.value = value; - else - this.value = String.Empty; - } - - public override bool AsBoolean() - { - if (String.IsNullOrEmpty(value)) - return false; - - if (value == "0" || value.ToLower() == "false") - return false; - - return true; - } - - public override int AsInteger() - { - double dbl; - if (Double.TryParse(value, out dbl)) - return (int)Math.Floor(dbl); - else - return 0; - } - - public override uint AsUInteger() - { - double dbl; - if (Double.TryParse(value, out dbl)) - return (uint)Math.Floor(dbl); - else - return 0; - } - - public override long AsLong() - { - double dbl; - if (Double.TryParse(value, out dbl)) - return (long)Math.Floor(dbl); - else - return 0; - } - - public override ulong AsULong() - { - double dbl; - if (Double.TryParse(value, out dbl)) - return (ulong)Math.Floor(dbl); - else - return 0; - } - - public override double AsReal() - { - double dbl; - if (Double.TryParse(value, out dbl)) - return dbl; - else - return 0d; - } - - public override string AsString() { return value; } - public override byte[] AsBinary() { return Encoding.UTF8.GetBytes(value); } - - public override UUID AsUUID() - { - UUID uuid; - if (UUID.TryParse(value, out uuid)) - return uuid; - else - return UUID.Zero; - } - - public override DateTime AsDate() - { - DateTime dt; - if (DateTime.TryParse(value, out dt)) - return dt; - else - return Utils.Epoch; - } - - public override Uri AsUri() - { - Uri uri; - if (Uri.TryCreate(value, UriKind.RelativeOrAbsolute, out uri)) - return uri; - else - return null; - } - - public override string ToString() { return AsString(); } - } - - /// - /// - /// - public sealed class OSDUUID : OSD - { - public readonly UUID value; - - public OSDUUID(UUID value) - { - Type = OSDType.UUID; - this.value = value; - } - - public override OSD Copy() { return new OSDUUID(value); } - public override bool AsBoolean() { return (value == UUID.Zero) ? false : true; } - public override string AsString() { return value.ToString(); } - public override UUID AsUUID() { return value; } - public override byte[] AsBinary() { return value.GetBytes(); } - public override string ToString() { return AsString(); } - } - - /// - /// - /// - public sealed class OSDDate : OSD - { - public readonly DateTime value; - - public OSDDate(DateTime value) - { - Type = OSDType.Date; - this.value = value; - } - - public override string AsString() - { - string format; - if (value.Millisecond > 0) - format = "yyyy-MM-ddTHH:mm:ss.ffZ"; - else - format = "yyyy-MM-ddTHH:mm:ssZ"; - return value.ToUniversalTime().ToString(format); - } - - public override int AsInteger() - { - return (int)Utils.DateTimeToUnixTime(value); - } - - public override uint AsUInteger() - { - return Utils.DateTimeToUnixTime(value); - } - - public override long AsLong() - { - return (long)Utils.DateTimeToUnixTime(value); - } - - public override ulong AsULong() - { - return Utils.DateTimeToUnixTime(value); - } - - public override byte[] AsBinary() - { - TimeSpan ts = value.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); - return Utils.DoubleToBytes(ts.TotalSeconds); - } - - public override OSD Copy() { return new OSDDate(value); } - public override DateTime AsDate() { return value; } - public override string ToString() { return AsString(); } - } - - /// - /// - /// - public sealed class OSDUri : OSD - { - public readonly Uri value; - - public OSDUri(Uri value) - { - Type = OSDType.URI; - this.value = value; - } - - public override string AsString() - { - if (value != null) - { - if (value.IsAbsoluteUri) - return value.AbsoluteUri; - else - return value.ToString(); - } - return string.Empty; - } - - public override OSD Copy() { return new OSDUri(value); } - public override Uri AsUri() { return value; } - public override byte[] AsBinary() { return Encoding.UTF8.GetBytes(AsString()); } - public override string ToString() { return AsString(); } - } - - /// - /// - /// - public sealed class OSDBinary : OSD - { - public readonly byte[] value; - - public OSDBinary(byte[] value) - { - Type = OSDType.Binary; - if (value != null) - this.value = value; - else - this.value = Utils.EmptyBytes; - } - - public OSDBinary(uint value) - { - Type = OSDType.Binary; - this.value = new byte[] - { - (byte)((value >> 24) % 256), - (byte)((value >> 16) % 256), - (byte)((value >> 8) % 256), - (byte)(value % 256) - }; - } - - public OSDBinary(long value) - { - Type = OSDType.Binary; - this.value = new byte[] - { - (byte)((value >> 56) % 256), - (byte)((value >> 48) % 256), - (byte)((value >> 40) % 256), - (byte)((value >> 32) % 256), - (byte)((value >> 24) % 256), - (byte)((value >> 16) % 256), - (byte)((value >> 8) % 256), - (byte)(value % 256) - }; - } - - public OSDBinary(ulong value) - { - Type = OSDType.Binary; - this.value = new byte[] - { - (byte)((value >> 56) % 256), - (byte)((value >> 48) % 256), - (byte)((value >> 40) % 256), - (byte)((value >> 32) % 256), - (byte)((value >> 24) % 256), - (byte)((value >> 16) % 256), - (byte)((value >> 8) % 256), - (byte)(value % 256) - }; - } - - public override OSD Copy() { return new OSDBinary(value); } - public override string AsString() { return Convert.ToBase64String(value); } - public override byte[] AsBinary() { return value; } - - public override int AsInteger() - { - return ( - (value[0] << 24) + - (value[1] << 16) + - (value[2] << 8) + - (value[3] << 0)); - } - - public override uint AsUInteger() - { - return (uint)( - (value[0] << 24) + - (value[1] << 16) + - (value[2] << 8) + - (value[3] << 0)); - } - - public override long AsLong() - { - return (long)( - ((long)value[0] << 56) + - ((long)value[1] << 48) + - ((long)value[2] << 40) + - ((long)value[3] << 32) + - ((long)value[4] << 24) + - ((long)value[5] << 16) + - ((long)value[6] << 8) + - ((long)value[7] << 0)); - } - - public override ulong AsULong() - { - return (ulong)( - ((ulong)value[0] << 56) + - ((ulong)value[1] << 48) + - ((ulong)value[2] << 40) + - ((ulong)value[3] << 32) + - ((ulong)value[4] << 24) + - ((ulong)value[5] << 16) + - ((ulong)value[6] << 8) + - ((ulong)value[7] << 0)); - } - - public override string ToString() - { - return Utils.BytesToHexString(value, null); - } - } - - /// - /// - /// - public sealed class OSDMap : OSD, IDictionary - { - public readonly Dictionary dicvalue; - - public OSDMap() - { - Type = OSDType.Map; - dicvalue = new Dictionary(); - } - - public OSDMap(int capacity) - { - Type = OSDType.Map; - dicvalue = new Dictionary(capacity); - } - - public OSDMap(Dictionary value) - { - Type = OSDType.Map; - if (value != null) - this.dicvalue = value; - else - this.dicvalue = new Dictionary(); - } - - public override string ToString() - { - return OSDParser.SerializeJsonString(this, true); - } - - public override OSD Copy() - { - return new OSDMap(new Dictionary(dicvalue)); - } - - #region IDictionary Implementation - - public int Count { get { return dicvalue.Count; } } - public bool IsReadOnly { get { return false; } } - public ICollection Keys { get { return dicvalue.Keys; } } - public ICollection Values { get { return dicvalue.Values; } } - - public OSD this[string key] - { - get - { - OSD llsd; - if (dicvalue.TryGetValue(key, out llsd)) - return llsd; - else - return new OSD(); - } - set { dicvalue[key] = value; } - } - - public bool ContainsKey(string key) - { - return dicvalue.ContainsKey(key); - } - - public void Add(string key, OSD llsd) - { - dicvalue.Add(key, llsd); - } - - public void Add(KeyValuePair kvp) - { - dicvalue.Add(kvp.Key, kvp.Value); - } - - public bool Remove(string key) - { - return dicvalue.Remove(key); - } - - public bool TryGetValue(string key, out OSD llsd) - { - return dicvalue.TryGetValue(key, out llsd); - } - - public override void Clear() - { - dicvalue.Clear(); - } - - public bool Contains(KeyValuePair kvp) - { - // This is a bizarre function... we don't really implement it - // properly, hopefully no one wants to use it - return dicvalue.ContainsKey(kvp.Key); - } - - public void CopyTo(KeyValuePair[] array, int index) - { - throw new NotImplementedException(); - } - - public bool Remove(KeyValuePair kvp) - { - return dicvalue.Remove(kvp.Key); - } - - public System.Collections.IDictionaryEnumerator GetEnumerator() - { - return dicvalue.GetEnumerator(); - } - - IEnumerator> IEnumerable>.GetEnumerator() - { - return null; - } - - IEnumerator IEnumerable.GetEnumerator() - { - return dicvalue.GetEnumerator(); - } - - #endregion IDictionary Implementation - } - - /// - /// - /// - public sealed class OSDArray : OSD, IList - { - public readonly List value; - - public OSDArray() - { - Type = OSDType.Array; - value = new List(); - } - - public OSDArray(int capacity) - { - Type = OSDType.Array; - value = new List(capacity); - } - - public OSDArray(List value) - { - Type = OSDType.Array; - if (value != null) - this.value = value; - else - this.value = new List(); - } - - public override byte[] AsBinary() - { - byte[] binary = new byte[value.Count]; - - for (int i = 0; i < value.Count; i++) - binary[i] = (byte)value[i].AsInteger(); - - return binary; - } - - public override long AsLong() - { - if (value.Count < 8) - return 0; - byte[] b = new byte[8]; - for (int i = 0; i < 8; i++) - b[i] = (byte)value[i].AsInteger(); - return ( - ((long)b[0] << 56) | - ((long)b[1] << 48) | - ((long)b[2] << 40) | - ((long)b[3] << 32) | - ((long)b[4] << 24) | - ((long)b[5] << 16) | - ((long)b[6] << 8) | - b[7]); - } - - public override ulong AsULong() - { - if (value.Count < 8) - return 0; - byte[] b = new byte[8]; - for (int i = 0; i < 8; i++) - b[i] = (byte)value[i].AsInteger(); - return ( - ((ulong)b[0] << 56) | - ((ulong)b[1] << 48) | - ((ulong)b[2] << 40) | - ((ulong)b[3] << 32) | - ((ulong)b[4] << 24) | - ((ulong)b[5] << 16) | - ((ulong)b[6] << 8) | - b[7]); - } - - public override int AsInteger() - { - if (value.Count < 4) - return 0; - byte[] by = new byte[4]; - for (int i = 0; i < 4; i++) - by[i] = (byte)value[i].AsInteger(); - return (by[0] << 24) | (by[1] << 16) | (by[2] << 8) | by[3]; - } - - public override uint AsUInteger() - { - if (value.Count < 4) - return 0; - byte[] by = new byte[4]; - for (int i = 0; i < 4; i++) - by[i] = (byte)value[i].AsInteger(); - return (uint)((by[0] << 24) | (by[1] << 16) | (by[2] << 8) | by[3]); - } - /* - public override Vector2 AsVector2() - { - Vector2 vector = Vector2.Zero; - - if (this.Count == 2) - { - vector.X = (float)this[0].AsReal(); - vector.Y = (float)this[1].AsReal(); - } - - return vector; - } - - public override Vector3 AsVector3() - { - Vector3 vector = Vector3.Zero; - - if (this.Count == 3) - { - vector.X = this[0].AsReal(); - vector.Y = this[1].AsReal(); - vector.Z = this[2].AsReal(); - } - - return vector; - } - - public override Vector3d AsVector3d() - { - Vector3d vector = Vector3d.Zero; - - if (this.Count == 3) - { - vector.X = this[0].AsReal(); - vector.Y = this[1].AsReal(); - vector.Z = this[2].AsReal(); - } - - return vector; - } - - public override Vector4 AsVector4() - { - Vector4 vector = Vector4.Zero; - - if (this.Count == 4) - { - vector.X = (float)this[0].AsReal(); - vector.Y = (float)this[1].AsReal(); - vector.Z = (float)this[2].AsReal(); - vector.W = (float)this[3].AsReal(); - } - - return vector; - } - - public override Quaternion AsQuaternion() - { - Quaternion quaternion = Quaternion.Identity; - - if (this.Count == 4) - { - quaternion.X = (float)this[0].AsReal(); - quaternion.Y = (float)this[1].AsReal(); - quaternion.Z = (float)this[2].AsReal(); - quaternion.W = (float)this[3].AsReal(); - } - - return quaternion; - } - */ - public override Color4 AsColor4() - { - Color4 color = Color4.Black; - - if (this.Count == 4) - { - color.R = (float)this[0].AsReal(); - color.G = (float)this[1].AsReal(); - color.B = (float)this[2].AsReal(); - color.A = (float)this[3].AsReal(); - } - - return color; - } - - public override OSD Copy() - { - return new OSDArray(new List(value)); - } - - public override string ToString() - { - return OSDParser.SerializeJsonString(this, true); - } - - #region IList Implementation - - public int Count { get { return value.Count; } } - public bool IsReadOnly { get { return false; } } - public OSD this[int index] - { - get { return value[index]; } - set { this.value[index] = value; } - } - - public int IndexOf(OSD llsd) - { - return value.IndexOf(llsd); - } - - public void Insert(int index, OSD llsd) - { - value.Insert(index, llsd); - } - - public void RemoveAt(int index) - { - value.RemoveAt(index); - } - - public void Add(OSD llsd) - { - value.Add(llsd); - } - - public override void Clear() - { - value.Clear(); - } - - public bool Contains(OSD llsd) - { - return value.Contains(llsd); - } - - public bool Contains(string element) - { - for (int i = 0; i < value.Count; i++) - { - if (value[i].Type == OSDType.String && value[i].AsString() == element) - return true; - } - - return false; - } - - public void CopyTo(OSD[] array, int index) - { - throw new NotImplementedException(); - } - - public bool Remove(OSD llsd) - { - return value.Remove(llsd); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return value.GetEnumerator(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return value.GetEnumerator(); - } - - #endregion IList Implementation - } - - public partial class OSDParser - { - const string LLSD_BINARY_HEADER = ""; - const string LLSD_XML_ALT_HEADER = "= 15 ? 15 : data.Length); - - if (header.StartsWith(LLSD_XML_HEADER, StringComparison.InvariantCultureIgnoreCase) || - header.StartsWith(LLSD_XML_ALT_HEADER, StringComparison.InvariantCultureIgnoreCase) || - header.StartsWith(LLSD_XML_ALT2_HEADER, StringComparison.InvariantCultureIgnoreCase)) - return DeserializeLLSDXml(data); - - if (header.StartsWith(LLSD_NOTATION_HEADER, StringComparison.InvariantCultureIgnoreCase)) - return DeserializeLLSDNotation(data); - - if (header.StartsWith(LLSD_BINARY_HEADER, StringComparison.InvariantCultureIgnoreCase)) - return DeserializeLLSDBinary(data); - - return DeserializeJson(data); - } - - public static OSD Deserialize(string data) - { - if (data.StartsWith(LLSD_XML_HEADER, StringComparison.InvariantCultureIgnoreCase) || - data.StartsWith(LLSD_XML_ALT_HEADER, StringComparison.InvariantCultureIgnoreCase) || - data.StartsWith(LLSD_XML_ALT2_HEADER, StringComparison.InvariantCultureIgnoreCase)) - return DeserializeLLSDXml(data); - - if (data.StartsWith(LLSD_NOTATION_HEADER, StringComparison.InvariantCultureIgnoreCase)) - return DeserializeLLSDNotation(data); - - if (data.StartsWith(LLSD_BINARY_HEADER, StringComparison.InvariantCultureIgnoreCase)) - return DeserializeLLSDBinary(Encoding.UTF8.GetBytes(data)); - - return DeserializeJson(data); - } - - public static OSD Deserialize(Stream stream) - { - if (stream.CanSeek) - { - byte[] headerData = new byte[15]; - stream.Read(headerData, 0, 15); - stream.Seek(0, SeekOrigin.Begin); - string header = Encoding.ASCII.GetString(headerData); - - if (header.StartsWith(LLSD_XML_HEADER) || header.StartsWith(LLSD_XML_ALT_HEADER) || header.StartsWith(LLSD_XML_ALT2_HEADER)) - return DeserializeLLSDXml(stream); - - if (header.StartsWith(LLSD_NOTATION_HEADER)) - return DeserializeLLSDNotation(stream); - - if (header.StartsWith(LLSD_BINARY_HEADER)) - return DeserializeLLSDBinary(stream); - - return DeserializeJson(stream); - } - else - { - throw new OSDException("Cannot deserialize structured data from unseekable streams"); - } - } - } -} +/* + * Copyright (c) 2006-2016, openmetaverse.co + * All rights reserved. + * + * - Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * - Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * - Neither the name of the openmetaverse.co nor the names + * of its contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Reflection; +using System.Text; +using System.Runtime.CompilerServices; + +namespace OpenMetaverse.StructuredData +{ + /// + /// + /// + public enum OSDType:byte + { + /// + Unknown, + /// + Boolean, + /// + Integer, + /// + Real, + /// + String, + /// + UUID, + /// + Date, + /// + URI, + /// + Binary, + /// + Map, + /// + Array, + LLSDxml, + OSDUTF8, + Long + } + + public enum OSDFormat + { + Xml = 0, + Json, + Binary + } + + /// + /// + /// + public class OSDException : Exception + { + public OSDException(string message) : base(message) { } + } + + /// + /// + /// + public partial class OSD + { + protected static readonly byte[] trueBinary = { 0x31 }; + protected static readonly byte[] falseBinary = { 0x30 }; + + public OSDType Type = OSDType.Unknown; + + // .net4.8 64Bit JIT fails polimorphism + public virtual bool AsBoolean() + { + switch (Type) + { + case OSDType.Boolean: + return ((OSDBoolean)this).value; + case OSDType.Integer: + return ((OSDInteger)this).value != 0; + case OSDType.Real: + double d = ((OSDReal)this).value; + return (!Double.IsNaN(d) && d != 0); + case OSDType.String: + if (string.IsNullOrEmpty(((OSDString)this).value) || + ((OSDString)this).value.Equals("0") || + ((OSDString)this).value.Equals("false", StringComparison.InvariantCultureIgnoreCase)) + return false; + return true; + case OSDType.UUID: + return ((OSDUUID)this).value.IsNotZero(); + case OSDType.Map: + return ((OSDMap)this).dicvalue.Count > 0; + case OSDType.Array: + return ((OSDArray)this).value.Count > 0; + case OSDType.OSDUTF8: + osUTF8 u = ((OSDUTF8)this).value; + if (osUTF8.IsNullOrEmpty(u)) + return false; + if (u.Equals('0') || u.ACSIILowerEquals("false")) + return false; + return true; + case OSDType.Long: + return ((OSDLong)this).value != 0; + default: + return false; + } + } + + public virtual int AsInteger() + { + switch (Type) + { + case OSDType.Boolean: + return ((OSDBoolean)this).value ? 1 : 0; + case OSDType.Integer: + return ((OSDInteger)this).value; + case OSDType.Long: + long nlv = ((OSDLong)this).value; + if (nlv >= Int32.MaxValue) + return Int32.MaxValue; + if (nlv <= Int32.MinValue) + return Int32.MinValue; + return (int)nlv; + case OSDType.Real: + double v = ((OSDReal)this).value; + if (Double.IsNaN(v)) + return 0; + if (v >= Int32.MaxValue) + return Int32.MaxValue; + if (v <= Int32.MinValue) + return Int32.MinValue; + return (int)Math.Round(v); + case OSDType.String: + if (Double.TryParse(((OSDString)this).value.AsSpan(), out double dbl)) + return (int)Math.Floor(dbl); + else + return 0; + case OSDType.OSDUTF8: + var us = ((OSDUTF8)this).value.ToString().AsSpan(); + if (Double.TryParse(us, out double udbl)) + return (int)Math.Floor(udbl); + else + return 0; + case OSDType.Binary: + byte[] b = ((OSDBinary)this).value; + if (b.Length < 4) + return 0; + return (b[0] << 24) | (b[1] << 16) | (b[2] << 8) | b[3]; + case OSDType.Array: + List l = ((OSDArray)this).value; + if (l.Count < 4) + return 0; + return + (byte)l[0].AsInteger() << 24 | + (byte)l[1].AsInteger() << 16 | + (byte)l[2].AsInteger() << 8 | + (byte)l[3].AsInteger(); + + case OSDType.Date: + return (int)Utils.DateTimeToUnixTime(((OSDDate)this).value); + default: + return 0; + } + } + + public virtual uint AsUInteger() + { + switch (Type) + { + case OSDType.Boolean: + return ((OSDBoolean)this).value ? 1U : 0; + case OSDType.Integer: + return (uint)((OSDInteger)this).value; + case OSDType.Long: + long nlv = ((OSDLong)this).value; + if (nlv >= UInt32.MaxValue) + return Int32.MaxValue; + if (nlv <= UInt32.MinValue) + return UInt32.MinValue; + return (uint)nlv; + case OSDType.Real: + double v = ((OSDReal)this).value; + if (Double.IsNaN(v)) + return 0; + if (v > UInt32.MaxValue) + return UInt32.MaxValue; + if (v < UInt32.MinValue) + return UInt32.MinValue; + return (uint)Math.Round(v); + case OSDType.String: + if (Double.TryParse(((OSDString)this).value.AsSpan(), out double dbl)) + return (uint)Math.Floor(dbl); + else + return 0; + case OSDType.OSDUTF8: + if (Double.TryParse(((OSDUTF8)this).value.ToString().AsSpan(), out double udbl)) + return (uint)Math.Floor(udbl); + else + return 0; + case OSDType.Date: + return Utils.DateTimeToUnixTime(((OSDDate)this).value); + case OSDType.Binary: + byte[] b = ((OSDBinary)this).value; + if(b.Length < 4) + return 0; + return (uint)( + (b[0] << 24) | (b[1] << 16) | (b[2] << 8) | b[3]); + case OSDType.Array: + List l = ((OSDArray)this).value; + if (l.Count < 4) + return 0; + return ( + ((uint)(byte)l[0].AsInteger() << 24) | + ((uint)(byte)l[1].AsInteger() << 16) | + ((uint)(byte)l[2].AsInteger() << 8) | + (byte)l[3].AsInteger()); + default: + return 0; + } + } + + public virtual long AsLong() + { + switch (Type) + { + case OSDType.Boolean: + return ((OSDBoolean)this).value ? 1 : 0; + case OSDType.Integer: + return ((OSDInteger)this).value; + case OSDType.Long: + return ((OSDLong)this).value; + case OSDType.Real: + double v = ((OSDReal)this).value; + if (Double.IsNaN(v)) + return 0; + if (v > Int64.MaxValue) + return Int64.MaxValue; + if (v < Int64.MinValue) + return Int64.MinValue; + return (long)Math.Round(v); + case OSDType.String: + if (Double.TryParse(((OSDString)this).value, out double dbl)) + return (long)Math.Floor(dbl); + else + return 0; + case OSDType.OSDUTF8: + var us = ((OSDUTF8)this).value.ToString().AsSpan(); + if (Double.TryParse(us, out double udbl)) + return (long)Math.Floor(udbl); + else + return 0; + case OSDType.Date: + return Utils.DateTimeToUnixTime(((OSDDate)this).value); + case OSDType.Binary: + { + byte[] b = ((OSDBinary)this).value; + if(b.Length == 4) + { + return + ((long)b[0] << 24) | + ((long)b[1] << 16) | + ((long)b[2] << 8) | + b[3]; + } + if(b.Length < 8) + return 0; + return + ((long)b[0] << 56) | + ((long)b[1] << 48) | + ((long)b[2] << 40) | + ((long)b[3] << 32) | + ((long)b[4] << 24) | + ((long)b[5] << 16) | + ((long)b[6] << 8) | + b[7]; + } + case OSDType.Array: + { + List l = ((OSDArray)this).value; + if (l.Count == 4) + return + ((long)(byte)l[0].AsInteger() << 24) | + ((long)(byte)l[1].AsInteger() << 16) | + ((long)(byte)l[2].AsInteger() << 8) | + (byte)l[3].AsInteger(); + if (l.Count < 8) + return 0; + return + ((long)(byte)l[0].AsInteger() << 56) | + ((long)(byte)l[1].AsInteger() << 48) | + ((long)(byte)l[2].AsInteger() << 40) | + ((long)(byte)l[3].AsInteger() << 32) | + ((long)(byte)l[4].AsInteger() << 24) | + ((long)(byte)l[5].AsInteger() << 16) | + ((long)(byte)l[6].AsInteger() << 8) | + (byte)l[7].AsInteger(); + } + default: + return 0; + } + } + + public virtual ulong AsULong() + { + switch (Type) + { + case OSDType.Boolean: + return ((OSDBoolean)this).value ? 1UL : 0; + case OSDType.Integer: + return (ulong)((OSDInteger)this).value; + case OSDType.Long: + return (ulong)((OSDLong)this).value; + case OSDType.Real: + double v = ((OSDReal)this).value; + if (Double.IsNaN(v)) + return 0; + if (v > UInt64.MaxValue) + return UInt64.MaxValue; + if (v < UInt64.MinValue) + return UInt64.MinValue; + return (ulong)Math.Round(v); + case OSDType.String: + if (Double.TryParse(((OSDString)this).value.AsSpan(), out double dbl)) + return (ulong)Math.Floor(dbl); + else + return 0; + case OSDType.OSDUTF8: + if (Double.TryParse(((OSDUTF8)this).value.ToString().AsSpan(), out double udbl)) + return (ulong)Math.Floor(udbl); + else + return 0; + case OSDType.Date: + return Utils.DateTimeToUnixTime(((OSDDate)this).value); + case OSDType.Binary: + { + byte[] b = ((OSDBinary)this).value; + if(b.Length == 4) + { + return + ((ulong)b[0] << 24) | + ((ulong)b[1] << 16) | + ((ulong)b[2] << 8) | + b[3]; + } + if (b.Length < 8) + return 0; + return ( + ((ulong)b[0] << 56) | + ((ulong)b[1] << 48) | + ((ulong)b[2] << 40) | + ((ulong)b[3] << 32) | + ((ulong)b[4] << 24) | + ((ulong)b[5] << 16) | + ((ulong)b[6] << 8) | + b[7]); + } + case OSDType.Array: + { + List l = ((OSDArray)this).value; + if (l.Count == 4) + return + ((ulong)(byte)l[0].AsInteger() << 24) | + ((ulong)(byte)l[1].AsInteger() << 16) | + ((ulong)(byte)l[2].AsInteger() << 8) | + (byte)l[3].AsInteger(); + if (l.Count < 8) + return 0; + return ( + ((ulong)(byte)l[0].AsInteger() << 56) | + ((ulong)(byte)l[1].AsInteger() << 48) | + ((ulong)(byte)l[2].AsInteger() << 40) | + ((ulong)(byte)l[3].AsInteger() << 32) | + ((ulong)(byte)l[4].AsInteger() << 24) | + ((ulong)(byte)l[5].AsInteger() << 16) | + ((ulong)(byte)l[6].AsInteger() << 8) | + (byte)l[7].AsInteger()); + } + default: + return 0; + } + } + + public virtual double AsReal() + { + switch (Type) + { + case OSDType.Boolean: + return ((OSDBoolean)this).value ? 1.0 : 0; + case OSDType.Integer: + return ((OSDInteger)this).value; + case OSDType.Long: + return ((OSDLong)this).value; + case OSDType.Real: + return ((OSDReal)this).value; + case OSDType.String: + if (Double.TryParse(((OSDString)this).value.AsSpan(), out double dbl)) + return dbl; + else + return 0; + case OSDType.OSDUTF8: + if (Double.TryParse(((OSDUTF8)this).value.ToString().AsSpan(), out double udbl)) + return udbl; + else + return 0; + default: + return 0; + } + } + + public virtual string AsString() + { + switch (Type) + { + case OSDType.Boolean: + return ((OSDBoolean)this).value ? "1" : "0"; + case OSDType.Integer: + return ((OSDInteger)this).value.ToString(); + case OSDType.Long: + return ((OSDLong)this).value.ToString(); + case OSDType.Real: + return ((OSDReal)this).value.ToString("g", Utils.EnUsCulture); + case OSDType.String: + return ((OSDString)this).value; + case OSDType.OSDUTF8: + return ((OSDUTF8)this).value.ToString(); + case OSDType.UUID: + return ((OSDUUID)this).value.ToString(); + case OSDType.Date: + string format; + DateTime dt = ((OSDDate)this).value; + if (dt.Millisecond > 0) + format = "yyyy-MM-ddTHH:mm:ss.ffZ"; + else + format = "yyyy-MM-ddTHH:mm:ssZ"; + return dt.ToUniversalTime().ToString(format); + case OSDType.URI: + Uri ur = ((OSDUri)this).value; + if (ur == null) + return string.Empty; + if (ur.IsAbsoluteUri) + return ur.AbsoluteUri; + else + return ur.ToString(); + + case OSDType.Binary: + byte[] b = ((OSDBinary)this).value; + return Convert.ToBase64String(b); + case OSDType.LLSDxml: + return ((OSDllsdxml)this).value; + default: + return string.Empty; + } + } + + public virtual UUID AsUUID() + { + switch (Type) + { + case OSDType.String: + if (UUID.TryParse(((OSDString)this).value.AsSpan(), out UUID uuid)) + return uuid; + else + return UUID.Zero; + case OSDType.OSDUTF8: + UUID ouuid; + if (UUID.TryParse(((OSDUTF8)this).value.ToString().AsSpan(), out ouuid)) + return ouuid; + else + return UUID.Zero; + case OSDType.UUID: + return ((OSDUUID)this).value; + default: + return UUID.Zero; + } + } + + public virtual DateTime AsDate() + { + switch (Type) + { + case OSDType.String: + DateTime dt; + if (DateTime.TryParse(((OSDString)this).value, out dt)) + return dt; + else + return Utils.Epoch; + case OSDType.OSDUTF8: + DateTime odt; + if (DateTime.TryParse(((OSDUTF8)this).value.ToString(), out odt)) + return odt; + else + return Utils.Epoch; + case OSDType.UUID: + case OSDType.Date: + return ((OSDDate)this).value; + default: + return Utils.Epoch; + } + } + public virtual Uri AsUri() + { + switch (Type) + { + case OSDType.String: + Uri uri; + if (Uri.TryCreate(((OSDString)this).value, UriKind.RelativeOrAbsolute, out uri)) + return uri; + else + return null; + case OSDType.OSDUTF8: + Uri ouri; + if (Uri.TryCreate(((OSDUTF8)this).value.ToString(), UriKind.RelativeOrAbsolute, out ouri)) + return ouri; + else + return null; + case OSDType.URI: + return ((OSDUri)this).value; + default: + return null; + } + } + + public virtual byte[] AsBinary() + { + switch (Type) + { + case OSDType.Boolean: + return ((OSDBoolean)this).value ? trueBinary : falseBinary; + case OSDType.Integer: + return Utils.IntToBytesBig(((OSDInteger)this).value); + case OSDType.Long: + return Utils.Int64ToBytesBig(((OSDLong)this).value); + case OSDType.Real: + return Utils.DoubleToBytesBig(((OSDReal)this).value); + case OSDType.String: + return Encoding.UTF8.GetBytes(((OSDString)this).value); + case OSDType.OSDUTF8: + return ((OSDUTF8)this).value.ToArray(); + case OSDType.UUID: + return (((OSDUUID)this).value).GetBytes(); + case OSDType.Date: + TimeSpan ts = (((OSDDate)this).value).ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); + return Utils.DoubleToBytes(ts.TotalSeconds); + case OSDType.URI: + return Encoding.UTF8.GetBytes(((OSDUri)this).AsString()); + case OSDType.Binary: + return ((OSDBinary)this).value; + case OSDType.Map: + case OSDType.Array: + List l = ((OSDArray)this).value; + byte[] binary = new byte[l.Count]; + for (int i = 0; i < l.Count; i++) + binary[i] = (byte)l[i].AsInteger(); + return binary; + case OSDType.LLSDxml: + return Encoding.UTF8.GetBytes(((OSDllsdxml)this).value); + default: + return Array.Empty(); + } + } + + public Vector2 AsVector2() + { + switch (Type) + { + case OSDType.String: + return Vector2.Parse(((OSDString)this).value); + case OSDType.OSDUTF8: + return Vector2.Parse(((OSDUTF8)this).value.ToString()); + case OSDType.Array: + List l = ((OSDArray)this).value; + Vector2 vector = Vector2.Zero; + if (l.Count == 2) + { + vector.X = (float)l[0].AsReal(); + vector.Y = (float)l[1].AsReal(); + } + return vector; + default: + return Vector2.Zero; + } + } + + public Vector3 AsVector3() + { + switch (Type) + { + case OSDType.String: + return Vector3.Parse(((OSDString)this).value.AsSpan()); + case OSDType.OSDUTF8: + return Vector3.Parse(((OSDUTF8)this).value.ToString().AsSpan()); + case OSDType.Array: + List l = ((OSDArray)this).value; + if (l.Count == 3) + { + return new Vector3( + (float)l[0].AsReal(), + (float)l[1].AsReal(), + (float)l[2].AsReal()); + } + return Vector3.Zero; + default: + return Vector3.Zero; + } + } + + public Vector3d AsVector3d() + { + switch (Type) + { + case OSDType.String: + return Vector3d.Parse(((OSDString)this).value.AsSpan()); + case OSDType.OSDUTF8: + return Vector3d.Parse(((OSDUTF8)this).value.ToString().AsSpan()); + case OSDType.Array: + List l = ((OSDArray)this).value; + Vector3d vector = Vector3d.Zero; + if (l.Count == 3) + { + vector.X = (float)l[0].AsReal(); + vector.Y = (float)l[1].AsReal(); + vector.Z = (float)l[2].AsReal(); + } + return vector; + default: + return Vector3d.Zero; + } + } + + public Vector4 AsVector4() + { + switch (Type) + { + case OSDType.String: + return Vector4.Parse(((OSDString)this).value); + case OSDType.OSDUTF8: + return Vector4.Parse(((OSDUTF8)this).value.ToString()); + case OSDType.Array: + List l = ((OSDArray)this).value; + Vector4 vector = Vector4.Zero; + if (l.Count == 4) + { + vector.X = (float)l[0].AsReal(); + vector.Y = (float)l[1].AsReal(); + vector.Z = (float)l[2].AsReal(); + vector.W = (float)l[3].AsReal(); + } + return vector; + default: + return Vector4.Zero; + } + } + + public Quaternion AsQuaternion() + { + switch (Type) + { + case OSDType.String: + return Quaternion.Parse(((OSDString)this).value); + case OSDType.OSDUTF8: + return Quaternion.Parse(((OSDString)this).value.ToString()); + case OSDType.Array: + List l = ((OSDArray)this).value; + Quaternion q = Quaternion.Identity; + if (l.Count == 4) + { + q.X = (float)l[0].AsReal(); + q.Y = (float)l[1].AsReal(); + q.Z = (float)l[2].AsReal(); + q.W = (float)l[3].AsReal(); + } + return q; + default: + return Quaternion.Identity; + } + } + + public virtual Color4 AsColor4() + { + switch (Type) + { + case OSDType.Array: + List l = ((OSDArray)this).value; + Color4 color = Color4.Black; + if (l.Count == 4) + { + color.R = (float)l[0].AsReal(); + color.G = (float)l[1].AsReal(); + color.B = (float)l[2].AsReal(); + color.A = (float)l[3].AsReal(); + } + return color; + default: + return Color4.Black; + } + } + + public virtual void Clear() { } + + public virtual OSD Copy() + { + return Type switch + { + OSDType.Boolean => new OSDBoolean(((OSDBoolean)this).value), + OSDType.Integer => new OSDInteger(((OSDInteger)this).value), + OSDType.Long => new OSDLong(((OSDLong)this).value), + OSDType.Real => new OSDReal(((OSDReal)this).value), + OSDType.String => new OSDString(((OSDString)this).value), + OSDType.OSDUTF8 => new OSDUTF8(((OSDUTF8)this).value), + OSDType.UUID => new OSDUUID(((OSDUUID)this).value), + OSDType.Date => new OSDDate(((OSDDate)this).value), + OSDType.URI => new OSDUri(((OSDUri)this).value), + OSDType.Binary => new OSDBinary(((OSDBinary)this).value), + OSDType.Map => new OSDMap(((OSDMap)this).dicvalue), + OSDType.Array => new OSDArray(((OSDArray)this).value), + OSDType.LLSDxml => new OSDBoolean(((OSDBoolean)this).value), + _ => new OSD(), + }; + } + + public override string ToString() + { + switch (Type) + { + case OSDType.Boolean: + return ((OSDBoolean)this).value ? "1" : "0"; + case OSDType.Integer: + return ((OSDInteger)this).value.ToString(); + case OSDType.Long: + return (((OSDLong)this).value).ToString(); + case OSDType.Real: + return ((OSDReal)this).value.ToString("g", Utils.EnUsCulture); + case OSDType.String: + return ((OSDString)this).value; + case OSDType.OSDUTF8: + return ((OSDUTF8)this).value.ToString(); + case OSDType.UUID: + return ((OSDUUID)this).value.ToString(); + case OSDType.Date: + string format; + DateTime dt = ((OSDDate)this).value; + if (dt.Millisecond > 0) + format = "yyyy-MM-ddTHH:mm:ss.ffZ"; + else + format = "yyyy-MM-ddTHH:mm:ssZ"; + return dt.ToUniversalTime().ToString(format); + case OSDType.URI: + Uri ur = ((OSDUri)this).value; + if (ur == null) + return string.Empty; + if (ur.IsAbsoluteUri) + return ur.AbsoluteUri; + else + return ur.ToString(); + case OSDType.Binary: + return Utils.BytesToHexString(((OSDBinary)this).value, null); + case OSDType.LLSDxml: + return ((OSDllsdxml)this).value; + case OSDType.Map: + return OSDParser.SerializeJsonString((OSDMap)this, true); + case OSDType.Array: + return OSDParser.SerializeJsonString((OSDArray)this, true); + default: + return "undef"; + } + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static OSD FromBoolean(bool value) { return new OSDBoolean(value); } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static OSD FromInteger(int value) { return new OSDInteger(value); } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static OSD FromInteger(uint value) { return new OSDInteger((int)value); } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static OSD FromInteger(short value) { return new OSDInteger(value); } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static OSD FromInteger(ushort value) { return new OSDInteger(value); } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static OSD FromInteger(sbyte value) { return new OSDInteger(value); } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static OSD FromInteger(byte value) { return new OSDInteger(value); } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static OSD FromUInteger(uint value) { return new OSDBinary(value); } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static OSD FromLong(long value) { return new OSDLong(value); } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static OSD FromULong(ulong value) { return new OSDBinary(value); } + public static OSD FromReal(double value) { return new OSDReal(value); } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static OSD FromReal(float value) { return new OSDReal((double)value); } + public static OSD FromString(string value) { return new OSDString(value); } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static OSD FromUUID(UUID value) { return new OSDUUID(value); } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static OSD FromDate(DateTime value) { return new OSDDate(value); } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static OSD FromUri(Uri value) { return new OSDUri(value); } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static OSD FromBinary(byte[] value) { return new OSDBinary(value); } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static OSD FromVector2(Vector2 value) + { + return new OSDArray() { OSD.FromReal(value.X), OSD.FromReal(value.Y) }; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static OSD FromVector3(Vector3 value) + { + return new OSDArray() { OSD.FromReal(value.X), OSD.FromReal(value.Y), OSD.FromReal(value.Z) }; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static OSD FromVector3d(Vector3d value) + { + return new OSDArray() { OSD.FromReal(value.X), OSD.FromReal(value.Y), OSD.FromReal(value.Z) }; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static OSD FromVector4(Vector4 value) + { + return new OSDArray() { OSD.FromReal(value.X), OSD.FromReal(value.Y), OSD.FromReal(value.Z), OSD.FromReal(value.W) }; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static OSD FromQuaternion(Quaternion value) + { + return new OSDArray() { OSD.FromReal(value.X), OSD.FromReal(value.Y), OSD.FromReal(value.Z), OSD.FromReal(value.W) }; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static OSD FromColor4(Color4 value) + { + return new OSDArray() { OSD.FromReal(value.R), OSD.FromReal(value.G), OSD.FromReal(value.B), OSD.FromReal(value.A) }; + } + + public static OSD FromObject(object value) + { + if (value == null) { return new OSD(); } + else if (value is bool bv) { return new OSDBoolean(bv); } + else if (value is int iv) { return new OSDInteger(iv); } + else if (value is uint uiv) { return new OSDBinary(uiv); } + else if (value is short sv) { return new OSDInteger((int)sv); } + else if (value is ushort usv) { return new OSDInteger((int)usv); } + else if (value is sbyte sbv) { return new OSDInteger((int)sbv); } + else if (value is byte btv) { return new OSDInteger((int)btv); } + else if (value is double dv) { return new OSDReal(dv); } + else if (value is float fv) { return new OSDReal((double)fv); } + else if (value is string stv) { return new OSDString(stv); } + else if (value is UUID uidv) { return new OSDUUID(uidv); } + else if (value is DateTime dtmv) { return new OSDDate(dtmv); } + else if (value is Uri uriv) { return new OSDUri(uriv); } + else if (value is byte[] btav) { return new OSDBinary(btav); } + else if (value is long lv) { return new OSDLong(lv); } + else if (value is ulong ulv) { return new OSDBinary(ulv); } + else if (value is Vector2 v2v) { return FromVector2(v2v); } + else if (value is Vector3 v3v) { return FromVector3(v3v); } + else if (value is Vector3d v3dv) { return FromVector3d(v3dv); } + else if (value is Vector4 v4v) { return FromVector4(v4v); } + else if (value is Quaternion qv) { return FromQuaternion(qv); } + else if (value is Color4 c4v) { return FromColor4(c4v); } + else return new OSD(); + } + + public static object ToObject(Type type, OSD value) + { + if (type == typeof(ulong)) + { + if (value.Type == OSDType.Binary) + { + byte[] bytes = value.AsBinary(); + return Utils.BytesToUInt64(bytes); + } + else + { + return (ulong)value.AsInteger(); + } + } + else if (type == typeof(uint)) + { + if (value.Type == OSDType.Binary) + { + byte[] bytes = value.AsBinary(); + return Utils.BytesToUInt(bytes); + } + else + { + return (uint)value.AsInteger(); + } + } + else if (type == typeof(ushort)) + { + return (ushort)value.AsInteger(); + } + else if (type == typeof(byte)) + { + return (byte)value.AsInteger(); + } + else if (type == typeof(short)) + { + return (short)value.AsInteger(); + } + else if (type == typeof(string)) + { + return value.AsString(); + } + else if (type == typeof(bool)) + { + return value.AsBoolean(); + } + else if (type == typeof(float)) + { + return (float)value.AsReal(); + } + else if (type == typeof(double)) + { + return value.AsReal(); + } + else if (type == typeof(int)) + { + return value.AsInteger(); + } + else if (type == typeof(long)) + { + return value.AsLong(); + } + else if (type == typeof(UUID)) + { + return value.AsUUID(); + } + else if (type == typeof(Vector3)) + { + if (value.Type == OSDType.Array) + return ((OSDArray)value).AsVector3(); + else + return Vector3.Zero; + } + else if (type == typeof(Vector4)) + { + if (value.Type == OSDType.Array) + return ((OSDArray)value).AsVector4(); + else + return Vector4.Zero; + } + else if (type == typeof(Quaternion)) + { + if (value.Type == OSDType.Array) + return ((OSDArray)value).AsQuaternion(); + else + return Quaternion.Identity; + } + else if (type == typeof(OSDArray)) + { + OSDArray newArray = new(); + foreach (OSD o in (OSDArray)value) + newArray.Add(o); + return newArray; + } + else if (type == typeof(OSDMap)) + { + OSDMap newMap = new(); + foreach (KeyValuePair o in (OSDMap)value) + newMap.Add(o); + return newMap; + } + else + { + return null; + } + } + + #region Implicit Conversions + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator OSD(bool value) { return new OSDBoolean(value); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator OSD(int value) { return new OSDInteger(value); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator OSD(uint value) { return new OSDInteger((int)value); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator OSD(short value) { return new OSDInteger((int)value); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator OSD(ushort value) { return new OSDInteger((int)value); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator OSD(sbyte value) { return new OSDInteger((int)value); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator OSD(byte value) { return new OSDInteger((int)value); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator OSD(long value) { return new OSDLong(value); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator OSD(ulong value) { return new OSDBinary(value); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator OSD(double value) { return new OSDReal(value); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator OSD(float value) { return new OSDReal(value); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator OSD(string value) { return new OSDString(value); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator OSD(UUID value) { return new OSDUUID(value); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator OSD(DateTime value) { return new OSDDate(value); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator OSD(Uri value) { return new OSDUri(value); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator OSD(byte[] value) { return new OSDBinary(value); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator OSD(Vector2 value) { return OSD.FromVector2(value); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator OSD(Vector3 value) { return OSD.FromVector3(value); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator OSD(Vector3d value) { return OSD.FromVector3d(value); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator OSD(Vector4 value) { return OSD.FromVector4(value); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator OSD(Quaternion value) { return OSD.FromQuaternion(value); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator OSD(Color4 value) { return OSD.FromColor4(value); } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator bool(OSD value) { return value.AsBoolean(); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator int(OSD value) { return value.AsInteger(); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator uint(OSD value) { return value.AsUInteger(); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator long(OSD value) { return value.AsLong(); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator ulong(OSD value) { return value.AsULong(); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator double(OSD value) { return value.AsReal(); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator float(OSD value) { return (float)value.AsReal(); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator string(OSD value) { return value.AsString(); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator UUID(OSD value) { return value.AsUUID(); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator DateTime(OSD value) { return value.AsDate(); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator Uri(OSD value) { return value.AsUri(); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator Vector2(OSD value) { return value.AsVector2(); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator byte[](OSD value) { return value.AsBinary(); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator Vector3(OSD value) { return value.AsVector3(); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator Vector3d(OSD value) { return value.AsVector3d(); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator Vector4(OSD value) { return value.AsVector4(); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator Quaternion(OSD value) { return value.AsQuaternion(); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator Color4(OSD value) { return value.AsColor4(); } + + #endregion Implicit Conversions + + /// + /// Uses reflection to create an SDMap from all of the SD + /// serializable types in an object + /// + /// Class or struct containing serializable types + /// An SDMap holding the serialized values from the + /// container object + public static OSDMap SerializeMembers(object obj) + { + Type t = obj.GetType(); + FieldInfo[] fields = t.GetFields(); + + OSDMap map = new(fields.Length); + + for (int i = 0; i < fields.Length; i++) + { + FieldInfo field = fields[i]; + if (!Attribute.IsDefined(field, typeof(NonSerializedAttribute))) + { + OSD serializedField = OSD.FromObject(field.GetValue(obj)); + + if (serializedField.Type != OSDType.Unknown || field.FieldType == typeof(string) || field.FieldType == typeof(byte[])) + map.Add(field.Name, serializedField); + } + } + + return map; + } + + /// + /// Uses reflection to deserialize member variables in an object from + /// an SDMap + /// + /// Reference to an object to fill with deserialized + /// values + /// Serialized values to put in the target + /// object + public static void DeserializeMembers(ref object obj, OSDMap serialized) + { + Type t = obj.GetType(); + FieldInfo[] fields = t.GetFields(); + + for (int i = 0; i < fields.Length; i++) + { + FieldInfo field = fields[i]; + if (!Attribute.IsDefined(field, typeof(NonSerializedAttribute))) + { + if (serialized.TryGetValue(field.Name, out OSD serializedField)) + field.SetValue(obj, ToObject(field.FieldType, serializedField)); + } + } + } + } + + /// + /// + /// + public sealed class OSDBoolean : OSD + { + public readonly bool value; + + public OSDBoolean(bool value) + { + Type = OSDType.Boolean; + this.value = value; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override bool AsBoolean() { return value; } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override int AsInteger() { return value ? 1 : 0; } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override long AsLong() { return value ? 1 : 0; } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override double AsReal() { return value ? 1d : 0d; } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override string AsString() { return value ? "1" : "0"; } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override byte[] AsBinary() { return value ? trueBinary : falseBinary; } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override OSD Copy() { return new OSDBoolean(value); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override string ToString() { return AsString(); } + } + + /// + /// + /// + public sealed class OSDInteger : OSD + { + public readonly int value; + + public OSDInteger(int value) + { + Type = OSDType.Integer; + this.value = value; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override bool AsBoolean() { return value != 0; } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override int AsInteger() { return value; } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override uint AsUInteger() { return (uint)value; } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override long AsLong() { return value; } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override ulong AsULong() { return (ulong)value; } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override double AsReal() { return (double)value; } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override string AsString() { return value.ToString(); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override byte[] AsBinary() { return Utils.IntToBytesBig(value); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override OSD Copy() { return new OSDInteger(value); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override string ToString() { return AsString(); } + } + public sealed class OSDLong : OSD + { + public readonly long value; + + public OSDLong(long value) + { + Type = OSDType.Long; + this.value = value; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override bool AsBoolean() { return value != 0; } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override int AsInteger() { return (int)value; } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override uint AsUInteger() { return (uint)value; } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override long AsLong() { return value; } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override ulong AsULong() { return (ulong)value; } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override double AsReal() { return (double)value; } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override string AsString() { return value.ToString(); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override byte[] AsBinary() { return Utils.Int64ToBytesBig(value); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override OSD Copy() { return new OSDLong(value); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override string ToString() { return AsString(); } + } + + /// + /// + /// + public sealed class OSDReal : OSD + { + public readonly double value; + + public OSDReal(double value) + { + Type = OSDType.Real; + this.value = value; + } + + public override bool AsBoolean() { return (!Double.IsNaN(value) && value != 0d); } + public override OSD Copy() { return new OSDReal(value); } + public override int AsInteger() + { + if (Double.IsNaN(value)) + return 0; + if (value > (double)Int32.MaxValue) + return Int32.MaxValue; + if (value < (double)Int32.MinValue) + return Int32.MinValue; + return (int)Math.Round(value); + } + + public override uint AsUInteger() + { + if (Double.IsNaN(value)) + return 0; + if (value > (double)UInt32.MaxValue) + return UInt32.MaxValue; + if (value < (double)UInt32.MinValue) + return UInt32.MinValue; + return (uint)Math.Round(value); + } + + public override long AsLong() + { + if (Double.IsNaN(value)) + return 0; + if (value > (double)Int64.MaxValue) + return Int64.MaxValue; + if (value < (double)Int64.MinValue) + return Int64.MinValue; + return (long)Math.Round(value); + } + + public override ulong AsULong() + { + if (Double.IsNaN(value)) + return 0; + if (value > (double)UInt64.MaxValue) + return Int32.MaxValue; + if (value < (double)UInt64.MinValue) + return UInt64.MinValue; + return (ulong)Math.Round(value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override double AsReal() { return value; } + // "r" ensures the value will correctly round-trip back through Double.TryParse + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override string AsString() { return value.ToString("g", Utils.EnUsCulture); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override byte[] AsBinary() { return Utils.DoubleToBytesBig(value); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override string ToString() { return AsString(); } + } + + /// + /// + /// + public sealed class OSDllsdxml : OSD + { + public readonly string value; + + public override OSD Copy() { return new OSDllsdxml(value); } + + public OSDllsdxml(string value) + { + Type = OSDType.LLSDxml; + // Refuse to hold null pointers + if (value != null) + this.value = value; + else + this.value = String.Empty; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override string AsString() { return value; } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override byte[] AsBinary() { return Encoding.UTF8.GetBytes(value); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override string ToString() { return AsString(); } + } + + public sealed class OSDUTF8 : OSD + { + public readonly osUTF8 value; + + public override OSD Copy() { return new OSDUTF8(value.Clone()); } + + public OSDUTF8(osUTF8 value) + { + Type = OSDType.OSDUTF8; + // Refuse to hold null pointers + if (value != null) + this.value = value; + else + this.value = new osUTF8(); + } + + public OSDUTF8(byte[] value) + { + Type = OSDType.OSDUTF8; + // Refuse to hold null pointers + if (value != null) + this.value = new osUTF8(value); + else + this.value = new osUTF8(); + } + + public OSDUTF8(string value) + { + Type = OSDType.OSDUTF8; + // Refuse to hold null pointers + if (value != null) + this.value = new osUTF8(value); + else + this.value = new osUTF8(); + } + + public override bool AsBoolean() + { + if (osUTF8.IsNullOrEmpty(value)) + return false; + + if (value.Equals('0') || value.ACSIILowerEquals("false")) + return false; + + return true; + } + + public override int AsInteger() + { + if (Double.TryParse(value.ToString().AsSpan(), out double dbl)) + return (int)Math.Floor(dbl); + else + return 0; + } + + public override uint AsUInteger() + { + if (Double.TryParse(value.ToString().AsSpan(), out double dbl)) + return (uint)Math.Floor(dbl); + else + return 0; + } + + public override long AsLong() + { + if (Double.TryParse(value.ToString().AsSpan(), out double dbl)) + return (long)Math.Floor(dbl); + else + return 0; + } + + public override ulong AsULong() + { + if (Double.TryParse(value.ToString().AsSpan(), out double dbl)) + return (ulong)Math.Floor(dbl); + else + return 0; + } + + public override double AsReal() + { + if (Double.TryParse(value.ToString().AsSpan(), out double dbl)) + return dbl; + else + return 0d; + } + + public override string AsString() { return value.ToString(); } + public override byte[] AsBinary() { return value.ToArray(); } + + public override UUID AsUUID() + { + if (UUID.TryParse(value.ToString().AsSpan(), out UUID uuid)) + return uuid; + else + return UUID.Zero; + } + + public override DateTime AsDate() + { + if (DateTime.TryParse(value.ToString().AsSpan(), out DateTime dt)) + return dt; + else + return Utils.Epoch; + } + + public override Uri AsUri() + { + if (Uri.TryCreate(value.ToString(), UriKind.RelativeOrAbsolute, out Uri uri)) + return uri; + else + return null; + } + + public override string ToString() { return AsString(); } + } + + public sealed class OSDString : OSD + { + public readonly string value; + + public override OSD Copy() { return new OSDString(value); } + + public OSDString(string value) + { + Type = OSDType.String; + // Refuse to hold null pointers + this.value = value ?? string.Empty; + } + + public override bool AsBoolean() + { + if (String.IsNullOrEmpty(value)) + return false; + + if (value.Equals("0") || value.Equals( "false", StringComparison.InvariantCultureIgnoreCase)) + return false; + + return true; + } + + public override int AsInteger() + { + if (Double.TryParse(value, out double dbl)) + return (int)Math.Floor(dbl); + else + return 0; + } + + public override uint AsUInteger() + { + if (Double.TryParse(value, out double dbl)) + return (uint)Math.Floor(dbl); + else + return 0; + } + + public override long AsLong() + { + if (Double.TryParse(value, out double dbl)) + return (long)Math.Floor(dbl); + else + return 0; + } + + public override ulong AsULong() + { + if (Double.TryParse(value, out double dbl)) + return (ulong)Math.Floor(dbl); + else + return 0; + } + + public override double AsReal() + { + if (Double.TryParse(value, out double dbl)) + return dbl; + else + return 0d; + } + + public override string AsString() { return value; } + public override byte[] AsBinary() { return Encoding.UTF8.GetBytes(value); } + + public override UUID AsUUID() + { + if (UUID.TryParse(value.AsSpan(), out UUID uuid)) + return uuid; + else + return UUID.Zero; + } + + public override DateTime AsDate() + { + if (DateTime.TryParse(value, out DateTime dt)) + return dt; + else + return Utils.Epoch; + } + + public override Uri AsUri() + { + if (Uri.TryCreate(value, UriKind.RelativeOrAbsolute, out Uri uri)) + return uri; + else + return null; + } + + public override string ToString() { return AsString(); } + } + + /// + /// + /// + public sealed class OSDUUID : OSD + { + public readonly UUID value; + + public OSDUUID(UUID value) + { + Type = OSDType.UUID; + this.value = value; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override OSD Copy() { return new OSDUUID(value); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override bool AsBoolean() { return value.IsNotZero(); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override string AsString() { return value.ToString(); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override UUID AsUUID() { return value; } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override byte[] AsBinary() { return value.GetBytes(); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override string ToString() { return AsString(); } + } + + /// + /// + /// + public sealed class OSDDate : OSD + { + public readonly DateTime value; + + public OSDDate(DateTime value) + { + Type = OSDType.Date; + this.value = value; + } + + public override string AsString() + { + string format; + if (value.Millisecond > 0) + format = "yyyy-MM-ddTHH:mm:ss.ffZ"; + else + format = "yyyy-MM-ddTHH:mm:ssZ"; + return value.ToUniversalTime().ToString(format); + } + + public override int AsInteger() + { + return (int)Utils.DateTimeToUnixTime(value); + } + + public override uint AsUInteger() + { + return Utils.DateTimeToUnixTime(value); + } + + public override long AsLong() + { + return (long)Utils.DateTimeToUnixTime(value); + } + + public override ulong AsULong() + { + return Utils.DateTimeToUnixTime(value); + } + + public override byte[] AsBinary() + { + TimeSpan ts = value.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); + return Utils.DoubleToBytes(ts.TotalSeconds); + } + + public override OSD Copy() { return new OSDDate(value); } + public override DateTime AsDate() { return value; } + public override string ToString() { return AsString(); } + } + + /// + /// + /// + public sealed class OSDUri : OSD + { + public readonly Uri value; + + public OSDUri(Uri value) + { + Type = OSDType.URI; + this.value = value; + } + + public override string AsString() + { + if (value != null) + { + if (value.IsAbsoluteUri) + return value.AbsoluteUri; + else + return value.ToString(); + } + return string.Empty; + } + + public override OSD Copy() { return new OSDUri(value); } + public override Uri AsUri() { return value; } + public override byte[] AsBinary() { return Encoding.UTF8.GetBytes(AsString()); } + public override string ToString() { return AsString(); } + } + + /// + /// + /// + public sealed class OSDBinary : OSD + { + public readonly byte[] value; + + public OSDBinary(byte[] value) + { + Type = OSDType.Binary; + if (value != null) + this.value = value; + else + this.value = Array.Empty(); + } + + public OSDBinary(uint value) + { + Type = OSDType.Binary; + this.value = new byte[] + { + (byte)((value >> 24) & 0xFF), + (byte)((value >> 16) & 0xFF), + (byte)((value >> 8) & 0xFF), + (byte)(value& 0xFF) + }; + } + + public OSDBinary(long value) + { + Type = OSDType.Binary; + this.value = new byte[] + { + (byte)((value >> 56) & 0xFF), + (byte)((value >> 48) & 0xFF), + (byte)((value >> 40) & 0xFF), + (byte)((value >> 32) & 0xFF), + (byte)((value >> 24) & 0xFF), + (byte)((value >> 16) & 0xFF), + (byte)((value >> 8) & 0xFF), + (byte)(value& 0xFF) + }; + } + + public OSDBinary(ulong value) + { + Type = OSDType.Binary; + this.value = new byte[] + { + (byte)((value >> 56) & 0xFF), + (byte)((value >> 48) & 0xFF), + (byte)((value >> 40) & 0xFF), + (byte)((value >> 32) & 0xFF), + (byte)((value >> 24) & 0xFF), + (byte)((value >> 16) & 0xFF), + (byte)((value >> 8) & 0xFF), + (byte)(value& 0xFF) + }; + } + + public override OSD Copy() { return new OSDBinary(value); } + public override string AsString() { return Convert.ToBase64String(value); } + public override byte[] AsBinary() { return value; } + + public override int AsInteger() + { + return ((value[0] << 24) | (value[1] << 16) | (value[2] << 8) | (value[3] << 0)); + } + + public override uint AsUInteger() + { + return (uint)((value[0] << 24) | (value[1] << 16) | (value[2] << 8) | (value[3] << 0));} + + public override long AsLong() + { + return (long)( + ((long)value[0] << 56) | + ((long)value[1] << 48) | + ((long)value[2] << 40) | + ((long)value[3] << 32) | + ((long)value[4] << 24) | + ((long)value[5] << 16) | + ((long)value[6] << 8) | + ((long)value[7] << 0)); + } + + public override ulong AsULong() + { + return (ulong)( + ((ulong)value[0] << 56) | + ((ulong)value[1] << 48) | + ((ulong)value[2] << 40) | + ((ulong)value[3] << 32) | + ((ulong)value[4] << 24) | + ((ulong)value[5] << 16) | + ((ulong)value[6] << 8) | + ((ulong)value[7] << 0)); + } + + public override string ToString() + { + return Utils.BytesToHexString(value, null); + } + } + + /// + /// + /// + public sealed class OSDMap : OSD, IDictionary + { + public readonly Dictionary dicvalue; + + public OSDMap() + { + Type = OSDType.Map; + dicvalue = new Dictionary(); + } + + public OSDMap(int capacity) + { + Type = OSDType.Map; + dicvalue = new Dictionary(capacity); + } + + public OSDMap(Dictionary value) + { + Type = OSDType.Map; + if (value != null) + this.dicvalue = value; + else + this.dicvalue = new Dictionary(); + } + + public override string ToString() + { + return OSDParser.SerializeJsonString(this, true); + } + + public override OSD Copy() + { + return new OSDMap(new Dictionary(dicvalue)); + } + + #region IDictionary Implementation + + public int Count { get { return dicvalue.Count; } } + public bool IsReadOnly { get { return false; } } + public ICollection Keys { get { return dicvalue.Keys; } } + public ICollection Values { get { return dicvalue.Values; } } + + public OSD this[string key] + { + get + { + if (dicvalue.TryGetValue(key, out OSD llsd)) + return llsd; + else + return new OSD(); + } + set { dicvalue[key] = value; } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool ContainsKey(string key) + { + return dicvalue.ContainsKey(key); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Add(string key, OSD llsd) + { + dicvalue.Add(key, llsd); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Add(KeyValuePair kvp) + { + dicvalue.Add(kvp.Key, kvp.Value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool Remove(string key) + { + return dicvalue.Remove(key); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryGetValue(string key, out OSD llsd) + { + return dicvalue.TryGetValue(key, out llsd); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryGetOSDMap(string key, out OSDMap ossd) + { + if (dicvalue.TryGetValue(key, out OSD tmp) && tmp is OSDMap map) + { + ossd = map; + return true; + } + ossd = null; + return false; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryGetOSDArray(string key, out OSDArray ossd) + { + if (dicvalue.TryGetValue(key, out OSD tmp) && tmp is OSDArray arr) + { + ossd = arr; + return true; + } + ossd = null; + return false; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryGetBool(string key, out bool ossd) + { + if (dicvalue.TryGetValue(key, out OSD tmp)) + { + ossd = tmp.AsBoolean(); + return true; + } + ossd = false; + return false; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryGetInt(string key, out int ossd) + { + if (dicvalue.TryGetValue(key, out OSD tmp)) + { + ossd = tmp.AsInteger(); + return true; + } + ossd = 0; + return false; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryGetLong(string key, out long ossd) + { + if (dicvalue.TryGetValue(key, out OSD tmp)) + { + ossd = tmp.AsLong(); + return true; + } + ossd = 0; + return false; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryGetFloat(string key, out float ossd) + { + if (dicvalue.TryGetValue(key, out OSD tmp)) + { + ossd = (float)tmp.AsReal(); + return true; + } + ossd = 0f; + return false; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryGetDouble(string key, out double ossd) + { + if (dicvalue.TryGetValue(key, out OSD tmp)) + { + ossd = tmp.AsReal(); + return true; + } + ossd = 0.0; + return false; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryGetString(string key, out string ossd) + { + if (dicvalue.TryGetValue(key, out OSD tmp)) + { + ossd = tmp.AsString(); + return true; + } + ossd = string.Empty; + return false; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryGetUUID(string key, out UUID ossd) + { + if (dicvalue.TryGetValue(key, out OSD tmp)) + { + ossd = tmp.AsUUID(); + return true; + } + ossd = UUID.Zero; + return false; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryGetDate(string key, out DateTime ossd) + { + if (dicvalue.TryGetValue(key, out OSD tmp)) + { + ossd = tmp.AsDate(); + return true; + } + ossd = Utils.Epoch; + return false; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryGetUri(string key, out Uri ossd) + { + if (dicvalue.TryGetValue(key, out OSD tmp)) + { + ossd = tmp.AsUri(); + return true; + } + ossd = null; + return false; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryGetBinary(string key, out byte[] ossd) + { + if (dicvalue.TryGetValue(key, out OSD tmp)) + { + ossd = tmp.AsBinary(); + return true; + } + ossd = null; + return false; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryGetVector2(string key, out Vector2 ossd) + { + if (dicvalue.TryGetValue(key, out OSD tmp)) + { + ossd = tmp.AsVector2(); + return true; + } + ossd = Vector2.Zero; + return false; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryGetVector3(string key, out Vector3 ossd) + { + if (dicvalue.TryGetValue(key, out OSD tmp)) + { + ossd = tmp.AsVector3(); + return true; + } + ossd = Vector3.Zero; + return false; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryGetVector3d(string key, out Vector3d ossd) + { + if (dicvalue.TryGetValue(key, out OSD tmp)) + { + ossd = tmp.AsVector3d(); + return true; + } + ossd = Vector3d.Zero; + return false; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryGetVector4(string key, out Vector4 ossd) + { + if (dicvalue.TryGetValue(key, out OSD tmp)) + { + ossd = tmp.AsVector4(); + return true; + } + ossd = Vector4.Zero; + return false; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryGetQuat(string key, out Quaternion ossd) + { + if (dicvalue.TryGetValue(key, out OSD tmp)) + { + ossd = tmp.AsQuaternion(); + return true; + } + ossd = Quaternion.Identity; + return false; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryGetColor4(string key, out Color4 ossd) + { + if (dicvalue.TryGetValue(key, out OSD tmp)) + { + ossd = tmp.AsColor4(); + return true; + } + ossd = Color4.Black; + return false; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override void Clear() + { + dicvalue.Clear(); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool Contains(KeyValuePair kvp) + { + // This is a bizarre function... we don't really implement it + // properly, hopefully no one wants to use it + return dicvalue.ContainsKey(kvp.Key); + } + + public void CopyTo(KeyValuePair[] array, int index) + { + throw new NotImplementedException(); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool Remove(KeyValuePair kvp) + { + return dicvalue.Remove(kvp.Key); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public System.Collections.IDictionaryEnumerator GetEnumerator() + { + return dicvalue.GetEnumerator(); + } + + IEnumerator> IEnumerable>.GetEnumerator() + { + return null; + } + + IEnumerator IEnumerable.GetEnumerator() + { + return dicvalue.GetEnumerator(); + } + + #endregion IDictionary Implementation + } + + /// + /// + /// + public sealed class OSDArray : OSD, IList + { + public readonly List value; + + public OSDArray() + { + Type = OSDType.Array; + value = new List(); + } + + public OSDArray(int capacity) + { + Type = OSDType.Array; + value = new List(capacity); + } + + public OSDArray(List value) + { + Type = OSDType.Array; + if (value != null) + this.value = value; + else + this.value = new List(); + } + + public override byte[] AsBinary() + { + byte[] binary = new byte[value.Count]; + + for (int i = 0; i < value.Count; i++) + binary[i] = (byte)value[i].AsInteger(); + + return binary; + } + + public override long AsLong() + { + if (value.Count < 8) + return 0; + byte[] b = new byte[8]; + for (int i = 0; i < 8; i++) + b[i] = (byte)value[i].AsInteger(); + return ( + ((long)b[0] << 56) | + ((long)b[1] << 48) | + ((long)b[2] << 40) | + ((long)b[3] << 32) | + ((long)b[4] << 24) | + ((long)b[5] << 16) | + ((long)b[6] << 8) | + b[7]); + } + + public override ulong AsULong() + { + if (value.Count < 8) + return 0; + byte[] b = new byte[8]; + for (int i = 0; i < 8; i++) + b[i] = (byte)value[i].AsInteger(); + return ( + ((ulong)b[0] << 56) | + ((ulong)b[1] << 48) | + ((ulong)b[2] << 40) | + ((ulong)b[3] << 32) | + ((ulong)b[4] << 24) | + ((ulong)b[5] << 16) | + ((ulong)b[6] << 8) | + b[7]); + } + + public override int AsInteger() + { + if (value.Count < 4) + return 0; + byte[] by = new byte[4]; + for (int i = 0; i < 4; i++) + by[i] = (byte)value[i].AsInteger(); + return (by[0] << 24) | (by[1] << 16) | (by[2] << 8) | by[3]; + } + + public override uint AsUInteger() + { + if (value.Count < 4) + return 0; + byte[] by = new byte[4]; + for (int i = 0; i < 4; i++) + by[i] = (byte)value[i].AsInteger(); + return (uint)((by[0] << 24) | (by[1] << 16) | (by[2] << 8) | by[3]); + } + /* + public override Vector2 AsVector2() + { + Vector2 vector = Vector2.Zero; + + if (this.Count == 2) + { + vector.X = (float)this[0].AsReal(); + vector.Y = (float)this[1].AsReal(); + } + + return vector; + } + + public override Vector3 AsVector3() + { + Vector3 vector = Vector3.Zero; + + if (this.Count == 3) + { + vector.X = this[0].AsReal(); + vector.Y = this[1].AsReal(); + vector.Z = this[2].AsReal(); + } + + return vector; + } + + public override Vector3d AsVector3d() + { + Vector3d vector = Vector3d.Zero; + + if (this.Count == 3) + { + vector.X = this[0].AsReal(); + vector.Y = this[1].AsReal(); + vector.Z = this[2].AsReal(); + } + + return vector; + } + + public override Vector4 AsVector4() + { + Vector4 vector = Vector4.Zero; + + if (this.Count == 4) + { + vector.X = (float)this[0].AsReal(); + vector.Y = (float)this[1].AsReal(); + vector.Z = (float)this[2].AsReal(); + vector.W = (float)this[3].AsReal(); + } + + return vector; + } + + public override Quaternion AsQuaternion() + { + Quaternion quaternion = Quaternion.Identity; + + if (this.Count == 4) + { + quaternion.X = (float)this[0].AsReal(); + quaternion.Y = (float)this[1].AsReal(); + quaternion.Z = (float)this[2].AsReal(); + quaternion.W = (float)this[3].AsReal(); + } + + return quaternion; + } + */ + public override Color4 AsColor4() + { + Color4 color = Color4.Black; + + if (this.Count == 4) + { + color.R = (float)this[0].AsReal(); + color.G = (float)this[1].AsReal(); + color.B = (float)this[2].AsReal(); + color.A = (float)this[3].AsReal(); + } + + return color; + } + + public override OSD Copy() + { + return new OSDArray(new List(value)); + } + + public override string ToString() + { + return OSDParser.SerializeJsonString(this, true); + } + + #region IList Implementation + + public int Count { get { return value.Count; } } + public bool IsReadOnly { get { return false; } } + public OSD this[int index] + { + get { return value[index]; } + set { this.value[index] = value; } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int IndexOf(OSD llsd) + { + return value.IndexOf(llsd); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Insert(int index, OSD llsd) + { + value.Insert(index, llsd); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void RemoveAt(int index) + { + value.RemoveAt(index); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Add(OSD llsd) + { + value.Add(llsd); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override void Clear() + { + value.Clear(); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool Contains(OSD llsd) + { + return value.Contains(llsd); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool Contains(string element) + { + for (int i = 0; i < value.Count; i++) + { + if (value[i].Type == OSDType.String && value[i].AsString() == element) + return true; + } + + return false; + } + + public void CopyTo(OSD[] array, int index) + { + throw new NotImplementedException(); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool Remove(OSD llsd) + { + return value.Remove(llsd); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return value.GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return value.GetEnumerator(); + } + + #endregion IList Implementation + } + + public partial class OSDParser + { + const string LLSD_BINARY_HEADER = ""; + const string LLSD_XML_ALT_HEADER = "= 15 ? 15 : data.Length); + + if (header.StartsWith(LLSD_XML_HEADER, StringComparison.InvariantCultureIgnoreCase) || + header.StartsWith(LLSD_XML_ALT_HEADER, StringComparison.InvariantCultureIgnoreCase) || + header.StartsWith(LLSD_XML_ALT2_HEADER, StringComparison.InvariantCultureIgnoreCase)) + return DeserializeLLSDXml(data); + + if (header.StartsWith(LLSD_NOTATION_HEADER, StringComparison.InvariantCultureIgnoreCase)) + return DeserializeLLSDNotation(data); + + if (header.StartsWith(LLSD_BINARY_HEADER, StringComparison.InvariantCultureIgnoreCase)) + return DeserializeLLSDBinary(data); + + return DeserializeJson(data); + } + + public static OSD Deserialize(string data) + { + if (data.StartsWith(LLSD_XML_HEADER, StringComparison.InvariantCultureIgnoreCase) || + data.StartsWith(LLSD_XML_ALT_HEADER, StringComparison.InvariantCultureIgnoreCase) || + data.StartsWith(LLSD_XML_ALT2_HEADER, StringComparison.InvariantCultureIgnoreCase)) + return DeserializeLLSDXml(data); + + if (data.StartsWith(LLSD_NOTATION_HEADER, StringComparison.InvariantCultureIgnoreCase)) + return DeserializeLLSDNotation(data); + + if (data.StartsWith(LLSD_BINARY_HEADER, StringComparison.InvariantCultureIgnoreCase)) + return DeserializeLLSDBinary(Encoding.UTF8.GetBytes(data)); + + return DeserializeJson(data); + } + + public static OSD Deserialize(Stream stream) + { + if (stream.CanSeek) + { + byte[] headerData = new byte[15]; + stream.Read(headerData, 0, 15); + stream.Seek(0, SeekOrigin.Begin); + string header = Encoding.ASCII.GetString(headerData); + + if (header.StartsWith(LLSD_XML_HEADER) || header.StartsWith(LLSD_XML_ALT_HEADER) || header.StartsWith(LLSD_XML_ALT2_HEADER)) + return DeserializeLLSDXml(stream); + + if (header.StartsWith(LLSD_NOTATION_HEADER)) + return DeserializeLLSDNotation(stream); + + if (header.StartsWith(LLSD_BINARY_HEADER)) + return DeserializeLLSDBinary(stream); + + return DeserializeJson(stream); + } + else + { + throw new OSDException("Cannot deserialize structured data from unseekable streams"); + } + } + } +} diff --git a/OpenMetaverse.Tests/BinaryLLSDTests.cs b/OpenMetaverse.Tests/BinaryLLSDTests.cs index 0f9e31f8..67962320 100644 --- a/OpenMetaverse.Tests/BinaryLLSDTests.cs +++ b/OpenMetaverse.Tests/BinaryLLSDTests.cs @@ -36,7 +36,7 @@ * */ -using NUnit.Framework; +using Xunit; using OpenMetaverse.StructuredData; using System; using System.IO; @@ -46,12 +46,12 @@ namespace OpenMetaverse.Tests { - [TestFixture()] + public class BinarySDTests { private static readonly byte[] binaryHead = Encoding.ASCII.GetBytes("\n"); - [Test()] + [Fact] public void HelperFunctions() { string s = "this is a teststring so that we can find something from the beginning"; @@ -60,39 +60,39 @@ public void HelperFunctions() stream.Position = 0L; bool result = OSDParser.FindString(stream, "this"); - Assert.AreEqual(true, result); - Assert.AreEqual(4L, stream.Position); + Assert.Equal(true, result); + Assert.Equal(4L, stream.Position); stream.Position = 10L; result = OSDParser.FindString(stream, "teststring"); - Assert.AreEqual(true, result); - Assert.AreEqual(20L, stream.Position); + Assert.Equal(true, result); + Assert.Equal(20L, stream.Position); stream.Position = 25L; result = OSDParser.FindString(stream, "notfound"); - Assert.AreEqual(false, result); - Assert.AreEqual(25L, stream.Position); + Assert.Equal(false, result); + Assert.Equal(25L, stream.Position); stream.Position = 60L; result = OSDParser.FindString(stream, "beginningAndMore"); - Assert.AreEqual(false, result); - Assert.AreEqual(60L, stream.Position); + Assert.Equal(false, result); + Assert.Equal(60L, stream.Position); byte[] sFrontWhiteSpace = Encoding.ASCII.GetBytes(" \t\t\n\rtest"); MemoryStream streamTwo = new MemoryStream(sFrontWhiteSpace); OSDParser.SkipWhiteSpace(streamTwo); - Assert.AreEqual(7L, streamTwo.Position); + Assert.Equal(7L, streamTwo.Position); byte[] sMiddleWhiteSpace = Encoding.ASCII.GetBytes("test \t\t\n\rtest"); MemoryStream streamThree = new MemoryStream(sMiddleWhiteSpace); streamThree.Position = 4L; OSDParser.SkipWhiteSpace(streamThree); - Assert.AreEqual(9L, streamThree.Position); + Assert.Equal(9L, streamThree.Position); byte[] sNoWhiteSpace = Encoding.ASCII.GetBytes("testtesttest"); MemoryStream streamFour = new MemoryStream(sNoWhiteSpace); OSDParser.SkipWhiteSpace(streamFour); - Assert.AreEqual(0L, streamFour.Position); + Assert.Equal(0L, streamFour.Position); } @@ -100,19 +100,19 @@ public void HelperFunctions() private static byte[] binaryUndefValue = { 0x21 }; private static byte[] binaryUndef = (byte[])ConcatenateArrays(binaryHead, binaryUndefValue); - [Test()] + [Fact] public void DeserializeUndef() { OSD llsdUndef = OSDParser.DeserializeLLSDBinary(binaryUndef); - Assert.AreEqual(OSDType.Unknown, llsdUndef.Type); + Assert.Equal(OSDType.Unknown, llsdUndef.Type); } - [Test()] + [Fact] public void SerializeUndef() { OSD llsdUndef = new OSD(); byte[] binaryUndefSerialized = OSDParser.SerializeLLSDBinary(llsdUndef); - Assert.AreEqual(binaryUndef, binaryUndefSerialized); + Assert.Equal(binaryUndef, binaryUndefSerialized); } private static byte[] binaryTrueValue = { 0x31 }; @@ -122,28 +122,28 @@ public void SerializeUndef() private static byte[] binaryFalseValue = { 0x30 }; private static byte[] binaryFalse = (byte[])ConcatenateArrays(binaryHead, binaryFalseValue); - [Test()] + [Fact] public void DeserializeBool() { OSD llsdTrue = OSDParser.DeserializeLLSDBinary(binaryTrue); - Assert.AreEqual(OSDType.Boolean, llsdTrue.Type); - Assert.AreEqual(true, llsdTrue.AsBoolean()); + Assert.Equal(OSDType.Boolean, llsdTrue.Type); + Assert.Equal(true, llsdTrue.AsBoolean()); OSD llsdFalse = OSDParser.DeserializeLLSDBinary(binaryFalse); - Assert.AreEqual(OSDType.Boolean, llsdFalse.Type); - Assert.AreEqual(false, llsdFalse.AsBoolean()); + Assert.Equal(OSDType.Boolean, llsdFalse.Type); + Assert.Equal(false, llsdFalse.AsBoolean()); } - [Test()] + [Fact] public void SerializeBool() { OSD llsdTrue = OSD.FromBoolean(true); byte[] binaryTrueSerialized = OSDParser.SerializeLLSDBinary(llsdTrue); - Assert.AreEqual(binaryTrue, binaryTrueSerialized); + Assert.Equal(binaryTrue, binaryTrueSerialized); OSD llsdFalse = OSD.FromBoolean(false); byte[] binaryFalseSerialized = OSDParser.SerializeLLSDBinary(llsdFalse); - Assert.AreEqual(binaryFalse, binaryFalseSerialized); + Assert.Equal(binaryFalse, binaryFalseSerialized); } private static byte[] binaryZeroIntValue = { 0x69, 0x0, 0x0, 0x0, 0x0 }; @@ -152,57 +152,57 @@ public void SerializeBool() private static byte[] binaryAnIntValue = { 0x69, 0x0, 0x12, 0xd7, 0x9b }; private static byte[] binaryAnInt = (byte[])ConcatenateArrays(binaryHead, binaryAnIntValue); - [Test()] + [Fact] public void DeserializeInteger() { OSD llsdZeroInteger = OSDParser.DeserializeLLSDBinary(binaryZeroInt); - Assert.AreEqual(OSDType.Integer, llsdZeroInteger.Type); - Assert.AreEqual(0, llsdZeroInteger.AsInteger()); + Assert.Equal(OSDType.Integer, llsdZeroInteger.Type); + Assert.Equal(0, llsdZeroInteger.AsInteger()); OSD llsdAnInteger = OSDParser.DeserializeLLSDBinary(binaryAnInt); - Assert.AreEqual(OSDType.Integer, llsdAnInteger.Type); - Assert.AreEqual(1234843, llsdAnInteger.AsInteger()); + Assert.Equal(OSDType.Integer, llsdAnInteger.Type); + Assert.Equal(1234843, llsdAnInteger.AsInteger()); } - [Test()] + [Fact] public void SerializeInteger() { OSD llsdZeroInt = OSD.FromInteger(0); byte[] binaryZeroIntSerialized = OSDParser.SerializeLLSDBinary(llsdZeroInt); - Assert.AreEqual(binaryZeroInt, binaryZeroIntSerialized); + Assert.Equal(binaryZeroInt, binaryZeroIntSerialized); binaryZeroIntSerialized = OSDParser.SerializeLLSDBinary(llsdZeroInt, false); - Assert.AreEqual(binaryZeroIntValue, binaryZeroIntSerialized); + Assert.Equal(binaryZeroIntValue, binaryZeroIntSerialized); OSD llsdAnInt = OSD.FromInteger(1234843); byte[] binaryAnIntSerialized = OSDParser.SerializeLLSDBinary(llsdAnInt); - Assert.AreEqual(binaryAnInt, binaryAnIntSerialized); + Assert.Equal(binaryAnInt, binaryAnIntSerialized); binaryAnIntSerialized = OSDParser.SerializeLLSDBinary(llsdAnInt, false); - Assert.AreEqual(binaryAnIntValue, binaryAnIntSerialized); + Assert.Equal(binaryAnIntValue, binaryAnIntSerialized); } private static byte[] binaryRealValue = { 0x72, 0x41, 0x2c, 0xec, 0xf6, 0x77, 0xce, 0xd9, 0x17 }; private static byte[] binaryReal = (byte[])ConcatenateArrays(binaryHead, binaryRealValue); - [Test()] + [Fact] public void DeserializeReal() { OSD llsdReal = OSDParser.DeserializeLLSDBinary(binaryReal); - Assert.AreEqual(OSDType.Real, llsdReal.Type); - Assert.AreEqual(947835.234d, llsdReal.AsReal()); + Assert.Equal(OSDType.Real, llsdReal.Type); + Assert.Equal(947835.234d, llsdReal.AsReal()); } - [Test()] + [Fact] public void SerializeReal() { OSD llsdReal = OSD.FromReal(947835.234d); byte[] binaryRealSerialized = OSDParser.SerializeLLSDBinary(llsdReal); - Assert.AreEqual(binaryReal, binaryRealSerialized); + Assert.Equal(binaryReal, binaryRealSerialized); binaryRealSerialized = OSDParser.SerializeLLSDBinary(llsdReal); - Assert.AreEqual(binaryReal, binaryRealSerialized); + Assert.Equal(binaryReal, binaryRealSerialized); } private static byte[] binaryAUUIDValue = { 0x75, 0x97, 0xf4, 0xae, 0xca, 0x88, 0xa1, 0x42, 0xa1, @@ -213,35 +213,35 @@ public void SerializeReal() private static byte[] binaryZeroUUID = (byte[])ConcatenateArrays(binaryHead, binaryZeroUUIDValue); - [Test()] + [Fact] public void DeserializeUUID() { OSD llsdAUUID = OSDParser.DeserializeLLSDBinary(binaryAUUID); - Assert.AreEqual(OSDType.UUID, llsdAUUID.Type); - Assert.AreEqual("97f4aeca-88a1-42a1-b385-b97b18abb255", llsdAUUID.AsString()); + Assert.Equal(OSDType.UUID, llsdAUUID.Type); + Assert.Equal("97f4aeca-88a1-42a1-b385-b97b18abb255", llsdAUUID.AsString()); OSD llsdZeroUUID = OSDParser.DeserializeLLSDBinary(binaryZeroUUID); - Assert.AreEqual(OSDType.UUID, llsdZeroUUID.Type); - Assert.AreEqual("00000000-0000-0000-0000-000000000000", llsdZeroUUID.AsString()); + Assert.Equal(OSDType.UUID, llsdZeroUUID.Type); + Assert.Equal("00000000-0000-0000-0000-000000000000", llsdZeroUUID.AsString()); } - [Test()] + [Fact] public void SerializeUUID() { OSD llsdAUUID = OSD.FromUUID(new UUID("97f4aeca-88a1-42a1-b385-b97b18abb255")); byte[] binaryAUUIDSerialized = OSDParser.SerializeLLSDBinary(llsdAUUID); - Assert.AreEqual(binaryAUUID, binaryAUUIDSerialized); + Assert.Equal(binaryAUUID, binaryAUUIDSerialized); binaryAUUIDSerialized = OSDParser.SerializeLLSDBinary(llsdAUUID); - Assert.AreEqual(binaryAUUID, binaryAUUIDSerialized); + Assert.Equal(binaryAUUID, binaryAUUIDSerialized); OSD llsdZeroUUID = OSD.FromUUID(new UUID("00000000-0000-0000-0000-000000000000")); byte[] binaryZeroUUIDSerialized = OSDParser.SerializeLLSDBinary(llsdZeroUUID); - Assert.AreEqual(binaryZeroUUID, binaryZeroUUIDSerialized); + Assert.Equal(binaryZeroUUID, binaryZeroUUIDSerialized); binaryZeroUUIDSerialized = OSDParser.SerializeLLSDBinary(llsdZeroUUID); - Assert.AreEqual(binaryZeroUUID, binaryZeroUUIDSerialized); + Assert.Equal(binaryZeroUUID, binaryZeroUUIDSerialized); } private static byte[] binaryBinStringValue = { 0x62, 0x0, 0x0, 0x0, 0x34, // this line is the encoding header @@ -251,19 +251,19 @@ public void SerializeUUID() 0x69, 0x73, 0x20, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0xa, 0xd }; private static byte[] binaryBinString = (byte[])ConcatenateArrays(binaryHead, binaryBinStringValue); - [Test()] + [Fact] public void DeserializeLLSDBinary() { OSD llsdBytes = OSDParser.DeserializeLLSDBinary(binaryBinString); - Assert.AreEqual(OSDType.Binary, llsdBytes.Type); + Assert.Equal(OSDType.Binary, llsdBytes.Type); byte[] contentBinString = { 0x74, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67, 0x20, 0x61, 0x20, 0x73, 0x69, 0x6d, 0x70, 0x6c, 0x65, 0x20, 0x62, 0x69, 0x6e, 0x61, 0x72, 0x79, 0x20, 0x63, 0x6f, 0x6e, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x20, 0x66, 0x6f, 0x72, 0x20, 0x74, 0x68, 0x69, 0x73, 0x20, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0xa, 0xd }; - Assert.AreEqual(contentBinString, llsdBytes.AsBinary()); + Assert.Equal(contentBinString, llsdBytes.AsBinary()); } - [Test()] + [Fact] public void SerializeLLSDBinary() { byte[] contentBinString = { 0x74, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67, 0x20, 0x61, 0x20, 0x73, @@ -272,7 +272,7 @@ public void SerializeLLSDBinary() 0x69, 0x73, 0x20, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0xa, 0xd }; OSD llsdBinary = OSD.FromBinary(contentBinString); byte[] binaryBinarySerialized = OSDParser.SerializeLLSDBinary(llsdBinary); - Assert.AreEqual(binaryBinString, binaryBinarySerialized); + Assert.Equal(binaryBinString, binaryBinarySerialized); } private static byte[] binaryEmptyStringValue = { 0x73, 0x0, 0x0, 0x0, 0x0 }; @@ -286,26 +286,26 @@ public void SerializeLLSDBinary() 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x30 }; private static byte[] binaryLongString = (byte[])ConcatenateArrays(binaryHead, binaryLongStringValue); - [Test()] + [Fact] public void DeserializeString() { OSD llsdEmptyString = OSDParser.DeserializeLLSDBinary(binaryEmptyString); - Assert.AreEqual(OSDType.String, llsdEmptyString.Type); + Assert.Equal(OSDType.String, llsdEmptyString.Type); string contentEmptyString = ""; - Assert.AreEqual(contentEmptyString, llsdEmptyString.AsString()); + Assert.Equal(contentEmptyString, llsdEmptyString.AsString()); OSD llsdLongString = OSDParser.DeserializeLLSDBinary(binaryLongString); - Assert.AreEqual(OSDType.String, llsdLongString.Type); + Assert.Equal(OSDType.String, llsdLongString.Type); string contentLongString = "abcdefghijklmnopqrstuvwxyz01234567890"; - Assert.AreEqual(contentLongString, llsdLongString.AsString()); + Assert.Equal(contentLongString, llsdLongString.AsString()); } - [Test()] + [Fact] public void SerializeString() { OSD llsdString = OSD.FromString("abcdefghijklmnopqrstuvwxyz01234567890"); byte[] binaryLongStringSerialized = OSDParser.SerializeLLSDBinary(llsdString); - Assert.AreEqual(binaryLongString, binaryLongStringSerialized); + Assert.Equal(binaryLongString, binaryLongStringSerialized); // A test with some utf8 characters string contentAStringXML = "ƖȔȠȨɆɒ"; @@ -318,8 +318,8 @@ public void SerializeString() OSD llsdAString = OSD.FromString(contentAString); byte[] binaryAString = OSDParser.SerializeLLSDBinary(llsdAString); OSD llsdAStringDS = OSDParser.DeserializeLLSDBinary(binaryAString); - Assert.AreEqual(OSDType.String, llsdAStringDS.Type); - Assert.AreEqual(contentAString, llsdAStringDS.AsString()); + Assert.Equal(OSDType.String, llsdAStringDS.Type); + Assert.Equal(contentAString, llsdAStringDS.AsString()); // we also test for a 4byte character. string xml = "𐄷"; @@ -332,8 +332,8 @@ public void SerializeString() OSD llsdStringOne = OSD.FromString(content); byte[] binaryAStringOneSerialized = OSDParser.SerializeLLSDBinary(llsdStringOne); OSD llsdStringOneDS = OSDParser.DeserializeLLSDBinary(binaryAStringOneSerialized); - Assert.AreEqual(OSDType.String, llsdStringOneDS.Type); - Assert.AreEqual(content, llsdStringOneDS.AsString()); + Assert.Equal(OSDType.String, llsdStringOneDS.Type); + Assert.Equal(content, llsdStringOneDS.AsString()); } @@ -345,22 +345,22 @@ public void SerializeString() 0x65, 0x73, 0x74, 0x75, 0x72, 0x6c, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x2f }; private static byte[] binaryURI = (byte[])ConcatenateArrays(binaryHead, binaryURIValue); - [Test()] + [Fact] public void DeserializeURI() { OSD llsdURI = OSDParser.DeserializeLLSDBinary(binaryURI); - Assert.AreEqual(OSDType.URI, llsdURI.Type); + Assert.Equal(OSDType.URI, llsdURI.Type); Uri uri = new Uri("http://www.testurl.test/"); - Assert.AreEqual(uri, llsdURI.AsUri()); + Assert.Equal(uri, llsdURI.AsUri()); } - [Test()] + [Fact] public void SerializeURI() { OSD llsdUri = OSD.FromUri(new Uri("http://www.testurl.test/")); byte[] binaryURISerialized = OSDParser.SerializeLLSDBinary(llsdUri); - Assert.AreEqual(binaryURI, binaryURISerialized); + Assert.Equal(binaryURI, binaryURISerialized); } // Here is a problem. @@ -371,38 +371,38 @@ public void SerializeURI() private static byte[] binaryDateTimeValue = { 100, 0, 0, 192, 141, 167, 222, 209, 65 }; private static byte[] binaryDateTime = (byte[])ConcatenateArrays(binaryHead, binaryDateTimeValue); - [Test()] + [Fact] public void DeserializeDateTime() { OSD llsdDateTime = OSDParser.DeserializeLLSDBinary(binaryDateTime); - Assert.AreEqual(OSDType.Date, llsdDateTime.Type); + Assert.Equal(OSDType.Date, llsdDateTime.Type); DateTime dt = new DateTime(2008, 1, 1, 20, 10, 31, 0, DateTimeKind.Utc); DateTime dateLocal = llsdDateTime.AsDate(); - Assert.AreEqual(dt, dateLocal.ToUniversalTime()); + Assert.Equal(dt, dateLocal.ToUniversalTime()); } - [Test()] + [Fact] public void SerializeDateTime() { DateTime dt = new DateTime(2008, 1, 1, 20, 10, 31, 0, DateTimeKind.Utc); OSD llsdDate = OSD.FromDate(dt); byte[] binaryDateSerialized = OSDParser.SerializeLLSDBinary(llsdDate); - Assert.AreEqual(binaryDateTime, binaryDateSerialized); + Assert.Equal(binaryDateTime, binaryDateSerialized); // check if a *local* time can be serialized and deserialized DateTime dtOne = new DateTime(2009, 12, 30, 8, 25, 10, DateTimeKind.Local); OSD llsdDateOne = OSD.FromDate(dtOne); byte[] binaryDateOneSerialized = OSDParser.SerializeLLSDBinary(llsdDateOne); OSD llsdDateOneDS = OSDParser.DeserializeLLSDBinary(binaryDateOneSerialized); - Assert.AreEqual(OSDType.Date, llsdDateOneDS.Type); - Assert.AreEqual(dtOne, llsdDateOneDS.AsDate()); + Assert.Equal(OSDType.Date, llsdDateOneDS.Type); + Assert.Equal(dtOne, llsdDateOneDS.AsDate()); DateTime dtTwo = new DateTime(2010, 11, 11, 10, 8, 20, DateTimeKind.Utc); OSD llsdDateTwo = OSD.FromDate(dtTwo); byte[] binaryDateTwoSerialized = OSDParser.SerializeLLSDBinary(llsdDateTwo); OSD llsdDateTwoDS = OSDParser.DeserializeLLSDBinary(binaryDateTwoSerialized); - Assert.AreEqual(OSDType.Date, llsdDateOneDS.Type); - Assert.AreEqual(dtTwo.ToLocalTime(), llsdDateTwoDS.AsDate()); + Assert.Equal(OSDType.Date, llsdDateOneDS.Type); + Assert.Equal(dtTwo.ToLocalTime(), llsdDateTwoDS.AsDate()); } // Data for empty array { } @@ -420,59 +420,59 @@ public void SerializeDateTime() 0x69, 0x0, 0x0, 0x0, 0x0, 0x5d }; private static byte[] binarySimpleArrayTwo = (byte[])ConcatenateArrays(binaryHead, binarySimpleArrayTwoValue); - [Test()] + [Fact] public void DeserializeArray() { OSD llsdEmptyArray = OSDParser.DeserializeLLSDBinary(binaryEmptyArray); - Assert.AreEqual(OSDType.Array, llsdEmptyArray.Type); + Assert.Equal(OSDType.Array, llsdEmptyArray.Type); OSDArray llsdEmptyArrayArray = (OSDArray)llsdEmptyArray; - Assert.AreEqual(0, llsdEmptyArrayArray.Count); + Assert.Equal(0, llsdEmptyArrayArray.Count); OSD llsdSimpleArray = OSDParser.DeserializeLLSDBinary(binarySimpleArray); - Assert.AreEqual(OSDType.Array, llsdSimpleArray.Type); + Assert.Equal(OSDType.Array, llsdSimpleArray.Type); OSDArray llsdArray = (OSDArray)llsdSimpleArray; - Assert.AreEqual(OSDType.Integer, llsdArray[0].Type); - Assert.AreEqual(0, llsdArray[0].AsInteger()); + Assert.Equal(OSDType.Integer, llsdArray[0].Type); + Assert.Equal(0, llsdArray[0].AsInteger()); OSD llsdSimpleArrayTwo = OSDParser.DeserializeLLSDBinary(binarySimpleArrayTwo); - Assert.AreEqual(OSDType.Array, llsdSimpleArrayTwo.Type); + Assert.Equal(OSDType.Array, llsdSimpleArrayTwo.Type); OSDArray llsdArrayTwo = (OSDArray)llsdSimpleArrayTwo; - Assert.AreEqual(2, llsdArrayTwo.Count); + Assert.Equal(2, llsdArrayTwo.Count); - Assert.AreEqual(OSDType.Integer, llsdArrayTwo[0].Type); - Assert.AreEqual(0, llsdArrayTwo[0].AsInteger()); - Assert.AreEqual(OSDType.Integer, llsdArrayTwo[1].Type); - Assert.AreEqual(0, llsdArrayTwo[1].AsInteger()); + Assert.Equal(OSDType.Integer, llsdArrayTwo[0].Type); + Assert.Equal(0, llsdArrayTwo[0].AsInteger()); + Assert.Equal(OSDType.Integer, llsdArrayTwo[1].Type); + Assert.Equal(0, llsdArrayTwo[1].AsInteger()); } - [Test()] + [Fact] public void SerializeArray() { OSDArray llsdEmptyArray = new OSDArray(); byte[] binaryEmptyArraySerialized = OSDParser.SerializeLLSDBinary(llsdEmptyArray); - Assert.AreEqual(binaryEmptyArray, binaryEmptyArraySerialized); + Assert.Equal(binaryEmptyArray, binaryEmptyArraySerialized); binaryEmptyArraySerialized = OSDParser.SerializeLLSDBinary(llsdEmptyArray, false); - Assert.AreEqual(binaryEmptyArrayValue, binaryEmptyArraySerialized); + Assert.Equal(binaryEmptyArrayValue, binaryEmptyArraySerialized); OSDArray llsdSimpleArray = new OSDArray(); llsdSimpleArray.Add(OSD.FromInteger(0)); byte[] binarySimpleArraySerialized = OSDParser.SerializeLLSDBinary(llsdSimpleArray); - Assert.AreEqual(binarySimpleArray, binarySimpleArraySerialized); + Assert.Equal(binarySimpleArray, binarySimpleArraySerialized); binarySimpleArraySerialized = OSDParser.SerializeLLSDBinary(llsdSimpleArray, false); - Assert.AreEqual(binarySimpleArrayValue, binarySimpleArraySerialized); + Assert.Equal(binarySimpleArrayValue, binarySimpleArraySerialized); OSDArray llsdSimpleArrayTwo = new OSDArray(); llsdSimpleArrayTwo.Add(OSD.FromInteger(0)); llsdSimpleArrayTwo.Add(OSD.FromInteger(0)); byte[] binarySimpleArrayTwoSerialized = OSDParser.SerializeLLSDBinary(llsdSimpleArrayTwo); - Assert.AreEqual(binarySimpleArrayTwo, binarySimpleArrayTwoSerialized); + Assert.Equal(binarySimpleArrayTwo, binarySimpleArrayTwoSerialized); binarySimpleArrayTwoSerialized = OSDParser.SerializeLLSDBinary(llsdSimpleArrayTwo, false); - Assert.AreEqual(binarySimpleArrayTwoValue, binarySimpleArrayTwoSerialized); + Assert.Equal(binarySimpleArrayTwoValue, binarySimpleArrayTwoSerialized); } // Data for empty dictionary { } @@ -502,42 +502,42 @@ public void SerializeArray() 0x7d }; private static byte[] binarySimpleMapTwo = (byte[])ConcatenateArrays(binaryHead, binarySimpleMapTwoValue); - [Test()] + [Fact] public void DeserializeDictionary() { OSDMap llsdEmptyMap = (OSDMap)OSDParser.DeserializeLLSDBinary(binaryEmptyMap); - Assert.AreEqual(OSDType.Map, llsdEmptyMap.Type); - Assert.AreEqual(0, llsdEmptyMap.Count); + Assert.Equal(OSDType.Map, llsdEmptyMap.Type); + Assert.Equal(0, llsdEmptyMap.Count); OSDMap llsdSimpleMap = (OSDMap)OSDParser.DeserializeLLSDBinary(binarySimpleMap); - Assert.AreEqual(OSDType.Map, llsdSimpleMap.Type); - Assert.AreEqual(1, llsdSimpleMap.Count); - Assert.AreEqual(OSDType.Integer, llsdSimpleMap["test"].Type); - Assert.AreEqual(0, llsdSimpleMap["test"].AsInteger()); + Assert.Equal(OSDType.Map, llsdSimpleMap.Type); + Assert.Equal(1, llsdSimpleMap.Count); + Assert.Equal(OSDType.Integer, llsdSimpleMap["test"].Type); + Assert.Equal(0, llsdSimpleMap["test"].AsInteger()); OSDMap llsdSimpleMapTwo = (OSDMap)OSDParser.DeserializeLLSDBinary(binarySimpleMapTwo); - Assert.AreEqual(OSDType.Map, llsdSimpleMapTwo.Type); - Assert.AreEqual(3, llsdSimpleMapTwo.Count); - Assert.AreEqual(OSDType.Unknown, llsdSimpleMapTwo["test"].Type); - Assert.AreEqual(OSDType.String, llsdSimpleMapTwo["tes1"].Type); - Assert.AreEqual("aha", llsdSimpleMapTwo["tes1"].AsString()); - Assert.AreEqual(OSDType.Integer, llsdSimpleMapTwo["t0st"].Type); - Assert.AreEqual(241, llsdSimpleMapTwo["t0st"].AsInteger()); + Assert.Equal(OSDType.Map, llsdSimpleMapTwo.Type); + Assert.Equal(3, llsdSimpleMapTwo.Count); + Assert.Equal(OSDType.Unknown, llsdSimpleMapTwo["test"].Type); + Assert.Equal(OSDType.String, llsdSimpleMapTwo["tes1"].Type); + Assert.Equal("aha", llsdSimpleMapTwo["tes1"].AsString()); + Assert.Equal(OSDType.Integer, llsdSimpleMapTwo["t0st"].Type); + Assert.Equal(241, llsdSimpleMapTwo["t0st"].AsInteger()); } - [Test()] + [Fact] public void SerializeDictionary() { OSDMap llsdEmptyMap = new OSDMap(); byte[] binaryEmptyMapSerialized = OSDParser.SerializeLLSDBinary(llsdEmptyMap); - Assert.AreEqual(binaryEmptyMap, binaryEmptyMapSerialized); + Assert.Equal(binaryEmptyMap, binaryEmptyMapSerialized); OSDMap llsdSimpleMap = new OSDMap(); llsdSimpleMap["test"] = OSD.FromInteger(0); byte[] binarySimpleMapSerialized = OSDParser.SerializeLLSDBinary(llsdSimpleMap); - Assert.AreEqual(binarySimpleMap, binarySimpleMapSerialized); + Assert.Equal(binarySimpleMap, binarySimpleMapSerialized); OSDMap llsdSimpleMapTwo = new OSDMap(); llsdSimpleMapTwo["t0st"] = OSD.FromInteger(241); @@ -549,13 +549,13 @@ public void SerializeDictionary() // the original serialized value is not *exactly* the same. Instead we compare to a deserialized // version created by this deserializer. OSDMap llsdSimpleMapDeserialized = (OSDMap)OSDParser.DeserializeLLSDBinary(binarySimpleMapTwoSerialized); - Assert.AreEqual(OSDType.Map, llsdSimpleMapDeserialized.Type); - Assert.AreEqual(3, llsdSimpleMapDeserialized.Count); - Assert.AreEqual(OSDType.Integer, llsdSimpleMapDeserialized["t0st"].Type); - Assert.AreEqual(241, llsdSimpleMapDeserialized["t0st"].AsInteger()); - Assert.AreEqual(OSDType.String, llsdSimpleMapDeserialized["tes1"].Type); - Assert.AreEqual("aha", llsdSimpleMapDeserialized["tes1"].AsString()); - Assert.AreEqual(OSDType.Unknown, llsdSimpleMapDeserialized["test"].Type); + Assert.Equal(OSDType.Map, llsdSimpleMapDeserialized.Type); + Assert.Equal(3, llsdSimpleMapDeserialized.Count); + Assert.Equal(OSDType.Integer, llsdSimpleMapDeserialized["t0st"].Type); + Assert.Equal(241, llsdSimpleMapDeserialized["t0st"].AsInteger()); + Assert.Equal(OSDType.String, llsdSimpleMapDeserialized["tes1"].Type); + Assert.Equal("aha", llsdSimpleMapDeserialized["tes1"].AsString()); + Assert.Equal(OSDType.Unknown, llsdSimpleMapDeserialized["test"].Type); // we also test for a 4byte key character. string xml = "𐄷"; @@ -568,13 +568,13 @@ public void SerializeDictionary() OSDMap llsdSimpleMapThree = new OSDMap(); OSD llsdSimpleValue = OSD.FromString(content); llsdSimpleMapThree[content] = llsdSimpleValue; - Assert.AreEqual(content, llsdSimpleMapThree[content].AsString()); + Assert.Equal(content, llsdSimpleMapThree[content].AsString()); byte[] binarySimpleMapThree = OSDParser.SerializeLLSDBinary(llsdSimpleMapThree); OSDMap llsdSimpleMapThreeDS = (OSDMap)OSDParser.DeserializeLLSDBinary(binarySimpleMapThree); - Assert.AreEqual(OSDType.Map, llsdSimpleMapThreeDS.Type); - Assert.AreEqual(1, llsdSimpleMapThreeDS.Count); - Assert.AreEqual(content, llsdSimpleMapThreeDS[content].AsString()); + Assert.Equal(OSDType.Map, llsdSimpleMapThreeDS.Type); + Assert.Equal(1, llsdSimpleMapThreeDS.Count); + Assert.Equal(content, llsdSimpleMapThreeDS[content].AsString()); } @@ -594,41 +594,41 @@ public void SerializeDictionary() 0x5d }; private static byte[] binaryNested = (byte[])ConcatenateArrays(binaryHead, binaryNestedValue); - [Test()] + [Fact] public void DeserializeNestedComposite() { OSD llsdNested = OSDParser.DeserializeLLSDBinary(binaryNested); - Assert.AreEqual(OSDType.Array, llsdNested.Type); + Assert.Equal(OSDType.Array, llsdNested.Type); OSDArray llsdArray = (OSDArray)llsdNested; - Assert.AreEqual(3, llsdArray.Count); + Assert.Equal(3, llsdArray.Count); OSDMap llsdMap = (OSDMap)llsdArray[0]; - Assert.AreEqual(OSDType.Map, llsdMap.Type); - Assert.AreEqual(2, llsdMap.Count); + Assert.Equal(OSDType.Map, llsdMap.Type); + Assert.Equal(2, llsdMap.Count); OSDArray llsdNestedArray = (OSDArray)llsdMap["t0st"]; - Assert.AreEqual(OSDType.Array, llsdNestedArray.Type); + Assert.Equal(OSDType.Array, llsdNestedArray.Type); OSDInteger llsdNestedIntOne = (OSDInteger)llsdNestedArray[0]; - Assert.AreEqual(OSDType.Integer, llsdNestedIntOne.Type); - Assert.AreEqual(1, llsdNestedIntOne.AsInteger()); + Assert.Equal(OSDType.Integer, llsdNestedIntOne.Type); + Assert.Equal(1, llsdNestedIntOne.AsInteger()); OSDInteger llsdNestedIntTwo = (OSDInteger)llsdNestedArray[1]; - Assert.AreEqual(OSDType.Integer, llsdNestedIntTwo.Type); - Assert.AreEqual(2, llsdNestedIntTwo.AsInteger()); + Assert.Equal(OSDType.Integer, llsdNestedIntTwo.Type); + Assert.Equal(2, llsdNestedIntTwo.AsInteger()); OSDString llsdString = (OSDString)llsdMap["test"]; - Assert.AreEqual(OSDType.String, llsdString.Type); - Assert.AreEqual("what", llsdString.AsString()); + Assert.Equal(OSDType.String, llsdString.Type); + Assert.Equal("what", llsdString.AsString()); OSDInteger llsdIntOne = (OSDInteger)llsdArray[1]; - Assert.AreEqual(OSDType.Integer, llsdIntOne.Type); - Assert.AreEqual(124, llsdIntOne.AsInteger()); + Assert.Equal(OSDType.Integer, llsdIntOne.Type); + Assert.Equal(124, llsdIntOne.AsInteger()); OSDInteger llsdIntTwo = (OSDInteger)llsdArray[2]; - Assert.AreEqual(OSDType.Integer, llsdIntTwo.Type); - Assert.AreEqual(987, llsdIntTwo.AsInteger()); + Assert.Equal(OSDType.Integer, llsdIntTwo.Type); + Assert.Equal(987, llsdIntTwo.AsInteger()); } - [Test()] + [Fact] public void SerializeNestedComposite() { OSDArray llsdNested = new OSDArray(); @@ -645,34 +645,34 @@ public void SerializeNestedComposite() byte[] binaryNestedSerialized = OSDParser.SerializeLLSDBinary(llsdNested); // Because maps don't preserve order, we compare here to a deserialized value. OSDArray llsdNestedDeserialized = (OSDArray)OSDParser.DeserializeLLSDBinary(binaryNestedSerialized); - Assert.AreEqual(OSDType.Array, llsdNestedDeserialized.Type); - Assert.AreEqual(3, llsdNestedDeserialized.Count); + Assert.Equal(OSDType.Array, llsdNestedDeserialized.Type); + Assert.Equal(3, llsdNestedDeserialized.Count); OSDMap llsdMapDeserialized = (OSDMap)llsdNestedDeserialized[0]; - Assert.AreEqual(OSDType.Map, llsdMapDeserialized.Type); - Assert.AreEqual(2, llsdMapDeserialized.Count); - Assert.AreEqual(OSDType.Array, llsdMapDeserialized["t0st"].Type); + Assert.Equal(OSDType.Map, llsdMapDeserialized.Type); + Assert.Equal(2, llsdMapDeserialized.Count); + Assert.Equal(OSDType.Array, llsdMapDeserialized["t0st"].Type); OSDArray llsdNestedArray = (OSDArray)llsdMapDeserialized["t0st"]; - Assert.AreEqual(OSDType.Array, llsdNestedArray.Type); - Assert.AreEqual(2, llsdNestedArray.Count); - Assert.AreEqual(OSDType.Integer, llsdNestedArray[0].Type); - Assert.AreEqual(1, llsdNestedArray[0].AsInteger()); - Assert.AreEqual(OSDType.Integer, llsdNestedArray[1].Type); - Assert.AreEqual(2, llsdNestedArray[1].AsInteger()); + Assert.Equal(OSDType.Array, llsdNestedArray.Type); + Assert.Equal(2, llsdNestedArray.Count); + Assert.Equal(OSDType.Integer, llsdNestedArray[0].Type); + Assert.Equal(1, llsdNestedArray[0].AsInteger()); + Assert.Equal(OSDType.Integer, llsdNestedArray[1].Type); + Assert.Equal(2, llsdNestedArray[1].AsInteger()); - Assert.AreEqual(OSDType.String, llsdMapDeserialized["test"].Type); - Assert.AreEqual("what", llsdMapDeserialized["test"].AsString()); + Assert.Equal(OSDType.String, llsdMapDeserialized["test"].Type); + Assert.Equal("what", llsdMapDeserialized["test"].AsString()); - Assert.AreEqual(OSDType.Integer, llsdNestedDeserialized[1].Type); - Assert.AreEqual(124, llsdNestedDeserialized[1].AsInteger()); + Assert.Equal(OSDType.Integer, llsdNestedDeserialized[1].Type); + Assert.Equal(124, llsdNestedDeserialized[1].AsInteger()); - Assert.AreEqual(OSDType.Integer, llsdNestedDeserialized[2].Type); - Assert.AreEqual(987, llsdNestedDeserialized[2].AsInteger()); + Assert.Equal(OSDType.Integer, llsdNestedDeserialized[2].Type); + Assert.Equal(987, llsdNestedDeserialized[2].AsInteger()); } - [Test()] + [Fact] public void SerializeLongMessage() { // each 80 chars @@ -698,18 +698,18 @@ public void SerializeLongMessage() byte[] binaryData = OSDParser.SerializeLLSDBinary(llsdMap); OSDMap llsdMapDS = (OSDMap)OSDParser.DeserializeLLSDBinary(binaryData); - Assert.AreEqual(OSDType.Map, llsdMapDS.Type); - Assert.AreEqual(10, llsdMapDS.Count); - Assert.AreEqual(sOne, llsdMapDS["testOne"].AsString()); - Assert.AreEqual(sTwo, llsdMapDS["testTwo"].AsString()); - Assert.AreEqual(sOne, llsdMapDS["testThree"].AsString()); - Assert.AreEqual(sTwo, llsdMapDS["testFour"].AsString()); - Assert.AreEqual(sOne, llsdMapDS["testFive"].AsString()); - Assert.AreEqual(sTwo, llsdMapDS["testSix"].AsString()); - Assert.AreEqual(sOne, llsdMapDS["testSeven"].AsString()); - Assert.AreEqual(sTwo, llsdMapDS["testEight"].AsString()); - Assert.AreEqual(sOne, llsdMapDS["testNine"].AsString()); - Assert.AreEqual(sTwo, llsdMapDS["testTen"].AsString()); + Assert.Equal(OSDType.Map, llsdMapDS.Type); + Assert.Equal(10, llsdMapDS.Count); + Assert.Equal(sOne, llsdMapDS["testOne"].AsString()); + Assert.Equal(sTwo, llsdMapDS["testTwo"].AsString()); + Assert.Equal(sOne, llsdMapDS["testThree"].AsString()); + Assert.Equal(sTwo, llsdMapDS["testFour"].AsString()); + Assert.Equal(sOne, llsdMapDS["testFive"].AsString()); + Assert.Equal(sTwo, llsdMapDS["testSix"].AsString()); + Assert.Equal(sOne, llsdMapDS["testSeven"].AsString()); + Assert.Equal(sTwo, llsdMapDS["testEight"].AsString()); + Assert.Equal(sOne, llsdMapDS["testNine"].AsString()); + Assert.Equal(sTwo, llsdMapDS["testTen"].AsString()); } diff --git a/OpenMetaverse.Tests/MessageTests.cs b/OpenMetaverse.Tests/MessageTests.cs index 87cda425..83dac3f8 100644 --- a/OpenMetaverse.Tests/MessageTests.cs +++ b/OpenMetaverse.Tests/MessageTests.cs @@ -24,13 +24,14 @@ * POSSIBILITY OF SUCH DAMAGE. */ -using NUnit.Framework; +using Xunit; +using MessagePack; +using MessagePack.Resolvers; using OpenMetaverse.Messages.Linden; using OpenMetaverse.StructuredData; using System; using System.IO; using System.Net; -using System.Runtime.Serialization.Formatters.Binary; using System.Text; using System.Xml.Serialization; @@ -41,14 +42,17 @@ namespace OpenMetaverse.Tests /// a passed test does not necessarily indicate the formatting is correct in the resulting OSD to be handled /// by the simulator. /// - [TestFixture] - public class MessageTests : Assert + + public class MessageTests { + private static readonly MessagePackSerializerOptions BenchmarkMessagePackOptions = + MessagePackSerializerOptions.Standard.WithResolver(TypelessContractlessStandardResolver.Instance); + private Uri testURI = new Uri("https://sim3187.agni.lindenlab.com:12043/cap/6028fc44-c1e5-80a1-f902-19bde114458b"); private IPAddress testIP = IPAddress.Parse("127.0.0.1"); private ulong testHandle = 1106108697797888; - [Test] + [Fact] public void AgentGroupDataUpdateMessage() { AgentGroupDataUpdateMessage s = new AgentGroupDataUpdateMessage(); @@ -95,25 +99,25 @@ public void AgentGroupDataUpdateMessage() AgentGroupDataUpdateMessage t = new AgentGroupDataUpdateMessage(); t.Deserialize(map); - Assert.AreEqual(s.AgentID, t.AgentID); + Assert.Equal(s.AgentID, t.AgentID); for (int i = 0; i < t.GroupDataBlock.Length; i++) { - Assert.AreEqual(s.GroupDataBlock[i].AcceptNotices, t.GroupDataBlock[i].AcceptNotices); - Assert.AreEqual(s.GroupDataBlock[i].Contribution, t.GroupDataBlock[i].Contribution); - Assert.AreEqual(s.GroupDataBlock[i].GroupID, t.GroupDataBlock[i].GroupID); - Assert.AreEqual(s.GroupDataBlock[i].GroupInsigniaID, t.GroupDataBlock[i].GroupInsigniaID); - Assert.AreEqual(s.GroupDataBlock[i].GroupName, t.GroupDataBlock[i].GroupName); - Assert.AreEqual(s.GroupDataBlock[i].GroupPowers, t.GroupDataBlock[i].GroupPowers); + Assert.Equal(s.GroupDataBlock[i].AcceptNotices, t.GroupDataBlock[i].AcceptNotices); + Assert.Equal(s.GroupDataBlock[i].Contribution, t.GroupDataBlock[i].Contribution); + Assert.Equal(s.GroupDataBlock[i].GroupID, t.GroupDataBlock[i].GroupID); + Assert.Equal(s.GroupDataBlock[i].GroupInsigniaID, t.GroupDataBlock[i].GroupInsigniaID); + Assert.Equal(s.GroupDataBlock[i].GroupName, t.GroupDataBlock[i].GroupName); + Assert.Equal(s.GroupDataBlock[i].GroupPowers, t.GroupDataBlock[i].GroupPowers); } for (int i = 0; i < t.NewGroupDataBlock.Length; i++) { - Assert.AreEqual(s.NewGroupDataBlock[i].ListInProfile, t.NewGroupDataBlock[i].ListInProfile); + Assert.Equal(s.NewGroupDataBlock[i].ListInProfile, t.NewGroupDataBlock[i].ListInProfile); } } - [Test] + [Fact] public void TeleportFinishMessage() { TeleportFinishMessage s = new TeleportFinishMessage(); @@ -131,17 +135,17 @@ public void TeleportFinishMessage() TeleportFinishMessage t = new TeleportFinishMessage(); t.Deserialize(map); - Assert.AreEqual(s.AgentID, t.AgentID); - Assert.AreEqual(s.Flags, t.Flags); - Assert.AreEqual(s.IP, t.IP); - Assert.AreEqual(s.LocationID, t.LocationID); - Assert.AreEqual(s.Port, t.Port); - Assert.AreEqual(s.RegionHandle, t.RegionHandle); - Assert.AreEqual(s.SeedCapability, t.SeedCapability); - Assert.AreEqual(s.SimAccess, t.SimAccess); + Assert.Equal(s.AgentID, t.AgentID); + Assert.Equal(s.Flags, t.Flags); + Assert.Equal(s.IP, t.IP); + Assert.Equal(s.LocationID, t.LocationID); + Assert.Equal(s.Port, t.Port); + Assert.Equal(s.RegionHandle, t.RegionHandle); + Assert.Equal(s.SeedCapability, t.SeedCapability); + Assert.Equal(s.SimAccess, t.SimAccess); } - [Test] + [Fact] public void EstablishAgentCommunicationMessage() { EstablishAgentCommunicationMessage s = new EstablishAgentCommunicationMessage(); @@ -155,13 +159,13 @@ public void EstablishAgentCommunicationMessage() EstablishAgentCommunicationMessage t = new EstablishAgentCommunicationMessage(); t.Deserialize(map); - Assert.AreEqual(s.Address, t.Address); - Assert.AreEqual(s.AgentID, t.AgentID); - Assert.AreEqual(s.Port, t.Port); - Assert.AreEqual(s.SeedCapability, t.SeedCapability); + Assert.Equal(s.Address, t.Address); + Assert.Equal(s.AgentID, t.AgentID); + Assert.Equal(s.Port, t.Port); + Assert.Equal(s.SeedCapability, t.SeedCapability); } - [Test] + [Fact] public void ParcelObjectOwnersMessage() { ParcelObjectOwnersReplyMessage s = new ParcelObjectOwnersReplyMessage(); @@ -190,15 +194,15 @@ public void ParcelObjectOwnersMessage() for (int i = 0; i < t.PrimOwnersBlock.Length; i++) { - Assert.AreEqual(s.PrimOwnersBlock[i].Count, t.PrimOwnersBlock[i].Count); - Assert.AreEqual(s.PrimOwnersBlock[i].IsGroupOwned, t.PrimOwnersBlock[i].IsGroupOwned); - Assert.AreEqual(s.PrimOwnersBlock[i].OnlineStatus, t.PrimOwnersBlock[i].OnlineStatus); - Assert.AreEqual(s.PrimOwnersBlock[i].OwnerID, t.PrimOwnersBlock[i].OwnerID); - Assert.AreEqual(s.PrimOwnersBlock[i].TimeStamp, t.PrimOwnersBlock[i].TimeStamp); + Assert.Equal(s.PrimOwnersBlock[i].Count, t.PrimOwnersBlock[i].Count); + Assert.Equal(s.PrimOwnersBlock[i].IsGroupOwned, t.PrimOwnersBlock[i].IsGroupOwned); + Assert.Equal(s.PrimOwnersBlock[i].OnlineStatus, t.PrimOwnersBlock[i].OnlineStatus); + Assert.Equal(s.PrimOwnersBlock[i].OwnerID, t.PrimOwnersBlock[i].OwnerID); + Assert.Equal(s.PrimOwnersBlock[i].TimeStamp, t.PrimOwnersBlock[i].TimeStamp); } } - [Test] + [Fact] public void ChatterBoxInvitationMessage() { ChatterBoxInvitationMessage s = new ChatterBoxInvitationMessage(); @@ -221,22 +225,22 @@ public void ChatterBoxInvitationMessage() ChatterBoxInvitationMessage t = new ChatterBoxInvitationMessage(); t.Deserialize(map); - Assert.AreEqual(s.BinaryBucket, t.BinaryBucket); - Assert.AreEqual(s.Dialog, t.Dialog); - Assert.AreEqual(s.FromAgentID, t.FromAgentID); - Assert.AreEqual(s.FromAgentName, t.FromAgentName); - Assert.AreEqual(s.GroupIM, t.GroupIM); - Assert.AreEqual(s.IMSessionID, t.IMSessionID); - Assert.AreEqual(s.Message, t.Message); - Assert.AreEqual(s.Offline, t.Offline); - Assert.AreEqual(s.ParentEstateID, t.ParentEstateID); - Assert.AreEqual(s.Position, t.Position); - Assert.AreEqual(s.RegionID, t.RegionID); - Assert.AreEqual(s.Timestamp, t.Timestamp); - Assert.AreEqual(s.ToAgentID, t.ToAgentID); + Assert.Equal(s.BinaryBucket, t.BinaryBucket); + Assert.Equal(s.Dialog, t.Dialog); + Assert.Equal(s.FromAgentID, t.FromAgentID); + Assert.Equal(s.FromAgentName, t.FromAgentName); + Assert.Equal(s.GroupIM, t.GroupIM); + Assert.Equal(s.IMSessionID, t.IMSessionID); + Assert.Equal(s.Message, t.Message); + Assert.Equal(s.Offline, t.Offline); + Assert.Equal(s.ParentEstateID, t.ParentEstateID); + Assert.Equal(s.Position, t.Position); + Assert.Equal(s.RegionID, t.RegionID); + Assert.Equal(s.Timestamp, t.Timestamp); + Assert.Equal(s.ToAgentID, t.ToAgentID); } - [Test] + [Fact] public void ChatterboxSessionEventReplyMessage() { ChatterboxSessionEventReplyMessage s = new ChatterboxSessionEventReplyMessage(); @@ -248,11 +252,11 @@ public void ChatterboxSessionEventReplyMessage() ChatterboxSessionEventReplyMessage t = new ChatterboxSessionEventReplyMessage(); t.Deserialize(map); - Assert.AreEqual(s.SessionID, t.SessionID); - Assert.AreEqual(s.Success, t.Success); + Assert.Equal(s.SessionID, t.SessionID); + Assert.Equal(s.Success, t.Success); } - [Test] + [Fact] public void ChatterBoxSessionStartReplyMessage() { ChatterBoxSessionStartReplyMessage s = new ChatterBoxSessionStartReplyMessage(); @@ -269,16 +273,16 @@ public void ChatterBoxSessionStartReplyMessage() ChatterBoxSessionStartReplyMessage t = new ChatterBoxSessionStartReplyMessage(); t.Deserialize(map); - Assert.AreEqual(s.ModeratedVoice, t.ModeratedVoice); - Assert.AreEqual(s.SessionID, t.SessionID); - Assert.AreEqual(s.SessionName, t.SessionName); - Assert.AreEqual(s.Success, t.Success); - Assert.AreEqual(s.TempSessionID, t.TempSessionID); - Assert.AreEqual(s.Type, t.Type); - Assert.AreEqual(s.VoiceEnabled, t.VoiceEnabled); + Assert.Equal(s.ModeratedVoice, t.ModeratedVoice); + Assert.Equal(s.SessionID, t.SessionID); + Assert.Equal(s.SessionName, t.SessionName); + Assert.Equal(s.Success, t.Success); + Assert.Equal(s.TempSessionID, t.TempSessionID); + Assert.Equal(s.Type, t.Type); + Assert.Equal(s.VoiceEnabled, t.VoiceEnabled); } - [Test] + [Fact] public void ChatterBoxSessionAgentListUpdatesMessage() { ChatterBoxSessionAgentListUpdatesMessage s = new ChatterBoxSessionAgentListUpdatesMessage(); @@ -309,19 +313,19 @@ public void ChatterBoxSessionAgentListUpdatesMessage() ChatterBoxSessionAgentListUpdatesMessage t = new ChatterBoxSessionAgentListUpdatesMessage(); t.Deserialize(map); - Assert.AreEqual(s.SessionID, t.SessionID); + Assert.Equal(s.SessionID, t.SessionID); for (int i = 0; i < t.Updates.Length; i++) { - Assert.AreEqual(s.Updates[i].AgentID, t.Updates[i].AgentID); - Assert.AreEqual(s.Updates[i].CanVoiceChat, t.Updates[i].CanVoiceChat); - Assert.AreEqual(s.Updates[i].IsModerator, t.Updates[i].IsModerator); - Assert.AreEqual(s.Updates[i].MuteText, t.Updates[i].MuteText); - Assert.AreEqual(s.Updates[i].MuteVoice, t.Updates[i].MuteVoice); - Assert.AreEqual(s.Updates[i].Transition, t.Updates[i].Transition); + Assert.Equal(s.Updates[i].AgentID, t.Updates[i].AgentID); + Assert.Equal(s.Updates[i].CanVoiceChat, t.Updates[i].CanVoiceChat); + Assert.Equal(s.Updates[i].IsModerator, t.Updates[i].IsModerator); + Assert.Equal(s.Updates[i].MuteText, t.Updates[i].MuteText); + Assert.Equal(s.Updates[i].MuteVoice, t.Updates[i].MuteVoice); + Assert.Equal(s.Updates[i].Transition, t.Updates[i].Transition); } } - [Test] + [Fact] public void ViewerStatsMessage() { ViewerStatsMessage s = new ViewerStatsMessage(); @@ -372,52 +376,52 @@ public void ViewerStatsMessage() ViewerStatsMessage t = new ViewerStatsMessage(); t.Deserialize(map); - Assert.AreEqual(s.AgentFPS, t.AgentFPS); - Assert.AreEqual(s.AgentsInView, t.AgentsInView); - Assert.AreEqual(s.SystemCPU, t.SystemCPU); - Assert.AreEqual(s.StatsDropped, t.StatsDropped); - Assert.AreEqual(s.StatsFailedResends, t.StatsFailedResends); - Assert.AreEqual(s.SystemGPU, t.SystemGPU); - Assert.AreEqual(s.SystemGPUClass, t.SystemGPUClass); - Assert.AreEqual(s.SystemGPUVendor, t.SystemGPUVendor); - Assert.AreEqual(s.SystemGPUVersion, t.SystemGPUVersion); - Assert.AreEqual(s.InCompressedPackets, t.InCompressedPackets); - Assert.AreEqual(s.InKbytes, t.InKbytes); - Assert.AreEqual(s.InPackets, t.InPackets); - Assert.AreEqual(s.InSavings, t.InSavings); - Assert.AreEqual(s.MiscInt1, t.MiscInt1); - Assert.AreEqual(s.MiscInt2, t.MiscInt2); - Assert.AreEqual(s.FailuresInvalid, t.FailuresInvalid); - Assert.AreEqual(s.AgentLanguage, t.AgentLanguage); - Assert.AreEqual(s.AgentMemoryUsed, t.AgentMemoryUsed); - Assert.AreEqual(s.MetersTraveled, t.MetersTraveled); - Assert.AreEqual(s.object_kbytes, t.object_kbytes); - Assert.AreEqual(s.FailuresOffCircuit, t.FailuresOffCircuit); - Assert.AreEqual(s.SystemOS, t.SystemOS); - Assert.AreEqual(s.OutCompressedPackets, t.OutCompressedPackets); - Assert.AreEqual(s.OutKbytes, t.OutKbytes); - Assert.AreEqual(s.OutPackets, t.OutPackets); - Assert.AreEqual(s.OutSavings, t.OutSavings); - Assert.AreEqual(s.AgentPing, t.AgentPing); - Assert.AreEqual(s.SystemInstalledRam, t.SystemInstalledRam); - Assert.AreEqual(s.RegionsVisited, t.RegionsVisited); - Assert.AreEqual(s.FailuresResent, t.FailuresResent); - Assert.AreEqual(s.AgentRuntime, t.AgentRuntime); - Assert.AreEqual(s.FailuresSendPacket, t.FailuresSendPacket); - Assert.AreEqual(s.SessionID, t.SessionID); - Assert.AreEqual(s.SimulatorFPS, t.SimulatorFPS); - Assert.AreEqual(s.AgentStartTime, t.AgentStartTime); - Assert.AreEqual(s.MiscString1, t.MiscString1); - Assert.AreEqual(s.texture_kbytes, t.texture_kbytes); - Assert.AreEqual(s.AgentVersion, t.AgentVersion); - Assert.AreEqual(s.MiscVersion, t.MiscVersion); - Assert.AreEqual(s.VertexBuffersEnabled, t.VertexBuffersEnabled); - Assert.AreEqual(s.world_kbytes, t.world_kbytes); + Assert.Equal(s.AgentFPS, t.AgentFPS); + Assert.Equal(s.AgentsInView, t.AgentsInView); + Assert.Equal(s.SystemCPU, t.SystemCPU); + Assert.Equal(s.StatsDropped, t.StatsDropped); + Assert.Equal(s.StatsFailedResends, t.StatsFailedResends); + Assert.Equal(s.SystemGPU, t.SystemGPU); + Assert.Equal(s.SystemGPUClass, t.SystemGPUClass); + Assert.Equal(s.SystemGPUVendor, t.SystemGPUVendor); + Assert.Equal(s.SystemGPUVersion, t.SystemGPUVersion); + Assert.Equal(s.InCompressedPackets, t.InCompressedPackets); + Assert.Equal(s.InKbytes, t.InKbytes); + Assert.Equal(s.InPackets, t.InPackets); + Assert.Equal(s.InSavings, t.InSavings); + Assert.Equal(s.MiscInt1, t.MiscInt1); + Assert.Equal(s.MiscInt2, t.MiscInt2); + Assert.Equal(s.FailuresInvalid, t.FailuresInvalid); + Assert.Equal(s.AgentLanguage, t.AgentLanguage); + Assert.Equal(s.AgentMemoryUsed, t.AgentMemoryUsed); + Assert.Equal(s.MetersTraveled, t.MetersTraveled); + Assert.Equal(s.object_kbytes, t.object_kbytes); + Assert.Equal(s.FailuresOffCircuit, t.FailuresOffCircuit); + Assert.Equal(s.SystemOS, t.SystemOS); + Assert.Equal(s.OutCompressedPackets, t.OutCompressedPackets); + Assert.Equal(s.OutKbytes, t.OutKbytes); + Assert.Equal(s.OutPackets, t.OutPackets); + Assert.Equal(s.OutSavings, t.OutSavings); + Assert.Equal(s.AgentPing, t.AgentPing); + Assert.Equal(s.SystemInstalledRam, t.SystemInstalledRam); + Assert.Equal(s.RegionsVisited, t.RegionsVisited); + Assert.Equal(s.FailuresResent, t.FailuresResent); + Assert.Equal(s.AgentRuntime, t.AgentRuntime); + Assert.Equal(s.FailuresSendPacket, t.FailuresSendPacket); + Assert.Equal(s.SessionID, t.SessionID); + Assert.Equal(s.SimulatorFPS, t.SimulatorFPS); + Assert.Equal(s.AgentStartTime, t.AgentStartTime); + Assert.Equal(s.MiscString1, t.MiscString1); + Assert.Equal(s.texture_kbytes, t.texture_kbytes); + Assert.Equal(s.AgentVersion, t.AgentVersion); + Assert.Equal(s.MiscVersion, t.MiscVersion); + Assert.Equal(s.VertexBuffersEnabled, t.VertexBuffersEnabled); + Assert.Equal(s.world_kbytes, t.world_kbytes); } - [Test] + [Fact] public void ParcelVoiceInfoRequestMessage() { ParcelVoiceInfoRequestMessage s = new ParcelVoiceInfoRequestMessage(); @@ -430,12 +434,12 @@ public void ParcelVoiceInfoRequestMessage() ParcelVoiceInfoRequestMessage t = new ParcelVoiceInfoRequestMessage(); t.Deserialize(map); - Assert.AreEqual(s.SipChannelUri, t.SipChannelUri); - Assert.AreEqual(s.ParcelID, t.ParcelID); - Assert.AreEqual(s.RegionName, t.RegionName); + Assert.Equal(s.SipChannelUri, t.SipChannelUri); + Assert.Equal(s.ParcelID, t.ParcelID); + Assert.Equal(s.RegionName, t.RegionName); } - [Test] + [Fact] public void ScriptRunningReplyMessage() { ScriptRunningReplyMessage s = new ScriptRunningReplyMessage(); @@ -449,14 +453,14 @@ public void ScriptRunningReplyMessage() ScriptRunningReplyMessage t = new ScriptRunningReplyMessage(); t.Deserialize(map); - Assert.AreEqual(s.ItemID, t.ItemID); - Assert.AreEqual(s.Mono, t.Mono); - Assert.AreEqual(s.ObjectID, t.ObjectID); - Assert.AreEqual(s.Running, t.Running); + Assert.Equal(s.ItemID, t.ItemID); + Assert.Equal(s.Mono, t.Mono); + Assert.Equal(s.ObjectID, t.ObjectID); + Assert.Equal(s.Running, t.Running); } - [Test] + [Fact] public void MapLayerMessage() { @@ -492,20 +496,20 @@ public void MapLayerMessage() t.Deserialize(map); - Assert.AreEqual(s.Flags, t.Flags); + Assert.Equal(s.Flags, t.Flags); for (int i = 0; i < s.LayerDataBlocks.Length; i++) { - Assert.AreEqual(s.LayerDataBlocks[i].ImageID, t.LayerDataBlocks[i].ImageID); - Assert.AreEqual(s.LayerDataBlocks[i].Top, t.LayerDataBlocks[i].Top); - Assert.AreEqual(s.LayerDataBlocks[i].Left, t.LayerDataBlocks[i].Left); - Assert.AreEqual(s.LayerDataBlocks[i].Right, t.LayerDataBlocks[i].Right); - Assert.AreEqual(s.LayerDataBlocks[i].Bottom, t.LayerDataBlocks[i].Bottom); + Assert.Equal(s.LayerDataBlocks[i].ImageID, t.LayerDataBlocks[i].ImageID); + Assert.Equal(s.LayerDataBlocks[i].Top, t.LayerDataBlocks[i].Top); + Assert.Equal(s.LayerDataBlocks[i].Left, t.LayerDataBlocks[i].Left); + Assert.Equal(s.LayerDataBlocks[i].Right, t.LayerDataBlocks[i].Right); + Assert.Equal(s.LayerDataBlocks[i].Bottom, t.LayerDataBlocks[i].Bottom); } } - [Test] // VARIANT A + [Fact] // VARIANT A public void ChatSessionRequestStartConference() { ChatSessionRequestStartConference s = new ChatSessionRequestStartConference(); @@ -519,15 +523,15 @@ public void ChatSessionRequestStartConference() ChatSessionRequestStartConference t = new ChatSessionRequestStartConference(); t.Deserialize(map); - Assert.AreEqual(s.SessionID, t.SessionID); - Assert.AreEqual(s.Method, t.Method); + Assert.Equal(s.SessionID, t.SessionID); + Assert.Equal(s.Method, t.Method); for (int i = 0; i < t.AgentsBlock.Length; i++) { - Assert.AreEqual(s.AgentsBlock[i], t.AgentsBlock[i]); + Assert.Equal(s.AgentsBlock[i], t.AgentsBlock[i]); } } - [Test] + [Fact] public void ChatSessionRequestMuteUpdate() { ChatSessionRequestMuteUpdate s = new ChatSessionRequestMuteUpdate(); @@ -541,14 +545,14 @@ public void ChatSessionRequestMuteUpdate() ChatSessionRequestMuteUpdate t = new ChatSessionRequestMuteUpdate(); t.Deserialize(map); - Assert.AreEqual(s.AgentID, t.AgentID); - Assert.AreEqual(s.Method, t.Method); - Assert.AreEqual(s.RequestKey, t.RequestKey); - Assert.AreEqual(s.RequestValue, t.RequestValue); - Assert.AreEqual(s.SessionID, t.SessionID); + Assert.Equal(s.AgentID, t.AgentID); + Assert.Equal(s.Method, t.Method); + Assert.Equal(s.RequestKey, t.RequestKey); + Assert.Equal(s.RequestValue, t.RequestValue); + Assert.Equal(s.SessionID, t.SessionID); } - [Test] + [Fact] public void ChatSessionAcceptInvitation() { ChatSessionAcceptInvitation s = new ChatSessionAcceptInvitation(); @@ -559,11 +563,11 @@ public void ChatSessionAcceptInvitation() ChatSessionAcceptInvitation t = new ChatSessionAcceptInvitation(); t.Deserialize(map); - Assert.AreEqual(s.Method, t.Method); - Assert.AreEqual(s.SessionID, t.SessionID); + Assert.Equal(s.Method, t.Method); + Assert.Equal(s.SessionID, t.SessionID); } - [Test] + [Fact] public void RequiredVoiceVersionMessage() { RequiredVoiceVersionMessage s = new RequiredVoiceVersionMessage(); @@ -576,12 +580,12 @@ public void RequiredVoiceVersionMessage() RequiredVoiceVersionMessage t = new RequiredVoiceVersionMessage(); t.Deserialize(map); - Assert.AreEqual(s.MajorVersion, t.MajorVersion); - Assert.AreEqual(s.MinorVersion, t.MinorVersion); - Assert.AreEqual(s.RegionName, t.RegionName); + Assert.Equal(s.MajorVersion, t.MajorVersion); + Assert.Equal(s.MinorVersion, t.MinorVersion); + Assert.Equal(s.RegionName, t.RegionName); } - [Test] + [Fact] public void CopyInventoryFromNotecardMessage() { CopyInventoryFromNotecardMessage s = new CopyInventoryFromNotecardMessage(); @@ -596,14 +600,14 @@ public void CopyInventoryFromNotecardMessage() CopyInventoryFromNotecardMessage t = new CopyInventoryFromNotecardMessage(); t.Deserialize(map); - Assert.AreEqual(s.CallbackID, t.CallbackID); - Assert.AreEqual(s.FolderID, t.FolderID); - Assert.AreEqual(s.ItemID, t.ItemID); - Assert.AreEqual(s.NotecardID, t.NotecardID); - Assert.AreEqual(s.ObjectID, t.ObjectID); + Assert.Equal(s.CallbackID, t.CallbackID); + Assert.Equal(s.FolderID, t.FolderID); + Assert.Equal(s.ItemID, t.ItemID); + Assert.Equal(s.NotecardID, t.NotecardID); + Assert.Equal(s.ObjectID, t.ObjectID); } - [Test] + [Fact] public void ProvisionVoiceAccountRequestMessage() { ProvisionVoiceAccountRequestMessage s = new ProvisionVoiceAccountRequestMessage(); @@ -615,11 +619,11 @@ public void ProvisionVoiceAccountRequestMessage() ProvisionVoiceAccountRequestMessage t = new ProvisionVoiceAccountRequestMessage(); t.Deserialize(map); - Assert.AreEqual(s.Password, t.Password); - Assert.AreEqual(s.Username, t.Username); + Assert.Equal(s.Password, t.Password); + Assert.Equal(s.Username, t.Username); } - [Test] + [Fact] public void UpdateAgentLanguageMessage() { UpdateAgentLanguageMessage s = new UpdateAgentLanguageMessage(); @@ -631,12 +635,12 @@ public void UpdateAgentLanguageMessage() UpdateAgentLanguageMessage t = new UpdateAgentLanguageMessage(); t.Deserialize(map); - Assert.AreEqual(s.Language, t.Language); - Assert.AreEqual(s.LanguagePublic, t.LanguagePublic); + Assert.Equal(s.Language, t.Language); + Assert.Equal(s.LanguagePublic, t.LanguagePublic); } - [Test] + [Fact] public void ParcelPropertiesMessage() { ParcelPropertiesMessage s = new ParcelPropertiesMessage(); @@ -701,64 +705,64 @@ public void ParcelPropertiesMessage() t.Deserialize(map); - Assert.AreEqual(s.AABBMax, t.AABBMax); - Assert.AreEqual(s.AABBMin, t.AABBMin); - Assert.AreEqual(s.Area, t.Area); - Assert.AreEqual(s.AuctionID, t.AuctionID); - Assert.AreEqual(s.AuthBuyerID, t.AuthBuyerID); - Assert.AreEqual(s.Bitmap, t.Bitmap); - Assert.AreEqual(s.Category, t.Category); - Assert.AreEqual(s.ClaimDate, t.ClaimDate); - Assert.AreEqual(s.ClaimPrice, t.ClaimPrice); - Assert.AreEqual(s.Desc, t.Desc); - Assert.AreEqual(s.GroupID, t.GroupID); - Assert.AreEqual(s.GroupPrims, t.GroupPrims); - Assert.AreEqual(s.IsGroupOwned, t.IsGroupOwned); - Assert.AreEqual(s.LandingType, t.LandingType); - Assert.AreEqual(s.LocalID, t.LocalID); - Assert.AreEqual(s.MaxPrims, t.MaxPrims); - Assert.AreEqual(s.MediaAutoScale, t.MediaAutoScale); - Assert.AreEqual(s.MediaDesc, t.MediaDesc); - Assert.AreEqual(s.MediaHeight, t.MediaHeight); - Assert.AreEqual(s.MediaID, t.MediaID); - Assert.AreEqual(s.MediaLoop, t.MediaLoop); - Assert.AreEqual(s.MediaType, t.MediaType); - Assert.AreEqual(s.MediaURL, t.MediaURL); - Assert.AreEqual(s.MediaWidth, t.MediaWidth); - Assert.AreEqual(s.MusicURL, t.MusicURL); - Assert.AreEqual(s.Name, t.Name); - Assert.AreEqual(s.ObscureMedia, t.ObscureMedia); - Assert.AreEqual(s.ObscureMusic, t.ObscureMusic); - Assert.AreEqual(s.OtherCleanTime, t.OtherCleanTime); - Assert.AreEqual(s.OtherCount, t.OtherCount); - Assert.AreEqual(s.OtherPrims, t.OtherPrims); - Assert.AreEqual(s.OwnerID, t.OwnerID); - Assert.AreEqual(s.OwnerPrims, t.OwnerPrims); - Assert.AreEqual(s.ParcelFlags, t.ParcelFlags); - Assert.AreEqual(s.ParcelPrimBonus, t.ParcelPrimBonus); - Assert.AreEqual(s.PassHours, t.PassHours); - Assert.AreEqual(s.PassPrice, t.PassPrice); - Assert.AreEqual(s.PublicCount, t.PublicCount); - Assert.AreEqual(s.RegionDenyAgeUnverified, t.RegionDenyAgeUnverified); - Assert.AreEqual(s.RegionDenyAnonymous, t.RegionDenyAnonymous); - Assert.AreEqual(s.RegionPushOverride, t.RegionPushOverride); - Assert.AreEqual(s.RentPrice, t.RentPrice); - Assert.AreEqual(s.RequestResult, t.RequestResult); - Assert.AreEqual(s.SalePrice, t.SalePrice); - Assert.AreEqual(s.SelectedPrims, t.SelectedPrims); - Assert.AreEqual(s.SelfCount, t.SelfCount); - Assert.AreEqual(s.SequenceID, t.SequenceID); - Assert.AreEqual(s.SimWideMaxPrims, t.SimWideMaxPrims); - Assert.AreEqual(s.SimWideTotalPrims, t.SimWideTotalPrims); - Assert.AreEqual(s.SnapSelection, t.SnapSelection); - Assert.AreEqual(s.SnapshotID, t.SnapshotID); - Assert.AreEqual(s.Status, t.Status); - Assert.AreEqual(s.TotalPrims, t.TotalPrims); - Assert.AreEqual(s.UserLocation, t.UserLocation); - Assert.AreEqual(s.UserLookAt, t.UserLookAt); + Assert.Equal(s.AABBMax, t.AABBMax); + Assert.Equal(s.AABBMin, t.AABBMin); + Assert.Equal(s.Area, t.Area); + Assert.Equal(s.AuctionID, t.AuctionID); + Assert.Equal(s.AuthBuyerID, t.AuthBuyerID); + Assert.Equal(s.Bitmap, t.Bitmap); + Assert.Equal(s.Category, t.Category); + Assert.Equal(s.ClaimDate, t.ClaimDate); + Assert.Equal(s.ClaimPrice, t.ClaimPrice); + Assert.Equal(s.Desc, t.Desc); + Assert.Equal(s.GroupID, t.GroupID); + Assert.Equal(s.GroupPrims, t.GroupPrims); + Assert.Equal(s.IsGroupOwned, t.IsGroupOwned); + Assert.Equal(s.LandingType, t.LandingType); + Assert.Equal(s.LocalID, t.LocalID); + Assert.Equal(s.MaxPrims, t.MaxPrims); + Assert.Equal(s.MediaAutoScale, t.MediaAutoScale); + Assert.Equal(s.MediaDesc, t.MediaDesc); + Assert.Equal(s.MediaHeight, t.MediaHeight); + Assert.Equal(s.MediaID, t.MediaID); + Assert.Equal(s.MediaLoop, t.MediaLoop); + Assert.Equal(s.MediaType, t.MediaType); + Assert.Equal(s.MediaURL, t.MediaURL); + Assert.Equal(s.MediaWidth, t.MediaWidth); + Assert.Equal(s.MusicURL, t.MusicURL); + Assert.Equal(s.Name, t.Name); + Assert.Equal(s.ObscureMedia, t.ObscureMedia); + Assert.Equal(s.ObscureMusic, t.ObscureMusic); + Assert.Equal(s.OtherCleanTime, t.OtherCleanTime); + Assert.Equal(s.OtherCount, t.OtherCount); + Assert.Equal(s.OtherPrims, t.OtherPrims); + Assert.Equal(s.OwnerID, t.OwnerID); + Assert.Equal(s.OwnerPrims, t.OwnerPrims); + Assert.Equal(s.ParcelFlags, t.ParcelFlags); + Assert.Equal(s.ParcelPrimBonus, t.ParcelPrimBonus); + Assert.Equal(s.PassHours, t.PassHours); + Assert.Equal(s.PassPrice, t.PassPrice); + Assert.Equal(s.PublicCount, t.PublicCount); + Assert.Equal(s.RegionDenyAgeUnverified, t.RegionDenyAgeUnverified); + Assert.Equal(s.RegionDenyAnonymous, t.RegionDenyAnonymous); + Assert.Equal(s.RegionPushOverride, t.RegionPushOverride); + Assert.Equal(s.RentPrice, t.RentPrice); + Assert.Equal(s.RequestResult, t.RequestResult); + Assert.Equal(s.SalePrice, t.SalePrice); + Assert.Equal(s.SelectedPrims, t.SelectedPrims); + Assert.Equal(s.SelfCount, t.SelfCount); + Assert.Equal(s.SequenceID, t.SequenceID); + Assert.Equal(s.SimWideMaxPrims, t.SimWideMaxPrims); + Assert.Equal(s.SimWideTotalPrims, t.SimWideTotalPrims); + Assert.Equal(s.SnapSelection, t.SnapSelection); + Assert.Equal(s.SnapshotID, t.SnapshotID); + Assert.Equal(s.Status, t.Status); + Assert.Equal(s.TotalPrims, t.TotalPrims); + Assert.Equal(s.UserLocation, t.UserLocation); + Assert.Equal(s.UserLookAt, t.UserLookAt); } - [Test] + [Fact] public void ParcelPropertiesUpdateMessage() { ParcelPropertiesUpdateMessage s = new ParcelPropertiesUpdateMessage(); @@ -794,33 +798,33 @@ public void ParcelPropertiesUpdateMessage() t.Deserialize(map); - Assert.AreEqual(s.AuthBuyerID, t.AuthBuyerID); - Assert.AreEqual(s.Category, t.Category); - Assert.AreEqual(s.Desc, t.Desc); - Assert.AreEqual(s.GroupID, t.GroupID); - Assert.AreEqual(s.Landing, t.Landing); - Assert.AreEqual(s.LocalID, t.LocalID); - Assert.AreEqual(s.MediaAutoScale, t.MediaAutoScale); - Assert.AreEqual(s.MediaDesc, t.MediaDesc); - Assert.AreEqual(s.MediaHeight, t.MediaHeight); - Assert.AreEqual(s.MediaID, t.MediaID); - Assert.AreEqual(s.MediaLoop, t.MediaLoop); - Assert.AreEqual(s.MediaType, t.MediaType); - Assert.AreEqual(s.MediaURL, t.MediaURL); - Assert.AreEqual(s.MediaWidth, t.MediaWidth); - Assert.AreEqual(s.MusicURL, t.MusicURL); - Assert.AreEqual(s.Name, t.Name); - Assert.AreEqual(s.ObscureMedia, t.ObscureMedia); - Assert.AreEqual(s.ObscureMusic, t.ObscureMusic); - Assert.AreEqual(s.ParcelFlags, t.ParcelFlags); - Assert.AreEqual(s.PassHours, t.PassHours); - Assert.AreEqual(s.PassPrice, t.PassPrice); - Assert.AreEqual(s.SalePrice, t.SalePrice); - Assert.AreEqual(s.SnapshotID, t.SnapshotID); - Assert.AreEqual(s.UserLocation, t.UserLocation); - Assert.AreEqual(s.UserLookAt, t.UserLookAt); + Assert.Equal(s.AuthBuyerID, t.AuthBuyerID); + Assert.Equal(s.Category, t.Category); + Assert.Equal(s.Desc, t.Desc); + Assert.Equal(s.GroupID, t.GroupID); + Assert.Equal(s.Landing, t.Landing); + Assert.Equal(s.LocalID, t.LocalID); + Assert.Equal(s.MediaAutoScale, t.MediaAutoScale); + Assert.Equal(s.MediaDesc, t.MediaDesc); + Assert.Equal(s.MediaHeight, t.MediaHeight); + Assert.Equal(s.MediaID, t.MediaID); + Assert.Equal(s.MediaLoop, t.MediaLoop); + Assert.Equal(s.MediaType, t.MediaType); + Assert.Equal(s.MediaURL, t.MediaURL); + Assert.Equal(s.MediaWidth, t.MediaWidth); + Assert.Equal(s.MusicURL, t.MusicURL); + Assert.Equal(s.Name, t.Name); + Assert.Equal(s.ObscureMedia, t.ObscureMedia); + Assert.Equal(s.ObscureMusic, t.ObscureMusic); + Assert.Equal(s.ParcelFlags, t.ParcelFlags); + Assert.Equal(s.PassHours, t.PassHours); + Assert.Equal(s.PassPrice, t.PassPrice); + Assert.Equal(s.SalePrice, t.SalePrice); + Assert.Equal(s.SnapshotID, t.SnapshotID); + Assert.Equal(s.UserLocation, t.UserLocation); + Assert.Equal(s.UserLookAt, t.UserLookAt); } - [Test] + [Fact] public void EnableSimulatorMessage() { EnableSimulatorMessage s = new EnableSimulatorMessage(); @@ -845,13 +849,13 @@ public void EnableSimulatorMessage() for (int i = 0; i < t.Simulators.Length; i++) { - Assert.AreEqual(s.Simulators[i].IP, t.Simulators[i].IP); - Assert.AreEqual(s.Simulators[i].Port, t.Simulators[i].Port); - Assert.AreEqual(s.Simulators[i].RegionHandle, t.Simulators[i].RegionHandle); + Assert.Equal(s.Simulators[i].IP, t.Simulators[i].IP); + Assert.Equal(s.Simulators[i].Port, t.Simulators[i].Port); + Assert.Equal(s.Simulators[i].RegionHandle, t.Simulators[i].RegionHandle); } } - [Test] + [Fact] public void RemoteParcelRequestReply() { RemoteParcelRequestReply s = new RemoteParcelRequestReply(); @@ -861,10 +865,10 @@ public void RemoteParcelRequestReply() RemoteParcelRequestReply t = new RemoteParcelRequestReply(); t.Deserialize(map); - Assert.AreEqual(s.ParcelID, t.ParcelID); + Assert.Equal(s.ParcelID, t.ParcelID); } - [Test] + [Fact] public void UpdateScriptTaskMessage() { UpdateScriptTaskUpdateMessage s = new UpdateScriptTaskUpdateMessage(); @@ -877,13 +881,13 @@ public void UpdateScriptTaskMessage() UpdateScriptTaskUpdateMessage t = new UpdateScriptTaskUpdateMessage(); t.Deserialize(map); - Assert.AreEqual(s.ItemID, t.ItemID); - Assert.AreEqual(s.ScriptRunning, t.ScriptRunning); - Assert.AreEqual(s.Target, t.Target); - Assert.AreEqual(s.TaskID, t.TaskID); + Assert.Equal(s.ItemID, t.ItemID); + Assert.Equal(s.ScriptRunning, t.ScriptRunning); + Assert.Equal(s.Target, t.Target); + Assert.Equal(s.TaskID, t.TaskID); } - [Test] + [Fact] public void UpdateScriptAgentMessage() { UpdateScriptAgentRequestMessage s = new UpdateScriptAgentRequestMessage(); @@ -895,11 +899,11 @@ public void UpdateScriptAgentMessage() UpdateScriptAgentRequestMessage t = new UpdateScriptAgentRequestMessage(); t.Deserialize(map); - Assert.AreEqual(s.ItemID, t.ItemID); - Assert.AreEqual(s.Target, t.Target); + Assert.Equal(s.ItemID, t.ItemID); + Assert.Equal(s.Target, t.Target); } - [Test] + [Fact] public void SendPostcardMessage() { SendPostcardMessage s = new SendPostcardMessage(); @@ -915,15 +919,15 @@ public void SendPostcardMessage() SendPostcardMessage t = new SendPostcardMessage(); t.Deserialize(map); - Assert.AreEqual(s.FromEmail, t.FromEmail); - Assert.AreEqual(s.FromName, t.FromName); - Assert.AreEqual(s.GlobalPosition, t.GlobalPosition); - Assert.AreEqual(s.Message, t.Message); - Assert.AreEqual(s.Subject, t.Subject); - Assert.AreEqual(s.ToEmail, t.ToEmail); + Assert.Equal(s.FromEmail, t.FromEmail); + Assert.Equal(s.FromName, t.FromName); + Assert.Equal(s.GlobalPosition, t.GlobalPosition); + Assert.Equal(s.Message, t.Message); + Assert.Equal(s.Subject, t.Subject); + Assert.Equal(s.ToEmail, t.ToEmail); } - [Test] + [Fact] public void UpdateNotecardAgentInventoryMessage() { UpdateAgentInventoryRequestMessage s = new UpdateAgentInventoryRequestMessage(); @@ -934,10 +938,10 @@ public void UpdateNotecardAgentInventoryMessage() UpdateAgentInventoryRequestMessage t = new UpdateAgentInventoryRequestMessage(); t.Deserialize(map); - Assert.AreEqual(s.ItemID, t.ItemID); + Assert.Equal(s.ItemID, t.ItemID); } - [Test] + [Fact] public void LandStatReplyMessage() { LandStatReplyMessage s = new LandStatReplyMessage(); @@ -973,24 +977,24 @@ public void LandStatReplyMessage() LandStatReplyMessage t = new LandStatReplyMessage(); t.Deserialize(map); - Assert.AreEqual(s.ReportType, t.ReportType); - Assert.AreEqual(s.RequestFlags, t.RequestFlags); - Assert.AreEqual(s.TotalObjectCount, t.TotalObjectCount); + Assert.Equal(s.ReportType, t.ReportType); + Assert.Equal(s.RequestFlags, t.RequestFlags); + Assert.Equal(s.TotalObjectCount, t.TotalObjectCount); for (int i = 0; i < t.ReportDataBlocks.Length; i++) { - Assert.AreEqual(s.ReportDataBlocks[i].Location, t.ReportDataBlocks[i].Location); - Assert.AreEqual(s.ReportDataBlocks[i].MonoScore, t.ReportDataBlocks[i].MonoScore); - Assert.AreEqual(s.ReportDataBlocks[i].OwnerName, t.ReportDataBlocks[i].OwnerName); - Assert.AreEqual(s.ReportDataBlocks[i].Score, t.ReportDataBlocks[i].Score); - Assert.AreEqual(s.ReportDataBlocks[i].TaskID, t.ReportDataBlocks[i].TaskID); - Assert.AreEqual(s.ReportDataBlocks[i].TaskLocalID, t.ReportDataBlocks[i].TaskLocalID); - Assert.AreEqual(s.ReportDataBlocks[i].TaskName, t.ReportDataBlocks[i].TaskName); - Assert.AreEqual(s.ReportDataBlocks[i].TimeStamp, t.ReportDataBlocks[i].TimeStamp); + Assert.Equal(s.ReportDataBlocks[i].Location, t.ReportDataBlocks[i].Location); + Assert.Equal(s.ReportDataBlocks[i].MonoScore, t.ReportDataBlocks[i].MonoScore); + Assert.Equal(s.ReportDataBlocks[i].OwnerName, t.ReportDataBlocks[i].OwnerName); + Assert.Equal(s.ReportDataBlocks[i].Score, t.ReportDataBlocks[i].Score); + Assert.Equal(s.ReportDataBlocks[i].TaskID, t.ReportDataBlocks[i].TaskID); + Assert.Equal(s.ReportDataBlocks[i].TaskLocalID, t.ReportDataBlocks[i].TaskLocalID); + Assert.Equal(s.ReportDataBlocks[i].TaskName, t.ReportDataBlocks[i].TaskName); + Assert.Equal(s.ReportDataBlocks[i].TimeStamp, t.ReportDataBlocks[i].TimeStamp); } } - [Test] + [Fact] public void TelportFailedMessage() { TeleportFailedMessage s = new TeleportFailedMessage(); @@ -1004,14 +1008,14 @@ public void TelportFailedMessage() TeleportFailedMessage t = new TeleportFailedMessage(); t.Deserialize(map); - Assert.AreEqual(s.AgentID, t.AgentID); - Assert.AreEqual(s.ExtraParams, t.ExtraParams); - Assert.AreEqual(s.MessageKey, t.MessageKey); - Assert.AreEqual(s.Reason, t.Reason); + Assert.Equal(s.AgentID, t.AgentID); + Assert.Equal(s.ExtraParams, t.ExtraParams); + Assert.Equal(s.MessageKey, t.MessageKey); + Assert.Equal(s.Reason, t.Reason); } - [Test] + [Fact] public void UpdateAgentInformationMessage() { UpdateAgentInformationMessage s = new UpdateAgentInformationMessage(); @@ -1021,10 +1025,10 @@ public void UpdateAgentInformationMessage() UpdateAgentInformationMessage t = new UpdateAgentInformationMessage(); t.Deserialize(map); - Assert.AreEqual(s.MaxAccess, t.MaxAccess); + Assert.Equal(s.MaxAccess, t.MaxAccess); } - [Test] + [Fact] public void PlacesReplyMessage() { PlacesReplyMessage s = new PlacesReplyMessage(); @@ -1074,30 +1078,30 @@ public void PlacesReplyMessage() PlacesReplyMessage t = new PlacesReplyMessage(); t.Deserialize(map); - Assert.AreEqual(s.AgentID, t.AgentID); - Assert.AreEqual(s.TransactionID, t.TransactionID); - Assert.AreEqual(s.QueryID, t.QueryID); + Assert.Equal(s.AgentID, t.AgentID); + Assert.Equal(s.TransactionID, t.TransactionID); + Assert.Equal(s.QueryID, t.QueryID); for (int i = 0; i < s.QueryDataBlocks.Length; i++) { - Assert.AreEqual(s.QueryDataBlocks[i].ActualArea, t.QueryDataBlocks[i].ActualArea); - Assert.AreEqual(s.QueryDataBlocks[i].BillableArea, t.QueryDataBlocks[i].BillableArea); - Assert.AreEqual(s.QueryDataBlocks[i].Description, t.QueryDataBlocks[i].Description); - Assert.AreEqual(s.QueryDataBlocks[i].Dwell, t.QueryDataBlocks[i].Dwell); - Assert.AreEqual(s.QueryDataBlocks[i].Flags, t.QueryDataBlocks[i].Flags); - Assert.AreEqual(s.QueryDataBlocks[i].GlobalX, t.QueryDataBlocks[i].GlobalX); - Assert.AreEqual(s.QueryDataBlocks[i].GlobalY, t.QueryDataBlocks[i].GlobalY); - Assert.AreEqual(s.QueryDataBlocks[i].GlobalZ, t.QueryDataBlocks[i].GlobalZ); - Assert.AreEqual(s.QueryDataBlocks[i].Name, t.QueryDataBlocks[i].Name); - Assert.AreEqual(s.QueryDataBlocks[i].OwnerID, t.QueryDataBlocks[i].OwnerID); - Assert.AreEqual(s.QueryDataBlocks[i].Price, t.QueryDataBlocks[i].Price); - Assert.AreEqual(s.QueryDataBlocks[i].ProductSku, t.QueryDataBlocks[i].ProductSku); - Assert.AreEqual(s.QueryDataBlocks[i].SimName, t.QueryDataBlocks[i].SimName); - Assert.AreEqual(s.QueryDataBlocks[i].SnapShotID, t.QueryDataBlocks[i].SnapShotID); + Assert.Equal(s.QueryDataBlocks[i].ActualArea, t.QueryDataBlocks[i].ActualArea); + Assert.Equal(s.QueryDataBlocks[i].BillableArea, t.QueryDataBlocks[i].BillableArea); + Assert.Equal(s.QueryDataBlocks[i].Description, t.QueryDataBlocks[i].Description); + Assert.Equal(s.QueryDataBlocks[i].Dwell, t.QueryDataBlocks[i].Dwell); + Assert.Equal(s.QueryDataBlocks[i].Flags, t.QueryDataBlocks[i].Flags); + Assert.Equal(s.QueryDataBlocks[i].GlobalX, t.QueryDataBlocks[i].GlobalX); + Assert.Equal(s.QueryDataBlocks[i].GlobalY, t.QueryDataBlocks[i].GlobalY); + Assert.Equal(s.QueryDataBlocks[i].GlobalZ, t.QueryDataBlocks[i].GlobalZ); + Assert.Equal(s.QueryDataBlocks[i].Name, t.QueryDataBlocks[i].Name); + Assert.Equal(s.QueryDataBlocks[i].OwnerID, t.QueryDataBlocks[i].OwnerID); + Assert.Equal(s.QueryDataBlocks[i].Price, t.QueryDataBlocks[i].Price); + Assert.Equal(s.QueryDataBlocks[i].ProductSku, t.QueryDataBlocks[i].ProductSku); + Assert.Equal(s.QueryDataBlocks[i].SimName, t.QueryDataBlocks[i].SimName); + Assert.Equal(s.QueryDataBlocks[i].SnapShotID, t.QueryDataBlocks[i].SnapShotID); } } - [Test] + [Fact] public void DirLandReplyMessage() { DirLandReplyMessage s = new DirLandReplyMessage(); @@ -1132,26 +1136,26 @@ public void DirLandReplyMessage() DirLandReplyMessage t = new DirLandReplyMessage(); t.Deserialize(map); - Assert.AreEqual(s.AgentID, t.AgentID); - Assert.AreEqual(s.QueryID, t.QueryID); + Assert.Equal(s.AgentID, t.AgentID); + Assert.Equal(s.QueryID, t.QueryID); for (int i = 0; i < s.QueryReplies.Length; i++) { - Assert.AreEqual(s.QueryReplies[i].ActualArea, t.QueryReplies[i].ActualArea); - Assert.AreEqual(s.QueryReplies[i].Auction, t.QueryReplies[i].Auction); - Assert.AreEqual(s.QueryReplies[i].ForSale, t.QueryReplies[i].ForSale); - Assert.AreEqual(s.QueryReplies[i].Name, t.QueryReplies[i].Name); - Assert.AreEqual(s.QueryReplies[i].ProductSku, t.QueryReplies[i].ProductSku); - Assert.AreEqual(s.QueryReplies[i].ParcelID, t.QueryReplies[i].ParcelID); - Assert.AreEqual(s.QueryReplies[i].SalePrice, t.QueryReplies[i].SalePrice); + Assert.Equal(s.QueryReplies[i].ActualArea, t.QueryReplies[i].ActualArea); + Assert.Equal(s.QueryReplies[i].Auction, t.QueryReplies[i].Auction); + Assert.Equal(s.QueryReplies[i].ForSale, t.QueryReplies[i].ForSale); + Assert.Equal(s.QueryReplies[i].Name, t.QueryReplies[i].Name); + Assert.Equal(s.QueryReplies[i].ProductSku, t.QueryReplies[i].ProductSku); + Assert.Equal(s.QueryReplies[i].ParcelID, t.QueryReplies[i].ParcelID); + Assert.Equal(s.QueryReplies[i].SalePrice, t.QueryReplies[i].SalePrice); } } #region Performance Testing private const int TEST_ITER = 100000; - [Test] - [Category("Benchmark")] + [Fact] + [Trait("Category", "Benchmark")] public void ReflectionPerformanceRemoteParcelResponse() { DateTime messageTestTime = DateTime.UtcNow; @@ -1164,12 +1168,12 @@ public void ReflectionPerformanceRemoteParcelResponse() RemoteParcelRequestReply t = new RemoteParcelRequestReply(); t.Deserialize(map); - Assert.AreEqual(s.ParcelID, t.ParcelID); + Assert.Equal(s.ParcelID, t.ParcelID); } TimeSpan duration = DateTime.UtcNow - messageTestTime; Console.WriteLine("RemoteParcelRequestReply: OMV Message System Serialization/Deserialization Passes: {0} Total time: {1}", TEST_ITER, duration); - BinaryFormatter formatter = new BinaryFormatter(); + //BinaryFormatter formatter = new BinaryFormatter(); DateTime xmlTestTime = DateTime.UtcNow; for (int x = 0; x < TEST_ITER; x++) { @@ -1177,21 +1181,26 @@ public void ReflectionPerformanceRemoteParcelResponse() s.ParcelID = UUID.Random(); MemoryStream stream = new MemoryStream(); + byte[] llsdPayload = OSDParser.SerializeLLSDBinary(s.Serialize(), false); - formatter.Serialize(stream, s); + MessagePackSerializer.Serialize(stream, llsdPayload, BenchmarkMessagePackOptions); + //formatter.Serialize(stream, s); stream.Seek(0, SeekOrigin.Begin); - RemoteParcelRequestReply t = (RemoteParcelRequestReply)formatter.Deserialize(stream); + //RemoteParcelRequestReply t = (RemoteParcelRequestReply)formatter.Deserialize(stream); + byte[] unpackedLlsd = MessagePackSerializer.Deserialize(stream, BenchmarkMessagePackOptions); + RemoteParcelRequestReply t = new RemoteParcelRequestReply(); + t.Deserialize((OSDMap)OSDParser.DeserializeLLSDBinary(unpackedLlsd)); - Assert.AreEqual(s.ParcelID, t.ParcelID); + Assert.Equal(s.ParcelID, t.ParcelID); } TimeSpan durationxml = DateTime.UtcNow - xmlTestTime; - Console.WriteLine("RemoteParcelRequestReply: .NET BinarySerialization/Deserialization Passes: {0} Total time: {1}", TEST_ITER, durationxml); + Console.WriteLine("RemoteParcelRequestReply: MessagePack(LLSD binary payload) Serialization/Deserialization Passes: {0} Total time: {1}", TEST_ITER, durationxml); } - [Test] - [Category("Benchmark")] + [Fact] + [Trait("Category", "Benchmark")] public void ReflectionPerformanceDirLandReply() { @@ -1229,24 +1238,23 @@ public void ReflectionPerformanceDirLandReply() DirLandReplyMessage t = new DirLandReplyMessage(); t.Deserialize(map); - Assert.AreEqual(s.AgentID, t.AgentID); - Assert.AreEqual(s.QueryID, t.QueryID); + Assert.Equal(s.AgentID, t.AgentID); + Assert.Equal(s.QueryID, t.QueryID); for (int i = 0; i < s.QueryReplies.Length; i++) { - Assert.AreEqual(s.QueryReplies[i].ActualArea, t.QueryReplies[i].ActualArea); - Assert.AreEqual(s.QueryReplies[i].Auction, t.QueryReplies[i].Auction); - Assert.AreEqual(s.QueryReplies[i].ForSale, t.QueryReplies[i].ForSale); - Assert.AreEqual(s.QueryReplies[i].Name, t.QueryReplies[i].Name); - Assert.AreEqual(s.QueryReplies[i].ProductSku, t.QueryReplies[i].ProductSku); - Assert.AreEqual(s.QueryReplies[i].ParcelID, t.QueryReplies[i].ParcelID); - Assert.AreEqual(s.QueryReplies[i].SalePrice, t.QueryReplies[i].SalePrice); + Assert.Equal(s.QueryReplies[i].ActualArea, t.QueryReplies[i].ActualArea); + Assert.Equal(s.QueryReplies[i].Auction, t.QueryReplies[i].Auction); + Assert.Equal(s.QueryReplies[i].ForSale, t.QueryReplies[i].ForSale); + Assert.Equal(s.QueryReplies[i].Name, t.QueryReplies[i].Name); + Assert.Equal(s.QueryReplies[i].ProductSku, t.QueryReplies[i].ProductSku); + Assert.Equal(s.QueryReplies[i].ParcelID, t.QueryReplies[i].ParcelID); + Assert.Equal(s.QueryReplies[i].SalePrice, t.QueryReplies[i].SalePrice); } } TimeSpan duration = DateTime.UtcNow - messageTestTime; Console.WriteLine("DirLandReplyMessage: OMV Message System Serialization/Deserialization Passes: {0} Total time: {1}", TEST_ITER, duration); - BinaryFormatter formatter = new BinaryFormatter(); DateTime xmlTestTime = DateTime.UtcNow; for (int x = 0; x < TEST_ITER; x++) { @@ -1278,32 +1286,37 @@ public void ReflectionPerformanceDirLandReply() s.QueryReplies[1] = q2; MemoryStream stream = new MemoryStream(); + byte[] llsdPayload = OSDParser.SerializeLLSDBinary(s.Serialize(), false); - formatter.Serialize(stream, s); + //formatter.Serialize(stream, s); + MessagePackSerializer.Serialize(stream, llsdPayload, BenchmarkMessagePackOptions); stream.Seek(0, SeekOrigin.Begin); - DirLandReplyMessage t = (DirLandReplyMessage)formatter.Deserialize(stream); + //DirLandReplyMessage t = (DirLandReplyMessage)formatter.Deserialize(stream); + byte[] unpackedLlsd = MessagePackSerializer.Deserialize(stream, BenchmarkMessagePackOptions); + DirLandReplyMessage t = new DirLandReplyMessage(); + t.Deserialize((OSDMap)OSDParser.DeserializeLLSDBinary(unpackedLlsd)); - Assert.AreEqual(s.AgentID, t.AgentID); - Assert.AreEqual(s.QueryID, t.QueryID); + Assert.Equal(s.AgentID, t.AgentID); + Assert.Equal(s.QueryID, t.QueryID); for (int i = 0; i < s.QueryReplies.Length; i++) { - Assert.AreEqual(s.QueryReplies[i].ActualArea, t.QueryReplies[i].ActualArea); - Assert.AreEqual(s.QueryReplies[i].Auction, t.QueryReplies[i].Auction); - Assert.AreEqual(s.QueryReplies[i].ForSale, t.QueryReplies[i].ForSale); - Assert.AreEqual(s.QueryReplies[i].Name, t.QueryReplies[i].Name); - Assert.AreEqual(s.QueryReplies[i].ProductSku, t.QueryReplies[i].ProductSku); - Assert.AreEqual(s.QueryReplies[i].ParcelID, t.QueryReplies[i].ParcelID); - Assert.AreEqual(s.QueryReplies[i].SalePrice, t.QueryReplies[i].SalePrice); + Assert.Equal(s.QueryReplies[i].ActualArea, t.QueryReplies[i].ActualArea); + Assert.Equal(s.QueryReplies[i].Auction, t.QueryReplies[i].Auction); + Assert.Equal(s.QueryReplies[i].ForSale, t.QueryReplies[i].ForSale); + Assert.Equal(s.QueryReplies[i].Name, t.QueryReplies[i].Name); + Assert.Equal(s.QueryReplies[i].ProductSku, t.QueryReplies[i].ProductSku); + Assert.Equal(s.QueryReplies[i].ParcelID, t.QueryReplies[i].ParcelID); + Assert.Equal(s.QueryReplies[i].SalePrice, t.QueryReplies[i].SalePrice); } } TimeSpan durationxml = DateTime.UtcNow - xmlTestTime; - Console.WriteLine("DirLandReplyMessage: .NET BinarySerialization/Deserialization Passes: {0} Total time: {1}", TEST_ITER, durationxml); + Console.WriteLine("DirLandReplyMessage: MessagePack(LLSD binary payload) Serialization/Deserialization Passes: {0} Total time: {1}", TEST_ITER, durationxml); } - [Test] - [Category("Benchmark")] + [Fact] + [Trait("Category", "Benchmark")] public void ReflectionPerformanceDirLandReply2() { XmlSerializer xmlSerializer = new XmlSerializer(typeof(DirLandReplyMessage)); @@ -1362,8 +1375,8 @@ public void ReflectionPerformanceDirLandReply2() Console.WriteLine(".NET BinarySerialization/Deserialization Passes: {0} Total time: {1}", TEST_ITER, timer.Elapsed.TotalSeconds); } - [Test] - [Category("Benchmark")] + [Fact] + [Trait("Category", "Benchmark")] public void ReflectionPerformanceParcelProperties() { DateTime messageTestTime = DateTime.UtcNow; @@ -1431,67 +1444,65 @@ public void ReflectionPerformanceParcelProperties() t.Deserialize(map); - Assert.AreEqual(s.AABBMax, t.AABBMax); - Assert.AreEqual(s.AABBMin, t.AABBMin); - Assert.AreEqual(s.Area, t.Area); - Assert.AreEqual(s.AuctionID, t.AuctionID); - Assert.AreEqual(s.AuthBuyerID, t.AuthBuyerID); - Assert.AreEqual(s.Bitmap, t.Bitmap); - Assert.AreEqual(s.Category, t.Category); - Assert.AreEqual(s.ClaimDate, t.ClaimDate); - Assert.AreEqual(s.ClaimPrice, t.ClaimPrice); - Assert.AreEqual(s.Desc, t.Desc); - Assert.AreEqual(s.GroupID, t.GroupID); - Assert.AreEqual(s.GroupPrims, t.GroupPrims); - Assert.AreEqual(s.IsGroupOwned, t.IsGroupOwned); - Assert.AreEqual(s.LandingType, t.LandingType); - Assert.AreEqual(s.LocalID, t.LocalID); - Assert.AreEqual(s.MaxPrims, t.MaxPrims); - Assert.AreEqual(s.MediaAutoScale, t.MediaAutoScale); - Assert.AreEqual(s.MediaDesc, t.MediaDesc); - Assert.AreEqual(s.MediaHeight, t.MediaHeight); - Assert.AreEqual(s.MediaID, t.MediaID); - Assert.AreEqual(s.MediaLoop, t.MediaLoop); - Assert.AreEqual(s.MediaType, t.MediaType); - Assert.AreEqual(s.MediaURL, t.MediaURL); - Assert.AreEqual(s.MediaWidth, t.MediaWidth); - Assert.AreEqual(s.MusicURL, t.MusicURL); - Assert.AreEqual(s.Name, t.Name); - Assert.AreEqual(s.ObscureMedia, t.ObscureMedia); - Assert.AreEqual(s.ObscureMusic, t.ObscureMusic); - Assert.AreEqual(s.OtherCleanTime, t.OtherCleanTime); - Assert.AreEqual(s.OtherCount, t.OtherCount); - Assert.AreEqual(s.OtherPrims, t.OtherPrims); - Assert.AreEqual(s.OwnerID, t.OwnerID); - Assert.AreEqual(s.OwnerPrims, t.OwnerPrims); - Assert.AreEqual(s.ParcelFlags, t.ParcelFlags); - Assert.AreEqual(s.ParcelPrimBonus, t.ParcelPrimBonus); - Assert.AreEqual(s.PassHours, t.PassHours); - Assert.AreEqual(s.PassPrice, t.PassPrice); - Assert.AreEqual(s.PublicCount, t.PublicCount); - Assert.AreEqual(s.RegionDenyAgeUnverified, t.RegionDenyAgeUnverified); - Assert.AreEqual(s.RegionDenyAnonymous, t.RegionDenyAnonymous); - Assert.AreEqual(s.RegionPushOverride, t.RegionPushOverride); - Assert.AreEqual(s.RentPrice, t.RentPrice); - Assert.AreEqual(s.RequestResult, t.RequestResult); - Assert.AreEqual(s.SalePrice, t.SalePrice); - Assert.AreEqual(s.SelectedPrims, t.SelectedPrims); - Assert.AreEqual(s.SelfCount, t.SelfCount); - Assert.AreEqual(s.SequenceID, t.SequenceID); - Assert.AreEqual(s.SimWideMaxPrims, t.SimWideMaxPrims); - Assert.AreEqual(s.SimWideTotalPrims, t.SimWideTotalPrims); - Assert.AreEqual(s.SnapSelection, t.SnapSelection); - Assert.AreEqual(s.SnapshotID, t.SnapshotID); - Assert.AreEqual(s.Status, t.Status); - Assert.AreEqual(s.TotalPrims, t.TotalPrims); - Assert.AreEqual(s.UserLocation, t.UserLocation); - Assert.AreEqual(s.UserLookAt, t.UserLookAt); + Assert.Equal(s.AABBMax, t.AABBMax); + Assert.Equal(s.AABBMin, t.AABBMin); + Assert.Equal(s.Area, t.Area); + Assert.Equal(s.AuctionID, t.AuctionID); + Assert.Equal(s.AuthBuyerID, t.AuthBuyerID); + Assert.Equal(s.Bitmap, t.Bitmap); + Assert.Equal(s.Category, t.Category); + Assert.Equal(s.ClaimDate, t.ClaimDate); + Assert.Equal(s.ClaimPrice, t.ClaimPrice); + Assert.Equal(s.Desc, t.Desc); + Assert.Equal(s.GroupID, t.GroupID); + Assert.Equal(s.GroupPrims, t.GroupPrims); + Assert.Equal(s.IsGroupOwned, t.IsGroupOwned); + Assert.Equal(s.LandingType, t.LandingType); + Assert.Equal(s.LocalID, t.LocalID); + Assert.Equal(s.MaxPrims, t.MaxPrims); + Assert.Equal(s.MediaAutoScale, t.MediaAutoScale); + Assert.Equal(s.MediaDesc, t.MediaDesc); + Assert.Equal(s.MediaHeight, t.MediaHeight); + Assert.Equal(s.MediaID, t.MediaID); + Assert.Equal(s.MediaLoop, t.MediaLoop); + Assert.Equal(s.MediaType, t.MediaType); + Assert.Equal(s.MediaURL, t.MediaURL); + Assert.Equal(s.MediaWidth, t.MediaWidth); + Assert.Equal(s.MusicURL, t.MusicURL); + Assert.Equal(s.Name, t.Name); + Assert.Equal(s.ObscureMedia, t.ObscureMedia); + Assert.Equal(s.ObscureMusic, t.ObscureMusic); + Assert.Equal(s.OtherCleanTime, t.OtherCleanTime); + Assert.Equal(s.OtherCount, t.OtherCount); + Assert.Equal(s.OtherPrims, t.OtherPrims); + Assert.Equal(s.OwnerID, t.OwnerID); + Assert.Equal(s.OwnerPrims, t.OwnerPrims); + Assert.Equal(s.ParcelFlags, t.ParcelFlags); + Assert.Equal(s.ParcelPrimBonus, t.ParcelPrimBonus); + Assert.Equal(s.PassHours, t.PassHours); + Assert.Equal(s.PassPrice, t.PassPrice); + Assert.Equal(s.PublicCount, t.PublicCount); + Assert.Equal(s.RegionDenyAgeUnverified, t.RegionDenyAgeUnverified); + Assert.Equal(s.RegionDenyAnonymous, t.RegionDenyAnonymous); + Assert.Equal(s.RegionPushOverride, t.RegionPushOverride); + Assert.Equal(s.RentPrice, t.RentPrice); + Assert.Equal(s.RequestResult, t.RequestResult); + Assert.Equal(s.SalePrice, t.SalePrice); + Assert.Equal(s.SelectedPrims, t.SelectedPrims); + Assert.Equal(s.SelfCount, t.SelfCount); + Assert.Equal(s.SequenceID, t.SequenceID); + Assert.Equal(s.SimWideMaxPrims, t.SimWideMaxPrims); + Assert.Equal(s.SimWideTotalPrims, t.SimWideTotalPrims); + Assert.Equal(s.SnapSelection, t.SnapSelection); + Assert.Equal(s.SnapshotID, t.SnapshotID); + Assert.Equal(s.Status, t.Status); + Assert.Equal(s.TotalPrims, t.TotalPrims); + Assert.Equal(s.UserLocation, t.UserLocation); + Assert.Equal(s.UserLookAt, t.UserLookAt); } TimeSpan duration = DateTime.UtcNow - messageTestTime; Console.WriteLine("ParcelPropertiesMessage: OMV Message System Serialization/Deserialization Passes: {0} Total time: {1}", TEST_ITER, duration); - BinaryFormatter formatter = new BinaryFormatter(); - DateTime xmlTestTime = DateTime.UtcNow; for (int x = 0; x < TEST_ITER; x++) { @@ -1554,71 +1565,76 @@ public void ReflectionPerformanceParcelProperties() s.UserLookAt = Vector3.Parse("<5,4,3>"); MemoryStream stream = new MemoryStream(); + byte[] llsdPayload = OSDParser.SerializeLLSDBinary(s.Serialize(), false); - formatter.Serialize(stream, s); + //formatter.Serialize(stream, s); + MessagePackSerializer.Serialize(stream, llsdPayload, BenchmarkMessagePackOptions); stream.Seek(0, SeekOrigin.Begin); - ParcelPropertiesMessage t = (ParcelPropertiesMessage)formatter.Deserialize(stream); - - Assert.AreEqual(s.AABBMax, t.AABBMax); - Assert.AreEqual(s.AABBMin, t.AABBMin); - Assert.AreEqual(s.Area, t.Area); - Assert.AreEqual(s.AuctionID, t.AuctionID); - Assert.AreEqual(s.AuthBuyerID, t.AuthBuyerID); - Assert.AreEqual(s.Bitmap, t.Bitmap); - Assert.AreEqual(s.Category, t.Category); - Assert.AreEqual(s.ClaimDate, t.ClaimDate); - Assert.AreEqual(s.ClaimPrice, t.ClaimPrice); - Assert.AreEqual(s.Desc, t.Desc); - Assert.AreEqual(s.GroupID, t.GroupID); - Assert.AreEqual(s.GroupPrims, t.GroupPrims); - Assert.AreEqual(s.IsGroupOwned, t.IsGroupOwned); - Assert.AreEqual(s.LandingType, t.LandingType); - Assert.AreEqual(s.LocalID, t.LocalID); - Assert.AreEqual(s.MaxPrims, t.MaxPrims); - Assert.AreEqual(s.MediaAutoScale, t.MediaAutoScale); - Assert.AreEqual(s.MediaDesc, t.MediaDesc); - Assert.AreEqual(s.MediaHeight, t.MediaHeight); - Assert.AreEqual(s.MediaID, t.MediaID); - Assert.AreEqual(s.MediaLoop, t.MediaLoop); - Assert.AreEqual(s.MediaType, t.MediaType); - Assert.AreEqual(s.MediaURL, t.MediaURL); - Assert.AreEqual(s.MediaWidth, t.MediaWidth); - Assert.AreEqual(s.MusicURL, t.MusicURL); - Assert.AreEqual(s.Name, t.Name); - Assert.AreEqual(s.ObscureMedia, t.ObscureMedia); - Assert.AreEqual(s.ObscureMusic, t.ObscureMusic); - Assert.AreEqual(s.OtherCleanTime, t.OtherCleanTime); - Assert.AreEqual(s.OtherCount, t.OtherCount); - Assert.AreEqual(s.OtherPrims, t.OtherPrims); - Assert.AreEqual(s.OwnerID, t.OwnerID); - Assert.AreEqual(s.OwnerPrims, t.OwnerPrims); - Assert.AreEqual(s.ParcelFlags, t.ParcelFlags); - Assert.AreEqual(s.ParcelPrimBonus, t.ParcelPrimBonus); - Assert.AreEqual(s.PassHours, t.PassHours); - Assert.AreEqual(s.PassPrice, t.PassPrice); - Assert.AreEqual(s.PublicCount, t.PublicCount); - Assert.AreEqual(s.RegionDenyAgeUnverified, t.RegionDenyAgeUnverified); - Assert.AreEqual(s.RegionDenyAnonymous, t.RegionDenyAnonymous); - Assert.AreEqual(s.RegionPushOverride, t.RegionPushOverride); - Assert.AreEqual(s.RentPrice, t.RentPrice); - Assert.AreEqual(s.RequestResult, t.RequestResult); - Assert.AreEqual(s.SalePrice, t.SalePrice); - Assert.AreEqual(s.SelectedPrims, t.SelectedPrims); - Assert.AreEqual(s.SelfCount, t.SelfCount); - Assert.AreEqual(s.SequenceID, t.SequenceID); - Assert.AreEqual(s.SimWideMaxPrims, t.SimWideMaxPrims); - Assert.AreEqual(s.SimWideTotalPrims, t.SimWideTotalPrims); - Assert.AreEqual(s.SnapSelection, t.SnapSelection); - Assert.AreEqual(s.SnapshotID, t.SnapshotID); - Assert.AreEqual(s.Status, t.Status); - Assert.AreEqual(s.TotalPrims, t.TotalPrims); - Assert.AreEqual(s.UserLocation, t.UserLocation); - Assert.AreEqual(s.UserLookAt, t.UserLookAt); + //ParcelPropertiesMessage t = (ParcelPropertiesMessage)formatter.Deserialize(stream); + byte[] unpackedLlsd = MessagePackSerializer.Deserialize(stream, BenchmarkMessagePackOptions); + ParcelPropertiesMessage t = new ParcelPropertiesMessage(); + t.Deserialize((OSDMap)OSDParser.DeserializeLLSDBinary(unpackedLlsd)); + + Assert.Equal(s.AABBMax, t.AABBMax); + Assert.Equal(s.AABBMin, t.AABBMin); + Assert.Equal(s.Area, t.Area); + Assert.Equal(s.AuctionID, t.AuctionID); + Assert.Equal(s.AuthBuyerID, t.AuthBuyerID); + Assert.Equal(s.Bitmap, t.Bitmap); + Assert.Equal(s.Category, t.Category); + Assert.Equal(s.ClaimDate, t.ClaimDate); + Assert.Equal(s.ClaimPrice, t.ClaimPrice); + Assert.Equal(s.Desc, t.Desc); + Assert.Equal(s.GroupID, t.GroupID); + Assert.Equal(s.GroupPrims, t.GroupPrims); + Assert.Equal(s.IsGroupOwned, t.IsGroupOwned); + Assert.Equal(s.LandingType, t.LandingType); + Assert.Equal(s.LocalID, t.LocalID); + Assert.Equal(s.MaxPrims, t.MaxPrims); + Assert.Equal(s.MediaAutoScale, t.MediaAutoScale); + Assert.Equal(s.MediaDesc, t.MediaDesc); + Assert.Equal(s.MediaHeight, t.MediaHeight); + Assert.Equal(s.MediaID, t.MediaID); + Assert.Equal(s.MediaLoop, t.MediaLoop); + Assert.Equal(s.MediaType, t.MediaType); + Assert.Equal(s.MediaURL, t.MediaURL); + Assert.Equal(s.MediaWidth, t.MediaWidth); + Assert.Equal(s.MusicURL, t.MusicURL); + Assert.Equal(s.Name, t.Name); + Assert.Equal(s.ObscureMedia, t.ObscureMedia); + Assert.Equal(s.ObscureMusic, t.ObscureMusic); + Assert.Equal(s.OtherCleanTime, t.OtherCleanTime); + Assert.Equal(s.OtherCount, t.OtherCount); + Assert.Equal(s.OtherPrims, t.OtherPrims); + Assert.Equal(s.OwnerID, t.OwnerID); + Assert.Equal(s.OwnerPrims, t.OwnerPrims); + Assert.Equal(s.ParcelFlags, t.ParcelFlags); + Assert.Equal(s.ParcelPrimBonus, t.ParcelPrimBonus); + Assert.Equal(s.PassHours, t.PassHours); + Assert.Equal(s.PassPrice, t.PassPrice); + Assert.Equal(s.PublicCount, t.PublicCount); + Assert.Equal(s.RegionDenyAgeUnverified, t.RegionDenyAgeUnverified); + Assert.Equal(s.RegionDenyAnonymous, t.RegionDenyAnonymous); + Assert.Equal(s.RegionPushOverride, t.RegionPushOverride); + Assert.Equal(s.RentPrice, t.RentPrice); + Assert.Equal(s.RequestResult, t.RequestResult); + Assert.Equal(s.SalePrice, t.SalePrice); + Assert.Equal(s.SelectedPrims, t.SelectedPrims); + Assert.Equal(s.SelfCount, t.SelfCount); + Assert.Equal(s.SequenceID, t.SequenceID); + Assert.Equal(s.SimWideMaxPrims, t.SimWideMaxPrims); + Assert.Equal(s.SimWideTotalPrims, t.SimWideTotalPrims); + Assert.Equal(s.SnapSelection, t.SnapSelection); + Assert.Equal(s.SnapshotID, t.SnapshotID); + Assert.Equal(s.Status, t.Status); + Assert.Equal(s.TotalPrims, t.TotalPrims); + Assert.Equal(s.UserLocation, t.UserLocation); + Assert.Equal(s.UserLookAt, t.UserLookAt); } TimeSpan durationxml = DateTime.UtcNow - xmlTestTime; - Console.WriteLine("ParcelPropertiesMessage: .NET BinarySerialization/Deserialization Passes: {0} Total time: {1}", TEST_ITER, durationxml); + Console.WriteLine("ParcelPropertiesMessage: MessagePack(LLSD binary payload) Serialization/Deserialization Passes: {0} Total time: {1}", TEST_ITER, durationxml); } #endregion diff --git a/OpenMetaverse.Tests/NetworkTests.cs b/OpenMetaverse.Tests/NetworkTests.cs index 39239e8d..ecdcf755 100644 --- a/OpenMetaverse.Tests/NetworkTests.cs +++ b/OpenMetaverse.Tests/NetworkTests.cs @@ -24,15 +24,15 @@ * POSSIBILITY OF SUCH DAMAGE. */ -using NUnit.Framework; +using Xunit; using OpenMetaverse.Packets; using System; namespace OpenMetaverse.Tests { - [TestFixture] - [Category("Network")] - public class NetworkTests : Assert + + [Trait("Category", "Network")] + public class NetworkTests : IDisposable { GridClient Client; @@ -50,27 +50,23 @@ public NetworkTests() // Register callbacks Client.Network.RegisterCallback(PacketType.ObjectUpdate, ObjectUpdateHandler); //Client.Self.OnTeleport += new MainAvatar.TeleportCallback(OnTeleportHandler) - } - [SetUp] - public void Init() - { Console.Write("Logging in Testing Anvil..."); // Connect to the grid string startLoc = NetworkManager.StartLocation("Hooper", 179, 18, 32); - Assert.IsTrue(Client.Network.Login("Testing", "Anvil", "testinganvil", "Unit Test Framework", startLoc, + Assert.True(Client.Network.Login("Testing", "Anvil", "testinganvil", "Unit Test Framework", startLoc, "contact@openmetaverse.co"), "Client failed to login, reason: " + Client.Network.LoginMessage); Console.WriteLine("Done"); - Assert.IsTrue(Client.Network.Connected, "Client is not connected to the grid"); + Assert.True(Client.Network.Connected, "Client is not connected to the grid"); //int start = Environment.TickCount; - Assert.AreEqual("hooper", Client.Network.CurrentSim.Name.ToLower(), "Logged in to sim " + - Client.Network.CurrentSim.Name + " instead of hooper"); + Assert.True(Client.Network.CurrentSim.Name.Equals("hooper", StringComparison.OrdinalIgnoreCase), + "Logged in to sim " + Client.Network.CurrentSim.Name + " instead of hooper"); } - [Test] + [Fact] public void DetectObjects() { int start = Environment.TickCount; @@ -78,13 +74,13 @@ public void DetectObjects() { if (Environment.TickCount - start > 20000) { - Assert.Fail("Timeout waiting for an ObjectUpdate packet"); + throw new Xunit.Sdk.XunitException("Timeout waiting for an ObjectUpdate packet"); } } } /* - [Test] + [Fact] public void U64Receive() { int start = Environment.TickCount; @@ -92,51 +88,51 @@ public void U64Receive() { if (Environment.TickCount - start > 10000) { - Assert.Fail("Timeout waiting for an ObjectUpdate packet"); + throw new Xunit.Sdk.XunitException("Timeout waiting for an ObjectUpdate packet"); } } - Assert.IsTrue(CurrentRegionHandle == HooperRegionHandle, "Current region is " + + Assert.True(CurrentRegionHandle == HooperRegionHandle, "Current region is " + CurrentRegionHandle + " (" + Client.Network.CurrentSim.Name + ")" + " when we were expecting " + HooperRegionHandle + " (Dore), possible endian issue"); } */ - /*[Test] + /*[Fact] public void Teleport() { // test in-sim teleports - Assert.IsTrue(CapsQueueRunning(), "CAPS Event queue is not running in " + Client.Network.CurrentSim.Name); + Assert.True(CapsQueueRunning(), "CAPS Event queue is not running in " + Client.Network.CurrentSim.Name); string localSimName = Client.Network.CurrentSim.Name; - Assert.IsTrue(Client.Self.Teleport(Client.Network.CurrentSim.Handle, new Vector3(121, 13, 41)), + Assert.True(Client.Self.Teleport(Client.Network.CurrentSim.Handle, new Vector3(121, 13, 41)), "Teleport In-Sim Failed " + Client.Network.CurrentSim.Name); // Assert that we really did make it to our scheduled destination - Assert.AreEqual(localSimName, Client.Network.CurrentSim.Name, + Assert.Equal(localSimName, Client.Network.CurrentSim.Name, "Expected to teleport to " + localSimName + ", ended up in " + Client.Network.CurrentSim.Name + ". Possibly region full or offline?"); - Assert.IsTrue(CapsQueueRunning(), "CAPS Event queue is not running in " + Client.Network.CurrentSim.Name); - Assert.IsTrue(Client.Self.Teleport(DoreRegionHandle, new Vector3(128, 128, 32)), + Assert.True(CapsQueueRunning(), "CAPS Event queue is not running in " + Client.Network.CurrentSim.Name); + Assert.True(Client.Self.Teleport(DoreRegionHandle, new Vector3(128, 128, 32)), "Teleport to Dore failed"); // Assert that we really did make it to our scheduled destination - Assert.AreEqual("dore", Client.Network.CurrentSim.Name.ToLower(), + Assert.Equal("dore", Client.Network.CurrentSim.Name.ToLower(), "Expected to teleport to Dore, ended up in " + Client.Network.CurrentSim.Name + ". Possibly region full or offline?"); - Assert.IsTrue(CapsQueueRunning(), "CAPS Event queue is not running in " + Client.Network.CurrentSim.Name); - Assert.IsTrue(Client.Self.Teleport(HooperRegionHandle, new Vector3(179, 18, 32)), + Assert.True(CapsQueueRunning(), "CAPS Event queue is not running in " + Client.Network.CurrentSim.Name); + Assert.True(Client.Self.Teleport(HooperRegionHandle, new Vector3(179, 18, 32)), "Teleport to Hooper failed"); // Assert that we really did make it to our scheduled destination - Assert.AreEqual("hooper", Client.Network.CurrentSim.Name.ToLower(), + Assert.Equal("hooper", Client.Network.CurrentSim.Name.ToLower(), "Expected to teleport to Hooper, ended up in " + Client.Network.CurrentSim.Name + ". Possibly region full or offline?"); }*/ - [Test] + [Fact] public void CapsQueue() { - Assert.IsTrue(CapsQueueRunning(), "CAPS Event Queue is not running and failed to start"); + Assert.True(CapsQueueRunning(), "CAPS Event Queue is not running and failed to start"); } public bool CapsQueueRunning() @@ -160,7 +156,7 @@ public bool CapsQueueRunning() else { Success = false; - Assert.Fail("Timeout waiting for event Queue to startup"); + throw new Xunit.Sdk.XunitException("Timeout waiting for event Queue to startup"); } Client.Network.EventQueueRunning -= capsRunning; return Success; @@ -174,8 +170,7 @@ private void ObjectUpdateHandler(object sender, PacketReceivedEventArgs e) //CurrentRegionHandle = update.RegionData.RegionHandle; } - [TearDown] - public void Shutdown() + public void Dispose() { Console.Write("Logging out..."); Client.Network.Logout(); diff --git a/OpenMetaverse.Tests/NotationLLSDTests.cs b/OpenMetaverse.Tests/NotationLLSDTests.cs index e7fddf28..a399a49d 100644 --- a/OpenMetaverse.Tests/NotationLLSDTests.cs +++ b/OpenMetaverse.Tests/NotationLLSDTests.cs @@ -36,7 +36,7 @@ * */ -using NUnit.Framework; +using Xunit; using OpenMetaverse.StructuredData; using System; using System.IO; @@ -46,265 +46,265 @@ namespace OpenMetaverse.Tests { - [TestFixture()] + public class NotationSDTests { - [Test()] + [Fact] public void HelperFunctions() { StringReader reader = new StringReader("test1tast2test3"); char[] charsOne = { 't', 'e', 's', 't' }; int resultOne = OSDParser.BufferCharactersEqual(reader, charsOne, 0); - Assert.AreEqual(charsOne.Length, resultOne); + Assert.Equal(charsOne.Length, resultOne); char[] charsTwo = { '1', 't', 'e' }; int resultTwo = OSDParser.BufferCharactersEqual(reader, charsTwo, 0); - Assert.AreEqual(2, resultTwo); + Assert.Equal(2, resultTwo); char[] charsThree = { 'a', 's', 't', '2', 't', 'e', 's' }; int resultThree = OSDParser.BufferCharactersEqual(reader, charsThree, 1); - Assert.AreEqual(1, resultThree); + Assert.Equal(1, resultThree); int resultFour = OSDParser.BufferCharactersEqual(reader, charsThree, 0); - Assert.AreEqual(charsThree.Length, resultFour); + Assert.Equal(charsThree.Length, resultFour); char[] charsFive = { 't', '3', 'a', 'a' }; int resultFive = OSDParser.BufferCharactersEqual(reader, charsFive, 0); - Assert.AreEqual(2, resultFive); + Assert.Equal(2, resultFive); } - [Test()] + [Fact] public void DeserializeUndef() { String s = "!"; OSD llsd = OSDParser.DeserializeLLSDNotation(s); - Assert.AreEqual(OSDType.Unknown, llsd.Type); + Assert.Equal(OSDType.Unknown, llsd.Type); } - [Test()] + [Fact] public void SerializeUndef() { OSD llsd = new OSD(); string s = OSDParser.SerializeLLSDNotation(llsd); OSD llsdDS = OSDParser.DeserializeLLSDNotation(s); - Assert.AreEqual(OSDType.Unknown, llsdDS.Type); + Assert.Equal(OSDType.Unknown, llsdDS.Type); } - [Test()] + [Fact] public void DeserializeBoolean() { String t = "true"; OSD llsdT = OSDParser.DeserializeLLSDNotation(t); - Assert.AreEqual(OSDType.Boolean, llsdT.Type); - Assert.AreEqual(true, llsdT.AsBoolean()); + Assert.Equal(OSDType.Boolean, llsdT.Type); + Assert.Equal(true, llsdT.AsBoolean()); String tTwo = "t"; OSD llsdTTwo = OSDParser.DeserializeLLSDNotation(tTwo); - Assert.AreEqual(OSDType.Boolean, llsdTTwo.Type); - Assert.AreEqual(true, llsdTTwo.AsBoolean()); + Assert.Equal(OSDType.Boolean, llsdTTwo.Type); + Assert.Equal(true, llsdTTwo.AsBoolean()); String tThree = "TRUE"; OSD llsdTThree = OSDParser.DeserializeLLSDNotation(tThree); - Assert.AreEqual(OSDType.Boolean, llsdTThree.Type); - Assert.AreEqual(true, llsdTThree.AsBoolean()); + Assert.Equal(OSDType.Boolean, llsdTThree.Type); + Assert.Equal(true, llsdTThree.AsBoolean()); String tFour = "T"; OSD llsdTFour = OSDParser.DeserializeLLSDNotation(tFour); - Assert.AreEqual(OSDType.Boolean, llsdTFour.Type); - Assert.AreEqual(true, llsdTFour.AsBoolean()); + Assert.Equal(OSDType.Boolean, llsdTFour.Type); + Assert.Equal(true, llsdTFour.AsBoolean()); String tFive = "1"; OSD llsdTFive = OSDParser.DeserializeLLSDNotation(tFive); - Assert.AreEqual(OSDType.Boolean, llsdTFive.Type); - Assert.AreEqual(true, llsdTFive.AsBoolean()); + Assert.Equal(OSDType.Boolean, llsdTFive.Type); + Assert.Equal(true, llsdTFive.AsBoolean()); String f = "false"; OSD llsdF = OSDParser.DeserializeLLSDNotation(f); - Assert.AreEqual(OSDType.Boolean, llsdF.Type); - Assert.AreEqual(false, llsdF.AsBoolean()); + Assert.Equal(OSDType.Boolean, llsdF.Type); + Assert.Equal(false, llsdF.AsBoolean()); String fTwo = "f"; OSD llsdFTwo = OSDParser.DeserializeLLSDNotation(fTwo); - Assert.AreEqual(OSDType.Boolean, llsdFTwo.Type); - Assert.AreEqual(false, llsdFTwo.AsBoolean()); + Assert.Equal(OSDType.Boolean, llsdFTwo.Type); + Assert.Equal(false, llsdFTwo.AsBoolean()); String fThree = "FALSE"; OSD llsdFThree = OSDParser.DeserializeLLSDNotation(fThree); - Assert.AreEqual(OSDType.Boolean, llsdFThree.Type); - Assert.AreEqual(false, llsdFThree.AsBoolean()); + Assert.Equal(OSDType.Boolean, llsdFThree.Type); + Assert.Equal(false, llsdFThree.AsBoolean()); String fFour = "F"; OSD llsdFFour = OSDParser.DeserializeLLSDNotation(fFour); - Assert.AreEqual(OSDType.Boolean, llsdFFour.Type); - Assert.AreEqual(false, llsdFFour.AsBoolean()); + Assert.Equal(OSDType.Boolean, llsdFFour.Type); + Assert.Equal(false, llsdFFour.AsBoolean()); String fFive = "0"; OSD llsdFFive = OSDParser.DeserializeLLSDNotation(fFive); - Assert.AreEqual(OSDType.Boolean, llsdFFive.Type); - Assert.AreEqual(false, llsdFFive.AsBoolean()); + Assert.Equal(OSDType.Boolean, llsdFFive.Type); + Assert.Equal(false, llsdFFive.AsBoolean()); } - [Test()] + [Fact] public void SerializeBoolean() { OSD llsdTrue = OSD.FromBoolean(true); string sTrue = OSDParser.SerializeLLSDNotation(llsdTrue); OSD llsdTrueDS = OSDParser.DeserializeLLSDNotation(sTrue); - Assert.AreEqual(OSDType.Boolean, llsdTrueDS.Type); - Assert.AreEqual(true, llsdTrueDS.AsBoolean()); + Assert.Equal(OSDType.Boolean, llsdTrueDS.Type); + Assert.Equal(true, llsdTrueDS.AsBoolean()); OSD llsdFalse = OSD.FromBoolean(false); string sFalse = OSDParser.SerializeLLSDNotation(llsdFalse); OSD llsdFalseDS = OSDParser.DeserializeLLSDNotation(sFalse); - Assert.AreEqual(OSDType.Boolean, llsdFalseDS.Type); - Assert.AreEqual(false, llsdFalseDS.AsBoolean()); + Assert.Equal(OSDType.Boolean, llsdFalseDS.Type); + Assert.Equal(false, llsdFalseDS.AsBoolean()); } - [Test()] + [Fact] public void DeserializeInteger() { string integerOne = "i12319423"; OSD llsdOne = OSDParser.DeserializeLLSDNotation(integerOne); - Assert.AreEqual(OSDType.Integer, llsdOne.Type); - Assert.AreEqual(12319423, llsdOne.AsInteger()); + Assert.Equal(OSDType.Integer, llsdOne.Type); + Assert.Equal(12319423, llsdOne.AsInteger()); string integerTwo = "i-489234"; OSD llsdTwo = OSDParser.DeserializeLLSDNotation(integerTwo); - Assert.AreEqual(OSDType.Integer, llsdTwo.Type); - Assert.AreEqual(-489234, llsdTwo.AsInteger()); + Assert.Equal(OSDType.Integer, llsdTwo.Type); + Assert.Equal(-489234, llsdTwo.AsInteger()); } - [Test()] + [Fact] public void SerializeInteger() { OSD llsdOne = OSD.FromInteger(12319423); string sOne = OSDParser.SerializeLLSDNotation(llsdOne); OSD llsdOneDS = OSDParser.DeserializeLLSDNotation(sOne); - Assert.AreEqual(OSDType.Integer, llsdOneDS.Type); - Assert.AreEqual(12319423, llsdOne.AsInteger()); + Assert.Equal(OSDType.Integer, llsdOneDS.Type); + Assert.Equal(12319423, llsdOne.AsInteger()); OSD llsdTwo = OSD.FromInteger(-71892034); string sTwo = OSDParser.SerializeLLSDNotation(llsdTwo); OSD llsdTwoDS = OSDParser.DeserializeLLSDNotation(sTwo); - Assert.AreEqual(OSDType.Integer, llsdTwoDS.Type); - Assert.AreEqual(-71892034, llsdTwoDS.AsInteger()); + Assert.Equal(OSDType.Integer, llsdTwoDS.Type); + Assert.Equal(-71892034, llsdTwoDS.AsInteger()); } - [Test()] + [Fact] public void DeserializeReal() { String realOne = "r1123412345.465711"; OSD llsdOne = OSDParser.DeserializeLLSDNotation(realOne); - Assert.AreEqual(OSDType.Real, llsdOne.Type); - Assert.AreEqual(1123412345.465711d, llsdOne.AsReal()); + Assert.Equal(OSDType.Real, llsdOne.Type); + Assert.Equal(1123412345.465711d, llsdOne.AsReal()); String realTwo = "r-11234684.923411"; OSD llsdTwo = OSDParser.DeserializeLLSDNotation(realTwo); - Assert.AreEqual(OSDType.Real, llsdTwo.Type); - Assert.AreEqual(-11234684.923411d, llsdTwo.AsReal()); + Assert.Equal(OSDType.Real, llsdTwo.Type); + Assert.Equal(-11234684.923411d, llsdTwo.AsReal()); String realThree = "r1"; OSD llsdThree = OSDParser.DeserializeLLSDNotation(realThree); - Assert.AreEqual(OSDType.Real, llsdThree.Type); - Assert.AreEqual(1d, llsdThree.AsReal()); + Assert.Equal(OSDType.Real, llsdThree.Type); + Assert.Equal(1d, llsdThree.AsReal()); String realFour = "r2.0193899999999998204e-06"; OSD llsdFour = OSDParser.DeserializeLLSDNotation(realFour); - Assert.AreEqual(OSDType.Real, llsdFour.Type); - Assert.AreEqual(2.0193899999999998204e-06d, llsdFour.AsReal()); + Assert.Equal(OSDType.Real, llsdFour.Type); + Assert.Equal(2.0193899999999998204e-06d, llsdFour.AsReal()); String realFive = "r0"; OSD llsdFive = OSDParser.DeserializeLLSDNotation(realFive); - Assert.AreEqual(OSDType.Real, llsdFive.Type); - Assert.AreEqual(0d, llsdFive.AsReal()); + Assert.Equal(OSDType.Real, llsdFive.Type); + Assert.Equal(0d, llsdFive.AsReal()); } - [Test()] + [Fact] public void SerializeReal() { OSD llsdOne = OSD.FromReal(12987234.723847d); string sOne = OSDParser.SerializeLLSDNotation(llsdOne); OSD llsdOneDS = OSDParser.DeserializeLLSDNotation(sOne); - Assert.AreEqual(OSDType.Real, llsdOneDS.Type); - Assert.AreEqual(12987234.723847d, llsdOneDS.AsReal()); + Assert.Equal(OSDType.Real, llsdOneDS.Type); + Assert.Equal(12987234.723847d, llsdOneDS.AsReal()); OSD llsdTwo = OSD.FromReal(-32347892.234234d); string sTwo = OSDParser.SerializeLLSDNotation(llsdTwo); OSD llsdTwoDS = OSDParser.DeserializeLLSDNotation(sTwo); - Assert.AreEqual(OSDType.Real, llsdTwoDS.Type); - Assert.AreEqual(-32347892.234234d, llsdTwoDS.AsReal()); + Assert.Equal(OSDType.Real, llsdTwoDS.Type); + Assert.Equal(-32347892.234234d, llsdTwoDS.AsReal()); OSD llsdThree = OSD.FromReal(Double.MaxValue); string sThree = OSDParser.SerializeLLSDNotation(llsdThree); OSD llsdThreeDS = OSDParser.DeserializeLLSDNotation(sThree); - Assert.AreEqual(OSDType.Real, llsdThreeDS.Type); - Assert.AreEqual(Double.MaxValue, llsdThreeDS.AsReal()); + Assert.Equal(OSDType.Real, llsdThreeDS.Type); + Assert.Equal(Double.MaxValue, llsdThreeDS.AsReal()); OSD llsdFour = OSD.FromReal(Double.MinValue); string sFour = OSDParser.SerializeLLSDNotation(llsdFour); OSD llsdFourDS = OSDParser.DeserializeLLSDNotation(sFour); - Assert.AreEqual(OSDType.Real, llsdFourDS.Type); - Assert.AreEqual(Double.MinValue, llsdFourDS.AsReal()); + Assert.Equal(OSDType.Real, llsdFourDS.Type); + Assert.Equal(Double.MinValue, llsdFourDS.AsReal()); OSD llsdFive = OSD.FromReal(-1.1123123E+50d); string sFive = OSDParser.SerializeLLSDNotation(llsdFive); OSD llsdFiveDS = OSDParser.DeserializeLLSDNotation(sFive); - Assert.AreEqual(OSDType.Real, llsdFiveDS.Type); - Assert.AreEqual(-1.1123123E+50d, llsdFiveDS.AsReal()); + Assert.Equal(OSDType.Real, llsdFiveDS.Type); + Assert.Equal(-1.1123123E+50d, llsdFiveDS.AsReal()); OSD llsdSix = OSD.FromReal(2.0193899999999998204e-06); string sSix = OSDParser.SerializeLLSDNotation(llsdSix); OSD llsdSixDS = OSDParser.DeserializeLLSDNotation(sSix); - Assert.AreEqual(OSDType.Real, llsdSixDS.Type); - Assert.AreEqual(2.0193899999999998204e-06, llsdSixDS.AsReal()); + Assert.Equal(OSDType.Real, llsdSixDS.Type); + Assert.Equal(2.0193899999999998204e-06, llsdSixDS.AsReal()); } - [Test()] + [Fact] public void DeserializeUUID() { String uuidOne = "u97f4aeca-88a1-42a1-b385-b97b18abb255"; OSD llsdOne = OSDParser.DeserializeLLSDNotation(uuidOne); - Assert.AreEqual(OSDType.UUID, llsdOne.Type); - Assert.AreEqual("97f4aeca-88a1-42a1-b385-b97b18abb255", llsdOne.AsString()); + Assert.Equal(OSDType.UUID, llsdOne.Type); + Assert.Equal("97f4aeca-88a1-42a1-b385-b97b18abb255", llsdOne.AsString()); String uuidTwo = "u00000000-0000-0000-0000-000000000000"; OSD llsdTwo = OSDParser.DeserializeLLSDNotation(uuidTwo); - Assert.AreEqual(OSDType.UUID, llsdTwo.Type); - Assert.AreEqual("00000000-0000-0000-0000-000000000000", llsdTwo.AsString()); + Assert.Equal(OSDType.UUID, llsdTwo.Type); + Assert.Equal("00000000-0000-0000-0000-000000000000", llsdTwo.AsString()); } - [Test()] + [Fact] public void SerializeUUID() { OSD llsdOne = OSD.FromUUID(new UUID("97f4aeca-88a1-42a1-b385-b97b18abb255")); string sOne = OSDParser.SerializeLLSDNotation(llsdOne); OSD llsdOneDS = OSDParser.DeserializeLLSDNotation(sOne); - Assert.AreEqual(OSDType.UUID, llsdOneDS.Type); - Assert.AreEqual("97f4aeca-88a1-42a1-b385-b97b18abb255", llsdOneDS.AsString()); + Assert.Equal(OSDType.UUID, llsdOneDS.Type); + Assert.Equal("97f4aeca-88a1-42a1-b385-b97b18abb255", llsdOneDS.AsString()); OSD llsdTwo = OSD.FromUUID(new UUID("00000000-0000-0000-0000-000000000000")); string sTwo = OSDParser.SerializeLLSDNotation(llsdTwo); OSD llsdTwoDS = OSDParser.DeserializeLLSDNotation(sTwo); - Assert.AreEqual(OSDType.UUID, llsdTwoDS.Type); - Assert.AreEqual("00000000-0000-0000-0000-000000000000", llsdTwoDS.AsString()); + Assert.Equal(OSDType.UUID, llsdTwoDS.Type); + Assert.Equal("00000000-0000-0000-0000-000000000000", llsdTwoDS.AsString()); } public void DeserializeString() { string sOne = "''"; OSD llsdOne = OSDParser.DeserializeLLSDNotation(sOne); - Assert.AreEqual(OSDType.String, llsdOne.Type); - Assert.AreEqual("", llsdOne.AsString()); + Assert.Equal(OSDType.String, llsdOne.Type); + Assert.Equal("", llsdOne.AsString()); // This is double escaping. Once for the encoding, and once for csharp. string sTwo = "'test\\'\"test'"; OSD llsdTwo = OSDParser.DeserializeLLSDNotation(sTwo); - Assert.AreEqual(OSDType.String, llsdTwo.Type); - Assert.AreEqual("test'\"test", llsdTwo.AsString()); + Assert.Equal(OSDType.String, llsdTwo.Type); + Assert.Equal("test'\"test", llsdTwo.AsString()); // "test \\lest" char[] cThree = { (char)0x27, (char)0x74, (char)0x65, (char)0x73, (char)0x74, (char)0x20, (char)0x5c, @@ -312,35 +312,35 @@ public void DeserializeString() string sThree = new string(cThree); OSD llsdThree = OSDParser.DeserializeLLSDNotation(sThree); - Assert.AreEqual(OSDType.String, llsdThree.Type); - Assert.AreEqual("test \\lest", llsdThree.AsString()); + Assert.Equal(OSDType.String, llsdThree.Type); + Assert.Equal("test \\lest", llsdThree.AsString()); string sFour = "'aa\t la'"; OSD llsdFour = OSDParser.DeserializeLLSDNotation(sFour); - Assert.AreEqual(OSDType.String, llsdFour.Type); - Assert.AreEqual("aa\t la", llsdFour.AsString()); + Assert.Equal(OSDType.String, llsdFour.Type); + Assert.Equal("aa\t la", llsdFour.AsString()); char[] cFive = { (char)0x27, (char)0x5c, (char)0x5c, (char)0x27 }; string sFive = new String(cFive); OSD llsdFive = OSDParser.DeserializeLLSDNotation(sFive); - Assert.AreEqual(OSDType.String, llsdFive.Type); - Assert.AreEqual("\\", llsdFive.AsString()); + Assert.Equal(OSDType.String, llsdFive.Type); + Assert.Equal("\\", llsdFive.AsString()); string sSix = "s(10)\"1234567890\""; OSD llsdSix = OSDParser.DeserializeLLSDNotation(sSix); - Assert.AreEqual(OSDType.String, llsdSix.Type); - Assert.AreEqual("1234567890", llsdSix.AsString()); + Assert.Equal(OSDType.String, llsdSix.Type); + Assert.Equal("1234567890", llsdSix.AsString()); string sSeven = "s(5)\"\\\\\\\\\\\""; OSD llsdSeven = OSDParser.DeserializeLLSDNotation(sSeven); - Assert.AreEqual(OSDType.String, llsdSeven.Type); - Assert.AreEqual("\\\\\\\\\\", llsdSeven.AsString()); + Assert.Equal(OSDType.String, llsdSeven.Type); + Assert.Equal("\\\\\\\\\\", llsdSeven.AsString()); string sEight = "\"aouAOUhsdjklfghskldjfghqeiurtzwieortzaslxfjkgh\""; OSD llsdEight = OSDParser.DeserializeLLSDNotation(sEight); - Assert.AreEqual(OSDType.String, llsdEight.Type); - Assert.AreEqual("aouAOUhsdjklfghskldjfghqeiurtzwieortzaslxfjkgh", llsdEight.AsString()); + Assert.Equal(OSDType.String, llsdEight.Type); + Assert.Equal("aouAOUhsdjklfghskldjfghqeiurtzwieortzaslxfjkgh", llsdEight.AsString()); @@ -351,12 +351,12 @@ public void DoSomeStringSerializingActionsAndAsserts(string s) OSD llsdOne = OSD.FromString(s); string sOne = OSDParser.SerializeLLSDNotation(llsdOne); OSD llsdOneDS = OSDParser.DeserializeLLSDNotation(sOne); - Assert.AreEqual(OSDType.String, llsdOne.Type); - Assert.AreEqual(s, llsdOneDS.AsString()); + Assert.Equal(OSDType.String, llsdOne.Type); + Assert.Equal(s, llsdOneDS.AsString()); } - [Test()] + [Fact] public void SerializeString() { DoSomeStringSerializingActionsAndAsserts(""); @@ -390,78 +390,78 @@ public void SerializeString() } - [Test()] + [Fact] public void DeserializeURI() { string sUriOne = "l\"http://test.com/test test>\\\"/&yes\""; OSD llsdOne = OSDParser.DeserializeLLSDNotation(sUriOne); - Assert.AreEqual(OSDType.URI, llsdOne.Type); - Assert.AreEqual("http://test.com/test%20test%3E%22/&yes", llsdOne.AsString()); + Assert.Equal(OSDType.URI, llsdOne.Type); + Assert.Equal("http://test.com/test%20test%3E%22/&yes", llsdOne.AsString()); string sUriTwo = "l\"test/test/test?test=1&toast=2\""; OSD llsdTwo = OSDParser.DeserializeLLSDNotation(sUriTwo); - Assert.AreEqual(OSDType.URI, llsdTwo.Type); - Assert.AreEqual("test/test/test?test=1&toast=2", llsdTwo.AsString()); + Assert.Equal(OSDType.URI, llsdTwo.Type); + Assert.Equal("test/test/test?test=1&toast=2", llsdTwo.AsString()); } - [Test()] + [Fact] public void SerializeURI() { Uri uriOne = new Uri("http://test.org/test test>\\\"/&yes\"", UriKind.RelativeOrAbsolute); OSD llsdOne = OSD.FromUri(uriOne); string sUriOne = OSDParser.SerializeLLSDNotation(llsdOne); OSD llsdOneDS = OSDParser.DeserializeLLSDNotation(sUriOne); - Assert.AreEqual(OSDType.URI, llsdOneDS.Type); - Assert.AreEqual(uriOne, llsdOneDS.AsUri()); + Assert.Equal(OSDType.URI, llsdOneDS.Type); + Assert.Equal(uriOne, llsdOneDS.AsUri()); Uri uriTwo = new Uri("test/test/near/the/end?test=1", UriKind.RelativeOrAbsolute); OSD llsdTwo = OSD.FromUri(uriTwo); string sUriTwo = OSDParser.SerializeLLSDNotation(llsdTwo); OSD llsdTwoDS = OSDParser.DeserializeLLSDNotation(sUriTwo); - Assert.AreEqual(OSDType.URI, llsdTwoDS.Type); - Assert.AreEqual(uriTwo, llsdTwoDS.AsUri()); + Assert.Equal(OSDType.URI, llsdTwoDS.Type); + Assert.Equal(uriTwo, llsdTwoDS.AsUri()); } - [Test()] + [Fact] public void DeserializeDate() { string sDateOne = "d\"2007-12-31T20:49:10Z\""; OSD llsdOne = OSDParser.DeserializeLLSDNotation(sDateOne); - Assert.AreEqual(OSDType.Date, llsdOne.Type); + Assert.Equal(OSDType.Date, llsdOne.Type); DateTime dt = new DateTime(2007, 12, 31, 20, 49, 10, 0, DateTimeKind.Utc); DateTime dtDS = llsdOne.AsDate(); - Assert.AreEqual(dt, dtDS.ToUniversalTime()); + Assert.Equal(dt, dtDS.ToUniversalTime()); } - [Test()] + [Fact] public void SerializeDate() { DateTime dtOne = new DateTime(2005, 8, 10, 11, 23, 4, DateTimeKind.Utc); OSD llsdOne = OSD.FromDate(dtOne); string sDtOne = OSDParser.SerializeLLSDNotation(llsdOne); OSD llsdOneDS = OSDParser.DeserializeLLSDNotation(sDtOne); - Assert.AreEqual(OSDType.Date, llsdOneDS.Type); + Assert.Equal(OSDType.Date, llsdOneDS.Type); DateTime dtOneDS = llsdOneDS.AsDate(); - Assert.AreEqual(dtOne, dtOneDS.ToUniversalTime()); + Assert.Equal(dtOne, dtOneDS.ToUniversalTime()); DateTime dtTwo = new DateTime(2010, 10, 11, 23, 00, 10, 100, DateTimeKind.Utc); OSD llsdTwo = OSD.FromDate(dtTwo); string sDtTwo = OSDParser.SerializeLLSDNotation(llsdTwo); OSD llsdTwoDS = OSDParser.DeserializeLLSDNotation(sDtTwo); - Assert.AreEqual(OSDType.Date, llsdTwoDS.Type); + Assert.Equal(OSDType.Date, llsdTwoDS.Type); DateTime dtTwoDS = llsdTwoDS.AsDate(); - Assert.AreEqual(dtTwo, dtTwoDS.ToUniversalTime()); + Assert.Equal(dtTwo, dtTwoDS.ToUniversalTime()); // check if a *local* time can be serialized and deserialized DateTime dtThree = new DateTime(2009, 12, 30, 8, 25, 10, DateTimeKind.Local); OSD llsdDateThree = OSD.FromDate(dtThree); string sDateThreeSerialized = OSDParser.SerializeLLSDNotation(llsdDateThree); OSD llsdDateThreeDS = OSDParser.DeserializeLLSDNotation(sDateThreeSerialized); - Assert.AreEqual(OSDType.Date, llsdDateThreeDS.Type); - Assert.AreEqual(dtThree, llsdDateThreeDS.AsDate()); + Assert.Equal(OSDType.Date, llsdDateThreeDS.Type); + Assert.Equal(dtThree, llsdDateThreeDS.AsDate()); } - [Test()] + [Fact] public void SerializeBinary() { byte[] binary = { 0x0, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0b, @@ -470,61 +470,61 @@ public void SerializeBinary() OSD llsdBinary = OSD.FromBinary(binary); string sBinarySerialized = OSDParser.SerializeLLSDNotation(llsdBinary); OSD llsdBinaryDS = OSDParser.DeserializeLLSDNotation(sBinarySerialized); - Assert.AreEqual(OSDType.Binary, llsdBinaryDS.Type); - Assert.AreEqual(binary, llsdBinaryDS.AsBinary()); + Assert.Equal(OSDType.Binary, llsdBinaryDS.Type); + Assert.Equal(binary, llsdBinaryDS.AsBinary()); } - [Test()] + [Fact] public void DeserializeArray() { string sArrayOne = "[]"; OSDArray llsdArrayOne = (OSDArray)OSDParser.DeserializeLLSDNotation(sArrayOne); - Assert.AreEqual(OSDType.Array, llsdArrayOne.Type); - Assert.AreEqual(0, llsdArrayOne.Count); + Assert.Equal(OSDType.Array, llsdArrayOne.Type); + Assert.Equal(0, llsdArrayOne.Count); string sArrayTwo = "[ i0 ]"; OSDArray llsdArrayTwo = (OSDArray)OSDParser.DeserializeLLSDNotation(sArrayTwo); - Assert.AreEqual(OSDType.Array, llsdArrayTwo.Type); - Assert.AreEqual(1, llsdArrayTwo.Count); + Assert.Equal(OSDType.Array, llsdArrayTwo.Type); + Assert.Equal(1, llsdArrayTwo.Count); OSDInteger llsdIntOne = (OSDInteger)llsdArrayTwo[0]; - Assert.AreEqual(OSDType.Integer, llsdIntOne.Type); - Assert.AreEqual(0, llsdIntOne.AsInteger()); + Assert.Equal(OSDType.Integer, llsdIntOne.Type); + Assert.Equal(0, llsdIntOne.AsInteger()); string sArrayThree = "[ i0, i1 ]"; OSDArray llsdArrayThree = (OSDArray)OSDParser.DeserializeLLSDNotation(sArrayThree); - Assert.AreEqual(OSDType.Array, llsdArrayThree.Type); - Assert.AreEqual(2, llsdArrayThree.Count); + Assert.Equal(OSDType.Array, llsdArrayThree.Type); + Assert.Equal(2, llsdArrayThree.Count); OSDInteger llsdIntTwo = (OSDInteger)llsdArrayThree[0]; - Assert.AreEqual(OSDType.Integer, llsdIntTwo.Type); - Assert.AreEqual(0, llsdIntTwo.AsInteger()); + Assert.Equal(OSDType.Integer, llsdIntTwo.Type); + Assert.Equal(0, llsdIntTwo.AsInteger()); OSDInteger llsdIntThree = (OSDInteger)llsdArrayThree[1]; - Assert.AreEqual(OSDType.Integer, llsdIntThree.Type); - Assert.AreEqual(1, llsdIntThree.AsInteger()); + Assert.Equal(OSDType.Integer, llsdIntThree.Type); + Assert.Equal(1, llsdIntThree.AsInteger()); string sArrayFour = " [ \"testtest\", \"aha\",t,f,i1, r1.2, [ i1] ] "; OSDArray llsdArrayFour = (OSDArray)OSDParser.DeserializeLLSDNotation(sArrayFour); - Assert.AreEqual(OSDType.Array, llsdArrayFour.Type); - Assert.AreEqual(7, llsdArrayFour.Count); - Assert.AreEqual("testtest", llsdArrayFour[0].AsString()); - Assert.AreEqual("aha", llsdArrayFour[1].AsString()); - Assert.AreEqual(true, llsdArrayFour[2].AsBoolean()); - Assert.AreEqual(false, llsdArrayFour[3].AsBoolean()); - Assert.AreEqual(1, llsdArrayFour[4].AsInteger()); - Assert.AreEqual(1.2d, llsdArrayFour[5].AsReal()); - Assert.AreEqual(OSDType.Array, llsdArrayFour[6].Type); + Assert.Equal(OSDType.Array, llsdArrayFour.Type); + Assert.Equal(7, llsdArrayFour.Count); + Assert.Equal("testtest", llsdArrayFour[0].AsString()); + Assert.Equal("aha", llsdArrayFour[1].AsString()); + Assert.Equal(true, llsdArrayFour[2].AsBoolean()); + Assert.Equal(false, llsdArrayFour[3].AsBoolean()); + Assert.Equal(1, llsdArrayFour[4].AsInteger()); + Assert.Equal(1.2d, llsdArrayFour[5].AsReal()); + Assert.Equal(OSDType.Array, llsdArrayFour[6].Type); OSDArray llsdArrayFive = (OSDArray)llsdArrayFour[6]; - Assert.AreEqual(1, llsdArrayFive[0].AsInteger()); + Assert.Equal(1, llsdArrayFive[0].AsInteger()); } - [Test()] + [Fact] public void SerializeArray() { OSDArray llsdOne = new OSDArray(); string sOne = OSDParser.SerializeLLSDNotation(llsdOne); OSDArray llsdOneDS = (OSDArray)OSDParser.DeserializeLLSDNotation(sOne); - Assert.AreEqual(OSDType.Array, llsdOneDS.Type); - Assert.AreEqual(0, llsdOneDS.Count); + Assert.Equal(OSDType.Array, llsdOneDS.Type); + Assert.Equal(0, llsdOneDS.Count); OSD llsdTwo = OSD.FromInteger(123234); OSD llsdThree = OSD.FromString("asedkfjhaqweiurohzasdf"); @@ -538,71 +538,71 @@ public void SerializeArray() string sFive = OSDParser.SerializeLLSDNotation(llsdOne); OSDArray llsdFive = (OSDArray)OSDParser.DeserializeLLSDNotation(sFive); - Assert.AreEqual(OSDType.Array, llsdFive.Type); - Assert.AreEqual(3, llsdFive.Count); - Assert.AreEqual(OSDType.Integer, llsdFive[0].Type); - Assert.AreEqual(123234, llsdFive[0].AsInteger()); - Assert.AreEqual(OSDType.String, llsdFive[1].Type); - Assert.AreEqual("asedkfjhaqweiurohzasdf", llsdFive[1].AsString()); + Assert.Equal(OSDType.Array, llsdFive.Type); + Assert.Equal(3, llsdFive.Count); + Assert.Equal(OSDType.Integer, llsdFive[0].Type); + Assert.Equal(123234, llsdFive[0].AsInteger()); + Assert.Equal(OSDType.String, llsdFive[1].Type); + Assert.Equal("asedkfjhaqweiurohzasdf", llsdFive[1].AsString()); OSDArray llsdSix = (OSDArray)llsdFive[2]; - Assert.AreEqual(OSDType.Array, llsdSix.Type); - Assert.AreEqual(2, llsdSix.Count); - Assert.AreEqual(OSDType.Integer, llsdSix[0].Type); - Assert.AreEqual(123234, llsdSix[0].AsInteger()); - Assert.AreEqual(OSDType.String, llsdSix[1].Type); - Assert.AreEqual("asedkfjhaqweiurohzasdf", llsdSix[1].AsString()); + Assert.Equal(OSDType.Array, llsdSix.Type); + Assert.Equal(2, llsdSix.Count); + Assert.Equal(OSDType.Integer, llsdSix[0].Type); + Assert.Equal(123234, llsdSix[0].AsInteger()); + Assert.Equal(OSDType.String, llsdSix[1].Type); + Assert.Equal("asedkfjhaqweiurohzasdf", llsdSix[1].AsString()); } - [Test()] + [Fact] public void DeserializeMap() { string sMapOne = " { } "; OSDMap llsdMapOne = (OSDMap)OSDParser.DeserializeLLSDNotation(sMapOne); - Assert.AreEqual(OSDType.Map, llsdMapOne.Type); - Assert.AreEqual(0, llsdMapOne.Count); + Assert.Equal(OSDType.Map, llsdMapOne.Type); + Assert.Equal(0, llsdMapOne.Count); string sMapTwo = " { \"test\":i2 } "; OSDMap llsdMapTwo = (OSDMap)OSDParser.DeserializeLLSDNotation(sMapTwo); - Assert.AreEqual(OSDType.Map, llsdMapTwo.Type); - Assert.AreEqual(1, llsdMapTwo.Count); - Assert.AreEqual(OSDType.Integer, llsdMapTwo["test"].Type); - Assert.AreEqual(2, llsdMapTwo["test"].AsInteger()); + Assert.Equal(OSDType.Map, llsdMapTwo.Type); + Assert.Equal(1, llsdMapTwo.Count); + Assert.Equal(OSDType.Integer, llsdMapTwo["test"].Type); + Assert.Equal(2, llsdMapTwo["test"].AsInteger()); string sMapThree = " { 'test':\"testtesttest\", 'aha':\"muahahaha\" , \"anywhere\":! } "; OSDMap llsdMapThree = (OSDMap)OSDParser.DeserializeLLSDNotation(sMapThree); - Assert.AreEqual(OSDType.Map, llsdMapThree.Type); - Assert.AreEqual(3, llsdMapThree.Count); - Assert.AreEqual(OSDType.String, llsdMapThree["test"].Type); - Assert.AreEqual("testtesttest", llsdMapThree["test"].AsString()); - Assert.AreEqual(OSDType.String, llsdMapThree["test"].Type); - Assert.AreEqual("muahahaha", llsdMapThree["aha"].AsString()); - Assert.AreEqual(OSDType.Unknown, llsdMapThree["self"].Type); + Assert.Equal(OSDType.Map, llsdMapThree.Type); + Assert.Equal(3, llsdMapThree.Count); + Assert.Equal(OSDType.String, llsdMapThree["test"].Type); + Assert.Equal("testtesttest", llsdMapThree["test"].AsString()); + Assert.Equal(OSDType.String, llsdMapThree["test"].Type); + Assert.Equal("muahahaha", llsdMapThree["aha"].AsString()); + Assert.Equal(OSDType.Unknown, llsdMapThree["self"].Type); string sMapFour = " { 'test' : { 'test' : i1, 't0st' : r2.5 }, 'tist' : \"hello world!\", 'tast' : \"last\" } "; OSDMap llsdMapFour = (OSDMap)OSDParser.DeserializeLLSDNotation(sMapFour); - Assert.AreEqual(OSDType.Map, llsdMapFour.Type); - Assert.AreEqual(3, llsdMapFour.Count); - Assert.AreEqual("hello world!", llsdMapFour["tist"].AsString()); - Assert.AreEqual("last", llsdMapFour["tast"].AsString()); + Assert.Equal(OSDType.Map, llsdMapFour.Type); + Assert.Equal(3, llsdMapFour.Count); + Assert.Equal("hello world!", llsdMapFour["tist"].AsString()); + Assert.Equal("last", llsdMapFour["tast"].AsString()); OSDMap llsdMapFive = (OSDMap)llsdMapFour["test"]; - Assert.AreEqual(OSDType.Map, llsdMapFive.Type); - Assert.AreEqual(2, llsdMapFive.Count); - Assert.AreEqual(OSDType.Integer, llsdMapFive["test"].Type); - Assert.AreEqual(1, llsdMapFive["test"].AsInteger()); - Assert.AreEqual(OSDType.Real, llsdMapFive["t0st"].Type); - Assert.AreEqual(2.5d, llsdMapFive["t0st"].AsReal()); + Assert.Equal(OSDType.Map, llsdMapFive.Type); + Assert.Equal(2, llsdMapFive.Count); + Assert.Equal(OSDType.Integer, llsdMapFive["test"].Type); + Assert.Equal(1, llsdMapFive["test"].AsInteger()); + Assert.Equal(OSDType.Real, llsdMapFive["t0st"].Type); + Assert.Equal(2.5d, llsdMapFive["t0st"].AsReal()); } - [Test()] + [Fact] public void SerializeMap() { OSDMap llsdOne = new OSDMap(); string sOne = OSDParser.SerializeLLSDNotation(llsdOne); OSDMap llsdOneDS = (OSDMap)OSDParser.DeserializeLLSDNotation(sOne); - Assert.AreEqual(OSDType.Map, llsdOneDS.Type); - Assert.AreEqual(0, llsdOneDS.Count); + Assert.Equal(OSDType.Map, llsdOneDS.Type); + Assert.Equal(0, llsdOneDS.Count); OSD llsdTwo = OSD.FromInteger(123234); OSD llsdThree = OSD.FromString("asedkfjhaqweiurohzasdf"); @@ -616,20 +616,20 @@ public void SerializeMap() string sFive = OSDParser.SerializeLLSDNotation(llsdOne); OSDMap llsdFive = (OSDMap)OSDParser.DeserializeLLSDNotation(sFive); - Assert.AreEqual(OSDType.Map, llsdFive.Type); - Assert.AreEqual(3, llsdFive.Count); - Assert.AreEqual(OSDType.Integer, llsdFive["test0"].Type); - Assert.AreEqual(123234, llsdFive["test0"].AsInteger()); - Assert.AreEqual(OSDType.String, llsdFive["test1"].Type); - Assert.AreEqual("asedkfjhaqweiurohzasdf", llsdFive["test1"].AsString()); + Assert.Equal(OSDType.Map, llsdFive.Type); + Assert.Equal(3, llsdFive.Count); + Assert.Equal(OSDType.Integer, llsdFive["test0"].Type); + Assert.Equal(123234, llsdFive["test0"].AsInteger()); + Assert.Equal(OSDType.String, llsdFive["test1"].Type); + Assert.Equal("asedkfjhaqweiurohzasdf", llsdFive["test1"].AsString()); OSDMap llsdSix = (OSDMap)llsdFive["test2"]; - Assert.AreEqual(OSDType.Map, llsdSix.Type); - Assert.AreEqual(2, llsdSix.Count); - Assert.AreEqual(OSDType.Integer, llsdSix["test0"].Type); - Assert.AreEqual(123234, llsdSix["test0"].AsInteger()); - Assert.AreEqual(OSDType.String, llsdSix["test1"].Type); - Assert.AreEqual("asedkfjhaqweiurohzasdf", llsdSix["test1"].AsString()); + Assert.Equal(OSDType.Map, llsdSix.Type); + Assert.Equal(2, llsdSix.Count); + Assert.Equal(OSDType.Integer, llsdSix["test0"].Type); + Assert.Equal(123234, llsdSix["test0"].AsInteger()); + Assert.Equal(OSDType.String, llsdSix["test1"].Type); + Assert.Equal("asedkfjhaqweiurohzasdf", llsdSix["test1"].AsString()); // We test here also for 4byte characters as map keys string xml = "𐄷"; @@ -643,12 +643,12 @@ public void SerializeMap() llsdSeven[content] = OSD.FromString(content); string sSeven = OSDParser.SerializeLLSDNotation(llsdSeven); OSDMap llsdSevenDS = (OSDMap)OSDParser.DeserializeLLSDNotation(sSeven); - Assert.AreEqual(OSDType.Map, llsdSevenDS.Type); - Assert.AreEqual(1, llsdSevenDS.Count); - Assert.AreEqual(content, llsdSevenDS[content].AsString()); + Assert.Equal(OSDType.Map, llsdSevenDS.Type); + Assert.Equal(1, llsdSevenDS.Count); + Assert.Equal(content, llsdSevenDS[content].AsString()); } - [Test()] + [Fact] public void DeserializeRealWorldExamples() { string realWorldExample = @" @@ -682,27 +682,27 @@ public void DeserializeRealWorldExamples() // We dont do full testing here. We are fine if a few values are right // and the parser doesnt throw an exception OSDArray llsdArray = (OSDArray)OSDParser.DeserializeLLSDNotation(realWorldExample); - Assert.AreEqual(OSDType.Array, llsdArray.Type); - Assert.AreEqual(3, llsdArray.Count); + Assert.Equal(OSDType.Array, llsdArray.Type); + Assert.Equal(3, llsdArray.Count); OSDMap llsdMapOne = (OSDMap)llsdArray[0]; - Assert.AreEqual(OSDType.Map, llsdMapOne.Type); - Assert.AreEqual("http://secondlife.com", llsdMapOne["destination"].AsString()); + Assert.Equal(OSDType.Map, llsdMapOne.Type); + Assert.Equal("http://secondlife.com", llsdMapOne["destination"].AsString()); OSDMap llsdMapTwo = (OSDMap)llsdArray[1]; - Assert.AreEqual(OSDType.Map, llsdMapTwo.Type); - Assert.AreEqual(OSDType.Integer, llsdMapTwo["version"].Type); - Assert.AreEqual(1, llsdMapTwo["version"].AsInteger()); + Assert.Equal(OSDType.Map, llsdMapTwo.Type); + Assert.Equal(OSDType.Integer, llsdMapTwo["version"].Type); + Assert.Equal(1, llsdMapTwo["version"].AsInteger()); OSDMap llsdMapThree = (OSDMap)llsdArray[2]; - Assert.AreEqual(OSDType.UUID, llsdMapThree["session_id"].Type); - Assert.AreEqual("2c585cec-038c-40b0-b42e-a25ebab4d132", llsdMapThree["session_id"].AsString()); - Assert.AreEqual(OSDType.UUID, llsdMapThree["agent_id"].Type); - Assert.AreEqual("3c115e51-04f4-523c-9fa6-98aff1034730", llsdMapThree["agent_id"].AsString()); + Assert.Equal(OSDType.UUID, llsdMapThree["session_id"].Type); + Assert.Equal("2c585cec-038c-40b0-b42e-a25ebab4d132", llsdMapThree["session_id"].AsString()); + Assert.Equal(OSDType.UUID, llsdMapThree["agent_id"].Type); + Assert.Equal("3c115e51-04f4-523c-9fa6-98aff1034730", llsdMapThree["agent_id"].AsString()); } - [Test()] + [Fact] public void SerializeFormattedTest() { // This is not a real test. Instead look at the console.out tab for how formatted notation looks like. @@ -732,14 +732,14 @@ public void SerializeFormattedTest() // we also try to parse this... and look a little at the results OSDArray llsdSeven = (OSDArray)OSDParser.DeserializeLLSDNotation(sThree); - Assert.AreEqual(OSDType.Array, llsdSeven.Type); - Assert.AreEqual(3, llsdSeven.Count); - Assert.AreEqual(OSDType.Integer, llsdSeven[0].Type); - Assert.AreEqual(1, llsdSeven[0].AsInteger()); - Assert.AreEqual(OSDType.Integer, llsdSeven[1].Type); - Assert.AreEqual(1, llsdSeven[1].AsInteger()); - - Assert.AreEqual(OSDType.Map, llsdSeven[2].Type); + Assert.Equal(OSDType.Array, llsdSeven.Type); + Assert.Equal(3, llsdSeven.Count); + Assert.Equal(OSDType.Integer, llsdSeven[0].Type); + Assert.Equal(1, llsdSeven[0].AsInteger()); + Assert.Equal(OSDType.Integer, llsdSeven[1].Type); + Assert.Equal(1, llsdSeven[1].AsInteger()); + + Assert.Equal(OSDType.Map, llsdSeven[2].Type); // thats enough for now. } } diff --git a/OpenMetaverse.Tests/OpenMetaverse.Tests.csproj b/OpenMetaverse.Tests/OpenMetaverse.Tests.csproj index 90d0b5bf..f59215b3 100644 --- a/OpenMetaverse.Tests/OpenMetaverse.Tests.csproj +++ b/OpenMetaverse.Tests/OpenMetaverse.Tests.csproj @@ -1,13 +1,14 @@  Local - net48 - True - 1591,1574,0419,0618 + true + false - - + + + + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/OpenMetaverse.Tests/PacketTests.cs b/OpenMetaverse.Tests/PacketTests.cs index 6abab3cf..907963cf 100644 --- a/OpenMetaverse.Tests/PacketTests.cs +++ b/OpenMetaverse.Tests/PacketTests.cs @@ -24,15 +24,15 @@ * POSSIBILITY OF SUCH DAMAGE. */ -using NUnit.Framework; +using Xunit; using OpenMetaverse.Packets; namespace OpenMetaverse.Tests { - [TestFixture] - public class PacketTests : Assert + + public class PacketTests { - [Test] + [Fact] public void HeaderFlags() { TestMessagePacket packet = new TestMessagePacket(); @@ -42,53 +42,53 @@ public void HeaderFlags() packet.Header.Resent = false; packet.Header.Zerocoded = false; - Assert.IsFalse(packet.Header.AppendedAcks, "AppendedAcks: Failed to initially set the flag to false"); - Assert.IsFalse(packet.Header.Reliable, "Reliable: Failed to initially set the flag to false"); - Assert.IsFalse(packet.Header.Resent, "Resent: Failed to initially set the flag to false"); - Assert.IsFalse(packet.Header.Zerocoded, "Zerocoded: Failed to initially set the flag to false"); + Assert.False(packet.Header.AppendedAcks, "AppendedAcks: Failed to initially set the flag to false"); + Assert.False(packet.Header.Reliable, "Reliable: Failed to initially set the flag to false"); + Assert.False(packet.Header.Resent, "Resent: Failed to initially set the flag to false"); + Assert.False(packet.Header.Zerocoded, "Zerocoded: Failed to initially set the flag to false"); packet.Header.AppendedAcks = false; packet.Header.Reliable = false; packet.Header.Resent = false; packet.Header.Zerocoded = false; - Assert.IsFalse(packet.Header.AppendedAcks, "AppendedAcks: Failed to set the flag to false a second time"); - Assert.IsFalse(packet.Header.Reliable, "Reliable: Failed to set the flag to false a second time"); - Assert.IsFalse(packet.Header.Resent, "Resent: Failed to set the flag to false a second time"); - Assert.IsFalse(packet.Header.Zerocoded, "Zerocoded: Failed to set the flag to false a second time"); + Assert.False(packet.Header.AppendedAcks, "AppendedAcks: Failed to set the flag to false a second time"); + Assert.False(packet.Header.Reliable, "Reliable: Failed to set the flag to false a second time"); + Assert.False(packet.Header.Resent, "Resent: Failed to set the flag to false a second time"); + Assert.False(packet.Header.Zerocoded, "Zerocoded: Failed to set the flag to false a second time"); packet.Header.AppendedAcks = true; packet.Header.Reliable = true; packet.Header.Resent = true; packet.Header.Zerocoded = true; - Assert.IsTrue(packet.Header.AppendedAcks, "AppendedAcks: Failed to set the flag to true"); - Assert.IsTrue(packet.Header.Reliable, "Reliable: Failed to set the flag to true"); - Assert.IsTrue(packet.Header.Resent, "Resent: Failed to set the flag to true"); - Assert.IsTrue(packet.Header.Zerocoded, "Zerocoded: Failed to set the flag to true"); + Assert.True(packet.Header.AppendedAcks, "AppendedAcks: Failed to set the flag to true"); + Assert.True(packet.Header.Reliable, "Reliable: Failed to set the flag to true"); + Assert.True(packet.Header.Resent, "Resent: Failed to set the flag to true"); + Assert.True(packet.Header.Zerocoded, "Zerocoded: Failed to set the flag to true"); packet.Header.AppendedAcks = true; packet.Header.Reliable = true; packet.Header.Resent = true; packet.Header.Zerocoded = true; - Assert.IsTrue(packet.Header.AppendedAcks, "AppendedAcks: Failed to set the flag to true a second time"); - Assert.IsTrue(packet.Header.Reliable, "Reliable: Failed to set the flag to true a second time"); - Assert.IsTrue(packet.Header.Resent, "Resent: Failed to set the flag to true a second time"); - Assert.IsTrue(packet.Header.Zerocoded, "Zerocoded: Failed to set the flag to true a second time"); + Assert.True(packet.Header.AppendedAcks, "AppendedAcks: Failed to set the flag to true a second time"); + Assert.True(packet.Header.Reliable, "Reliable: Failed to set the flag to true a second time"); + Assert.True(packet.Header.Resent, "Resent: Failed to set the flag to true a second time"); + Assert.True(packet.Header.Zerocoded, "Zerocoded: Failed to set the flag to true a second time"); packet.Header.AppendedAcks = false; packet.Header.Reliable = false; packet.Header.Resent = false; packet.Header.Zerocoded = false; - Assert.IsFalse(packet.Header.AppendedAcks, "AppendedAcks: Failed to set the flag back to false"); - Assert.IsFalse(packet.Header.Reliable, "Reliable: Failed to set the flag back to false"); - Assert.IsFalse(packet.Header.Resent, "Resent: Failed to set the flag back to false"); - Assert.IsFalse(packet.Header.Zerocoded, "Zerocoded: Failed to set the flag back to false"); + Assert.False(packet.Header.AppendedAcks, "AppendedAcks: Failed to set the flag back to false"); + Assert.False(packet.Header.Reliable, "Reliable: Failed to set the flag back to false"); + Assert.False(packet.Header.Resent, "Resent: Failed to set the flag back to false"); + Assert.False(packet.Header.Zerocoded, "Zerocoded: Failed to set the flag back to false"); } - [Test] + [Fact] public void ToBytesMultiple() { UUID testID = UUID.Random(); @@ -131,16 +131,16 @@ public void ToBytesMultiple() for (int i = 0; i < splitPackets.Length; i++) { byte[] packetData = splitPackets[i]; - int len = packetData.Length - 1; + int len = packetData.Length; DirPlacesReplyPacket packet = (DirPlacesReplyPacket)Packet.BuildPacket(packetData, ref len, packetData); - Assert.IsTrue(packet.AgentData.AgentID == bigPacket.AgentData.AgentID); + Assert.True(packet.AgentData.AgentID == bigPacket.AgentData.AgentID); for (int j = 0; j < packet.QueryReplies.Length; j++) { - Assert.IsTrue(packet.QueryReplies[j].Dwell == (float)(queryRepliesCount + j), + Assert.True(packet.QueryReplies[j].Dwell == (float)(queryRepliesCount + j), "Expected Dwell of " + (float)(queryRepliesCount + j) + " but got " + packet.QueryReplies[j].Dwell); - Assert.IsTrue(packet.QueryReplies[j].ParcelID == testID); + Assert.True(packet.QueryReplies[j].ParcelID == testID); } queryDataCount += packet.QueryData.Length; @@ -148,9 +148,9 @@ public void ToBytesMultiple() statusDataCount += packet.StatusData.Length; } - Assert.IsTrue(queryDataCount == bigPacket.QueryData.Length); - Assert.IsTrue(queryRepliesCount == bigPacket.QueryData.Length); - Assert.IsTrue(statusDataCount == bigPacket.StatusData.Length); + Assert.True(queryDataCount == bigPacket.QueryData.Length); + Assert.True(queryRepliesCount == bigPacket.QueryData.Length); + Assert.True(statusDataCount == bigPacket.StatusData.Length); ScriptDialogPacket scriptDialogPacket = new ScriptDialogPacket(); scriptDialogPacket.Data.ChatChannel = 0; @@ -167,8 +167,8 @@ public void ToBytesMultiple() byte[][] splitPacket = scriptDialogPacket.ToBytesMultiple(); - Assert.IsNotNull(splitPacket); - Assert.IsTrue(splitPacket.Length == 1, "Expected ScriptDialog packet to split into 1 packet but got " + splitPacket.Length); + Assert.NotNull(splitPacket); + Assert.True(splitPacket.Length == 1, "Expected ScriptDialog packet to split into 1 packet but got " + splitPacket.Length); ParcelReturnObjectsPacket proPacket = new ParcelReturnObjectsPacket(); proPacket.AgentData.AgentID = UUID.Zero; @@ -182,8 +182,8 @@ public void ToBytesMultiple() splitPacket = proPacket.ToBytesMultiple(); - Assert.IsNotNull(splitPacket); - Assert.IsTrue(splitPacket.Length == 1, "Expected ParcelReturnObjectsPacket packet to split into 1 packet but got " + splitPacket.Length); + Assert.NotNull(splitPacket); + Assert.True(splitPacket.Length == 1, "Expected ParcelReturnObjectsPacket packet to split into 1 packet but got " + splitPacket.Length); InventoryDescendentsPacket invPacket = new InventoryDescendentsPacket(); invPacket.FolderData = new InventoryDescendentsPacket.FolderDataBlock[1]; @@ -199,15 +199,15 @@ public void ToBytesMultiple() splitPacket = invPacket.ToBytesMultiple(); - Assert.IsNotNull(splitPacket); - Assert.IsTrue(splitPacket.Length == 1, "Split InventoryDescendents packet into " + splitPacket.Length + " instead of 1 packet"); + Assert.NotNull(splitPacket); + Assert.True(splitPacket.Length == 1, "Split InventoryDescendents packet into " + splitPacket.Length + " instead of 1 packet"); int x = 0; int y = splitPacket[0].Length - 1; invPacket.FromBytes(splitPacket[0], ref x, ref y, null); - Assert.IsTrue(invPacket.FolderData.Length == 1, "InventoryDescendents packet came back with " + invPacket.FolderData.Length + " FolderData blocks"); - Assert.IsTrue(invPacket.ItemData.Length == 5, "InventoryDescendents packet came back with " + invPacket.ItemData.Length + " ItemData blocks"); + Assert.True(invPacket.FolderData.Length == 1, "InventoryDescendents packet came back with " + invPacket.FolderData.Length + " FolderData blocks"); + Assert.True(invPacket.ItemData.Length == 5, "InventoryDescendents packet came back with " + invPacket.ItemData.Length + " ItemData blocks"); } } } diff --git a/OpenMetaverse.Tests/PrimObjectTests.cs b/OpenMetaverse.Tests/PrimObjectTests.cs index d8d5a861..81b4fcfe 100644 --- a/OpenMetaverse.Tests/PrimObjectTests.cs +++ b/OpenMetaverse.Tests/PrimObjectTests.cs @@ -24,15 +24,15 @@ * POSSIBILITY OF SUCH DAMAGE. */ -using NUnit.Framework; +using Xunit; using System; namespace OpenMetaverse.Tests { - [TestFixture] - public class PrimObjectTests : Assert + + public class PrimObjectTests { - [Test] + [Fact] public void PathBegin() { for (byte i = 0; i < byte.MaxValue; i++) @@ -40,12 +40,12 @@ public void PathBegin() float floatValue = Primitive.UnpackBeginCut(i); ushort result = Primitive.PackBeginCut(floatValue); - Assert.IsTrue(result == i, "Started with " + i + ", float value was " + floatValue + + Assert.True(result == i, "Started with " + i + ", float value was " + floatValue + ", and ended up with " + result); } } - [Test] + [Fact] public void PathEnd() { for (byte i = 0; i < byte.MaxValue; i++) @@ -53,12 +53,12 @@ public void PathEnd() float floatValue = Primitive.UnpackEndCut(i); ushort result = Primitive.PackEndCut(floatValue); - Assert.IsTrue(result == i, "Started with " + i + ", float value was " + floatValue + + Assert.True(result == i, "Started with " + i + ", float value was " + floatValue + ", and ended up with " + result); } } - [Test] + [Fact] public void PathRevolutions() { for (byte i = 0; i < byte.MaxValue; i++) @@ -66,12 +66,12 @@ public void PathRevolutions() float floatValue = Primitive.UnpackPathRevolutions(i); byte result = Primitive.PackPathRevolutions(floatValue); - Assert.IsTrue(result == i, "Started with " + i + ", float value was " + floatValue + + Assert.True(result == i, "Started with " + i + ", float value was " + floatValue + ", and ended up with " + result); } } - [Test] + [Fact] public void PathScale() { for (byte i = 0; i < byte.MaxValue; i++) @@ -79,12 +79,12 @@ public void PathScale() float floatValue = Primitive.UnpackPathScale(i); byte result = Primitive.PackPathScale(floatValue); - Assert.IsTrue(result == i, "Started with " + i + ", float value was " + floatValue + + Assert.True(result == i, "Started with " + i + ", float value was " + floatValue + ", and ended up with " + result); } } - //[Test] + //[Fact] //public void PathShear() //{ // for (byte i = 0; i < byte.MaxValue; i++) @@ -92,12 +92,12 @@ public void PathScale() // float floatValue = Primitive.UnpackPathShear(i); // byte result = Primitive.PackPathShear(floatValue); - // Assert.IsTrue(result == i, "Started with " + i + ", float value was " + floatValue + + // Assert.True(result == i, "Started with " + i + ", float value was " + floatValue + // ", and ended up with " + result); // } //} - [Test] + [Fact] public void PathTaper() { for (sbyte i = sbyte.MinValue; i < sbyte.MaxValue; i++) @@ -105,12 +105,12 @@ public void PathTaper() float floatValue = Primitive.UnpackPathTaper(i); sbyte result = Primitive.PackPathTaper(floatValue); - Assert.IsTrue(result == i, "Started with " + i + ", float value was " + floatValue + + Assert.True(result == i, "Started with " + i + ", float value was " + floatValue + ", and ended up with " + result); } } - [Test] + [Fact] public void TextureEntryOffsets() { for (float i = -1.0f; i <= 1.0f; i += 0.001f) @@ -121,11 +121,11 @@ public void TextureEntryOffsets() float foffset = Helpers.TEOffsetFloat(BitConverter.GetBytes(offset), 0); foffset = (float)Math.Round(foffset, 3); - Assert.IsTrue(foffset - i < Single.Epsilon, foffset + " is not equal to " + i); + Assert.True(foffset - i < Single.Epsilon, foffset + " is not equal to " + i); } } - [Test] + [Fact] public void TextureEntry() { Primitive.TextureEntry te = new Primitive.TextureEntry(UUID.Random()); @@ -149,11 +149,11 @@ public void TextureEntry() byte[] teBytes2 = te2.GetBytes(); - Assert.IsTrue(teBytes.Length == teBytes2.Length); + Assert.True(teBytes.Length == teBytes2.Length); for (int i = 0; i < teBytes.Length; i++) { - Assert.IsTrue(teBytes[i] == teBytes2[i], "Byte " + i + " is not equal"); + Assert.True(teBytes[i] == teBytes2[i], "Byte " + i + " is not equal"); } } } diff --git a/OpenMetaverse.Tests/TypeTests.cs b/OpenMetaverse.Tests/TypeTests.cs index 1e960713..8e94c27c 100644 --- a/OpenMetaverse.Tests/TypeTests.cs +++ b/OpenMetaverse.Tests/TypeTests.cs @@ -24,24 +24,24 @@ * POSSIBILITY OF SUCH DAMAGE. */ -using NUnit.Framework; +using Xunit; using OpenMetaverse.StructuredData; using System; using System.Collections.Generic; namespace OpenMetaverse.Tests { - [TestFixture] - public class TypeTests : Assert + + public class TypeTests { - [Test] + [Fact] public void UUIDs() { // Creation UUID a = new UUID(); byte[] bytes = a.GetBytes(); for (int i = 0; i < 16; i++) - Assert.IsTrue(bytes[i] == 0x00); + Assert.True(bytes[i] == 0x00); // Comparison a = new UUID(new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, @@ -49,7 +49,7 @@ public void UUIDs() UUID b = new UUID(new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F }, 0); - Assert.IsTrue(a == b, "UUID comparison operator failed, " + a.ToString() + " should equal " + + Assert.True(a == b, "UUID comparison operator failed, " + a.ToString() + " should equal " + b.ToString()); // From string @@ -58,45 +58,45 @@ public void UUIDs() string zeroonetwo = "00010203-0405-0607-0809-0a0b0c0d0e0f"; b = new UUID(zeroonetwo); - Assert.IsTrue(a == b, "UUID hyphenated string constructor failed, should have " + a.ToString() + + Assert.True(a == b, "UUID hyphenated string constructor failed, should have " + a.ToString() + " but we got " + b.ToString()); // ToString() - Assert.IsTrue(a == b); - Assert.IsTrue(a == (UUID)zeroonetwo); + Assert.True(a == b); + Assert.True(a == (UUID)zeroonetwo); // TODO: CRC test } - [Test] + [Fact] public void Vector3ApproxEquals() { Vector3 a = new Vector3(1f, 0f, 0f); Vector3 b = new Vector3(0f, 0f, 0f); - Assert.IsFalse(a.ApproxEquals(b, 0.9f), "ApproxEquals failed (1)"); - Assert.IsTrue(a.ApproxEquals(b, 1.0f), "ApproxEquals failed (2)"); + Assert.False(a.ApproxEquals(b, 0.9f), "ApproxEquals failed (1)"); + Assert.True(a.ApproxEquals(b, 1.0f), "ApproxEquals failed (2)"); a = new Vector3(-1f, 0f, 0f); b = new Vector3(1f, 0f, 0f); - Assert.IsFalse(a.ApproxEquals(b, 1.9f), "ApproxEquals failed (3)"); - Assert.IsTrue(a.ApproxEquals(b, 2.0f), "ApproxEquals failed (4)"); + Assert.False(a.ApproxEquals(b, 1.9f), "ApproxEquals failed (3)"); + Assert.True(a.ApproxEquals(b, 2.0f), "ApproxEquals failed (4)"); a = new Vector3(0f, -1f, 0f); b = new Vector3(0f, -1.1f, 0f); - Assert.IsFalse(a.ApproxEquals(b, 0.09f), "ApproxEquals failed (5)"); - Assert.IsTrue(a.ApproxEquals(b, 0.11f), "ApproxEquals failed (6)"); + Assert.False(a.ApproxEquals(b, 0.09f), "ApproxEquals failed (5)"); + Assert.True(a.ApproxEquals(b, 0.11f), "ApproxEquals failed (6)"); a = new Vector3(0f, 0f, 0.00001f); b = new Vector3(0f, 0f, 0f); - Assert.IsFalse(b.ApproxEquals(a, Single.Epsilon), "ApproxEquals failed (6)"); - Assert.IsTrue(b.ApproxEquals(a, 0.0001f), "ApproxEquals failed (7)"); + Assert.False(b.ApproxEquals(a, Single.Epsilon), "ApproxEquals failed (6)"); + Assert.True(b.ApproxEquals(a, 0.0001f), "ApproxEquals failed (7)"); } - [Test] + [Fact] public void VectorCasting() { Dictionary testNumbers; @@ -133,41 +133,41 @@ public void VectorCasting() } else { - Assert.IsFalse(a == b, string.Format( + Assert.False(a == b, string.Format( "Vector casting failed, precision loss should" + " have occurred. " + "{0}: {1}, {2}", kvp.Key, a.X, b.X)); - Assert.IsFalse(b == d, string.Format( + Assert.False(b == d, string.Format( "Vector casting failed, explicit cast of double" + " to float should result in precision loss" + " whichwas should not magically disappear when" + " Vector3 is implicitly cast to Vector3d." + " {0}: {1}, {2}", kvp.Key, b.X, d.X)); } - Assert.IsTrue(a == c, string.Format( + Assert.True(a == c, string.Format( "Vector casting failed, Vector3 compared to" + " explicit cast of Vector3d to Vector3 should" + " result in identical precision loss." + " {0}: {1}, {2}", kvp.Key, a.X, c.X)); - Assert.IsTrue(a == d, string.Format( + Assert.True(a == d, string.Format( "Vector casting failed, implicit cast of Vector3" + " to Vector3d should not result in precision loss." + " {0}: {1}, {2}", kvp.Key, a.X, d.X)); } } - [Test] + [Fact] public void Quaternions() { Quaternion a = new Quaternion(1, 0, 0, 0); Quaternion b = new Quaternion(1, 0, 0, 0); - Assert.IsTrue(a == b, "Quaternion comparison operator failed"); + Assert.True(a == b, "Quaternion comparison operator failed"); Quaternion expected = new Quaternion(0, 0, 0, -1); Quaternion result = a * b; - Assert.IsTrue(result == expected, a.ToString() + " * " + b.ToString() + " produced " + result.ToString() + + Assert.True(result == expected, a.ToString() + " * " + b.ToString() + " produced " + result.ToString() + " instead of " + expected.ToString()); a = new Quaternion(1, 0, 0, 0); @@ -175,7 +175,7 @@ public void Quaternions() expected = new Quaternion(0, 0, 1, 0); result = a * b; - Assert.IsTrue(result == expected, a.ToString() + " * " + b.ToString() + " produced " + result.ToString() + + Assert.True(result == expected, a.ToString() + " * " + b.ToString() + " produced " + result.ToString() + " instead of " + expected.ToString()); a = new Quaternion(0, 0, 1, 0); @@ -183,11 +183,11 @@ public void Quaternions() expected = new Quaternion(-1, 0, 0, 0); result = a * b; - Assert.IsTrue(result == expected, a.ToString() + " * " + b.ToString() + " produced " + result.ToString() + + Assert.True(result == expected, a.ToString() + " * " + b.ToString() + " produced " + result.ToString() + " instead of " + expected.ToString()); } - [Test] + [Fact] public void testMatrix() { Matrix4 matrix = new Matrix4(0, 0, 74, 1, @@ -196,10 +196,10 @@ public void testMatrix() 0, 0, 0, 0); /* determinant of singular matrix returns zero */ - Assert.AreEqual(0d, (double)matrix.Determinant(), 0.001d); + Assert.InRange((double)matrix.Determinant(), -0.001d, 0.001d); /* inverse of identity matrix is the identity matrix */ - Assert.IsTrue(Matrix4.Identity == Matrix4.Inverse(Matrix4.Identity)); + Assert.True(Matrix4.Identity == Matrix4.Inverse(Matrix4.Identity)); /* inverse of non-singular matrix returns True And InverseMatrix */ matrix = new Matrix4(1, 1, 0, 0, @@ -210,10 +210,10 @@ public void testMatrix() 1, -1, 1, 0, -1, 1, 0, 0, 0, 0, 0, 1); - Assert.AreEqual(expectedInverse, Matrix4.Inverse(matrix)); + Assert.Equal(expectedInverse, Matrix4.Inverse(matrix)); } - //[Test] + //[Fact] //public void VectorQuaternionMath() //{ // // Convert a vector to a quaternion and back @@ -222,10 +222,10 @@ public void testMatrix() // Vector3 c; // b.GetEulerAngles(out c.X, out c.Y, out c.Z); - // Assert.IsTrue(a == c, c.ToString() + " does not equal " + a.ToString()); + // Assert.True(a == c, c.ToString() + " does not equal " + a.ToString()); //} - [Test] + [Fact] public void FloatsToTerseStrings() { float f = 1.20f; @@ -233,55 +233,55 @@ public void FloatsToTerseStrings() string b = "1.2"; a = Helpers.FloatToTerseString(f); - Assert.IsTrue(a == b, f.ToString() + " converted to " + a + ", expecting " + b); + Assert.True(a == b, f.ToString() + " converted to " + a + ", expecting " + b); f = 24.00f; b = "24"; a = Helpers.FloatToTerseString(f); - Assert.IsTrue(a == b, f.ToString() + " converted to " + a + ", expecting " + b); + Assert.True(a == b, f.ToString() + " converted to " + a + ", expecting " + b); f = -0.59f; b = "-.59"; a = Helpers.FloatToTerseString(f); - Assert.IsTrue(a == b, f.ToString() + " converted to " + a + ", expecting " + b); + Assert.True(a == b, f.ToString() + " converted to " + a + ", expecting " + b); f = 0.59f; b = ".59"; a = Helpers.FloatToTerseString(f); - Assert.IsTrue(a == b, f.ToString() + " converted to " + a + ", expecting " + b); + Assert.True(a == b, f.ToString() + " converted to " + a + ", expecting " + b); } - [Test] + [Fact] public void BitUnpacking() { byte[] data = new byte[] { 0x80, 0x00, 0x0F, 0x50, 0x83, 0x7D }; BitPack bitpacker = new BitPack(data, 0); int b = bitpacker.UnpackBits(1); - Assert.IsTrue(b == 1, "Unpacked " + b + " instead of 1"); + Assert.True(b == 1, "Unpacked " + b + " instead of 1"); b = bitpacker.UnpackBits(1); - Assert.IsTrue(b == 0, "Unpacked " + b + " instead of 0"); + Assert.True(b == 0, "Unpacked " + b + " instead of 0"); bitpacker = new BitPack(data, 2); b = bitpacker.UnpackBits(4); - Assert.IsTrue(b == 0, "Unpacked " + b + " instead of 0"); + Assert.True(b == 0, "Unpacked " + b + " instead of 0"); b = bitpacker.UnpackBits(8); - Assert.IsTrue(b == 0xF5, "Unpacked " + b + " instead of 0xF5"); + Assert.True(b == 0xF5, "Unpacked " + b + " instead of 0xF5"); b = bitpacker.UnpackBits(4); - Assert.IsTrue(b == 0, "Unpacked " + b + " instead of 0"); + Assert.True(b == 0, "Unpacked " + b + " instead of 0"); b = bitpacker.UnpackBits(10); - Assert.IsTrue(b == 0x0183, "Unpacked " + b + " instead of 0x0183"); + Assert.True(b == 0x0183, "Unpacked " + b + " instead of 0x0183"); } - [Test] + [Fact] public void BitPacking() { byte[] packedBytes = new byte[12]; @@ -295,16 +295,16 @@ public void BitPacking() bitpacker = new BitPack(packedBytes, 0); int b = bitpacker.UnpackBits(32); - Assert.IsTrue(b == 0x0ABBCCDD, "Unpacked " + b + " instead of 2864434397"); + Assert.True(b == 0x0ABBCCDD, "Unpacked " + b + " instead of 2864434397"); b = bitpacker.UnpackBits(5); - Assert.IsTrue(b == 25, "Unpacked " + b + " instead of 25"); + Assert.True(b == 25, "Unpacked " + b + " instead of 25"); float f = bitpacker.UnpackFloat(); - Assert.IsTrue(f == 123.321f, "Unpacked " + f + " instead of 123.321"); + Assert.True(f == 123.321f, "Unpacked " + f + " instead of 123.321"); b = bitpacker.UnpackBits(16); - Assert.IsTrue(b == 1000, "Unpacked " + b + " instead of 1000"); + Assert.True(b == 1000, "Unpacked " + b + " instead of 1000"); packedBytes = new byte[1]; bitpacker = new BitPack(packedBytes, 0); @@ -312,7 +312,7 @@ public void BitPacking() bitpacker = new BitPack(packedBytes, 0); b = bitpacker.UnpackBits(1); - Assert.IsTrue(b == 1, "Unpacked " + b + " instead of 1"); + Assert.True(b == 1, "Unpacked " + b + " instead of 1"); packedBytes = new byte[1]{255}; bitpacker = new BitPack(packedBytes, 0, 0); // tell to append @@ -320,10 +320,10 @@ public void BitPacking() bitpacker = new BitPack(packedBytes, 0); b = bitpacker.UnpackBits(1); - Assert.IsTrue(b == 0, "Unpacked " + b + " instead of 0"); + Assert.True(b == 0, "Unpacked " + b + " instead of 0"); } - [Test] + [Fact] public void LLSDTerseParsing() { string testOne = "[r0.99967899999999998428,r-0.025334599999999998787,r0]"; @@ -331,35 +331,35 @@ public void LLSDTerseParsing() string testThree = "{'region_handle':[r255232, r256512], 'position':[r33.6, r33.71, r43.13], 'look_at':[r34.6, r33.71, r43.13]}"; OSD obj = OSDParser.DeserializeLLSDNotation(testOne); - Assert.IsInstanceOf(typeof(OSDArray), obj, "Expected SDArray, got " + obj.GetType().ToString()); + Assert.True(obj is OSDArray, "Expected SDArray, got " + obj.GetType().ToString()); OSDArray array = (OSDArray)obj; - Assert.IsTrue(array.Count == 3, "Expected three contained objects, got " + array.Count); - Assert.IsTrue(array[0].AsReal() > 0.9d && array[0].AsReal() < 1.0d, "Unexpected value for first real " + array[0].AsReal()); - Assert.IsTrue(array[1].AsReal() < 0.0d && array[1].AsReal() > -0.03d, "Unexpected value for second real " + array[1].AsReal()); - Assert.IsTrue(array[2].AsReal() == 0.0d, "Unexpected value for third real " + array[2].AsReal()); + Assert.True(array.Count == 3, "Expected three contained objects, got " + array.Count); + Assert.True(array[0].AsReal() > 0.9d && array[0].AsReal() < 1.0d, "Unexpected value for first real " + array[0].AsReal()); + Assert.True(array[1].AsReal() < 0.0d && array[1].AsReal() > -0.03d, "Unexpected value for second real " + array[1].AsReal()); + Assert.True(array[2].AsReal() == 0.0d, "Unexpected value for third real " + array[2].AsReal()); obj = OSDParser.DeserializeLLSDNotation(testTwo); - Assert.IsInstanceOf(typeof(OSDArray), obj, "Expected SDArray, got " + obj.GetType().ToString()); + Assert.True(obj is OSDArray, "Expected SDArray, got " + obj.GetType().ToString()); array = (OSDArray)obj; - Assert.IsTrue(array.Count == 2, "Expected two contained objects, got " + array.Count); - Assert.IsTrue(array[1].AsReal() == 0.0d, "Unexpected value for real " + array[1].AsReal()); + Assert.True(array.Count == 2, "Expected two contained objects, got " + array.Count); + Assert.True(array[1].AsReal() == 0.0d, "Unexpected value for real " + array[1].AsReal()); obj = array[0]; - Assert.IsInstanceOf(typeof(OSDArray), obj, "Expected ArrayList, got " + obj.GetType().ToString()); + Assert.True(obj is OSDArray, "Expected ArrayList, got " + obj.GetType().ToString()); array = (OSDArray)obj; - Assert.IsTrue(array[0].AsReal() == 1.0d && array[1].AsReal() == 1.0d && array[2].AsReal() == 1.0d, + Assert.True(array[0].AsReal() == 1.0d && array[1].AsReal() == 1.0d && array[2].AsReal() == 1.0d, "Unexpected value(s) for nested array: " + array[0].AsReal() + ", " + array[1].AsReal() + ", " + array[2].AsReal()); obj = OSDParser.DeserializeLLSDNotation(testThree); - Assert.IsInstanceOf(typeof(OSDMap), obj, "Expected LLSDMap, got " + obj.GetType().ToString()); + Assert.True(obj is OSDMap, "Expected LLSDMap, got " + obj.GetType().ToString()); OSDMap hashtable = (OSDMap)obj; - Assert.IsTrue(hashtable.Count == 3, "Expected three contained objects, got " + hashtable.Count); - Assert.IsInstanceOf(typeof(OSDArray), hashtable["region_handle"]); - Assert.IsTrue(((OSDArray)hashtable["region_handle"]).Count == 2); - Assert.IsInstanceOf(typeof(OSDArray), hashtable["position"]); - Assert.IsTrue(((OSDArray)hashtable["position"]).Count == 3); - Assert.IsInstanceOf(typeof(OSDArray), hashtable["look_at"]); - Assert.IsTrue(((OSDArray)hashtable["look_at"]).Count == 3); + Assert.True(hashtable.Count == 3, "Expected three contained objects, got " + hashtable.Count); + Assert.IsType(hashtable["region_handle"]); + Assert.True(((OSDArray)hashtable["region_handle"]).Count == 2); + Assert.IsType(hashtable["position"]); + Assert.True(((OSDArray)hashtable["position"]).Count == 3); + Assert.IsType(hashtable["look_at"]); + Assert.True(((OSDArray)hashtable["look_at"]).Count == 3); } } } diff --git a/OpenMetaverse.Tests/XmlLLSDTests.cs b/OpenMetaverse.Tests/XmlLLSDTests.cs index cc3a7bbe..81242099 100644 --- a/OpenMetaverse.Tests/XmlLLSDTests.cs +++ b/OpenMetaverse.Tests/XmlLLSDTests.cs @@ -24,7 +24,7 @@ * POSSIBILITY OF SUCH DAMAGE. */ -using NUnit.Framework; +using Xunit; using OpenMetaverse.StructuredData; using System; using System.Text; @@ -35,7 +35,7 @@ namespace OpenMetaverse.Tests /// XmlSDTests is a suite of tests for libsl implementation of the SD XML format. /// /// - [TestFixture] + public class XmlSDTests { /// @@ -43,7 +43,7 @@ public class XmlSDTests /// The LLSD string in the test is a pared down version of the sample on the blog. /// http://wiki.secondlife.com/wiki/LLSD /// - [Test] + [Fact] public void DeserializeLLSDSample() { OSD theSD = null; @@ -83,80 +83,80 @@ public void DeserializeLLSDSample() theSD = OSDParser.DeserializeLLSDXml(bytes); //Confirm the contents - Assert.IsNotNull(theSD); - Assert.IsTrue(theSD is OSDMap); - Assert.IsTrue(theSD.Type == OSDType.Map); + Assert.NotNull(theSD); + Assert.True(theSD is OSDMap); + Assert.True(theSD.Type == OSDType.Map); map = (OSDMap)theSD; tempSD = map["region_id"]; - Assert.IsNotNull(tempSD); - Assert.IsTrue(tempSD is OSDUUID); - Assert.IsTrue(tempSD.Type == OSDType.UUID); + Assert.NotNull(tempSD); + Assert.True(tempSD is OSDUUID); + Assert.True(tempSD.Type == OSDType.UUID); tempUUID = (OSDUUID)tempSD; - Assert.AreEqual(new UUID("67153d5b-3659-afb4-8510-adda2c034649"), tempUUID.AsUUID()); + Assert.Equal(new UUID("67153d5b-3659-afb4-8510-adda2c034649"), tempUUID.AsUUID()); tempSD = map["scale"]; - Assert.IsNotNull(tempSD); - Assert.IsTrue(tempSD is OSDString); - Assert.IsTrue(tempSD.Type == OSDType.String); + Assert.NotNull(tempSD); + Assert.True(tempSD is OSDString); + Assert.True(tempSD.Type == OSDType.String); tempStr = (OSDString)tempSD; - Assert.AreEqual("one minute", tempStr.AsString()); + Assert.Equal("one minute", tempStr.AsString()); tempSD = map["simulator statistics"]; - Assert.IsNotNull(tempSD); - Assert.IsTrue(tempSD is OSDMap); - Assert.IsTrue(tempSD.Type == OSDType.Map); + Assert.NotNull(tempSD); + Assert.True(tempSD is OSDMap); + Assert.True(tempSD.Type == OSDType.Map); map = (OSDMap)tempSD; tempSD = map["time dilation"]; - Assert.IsNotNull(tempSD); - Assert.IsTrue(tempSD is OSDReal); - Assert.IsTrue(tempSD.Type == OSDType.Real); + Assert.NotNull(tempSD); + Assert.True(tempSD is OSDReal); + Assert.True(tempSD.Type == OSDType.Real); tempReal = (OSDReal)tempSD; - Assert.AreEqual(0.9878624d, tempReal.AsReal()); + Assert.Equal(0.9878624d, tempReal.AsReal()); //TODO - figure out any relevant rounding variability for 64 bit reals tempSD = map["sim fps"]; - Assert.IsNotNull(tempSD); - Assert.IsTrue(tempSD is OSDReal); - Assert.IsTrue(tempSD.Type == OSDType.Real); + Assert.NotNull(tempSD); + Assert.True(tempSD is OSDReal); + Assert.True(tempSD.Type == OSDType.Real); tempReal = (OSDReal)tempSD; - Assert.AreEqual(44.38898d, tempReal.AsReal()); + Assert.Equal(44.38898d, tempReal.AsReal()); tempSD = map["agent updates per second"]; - Assert.IsNotNull(tempSD); - Assert.IsTrue(tempSD is OSDReal); - Assert.IsTrue(tempSD.Type == OSDType.Real); + Assert.NotNull(tempSD); + Assert.True(tempSD is OSDReal); + Assert.True(tempSD.Type == OSDType.Real); tempReal = (OSDReal)tempSD; - Assert.AreEqual(Double.NaN, tempSD.AsReal()); + Assert.Equal(Double.NaN, tempSD.AsReal()); tempSD = map["total task count"]; - Assert.IsNotNull(tempSD); - Assert.IsTrue(tempSD is OSDReal); - Assert.IsTrue(tempSD.Type == OSDType.Real); + Assert.NotNull(tempSD); + Assert.True(tempSD is OSDReal); + Assert.True(tempSD.Type == OSDType.Real); tempReal = (OSDReal)tempSD; - Assert.AreEqual(4.0d, tempReal.AsReal()); + Assert.Equal(4.0d, tempReal.AsReal()); tempSD = map["active task count"]; - Assert.IsNotNull(tempSD); - Assert.IsTrue(tempSD is OSDReal); - Assert.IsTrue(tempSD.Type == OSDType.Real); + Assert.NotNull(tempSD); + Assert.True(tempSD is OSDReal); + Assert.True(tempSD.Type == OSDType.Real); tempReal = (OSDReal)tempSD; - Assert.AreEqual(0.0d, tempReal.AsReal()); + Assert.Equal(0.0d, tempReal.AsReal()); tempSD = map["pending uploads"]; - Assert.IsNotNull(tempSD); - Assert.IsTrue(tempSD is OSDReal); - Assert.IsTrue(tempSD.Type == OSDType.Real); + Assert.NotNull(tempSD); + Assert.True(tempSD is OSDReal); + Assert.True(tempSD.Type == OSDType.Real); tempReal = (OSDReal)tempSD; - Assert.AreEqual(0.0001096525d, tempReal.AsReal()); + Assert.Equal(0.0001096525d, tempReal.AsReal()); } /// /// Test that various Real representations are parsed correctly. /// - [Test] + [Fact] public void DeserializeReals() { OSD theSD = null; @@ -177,34 +177,34 @@ public void DeserializeReals() byte[] bytes = Encoding.UTF8.GetBytes(testSD); theSD = OSDParser.DeserializeLLSDXml(bytes); - Assert.IsTrue(theSD is OSDArray); + Assert.True(theSD is OSDArray); array = (OSDArray)theSD; - Assert.AreEqual(OSDType.Real, array[0].Type); + Assert.Equal(OSDType.Real, array[0].Type); tempReal = (OSDReal)array[0]; - Assert.AreEqual(44.38898d, tempReal.AsReal()); + Assert.Equal(44.38898d, tempReal.AsReal()); - Assert.AreEqual(OSDType.Real, array[1].Type); + Assert.Equal(OSDType.Real, array[1].Type); tempReal = (OSDReal)array[1]; - Assert.AreEqual(Double.NaN, tempReal.AsReal()); + Assert.Equal(Double.NaN, tempReal.AsReal()); - Assert.AreEqual(OSDType.Real, array[2].Type); + Assert.Equal(OSDType.Real, array[2].Type); tempReal = (OSDReal)array[2]; - Assert.AreEqual(4.0d, tempReal.AsReal()); + Assert.Equal(4.0d, tempReal.AsReal()); - Assert.AreEqual(OSDType.Real, array[3].Type); + Assert.Equal(OSDType.Real, array[3].Type); tempReal = (OSDReal)array[3]; - Assert.AreEqual(-13.333d, tempReal.AsReal()); + Assert.Equal(-13.333d, tempReal.AsReal()); - Assert.AreEqual(OSDType.Real, array[4].Type); + Assert.Equal(OSDType.Real, array[4].Type); tempReal = (OSDReal)array[4]; - Assert.AreEqual(0d, tempReal.AsReal()); + Assert.Equal(0d, tempReal.AsReal()); } /// /// Test that various String representations are parsed correctly. /// - [Test] + [Fact] public void DeserializeStrings() { OSD theSD = null; @@ -224,24 +224,24 @@ public void DeserializeStrings() byte[] bytes = Encoding.UTF8.GetBytes(testSD); theSD = OSDParser.DeserializeLLSDXml(bytes); - Assert.IsTrue(theSD is OSDArray); + Assert.True(theSD is OSDArray); array = (OSDArray)theSD; - Assert.AreEqual(OSDType.String, array[0].Type); + Assert.Equal(OSDType.String, array[0].Type); tempStr = (OSDString)array[0]; - Assert.AreEqual("Kissling", tempStr.AsString()); + Assert.Equal("Kissling", tempStr.AsString()); - Assert.AreEqual(OSDType.String, array[1].Type); + Assert.Equal(OSDType.String, array[1].Type); tempStr = (OSDString)array[1]; - Assert.AreEqual("Attack ships on fire off the shoulder of Orion", tempStr.AsString()); + Assert.Equal("Attack ships on fire off the shoulder of Orion", tempStr.AsString()); - Assert.AreEqual(OSDType.String, array[2].Type); + Assert.Equal(OSDType.String, array[2].Type); tempStr = (OSDString)array[2]; - Assert.AreEqual("< > & \' \"", tempStr.AsString()); + Assert.Equal("< > & \' \"", tempStr.AsString()); - Assert.AreEqual(OSDType.String, array[3].Type); + Assert.Equal(OSDType.String, array[3].Type); tempStr = (OSDString)array[3]; - Assert.AreEqual("", tempStr.AsString()); + Assert.Equal("", tempStr.AsString()); } @@ -253,7 +253,7 @@ public void DeserializeStrings() /// implemented using int, a.k.a. Int32. Not testing Int64 range until /// it's understood if there was a design reason for the Int32. /// - [Test] + [Fact] public void DeserializeIntegers() { OSD theSD = null; @@ -274,34 +274,34 @@ public void DeserializeIntegers() byte[] bytes = Encoding.UTF8.GetBytes(testSD); theSD = OSDParser.DeserializeLLSDXml(bytes); - Assert.IsTrue(theSD is OSDArray); + Assert.True(theSD is OSDArray); array = (OSDArray)theSD; - Assert.AreEqual(OSDType.Integer, array[0].Type); + Assert.Equal(OSDType.Integer, array[0].Type); tempInt = (OSDInteger)array[0]; - Assert.AreEqual(2147483647, tempInt.AsInteger()); + Assert.Equal(2147483647, tempInt.AsInteger()); - Assert.AreEqual(OSDType.Integer, array[1].Type); + Assert.Equal(OSDType.Integer, array[1].Type); tempInt = (OSDInteger)array[1]; - Assert.AreEqual(-2147483648, tempInt.AsInteger()); + Assert.Equal(-2147483648, tempInt.AsInteger()); - Assert.AreEqual(OSDType.Integer, array[2].Type); + Assert.Equal(OSDType.Integer, array[2].Type); tempInt = (OSDInteger)array[2]; - Assert.AreEqual(0, tempInt.AsInteger()); + Assert.Equal(0, tempInt.AsInteger()); - Assert.AreEqual(OSDType.Integer, array[3].Type); + Assert.Equal(OSDType.Integer, array[3].Type); tempInt = (OSDInteger)array[3]; - Assert.AreEqual(13, tempInt.AsInteger()); + Assert.Equal(13, tempInt.AsInteger()); - Assert.AreEqual(OSDType.Integer, array[4].Type); + Assert.Equal(OSDType.Integer, array[4].Type); tempInt = (OSDInteger)array[4]; - Assert.AreEqual(0, tempInt.AsInteger()); + Assert.Equal(0, tempInt.AsInteger()); } /// /// Test that various UUID representations are parsed correctly. /// - [Test] + [Fact] public void DeserializeUUID() { OSD theSD = null; @@ -319,22 +319,22 @@ public void DeserializeUUID() byte[] bytes = Encoding.UTF8.GetBytes(testSD); theSD = OSDParser.DeserializeLLSDXml(bytes); - Assert.IsTrue(theSD is OSDArray); + Assert.True(theSD is OSDArray); array = (OSDArray)theSD; - Assert.AreEqual(OSDType.UUID, array[0].Type); + Assert.Equal(OSDType.UUID, array[0].Type); tempUUID = (OSDUUID)array[0]; - Assert.AreEqual(new UUID("d7f4aeca-88f1-42a1-b385-b9db18abb255"), tempUUID.AsUUID()); + Assert.Equal(new UUID("d7f4aeca-88f1-42a1-b385-b9db18abb255"), tempUUID.AsUUID()); - Assert.AreEqual(OSDType.UUID, array[1].Type); + Assert.Equal(OSDType.UUID, array[1].Type); tempUUID = (OSDUUID)array[1]; - Assert.AreEqual(UUID.Zero, tempUUID.AsUUID()); + Assert.Equal(UUID.Zero, tempUUID.AsUUID()); } /// /// Test that various date representations are parsed correctly. /// - [Test] + [Fact] public void DeserializeDates() { OSD theSD = null; @@ -354,28 +354,28 @@ public void DeserializeDates() byte[] bytes = Encoding.UTF8.GetBytes(testSD); theSD = OSDParser.DeserializeLLSDXml(bytes); - Assert.IsTrue(theSD is OSDArray); + Assert.True(theSD is OSDArray); array = (OSDArray)theSD; - Assert.AreEqual(OSDType.Date, array[0].Type); + Assert.Equal(OSDType.Date, array[0].Type); tempDate = (OSDDate)array[0]; DateTime.TryParse("2006-02-01T14:29:53Z", out testDate); - Assert.AreEqual(testDate, tempDate.AsDate()); + Assert.Equal(testDate, tempDate.AsDate()); - Assert.AreEqual(OSDType.Date, array[1].Type); + Assert.Equal(OSDType.Date, array[1].Type); tempDate = (OSDDate)array[1]; DateTime.TryParse("1999-01-01T00:00:00Z", out testDate); - Assert.AreEqual(testDate, tempDate.AsDate()); + Assert.Equal(testDate, tempDate.AsDate()); - Assert.AreEqual(OSDType.Date, array[2].Type); + Assert.Equal(OSDType.Date, array[2].Type); tempDate = (OSDDate)array[2]; - Assert.AreEqual(Utils.Epoch, tempDate.AsDate()); + Assert.Equal(Utils.Epoch, tempDate.AsDate()); } /// /// Test that various Boolean representations are parsed correctly. /// - [Test] + [Fact] public void DeserializeBoolean() { OSD theSD = null; @@ -396,34 +396,34 @@ public void DeserializeBoolean() byte[] bytes = Encoding.UTF8.GetBytes(testSD); theSD = OSDParser.DeserializeLLSDXml(bytes); - Assert.IsTrue(theSD is OSDArray); + Assert.True(theSD is OSDArray); array = (OSDArray)theSD; - Assert.AreEqual(OSDType.Boolean, array[0].Type); + Assert.Equal(OSDType.Boolean, array[0].Type); tempBool = (OSDBoolean)array[0]; - Assert.AreEqual(true, tempBool.AsBoolean()); + Assert.Equal(true, tempBool.AsBoolean()); - Assert.AreEqual(OSDType.Boolean, array[1].Type); + Assert.Equal(OSDType.Boolean, array[1].Type); tempBool = (OSDBoolean)array[1]; - Assert.AreEqual(true, tempBool.AsBoolean()); + Assert.Equal(true, tempBool.AsBoolean()); - Assert.AreEqual(OSDType.Boolean, array[2].Type); + Assert.Equal(OSDType.Boolean, array[2].Type); tempBool = (OSDBoolean)array[2]; - Assert.AreEqual(false, tempBool.AsBoolean()); + Assert.Equal(false, tempBool.AsBoolean()); - Assert.AreEqual(OSDType.Boolean, array[3].Type); + Assert.Equal(OSDType.Boolean, array[3].Type); tempBool = (OSDBoolean)array[3]; - Assert.AreEqual(false, tempBool.AsBoolean()); + Assert.Equal(false, tempBool.AsBoolean()); - Assert.AreEqual(OSDType.Boolean, array[4].Type); + Assert.Equal(OSDType.Boolean, array[4].Type); tempBool = (OSDBoolean)array[4]; - Assert.AreEqual(false, tempBool.AsBoolean()); + Assert.Equal(false, tempBool.AsBoolean()); } /// /// Test that binary elements are parsed correctly. /// - [Test] + [Fact] public void DeserializeBinary() { OSD theSD = null; @@ -443,23 +443,23 @@ public void DeserializeBinary() byte[] bytes = Encoding.UTF8.GetBytes(testSD); theSD = OSDParser.DeserializeLLSDXml(bytes); - Assert.IsTrue(theSD is OSDArray); + Assert.True(theSD is OSDArray); array = (OSDArray)theSD; - Assert.AreEqual(OSDType.Binary, array[0].Type); + Assert.Equal(OSDType.Binary, array[0].Type); tempBinary = (OSDBinary)array[0]; byte[] testData1 = { 114, 97, 110, 100, 111, 109 }; TestHelper.TestBinary(tempBinary, testData1); - Assert.AreEqual(OSDType.Binary, array[1].Type); + Assert.Equal(OSDType.Binary, array[1].Type); tempBinary = (OSDBinary)array[1]; byte[] testData2 = {116, 104, 101, 32, 113, 117, 105, 99, 107, 32, 98, 114, 111, 119, 110, 32, 102, 111, 120}; TestHelper.TestBinary(tempBinary, testData2); - Assert.AreEqual(OSDType.Binary, array[1].Type); + Assert.Equal(OSDType.Binary, array[1].Type); tempBinary = (OSDBinary)array[2]; - Assert.AreEqual(0, tempBinary.AsBinary().Length); + Assert.Equal(0, tempBinary.AsBinary().Length); } /// @@ -468,7 +468,7 @@ public void DeserializeBinary() /// value and there is no SD child class for Undefined elements - the /// current implementation generates an instance of SD /// - [Test] + [Fact] public void DeserializeUndef() { OSD theSD = null; @@ -481,13 +481,13 @@ public void DeserializeUndef() byte[] bytes = Encoding.UTF8.GetBytes(testSD); theSD = OSDParser.DeserializeLLSDXml(bytes); - Assert.IsTrue(theSD is OSD); + Assert.True(theSD is OSD); } /// /// Test that various URI representations are parsed correctly. /// - [Test] + [Fact] public void DeserializeURI() { OSD theSD = null; @@ -505,24 +505,24 @@ public void DeserializeURI() byte[] bytes = Encoding.UTF8.GetBytes(testSD); theSD = OSDParser.DeserializeLLSDXml(bytes); - Assert.IsTrue(theSD is OSDArray); + Assert.True(theSD is OSDArray); array = (OSDArray)theSD; - Assert.AreEqual(OSDType.URI, array[0].Type); + Assert.Equal(OSDType.URI, array[0].Type); tempURI = (OSDUri)array[0]; Uri testURI = new Uri(@"http://sim956.agni.lindenlab.com:12035/runtime/agents"); - Assert.AreEqual(testURI, tempURI.AsUri()); + Assert.Equal(testURI, tempURI.AsUri()); - Assert.AreEqual(OSDType.URI, array[1].Type); + Assert.Equal(OSDType.URI, array[1].Type); tempURI = (OSDUri)array[1]; - Assert.AreEqual("", tempURI.AsUri().ToString()); + Assert.Equal("", tempURI.AsUri().ToString()); } /// /// Test some nested containers. This is not a very deep or complicated SD graph /// but it should reveal basic nesting issues. /// - [Test] + [Fact] public void DeserializeNestedContainers() { OSD theSD = null; @@ -558,36 +558,36 @@ public void DeserializeNestedContainers() byte[] bytes = Encoding.UTF8.GetBytes(testSD); theSD = OSDParser.DeserializeLLSDXml(bytes); - Assert.IsTrue(theSD is OSDArray); + Assert.True(theSD is OSDArray); array = (OSDArray)theSD; - Assert.AreEqual(2, array.Count); + Assert.Equal(2, array.Count); //The first element of top level array, a map - Assert.AreEqual(OSDType.Map, array[0].Type); + Assert.Equal(OSDType.Map, array[0].Type); map = (OSDMap)array[0]; //First nested map tempSD = map["Map One"]; - Assert.IsNotNull(tempSD); - Assert.AreEqual(OSDType.Map, tempSD.Type); + Assert.NotNull(tempSD); + Assert.Equal(OSDType.Map, tempSD.Type); map = (OSDMap)tempSD; //First nested array tempSD = map["Array One"]; - Assert.IsNotNull(tempSD); - Assert.AreEqual(OSDType.Array, tempSD.Type); + Assert.NotNull(tempSD); + Assert.Equal(OSDType.Array, tempSD.Type); array = (OSDArray)tempSD; - Assert.AreEqual(2, array.Count); + Assert.Equal(2, array.Count); array = (OSDArray)theSD; //Second element of top level array, an array tempSD = array[1]; - Assert.AreEqual(OSDType.Array, tempSD.Type); + Assert.Equal(OSDType.Array, tempSD.Type); array = (OSDArray)tempSD; - Assert.AreEqual(3, array.Count); + Assert.Equal(3, array.Count); //Nested array tempSD = array[2]; - Assert.AreEqual(OSDType.Array, tempSD.Type); + Assert.Equal(OSDType.Array, tempSD.Type); array = (OSDArray)tempSD; - Assert.AreEqual(3, array.Count); + Assert.Equal(3, array.Count); } } @@ -602,12 +602,12 @@ internal static class TestHelper internal static void TestBinary(OSDBinary inBinary, byte[] inExpected) { byte[] binary = inBinary.AsBinary(); - Assert.AreEqual(inExpected.Length, binary.Length); + Assert.Equal(inExpected.Length, binary.Length); for (int i = 0; i < inExpected.Length; i++) { if (inExpected[i] != binary[i]) { - Assert.Fail("Expected " + inExpected[i].ToString() + " at position " + i.ToString() + + throw new Xunit.Sdk.XunitException("Expected " + inExpected[i].ToString() + " at position " + i.ToString() + " but saw " + binary[i].ToString()); } } diff --git a/OpenMetaverse.Types/Color4.cs b/OpenMetaverse.Types/Color4.cs index 99d0e7cf..be081432 100644 --- a/OpenMetaverse.Types/Color4.cs +++ b/OpenMetaverse.Types/Color4.cs @@ -1,525 +1,520 @@ -/* - * Copyright (c) 2006-2016, openmetaverse.co - * All rights reserved. - * - * - Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, this - * list of conditions and the following disclaimer. - * - Neither the name of the openmetaverse.co nor the names - * of its contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Runtime.InteropServices; - -namespace OpenMetaverse -{ - /// - /// An 8-bit color structure including an alpha channel - /// - [Serializable] - [StructLayout(LayoutKind.Sequential)] - public struct Color4 : IComparable, IEquatable - { - /// Red - public float R; - /// Green - public float G; - /// Blue - public float B; - /// Alpha - public float A; - - #region Constructors - - /// - /// - /// - /// - /// - /// - /// - public Color4(byte r, byte g, byte b, byte a) - { - const float quanta = 1.0f / 255.0f; - - R = (float)r * quanta; - G = (float)g * quanta; - B = (float)b * quanta; - A = (float)a * quanta; - } - - public Color4(float r, float g, float b, float a) - { - // Quick check to see if someone is doing something obviously wrong - // like using float values from 0.0 - 255.0 - if (r > 1f || g > 1f || b > 1f || a > 1f) - throw new ArgumentException( - String.Format("Attempting to initialize Color4 with out of range values <{0},{1},{2},{3}>", - r, g, b, a)); - - // Valid range is from 0.0 to 1.0 - R = Utils.Clamp(r, 0f, 1f); - G = Utils.Clamp(g, 0f, 1f); - B = Utils.Clamp(b, 0f, 1f); - A = Utils.Clamp(a, 0f, 1f); - } - - /// - /// Builds a color from a byte array - /// - /// Byte array containing a 16 byte color - /// Beginning position in the byte array - /// True if the byte array stores inverted values, - /// otherwise false. For example the color black (fully opaque) inverted - /// would be 0xFF 0xFF 0xFF 0x00 - public Color4(byte[] byteArray, int pos, bool inverted) - { - R = G = B = A = 0f; - FromBytes(byteArray, pos, inverted); - } - - /// - /// Returns the raw bytes for this vector - /// - /// Byte array containing a 16 byte color - /// Beginning position in the byte array - /// True if the byte array stores inverted values, - /// otherwise false. For example the color black (fully opaque) inverted - /// would be 0xFF 0xFF 0xFF 0x00 - /// True if the alpha value is inverted in - /// addition to whatever the inverted parameter is. Setting inverted true - /// and alphaInverted true will flip the alpha value back to non-inverted, - /// but keep the other color bytes inverted - /// A 16 byte array containing R, G, B, and A - public Color4(byte[] byteArray, int pos, bool inverted, bool alphaInverted) - { - R = G = B = A = 0f; - FromBytes(byteArray, pos, inverted, alphaInverted); - } - - /// - /// Copy constructor - /// - /// Color to copy - public Color4(Color4 color) - { - R = color.R; - G = color.G; - B = color.B; - A = color.A; - } - - #endregion Constructors - - #region Public Methods - - /// - /// IComparable.CompareTo implementation - /// - /// Sorting ends up like this: |--Grayscale--||--Color--|. - /// Alpha is only used when the colors are otherwise equivalent - public int CompareTo(Color4 color) - { - float thisHue = GetHue(); - float thatHue = color.GetHue(); - - if (thisHue < 0f && thatHue < 0f) - { - // Both monochromatic - if (R == color.R) - { - // Monochromatic and equal, compare alpha - return A.CompareTo(color.A); - } - else - { - // Compare lightness - return R.CompareTo(R); - } - } - else - { - if (thisHue == thatHue) - { - // RGB is equal, compare alpha - return A.CompareTo(color.A); - } - else - { - // Compare hues - return thisHue.CompareTo(thatHue); - } - } - } - - public void FromBytes(byte[] byteArray, int pos, bool inverted) - { - const float quanta = 1.0f / 255.0f; - - if (inverted) - { - R = (float)(255 - byteArray[pos]) * quanta; - G = (float)(255 - byteArray[pos + 1]) * quanta; - B = (float)(255 - byteArray[pos + 2]) * quanta; - A = (float)(255 - byteArray[pos + 3]) * quanta; - } - else - { - R = (float)byteArray[pos] * quanta; - G = (float)byteArray[pos + 1] * quanta; - B = (float)byteArray[pos + 2] * quanta; - A = (float)byteArray[pos + 3] * quanta; - } - } - - /// - /// Builds a color from a byte array - /// - /// Byte array containing a 16 byte color - /// Beginning position in the byte array - /// True if the byte array stores inverted values, - /// otherwise false. For example the color black (fully opaque) inverted - /// would be 0xFF 0xFF 0xFF 0x00 - /// True if the alpha value is inverted in - /// addition to whatever the inverted parameter is. Setting inverted true - /// and alphaInverted true will flip the alpha value back to non-inverted, - /// but keep the other color bytes inverted - public void FromBytes(byte[] byteArray, int pos, bool inverted, bool alphaInverted) - { - FromBytes(byteArray, pos, inverted); - - if (alphaInverted) - A = 1.0f - A; - } - - public byte[] GetBytes() - { - return GetBytes(false); - } - - public byte[] GetBytes(bool inverted) - { - byte[] byteArray = new byte[4]; - ToBytes(byteArray, 0, inverted); - return byteArray; - } - - public byte[] GetFloatBytes() - { - byte[] bytes = new byte[16]; - ToFloatBytes(bytes, 0); - return bytes; - } - - /// - /// Writes the raw bytes for this color to a byte array - /// - /// Destination byte array - /// Position in the destination array to start - /// writing. Must be at least 16 bytes before the end of the array - public void ToBytes(byte[] dest, int pos) - { - ToBytes(dest, pos, false); - } - - /// - /// Serializes this color into four bytes in a byte array - /// - /// Destination byte array - /// Position in the destination array to start - /// writing. Must be at least 4 bytes before the end of the array - /// True to invert the output (1.0 becomes 0 - /// instead of 255) - public void ToBytes(byte[] dest, int pos, bool inverted) - { - dest[pos + 0] = Utils.FloatToByte(R, 0f, 1f); - dest[pos + 1] = Utils.FloatToByte(G, 0f, 1f); - dest[pos + 2] = Utils.FloatToByte(B, 0f, 1f); - dest[pos + 3] = Utils.FloatToByte(A, 0f, 1f); - - if (inverted) - { - dest[pos + 0] = (byte)(255 - dest[pos + 0]); - dest[pos + 1] = (byte)(255 - dest[pos + 1]); - dest[pos + 2] = (byte)(255 - dest[pos + 2]); - dest[pos + 3] = (byte)(255 - dest[pos + 3]); - } - } - - /// - /// Writes the raw bytes for this color to a byte array - /// - /// Destination byte array - /// Position in the destination array to start - /// writing. Must be at least 16 bytes before the end of the array - public void ToFloatBytes(byte[] dest, int pos) - { - Buffer.BlockCopy(BitConverter.GetBytes(R), 0, dest, pos + 0, 4); - Buffer.BlockCopy(BitConverter.GetBytes(G), 0, dest, pos + 4, 4); - Buffer.BlockCopy(BitConverter.GetBytes(B), 0, dest, pos + 8, 4); - Buffer.BlockCopy(BitConverter.GetBytes(A), 0, dest, pos + 12, 4); - } - - public float GetHue() - { - const float HUE_MAX = 360f; - - float max = Math.Max(Math.Max(R, G), B); - float min = Math.Min(Math.Min(R, B), B); - - if (max == min) - { - // Achromatic, hue is undefined - return -1f; - } - else if (R == max) - { - float bDelta = (((max - B) * (HUE_MAX / 6f)) + ((max - min) / 2f)) / (max - min); - float gDelta = (((max - G) * (HUE_MAX / 6f)) + ((max - min) / 2f)) / (max - min); - return bDelta - gDelta; - } - else if (G == max) - { - float rDelta = (((max - R) * (HUE_MAX / 6f)) + ((max - min) / 2f)) / (max - min); - float bDelta = (((max - B) * (HUE_MAX / 6f)) + ((max - min) / 2f)) / (max - min); - return (HUE_MAX / 3f) + rDelta - bDelta; - } - else // B == max - { - float gDelta = (((max - G) * (HUE_MAX / 6f)) + ((max - min) / 2f)) / (max - min); - float rDelta = (((max - R) * (HUE_MAX / 6f)) + ((max - min) / 2f)) / (max - min); - return ((2f * HUE_MAX) / 3f) + gDelta - rDelta; - } - } - - /// - /// Ensures that values are in range 0-1 - /// - public void ClampValues() - { - if (R < 0f) - R = 0f; - if (G < 0f) - G = 0f; - if (B < 0f) - B = 0f; - if (A < 0f) - A = 0f; - if (R > 1f) - R = 1f; - if (G > 1f) - G = 1f; - if (B > 1f) - B = 1f; - if (A > 1f) - A = 1f; - } - - #endregion Public Methods - - #region Static Methods - - /// - /// Create an RGB color from a hue, saturation, value combination - /// - /// Hue - /// Saturation - /// Value - /// An fully opaque RGB color (alpha is 1.0) - public static Color4 FromHSV(double hue, double saturation, double value) - { - double r = 0d; - double g = 0d; - double b = 0d; - - if (saturation == 0d) - { - // If s is 0, all colors are the same. - // This is some flavor of gray. - r = value; - g = value; - b = value; - } - else - { - double p; - double q; - double t; - - double fractionalSector; - int sectorNumber; - double sectorPos; - - // The color wheel consists of 6 sectors. - // Figure out which sector you//re in. - sectorPos = hue / 60d; - sectorNumber = (int)(Math.Floor(sectorPos)); - - // get the fractional part of the sector. - // That is, how many degrees into the sector - // are you? - fractionalSector = sectorPos - sectorNumber; - - // Calculate values for the three axes - // of the color. - p = value * (1d - saturation); - q = value * (1d - (saturation * fractionalSector)); - t = value * (1d - (saturation * (1d - fractionalSector))); - - // Assign the fractional colors to r, g, and b - // based on the sector the angle is in. - switch (sectorNumber) - { - case 0: - r = value; - g = t; - b = p; - break; - case 1: - r = q; - g = value; - b = p; - break; - case 2: - r = p; - g = value; - b = t; - break; - case 3: - r = p; - g = q; - b = value; - break; - case 4: - r = t; - g = p; - b = value; - break; - case 5: - r = value; - g = p; - b = q; - break; - } - } - - return new Color4((float)r, (float)g, (float)b, 1f); - } - - /// - /// Performs linear interpolation between two colors - /// - /// Color to start at - /// Color to end at - /// Amount to interpolate - /// The interpolated color - public static Color4 Lerp(Color4 value1, Color4 value2, float amount) - { - return new Color4( - Utils.Lerp(value1.R, value2.R, amount), - Utils.Lerp(value1.G, value2.G, amount), - Utils.Lerp(value1.B, value2.B, amount), - Utils.Lerp(value1.A, value2.A, amount)); - } - - #endregion Static Methods - - #region Overrides - - public override string ToString() - { - return String.Format(Utils.EnUsCulture, "<{0}, {1}, {2}, {3}>", R, G, B, A); - } - - public string ToRGBString() - { - return String.Format(Utils.EnUsCulture, "<{0}, {1}, {2}>", R, G, B); - } - - public override bool Equals(object obj) - { - return (obj is Color4) ? this == (Color4)obj : false; - } - - public bool Equals(Color4 other) - { - return this == other; - } - - public override int GetHashCode() - { - return R.GetHashCode() ^ G.GetHashCode() ^ B.GetHashCode() ^ A.GetHashCode(); - } - - #endregion Overrides - - #region Operators - - public static bool operator ==(Color4 lhs, Color4 rhs) - { - return (lhs.R == rhs.R) && (lhs.G == rhs.G) && (lhs.B == rhs.B) && (lhs.A == rhs.A); - } - - public static bool operator !=(Color4 lhs, Color4 rhs) - { - return !(lhs == rhs); - } - - public static Color4 operator +(Color4 lhs, Color4 rhs) - { - lhs.R += rhs.R; - lhs.G += rhs.G; - lhs.B += rhs.B; - lhs.A += rhs.A; - lhs.ClampValues(); - - return lhs; - } - - public static Color4 operator -(Color4 lhs, Color4 rhs) - { - lhs.R -= rhs.R; - lhs.G -= rhs.G; - lhs.B -= rhs.B; - lhs.A -= rhs.A; - lhs.ClampValues(); - - return lhs; - } - - public static Color4 operator *(Color4 lhs, Color4 rhs) - { - lhs.R *= rhs.R; - lhs.G *= rhs.G; - lhs.B *= rhs.B; - lhs.A *= rhs.A; - lhs.ClampValues(); - - return lhs; - } - - #endregion Operators - - /// A Color4 with zero RGB values and fully opaque (alpha 1.0) - public readonly static Color4 Black = new Color4(0f, 0f, 0f, 1f); - - /// A Color4 with full RGB values (1.0) and fully opaque (alpha 1.0) - public readonly static Color4 White = new Color4(1f, 1f, 1f, 1f); - } -} +/* + * Copyright (c) 2006-2016, openmetaverse.co + * All rights reserved. + * + * - Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * - Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * - Neither the name of the openmetaverse.co nor the names + * of its contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Runtime.InteropServices; + +namespace OpenMetaverse +{ + /// + /// An 8-bit color structure including an alpha channel + /// + [Serializable] + [StructLayout(LayoutKind.Sequential)] + public struct Color4 : IComparable, IEquatable + { + /// Red + public float R; + /// Green + public float G; + /// Blue + public float B; + /// Alpha + public float A; + + #region Constructors + + /// + /// + /// + /// + /// + /// + /// + public Color4(byte r, byte g, byte b, byte a) + { + const float quanta = 1.0f / 255.0f; + + R = (float)r * quanta; + G = (float)g * quanta; + B = (float)b * quanta; + A = (float)a * quanta; + } + + public Color4(float r, float g, float b, float a) + { + // Quick check to see if someone is doing something obviously wrong + // like using float values from 0.0 - 255.0 + if (r > 1f || g > 1f || b > 1f || a > 1f) + throw new ArgumentException($"Attempting to initialize Color4 with out of range values <{r},{g},{b},{a}>"); + + // Valid range is from 0.0 to 1.0 + R = Utils.Clamp(r, 0f, 1f); + G = Utils.Clamp(g, 0f, 1f); + B = Utils.Clamp(b, 0f, 1f); + A = Utils.Clamp(a, 0f, 1f); + } + + /// + /// Builds a color from a byte array + /// + /// Byte array containing a 16 byte color + /// Beginning position in the byte array + /// True if the byte array stores inverted values, + /// otherwise false. For example the color black (fully opaque) inverted + /// would be 0xFF 0xFF 0xFF 0x00 + public Color4(byte[] byteArray, int pos, bool inverted) + { + R = G = B = A = 0f; + FromBytes(byteArray, pos, inverted); + } + + /// + /// Returns the raw bytes for this vector + /// + /// Byte array containing a 16 byte color + /// Beginning position in the byte array + /// True if the byte array stores inverted values, + /// otherwise false. For example the color black (fully opaque) inverted + /// would be 0xFF 0xFF 0xFF 0x00 + /// True if the alpha value is inverted in + /// addition to whatever the inverted parameter is. Setting inverted true + /// and alphaInverted true will flip the alpha value back to non-inverted, + /// but keep the other color bytes inverted + /// A 16 byte array containing R, G, B, and A + public Color4(byte[] byteArray, int pos, bool inverted, bool alphaInverted) + { + R = G = B = A = 0f; + FromBytes(byteArray, pos, inverted, alphaInverted); + } + + /// + /// Copy constructor + /// + /// Color to copy + public Color4(Color4 color) + { + R = color.R; + G = color.G; + B = color.B; + A = color.A; + } + + #endregion Constructors + + #region Public Methods + + /// + /// IComparable.CompareTo implementation + /// + /// Sorting ends up like this: |--Grayscale--||--Color--|. + /// Alpha is only used when the colors are otherwise equivalent + public int CompareTo(Color4 color) + { + float thisHue = GetHue(); + float thatHue = color.GetHue(); + + if (thisHue < 0f && thatHue < 0f) + { + // Both monochromatic + if (R == color.R) + { + // Monochromatic and equal, compare alpha + return A.CompareTo(color.A); + } + else + { + // Compare lightness + return R.CompareTo(R); + } + } + else + { + if (thisHue == thatHue) + { + // RGB is equal, compare alpha + return A.CompareTo(color.A); + } + else + { + // Compare hues + return thisHue.CompareTo(thatHue); + } + } + } + + public void FromBytes(byte[] byteArray, int pos, bool inverted) + { + const float quanta = 1.0f / 255.0f; + + if (inverted) + { + R = (float)(255 - byteArray[pos]) * quanta; + G = (float)(255 - byteArray[pos + 1]) * quanta; + B = (float)(255 - byteArray[pos + 2]) * quanta; + A = (float)(255 - byteArray[pos + 3]) * quanta; + } + else + { + R = (float)byteArray[pos] * quanta; + G = (float)byteArray[pos + 1] * quanta; + B = (float)byteArray[pos + 2] * quanta; + A = (float)byteArray[pos + 3] * quanta; + } + } + + /// + /// Builds a color from a byte array + /// + /// Byte array containing a 16 byte color + /// Beginning position in the byte array + /// True if the byte array stores inverted values, + /// otherwise false. For example the color black (fully opaque) inverted + /// would be 0xFF 0xFF 0xFF 0x00 + /// True if the alpha value is inverted in + /// addition to whatever the inverted parameter is. Setting inverted true + /// and alphaInverted true will flip the alpha value back to non-inverted, + /// but keep the other color bytes inverted + public void FromBytes(byte[] byteArray, int pos, bool inverted, bool alphaInverted) + { + FromBytes(byteArray, pos, inverted); + + if (alphaInverted) + A = 1.0f - A; + } + + public byte[] GetBytes() + { + return GetBytes(false); + } + + public byte[] GetBytes(bool inverted) + { + byte[] byteArray = new byte[4]; + ToBytes(byteArray, 0, inverted); + return byteArray; + } + + public byte[] GetFloatBytes() + { + byte[] bytes = new byte[16]; + ToFloatBytes(bytes, 0); + return bytes; + } + + /// + /// Writes the raw bytes for this color to a byte array + /// + /// Destination byte array + /// Position in the destination array to start + /// writing. Must be at least 16 bytes before the end of the array + public void ToBytes(byte[] dest, int pos) + { + ToBytes(dest, pos, false); + } + + /// + /// Serializes this color into four bytes in a byte array + /// + /// Destination byte array + /// Position in the destination array to start + /// writing. Must be at least 4 bytes before the end of the array + /// True to invert the output (1.0 becomes 0 + /// instead of 255) + public void ToBytes(byte[] dest, int pos, bool inverted) + { + if (!inverted) + { + dest[pos + 0] = Utils.FloatZeroOneToByte(R); + dest[pos + 1] = Utils.FloatZeroOneToByte(G); + dest[pos + 2] = Utils.FloatZeroOneToByte(B); + dest[pos + 3] = Utils.FloatZeroOneToByte(A); + } + else + { + dest[pos + 0] = (byte)(255 - Utils.FloatZeroOneToByte(R)); + dest[pos + 1] = (byte)(255 - Utils.FloatZeroOneToByte(G)); + dest[pos + 2] = (byte)(255 - Utils.FloatZeroOneToByte(B)); + dest[pos + 3] = (byte)(255 - Utils.FloatZeroOneToByte(A)); + } + } + + /// + /// Writes the raw bytes for this color to a byte array + /// + /// Destination byte array + /// Position in the destination array to start + /// writing. Must be at least 16 bytes before the end of the array + public void ToFloatBytes(byte[] dest, int pos) + { + Buffer.BlockCopy(BitConverter.GetBytes(R), 0, dest, pos + 0, 4); + Buffer.BlockCopy(BitConverter.GetBytes(G), 0, dest, pos + 4, 4); + Buffer.BlockCopy(BitConverter.GetBytes(B), 0, dest, pos + 8, 4); + Buffer.BlockCopy(BitConverter.GetBytes(A), 0, dest, pos + 12, 4); + } + + public float GetHue() + { + const float HUE_MAX = 360f; + + float max = MathF.Max(MathF.Max(R, G), B); + float min = MathF.Min(MathF.Min(R, B), B); + + if (max == min) + { + // Achromatic, hue is undefined + return -1f; + } + else if (R == max) + { + float bDelta = (((max - B) * (HUE_MAX / 6f)) + ((max - min) / 2f)) / (max - min); + float gDelta = (((max - G) * (HUE_MAX / 6f)) + ((max - min) / 2f)) / (max - min); + return bDelta - gDelta; + } + else if (G == max) + { + float rDelta = (((max - R) * (HUE_MAX / 6f)) + ((max - min) / 2f)) / (max - min); + float bDelta = (((max - B) * (HUE_MAX / 6f)) + ((max - min) / 2f)) / (max - min); + return (HUE_MAX / 3f) + rDelta - bDelta; + } + else // B == max + { + float gDelta = (((max - G) * (HUE_MAX / 6f)) + ((max - min) / 2f)) / (max - min); + float rDelta = (((max - R) * (HUE_MAX / 6f)) + ((max - min) / 2f)) / (max - min); + return ((2f * HUE_MAX) / 3f) + gDelta - rDelta; + } + } + + /// + /// Ensures that values are in range 0-1 + /// + public void ClampValues() + { + if (R < 0f) R = 0f; + else if (R > 1f) R = 1f; + + if (G < 0f) G = 0f; + else if(G > 1f) G = 1f; + + if (B < 0f) B = 0f; + else if (B > 1f) B = 1f; + + if (A < 0f) A = 0f; + else if (A > 1f) A = 1f; + } + + #endregion Public Methods + + #region Static Methods + + /// + /// Create an RGB color from a hue, saturation, value combination + /// + /// Hue + /// Saturation + /// Value + /// An fully opaque RGB color (alpha is 1.0) + public static Color4 FromHSV(double hue, double saturation, double value) + { + double r = 0d; + double g = 0d; + double b = 0d; + + if (saturation == 0d) + { + // If s is 0, all colors are the same. + // This is some flavor of gray. + r = value; + g = value; + b = value; + } + else + { + double p; + double q; + double t; + + double fractionalSector; + int sectorNumber; + double sectorPos; + + // The color wheel consists of 6 sectors. + // Figure out which sector you//re in. + sectorPos = hue / 60d; + sectorNumber = (int)(Math.Floor(sectorPos)); + + // get the fractional part of the sector. + // That is, how many degrees into the sector + // are you? + fractionalSector = sectorPos - sectorNumber; + + // Calculate values for the three axes + // of the color. + p = value * (1d - saturation); + q = value * (1d - (saturation * fractionalSector)); + t = value * (1d - (saturation * (1d - fractionalSector))); + + // Assign the fractional colors to r, g, and b + // based on the sector the angle is in. + switch (sectorNumber) + { + case 0: + r = value; + g = t; + b = p; + break; + case 1: + r = q; + g = value; + b = p; + break; + case 2: + r = p; + g = value; + b = t; + break; + case 3: + r = p; + g = q; + b = value; + break; + case 4: + r = t; + g = p; + b = value; + break; + case 5: + r = value; + g = p; + b = q; + break; + } + } + + return new Color4((float)r, (float)g, (float)b, 1f); + } + + /// + /// Performs linear interpolation between two colors + /// + /// Color to start at + /// Color to end at + /// Amount to interpolate + /// The interpolated color + public static Color4 Lerp(Color4 value1, Color4 value2, float amount) + { + return new Color4( + Utils.Lerp(value1.R, value2.R, amount), + Utils.Lerp(value1.G, value2.G, amount), + Utils.Lerp(value1.B, value2.B, amount), + Utils.Lerp(value1.A, value2.A, amount)); + } + + #endregion Static Methods + + #region Overrides + + public override string ToString() + { + return String.Format(Utils.EnUsCulture, $"<{R}, {G}, {B}, {A}>"); + } + + public string ToRGBString() + { + return String.Format(Utils.EnUsCulture, $"<{R}, {G}, {B}>"); + } + + public override bool Equals(object obj) + { + return (obj is Color4) ? this == (Color4)obj : false; + } + + public bool Equals(Color4 other) + { + return this == other; + } + + public override int GetHashCode() + { + return R.GetHashCode() ^ G.GetHashCode() ^ B.GetHashCode() ^ A.GetHashCode(); + } + + #endregion Overrides + + #region Operators + + public static bool operator ==(Color4 lhs, Color4 rhs) + { + return (lhs.R == rhs.R) && (lhs.G == rhs.G) && (lhs.B == rhs.B) && (lhs.A == rhs.A); + } + + public static bool operator !=(Color4 lhs, Color4 rhs) + { + return !(lhs == rhs); + } + + public static Color4 operator +(Color4 lhs, in Color4 rhs) + { + lhs.R += rhs.R; + lhs.G += rhs.G; + lhs.B += rhs.B; + lhs.A += rhs.A; + lhs.ClampValues(); + + return lhs; + } + + public static Color4 operator -(Color4 lhs, in Color4 rhs) + { + lhs.R -= rhs.R; + lhs.G -= rhs.G; + lhs.B -= rhs.B; + lhs.A -= rhs.A; + lhs.ClampValues(); + + return lhs; + } + + public static Color4 operator *(Color4 lhs, in Color4 rhs) + { + lhs.R *= rhs.R; + lhs.G *= rhs.G; + lhs.B *= rhs.B; + lhs.A *= rhs.A; + lhs.ClampValues(); + + return lhs; + } + + #endregion Operators + + /// A Color4 with zero RGB values and fully opaque (alpha 1.0) + public readonly static Color4 Black = new(0f, 0f, 0f, 1f); + + /// A Color4 with full RGB values (1.0) and fully opaque (alpha 1.0) + public readonly static Color4 White = new(1f, 1f, 1f, 1f); + } +} diff --git a/OpenMetaverse.Types/DoubleDictionary.cs b/OpenMetaverse.Types/DoubleDictionary.cs index 06f4b362..41b910df 100644 --- a/OpenMetaverse.Types/DoubleDictionary.cs +++ b/OpenMetaverse.Types/DoubleDictionary.cs @@ -73,24 +73,18 @@ public void Add(TKey1 key1, TKey2 key2, TValue value) public bool Remove(TKey1 key1, TKey2 key2) { - bool success; rwLock.EnterWriteLock(); - try { Dictionary1.Remove(key1); - success = Dictionary2.Remove(key2); + return Dictionary2.Remove(key2); } finally { rwLock.ExitWriteLock(); } - - return success; } public bool Remove(TKey1 key1) { - bool found = false; rwLock.EnterWriteLock(); - try { // This is an O(n) operation! @@ -103,27 +97,22 @@ public bool Remove(TKey1 key1) { Dictionary1.Remove(key1); Dictionary2.Remove(kvp.Key); - found = true; - break; + return true; } } } + return false; } finally { rwLock.ExitWriteLock(); } - - return found; } public bool Remove(TKey2 key2) { - bool found = false; rwLock.EnterWriteLock(); - try { // This is an O(n) operation! - TValue value; - if (Dictionary2.TryGetValue(key2, out value)) + if (Dictionary2.TryGetValue(key2, out TValue value)) { foreach (KeyValuePair kvp in Dictionary1) { @@ -131,15 +120,13 @@ public bool Remove(TKey2 key2) { Dictionary2.Remove(key2); Dictionary1.Remove(kvp.Key); - found = true; - break; + return true; } } } + return false; } finally { rwLock.ExitWriteLock(); } - - return found; } public void Clear() @@ -171,30 +158,21 @@ public bool ContainsKey(TKey2 key) public bool TryGetValue(TKey1 key, out TValue value) { - bool success; rwLock.EnterReadLock(); - - try { success = Dictionary1.TryGetValue(key, out value); } + try { return Dictionary1.TryGetValue(key, out value); } finally { rwLock.ExitReadLock(); } - - return success; } public bool TryGetValue(TKey2 key, out TValue value) { - bool success; rwLock.EnterReadLock(); - - try { success = Dictionary2.TryGetValue(key, out value); } + try { return Dictionary2.TryGetValue(key, out value); } finally { rwLock.ExitReadLock(); } - - return success; } public void ForEach(Action action) { rwLock.EnterReadLock(); - try { foreach (TValue value in Dictionary1.Values) @@ -206,7 +184,6 @@ public void ForEach(Action action) public void ForEach(Action> action) { rwLock.EnterReadLock(); - try { foreach (KeyValuePair entry in Dictionary1) @@ -218,7 +195,6 @@ public void ForEach(Action> action) public void ForEach(Action> action) { rwLock.EnterReadLock(); - try { foreach (KeyValuePair entry in Dictionary2) @@ -247,7 +223,6 @@ public IList FindAll(Predicate predicate) { IList list = new List(); rwLock.EnterReadLock(); - try { foreach (TValue value in Dictionary1.Values) diff --git a/OpenMetaverse.Types/Enums.cs b/OpenMetaverse.Types/Enums.cs index cfa5c346..a75fd760 100644 --- a/OpenMetaverse.Types/Enums.cs +++ b/OpenMetaverse.Types/Enums.cs @@ -1,298 +1,312 @@ -/* - * Copyright (c) 2006-2016, openmetaverse.co - * All rights reserved. - * - * - Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, this - * list of conditions and the following disclaimer. - * - Neither the name of the openmetaverse.co nor the names - * of its contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -using System; - -namespace OpenMetaverse -{ - /// - /// Attribute class that allows extra attributes to be attached to ENUMs - /// - public class EnumInfoAttribute : Attribute - { - /// Text used when presenting ENUM to user - public string Text = string.Empty; - - /// Default initializer - public EnumInfoAttribute() { } - - /// Text used when presenting ENUM to user - public EnumInfoAttribute(string text) - { - this.Text = text; - } - } - - /// - /// The different types of grid assets - /// - public enum AssetType : sbyte - { - /// Unknown asset type - Unknown = -1, - /// Texture asset, stores in JPEG2000 J2C stream format - Texture = 0, - /// Sound asset - Sound = 1, - /// Calling card for another avatar - CallingCard = 2, - /// Link to a location in world - Landmark = 3, - // Legacy script asset, you should never see one of these - //[Obsolete] - //Script = 4, - /// Collection of textures and parameters that can be worn by an avatar - Clothing = 5, - /// Primitive that can contain textures, sounds, - /// scripts and more - Object = 6, - /// Notecard asset - Notecard = 7, - /// Holds a collection of inventory items. "Category" in the Linden viewer - Folder = 8, - /// Linden scripting language script - LSLText = 10, - /// LSO bytecode for a script - LSLBytecode = 11, - /// Uncompressed TGA texture - TextureTGA = 12, - /// Collection of textures and shape parameters that can be worn - Bodypart = 13, - /// Uncompressed sound - SoundWAV = 17, - /// Uncompressed TGA non-square image, not to be used as a - /// texture - ImageTGA = 18, - /// Compressed JPEG non-square image, not to be used as a - /// texture - ImageJPEG = 19, - /// Animation - Animation = 20, - /// Sequence of animations, sounds, chat, and pauses - Gesture = 21, - /// Simstate file - Simstate = 22, - /// Asset is a link to another inventory item - Link = 24, - /// Asset is a link to another inventory folder - LinkFolder = 25, - /// Marketplace Folder. Same as an Category but different display methods. - MarketplaceFolder = 26, - /// Linden mesh format - Mesh = 49, - - Settings = 56 - } - - /// - /// The different types of folder. - /// - public enum FolderType : sbyte - { - /// None folder type - None = -1, - /// Texture folder type - Texture = 0, - /// Sound folder type - Sound = 1, - /// Calling card folder type - CallingCard = 2, - /// Landmark folder type - Landmark = 3, - /// Clothing folder type - Clothing = 5, - /// Object folder type - Object = 6, - /// Notecard folder type - Notecard = 7, - /// The root folder type - Root = 8, - /// LSLText folder - LSLText = 10, - /// Bodyparts folder - BodyPart = 13, - /// Trash folder - Trash = 14, - /// Snapshot folder - Snapshot = 15, - /// Lost And Found folder - LostAndFound = 16, - /// Animation folder - Animation = 20, - /// Gesture folder - Gesture = 21, - /// Favorites folder - Favorites = 23, - /// Ensemble beginning range - EnsembleStart = 26, - /// Ensemble ending range - EnsembleEnd = 45, - /// Current outfit folder - CurrentOutfit = 46, - /// Outfit folder - Outfit = 47, - /// My outfits folder - MyOutfits = 48, - /// Mesh folder - Mesh = 49, - /// Marketplace direct delivery inbox ("Received Items") - Inbox = 50, - /// Marketplace direct delivery outbox - Outbox = 51, - /// Basic root folder - BasicRoot = 52, - /// Marketplace listings folder - MarketplaceListings = 53, - /// Marketplace stock folder - MarkplaceStock = 54, - /// Settings folder - Settings = 56, - /// Hypergrid Suitcase folder - Suitcase = 100 - } - - /// - /// Inventory Item Types, eg Script, Notecard, Folder, etc - /// - public enum InventoryType : sbyte - { - /// Unknown - Unknown = -1, - /// Texture - Texture = 0, - /// Sound - Sound = 1, - /// Calling Card - CallingCard = 2, - /// Landmark - Landmark = 3, - /* - /// Script - //[Obsolete("See LSL")] Script = 4, - /// Clothing - //[Obsolete("See Wearable")] Clothing = 5, - /// Object, both single and coalesced - */ - Object = 6, - /// Notecard - Notecard = 7, - /// - Category = 8, - /// Folder - Folder = 8, - /// - RootCategory = 9, - /// an LSL Script - LSL = 10, - /* - /// - //[Obsolete("See LSL")] LSLBytecode = 11, - /// - //[Obsolete("See Texture")] TextureTGA = 12, - /// - //[Obsolete] Bodypart = 13, - /// - //[Obsolete] Trash = 14, - */ - /// - Snapshot = 15, - /* - /// - //[Obsolete] LostAndFound = 16, - */ - /// - Attachment = 17, - /// - Wearable = 18, - /// - Animation = 19, - /// - Gesture = 20, - - /// - Mesh = 22, - - Settings = 25, - } - - /// - /// Item Sale Status - /// - public enum SaleType : byte - { - /// Not for sale - Not = 0, - /// The original is for sale - Original = 1, - /// Copies are for sale - Copy = 2, - /// The contents of the object are for sale - Contents = 3 - } - - /// - /// Types of wearable assets - /// - public enum WearableType : byte - { - /// Body shape - Shape = 0, - /// Skin textures and attributes - Skin, - /// Hair - Hair, - /// Eyes - Eyes, - /// Shirt - Shirt, - /// Pants - Pants, - /// Shoes - Shoes, - /// Socks - Socks, - /// Jacket - Jacket, - /// Gloves - Gloves, - /// Undershirt - Undershirt, - /// Underpants - Underpants, - /// Skirt - Skirt, - /// Alpha mask to hide parts of the avatar - Alpha, - /// Tattoo - Tattoo, - /// Physics - Physics, - /// Universal - Universal, - /// Invalid wearable asset - Invalid = 255 - }; -} +/* + * Copyright (c) 2006-2016, openmetaverse.co + * All rights reserved. + * + * - Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * - Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * - Neither the name of the openmetaverse.co nor the names + * of its contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +using System; + +namespace OpenMetaverse +{ + /// + /// Attribute class that allows extra attributes to be attached to ENUMs + /// + public class EnumInfoAttribute : Attribute + { + /// Text used when presenting ENUM to user + public string Text = string.Empty; + + /// Default initializer + public EnumInfoAttribute() { } + + /// Text used when presenting ENUM to user + public EnumInfoAttribute(string text) + { + this.Text = text; + } + } + + /// + /// The different types of grid assets + /// + public enum AssetType : sbyte + { + /// Unknown asset type + Unknown = -1, + /// Texture asset, stores in JPEG2000 J2C stream format + Texture = 0, + /// Sound asset + Sound = 1, + /// Calling card for another avatar + CallingCard = 2, + /// Link to a location in world + Landmark = 3, + // Legacy script asset, you should never see one of these + //[Obsolete] + //Script = 4, + /// Collection of textures and parameters that can be worn by an avatar + Clothing = 5, + /// Primitive that can contain textures, sounds, + /// scripts and more + Object = 6, + /// Notecard asset + Notecard = 7, + /// Holds a collection of inventory items. "Category" in the Linden viewer + Folder = 8, + /// Linden scripting language script + LSLText = 10, + /// LSO bytecode for a script + LSLBytecode = 11, + /// Uncompressed TGA texture + TextureTGA = 12, + /// Collection of textures and shape parameters that can be worn + Bodypart = 13, + /// Uncompressed sound + SoundWAV = 17, + /// Uncompressed TGA non-square image, not to be used as a + /// texture + ImageTGA = 18, + /// Compressed JPEG non-square image, not to be used as a + /// texture + ImageJPEG = 19, + /// Animation + Animation = 20, + /// Sequence of animations, sounds, chat, and pauses + Gesture = 21, + /// Simstate file + Simstate = 22, + /// Asset is a link to another inventory item + Link = 24, + /// Asset is a link to another inventory folder + LinkFolder = 25, + /// Marketplace Folder. Same as an Category but different display methods. + MarketplaceFolder = 26, + /// Linden mesh format + Mesh = 49, + + Settings = 56, + /// Render material + Material = 57, + + GLTF = 58, + GLTF_bin = 59, + + OSMaterial = -2 // OpenSimulator specific + } + + /// + /// The different types of folder. + /// + public enum FolderType : sbyte + { + /// None folder type + None = -1, + /// Texture folder type + Texture = 0, + /// Sound folder type + Sound = 1, + /// Calling card folder type + CallingCard = 2, + /// Landmark folder type + Landmark = 3, + /// Clothing folder type + Clothing = 5, + /// Object folder type + Object = 6, + /// Notecard folder type + Notecard = 7, + /// The root folder type + Root = 8, + /// LSLText folder + LSLText = 10, + /// Bodyparts folder + BodyPart = 13, + /// Trash folder + Trash = 14, + /// Snapshot folder + Snapshot = 15, + /// Lost And Found folder + LostAndFound = 16, + /// Animation folder + Animation = 20, + /// Gesture folder + Gesture = 21, + /// Favorites folder + Favorites = 23, + /// Ensemble beginning range + EnsembleStart = 26, + /// Ensemble ending range + EnsembleEnd= 45, + /// Current outfit folder + CurrentOutfit = 46, + /// Outfit folder + Outfit = 47, + /// My outfits folder + MyOutfits = 48, + /// Mesh folder + Mesh = 49, + /// Marketplace direct delivery inbox ("Received Items") + Inbox = 50, + /// Marketplace direct delivery outbox + Outbox = 51, + /// Basic root folder + BasicRoot = 52, + /// Marketplace listings folder + MarketplaceListings = 53, + /// Marketplace stock folder + MarkplaceStock = 54, + /// Settings folder + Settings = 56, + /// Render materials folder + Material = 57, + /// Hypergrid Suitcase folder + Suitcase = 100 + } + + /// + /// Inventory Item Types, eg Script, Notecard, Folder, etc + /// + public enum InventoryType : sbyte + { + /// Unknown + Unknown = -1, + /// Texture + Texture = 0, + /// Sound + Sound = 1, + /// Calling Card + CallingCard = 2, + /// Landmark + Landmark = 3, + /* + /// Script + //[Obsolete("See LSL")] Script = 4, + /// Clothing + //[Obsolete("See Wearable")] Clothing = 5, + /// Object, both single and coalesced + */ + Object = 6, + /// Notecard + Notecard = 7, + /// + Category = 8, + /// Folder + Folder = 8, + /// + RootCategory = 9, + /// an LSL Script + LSL = 10, + /* + /// + //[Obsolete("See LSL")] LSLBytecode = 11, + /// + //[Obsolete("See Texture")] TextureTGA = 12, + /// + //[Obsolete] Bodypart = 13, + /// + //[Obsolete] Trash = 14, + */ + /// + Snapshot = 15, + /* + /// + //[Obsolete] LostAndFound = 16, + */ + /// + Attachment = 17, + /// + Wearable = 18, + /// + Animation = 19, + /// + Gesture = 20, + + /// + Mesh = 22, + + Settings = 25, + + Material = 26, + + GLTF = 27, + GLTF_bin = 28 + } + + /// + /// Item Sale Status + /// + public enum SaleType : byte + { + /// Not for sale + Not = 0, + /// The original is for sale + Original = 1, + /// Copies are for sale + Copy = 2, + /// The contents of the object are for sale + Contents = 3 + } + + /// + /// Types of wearable assets + /// + public enum WearableType : byte + { + /// Body shape + Shape = 0, + /// Skin textures and attributes + Skin, + /// Hair + Hair, + /// Eyes + Eyes, + /// Shirt + Shirt, + /// Pants + Pants, + /// Shoes + Shoes, + /// Socks + Socks, + /// Jacket + Jacket, + /// Gloves + Gloves, + /// Undershirt + Undershirt, + /// Underpants + Underpants, + /// Skirt + Skirt, + /// Alpha mask to hide parts of the avatar + Alpha, + /// Tattoo + Tattoo, + /// Physics + Physics, + /// Universal + Universal, + /// Invalid wearable asset + Invalid = 255 + }; +} diff --git a/OpenMetaverse.Types/EnumsPrimitive.cs b/OpenMetaverse.Types/EnumsPrimitive.cs index e0a94eb3..e72a4938 100644 --- a/OpenMetaverse.Types/EnumsPrimitive.cs +++ b/OpenMetaverse.Types/EnumsPrimitive.cs @@ -234,6 +234,9 @@ public enum ExtraParamType : ushort LightImage = 0x40, /// Whether this object is a mesh Mesh = 0x60, + MeshFlag = 0x70, + RenderMaterial = 0x80, + ReflectionProbe = 0x90 } /// @@ -272,6 +275,8 @@ public enum SculptType : byte /// Mesh = 5, /// + llGLTF = 6, + /// Invert = 64, /// Mirror = 128 diff --git a/OpenMetaverse.Types/Matrix3x3.cs b/OpenMetaverse.Types/Matrix3x3.cs new file mode 100644 index 00000000..6e115a7e --- /dev/null +++ b/OpenMetaverse.Types/Matrix3x3.cs @@ -0,0 +1,937 @@ +/* + * Copyright (c) 2006-2016, openmetaverse.co + * All rights reserved. + * + * - Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * - Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * - Neither the name of the openmetaverse.co nor the names + * of its contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Runtime.Intrinsics.X86; +using System.Runtime.Intrinsics; + +namespace OpenMetaverse +{ + [Serializable] + [StructLayout(LayoutKind.Sequential)] + public struct Matrix3x3 : IEquatable< Matrix3x3> + { + public float M11, M12, M13; + public float M21, M22, M23; + public float M31, M32, M33; + + #region Properties + + public Vector3 AtAxis + { + get + { + return new Vector3(M11, M21, M31); + } + set + { + M11 = value.X; + M21 = value.Y; + M31 = value.Z; + } + } + + public Vector3 LeftAxis + { + get + { + return new Vector3(M12, M22, M32); + } + set + { + M12 = value.X; + M22 = value.Y; + M32 = value.Z; + } + } + + public Vector3 UpAxis + { + get + { + return new Vector3(M13, M23, M33); + } + set + { + M13 = value.X; + M23 = value.Y; + M33 = value.Z; + } + } + + #endregion Properties + + #region Constructors + + public Matrix3x3( + float m11, float m12, float m13, + float m21, float m22, float m23, + float m31, float m32, float m33) + { + M11 = m11; + M12 = m12; + M13 = m13; + + M21 = m21; + M22 = m22; + M23 = m23; + + M31 = m31; + M32 = m32; + M33 = m33; + } + + public Matrix3x3(float roll, float pitch, float yaw) + { + float a = MathF.Cos(roll); + float b = MathF.Sin(roll); + float c = MathF.Cos(pitch); + float d = MathF.Sin(pitch); + float e = MathF.Cos(yaw); + float f = MathF.Sin(yaw); + + float ad = a * d; + float bd = b * d; + M11 = c * e; + M12 = -c * f; + M13 = d; + + M21 = bd * e + a * f; + M22 = -bd * f + a * e; + M23 = -b * c; + + M31 = -ad * e + b * f; + M32 = ad * f + b * e; + M33 = a * c; + } + + public Matrix3x3(Matrix3x3 m) + { + this = m; + } + + #endregion Constructors + + #region Public Methods + + public float Determinant() + { + return Determinant3x3(); + } + + public float Determinant3x3() + { + float diag1 = M11 * M22 * M33; + float diag2 = M12 * M23 * M31; + float diag3 = M13 * M21 * M32; + float diag4 = M31 * M22 * M13; + float diag5 = M32 * M23 * M11; + float diag6 = M33 * M21 * M12; + + return diag1 + diag2 + diag3 - (diag4 + diag5 + diag6); + } + + public float Trace() + { + return M11 + M22 + M33; + } + + /// + /// Convert this matrix to euler rotations + /// + /// X euler angle + /// Y euler angle + /// Z euler angle + public void GetEulerAngles(out float roll, out float pitch, out float yaw) + { + float angleX, angleY, angleZ; + float cx, cy, cz; // cosines + float sx, sz; // sines + + angleY = MathF.Asin(Utils.Clamp(M13, -1f, 1f)); + cy = MathF.Cos(angleY); + + if (MathF.Abs(cy) > 0.005f) + { + // No gimbal lock + cx = M33 / cy; + sx = (-M23) / cy; + + angleX = MathF.Atan2(sx, cx); + + cz = M11 / cy; + sz = (-M12) / cy; + + angleZ = MathF.Atan2(sz, cz); + } + else + { + // Gimbal lock + angleX = 0; + + cz = M22; + sz = M21; + + angleZ = MathF.Atan2(sz, cz); + } + + // Return only positive angles in [0,360] + if (angleX < 0) angleX += 360f; + if (angleY < 0) angleY += 360f; + if (angleZ < 0) angleZ += 360f; + + roll = (float)angleX; + pitch = (float)angleY; + yaw = (float)angleZ; + } + + /// + /// Convert this matrix to a quaternion rotation + /// + /// A quaternion representation of this rotation matrix + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Quaternion GetQuaternion() + { + Quaternion quat = new Quaternion(); + float trace = Trace() + 1f; + + if (trace > float.Epsilon) + { + float s = 0.5f / MathF.Sqrt(trace); + + quat.X = (M32 - M23) * s; + quat.Y = (M13 - M31) * s; + quat.Z = (M21 - M12) * s; + quat.W = 0.25f / s; + } + else + { + if (M11 > M22 && M11 > M33) + { + float s = 2.0f * MathF.Sqrt(1.0f + M11 - M22 - M33); + + quat.X = 0.25f * s; + quat.Y = (M12 + M21) / s; + quat.Z = (M13 + M31) / s; + quat.W = (M23 - M32) / s; + } + else if (M22 > M33) + { + float s = 2.0f * MathF.Sqrt(1.0f + M22 - M11 - M33); + + quat.X = (M12 + M21) / s; + quat.Y = 0.25f * s; + quat.Z = (M23 + M32) / s; + quat.W = (M13 - M31) / s; + } + else + { + float s = 2.0f * MathF.Sqrt(1.0f + M33 - M11 - M22); + + quat.X = (M13 + M31) / s; + quat.Y = (M23 + M32) / s; + quat.Z = 0.25f * s; + quat.W = (M12 - M21) / s; + } + } + + return quat; + } + + public bool Decompose(out Vector3 scale, out Quaternion rotation) + { + float sx = MathF.Sqrt(M11 * M11 + M12 * M12 + M13 * M13); + float sy = MathF.Sqrt(M21 * M21 + M22 * M22 + M23 * M23); + float sz = MathF.Sqrt(M31 * M31 + M32 * M32 + M33 * M33); + + scale = new Vector3(sx, sy, sz); + if (sx == 0.0 || sy == 0.0 || sz == 0.0) + { + rotation = Quaternion.Identity; + return false; + } + + Matrix3x3 m1 = new Matrix3x3( + M11 / sx, M12 / sx, M13 / sx, + M21 / sy, M22 / sy, M23 / sy, + M31 / sz, M32 / sz, M33 / sz); + + rotation = Quaternion.CreateFromRotationMatrix(m1); + return true; + } + + #endregion Public Methods + + #region Static Methods + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Matrix3x3 Add(Matrix3x3 matrix1, in Matrix3x3 matrix2) + { + return new Matrix3x3( + matrix1.M11 + matrix2.M11, + matrix1.M12 + matrix2.M12, + matrix1.M13 + matrix2.M13, + + matrix1.M21 + matrix2.M21, + matrix1.M22 + matrix2.M22, + matrix1.M23 + matrix2.M23, + + matrix1.M31 + matrix2.M31, + matrix1.M32 + matrix2.M32, + matrix1.M33 + matrix2.M33 + ); + } + + public static Matrix3x3 CreateFromAxisAngle(Vector3 axis, float angle) + { + float x = axis.X; + float y = axis.Y; + float z = axis.Z; + float sin = MathF.Sin(angle); + float cos = MathF.Cos(angle); + float xx = x * x; + float yy = y * y; + float zz = z * z; + float xy = x * y; + float xz = x * z; + float yz = y * z; + + return new Matrix3x3( + xx + (cos * (1f - xx)), + xy - (cos * xy) + (sin * z), + xz - (cos * xz) - (sin * y), + + xy - (cos * xy) - (sin * z), + yy + (cos * (1f - yy)), + yz - (cos * yz) + (sin * x), + + xz - (cos * xz) + (sin * y), + yz - (cos * yz) - (sin * x), + zz + (cos * (1f - zz)) + ); + } + + /// + /// Construct a matrix from euler rotation values in radians + /// + /// X euler angle in radians + /// Y euler angle in radians + /// Z euler angle in radians + public static Matrix3x3 CreateFromEulers(float roll, float pitch, float yaw) + { + float a = MathF.Cos(roll); + float b = MathF.Sin(roll); + float c = MathF.Cos(pitch); + float d = MathF.Sin(pitch); + float e = MathF.Cos(yaw); + float f = MathF.Sin(yaw); + + float ad = a * d; + float bd = b * d; + return new Matrix3x3( + c * e, + -c * f, + d, + + bd * e + a * f, + -bd * f + a * e, + -b * c, + + -ad * e + b * f, + ad * f + b * e, + a * c + ); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Matrix3x3 CreateFromQuaternion(Quaternion rot) + { + float x2 = rot.X + rot.X; + float y2 = rot.Y + rot.Y; + float z2 = rot.Z + rot.Z; + + float wx2 = rot.W * x2; + float wy2 = rot.W * y2; + float wz2 = rot.W * z2; + float xx2 = rot.X * x2; + float xy2 = rot.X * y2; + float xz2 = rot.X * z2; + float yy2 = rot.Y * y2; + float yz2 = rot.Y * z2; + float zz2 = rot.Z * z2; + + return new Matrix3x3( + 1.0f - yy2 - zz2, xy2 + wz2, xz2 - wy2, + xy2 - wz2, 1.0f - xx2 - zz2, yz2 + wx2, + xz2 + wy2, yz2 - wx2, 1.0f - xx2 - yy2 + ); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Matrix3x3 CreateFromQuaternion(ref Quaternion rot) + { + float wx2, wy2, wz2; + float xx2, xy2, xz2; + float yy2, yz2; + float zz2; + + if (Sse41.IsSupported) + { + unsafe + { + Vector128 vrot = Sse.LoadVector128((float*)Unsafe.AsPointer(ref rot)); + Vector128 vrot2 = Sse.Add(vrot, vrot); + Vector128 v2 = Sse.Multiply(vrot, vrot2); + xx2 = Vector128.GetElement(v2, 0); + yy2 = Vector128.GetElement(v2, 1); + zz2 = Vector128.GetElement(v2, 3); + + v2 = Sse.Multiply(vrot2, Sse3.Shuffle(vrot, vrot, 0xff)); + wx2 = Vector128.GetElement(v2, 0); + wy2 = Vector128.GetElement(v2, 1); + wz2 = Vector128.GetElement(v2, 2); + + v2 = Sse.Multiply(vrot2, Sse3.Shuffle(vrot, vrot, 0x00)); + xy2 = Vector128.GetElement(v2, 1); + xz2 = Vector128.GetElement(v2, 2); + + yz2 = Vector128.GetElement(vrot, 1) * Vector128.GetElement(vrot2, 2); + + return new Matrix3x3( + 1.0f - yy2 - zz2, xy2 + wz2, xz2 - wy2, + xy2 - wz2, 1.0f - xx2 - zz2, yz2 + wx2, + xz2 + wy2, yz2 - wx2, 1.0f - xx2 - yy2); + } + } + + float x2 = rot.X + rot.X; + float y2 = rot.Y + rot.Y; + float z2 = rot.Z + rot.Z; + + wx2 = rot.W * x2; + wy2 = rot.W * y2; + wz2 = rot.W * z2; + xx2 = rot.X * x2; + xy2 = rot.X * y2; + xz2 = rot.X * z2; + yy2 = rot.Y * y2; + yz2 = rot.Y * z2; + zz2 = rot.Z * z2; + + return new Matrix3x3( + 1.0f - yy2 - zz2, xy2 + wz2, xz2 - wy2, + xy2 - wz2, 1.0f - xx2 - zz2, yz2 + wx2, + xz2 + wy2, yz2 - wx2, 1.0f - xx2 - yy2 + ); + } + + public static Matrix3x3 CreateRotationX(float radians) + { + float cos = MathF.Cos(radians); + float sin = MathF.Sin(radians); + + return new Matrix3x3( + 1f, 0f, 0f, + 0f, cos, sin, + 0f, -sin, cos + ); + } + + public static Matrix3x3 CreateRotationY(float radians) + { + float cos = MathF.Cos(radians); + float sin = MathF.Sin(radians); + + return new Matrix3x3( + cos, 0f, -sin, + 0f, 1f, 0f, + sin, 0f, cos + ); + } + + public static Matrix3x3 CreateRotationZ(float radians) + { + float cos = MathF.Cos(radians); + float sin = MathF.Sin(radians); + + return new Matrix3x3( + cos, sin, 0f, + -sin, cos, 0f, + 0f, 0f, 1f + ); + } + + public static Matrix3x3 CreateScale(Vector3 scale) + { + return new Matrix3x3( + scale.X, 0f, 0f, + 0f, scale.Y, 0f, + 0f, 0f, scale.Z + ); + } + + public static Matrix3x3 Divide(Matrix3x3 matrix1, Matrix3x3 matrix2) + { + return new Matrix3x3( + matrix1.M11 / matrix2.M11, + matrix1.M12 / matrix2.M12, + matrix1.M13 / matrix2.M13, + + matrix1.M21 / matrix2.M21, + matrix1.M22 / matrix2.M22, + matrix1.M23 / matrix2.M23, + + matrix1.M31 / matrix2.M31, + matrix1.M32 / matrix2.M32, + matrix1.M33 / matrix2.M33 + ); + } + + public static Matrix3x3 Divide(Matrix3x3 matrix1, float divider) + { + float oodivider = 1f / divider; + return new Matrix3x3( + matrix1.M11 * oodivider, + matrix1.M12 * oodivider, + matrix1.M13 * oodivider, + + matrix1.M21 * oodivider, + matrix1.M22 * oodivider, + matrix1.M23 * oodivider, + + matrix1.M31 * oodivider, + matrix1.M32 * oodivider, + matrix1.M33 * oodivider + ); + } + + public static Matrix3x3 Lerp(Matrix3x3 matrix1, Matrix3x3 matrix2, float amount) + { + return new Matrix3x3( + matrix1.M11 + ((matrix2.M11 - matrix1.M11) * amount), + matrix1.M12 + ((matrix2.M12 - matrix1.M12) * amount), + matrix1.M13 + ((matrix2.M13 - matrix1.M13) * amount), + + matrix1.M21 + ((matrix2.M21 - matrix1.M21) * amount), + matrix1.M22 + ((matrix2.M22 - matrix1.M22) * amount), + matrix1.M23 + ((matrix2.M23 - matrix1.M23) * amount), + + matrix1.M31 + ((matrix2.M31 - matrix1.M31) * amount), + matrix1.M32 + ((matrix2.M32 - matrix1.M32) * amount), + matrix1.M33 + ((matrix2.M33 - matrix1.M33) * amount) + ); + } + + public static Matrix3x3 Multiply(Matrix3x3 matrix1, Matrix3x3 matrix2) + { + return new Matrix3x3( + matrix1.M11 * matrix2.M11 + matrix1.M12 * matrix2.M21 + matrix1.M13 * matrix2.M31, + matrix1.M11 * matrix2.M12 + matrix1.M12 * matrix2.M22 + matrix1.M13 * matrix2.M32, + matrix1.M11 * matrix2.M13 + matrix1.M12 * matrix2.M23 + matrix1.M13 * matrix2.M33, + + matrix1.M21 * matrix2.M11 + matrix1.M22 * matrix2.M21 + matrix1.M23 * matrix2.M31, + matrix1.M21 * matrix2.M12 + matrix1.M22 * matrix2.M22 + matrix1.M23 * matrix2.M32, + matrix1.M21 * matrix2.M13 + matrix1.M22 * matrix2.M23 + matrix1.M23 * matrix2.M33, + + matrix1.M31 * matrix2.M11 + matrix1.M32 * matrix2.M21 + matrix1.M33 * matrix2.M31, + matrix1.M31 * matrix2.M12 + matrix1.M32 * matrix2.M22 + matrix1.M33 * matrix2.M32, + matrix1.M31 * matrix2.M13 + matrix1.M32 * matrix2.M23 + matrix1.M33 * matrix2.M33 + ); + } + + public static Matrix3x3 Multiply(Matrix3x3 matrix1, float scaleFactor) + { + Matrix3x3 matrix; + matrix.M11 = matrix1.M11 * scaleFactor; + matrix.M12 = matrix1.M12 * scaleFactor; + matrix.M13 = matrix1.M13 * scaleFactor; + + matrix.M21 = matrix1.M21 * scaleFactor; + matrix.M22 = matrix1.M22 * scaleFactor; + matrix.M23 = matrix1.M23 * scaleFactor; + + matrix.M31 = matrix1.M31 * scaleFactor; + matrix.M32 = matrix1.M32 * scaleFactor; + matrix.M33 = matrix1.M33 * scaleFactor; + + return matrix; + } + + public static Matrix3x3 Negate(Matrix3x3 matrix) + { + return new Matrix3x3( + -matrix.M11, -matrix.M12, -matrix.M13, + -matrix.M21, -matrix.M22, -matrix.M23, + -matrix.M31, -matrix.M32, -matrix.M33 + ); + } + + public static Matrix3x3 Subtract(Matrix3x3 matrix1, Matrix3x3 matrix2) + { + return new Matrix3x3( + matrix1.M11 - matrix2.M11, + matrix1.M12 - matrix2.M12, + matrix1.M13 - matrix2.M13, + + matrix1.M21 - matrix2.M21, + matrix1.M22 - matrix2.M22, + matrix1.M23 - matrix2.M23, + + matrix1.M31 - matrix2.M31, + matrix1.M32 - matrix2.M32, + matrix1.M33 - matrix2.M33 + ); + } + + public static Matrix3x3 Transform(Matrix3x3 value, Quaternion rotation) + { + float x2 = rotation.X + rotation.X; + float y2 = rotation.Y + rotation.Y; + float z2 = rotation.Z + rotation.Z; + + float a = (1f - rotation.Y * y2) - rotation.Z * z2; + float b = rotation.X * y2 - rotation.W * z2; + float c = rotation.X * z2 + rotation.W * y2; + float d = rotation.X * y2 + rotation.W * z2; + float e = (1f - rotation.X * x2) - rotation.Z * z2; + float f = rotation.Y * z2 - rotation.W * x2; + float g = rotation.X * z2 - rotation.W * y2; + float h = rotation.Y * z2 + rotation.W * x2; + float i = (1f - rotation.X * x2) - rotation.Y * y2; + + return new Matrix3x3( + value.M11 * a + value.M12 * b + value.M13 * c, + value.M11 * d + value.M12 * e + value.M13 * f, + value.M11 * g + value.M12 * h + value.M13 * i, + + value.M21 * a + value.M22 * b + value.M23 * c, + value.M21 * d + value.M22 * e + value.M23 * f, + value.M21 * g + value.M22 * h + value.M23 * i, + + value.M31 * a + value.M32 * b + value.M33 * c, + value.M31 * d + value.M32 * e + value.M33 * f, + value.M31 * g + value.M32 * h + value.M33 * i + ); + } + + public static Matrix3x3 Transpose( Matrix3x3 matrix) + { + return new Matrix3x3( + matrix.M11, + matrix.M21, + matrix.M31, + matrix.M12, + matrix.M22, + matrix.M32, + matrix.M13, + matrix.M23, + matrix.M33 + ); + } + + public static Matrix3x3 Inverse3x3(Matrix3x3 matrix) + { + if (matrix.Determinant3x3() == 0f) + throw new ArgumentException("Singular matrix inverse not possible"); + + return (Adjoint(matrix) / matrix.Determinant3x3()); + } + + public static Matrix3x3 Inverse(Matrix3x3 matrix) + { + if (matrix.Determinant() == 0f) + throw new ArgumentException("Singular matrix inverse not possible"); + + return Adjoint(matrix) / matrix.Determinant(); + } + + public static Matrix3x3 Adjoint(Matrix3x3 matrix) + { + Matrix3x3 adjointMatrix = new(); + for (int i = 0; i < 3; i++) + { + for (int j = 0; j < 3; j++) + adjointMatrix[i,j] = MathF.Pow(-1, i + j) * ((Minor(matrix, i, j)).Determinant3x3()); + } + + adjointMatrix = Transpose(adjointMatrix); + return adjointMatrix; + } + + public static Matrix3x3 Minor(Matrix3x3 matrix, int row, int col) + { + Matrix3x3 minor = new(); + int m = 0, n = 0; + + for (int i = 0; i < 3; i++) + { + if (i == row) + continue; + n = 0; + for (int j = 0; j < 3; j++) + { + if (j == col) + continue; + minor[m,n] = matrix[i,j]; + n++; + } + m++; + } + + return minor; + } + + #endregion Static Methods + + #region Overrides + + public override bool Equals(object obj) + { + return (obj is Matrix3x3) ? this.Equals(( Matrix3x3)obj) : false; + } + + public bool Equals( Matrix3x3 other) + { + return M11 == other.M11 && M12 == other.M12 && M13 == other.M13 && + M21 == other.M21 && M22 == other.M22 && M23 == other.M23 && + M31 == other.M31 && M32 == other.M32 && M33 == other.M33; + } + + public override int GetHashCode() + { + return + M11.GetHashCode() ^ M12.GetHashCode() ^ M13.GetHashCode() ^ + M21.GetHashCode() ^ M22.GetHashCode() ^ M23.GetHashCode() ^ + M31.GetHashCode() ^ M32.GetHashCode() ^ M33.GetHashCode(); + } + + /// + /// Get a formatted string representation of the vector + /// + /// A string representation of the vector + public override string ToString() + { + return string.Format(Utils.EnUsCulture, + "|{0}, {1}, {2}|\n|{3}, {4}, {5}|\n|{6}, {7} {8}|\n", + M11, M12, M13, M21, M22, M23, M31, M32, M33); + } + + #endregion Overrides + + #region Operators + + public static bool operator ==(Matrix3x3 left, Matrix3x3 right) + { + return left.Equals(right); + } + + public static bool operator !=(Matrix3x3 left, Matrix3x3 right) + { + return !left.Equals(right); + } + + public static Matrix3x3 operator +(Matrix3x3 left, Matrix3x3 right) + { + return Add(left, right); + } + + public static Matrix3x3 operator -(Matrix3x3 matrix) + { + return Negate(matrix); + } + + public static Matrix3x3 operator -(Matrix3x3 left, Matrix3x3 right) + { + return Subtract(left, right); + } + + public static Matrix3x3 operator *(Matrix3x3 left, Matrix3x3 right) + { + return Multiply(left, right); + } + + public static Matrix3x3 operator *(Matrix3x3 left, float scalar) + { + return Multiply(left, scalar); + } + + public static Matrix3x3 operator /(Matrix3x3 left, Matrix3x3 right) + { + return Divide(left, right); + } + + public static Matrix3x3 operator /(Matrix3x3 matrix, float divider) + { + return Divide(matrix, divider); + } + + public Vector3 this[int row] + { + get + { + switch (row) + { + case 0: + return new Vector3(M11, M12, M13); + case 1: + return new Vector3(M21, M22, M23); + case 2: + return new Vector3(M31, M32, M33); + default: + throw new IndexOutOfRangeException("Matrix3x3 row index must be from 0-2"); + } + } + set + { + switch (row) + { + case 0: + M11 = value.X; + M12 = value.Y; + M13 = value.Z; + break; + case 1: + M21 = value.X; + M22 = value.Y; + M23 = value.Z; + break; + case 2: + M31 = value.X; + M32 = value.Y; + M33 = value.Z; + break; + default: + throw new IndexOutOfRangeException("Matrix3x3 row index must be from 0-2"); + } + } + } + + public float this[int row, int column] + { + get + { + switch (row) + { + case 0: + switch (column) + { + case 0: + return M11; + case 1: + return M12; + case 2: + return M13; + default: + throw new IndexOutOfRangeException(" Matrix3x3 row and column values must be from 0-2"); + } + case 1: + switch (column) + { + case 0: + return M21; + case 1: + return M22; + case 2: + return M23; + default: + throw new IndexOutOfRangeException(" Matrix3x3 row and column values must be from 0-2"); + } + case 2: + switch (column) + { + case 0: + return M31; + case 1: + return M32; + case 2: + return M33; + default: + throw new IndexOutOfRangeException(" Matrix3x3 row and column values must be from 0-2"); + } + default: + throw new IndexOutOfRangeException(" Matrix3x3 row and column values must be from 0-2"); + } + } + set + { + switch (row) + { + case 0: + switch (column) + { + case 0: + M11 = value; return; + case 1: + M12 = value; return; + case 2: + M13 = value; return; + default: + throw new IndexOutOfRangeException(" Matrix3x3 row and column values must be from 0-2"); + } + case 1: + switch (column) + { + case 0: + M21 = value; return; + case 1: + M22 = value; return; + case 2: + M23 = value; return; + default: + throw new IndexOutOfRangeException(" Matrix3x3 row and column values must be from 0-2"); + } + case 2: + switch (column) + { + case 0: + M31 = value; return; + case 1: + M32 = value; return; + case 2: + M33 = value; return; + default: + throw new IndexOutOfRangeException(" Matrix3x3 row and column values must be from 0-2"); + } + default: + throw new IndexOutOfRangeException(" Matrix3x3 row and column values must be from 0-2"); + } + } + } + + #endregion Operators + + /// A 3x3 matrix containing all zeroes + public static readonly Matrix3x3 Zero = new(); + + /// A 3x3 identity matrix + public static readonly Matrix3x3 Identity = new( + 1f, 0f, 0f, + 0f, 1f, 0f, + 0f, 0f, 1f); + } +} diff --git a/OpenMetaverse.Types/Matrix4.cs b/OpenMetaverse.Types/Matrix4.cs index 73cbb11a..915a1a72 100644 --- a/OpenMetaverse.Types/Matrix4.cs +++ b/OpenMetaverse.Types/Matrix4.cs @@ -1,1269 +1,1323 @@ -/* - * Copyright (c) 2006-2016, openmetaverse.co - * All rights reserved. - * - * - Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, this - * list of conditions and the following disclaimer. - * - Neither the name of the openmetaverse.co nor the names - * of its contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Runtime.InteropServices; - -namespace OpenMetaverse -{ - [Serializable] - [StructLayout(LayoutKind.Sequential)] - public struct Matrix4 : IEquatable - { - public float M11, M12, M13, M14; - public float M21, M22, M23, M24; - public float M31, M32, M33, M34; - public float M41, M42, M43, M44; - - #region Properties - - public Vector3 AtAxis - { - get - { - return new Vector3(M11, M21, M31); - } - set - { - M11 = value.X; - M21 = value.Y; - M31 = value.Z; - } - } - - public Vector3 LeftAxis - { - get - { - return new Vector3(M12, M22, M32); - } - set - { - M12 = value.X; - M22 = value.Y; - M32 = value.Z; - } - } - - public Vector3 UpAxis - { - get - { - return new Vector3(M13, M23, M33); - } - set - { - M13 = value.X; - M23 = value.Y; - M33 = value.Z; - } - } - - #endregion Properties - - #region Constructors - - public Matrix4( - float m11, float m12, float m13, float m14, - float m21, float m22, float m23, float m24, - float m31, float m32, float m33, float m34, - float m41, float m42, float m43, float m44) - { - M11 = m11; - M12 = m12; - M13 = m13; - M14 = m14; - - M21 = m21; - M22 = m22; - M23 = m23; - M24 = m24; - - M31 = m31; - M32 = m32; - M33 = m33; - M34 = m34; - - M41 = m41; - M42 = m42; - M43 = m43; - M44 = m44; - } - - public Matrix4(float roll, float pitch, float yaw) - { - this = CreateFromEulers(roll, pitch, yaw); - } - - public Matrix4(Matrix4 m) - { - M11 = m.M11; - M12 = m.M12; - M13 = m.M13; - M14 = m.M14; - - M21 = m.M21; - M22 = m.M22; - M23 = m.M23; - M24 = m.M24; - - M31 = m.M31; - M32 = m.M32; - M33 = m.M33; - M34 = m.M34; - - M41 = m.M41; - M42 = m.M42; - M43 = m.M43; - M44 = m.M44; - } - - #endregion Constructors - - #region Public Methods - - public float Determinant() - { - return - M14 * M23 * M32 * M41 - M13 * M24 * M32 * M41 - M14 * M22 * M33 * M41 + M12 * M24 * M33 * M41 + - M13 * M22 * M34 * M41 - M12 * M23 * M34 * M41 - M14 * M23 * M31 * M42 + M13 * M24 * M31 * M42 + - M14 * M21 * M33 * M42 - M11 * M24 * M33 * M42 - M13 * M21 * M34 * M42 + M11 * M23 * M34 * M42 + - M14 * M22 * M31 * M43 - M12 * M24 * M31 * M43 - M14 * M21 * M32 * M43 + M11 * M24 * M32 * M43 + - M12 * M21 * M34 * M43 - M11 * M22 * M34 * M43 - M13 * M22 * M31 * M44 + M12 * M23 * M31 * M44 + - M13 * M21 * M32 * M44 - M11 * M23 * M32 * M44 - M12 * M21 * M33 * M44 + M11 * M22 * M33 * M44; - } - - public float Determinant3x3() - { - float det = 0f; - - float diag1 = M11 * M22 * M33; - float diag2 = M12 * M23 * M31; - float diag3 = M13 * M21 * M32; - float diag4 = M31 * M22 * M13; - float diag5 = M32 * M23 * M11; - float diag6 = M33 * M21 * M12; - - det = diag1 + diag2 + diag3 - (diag4 + diag5 + diag6); - - return det; - } - - public float Trace() - { - return M11 + M22 + M33 + M44; - } - - /// - /// Convert this matrix to euler rotations - /// - /// X euler angle - /// Y euler angle - /// Z euler angle - public void GetEulerAngles(out float roll, out float pitch, out float yaw) - { - double angleX, angleY, angleZ; - double cx, cy, cz; // cosines - double sx, sz; // sines - - angleY = Math.Asin(Utils.Clamp(M13, -1f, 1f)); - cy = Math.Cos(angleY); - - if (Math.Abs(cy) > 0.005f) - { - // No gimbal lock - cx = M33 / cy; - sx = (-M23) / cy; - - angleX = (float)Math.Atan2(sx, cx); - - cz = M11 / cy; - sz = (-M12) / cy; - - angleZ = (float)Math.Atan2(sz, cz); - } - else - { - // Gimbal lock - angleX = 0; - - cz = M22; - sz = M21; - - angleZ = Math.Atan2(sz, cz); - } - - // Return only positive angles in [0,360] - if (angleX < 0) angleX += 360d; - if (angleY < 0) angleY += 360d; - if (angleZ < 0) angleZ += 360d; - - roll = (float)angleX; - pitch = (float)angleY; - yaw = (float)angleZ; - } - - /// - /// Convert this matrix to a quaternion rotation - /// - /// A quaternion representation of this rotation matrix - public Quaternion GetQuaternion() - { - Quaternion quat = new Quaternion(); - float trace = Trace() + 1f; - - if (trace > Single.Epsilon) - { - float s = 0.5f / (float)Math.Sqrt(trace); - - quat.X = (M32 - M23) * s; - quat.Y = (M13 - M31) * s; - quat.Z = (M21 - M12) * s; - quat.W = 0.25f / s; - } - else - { - if (M11 > M22 && M11 > M33) - { - float s = 2.0f * (float)Math.Sqrt(1.0f + M11 - M22 - M33); - - quat.X = 0.25f * s; - quat.Y = (M12 + M21) / s; - quat.Z = (M13 + M31) / s; - quat.W = (M23 - M32) / s; - } - else if (M22 > M33) - { - float s = 2.0f * (float)Math.Sqrt(1.0f + M22 - M11 - M33); - - quat.X = (M12 + M21) / s; - quat.Y = 0.25f * s; - quat.Z = (M23 + M32) / s; - quat.W = (M13 - M31) / s; - } - else - { - float s = 2.0f * (float)Math.Sqrt(1.0f + M33 - M11 - M22); - - quat.X = (M13 + M31) / s; - quat.Y = (M23 + M32) / s; - quat.Z = 0.25f * s; - quat.W = (M12 - M21) / s; - } - } - - return quat; - } - - public bool Decompose(out Vector3 scale, out Quaternion rotation, out Vector3 translation) - { - translation.X = this.M41; - translation.Y = this.M42; - translation.Z = this.M43; - - float xs = (Math.Sign(M11 * M12 * M13 * M14) < 0) ? -1 : 1; - float ys = (Math.Sign(M21 * M22 * M23 * M24) < 0) ? -1 : 1; - float zs = (Math.Sign(M31 * M32 * M33 * M34) < 0) ? -1 : 1; - - scale.X = xs * (float)Math.Sqrt(this.M11 * this.M11 + this.M12 * this.M12 + this.M13 * this.M13); - scale.Y = ys * (float)Math.Sqrt(this.M21 * this.M21 + this.M22 * this.M22 + this.M23 * this.M23); - scale.Z = zs * (float)Math.Sqrt(this.M31 * this.M31 + this.M32 * this.M32 + this.M33 * this.M33); - - if (scale.X == 0.0 || scale.Y == 0.0 || scale.Z == 0.0) - { - rotation = Quaternion.Identity; - return false; - } - - Matrix4 m1 = new Matrix4(this.M11 / scale.X, M12 / scale.X, M13 / scale.X, 0, - this.M21 / scale.Y, M22 / scale.Y, M23 / scale.Y, 0, - this.M31 / scale.Z, M32 / scale.Z, M33 / scale.Z, 0, - 0, 0, 0, 1); - - rotation = Quaternion.CreateFromRotationMatrix(m1); - return true; - } - - #endregion Public Methods - - #region Static Methods - - public static Matrix4 Add(Matrix4 matrix1, Matrix4 matrix2) - { - Matrix4 matrix; - matrix.M11 = matrix1.M11 + matrix2.M11; - matrix.M12 = matrix1.M12 + matrix2.M12; - matrix.M13 = matrix1.M13 + matrix2.M13; - matrix.M14 = matrix1.M14 + matrix2.M14; - - matrix.M21 = matrix1.M21 + matrix2.M21; - matrix.M22 = matrix1.M22 + matrix2.M22; - matrix.M23 = matrix1.M23 + matrix2.M23; - matrix.M24 = matrix1.M24 + matrix2.M24; - - matrix.M31 = matrix1.M31 + matrix2.M31; - matrix.M32 = matrix1.M32 + matrix2.M32; - matrix.M33 = matrix1.M33 + matrix2.M33; - matrix.M34 = matrix1.M34 + matrix2.M34; - - matrix.M41 = matrix1.M41 + matrix2.M41; - matrix.M42 = matrix1.M42 + matrix2.M42; - matrix.M43 = matrix1.M43 + matrix2.M43; - matrix.M44 = matrix1.M44 + matrix2.M44; - return matrix; - } - - public static Matrix4 CreateFromAxisAngle(Vector3 axis, float angle) - { - Matrix4 matrix = new Matrix4(); - - float x = axis.X; - float y = axis.Y; - float z = axis.Z; - float sin = (float)Math.Sin(angle); - float cos = (float)Math.Cos(angle); - float xx = x * x; - float yy = y * y; - float zz = z * z; - float xy = x * y; - float xz = x * z; - float yz = y * z; - - matrix.M11 = xx + (cos * (1f - xx)); - matrix.M12 = (xy - (cos * xy)) + (sin * z); - matrix.M13 = (xz - (cos * xz)) - (sin * y); - //matrix.M14 = 0f; - - matrix.M21 = (xy - (cos * xy)) - (sin * z); - matrix.M22 = yy + (cos * (1f - yy)); - matrix.M23 = (yz - (cos * yz)) + (sin * x); - //matrix.M24 = 0f; - - matrix.M31 = (xz - (cos * xz)) + (sin * y); - matrix.M32 = (yz - (cos * yz)) - (sin * x); - matrix.M33 = zz + (cos * (1f - zz)); - //matrix.M34 = 0f; - - //matrix.M41 = matrix.M42 = matrix.M43 = 0f; - matrix.M44 = 1f; - - return matrix; - } - - /// - /// Construct a matrix from euler rotation values in radians - /// - /// X euler angle in radians - /// Y euler angle in radians - /// Z euler angle in radians - public static Matrix4 CreateFromEulers(float roll, float pitch, float yaw) - { - Matrix4 m; - - float a, b, c, d, e, f; - float ad, bd; - - a = (float)Math.Cos(roll); - b = (float)Math.Sin(roll); - c = (float)Math.Cos(pitch); - d = (float)Math.Sin(pitch); - e = (float)Math.Cos(yaw); - f = (float)Math.Sin(yaw); - - ad = a * d; - bd = b * d; - - m.M11 = c * e; - m.M12 = -c * f; - m.M13 = d; - m.M14 = 0f; - - m.M21 = bd * e + a * f; - m.M22 = -bd * f + a * e; - m.M23 = -b * c; - m.M24 = 0f; - - m.M31 = -ad * e + b * f; - m.M32 = ad * f + b * e; - m.M33 = a * c; - m.M34 = 0f; - - m.M41 = m.M42 = m.M43 = 0f; - m.M44 = 1f; - - return m; - } - - public static Matrix4 CreateFromQuaternion(Quaternion rot) - { - Matrix4 matrix; - - float x2 = rot.X + rot.X; - float y2 = rot.Y + rot.Y; - float z2 = rot.Z + rot.Z; - - float wx2 = rot.W * x2; - float wy2 = rot.W * y2; - float wz2 = rot.W * z2; - float xx2 = rot.X * x2; - float xy2 = rot.X * y2; - float xz2 = rot.X * z2; - float yy2 = rot.Y * y2; - float yz2 = rot.Y * z2; - float zz2 = rot.Z * z2; - - matrix.M11 = 1.0f - yy2 - zz2; - matrix.M12 = xy2 - wz2; - matrix.M13 = xz2 + wy2; - matrix.M14 = 0f; - - matrix.M21 = xy2 + wz2; - matrix.M22 = 1.0f - xx2 - zz2; - matrix.M23 = yz2 - wx2; - matrix.M24 = 0f; - - matrix.M31 = xz2 - wy2; - matrix.M32 = yz2 + wx2; - matrix.M33 = 1.0f - xx2 - yy2; - matrix.M34 = 0f; - - matrix.M43 = matrix.M42 = matrix.M41 = 0f; - matrix.M44 = 1f; - - return matrix; - } - - public static Matrix4 CreateLookAt(Vector3 cameraPosition, Vector3 cameraTarget, Vector3 cameraUpVector) - { - Matrix4 matrix; - - Vector3 z = Vector3.Normalize(cameraPosition - cameraTarget); - Vector3 x = Vector3.Normalize(Vector3.Cross(cameraUpVector, z)); - Vector3 y = Vector3.Cross(z, x); - - matrix.M11 = x.X; - matrix.M12 = y.X; - matrix.M13 = z.X; - matrix.M14 = 0f; - - matrix.M21 = x.Y; - matrix.M22 = y.Y; - matrix.M23 = z.Y; - matrix.M24 = 0f; - - matrix.M31 = x.Z; - matrix.M32 = y.Z; - matrix.M33 = z.Z; - matrix.M34 = 0f; - - matrix.M41 = -Vector3.Dot(x, cameraPosition); - matrix.M42 = -Vector3.Dot(y, cameraPosition); - matrix.M43 = -Vector3.Dot(z, cameraPosition); - matrix.M44 = 1f; - - return matrix; - } - - public static Matrix4 CreateRotationX(float radians) - { - Matrix4 matrix; - - float cos = (float)Math.Cos(radians); - float sin = (float)Math.Sin(radians); - - matrix.M11 = 1f; - matrix.M12 = 0f; - matrix.M13 = 0f; - matrix.M14 = 0f; - - matrix.M21 = 0f; - matrix.M22 = cos; - matrix.M23 = sin; - matrix.M24 = 0f; - - matrix.M31 = 0f; - matrix.M32 = -sin; - matrix.M33 = cos; - matrix.M34 = 0f; - - matrix.M41 = 0f; - matrix.M42 = 0f; - matrix.M43 = 0f; - matrix.M44 = 1f; - - return matrix; - } - - public static Matrix4 CreateRotationY(float radians) - { - Matrix4 matrix; - - float cos = (float)Math.Cos(radians); - float sin = (float)Math.Sin(radians); - - matrix.M11 = cos; - matrix.M12 = 0f; - matrix.M13 = -sin; - matrix.M14 = 0f; - - matrix.M21 = 0f; - matrix.M22 = 1f; - matrix.M23 = 0f; - matrix.M24 = 0f; - - matrix.M31 = sin; - matrix.M32 = 0f; - matrix.M33 = cos; - matrix.M34 = 0f; - - matrix.M41 = 0f; - matrix.M42 = 0f; - matrix.M43 = 0f; - matrix.M44 = 1f; - - return matrix; - } - - public static Matrix4 CreateRotationZ(float radians) - { - Matrix4 matrix; - - float cos = (float)Math.Cos(radians); - float sin = (float)Math.Sin(radians); - - matrix.M11 = cos; - matrix.M12 = sin; - matrix.M13 = 0f; - matrix.M14 = 0f; - - matrix.M21 = -sin; - matrix.M22 = cos; - matrix.M23 = 0f; - matrix.M24 = 0f; - - matrix.M31 = 0f; - matrix.M32 = 0f; - matrix.M33 = 1f; - matrix.M34 = 0f; - - matrix.M41 = 0f; - matrix.M42 = 0f; - matrix.M43 = 0f; - matrix.M44 = 1f; - - return matrix; - } - - public static Matrix4 CreateScale(Vector3 scale) - { - Matrix4 matrix; - - matrix.M11 = scale.X; - matrix.M12 = 0f; - matrix.M13 = 0f; - matrix.M14 = 0f; - - matrix.M21 = 0f; - matrix.M22 = scale.Y; - matrix.M23 = 0f; - matrix.M24 = 0f; - - matrix.M31 = 0f; - matrix.M32 = 0f; - matrix.M33 = scale.Z; - matrix.M34 = 0f; - - matrix.M41 = 0f; - matrix.M42 = 0f; - matrix.M43 = 0f; - matrix.M44 = 1f; - - return matrix; - } - - public static Matrix4 CreateTranslation(Vector3 position) - { - Matrix4 matrix; - - matrix.M11 = 1f; - matrix.M12 = 0f; - matrix.M13 = 0f; - matrix.M14 = 0f; - - matrix.M21 = 0f; - matrix.M22 = 1f; - matrix.M23 = 0f; - matrix.M24 = 0f; - - matrix.M31 = 0f; - matrix.M32 = 0f; - matrix.M33 = 1f; - matrix.M34 = 0f; - - matrix.M41 = position.X; - matrix.M42 = position.Y; - matrix.M43 = position.Z; - matrix.M44 = 1f; - - return matrix; - } - - public static Matrix4 CreateWorld(Vector3 position, Vector3 forward, Vector3 up) - { - Matrix4 result; - - // Normalize forward vector - forward.Normalize(); - - // Calculate right vector - Vector3 right = Vector3.Cross(forward, up); - right.Normalize(); - - // Recalculate up vector - up = Vector3.Cross(right, forward); - up.Normalize(); - - result.M11 = right.X; - result.M12 = right.Y; - result.M13 = right.Z; - result.M14 = 0.0f; - - result.M21 = up.X; - result.M22 = up.Y; - result.M23 = up.Z; - result.M24 = 0.0f; - - result.M31 = -forward.X; - result.M32 = -forward.Y; - result.M33 = -forward.Z; - result.M34 = 0.0f; - - result.M41 = position.X; - result.M42 = position.Y; - result.M43 = position.Z; - result.M44 = 1.0f; - - return result; - } - - public static Matrix4 Divide(Matrix4 matrix1, Matrix4 matrix2) - { - Matrix4 matrix; - - matrix.M11 = matrix1.M11 / matrix2.M11; - matrix.M12 = matrix1.M12 / matrix2.M12; - matrix.M13 = matrix1.M13 / matrix2.M13; - matrix.M14 = matrix1.M14 / matrix2.M14; - - matrix.M21 = matrix1.M21 / matrix2.M21; - matrix.M22 = matrix1.M22 / matrix2.M22; - matrix.M23 = matrix1.M23 / matrix2.M23; - matrix.M24 = matrix1.M24 / matrix2.M24; - - matrix.M31 = matrix1.M31 / matrix2.M31; - matrix.M32 = matrix1.M32 / matrix2.M32; - matrix.M33 = matrix1.M33 / matrix2.M33; - matrix.M34 = matrix1.M34 / matrix2.M34; - - matrix.M41 = matrix1.M41 / matrix2.M41; - matrix.M42 = matrix1.M42 / matrix2.M42; - matrix.M43 = matrix1.M43 / matrix2.M43; - matrix.M44 = matrix1.M44 / matrix2.M44; - - return matrix; - } - - public static Matrix4 Divide(Matrix4 matrix1, float divider) - { - Matrix4 matrix; - - float oodivider = 1f / divider; - matrix.M11 = matrix1.M11 * oodivider; - matrix.M12 = matrix1.M12 * oodivider; - matrix.M13 = matrix1.M13 * oodivider; - matrix.M14 = matrix1.M14 * oodivider; - - matrix.M21 = matrix1.M21 * oodivider; - matrix.M22 = matrix1.M22 * oodivider; - matrix.M23 = matrix1.M23 * oodivider; - matrix.M24 = matrix1.M24 * oodivider; - - matrix.M31 = matrix1.M31 * oodivider; - matrix.M32 = matrix1.M32 * oodivider; - matrix.M33 = matrix1.M33 * oodivider; - matrix.M34 = matrix1.M34 * oodivider; - - matrix.M41 = matrix1.M41 * oodivider; - matrix.M42 = matrix1.M42 * oodivider; - matrix.M43 = matrix1.M43 * oodivider; - matrix.M44 = matrix1.M44 * oodivider; - - return matrix; - } - - public static Matrix4 Lerp(Matrix4 matrix1, Matrix4 matrix2, float amount) - { - Matrix4 matrix; - - matrix.M11 = matrix1.M11 + ((matrix2.M11 - matrix1.M11) * amount); - matrix.M12 = matrix1.M12 + ((matrix2.M12 - matrix1.M12) * amount); - matrix.M13 = matrix1.M13 + ((matrix2.M13 - matrix1.M13) * amount); - matrix.M14 = matrix1.M14 + ((matrix2.M14 - matrix1.M14) * amount); - - matrix.M21 = matrix1.M21 + ((matrix2.M21 - matrix1.M21) * amount); - matrix.M22 = matrix1.M22 + ((matrix2.M22 - matrix1.M22) * amount); - matrix.M23 = matrix1.M23 + ((matrix2.M23 - matrix1.M23) * amount); - matrix.M24 = matrix1.M24 + ((matrix2.M24 - matrix1.M24) * amount); - - matrix.M31 = matrix1.M31 + ((matrix2.M31 - matrix1.M31) * amount); - matrix.M32 = matrix1.M32 + ((matrix2.M32 - matrix1.M32) * amount); - matrix.M33 = matrix1.M33 + ((matrix2.M33 - matrix1.M33) * amount); - matrix.M34 = matrix1.M34 + ((matrix2.M34 - matrix1.M34) * amount); - - matrix.M41 = matrix1.M41 + ((matrix2.M41 - matrix1.M41) * amount); - matrix.M42 = matrix1.M42 + ((matrix2.M42 - matrix1.M42) * amount); - matrix.M43 = matrix1.M43 + ((matrix2.M43 - matrix1.M43) * amount); - matrix.M44 = matrix1.M44 + ((matrix2.M44 - matrix1.M44) * amount); - - return matrix; - } - - public static Matrix4 Multiply(Matrix4 matrix1, Matrix4 matrix2) - { - return new Matrix4( - matrix1.M11 * matrix2.M11 + matrix1.M12 * matrix2.M21 + matrix1.M13 * matrix2.M31 + matrix1.M14 * matrix2.M41, - matrix1.M11 * matrix2.M12 + matrix1.M12 * matrix2.M22 + matrix1.M13 * matrix2.M32 + matrix1.M14 * matrix2.M42, - matrix1.M11 * matrix2.M13 + matrix1.M12 * matrix2.M23 + matrix1.M13 * matrix2.M33 + matrix1.M14 * matrix2.M43, - matrix1.M11 * matrix2.M14 + matrix1.M12 * matrix2.M24 + matrix1.M13 * matrix2.M34 + matrix1.M14 * matrix2.M44, - - matrix1.M21 * matrix2.M11 + matrix1.M22 * matrix2.M21 + matrix1.M23 * matrix2.M31 + matrix1.M24 * matrix2.M41, - matrix1.M21 * matrix2.M12 + matrix1.M22 * matrix2.M22 + matrix1.M23 * matrix2.M32 + matrix1.M24 * matrix2.M42, - matrix1.M21 * matrix2.M13 + matrix1.M22 * matrix2.M23 + matrix1.M23 * matrix2.M33 + matrix1.M24 * matrix2.M43, - matrix1.M21 * matrix2.M14 + matrix1.M22 * matrix2.M24 + matrix1.M23 * matrix2.M34 + matrix1.M24 * matrix2.M44, - - matrix1.M31 * matrix2.M11 + matrix1.M32 * matrix2.M21 + matrix1.M33 * matrix2.M31 + matrix1.M34 * matrix2.M41, - matrix1.M31 * matrix2.M12 + matrix1.M32 * matrix2.M22 + matrix1.M33 * matrix2.M32 + matrix1.M34 * matrix2.M42, - matrix1.M31 * matrix2.M13 + matrix1.M32 * matrix2.M23 + matrix1.M33 * matrix2.M33 + matrix1.M34 * matrix2.M43, - matrix1.M31 * matrix2.M14 + matrix1.M32 * matrix2.M24 + matrix1.M33 * matrix2.M34 + matrix1.M34 * matrix2.M44, - - matrix1.M41 * matrix2.M11 + matrix1.M42 * matrix2.M21 + matrix1.M43 * matrix2.M31 + matrix1.M44 * matrix2.M41, - matrix1.M41 * matrix2.M12 + matrix1.M42 * matrix2.M22 + matrix1.M43 * matrix2.M32 + matrix1.M44 * matrix2.M42, - matrix1.M41 * matrix2.M13 + matrix1.M42 * matrix2.M23 + matrix1.M43 * matrix2.M33 + matrix1.M44 * matrix2.M43, - matrix1.M41 * matrix2.M14 + matrix1.M42 * matrix2.M24 + matrix1.M43 * matrix2.M34 + matrix1.M44 * matrix2.M44 - ); - } - - public static Matrix4 Multiply(Matrix4 matrix1, float scaleFactor) - { - Matrix4 matrix; - matrix.M11 = matrix1.M11 * scaleFactor; - matrix.M12 = matrix1.M12 * scaleFactor; - matrix.M13 = matrix1.M13 * scaleFactor; - matrix.M14 = matrix1.M14 * scaleFactor; - - matrix.M21 = matrix1.M21 * scaleFactor; - matrix.M22 = matrix1.M22 * scaleFactor; - matrix.M23 = matrix1.M23 * scaleFactor; - matrix.M24 = matrix1.M24 * scaleFactor; - - matrix.M31 = matrix1.M31 * scaleFactor; - matrix.M32 = matrix1.M32 * scaleFactor; - matrix.M33 = matrix1.M33 * scaleFactor; - matrix.M34 = matrix1.M34 * scaleFactor; - - matrix.M41 = matrix1.M41 * scaleFactor; - matrix.M42 = matrix1.M42 * scaleFactor; - matrix.M43 = matrix1.M43 * scaleFactor; - matrix.M44 = matrix1.M44 * scaleFactor; - return matrix; - } - - public static Matrix4 Negate(Matrix4 matrix) - { - Matrix4 result; - result.M11 = -matrix.M11; - result.M12 = -matrix.M12; - result.M13 = -matrix.M13; - result.M14 = -matrix.M14; - - result.M21 = -matrix.M21; - result.M22 = -matrix.M22; - result.M23 = -matrix.M23; - result.M24 = -matrix.M24; - - result.M31 = -matrix.M31; - result.M32 = -matrix.M32; - result.M33 = -matrix.M33; - result.M34 = -matrix.M34; - - result.M41 = -matrix.M41; - result.M42 = -matrix.M42; - result.M43 = -matrix.M43; - result.M44 = -matrix.M44; - return result; - } - - public static Matrix4 Subtract(Matrix4 matrix1, Matrix4 matrix2) - { - Matrix4 matrix; - matrix.M11 = matrix1.M11 - matrix2.M11; - matrix.M12 = matrix1.M12 - matrix2.M12; - matrix.M13 = matrix1.M13 - matrix2.M13; - matrix.M14 = matrix1.M14 - matrix2.M14; - - matrix.M21 = matrix1.M21 - matrix2.M21; - matrix.M22 = matrix1.M22 - matrix2.M22; - matrix.M23 = matrix1.M23 - matrix2.M23; - matrix.M24 = matrix1.M24 - matrix2.M24; - - matrix.M31 = matrix1.M31 - matrix2.M31; - matrix.M32 = matrix1.M32 - matrix2.M32; - matrix.M33 = matrix1.M33 - matrix2.M33; - matrix.M34 = matrix1.M34 - matrix2.M34; - - matrix.M41 = matrix1.M41 - matrix2.M41; - matrix.M42 = matrix1.M42 - matrix2.M42; - matrix.M43 = matrix1.M43 - matrix2.M43; - matrix.M44 = matrix1.M44 - matrix2.M44; - return matrix; - } - - public static Matrix4 Transform(Matrix4 value, Quaternion rotation) - { - Matrix4 matrix; - - float x2 = rotation.X + rotation.X; - float y2 = rotation.Y + rotation.Y; - float z2 = rotation.Z + rotation.Z; - - float a = (1f - rotation.Y * y2) - rotation.Z * z2; - float b = rotation.X * y2 - rotation.W * z2; - float c = rotation.X * z2 + rotation.W * y2; - float d = rotation.X * y2 + rotation.W * z2; - float e = (1f - rotation.X * x2) - rotation.Z * z2; - float f = rotation.Y * z2 - rotation.W * x2; - float g = rotation.X * z2 - rotation.W * y2; - float h = rotation.Y * z2 + rotation.W * x2; - float i = (1f - rotation.X * x2) - rotation.Y * y2; - - matrix.M11 = ((value.M11 * a) + (value.M12 * b)) + (value.M13 * c); - matrix.M12 = ((value.M11 * d) + (value.M12 * e)) + (value.M13 * f); - matrix.M13 = ((value.M11 * g) + (value.M12 * h)) + (value.M13 * i); - matrix.M14 = value.M14; - - matrix.M21 = ((value.M21 * a) + (value.M22 * b)) + (value.M23 * c); - matrix.M22 = ((value.M21 * d) + (value.M22 * e)) + (value.M23 * f); - matrix.M23 = ((value.M21 * g) + (value.M22 * h)) + (value.M23 * i); - matrix.M24 = value.M24; - - matrix.M31 = ((value.M31 * a) + (value.M32 * b)) + (value.M33 * c); - matrix.M32 = ((value.M31 * d) + (value.M32 * e)) + (value.M33 * f); - matrix.M33 = ((value.M31 * g) + (value.M32 * h)) + (value.M33 * i); - matrix.M34 = value.M34; - - matrix.M41 = ((value.M41 * a) + (value.M42 * b)) + (value.M43 * c); - matrix.M42 = ((value.M41 * d) + (value.M42 * e)) + (value.M43 * f); - matrix.M43 = ((value.M41 * g) + (value.M42 * h)) + (value.M43 * i); - matrix.M44 = value.M44; - - return matrix; - } - - public static Matrix4 Transpose(Matrix4 matrix) - { - Matrix4 result; - - result.M11 = matrix.M11; - result.M12 = matrix.M21; - result.M13 = matrix.M31; - result.M14 = matrix.M41; - - result.M21 = matrix.M12; - result.M22 = matrix.M22; - result.M23 = matrix.M32; - result.M24 = matrix.M42; - - result.M31 = matrix.M13; - result.M32 = matrix.M23; - result.M33 = matrix.M33; - result.M34 = matrix.M43; - - result.M41 = matrix.M14; - result.M42 = matrix.M24; - result.M43 = matrix.M34; - result.M44 = matrix.M44; - - return result; - } - - public static Matrix4 Inverse3x3(Matrix4 matrix) - { - if (matrix.Determinant3x3() == 0f) - throw new ArgumentException("Singular matrix inverse not possible"); - - return (Adjoint3x3(matrix) / matrix.Determinant3x3()); - } - - public static Matrix4 Adjoint3x3(Matrix4 matrix) - { - Matrix4 adjointMatrix = new Matrix4(); - for (int i = 0; i < 4; i++) - { - for (int j = 0; j < 4; j++) - adjointMatrix[i, j] = (float)(Math.Pow(-1, i + j) * (Minor(matrix, i, j).Determinant3x3())); - } - - adjointMatrix = Transpose(adjointMatrix); - return adjointMatrix; - } - - public static Matrix4 Inverse(Matrix4 matrix) - { - if (matrix.Determinant() == 0f) - throw new ArgumentException("Singular matrix inverse not possible"); - - return (Adjoint(matrix) / matrix.Determinant()); - } - - public static Matrix4 Adjoint(Matrix4 matrix) - { - Matrix4 adjointMatrix = new Matrix4(); - for (int i = 0; i < 4; i++) - { - for (int j = 0; j < 4; j++) - adjointMatrix[i, j] = (float)(Math.Pow(-1, i + j) * ((Minor(matrix, i, j)).Determinant3x3())); - } - - adjointMatrix = Transpose(adjointMatrix); - return adjointMatrix; - } - - public static Matrix4 Minor(Matrix4 matrix, int row, int col) - { - Matrix4 minor = new Matrix4(); - int m = 0, n = 0; - - for (int i = 0; i < 4; i++) - { - if (i == row) - continue; - n = 0; - for (int j = 0; j < 4; j++) - { - if (j == col) - continue; - minor[m, n] = matrix[i, j]; - n++; - } - m++; - } - - return minor; - } - - #endregion Static Methods - - #region Overrides - - public override bool Equals(object obj) - { - return (obj is Matrix4) ? this.Equals((Matrix4)obj) : false; - } - - public bool Equals(Matrix4 other) - { - return M11 == other.M11 && M12 == other.M12 && M13 == other.M13 && M14 == other.M14 && - M21 == other.M21 && M22 == other.M22 && M23 == other.M23 && M24 == other.M24 && - M31 == other.M31 && M32 == other.M32 && M33 == other.M33 && M14 == other.M34 && - M41 == other.M41 && M42 == other.M42 && M43 == other.M43 && M44 == other.M44; - } - - public override int GetHashCode() - { - return - M11.GetHashCode() ^ M12.GetHashCode() ^ M13.GetHashCode() ^ M14.GetHashCode() ^ - M21.GetHashCode() ^ M22.GetHashCode() ^ M23.GetHashCode() ^ M24.GetHashCode() ^ - M31.GetHashCode() ^ M32.GetHashCode() ^ M33.GetHashCode() ^ M34.GetHashCode() ^ - M41.GetHashCode() ^ M42.GetHashCode() ^ M43.GetHashCode() ^ M44.GetHashCode(); - } - - /// - /// Get a formatted string representation of the vector - /// - /// A string representation of the vector - public override string ToString() - { - return string.Format(Utils.EnUsCulture, - "|{0}, {1}, {2}, {3}|\n|{4}, {5}, {6}, {7}|\n|{8}, {9}, {10}, {11}|\n|{12}, {13}, {14}, {15}|", - M11, M12, M13, M14, M21, M22, M23, M24, M31, M32, M33, M34, M41, M42, M43, M44); - } - - #endregion Overrides - - #region Operators - - public static bool operator ==(Matrix4 left, Matrix4 right) - { - return left.Equals(right); - } - - public static bool operator !=(Matrix4 left, Matrix4 right) - { - return !left.Equals(right); - } - - public static Matrix4 operator +(Matrix4 left, Matrix4 right) - { - return Add(left, right); - } - - public static Matrix4 operator -(Matrix4 matrix) - { - return Negate(matrix); - } - - public static Matrix4 operator -(Matrix4 left, Matrix4 right) - { - return Subtract(left, right); - } - - public static Matrix4 operator *(Matrix4 left, Matrix4 right) - { - return Multiply(left, right); - } - - public static Matrix4 operator *(Matrix4 left, float scalar) - { - return Multiply(left, scalar); - } - - public static Matrix4 operator /(Matrix4 left, Matrix4 right) - { - return Divide(left, right); - } - - public static Matrix4 operator /(Matrix4 matrix, float divider) - { - return Divide(matrix, divider); - } - - public Vector4 this[int row] - { - get - { - switch (row) - { - case 0: - return new Vector4(M11, M12, M13, M14); - case 1: - return new Vector4(M21, M22, M23, M24); - case 2: - return new Vector4(M31, M32, M33, M34); - case 3: - return new Vector4(M41, M42, M43, M44); - default: - throw new IndexOutOfRangeException("Matrix4 row index must be from 0-3"); - } - } - set - { - switch (row) - { - case 0: - M11 = value.X; - M12 = value.Y; - M13 = value.Z; - M14 = value.W; - break; - case 1: - M21 = value.X; - M22 = value.Y; - M23 = value.Z; - M24 = value.W; - break; - case 2: - M31 = value.X; - M32 = value.Y; - M33 = value.Z; - M34 = value.W; - break; - case 3: - M41 = value.X; - M42 = value.Y; - M43 = value.Z; - M44 = value.W; - break; - default: - throw new IndexOutOfRangeException("Matrix4 row index must be from 0-3"); - } - } - } - - public float this[int row, int column] - { - get - { - switch (row) - { - case 0: - switch (column) - { - case 0: - return M11; - case 1: - return M12; - case 2: - return M13; - case 3: - return M14; - default: - throw new IndexOutOfRangeException("Matrix4 row and column values must be from 0-3"); - } - case 1: - switch (column) - { - case 0: - return M21; - case 1: - return M22; - case 2: - return M23; - case 3: - return M24; - default: - throw new IndexOutOfRangeException("Matrix4 row and column values must be from 0-3"); - } - case 2: - switch (column) - { - case 0: - return M31; - case 1: - return M32; - case 2: - return M33; - case 3: - return M34; - default: - throw new IndexOutOfRangeException("Matrix4 row and column values must be from 0-3"); - } - case 3: - switch (column) - { - case 0: - return M41; - case 1: - return M42; - case 2: - return M43; - case 3: - return M44; - default: - throw new IndexOutOfRangeException("Matrix4 row and column values must be from 0-3"); - } - default: - throw new IndexOutOfRangeException("Matrix4 row and column values must be from 0-3"); - } - } - set - { - switch (row) - { - case 0: - switch (column) - { - case 0: - M11 = value; return; - case 1: - M12 = value; return; - case 2: - M13 = value; return; - case 3: - M14 = value; return; - default: - throw new IndexOutOfRangeException("Matrix4 row and column values must be from 0-3"); - } - case 1: - switch (column) - { - case 0: - M21 = value; return; - case 1: - M22 = value; return; - case 2: - M23 = value; return; - case 3: - M24 = value; return; - default: - throw new IndexOutOfRangeException("Matrix4 row and column values must be from 0-3"); - } - case 2: - switch (column) - { - case 0: - M31 = value; return; - case 1: - M32 = value; return; - case 2: - M33 = value; return; - case 3: - M34 = value; return; - default: - throw new IndexOutOfRangeException("Matrix4 row and column values must be from 0-3"); - } - case 3: - switch (column) - { - case 0: - M41 = value; return; - case 1: - M42 = value; return; - case 2: - M43 = value; return; - case 3: - M44 = value; return; - default: - throw new IndexOutOfRangeException("Matrix4 row and column values must be from 0-3"); - } - default: - throw new IndexOutOfRangeException("Matrix4 row and column values must be from 0-3"); - } - } - } - - #endregion Operators - - /// A 4x4 matrix containing all zeroes - public static readonly Matrix4 Zero = new Matrix4(); - - /// A 4x4 identity matrix - public static readonly Matrix4 Identity = new Matrix4( - 1f, 0f, 0f, 0f, - 0f, 1f, 0f, 0f, - 0f, 0f, 1f, 0f, - 0f, 0f, 0f, 1f); - } -} +/* + * Copyright (c) 2006-2016, openmetaverse.co + * All rights reserved. + * + * - Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * - Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * - Neither the name of the openmetaverse.co nor the names + * of its contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +namespace OpenMetaverse +{ + [Serializable] + [StructLayout(LayoutKind.Sequential)] + public struct Matrix4 : IEquatable + { + public float M11, M12, M13, M14; + public float M21, M22, M23, M24; + public float M31, M32, M33, M34; + public float M41, M42, M43, M44; + + #region Properties + + public Vector3 AtAxis + { + get + { + return new Vector3(M11, M21, M31); + } + set + { + M11 = value.X; + M21 = value.Y; + M31 = value.Z; + } + } + + public Vector3 LeftAxis + { + get + { + return new Vector3(M12, M22, M32); + } + set + { + M12 = value.X; + M22 = value.Y; + M32 = value.Z; + } + } + + public Vector3 UpAxis + { + get + { + return new Vector3(M13, M23, M33); + } + set + { + M13 = value.X; + M23 = value.Y; + M33 = value.Z; + } + } + + #endregion Properties + + #region Constructors + + public Matrix4( + float m11, float m12, float m13, float m14, + float m21, float m22, float m23, float m24, + float m31, float m32, float m33, float m34, + float m41, float m42, float m43, float m44) + { + Unsafe.SkipInit(out this); + + M11 = m11; + M12 = m12; + M13 = m13; + M14 = m14; + + M21 = m21; + M22 = m22; + M23 = m23; + M24 = m24; + + M31 = m31; + M32 = m32; + M33 = m33; + M34 = m34; + + M41 = m41; + M42 = m42; + M43 = m43; + M44 = m44; + } + + public Matrix4(float roll, float pitch, float yaw) + { + this = CreateFromEulers(roll, pitch, yaw); + } + + public Matrix4(Matrix4 m) + { + M11 = m.M11; + M12 = m.M12; + M13 = m.M13; + M14 = m.M14; + + M21 = m.M21; + M22 = m.M22; + M23 = m.M23; + M24 = m.M24; + + M31 = m.M31; + M32 = m.M32; + M33 = m.M33; + M34 = m.M34; + + M41 = m.M41; + M42 = m.M42; + M43 = m.M43; + M44 = m.M44; + } + + #endregion Constructors + + #region Public Methods + + public float Determinant() + { + return + M14 * M23 * M32 * M41 - M13 * M24 * M32 * M41 - M14 * M22 * M33 * M41 + M12 * M24 * M33 * M41 + + M13 * M22 * M34 * M41 - M12 * M23 * M34 * M41 - M14 * M23 * M31 * M42 + M13 * M24 * M31 * M42 + + M14 * M21 * M33 * M42 - M11 * M24 * M33 * M42 - M13 * M21 * M34 * M42 + M11 * M23 * M34 * M42 + + M14 * M22 * M31 * M43 - M12 * M24 * M31 * M43 - M14 * M21 * M32 * M43 + M11 * M24 * M32 * M43 + + M12 * M21 * M34 * M43 - M11 * M22 * M34 * M43 - M13 * M22 * M31 * M44 + M12 * M23 * M31 * M44 + + M13 * M21 * M32 * M44 - M11 * M23 * M32 * M44 - M12 * M21 * M33 * M44 + M11 * M22 * M33 * M44; + } + + public float Determinant3x3() + { + float det = 0f; + + float diag1 = M11 * M22 * M33; + float diag2 = M12 * M23 * M31; + float diag3 = M13 * M21 * M32; + float diag4 = M31 * M22 * M13; + float diag5 = M32 * M23 * M11; + float diag6 = M33 * M21 * M12; + + det = diag1 + diag2 + diag3 - (diag4 + diag5 + diag6); + + return det; + } + + public float Trace() + { + return M11 + M22 + M33 + M44; + } + + /// + /// Convert this matrix to euler rotations + /// + /// X euler angle + /// Y euler angle + /// Z euler angle + public void GetEulerAngles(out float roll, out float pitch, out float yaw) + { + float angleX, angleY, angleZ; + float cx, cy, cz; // cosines + float sx, sz; // sines + + angleY = MathF.Asin(Utils.Clamp(M13, -1f, 1f)); + cy = MathF.Cos(angleY); + + if (MathF.Abs(cy) > 0.005f) + { + // No gimbal lock + cx = M33 / cy; + sx = (-M23) / cy; + + angleX = MathF.Atan2(sx, cx); + + cz = M11 / cy; + sz = (-M12) / cy; + + angleZ = MathF.Atan2(sz, cz); + } + else + { + // Gimbal lock + angleX = 0; + + cz = M22; + sz = M21; + + angleZ = MathF.Atan2(sz, cz); + } + + // Return only positive angles in [0,360] + if (angleX < 0) angleX += 360f; + if (angleY < 0) angleY += 360f; + if (angleZ < 0) angleZ += 360f; + + roll = angleX; + pitch = angleY; + yaw = angleZ; + } + + /// + /// Convert this matrix to a quaternion rotation + /// + /// A quaternion representation of this rotation matrix + public Quaternion GetQuaternion() + { + Quaternion quat = new Quaternion(); + float trace = Trace() + 1f; + + if (trace > Single.Epsilon) + { + float s = 0.5f / MathF.Sqrt(trace); + + quat.X = (M32 - M23) * s; + quat.Y = (M13 - M31) * s; + quat.Z = (M21 - M12) * s; + quat.W = 0.25f / s; + } + else + { + if (M11 > M22 && M11 > M33) + { + float s = 2.0f * MathF.Sqrt(1.0f + M11 - M22 - M33); + + quat.X = 0.25f * s; + quat.Y = (M12 + M21) / s; + quat.Z = (M13 + M31) / s; + quat.W = (M23 - M32) / s; + } + else if (M22 > M33) + { + float s = 2.0f * MathF.Sqrt(1.0f + M22 - M11 - M33); + + quat.X = (M12 + M21) / s; + quat.Y = 0.25f * s; + quat.Z = (M23 + M32) / s; + quat.W = (M13 - M31) / s; + } + else + { + float s = 2.0f * MathF.Sqrt(1.0f + M33 - M11 - M22); + + quat.X = (M13 + M31) / s; + quat.Y = (M23 + M32) / s; + quat.Z = 0.25f * s; + quat.W = (M12 - M21) / s; + } + } + + return quat; + } + + public bool Decompose(out Vector3 scale, out Quaternion rotation, out Vector3 translation) + { + translation = new Vector3(M41, M42,M43); + + float xs = (Math.Sign(M11 * M12 * M13 * M14) < 0) ? -1 : 1; + float ys = (Math.Sign(M21 * M22 * M23 * M24) < 0) ? -1 : 1; + float zs = (Math.Sign(M31 * M32 * M33 * M34) < 0) ? -1 : 1; + + xs *= MathF.Sqrt(M11 * M11 + M12 * M12 + M13 * M13); + ys *= MathF.Sqrt(M21 * M21 + M22 * M22 + M23 * M23); + zs *= MathF.Sqrt(M31 * M31 + M32 * M32 + M33 * M33); + + scale = new Vector3(xs, ys, zs); + + if (xs == 0.0 || ys == 0.0 || zs == 0.0) + { + rotation = Quaternion.Identity; + return false; + } + + Matrix4 m1 = new Matrix4(M11 / xs, M12 / xs, M13 / xs, 0, + M21 / ys, M22 / ys, M23 / ys, 0, + M31 / zs, M32 / zs, M33 / zs, 0, + 0, 0, 0, 1); + + rotation = Quaternion.CreateFromRotationMatrix(m1); + return true; + } + + #endregion Public Methods + + #region Static Methods + + public static Matrix4 Add(Matrix4 matrix1, Matrix4 matrix2) + { + Matrix4 matrix; + matrix.M11 = matrix1.M11 + matrix2.M11; + matrix.M12 = matrix1.M12 + matrix2.M12; + matrix.M13 = matrix1.M13 + matrix2.M13; + matrix.M14 = matrix1.M14 + matrix2.M14; + + matrix.M21 = matrix1.M21 + matrix2.M21; + matrix.M22 = matrix1.M22 + matrix2.M22; + matrix.M23 = matrix1.M23 + matrix2.M23; + matrix.M24 = matrix1.M24 + matrix2.M24; + + matrix.M31 = matrix1.M31 + matrix2.M31; + matrix.M32 = matrix1.M32 + matrix2.M32; + matrix.M33 = matrix1.M33 + matrix2.M33; + matrix.M34 = matrix1.M34 + matrix2.M34; + + matrix.M41 = matrix1.M41 + matrix2.M41; + matrix.M42 = matrix1.M42 + matrix2.M42; + matrix.M43 = matrix1.M43 + matrix2.M43; + matrix.M44 = matrix1.M44 + matrix2.M44; + return matrix; + } + + public static Matrix4 CreateFromAxisAngle(Vector3 axis, float angle) + { + Matrix4 matrix = new Matrix4(); + + float x = axis.X; + float y = axis.Y; + float z = axis.Z; + float sin = MathF.Sin(angle); + float cos = MathF.Cos(angle); + float xx = x * x; + float yy = y * y; + float zz = z * z; + float xy = x * y; + float xz = x * z; + float yz = y * z; + + matrix.M11 = xx + (cos * (1f - xx)); + matrix.M12 = (xy - (cos * xy)) + (sin * z); + matrix.M13 = (xz - (cos * xz)) - (sin * y); + //matrix.M14 = 0f; + + matrix.M21 = (xy - (cos * xy)) - (sin * z); + matrix.M22 = yy + (cos * (1f - yy)); + matrix.M23 = (yz - (cos * yz)) + (sin * x); + //matrix.M24 = 0f; + + matrix.M31 = (xz - (cos * xz)) + (sin * y); + matrix.M32 = (yz - (cos * yz)) - (sin * x); + matrix.M33 = zz + (cos * (1f - zz)); + //matrix.M34 = 0f; + + //matrix.M41 = matrix.M42 = matrix.M43 = 0f; + matrix.M44 = 1f; + + return matrix; + } + + /// + /// Construct a matrix from euler rotation values in radians + /// + /// X euler angle in radians + /// Y euler angle in radians + /// Z euler angle in radians + public static Matrix4 CreateFromEulers(float roll, float pitch, float yaw) + { + Matrix4 m; + + float a, b, c, d, e, f; + float ad, bd; + + a = MathF.Cos(roll); + b = MathF.Sin(roll); + c = MathF.Cos(pitch); + d = MathF.Sin(pitch); + e = MathF.Cos(yaw); + f = MathF.Sin(yaw); + + ad = a * d; + bd = b * d; + + m.M11 = c * e; + m.M12 = -c * f; + m.M13 = d; + m.M14 = 0f; + + m.M21 = bd * e + a * f; + m.M22 = -bd * f + a * e; + m.M23 = -b * c; + m.M24 = 0f; + + m.M31 = -ad * e + b * f; + m.M32 = ad * f + b * e; + m.M33 = a * c; + m.M34 = 0f; + + m.M41 = m.M42 = m.M43 = 0f; + m.M44 = 1f; + + return m; + } + + public static Matrix4 CreateFromQuaternion(Quaternion rot) + { + float x2 = rot.X + rot.X; + float y2 = rot.Y + rot.Y; + float z2 = rot.Z + rot.Z; + + float wx2 = rot.W * x2; + float wy2 = rot.W * y2; + float wz2 = rot.W * z2; + float xx2 = rot.X * x2; + float xy2 = rot.X * y2; + float xz2 = rot.X * z2; + float yy2 = rot.Y * y2; + float yz2 = rot.Y * z2; + float zz2 = rot.Z * z2; + + return new Matrix4( + 1.0f - yy2 - zz2, xy2 + wz2, xz2 - wy2, 0, + xy2 - wz2, 1.0f - xx2 - zz2, yz2 + wx2, 0, + xz2 + wy2, yz2 - wx2, 1.0f - xx2 - yy2, 0, + 0, 0, 0, 1.0f); + } + + public static Matrix4 CreateFromQuaternion(ref Quaternion rot) + { + float x2 = rot.X + rot.X; + float y2 = rot.Y + rot.Y; + float z2 = rot.Z + rot.Z; + + float wx2 = rot.W * x2; + float wy2 = rot.W * y2; + float wz2 = rot.W * z2; + float xx2 = rot.X * x2; + float xy2 = rot.X * y2; + float xz2 = rot.X * z2; + float yy2 = rot.Y * y2; + float yz2 = rot.Y * z2; + float zz2 = rot.Z * z2; + + return new Matrix4( + 1.0f - yy2 - zz2, xy2 + wz2, xz2 - wy2, 0, + xy2 - wz2, 1.0f - xx2 - zz2, yz2 + wx2, 0, + xz2 + wy2, yz2 - wx2, 1.0f - xx2 - yy2, 0, + 0, 0, 0, 1.0f); + } + public static Matrix4 CreateFromInverseQuaternion(Quaternion rot) + { + float x2 = rot.X + rot.X; + float y2 = rot.Y + rot.Y; + float z2 = rot.Z + rot.Z; + + float wx2 = rot.W * x2; + float wy2 = rot.W * y2; + float wz2 = rot.W * z2; + float xx2 = rot.X * x2; + float xy2 = rot.X * y2; + float xz2 = rot.X * z2; + float yy2 = rot.Y * y2; + float yz2 = rot.Y * z2; + float zz2 = rot.Z * z2; + + return new Matrix4( + 1.0f - yy2 - zz2, xy2 - wz2, xz2 + wy2, 0, + xy2 + wz2, 1.0f - xx2 - zz2, yz2 - wx2, 0, + xz2 - wy2, yz2 + wx2, 1.0f - xx2 - yy2, 0, + 0, 0, 0, 1.0f); + } + + public static Matrix4 CreateFromInverseQuaternion(ref Quaternion rot) + { + float x2 = rot.X + rot.X; + float y2 = rot.Y + rot.Y; + float z2 = rot.Z + rot.Z; + + float wx2 = rot.W * x2; + float wy2 = rot.W * y2; + float wz2 = rot.W * z2; + float xx2 = rot.X * x2; + float xy2 = rot.X * y2; + float xz2 = rot.X * z2; + float yy2 = rot.Y * y2; + float yz2 = rot.Y * z2; + float zz2 = rot.Z * z2; + + return new Matrix4( + 1.0f - yy2 - zz2, xy2 - wz2, xz2 + wy2, 0, + xy2 + wz2, 1.0f - xx2 - zz2, yz2 - wx2, 0, + xz2 - wy2, yz2 + wx2, 1.0f - xx2 - yy2, 0, + 0, 0, 0, 1.0f); + } + public static Matrix4 CreateLookAt(Vector3 cameraPosition, Vector3 cameraTarget, Vector3 cameraUpVector) + { + Matrix4 matrix; + + Vector3 z = Vector3.Normalize(cameraPosition - cameraTarget); + Vector3 x = Vector3.Normalize(Vector3.Cross(cameraUpVector, z)); + Vector3 y = Vector3.Cross(z, x); + + matrix.M11 = x.X; + matrix.M12 = y.X; + matrix.M13 = z.X; + matrix.M14 = 0f; + + matrix.M21 = x.Y; + matrix.M22 = y.Y; + matrix.M23 = z.Y; + matrix.M24 = 0f; + + matrix.M31 = x.Z; + matrix.M32 = y.Z; + matrix.M33 = z.Z; + matrix.M34 = 0f; + + matrix.M41 = -Vector3.Dot(x, cameraPosition); + matrix.M42 = -Vector3.Dot(y, cameraPosition); + matrix.M43 = -Vector3.Dot(z, cameraPosition); + matrix.M44 = 1f; + + return matrix; + } + + public static Matrix4 CreateRotationX(float radians) + { + Matrix4 matrix; + + float cos = MathF.Cos(radians); + float sin = MathF.Sin(radians); + + matrix.M11 = 1f; + matrix.M12 = 0f; + matrix.M13 = 0f; + matrix.M14 = 0f; + + matrix.M21 = 0f; + matrix.M22 = cos; + matrix.M23 = sin; + matrix.M24 = 0f; + + matrix.M31 = 0f; + matrix.M32 = -sin; + matrix.M33 = cos; + matrix.M34 = 0f; + + matrix.M41 = 0f; + matrix.M42 = 0f; + matrix.M43 = 0f; + matrix.M44 = 1f; + + return matrix; + } + + public static Matrix4 CreateRotationY(float radians) + { + Matrix4 matrix; + + float cos = MathF.Cos(radians); + float sin = MathF.Sin(radians); + + matrix.M11 = cos; + matrix.M12 = 0f; + matrix.M13 = -sin; + matrix.M14 = 0f; + + matrix.M21 = 0f; + matrix.M22 = 1f; + matrix.M23 = 0f; + matrix.M24 = 0f; + + matrix.M31 = sin; + matrix.M32 = 0f; + matrix.M33 = cos; + matrix.M34 = 0f; + + matrix.M41 = 0f; + matrix.M42 = 0f; + matrix.M43 = 0f; + matrix.M44 = 1f; + + return matrix; + } + + public static Matrix4 CreateRotationZ(float radians) + { + Matrix4 matrix; + + float cos = MathF.Cos(radians); + float sin = MathF.Sin(radians); + + matrix.M11 = cos; + matrix.M12 = sin; + matrix.M13 = 0f; + matrix.M14 = 0f; + + matrix.M21 = -sin; + matrix.M22 = cos; + matrix.M23 = 0f; + matrix.M24 = 0f; + + matrix.M31 = 0f; + matrix.M32 = 0f; + matrix.M33 = 1f; + matrix.M34 = 0f; + + matrix.M41 = 0f; + matrix.M42 = 0f; + matrix.M43 = 0f; + matrix.M44 = 1f; + + return matrix; + } + + public static Matrix4 CreateScale(Vector3 scale) + { + Matrix4 matrix; + + matrix.M11 = scale.X; + matrix.M12 = 0f; + matrix.M13 = 0f; + matrix.M14 = 0f; + + matrix.M21 = 0f; + matrix.M22 = scale.Y; + matrix.M23 = 0f; + matrix.M24 = 0f; + + matrix.M31 = 0f; + matrix.M32 = 0f; + matrix.M33 = scale.Z; + matrix.M34 = 0f; + + matrix.M41 = 0f; + matrix.M42 = 0f; + matrix.M43 = 0f; + matrix.M44 = 1f; + + return matrix; + } + + public static Matrix4 CreateTranslation(Vector3 position) + { + Matrix4 matrix; + + matrix.M11 = 1f; + matrix.M12 = 0f; + matrix.M13 = 0f; + matrix.M14 = 0f; + + matrix.M21 = 0f; + matrix.M22 = 1f; + matrix.M23 = 0f; + matrix.M24 = 0f; + + matrix.M31 = 0f; + matrix.M32 = 0f; + matrix.M33 = 1f; + matrix.M34 = 0f; + + matrix.M41 = position.X; + matrix.M42 = position.Y; + matrix.M43 = position.Z; + matrix.M44 = 1f; + + return matrix; + } + + public static Matrix4 CreateWorld(Vector3 position, Vector3 forward, Vector3 up) + { + Matrix4 result; + + // Normalize forward vector + forward.Normalize(); + + // Calculate right vector + Vector3 right = Vector3.Cross(forward, up); + right.Normalize(); + + // Recalculate up vector + up = Vector3.Cross(right, forward); + up.Normalize(); + + result.M11 = right.X; + result.M12 = right.Y; + result.M13 = right.Z; + result.M14 = 0.0f; + + result.M21 = up.X; + result.M22 = up.Y; + result.M23 = up.Z; + result.M24 = 0.0f; + + result.M31 = -forward.X; + result.M32 = -forward.Y; + result.M33 = -forward.Z; + result.M34 = 0.0f; + + result.M41 = position.X; + result.M42 = position.Y; + result.M43 = position.Z; + result.M44 = 1.0f; + + return result; + } + + public static Matrix4 Divide(Matrix4 matrix1, Matrix4 matrix2) + { + Matrix4 matrix; + + matrix.M11 = matrix1.M11 / matrix2.M11; + matrix.M12 = matrix1.M12 / matrix2.M12; + matrix.M13 = matrix1.M13 / matrix2.M13; + matrix.M14 = matrix1.M14 / matrix2.M14; + + matrix.M21 = matrix1.M21 / matrix2.M21; + matrix.M22 = matrix1.M22 / matrix2.M22; + matrix.M23 = matrix1.M23 / matrix2.M23; + matrix.M24 = matrix1.M24 / matrix2.M24; + + matrix.M31 = matrix1.M31 / matrix2.M31; + matrix.M32 = matrix1.M32 / matrix2.M32; + matrix.M33 = matrix1.M33 / matrix2.M33; + matrix.M34 = matrix1.M34 / matrix2.M34; + + matrix.M41 = matrix1.M41 / matrix2.M41; + matrix.M42 = matrix1.M42 / matrix2.M42; + matrix.M43 = matrix1.M43 / matrix2.M43; + matrix.M44 = matrix1.M44 / matrix2.M44; + + return matrix; + } + + public static Matrix4 Divide(Matrix4 matrix1, float divider) + { + Matrix4 matrix; + + float oodivider = 1f / divider; + matrix.M11 = matrix1.M11 * oodivider; + matrix.M12 = matrix1.M12 * oodivider; + matrix.M13 = matrix1.M13 * oodivider; + matrix.M14 = matrix1.M14 * oodivider; + + matrix.M21 = matrix1.M21 * oodivider; + matrix.M22 = matrix1.M22 * oodivider; + matrix.M23 = matrix1.M23 * oodivider; + matrix.M24 = matrix1.M24 * oodivider; + + matrix.M31 = matrix1.M31 * oodivider; + matrix.M32 = matrix1.M32 * oodivider; + matrix.M33 = matrix1.M33 * oodivider; + matrix.M34 = matrix1.M34 * oodivider; + + matrix.M41 = matrix1.M41 * oodivider; + matrix.M42 = matrix1.M42 * oodivider; + matrix.M43 = matrix1.M43 * oodivider; + matrix.M44 = matrix1.M44 * oodivider; + + return matrix; + } + + public static Matrix4 Lerp(Matrix4 matrix1, Matrix4 matrix2, float amount) + { + Matrix4 matrix; + + matrix.M11 = matrix1.M11 + ((matrix2.M11 - matrix1.M11) * amount); + matrix.M12 = matrix1.M12 + ((matrix2.M12 - matrix1.M12) * amount); + matrix.M13 = matrix1.M13 + ((matrix2.M13 - matrix1.M13) * amount); + matrix.M14 = matrix1.M14 + ((matrix2.M14 - matrix1.M14) * amount); + + matrix.M21 = matrix1.M21 + ((matrix2.M21 - matrix1.M21) * amount); + matrix.M22 = matrix1.M22 + ((matrix2.M22 - matrix1.M22) * amount); + matrix.M23 = matrix1.M23 + ((matrix2.M23 - matrix1.M23) * amount); + matrix.M24 = matrix1.M24 + ((matrix2.M24 - matrix1.M24) * amount); + + matrix.M31 = matrix1.M31 + ((matrix2.M31 - matrix1.M31) * amount); + matrix.M32 = matrix1.M32 + ((matrix2.M32 - matrix1.M32) * amount); + matrix.M33 = matrix1.M33 + ((matrix2.M33 - matrix1.M33) * amount); + matrix.M34 = matrix1.M34 + ((matrix2.M34 - matrix1.M34) * amount); + + matrix.M41 = matrix1.M41 + ((matrix2.M41 - matrix1.M41) * amount); + matrix.M42 = matrix1.M42 + ((matrix2.M42 - matrix1.M42) * amount); + matrix.M43 = matrix1.M43 + ((matrix2.M43 - matrix1.M43) * amount); + matrix.M44 = matrix1.M44 + ((matrix2.M44 - matrix1.M44) * amount); + + return matrix; + } + + public static Matrix4 Multiply(Matrix4 matrix1, Matrix4 matrix2) + { + return new Matrix4( + matrix1.M11 * matrix2.M11 + matrix1.M12 * matrix2.M21 + matrix1.M13 * matrix2.M31 + matrix1.M14 * matrix2.M41, + matrix1.M11 * matrix2.M12 + matrix1.M12 * matrix2.M22 + matrix1.M13 * matrix2.M32 + matrix1.M14 * matrix2.M42, + matrix1.M11 * matrix2.M13 + matrix1.M12 * matrix2.M23 + matrix1.M13 * matrix2.M33 + matrix1.M14 * matrix2.M43, + matrix1.M11 * matrix2.M14 + matrix1.M12 * matrix2.M24 + matrix1.M13 * matrix2.M34 + matrix1.M14 * matrix2.M44, + + matrix1.M21 * matrix2.M11 + matrix1.M22 * matrix2.M21 + matrix1.M23 * matrix2.M31 + matrix1.M24 * matrix2.M41, + matrix1.M21 * matrix2.M12 + matrix1.M22 * matrix2.M22 + matrix1.M23 * matrix2.M32 + matrix1.M24 * matrix2.M42, + matrix1.M21 * matrix2.M13 + matrix1.M22 * matrix2.M23 + matrix1.M23 * matrix2.M33 + matrix1.M24 * matrix2.M43, + matrix1.M21 * matrix2.M14 + matrix1.M22 * matrix2.M24 + matrix1.M23 * matrix2.M34 + matrix1.M24 * matrix2.M44, + + matrix1.M31 * matrix2.M11 + matrix1.M32 * matrix2.M21 + matrix1.M33 * matrix2.M31 + matrix1.M34 * matrix2.M41, + matrix1.M31 * matrix2.M12 + matrix1.M32 * matrix2.M22 + matrix1.M33 * matrix2.M32 + matrix1.M34 * matrix2.M42, + matrix1.M31 * matrix2.M13 + matrix1.M32 * matrix2.M23 + matrix1.M33 * matrix2.M33 + matrix1.M34 * matrix2.M43, + matrix1.M31 * matrix2.M14 + matrix1.M32 * matrix2.M24 + matrix1.M33 * matrix2.M34 + matrix1.M34 * matrix2.M44, + + matrix1.M41 * matrix2.M11 + matrix1.M42 * matrix2.M21 + matrix1.M43 * matrix2.M31 + matrix1.M44 * matrix2.M41, + matrix1.M41 * matrix2.M12 + matrix1.M42 * matrix2.M22 + matrix1.M43 * matrix2.M32 + matrix1.M44 * matrix2.M42, + matrix1.M41 * matrix2.M13 + matrix1.M42 * matrix2.M23 + matrix1.M43 * matrix2.M33 + matrix1.M44 * matrix2.M43, + matrix1.M41 * matrix2.M14 + matrix1.M42 * matrix2.M24 + matrix1.M43 * matrix2.M34 + matrix1.M44 * matrix2.M44 + ); + } + + public static Matrix4 Multiply(Matrix4 matrix1, float scaleFactor) + { + Matrix4 matrix; + matrix.M11 = matrix1.M11 * scaleFactor; + matrix.M12 = matrix1.M12 * scaleFactor; + matrix.M13 = matrix1.M13 * scaleFactor; + matrix.M14 = matrix1.M14 * scaleFactor; + + matrix.M21 = matrix1.M21 * scaleFactor; + matrix.M22 = matrix1.M22 * scaleFactor; + matrix.M23 = matrix1.M23 * scaleFactor; + matrix.M24 = matrix1.M24 * scaleFactor; + + matrix.M31 = matrix1.M31 * scaleFactor; + matrix.M32 = matrix1.M32 * scaleFactor; + matrix.M33 = matrix1.M33 * scaleFactor; + matrix.M34 = matrix1.M34 * scaleFactor; + + matrix.M41 = matrix1.M41 * scaleFactor; + matrix.M42 = matrix1.M42 * scaleFactor; + matrix.M43 = matrix1.M43 * scaleFactor; + matrix.M44 = matrix1.M44 * scaleFactor; + return matrix; + } + + public static Matrix4 Negate(Matrix4 matrix) + { + Matrix4 result; + result.M11 = -matrix.M11; + result.M12 = -matrix.M12; + result.M13 = -matrix.M13; + result.M14 = -matrix.M14; + + result.M21 = -matrix.M21; + result.M22 = -matrix.M22; + result.M23 = -matrix.M23; + result.M24 = -matrix.M24; + + result.M31 = -matrix.M31; + result.M32 = -matrix.M32; + result.M33 = -matrix.M33; + result.M34 = -matrix.M34; + + result.M41 = -matrix.M41; + result.M42 = -matrix.M42; + result.M43 = -matrix.M43; + result.M44 = -matrix.M44; + return result; + } + + public static Matrix4 Subtract(Matrix4 matrix1, Matrix4 matrix2) + { + Matrix4 matrix; + matrix.M11 = matrix1.M11 - matrix2.M11; + matrix.M12 = matrix1.M12 - matrix2.M12; + matrix.M13 = matrix1.M13 - matrix2.M13; + matrix.M14 = matrix1.M14 - matrix2.M14; + + matrix.M21 = matrix1.M21 - matrix2.M21; + matrix.M22 = matrix1.M22 - matrix2.M22; + matrix.M23 = matrix1.M23 - matrix2.M23; + matrix.M24 = matrix1.M24 - matrix2.M24; + + matrix.M31 = matrix1.M31 - matrix2.M31; + matrix.M32 = matrix1.M32 - matrix2.M32; + matrix.M33 = matrix1.M33 - matrix2.M33; + matrix.M34 = matrix1.M34 - matrix2.M34; + + matrix.M41 = matrix1.M41 - matrix2.M41; + matrix.M42 = matrix1.M42 - matrix2.M42; + matrix.M43 = matrix1.M43 - matrix2.M43; + matrix.M44 = matrix1.M44 - matrix2.M44; + return matrix; + } + + public static Matrix4 Transform(Matrix4 value, Quaternion rotation) + { + Matrix4 matrix; + + float x2 = rotation.X + rotation.X; + float y2 = rotation.Y + rotation.Y; + float z2 = rotation.Z + rotation.Z; + + float a = (1f - rotation.Y * y2) - rotation.Z * z2; + float b = rotation.X * y2 - rotation.W * z2; + float c = rotation.X * z2 + rotation.W * y2; + float d = rotation.X * y2 + rotation.W * z2; + float e = (1f - rotation.X * x2) - rotation.Z * z2; + float f = rotation.Y * z2 - rotation.W * x2; + float g = rotation.X * z2 - rotation.W * y2; + float h = rotation.Y * z2 + rotation.W * x2; + float i = (1f - rotation.X * x2) - rotation.Y * y2; + + matrix.M11 = ((value.M11 * a) + (value.M12 * b)) + (value.M13 * c); + matrix.M12 = ((value.M11 * d) + (value.M12 * e)) + (value.M13 * f); + matrix.M13 = ((value.M11 * g) + (value.M12 * h)) + (value.M13 * i); + matrix.M14 = value.M14; + + matrix.M21 = ((value.M21 * a) + (value.M22 * b)) + (value.M23 * c); + matrix.M22 = ((value.M21 * d) + (value.M22 * e)) + (value.M23 * f); + matrix.M23 = ((value.M21 * g) + (value.M22 * h)) + (value.M23 * i); + matrix.M24 = value.M24; + + matrix.M31 = ((value.M31 * a) + (value.M32 * b)) + (value.M33 * c); + matrix.M32 = ((value.M31 * d) + (value.M32 * e)) + (value.M33 * f); + matrix.M33 = ((value.M31 * g) + (value.M32 * h)) + (value.M33 * i); + matrix.M34 = value.M34; + + matrix.M41 = ((value.M41 * a) + (value.M42 * b)) + (value.M43 * c); + matrix.M42 = ((value.M41 * d) + (value.M42 * e)) + (value.M43 * f); + matrix.M43 = ((value.M41 * g) + (value.M42 * h)) + (value.M43 * i); + matrix.M44 = value.M44; + + return matrix; + } + + public static Matrix4 Transpose(Matrix4 matrix) + { + Matrix4 result; + + result.M11 = matrix.M11; + result.M12 = matrix.M21; + result.M13 = matrix.M31; + result.M14 = matrix.M41; + + result.M21 = matrix.M12; + result.M22 = matrix.M22; + result.M23 = matrix.M32; + result.M24 = matrix.M42; + + result.M31 = matrix.M13; + result.M32 = matrix.M23; + result.M33 = matrix.M33; + result.M34 = matrix.M43; + + result.M41 = matrix.M14; + result.M42 = matrix.M24; + result.M43 = matrix.M34; + result.M44 = matrix.M44; + + return result; + } + + public static Matrix4 Inverse3x3(Matrix4 matrix) + { + if (matrix.Determinant3x3() == 0f) + throw new ArgumentException("Singular matrix inverse not possible"); + + return (Adjoint3x3(matrix) / matrix.Determinant3x3()); + } + + public static Matrix4 Adjoint3x3(Matrix4 matrix) + { + Matrix4 adjointMatrix = new Matrix4(); + for (int i = 0; i < 4; i++) + { + for (int j = 0; j < 4; j++) + adjointMatrix[i,j] = MathF.Pow(-1, i + j) * (Minor(matrix, i, j).Determinant3x3()); + } + + adjointMatrix = Transpose(adjointMatrix); + return adjointMatrix; + } + + public static Matrix4 Inverse(Matrix4 matrix) + { + if (matrix.Determinant() == 0f) + throw new ArgumentException("Singular matrix inverse not possible"); + + return (Adjoint(matrix) / matrix.Determinant()); + } + + public static Matrix4 Adjoint(Matrix4 matrix) + { + Matrix4 adjointMatrix = new Matrix4(); + for (int i = 0; i < 4; i++) + { + for (int j = 0; j < 4; j++) + adjointMatrix[i,j] = MathF.Pow(-1, i + j) * ((Minor(matrix, i, j)).Determinant3x3()); + } + + adjointMatrix = Transpose(adjointMatrix); + return adjointMatrix; + } + + public static Matrix4 Minor(Matrix4 matrix, int row, int col) + { + Matrix4 minor = new Matrix4(); + int m = 0, n = 0; + + for (int i = 0; i < 4; i++) + { + if (i == row) + continue; + n = 0; + for (int j = 0; j < 4; j++) + { + if (j == col) + continue; + minor[m,n] = matrix[i,j]; + n++; + } + m++; + } + + return minor; + } + + #endregion Static Methods + + #region Overrides + + public override bool Equals(object obj) + { + return (obj is Matrix4) ? this.Equals((Matrix4)obj) : false; + } + + public bool Equals(Matrix4 other) + { + return M11 == other.M11 && M12 == other.M12 && M13 == other.M13 && M14 == other.M14 && + M21 == other.M21 && M22 == other.M22 && M23 == other.M23 && M24 == other.M24 && + M31 == other.M31 && M32 == other.M32 && M33 == other.M33 && M14 == other.M34 && + M41 == other.M41 && M42 == other.M42 && M43 == other.M43 && M44 == other.M44; + } + + public override int GetHashCode() + { + return + M11.GetHashCode() ^ M12.GetHashCode() ^ M13.GetHashCode() ^ M14.GetHashCode() ^ + M21.GetHashCode() ^ M22.GetHashCode() ^ M23.GetHashCode() ^ M24.GetHashCode() ^ + M31.GetHashCode() ^ M32.GetHashCode() ^ M33.GetHashCode() ^ M34.GetHashCode() ^ + M41.GetHashCode() ^ M42.GetHashCode() ^ M43.GetHashCode() ^ M44.GetHashCode(); + } + + /// + /// Get a formatted string representation of the vector + /// + /// A string representation of the vector + public override string ToString() + { + return string.Format(Utils.EnUsCulture, + "|{0}, {1}, {2}, {3}|\n|{4}, {5}, {6}, {7}|\n|{8}, {9}, {10}, {11}|\n|{12}, {13}, {14}, {15}|", + M11, M12, M13, M14, M21, M22, M23, M24, M31, M32, M33, M34, M41, M42, M43, M44); + } + + #endregion Overrides + + #region Operators + + public static bool operator ==(Matrix4 left, Matrix4 right) + { + return left.Equals(right); + } + + public static bool operator !=(Matrix4 left, Matrix4 right) + { + return !left.Equals(right); + } + + public static Matrix4 operator +(Matrix4 left, Matrix4 right) + { + return Add(left, right); + } + + public static Matrix4 operator -(Matrix4 matrix) + { + return Negate(matrix); + } + + public static Matrix4 operator -(Matrix4 left, Matrix4 right) + { + return Subtract(left, right); + } + + public static Matrix4 operator *(Matrix4 left, Matrix4 right) + { + return Multiply(left, right); + } + + public static Matrix4 operator *(Matrix4 left, float scalar) + { + return Multiply(left, scalar); + } + + public static Matrix4 operator /(Matrix4 left, Matrix4 right) + { + return Divide(left, right); + } + + public static Matrix4 operator /(Matrix4 matrix, float divider) + { + return Divide(matrix, divider); + } + + public Vector4 this[int row] + { + get + { + switch (row) + { + case 0: + return new Vector4(M11, M12, M13, M14); + case 1: + return new Vector4(M21, M22, M23, M24); + case 2: + return new Vector4(M31, M32, M33, M34); + case 3: + return new Vector4(M41, M42, M43, M44); + default: + throw new IndexOutOfRangeException("Matrix4 row index must be from 0-3"); + } + } + set + { + switch (row) + { + case 0: + M11 = value.X; + M12 = value.Y; + M13 = value.Z; + M14 = value.W; + break; + case 1: + M21 = value.X; + M22 = value.Y; + M23 = value.Z; + M24 = value.W; + break; + case 2: + M31 = value.X; + M32 = value.Y; + M33 = value.Z; + M34 = value.W; + break; + case 3: + M41 = value.X; + M42 = value.Y; + M43 = value.Z; + M44 = value.W; + break; + default: + throw new IndexOutOfRangeException("Matrix4 row index must be from 0-3"); + } + } + } + + public float this[int row, int column] + { + get + { + switch (row) + { + case 0: + switch (column) + { + case 0: + return M11; + case 1: + return M12; + case 2: + return M13; + case 3: + return M14; + default: + throw new IndexOutOfRangeException("Matrix4 row and column values must be from 0-3"); + } + case 1: + switch (column) + { + case 0: + return M21; + case 1: + return M22; + case 2: + return M23; + case 3: + return M24; + default: + throw new IndexOutOfRangeException("Matrix4 row and column values must be from 0-3"); + } + case 2: + switch (column) + { + case 0: + return M31; + case 1: + return M32; + case 2: + return M33; + case 3: + return M34; + default: + throw new IndexOutOfRangeException("Matrix4 row and column values must be from 0-3"); + } + case 3: + switch (column) + { + case 0: + return M41; + case 1: + return M42; + case 2: + return M43; + case 3: + return M44; + default: + throw new IndexOutOfRangeException("Matrix4 row and column values must be from 0-3"); + } + default: + throw new IndexOutOfRangeException("Matrix4 row and column values must be from 0-3"); + } + } + set + { + switch (row) + { + case 0: + switch (column) + { + case 0: + M11 = value; return; + case 1: + M12 = value; return; + case 2: + M13 = value; return; + case 3: + M14 = value; return; + default: + throw new IndexOutOfRangeException("Matrix4 row and column values must be from 0-3"); + } + case 1: + switch (column) + { + case 0: + M21 = value; return; + case 1: + M22 = value; return; + case 2: + M23 = value; return; + case 3: + M24 = value; return; + default: + throw new IndexOutOfRangeException("Matrix4 row and column values must be from 0-3"); + } + case 2: + switch (column) + { + case 0: + M31 = value; return; + case 1: + M32 = value; return; + case 2: + M33 = value; return; + case 3: + M34 = value; return; + default: + throw new IndexOutOfRangeException("Matrix4 row and column values must be from 0-3"); + } + case 3: + switch (column) + { + case 0: + M41 = value; return; + case 1: + M42 = value; return; + case 2: + M43 = value; return; + case 3: + M44 = value; return; + default: + throw new IndexOutOfRangeException("Matrix4 row and column values must be from 0-3"); + } + default: + throw new IndexOutOfRangeException("Matrix4 row and column values must be from 0-3"); + } + } + } + + #endregion Operators + + /// A 4x4 matrix containing all zeroes + public static readonly Matrix4 Zero = new Matrix4(); + + /// A 4x4 identity matrix + public static readonly Matrix4 Identity = new( + 1f, 0f, 0f, 0f, + 0f, 1f, 0f, 0f, + 0f, 0f, 1f, 0f, + 0f, 0f, 0f, 1f); + } +} diff --git a/OpenMetaverse.Types/OSUTF8.cs b/OpenMetaverse.Types/OSUTF8.cs index 1cc7ecf0..b4ccb0f6 100644 --- a/OpenMetaverse.Types/OSUTF8.cs +++ b/OpenMetaverse.Types/OSUTF8.cs @@ -38,6 +38,10 @@ Ubit Umarov (Leal Duarte) 2020 using System.Text; using System.Collections.Generic; using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Runtime.Intrinsics.X86; +using System.Runtime.Intrinsics; +using System.IO; namespace OpenMetaverse { @@ -46,50 +50,72 @@ public class osUTF8 internal byte[] m_data; internal int m_len; - public static readonly osUTF8 Empty = new osUTF8(); + public static readonly osUTF8 Empty = new(); + [MethodImpl(MethodImplOptions.AggressiveInlining)] public osUTF8() { - m_data = new byte[0]; + m_data = Array.Empty(); m_len = 0; } + [MethodImpl(MethodImplOptions.AggressiveInlining)] public osUTF8(int capacity) { m_data = new byte[capacity]; m_len = 0; } + [MethodImpl(MethodImplOptions.AggressiveInlining)] public osUTF8(byte[] source) { m_data = source; m_len = source.Length; } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public osUTF8(byte[] source, int len) + { + m_data = source; + m_len = len; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] public osUTF8(osUTF8Slice source) { m_data = source.ToArray(); m_len = m_data.Length; } + [MethodImpl(MethodImplOptions.AggressiveInlining)] public osUTF8(osUTF8 source) { m_data = source.ToArray(); m_len = source.Length; } + [MethodImpl(MethodImplOptions.AggressiveInlining)] public osUTF8(string source) { m_data = Utils.StringToBytesNoTerm(source); m_len = m_data.Length; } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public osUTF8(ReadOnlySpan ut8) + { + m_data = ut8.ToArray(); + m_len = m_data.Length; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] public osUTF8(string source, int maxlen) { m_data = Utils.StringToBytesNoTerm(source, maxlen); m_len = m_data.Length; } + [MethodImpl(MethodImplOptions.AggressiveInlining)] public osUTF8(string source, bool isascii) { if(isascii) @@ -111,26 +137,29 @@ public byte this[int i] { if (i >= m_len) i = m_len - 1; - if (i < 0) - i = 0; - else if (i >= m_data.Length) + if (i >= m_data.Length) i = m_data.Length - 1; - return m_data[i]; + if (i <= 0) + return Unsafe.As(ref MemoryMarshal.GetArrayDataReference(m_data)); + return Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(m_data), i)); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] set { if (i > 0 && i < m_len) - m_data[i] = value; + Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(m_data), i)) = value; } } public int Length { + [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return m_len; } } public int Capacity { + [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return m_data.Length; } } @@ -159,24 +188,24 @@ public override bool Equals(object obj) if (obj == null) return false; - if (obj is osUTF8) - return Equals((osUTF8)obj); + if (obj is osUTF8 osUTF8obj) + return Equals(osUTF8obj); - if (obj is osUTF8Slice) - return Equals((osUTF8Slice)obj); + if (obj is osUTF8Slice osUTF8Sliceobj) + return Equals(osUTF8Sliceobj); - if (obj is string) - return Equals((string)obj); + if (obj is string v) + return Equals(v); - if (obj is byte[]) - return Equals((byte[])obj); + if (obj is byte[] byteobj) + return Equals(byteobj); return false; } public unsafe bool Equals(osUTF8Slice o) { - if (o == null || m_len != o.m_len) + if (o is null || m_len != o.m_len) return false; byte[] otherdata = o.m_data; @@ -231,7 +260,7 @@ public unsafe bool Equals(byte[] o) public unsafe bool Equals(osUTF8 o) { - if (o == null || m_len != o.m_len) + if (o is null || m_len != o.m_len) return false; byte[] otherdata = o.m_data; @@ -252,14 +281,41 @@ public unsafe bool Equals(osUTF8 o) return true; } + [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Equals(string s) { if (string.IsNullOrEmpty(s)) return m_len == 0; - osUTF8 o = new osUTF8(s); + osUTF8 o = new(s); return Equals(o); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool Equals(ReadOnlySpan s) + { + if(m_len != s.Length) + return false; + + ReadOnlySpan os = m_data.AsSpan(0, m_data.Length); + return os.SequenceEqual(s); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool operator ==(osUTF8 value1, osUTF8 value2) + { + if (value1 is null) + return value2 is null; + return value1.Equals(value2); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool operator !=(osUTF8 value1, osUTF8 value2) + { + if (value1 is null) + return value2 is not null; + return !value1.Equals(value2); + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Equals(char c) { @@ -268,7 +324,7 @@ public bool Equals(char c) public unsafe bool ACSIILowerEquals(osUTF8 o) { - if (o == null || m_len != o.m_len) + if (o is null || m_len != o.m_len) return false; fixed (byte* a = m_data, b = o.m_data) @@ -292,7 +348,7 @@ public unsafe bool ACSIILowerEquals(osUTF8 o) public unsafe bool ACSIILowerEquals(osUTF8Slice o) { - if (o == null || m_len != o.m_len) + if (o is null || m_len != o.m_len) return false; fixed (byte* a = m_data, b = o.m_data) @@ -314,6 +370,30 @@ public unsafe bool ACSIILowerEquals(osUTF8Slice o) return true; } + public unsafe bool ACSIILowerEquals(byte[] o) + { + if (o == null || m_len != o.Length) + return false; + + fixed (byte* a = m_data, b = o) + { + byte* ptr = a; + byte* end = a + m_len; + byte* ptrb = b; + while (ptr < end) + { + byte c = *ptr; + if (c >= 0x41 && c <= 0x5a) + c |= 0x20; + if (c != *ptrb) + return false; + ++ptr; + ++ptrb; + } + } + return true; + } + public unsafe bool ACSIILowerEquals(string o) { if (string.IsNullOrEmpty(o) || m_len != o.Length) @@ -339,11 +419,13 @@ public unsafe bool ACSIILowerEquals(string o) return true; } + [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Clear() { m_len = 0; } + [MethodImpl(MethodImplOptions.AggressiveInlining)] public osUTF8 Clone() { byte[] b = new byte[m_data.Length]; @@ -351,6 +433,7 @@ public osUTF8 Clone() return new osUTF8(b); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] public osUTF8 Extract() { byte[] b = new byte[m_len]; @@ -358,6 +441,7 @@ public osUTF8 Extract() return new osUTF8(b); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] public byte[] ToArray() { byte[] b = new byte[m_len]; @@ -365,11 +449,13 @@ public byte[] ToArray() return b; } + [MethodImpl(MethodImplOptions.AggressiveInlining)] public byte[] GetArray() { return m_data; } + [MethodImpl(MethodImplOptions.AggressiveInlining)] public osUTF8 Concat(osUTF8 other) { byte[] b = new byte[m_len + other.m_len]; @@ -398,17 +484,24 @@ public void CheckCapacity(int needed) } } + [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendASCII(char c) { - CheckCapacity(1); - m_data[m_len] = (byte)c; - ++m_len; + Append((byte)c); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Append(byte c) { CheckCapacity(1); - m_data[m_len] = c; + Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(m_data), m_len)) = c; + ++m_len; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void AppendSafe(byte c) + { + Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(m_data), m_len)) = c; ++m_len; } @@ -449,6 +542,7 @@ public void Append(string s) m_len = indx; } + [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Append(byte[] b) { int nbytes = b.Length; @@ -457,6 +551,18 @@ public void Append(byte[] b) m_len += nbytes; } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Append(byte[] b, int bstart, int nbytes) + { + if(bstart + nbytes >= b.Length) + nbytes = b.Length - bstart; + + CheckCapacity(nbytes); + Array.Copy(b, bstart, m_data, m_len, nbytes); + m_len += nbytes; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Append(osUTF8 b) { int nbytes = b.m_len; @@ -465,6 +571,16 @@ public void Append(osUTF8 b) m_len += nbytes; } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Append(ReadOnlySpan b) + { + int nbytes = b.Length; + CheckCapacity(nbytes); + b.CopyTo(new Span(m_data,m_len, nbytes)); + m_len += nbytes; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe void AppendInt(sbyte v) { CheckCapacity(4); @@ -472,12 +588,15 @@ public unsafe void AppendInt(sbyte v) m_len += Utils.IntToByteString(v, d + m_len); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe void AppendInt(byte v) { - CheckCapacity(4); + CheckCapacity(3); fixed (byte* d = m_data) m_len += Utils.UIntToByteString(v, d + m_len); } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe void AppendInt(int v) { CheckCapacity(16); @@ -485,6 +604,7 @@ public unsafe void AppendInt(int v) m_len += Utils.IntToByteString(v, d + m_len); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe void AppendInt(uint v) { CheckCapacity(16); @@ -492,6 +612,7 @@ public unsafe void AppendInt(uint v) m_len += Utils.UIntToByteString(v, d + m_len); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe void AppendInt(long v) { CheckCapacity(32); @@ -499,6 +620,7 @@ public unsafe void AppendInt(long v) m_len += Utils.LongToByteString(v, d + m_len); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe void AppendInt(ulong v) { CheckCapacity(32); @@ -506,6 +628,7 @@ public unsafe void AppendInt(ulong v) m_len += Utils.ULongToByteString(v, d + m_len); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe void AppendUUID(UUID u) { CheckCapacity(36); @@ -558,7 +681,7 @@ public osUTF8Slice SubUTF8(int start) [MethodImpl(MethodImplOptions.AggressiveInlining)] public osUTF8Slice SubUTF8(int start, int len) { - osUTF8Slice oss = new osUTF8Slice(this); + osUTF8Slice oss = new(this); return oss.SubUTF8(start, len); } @@ -572,91 +695,91 @@ public string SubString(int start) [MethodImpl(MethodImplOptions.AggressiveInlining)] public string SubString(int start, int len) { - osUTF8Slice oss = new osUTF8Slice(this); + osUTF8Slice oss = new(this); return oss.SubString(start, len); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public osUTF8Slice TrimStart() { - osUTF8Slice ret = new osUTF8Slice(this); + osUTF8Slice ret = new(this); return ret.TrimStart(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public osUTF8Slice TrimEnd() { - osUTF8Slice ret = new osUTF8Slice(this); + osUTF8Slice ret = new(this); return ret.TrimEnd(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public osUTF8Slice Trim() { - osUTF8Slice ret = new osUTF8Slice(this); + osUTF8Slice ret = new(this); return ret.Trim(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public osUTF8Slice TrimStart(byte b) { - osUTF8Slice ret = new osUTF8Slice(this); + osUTF8Slice ret = new(this); return ret.TrimStart(b); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public osUTF8Slice TrimEnd(byte b) { - osUTF8Slice ret = new osUTF8Slice(this); + osUTF8Slice ret = new(this); return ret.TrimEnd(b); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public osUTF8Slice Trim(byte b) { - osUTF8Slice ret = new osUTF8Slice(this); + osUTF8Slice ret = new(this); return ret.Trim(b); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public osUTF8Slice TrimStart(byte[] v) { - osUTF8Slice ret = new osUTF8Slice(this); + osUTF8Slice ret = new(this); return ret.TrimStart(v); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public osUTF8Slice TrimEnd(byte[] v) { - osUTF8Slice ret = new osUTF8Slice(this); + osUTF8Slice ret = new(this); return ret.TrimEnd(v); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public osUTF8Slice Trim(byte[] v) { - osUTF8Slice ret = new osUTF8Slice(this); + osUTF8Slice ret = new(this); return ret.Trim(v); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public osUTF8Slice TrimStart(char[] v) { - osUTF8Slice ret = new osUTF8Slice(this); + osUTF8Slice ret = new(this); return ret.TrimStart(v); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public osUTF8Slice TrimEnd(char[] v) { - osUTF8Slice ret = new osUTF8Slice(this); + osUTF8Slice ret = new(this); return ret.TrimEnd(v); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public osUTF8Slice Trim(char[] v) { - osUTF8Slice ret = new osUTF8Slice(this); + osUTF8Slice ret = new(this); return ret.Trim(v); } @@ -679,32 +802,32 @@ public unsafe bool StartsWith(osUTF8 other) public bool StartsWith(string s) { - osUTF8 other = new osUTF8(s); // yeack + osUTF8 other = new(s); // yeack return StartsWith(other); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool StartsWith(byte b) { - return m_data[0] == b; + return Unsafe.As(ref MemoryMarshal.GetArrayDataReference(m_data)) == b; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool StartsWith(char b) { - return m_data[0] == (byte)b; + return Unsafe.As(ref MemoryMarshal.GetArrayDataReference(m_data)) == (byte)b; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool EndsWith(byte b) { - return m_data[m_len - 1] == b; + return Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(m_data), m_len - 1)) == b; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool EndsWith(char b) { - return m_data[m_len - 1] == (byte)b; + return Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(m_data), m_len - 1)) == (byte)b; } public unsafe bool EndsWith(osUTF8 other) @@ -726,28 +849,15 @@ public unsafe bool EndsWith(osUTF8 other) public bool EndsWith(string s) { - osUTF8 other = new osUTF8(s); // yeack + osUTF8 other = new(s); // yeack return EndsWith(other); } public unsafe int IndexOf(byte b) { - if (m_len > 8) - { - fixed (byte* a = m_data) - { - for (int i = 0; i < m_len; ++i) - { - if (a[i] == b) - return i; - } - return -1; - } - } - for (int i = 0; i < m_len; ++i) { - if (m_data[i] == b) + if (Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(m_data), i)) == b) return i; } return -1; @@ -757,7 +867,7 @@ public int IndexOf(char b) { if (b < 0x80) return IndexOf((byte)b); - string s = new string(new char[] { b }); + string s = new(new char[] { b }); return IndexOf(s); } @@ -813,12 +923,12 @@ public int IndexOf(string s) { if (string.IsNullOrEmpty(s)) return -1; - osUTF8 o = new osUTF8(s); + osUTF8 o = new(s); return IndexOf(o); } [MethodImpl(MethodImplOptions.AggressiveInlining)] - private bool checkAny(byte b, byte[] bytes) + private static bool checkAny(byte b, byte[] bytes) { for (int i = 0; i < bytes.Length; ++i) { @@ -829,7 +939,7 @@ private bool checkAny(byte b, byte[] bytes) } [MethodImpl(MethodImplOptions.AggressiveInlining)] - private bool checkAny(byte b, char[] chars) + private static bool checkAny(byte b, char[] chars) { for (int i = 0; i < chars.Length; ++i) { @@ -917,7 +1027,7 @@ public osUTF8Slice[] Split(char b, bool ignoreEmpty = true) if (b < 0x80) return Split((byte)b, ignoreEmpty); - return new osUTF8Slice[0]; + return Array.Empty(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -926,10 +1036,188 @@ public static bool TryParseInt(osUTF8 t, out int res) return osUTF8Slice.TryParseInt(new osUTF8Slice(t), out res); } - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool TryParseUUID(osUTF8 inp, out UUID res, bool dashs = true) + public unsafe static bool TryParseUUID(osUTF8 inp, out UUID result) { - return osUTF8Slice.TryParseUUID(new osUTF8Slice(inp), out res, dashs); + result = new UUID(); + int len = inp.m_len; + if (len < 32) + return false; + + try + { + fixed (byte* bval = inp.m_data) + { + byte* val = bval; + + while (*val == ' ') + { + ++val; + --len; + if (len < 32) + return false; + } + + if (val[8] == '-') + { + if (len < 36) + return false; + if (val[13] != '-' || val[18] != '-' || val[23] != '-') + return false; + + if (Sse42.IsSupported) + { + Vector128 input = Unsafe.As>(ref Unsafe.AsRef(val)); + Vector128 upper = Ssse3.Shuffle(input, Vector128.Create(0, 2, 4, 6, 9, 11, 14, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff)); + Vector128 lower = Ssse3.Shuffle(input, Vector128.Create(1, 3, 5, 7, 10, 12, 15, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff)); + input = Unsafe.As>(ref Unsafe.AddByteOffset(ref Unsafe.AsRef(val), 16 + 3)); + Vector128 upperhalf = Ssse3.Shuffle(input, Vector128.Create(0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0, 2, 5, 7, 9, 11, 13, 15)); + Vector128 lowerhalf = Ssse3.Shuffle(input, Vector128.Create(0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 1, 3, 6, 8, 10, 12, 14, 0xff)); + upper = Sse2.Or(upper, upperhalf); + lower = Sse2.Or(lower, lowerhalf); + + upper = Sse41.Insert(upper, Unsafe.As(ref Unsafe.AddByteOffset(ref Unsafe.AsRef(val), 16)), 7); + lower = Sse41.Insert(lower, Unsafe.As(ref Unsafe.AddByteOffset(ref Unsafe.AsRef(val), 17)), 7); + lower = Sse41.Insert(lower, Unsafe.As(ref Unsafe.AddByteOffset(ref Unsafe.AsRef(val), 35)), 15); + + Vector128 charf = Vector128.Create((byte)'f'); + Vector128 tmpcmp = Sse2.Subtract(charf, lower); + int cmp = Sse2.MoveMask(tmpcmp); + if (cmp != 0) + throw new Exception("bad"); + + tmpcmp = Sse2.Subtract(charf, upper); + cmp = Sse2.MoveMask(tmpcmp); + if (cmp != 0) + throw new Exception("bad"); + + Vector128 charTolower = Vector128.Create((byte)0x20); + Vector128 lowerLetters = Sse2.Or(lower, charTolower); + Vector128 upperLetters = Sse2.Or(upper, charTolower); + + Vector128 letterTohex = Vector128.Create((byte)('a' - '0' - 10)); + lowerLetters = Sse2.Subtract(lowerLetters, letterTohex); + upperLetters = Sse2.Subtract(upperLetters, letterTohex); + + Vector128 char9 = Vector128.Create((byte)'9'); + Vector128 above9lower = (Sse2.CompareGreaterThan(lower.AsSByte(), char9.AsSByte())).AsByte(); + + Vector128 ten = Vector128.Create((byte)('0' + 10)); + tmpcmp = Sse2.Subtract(lowerLetters, ten); + tmpcmp = Sse2.And(tmpcmp, above9lower); + cmp = Sse2.MoveMask(tmpcmp); + if (cmp != 0) + throw new Exception("bad"); + Vector128 above9upper = (Sse2.CompareGreaterThan(upper.AsSByte(), char9.AsSByte())).AsByte(); + + tmpcmp = Sse2.Subtract(upperLetters, ten); + tmpcmp = Sse2.And(tmpcmp, above9upper); + cmp = Sse2.MoveMask(tmpcmp); + if (cmp != 0) + throw new Exception("bad"); + + lower = Sse41.BlendVariable(lower, lowerLetters, above9lower); + upper = Sse41.BlendVariable(upper, upperLetters, above9upper); + Vector128 charzero = Vector128.Create((byte)'0'); + lower = Sse2.Subtract(lower, charzero); + cmp = Sse2.MoveMask(lower); + if (cmp != 0) + throw new Exception("bad"); + upper = Sse2.Subtract(upper, charzero); + cmp = Sse2.MoveMask(upper); + if (cmp != 0) + throw new Exception("bad"); + upper = Sse2.ShiftLeftLogical(upper.AsUInt16(), 4).AsByte(); + lower = Sse2.Or(lower, upper); + if (BitConverter.IsLittleEndian) + lower = Ssse3.Shuffle(lower, Vector128.Create((byte)0x03, 0x02, 0x01, 0x00, 0x05, 0x04, 0x07, 0x06, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F)); + Unsafe.As>(ref Unsafe.AsRef(in result)) = lower; + return true; + } + + if (BitConverter.IsLittleEndian) + { + result.bytea3 = Utils.HexToByte(val, 0); + result.bytea2 = Utils.HexToByte(val, 2); + result.bytea1 = Utils.HexToByte(val, 4); + result.bytea0 = Utils.HexToByte(val, 6); + + result.byteb1 = Utils.HexToByte(val, 9); + result.byteb0 = Utils.HexToByte(val, 11); + + result.bytec1 = Utils.HexToByte(val, 14); + result.bytec0 = Utils.HexToByte(val, 16); + } + else + { + result.bytea0 = Utils.HexToByte(val, 0); + result.bytea1 = Utils.HexToByte(val, 2); + result.bytea2 = Utils.HexToByte(val, 4); + result.bytea3 = Utils.HexToByte(val, 6); + + result.byteb0 = Utils.HexToByte(val, 9); + result.byteb1 = Utils.HexToByte(val, 11); + + result.bytec0 = Utils.HexToByte(val, 14); + result.bytec1 = Utils.HexToByte(val, 16); + } + + result.d = Utils.HexToByte(val, 19); + result.e = Utils.HexToByte(val, 21); + + + result.f = Utils.HexToByte(val, 24); + result.g = Utils.HexToByte(val, 26); + result.h = Utils.HexToByte(val, 28); + result.i = Utils.HexToByte(val, 30); + result.j = Utils.HexToByte(val, 32); + result.k = Utils.HexToByte(val, 34); + return true; + } + else + { + if (BitConverter.IsLittleEndian) + { + result.bytea3 = Utils.HexToByte(val, 0); + result.bytea2 = Utils.HexToByte(val, 2); + result.bytea1 = Utils.HexToByte(val, 4); + result.bytea0 = Utils.HexToByte(val, 6); + + result.byteb1 = Utils.HexToByte(val, 8); + result.byteb0 = Utils.HexToByte(val, 10); + + result.bytec1 = Utils.HexToByte(val, 12); + result.bytec0 = Utils.HexToByte(val, 14); + } + else + { + result.bytea0 = Utils.HexToByte(val, 0); + result.bytea1 = Utils.HexToByte(val, 2); + result.bytea2 = Utils.HexToByte(val, 4); + result.bytea3 = Utils.HexToByte(val, 6); + + result.byteb0 = Utils.HexToByte(val, 8); + result.byteb1 = Utils.HexToByte(val, 10); + + result.bytec0 = Utils.HexToByte(val, 12); + result.bytec1 = Utils.HexToByte(val, 14); + } + + result.d = Utils.HexToByte(val, 16); + result.e = Utils.HexToByte(val, 18); + + result.f = Utils.HexToByte(val, 20); + result.g = Utils.HexToByte(val, 22); + result.h = Utils.HexToByte(val, 24); + result.i = Utils.HexToByte(val, 26); + result.j = Utils.HexToByte(val, 28); + result.k = Utils.HexToByte(val, 30); + return true; + } + } + } + catch { } + result = new UUID(); + return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -987,17 +1275,17 @@ public static byte[] GetASCIIBytes(string s) public static bool IsNullOrEmpty(osUTF8 u) { - return (u == null || u.m_len == 0); + return (u is null || u.m_len == 0); } public static bool IsEmpty(osUTF8 u) { - return (u == null || u.m_len == 0); + return (u is null || u.m_len == 0); } public static unsafe bool IsNullOrWhitespace(osUTF8 u) { - if(u == null || u.m_len == 0) + if(u is null || u.m_len == 0) return true; byte[] data = u.m_data; for (int i = 0; i < u.m_len; ++i) @@ -1040,7 +1328,7 @@ public osUTF8 RemoveBytes(int start, int len) if (start >= m_len) return Clone(); - osUTF8 o = new osUTF8(m_len); + osUTF8 o = new(m_len); Array.Copy(m_data, 0, o.m_data, 0, start); o.m_len = start; @@ -1055,5 +1343,26 @@ public osUTF8 RemoveBytes(int start, int len) o.m_len = m_len - len; return o; } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void ToVarBin(Stream ms) + { + Utils.UIntToVarBytes(ms, (uint)m_len); + if (m_len > 0) + ms.Write(m_data, 0, m_len); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static osUTF8 FromVarBin(Stream ms) + { + int len = (int)Utils.VarBytestoUlong(ms); + if(len > 0) + { + byte[] data = new byte[len]; + ms.Read(data,0, len); + return new osUTF8(data); + } + return new osUTF8(); + } } } diff --git a/OpenMetaverse.Types/OSUTF8Cached.cs b/OpenMetaverse.Types/OSUTF8Cached.cs index 4b8cb436..25207f1e 100644 --- a/OpenMetaverse.Types/OSUTF8Cached.cs +++ b/OpenMetaverse.Types/OSUTF8Cached.cs @@ -39,9 +39,9 @@ namespace OpenMetaverse { public static class OSUTF8Cached { - const int MAXSIZE = 128; // 8MB + const int MAXSIZE = 128; // 16MB const int PREALLOC = 128; - const int MAXDATASIZE = 64 * 1024; + public const int MAXDATASIZE = 128 * 1024; private static readonly osUTF8[] m_pool = new osUTF8[MAXSIZE]; private static readonly object m_poollock = new object(); @@ -123,5 +123,23 @@ public static byte[] GetArrayAndRelease(osUTF8 os) } return result; } + + public static string GetStringAndRelease(osUTF8 os) + { + string ret = os.ToString(); + if (os.m_data.Length == MAXDATASIZE) + { + lock (m_poollock) + { + if (m_poolPtr < MAXSIZE - 1) + { + os.Clear(); + m_poolPtr++; + m_pool[m_poolPtr] = os; + } + } + } + return ret; + } } } diff --git a/OpenMetaverse.Types/OSUTF8Constants.cs b/OpenMetaverse.Types/OSUTF8Constants.cs index 36cc94e5..8d7a3518 100644 --- a/OpenMetaverse.Types/OSUTF8Constants.cs +++ b/OpenMetaverse.Types/OSUTF8Constants.cs @@ -31,81 +31,107 @@ namespace OpenMetaverse public static class osUTF8Const { // direct utf8 string byte arrays to use with osUTF8 and osUTF8Slice - // waste time calling osUTF8.GetASCIIBytes just because it is more readable then {(byte)char,... } form - public static readonly byte[] XMLundef = osUTF8.GetASCIIBytes(""); - public static readonly byte[] XMLfullbooleanOne = osUTF8.GetASCIIBytes("1"); - public static readonly byte[] XMLfullbooleanZero = osUTF8.GetASCIIBytes("0"); - public static readonly byte[] XMLintegerStart = osUTF8.GetASCIIBytes(""); - public static readonly byte[] XMLintegerEmpty = osUTF8.GetASCIIBytes(""); - public static readonly byte[] XMLintegerEnd = osUTF8.GetASCIIBytes(""); - public static readonly byte[] XMLrealStart = osUTF8.GetASCIIBytes(""); - public static readonly byte[] XMLrealZero = osUTF8.GetASCIIBytes("0"); - public static readonly byte[] XMLrealZeroarrayEnd = osUTF8.GetASCIIBytes("0"); - public static readonly byte[] XMLrealEnd = osUTF8.GetASCIIBytes(""); - public static readonly byte[] XMLrealEndarrayEnd = osUTF8.GetASCIIBytes(""); - public static readonly byte[] XMLstringStart = osUTF8.GetASCIIBytes(""); - public static readonly byte[] XMLstringEmpty = osUTF8.GetASCIIBytes(""); - public static readonly byte[] XMLstringEnd = osUTF8.GetASCIIBytes(""); - public static readonly byte[] XMLuuidStart = osUTF8.GetASCIIBytes(""); - public static readonly byte[] XMLuuidEmpty = osUTF8.GetASCIIBytes(""); - public static readonly byte[] XMLuuidEnd = osUTF8.GetASCIIBytes(""); - public static readonly byte[] XMLdateStart = osUTF8.GetASCIIBytes(""); - public static readonly byte[] XMLdateEmpty = osUTF8.GetASCIIBytes(""); - public static readonly byte[] XMLdateEnd = osUTF8.GetASCIIBytes(""); - public static readonly byte[] XMLuriStart = osUTF8.GetASCIIBytes(""); - public static readonly byte[] XMLuriEmpty = osUTF8.GetASCIIBytes(""); - public static readonly byte[] XMLuriEnd = osUTF8.GetASCIIBytes(""); - public static readonly byte[] XMLformalBinaryStart = osUTF8.GetASCIIBytes(""); - public static readonly byte[] XMLbinaryStart = osUTF8.GetASCIIBytes(""); - public static readonly byte[] XMLbinaryEmpty = osUTF8.GetASCIIBytes(""); - public static readonly byte[] XMLbinaryEnd = osUTF8.GetASCIIBytes(""); - public static readonly byte[] XMLmapStart = osUTF8.GetASCIIBytes(""); - public static readonly byte[] XMLmapEmpty = osUTF8.GetASCIIBytes(""); - public static readonly byte[] XMLmapEnd = osUTF8.GetASCIIBytes(""); - public static readonly byte[] XMLkeyStart = osUTF8.GetASCIIBytes(""); - public static readonly byte[] XMLkeyEmpty = osUTF8.GetASCIIBytes(""); - public static readonly byte[] XMLkeyEnd = osUTF8.GetASCIIBytes(""); - public static readonly byte[] XMLkeyEndundef = osUTF8.GetASCIIBytes(""); - public static readonly byte[] XMLkeyEndmapStart = osUTF8.GetASCIIBytes(""); - public static readonly byte[] XMLkeyEndmapEmpty = osUTF8.GetASCIIBytes(""); - public static readonly byte[] XMLkeyEndarrayStart = osUTF8.GetASCIIBytes(""); - public static readonly byte[] XMLkeyEndarrayEmpty = osUTF8.GetASCIIBytes(""); - public static readonly byte[] XMLkeyEndarrayStartmapStart = osUTF8.GetASCIIBytes(""); - public static readonly byte[] XMLarrayStart = osUTF8.GetASCIIBytes(""); - public static readonly byte[] XMLarrayStartrealZero = osUTF8.GetASCIIBytes("0"); - public static readonly byte[] XMLarrayStartrealStart = osUTF8.GetASCIIBytes(""); - public static readonly byte[] XMLkeyEndarrayStartrealZero = osUTF8.GetASCIIBytes("0"); - public static readonly byte[] XMLkeyEndarrayStartrealStart = osUTF8.GetASCIIBytes(""); - public static readonly byte[] XMLarrayEmpty = osUTF8.GetASCIIBytes(""); - public static readonly byte[] XMLarrayEnd = osUTF8.GetASCIIBytes(""); - public static readonly byte[] XMLamp_lt = osUTF8.GetASCIIBytes("<"); - public static readonly byte[] XMLamp_gt = osUTF8.GetASCIIBytes(">"); - public static readonly byte[] XMLamp = osUTF8.GetASCIIBytes("&"); - public static readonly byte[] XMLamp_quot = osUTF8.GetASCIIBytes("""); - public static readonly byte[] XMLamp_apos = osUTF8.GetASCIIBytes("'"); - public static readonly byte[] XMLformalHeader = osUTF8.GetASCIIBytes(""); - public static readonly byte[] XMLformalHeaderllsdstart = osUTF8.GetASCIIBytes(""); - public static readonly byte[] XMLllsdStart = osUTF8.GetASCIIBytes(""); - public static readonly byte[] XMLllsdEnd = osUTF8.GetASCIIBytes(""); - public static readonly byte[] XMLllsdEmpty = osUTF8.GetASCIIBytes(""); - public static readonly byte[] XMLmapEndarrayEnd = osUTF8.GetASCIIBytes(""); - - public static readonly byte[] XMLarrayEndmapEnd = osUTF8.GetASCIIBytes(""); - - public static readonly byte[] XMLelement_name_Empty = osUTF8.GetASCIIBytes("name"); - public static readonly byte[] XMLelement_name_Start = osUTF8.GetASCIIBytes("name"); - - public static readonly byte[] XMLelement_agent_id_Empty = osUTF8.GetASCIIBytes("agent_id"); - public static readonly byte[] XMLelement_agent_id_Start = osUTF8.GetASCIIBytes("agent_id"); - - public static readonly byte[] XMLelement_owner_id_Empty = osUTF8.GetASCIIBytes("owner_id"); - public static readonly byte[] XMLelement_owner_id_Start = osUTF8.GetASCIIBytes("owner_id"); - - public static readonly byte[] XMLelement_parent_id_Empty = osUTF8.GetASCIIBytes("parent_id"); - public static readonly byte[] XMLelement_parent_id_Start = osUTF8.GetASCIIBytes("parent_id"); - - public static readonly byte[] XMLelement_folder_id_Empty = osUTF8.GetASCIIBytes("folder_id"); - public static readonly byte[] XMLelement_folder_id_Start = osUTF8.GetASCIIBytes("folder_id"); + public static readonly byte[] XMLundef = ""u8.ToArray(); + public static readonly byte[] XMLfullbooleanOne = "1"u8.ToArray(); + public static readonly byte[] XMLfullbooleanZero = "0"u8.ToArray(); + public static readonly byte[] XMLintegerStart = ""u8.ToArray(); + public static readonly byte[] XMLintegerEmpty = ""u8.ToArray(); + public static readonly byte[] XMLintegerEnd = ""u8.ToArray(); + public static readonly byte[] XMLrealStart = ""u8.ToArray(); + public static readonly byte[] XMLrealZero = "0"u8.ToArray(); + public static readonly byte[] XMLrealZeroarrayEnd = "0"u8.ToArray(); + public static readonly byte[] XMLrealEnd = ""u8.ToArray(); + public static readonly byte[] XMLrealEndarrayEnd = ""u8.ToArray(); + public static readonly byte[] XMLstringStart = ""u8.ToArray(); + public static readonly byte[] XMLstringEmpty = ""u8.ToArray(); + public static readonly byte[] XMLstringEnd = ""u8.ToArray(); + public static readonly byte[] XMLuuidStart = ""u8.ToArray(); + public static readonly byte[] XMLuuidEmpty = ""u8.ToArray(); + public static readonly byte[] XMLuuidEnd = ""u8.ToArray(); + public static readonly byte[] XMLdateStart = ""u8.ToArray(); + public static readonly byte[] XMLdateEmpty = ""u8.ToArray(); + public static readonly byte[] XMLdateEnd = ""u8.ToArray(); + public static readonly byte[] XMLuriStart = ""u8.ToArray(); + public static readonly byte[] XMLuriEmpty = ""u8.ToArray(); + public static readonly byte[] XMLuriEnd = ""u8.ToArray(); + public static readonly byte[] XMLformalBinaryStart = ""u8.ToArray(); + public static readonly byte[] XMLbinaryStart = ""u8.ToArray(); + public static readonly byte[] XMLbinaryEmpty = ""u8.ToArray(); + public static readonly byte[] XMLbinaryEnd = ""u8.ToArray(); + public static readonly byte[] XMLmapStart = ""u8.ToArray(); + public static readonly byte[] XMLmapEmpty = ""u8.ToArray(); + public static readonly byte[] XMLmapEnd = ""u8.ToArray(); + public static readonly byte[] XMLkeyStart = ""u8.ToArray(); + public static readonly byte[] XMLkeyEmpty = ""u8.ToArray(); + public static readonly byte[] XMLkeyEnd = ""u8.ToArray(); + public static readonly byte[] XMLkeyEndundef = ""u8.ToArray(); + public static readonly byte[] XMLkeyEndmapStart = ""u8.ToArray(); + public static readonly byte[] XMLkeyEndmapEmpty = ""u8.ToArray(); + public static readonly byte[] XMLkeyEndarrayStart = ""u8.ToArray(); + public static readonly byte[] XMLkeyEndarrayEmpty = ""u8.ToArray(); + public static readonly byte[] XMLkeyEndarrayStartmapStart = ""u8.ToArray(); + public static readonly byte[] XMLarrayStart = ""u8.ToArray(); + public static readonly byte[] XMLarrayStartrealZero = "0"u8.ToArray(); + public static readonly byte[] XMLarrayStartrealStart = ""u8.ToArray(); + public static readonly byte[] XMLkeyEndarrayStartrealZero = "0"u8.ToArray(); + public static readonly byte[] XMLkeyEndarrayStartrealStart = ""u8.ToArray(); + public static readonly byte[] XMLarrayEmpty = ""u8.ToArray(); + public static readonly byte[] XMLarrayEnd = ""u8.ToArray(); + public static readonly byte[] XMLamp_lt = "<"u8.ToArray(); + public static readonly byte[] XMLamp_gt = ">"u8.ToArray(); + public static readonly byte[] XMLamp = "&"u8.ToArray(); + public static readonly byte[] XMLamp_quot = """u8.ToArray(); + public static readonly byte[] XMLamp_apos = "'"u8.ToArray(); + public static readonly byte[] XMLformalHeader = ""u8.ToArray(); + public static readonly byte[] XMLformalHeaderllsdstart = ""u8.ToArray(); + public static readonly byte[] XMLllsdStart = ""u8.ToArray(); + public static readonly byte[] XMLllsdEnd = ""u8.ToArray(); + public static readonly byte[] XMLllsdEmpty = ""u8.ToArray(); + public static readonly byte[] XMLmapEndarrayEnd = ""u8.ToArray(); + + public static readonly byte[] XMLarrayEndmapEnd = ""u8.ToArray(); + + public static readonly byte[] XMLelement_name_Empty = "name"u8.ToArray(); + public static readonly byte[] XMLelement_name_Start = "name"u8.ToArray(); + + public static readonly byte[] XMLelement_agent_id_Empty = "agent_id"u8.ToArray(); + public static readonly byte[] XMLelement_agent_id_Start = "agent_id"u8.ToArray(); + + public static readonly byte[] XMLelement_owner_id_Empty = "owner_id"u8.ToArray(); + public static readonly byte[] XMLelement_owner_id_Start = "owner_id"u8.ToArray(); + + public static readonly byte[] XMLelement_creator_id_Empty = "creator_id"u8.ToArray(); + public static readonly byte[] XMLelement_creator_id_Start = "creator_id"u8.ToArray(); + + public static readonly byte[] XMLelement_group_id_Empty = "group_id"u8.ToArray(); + public static readonly byte[] XMLelement_group_id_Start = "cgroup_id"u8.ToArray(); + + public static readonly byte[] XMLelement_parent_id_Empty = "parent_id"u8.ToArray(); + public static readonly byte[] XMLelement_parent_id_Start = "parent_id"u8.ToArray(); + + public static readonly byte[] XMLelement_folder_id_Empty = "folder_id"u8.ToArray(); + public static readonly byte[] XMLelement_folder_id_Start = "folder_id"u8.ToArray(); + + public static readonly byte[] XMLelement_asset_id_Empty = "asset_id"u8.ToArray(); + public static readonly byte[] XMLelement_asset_id_Start = "asset_id"u8.ToArray(); + + public static readonly byte[] XMLelement_item_id_Empty = "item_id"u8.ToArray(); + public static readonly byte[] XMLelement_item_id_Start = "item_id"u8.ToArray(); + + public static readonly byte[] XMLelement_category_id_Empty = "category_id"u8.ToArray(); + public static readonly byte[] XMLelement_category_id_Start = "category_id"u8.ToArray(); + + public static readonly byte[] XMLelement_version_Empty = "version"u8.ToArray(); + public static readonly byte[] XMLelement_version_Start = "version"u8.ToArray(); + + public static readonly byte[] XMLelement_sale_info_Empty = "sale_infosale_pricesale_type"u8.ToArray(); + public static readonly byte[] XMLelement_sale_info_Start = "sale_infosale_price"u8.ToArray(); + public static readonly byte[] XMLelement_sale_info_Mid = "sale_type"u8.ToArray(); + public static readonly byte[] XMLelement_sale_info_End = ""u8.ToArray(); + + public static readonly byte[] OSUTF8null = "null"u8.ToArray(); + public static readonly byte[] OSUTF8true = "true"u8.ToArray(); + public static readonly byte[] OSUTF8false = "false"u8.ToArray(); public static readonly byte[] base64Bytes = {(byte)'A',(byte)'B',(byte)'C',(byte)'D',(byte)'E',(byte)'F',(byte)'G',(byte)'H',(byte)'I',(byte)'J',(byte)'K',(byte)'L',(byte)'M',(byte)'N',(byte)'O', (byte)'P',(byte)'Q',(byte)'R',(byte)'S',(byte)'T',(byte)'U',(byte)'V',(byte)'W',(byte)'X',(byte)'Y',(byte)'Z',(byte)'a',(byte)'b',(byte)'c',(byte)'d', diff --git a/OpenMetaverse.Types/OSUTF8Slice.cs b/OpenMetaverse.Types/OSUTF8Slice.cs index 1f428635..ef8e4249 100644 --- a/OpenMetaverse.Types/OSUTF8Slice.cs +++ b/OpenMetaverse.Types/OSUTF8Slice.cs @@ -38,6 +38,9 @@ Ubit Umarov (Leal Duarte) 2020 using System.Text; using System.Collections.Generic; using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Runtime.Intrinsics.X86; +using System.Runtime.Intrinsics; namespace OpenMetaverse { @@ -51,7 +54,7 @@ public class osUTF8Slice public osUTF8Slice() { - m_data = new byte[0]; + m_data = Array.Empty(); m_offset = 0; m_len = 0; } @@ -128,11 +131,11 @@ public byte this[int i] if (i >= m_len) i = m_len - 1; i += m_offset; - if (i < 0) - i = 0; - else if (i >= m_data.Length) + if (i >= m_data.Length) i = m_data.Length - 1; - return m_data[i]; + if (i <= 0) + return Unsafe.As(ref MemoryMarshal.GetArrayDataReference(m_data)); + return Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(m_data), i)); } set { @@ -140,7 +143,7 @@ public byte this[int i] { i += m_offset; if(i < m_len) - m_data[i] = value; + Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(m_data), i)) = value; } } } @@ -179,24 +182,45 @@ public void MoveStart(int of) m_len = m_data.Length - m_offset; } + public void FromBytesSafe(byte[] source, int offset, int len) + { + m_data = source; + m_offset = offset; + m_len = len; + } + + public void FromBytes(byte[] source, int offset, int len) + { + if (source == null || offset >= source.Length || offset + len >= source.Length) + { + m_offset = 0; + m_len = 0; + } + if (len < 0) + len = 0; + m_data = source; + m_offset = offset; + m_len = len; + } + public static bool IsNullOrEmpty(osUTF8Slice u) { - return (u == null || u.m_len == 0); + return (u is null || u.m_len == 0); } public static bool IsEmpty(osUTF8Slice u) { - return (u == null || u.m_len == 0); + return (u is null || u.m_len == 0); } public static unsafe bool IsNullOrWhitespace(osUTF8Slice u) { - if (u == null || u.m_len == 0) + if (u is null || u.m_len == 0) return true; byte[] data = u.m_data; for (int i = u.m_offset; i < u.m_offset + u.m_len; ++i) { - if (data[i] != 0x20) + if (Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(data), i)) != 0x20) return false; } return true; @@ -205,26 +229,11 @@ public static unsafe bool IsNullOrWhitespace(osUTF8Slice u) public unsafe override int GetHashCode() { int hash = m_len; - if (m_len < 8) - { - for (int i = m_offset; i < m_offset + m_len; ++i) - { - hash += m_data[i]; - hash <<= 3; - hash += hash >> 26; - } - } - else + for (int i = m_offset; i < m_offset + m_len; ++i) { - fixed (byte* a = &m_data[m_offset]) - { - for (int i = 0; i < m_len; ++i) - { - hash += a[i]; - hash <<= 5; - hash += hash >> 26; - } - } + hash += Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(m_data), i)); + hash <<= 3; + hash += hash >> 26; } return hash & 0x7fffffff; } @@ -239,103 +248,64 @@ public override string ToString() public override bool Equals(object obj) { - if (obj == null) + if (obj is null) return false; - if (obj is osUTF8) - return Equals((osUTF8)obj); + if (obj is osUTF8 o8) + return Equals(o8); - if (obj is osUTF8Slice) - return Equals((osUTF8Slice)obj); + if (obj is osUTF8Slice o8s) + return Equals(o8s); - if (obj is string) - return Equals((string)obj); + if (obj is string os) + return Equals(os); - if (obj is byte[]) - return Equals((byte[])obj); + if (obj is byte[] oba) + return Equals(oba); return false; } - public unsafe bool Equals(osUTF8Slice o) + public bool Equals(osUTF8Slice o) { - if (o == null || m_len != o.m_len) + if (o is null || m_len != o.m_len) return false; byte[] otherdata = o.m_data; - - if (m_len < 8) - { - for (int i = m_offset, j = o.m_offset; i < m_offset + m_len; ++i, ++j) - { - if (m_data[i] != otherdata[j]) - return false; - } - return true; - } - - fixed (byte* a = &m_data[m_offset], b = &otherdata[o.m_offset]) + for (int i = m_offset, j = o.m_offset; i < m_offset + m_len; ++i, ++j) { - for (int i = 0; i < m_len; ++i) - { - if (a[i] != b[i]) - return false; - } + if (Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(m_data), i)) != + Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(otherdata), j))) + return false; } - return true; } - public unsafe bool Equals(osUTF8 o) + public bool Equals(osUTF8 o) { - if (o == null || m_len != o.m_len) + if (o is null || m_len != o.m_len) return false; byte[] otherdata = o.m_data; - - if (m_len < 8) + for (int i = m_offset, j = 0; i < m_offset + m_len; ++i, ++j) { - for (int i = m_offset, j = 0; i < m_offset + m_len; ++i, ++j) - { - if (m_data[i] != otherdata[j]) - return false; - } - return true; - } - - fixed (byte* a = &m_data[m_offset], b = otherdata) - { - for (int i = 0; i < m_len; ++i) - { - if (a[i] != b[i]) - return false; - } + if (Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(m_data), i)) != + Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(otherdata), j))) + return false; } return true; } - public unsafe bool Equals(byte[] o) + public bool Equals(byte[] o) { if (o == null || m_len != o.Length) return false; - if (m_len < 8) + for (int i = m_offset, j = 0; i < m_offset + m_len; ++i, ++j) { - for (int i = m_offset, j = 0; i < m_offset + m_len; ++i, ++j) - { - if (m_data[i] != o[j]) - return false; - } - return true; - } - - fixed (byte* a = &m_data[m_offset], b = o) - { - for (int i = 0; i < m_len; ++i) - { - if (a[i] != b[i]) - return false; - } + if (Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(m_data), i)) != + Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(o), j))) + return false; } return true; } @@ -344,19 +314,36 @@ public bool Equals(string s) { if(string.IsNullOrEmpty(s)) return m_len == 0; - osUTF8 o = new osUTF8(s); + osUTF8 o = new(s); return Equals(o); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool operator ==(osUTF8Slice value1, osUTF8Slice value2) + { + if (value1 is null) + return value2 is null; + return value1.Equals(value2); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool operator !=(osUTF8Slice value1, osUTF8Slice value2) + { + if (value1 is null) + return value2 is not null; + return !value1.Equals(value2); + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Equals(char c) { - return m_len == 1 && m_data[m_offset] == (byte)c; + return m_len == 1 && + Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(m_data), m_offset)) == (byte)c; } public unsafe bool ACSIILowerEquals(osUTF8 o) { - if (o == null || m_len != o.m_len) + if (o is null || m_len != o.m_len) return false; fixed (byte* a = &m_data[m_offset], b = o.m_data) @@ -501,7 +488,7 @@ public void AppendASCII(char c) { int indx = m_offset + m_len; CheckCapacity(ref indx, 1); - m_data[indx] = (byte)c; + Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(m_data), indx)) = (byte)c; ++m_len; } @@ -626,22 +613,22 @@ public osUTF8Slice SubUTF8(int start, int len) int last = start + len - 1; // cut at code points; - if (start > 0 && (m_data[start] & 0x80) != 0) + if (start > 0 && (Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(m_data), start)) & 0x80) != 0) { do { --last; } - while (start > 0 && (m_data[start] & 0xc0) != 0xc0); + while (start > 0 && (Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(m_data), start)) & 0xc0) != 0xc0); } - if (last > start && (m_data[last] & 0x80) != 0) + if (last > start && (Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(m_data), last)) & 0x80) != 0) { do { --last; } - while (last > start && (m_data[last] & 0xc0) != 0xc0); + while (last > start && (Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(m_data), last)) & 0xc0) != 0xc0); } return new osUTF8Slice(m_data, start, last - start + 1); @@ -688,22 +675,22 @@ public void SubUTF8Self(int start, int len) int last = start + len - 1; // cut at code points; - if (start > 0 && (m_data[start] & 0x80) != 0) + if (start > 0 && (Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(m_data), start)) & 0x80) != 0) { do { --last; } - while (start > 0 && (m_data[start] & 0xc0) != 0xc0); + while (start > 0 && (Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(m_data), start)) & 0xc0) != 0xc0); } - if (last > start && (m_data[last] & 0x80) != 0) + if (last > start && (Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(m_data), last)) & 0x80) != 0) { do { --last; } - while (last > start && (m_data[last] & 0xc0) != 0xc0); + while (last > start && (Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(m_data), last)) & 0xc0) != 0xc0); } m_offset = start; @@ -725,7 +712,7 @@ public string SubString(int start, int len) } [MethodImpl(MethodImplOptions.AggressiveInlining)] - private bool checkAny(byte b, byte[] bytes) + private static bool checkAny(byte b, byte[] bytes) { for (int i = 0; i < bytes.Length; ++i) { @@ -736,7 +723,7 @@ private bool checkAny(byte b, byte[] bytes) } [MethodImpl(MethodImplOptions.AggressiveInlining)] - private bool checkAny(byte b, char[] chars) + private static bool checkAny(byte b, char[] chars) { for (int i = 0; i < chars.Length; ++i) { @@ -749,7 +736,7 @@ private bool checkAny(byte b, char[] chars) // inplace remove white spaces at start public void SelfTrimStart() { - while (m_len > 0 && m_data[m_offset] == 0x20) + while (m_len > 0 && Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(m_data), m_offset)) == 0x20) { ++m_offset; --m_len; @@ -758,7 +745,7 @@ public void SelfTrimStart() public void SelfTrimStart(byte b) { - while (m_len > 0 && m_data[m_offset] == b) + while (m_len > 0 && Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(m_data), m_offset)) == b) { ++m_offset; --m_len; @@ -767,7 +754,7 @@ public void SelfTrimStart(byte b) public void SelfTrimStart(byte[] b) { - while (m_len > 0 && checkAny(m_data[m_offset], b)) + while (m_len > 0 && checkAny(Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(m_data), m_offset)), b)) { ++m_offset; --m_len; @@ -776,7 +763,7 @@ public void SelfTrimStart(byte[] b) public void SelfTrimStart(char[] b) { - while (m_len > 0 && checkAny(m_data[m_offset], b)) + while (m_len > 0 && checkAny(Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(m_data), m_offset)), b)) { ++m_offset; --m_len; @@ -788,7 +775,7 @@ public void SelfTrimEnd() if (m_len == 0) return; int last = m_offset + m_len - 1; - while (m_len > 0 && m_data[last] == 0x20) + while (m_len > 0 && Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(m_data), last)) == 0x20) { --last; --m_len; @@ -800,7 +787,7 @@ public void SelfTrimEnd(byte b) if (m_len == 0) return; int last = m_offset + m_len - 1; - while (m_len > 0 && m_data[last] == b) + while (m_len > 0 && Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(m_data), last)) == b) { --last; --m_len; @@ -812,7 +799,7 @@ public void SelfTrimEnd(byte[] b) if (m_len == 0) return; int last = m_offset + m_len - 1; - while (m_len > 0 && checkAny(m_data[last], b)) + while (m_len > 0 && checkAny(Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(m_data), last)), b)) { --last; --m_len; @@ -824,7 +811,7 @@ public void SelfTrimEnd(char[] b) if (m_len == 0) return; int last = m_offset + m_len - 1; - while (m_len > 0 && checkAny(m_data[last], b)) + while (m_len > 0 && checkAny(Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(m_data), last)), b)) { --last; --m_len; @@ -1002,22 +989,22 @@ public bool StartsWith(string s) public bool StartsWith(byte b) { - return m_data[m_offset] == b; + return Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(m_data), m_offset)) == b; } public bool StartsWith(char b) { - return m_data[m_offset] == (byte)b; + return Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(m_data), m_offset)) == (byte)b; } public bool EndsWith(byte b) { - return m_data[m_offset + m_len - 1] == b; + return Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(m_data), m_offset + m_len - 1)) == b; } public bool EndsWith(char b) { - return m_data[m_offset + m_len - 1] == (byte)b; + return Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(m_data), m_offset + m_len - 1)) == (byte)b; } public unsafe bool EndsWith(osUTF8Slice other) @@ -1079,22 +1066,9 @@ public bool EndsWith(string s) public unsafe int IndexOf(byte b) { - if (m_len > 8) - { - fixed (byte* a = &m_data[m_offset]) - { - for (int i = 0; i < m_len; ++i) - { - if (a[i] == b) - return i; - } - return -1; - } - } - for (int i = m_offset; i < m_offset + m_len; ++i) { - if (m_data[i] == b) + if (Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(m_data), i)) == b) return i - m_offset; } return -1; @@ -1104,7 +1078,7 @@ public int IndexOf(char b) { if (b < 0x80) return IndexOf((byte)b); - string s = new string(new char[] { b }); + string s = new(new char[] { b }); return IndexOf(s); } @@ -1185,52 +1159,28 @@ public int IndexOf(string s) { if (string.IsNullOrEmpty(s)) return -1; - osUTF8 o = new osUTF8(s); + osUTF8 o = new(s); return IndexOf(o); } - public unsafe int IndexOfAny(byte[] b) + public int IndexOfAny(byte[] b) { - if (m_len < 8) - { - for (int i = m_offset; i < m_offset + m_len; ++i) - { - if (checkAny(m_data[i], b)) - return i - m_offset; - } - return -1; - } - fixed (byte* a = &m_data[m_offset]) + for (int i = m_offset; i < m_offset + m_len; ++i) { - for (int i = 0; i < m_len; ++i) - { - if (checkAny(a[i], b)) - return i; - } - return -1; + if (checkAny(Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(m_data), i)), b)) + return i - m_offset; } + return -1; } - public unsafe int IndexOfAny(char[] b) + public int IndexOfAny(char[] b) { - if (m_len < 8) - { - for (int i = m_offset; i < m_offset + m_len; ++i) - { - if (checkAny(m_data[i], b)) - return i - m_offset; - } - return -1; - } - fixed (byte* a = &m_data[m_offset]) + for (int i = m_offset; i < m_offset + m_len; ++i) { - for (int i = 0; i < m_len; ++i) - { - if (checkAny(a[i], b)) - return i; - } - return -1; + if (checkAny(Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(m_data), i)), b)) + return i - m_offset; } + return -1; } public bool Contains(osUTF8Slice other) @@ -1329,48 +1279,28 @@ public osUTF8Slice[] Split(char b, bool ignoreEmpty = true) if (b < 0x80) return Split((byte)b, ignoreEmpty); - return new osUTF8Slice[0]; + return Array.Empty(); } public unsafe bool ReadLine(out osUTF8Slice line) { if (m_len == 0) { - line = new osUTF8Slice(new byte[0], 0, 0); + line = new osUTF8Slice(); return false; } int lineend = -1; byte b = 0; - if (m_len < 8) - { - for (int i = m_offset; i < m_offset + m_len; ++i) - { - b = m_data[i]; - if (b == (byte)'\r' || b == (byte)'\n') - { - if (i > 0 && m_data[i - 1] == (byte)'\\') - continue; - lineend = i; - break; - } - } - } - else + for (int i = m_offset; i < m_offset + m_len; ++i) { - fixed (byte* a = &m_data[m_offset]) + b = Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(m_data), i)); + if (b == (byte)'\r' || b == (byte)'\n') { - for (int i = 0; i < m_len; ++i) - { - b = a[i]; - if (b == (byte)'\r' || b == (byte)'\n') - { - if (i > 0 && a[i - 1] == (byte)'\\') - continue; - lineend = i + m_offset; - break; - } - } + if (i > 0 && Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(m_data), i - 1)) == (byte)'\\') + continue; + lineend = i; + break; } } @@ -1404,7 +1334,7 @@ public unsafe bool ReadLine(out osUTF8Slice line) if (b == (byte)'\r') { - if (m_data[m_offset] == (byte)'\n') + if (Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(m_data), m_offset)) == (byte)'\n') { ++m_offset; --m_len; @@ -1424,35 +1354,15 @@ public unsafe bool SkipLine() int lineend = -1; byte b = 0; - if (m_len < 8) - { - for (int i = m_offset; i < m_offset + m_len; ++i) - { - b = m_data[i]; - if (b == (byte)'\r' || b == (byte)'\n') - { - if (i > 0 && m_data[i - 1] == (byte)'\\') - continue; - lineend = i; - break; - } - } - } - else + for (int i = m_offset; i < m_offset + m_len; ++i) { - fixed (byte* a = &m_data[m_offset]) + b = Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(m_data), i)); + if (b == (byte)'\r' || b == (byte)'\n') { - for (int i = 0; i < m_len; ++i) - { - b = a[i]; - if (b == (byte)'\r' || b == (byte)'\n') - { - if (i > 0 && a[i - 1] == (byte)'\\') - continue; - lineend = i + m_offset; - break; - } - } + if (i > 0 && Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(m_data), i - 1)) == (byte)'\\') + continue; + lineend = i; + break; } } @@ -1483,7 +1393,7 @@ public unsafe bool SkipLine() if (b == (byte)'\r') { - if (m_data[m_offset] == (byte)'\n') + if (Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(m_data), m_offset)) == (byte)'\n') { ++m_offset; --m_len; @@ -1547,27 +1457,25 @@ public osUTF8Slice RemoveBytes(int start, int len) return o; } - public static bool TryParseInt(osUTF8Slice t, out int res) + public bool TryParseInt(out int res) { res = 0; - t.SelfTrim(); - int len = t.m_len; - if (len == 0) + SelfTrim(); + if (m_len == 0) return false; - byte[] data = t.m_data; - - int start = t.m_offset; + int len = m_len; + int start = m_offset; len += start; bool neg = false; - if (data[start] == (byte)'-') + if (Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(m_data), start)) == (byte)'-') { neg = true; ++start; } - else if (data[start] == (byte)'+') + else if (Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(m_data), start)) == (byte)'+') ++start; int b; @@ -1575,7 +1483,7 @@ public static bool TryParseInt(osUTF8Slice t, out int res) { while (start < len) { - b = data[start]; + b = Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(m_data), start)); b -= (byte)'0'; if (b < 0 || b > 9) break; @@ -1591,98 +1499,234 @@ public static bool TryParseInt(osUTF8Slice t, out int res) catch { } return false; } - - public static bool TryParseUUID(osUTF8Slice inp, out UUID res, bool dashs = true) + public static bool TryParseInt(osUTF8Slice t, out int res) { - res = UUID.Zero; - osUTF8Slice t = new osUTF8Slice(inp); + res = 0; t.SelfTrim(); int len = t.m_len; if (len == 0) return false; - if (dashs) - { - if (len < 36) - return false; - } - else - { - if (len < 32) - return false; - } - byte[] data = t.m_data; - int dataoffset = t.m_offset; - int _a = 0; - if (!Utils.TryHexToInt(data, dataoffset, 8, out _a)) - return false; - dataoffset += 8; + int start = t.m_offset; + len += start; - if (dashs) + bool neg = false; + if (Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(data), start)) == (byte)'-') { - if (data[dataoffset] != (byte)'-') - return false; - ++dataoffset; + neg = true; + ++start; } + else if (Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(data), start)) == (byte)'+') + ++start; - int n; - if (!Utils.TryHexToInt(data, dataoffset, 4, out n)) - return false; - short _b = (short)n; - dataoffset += 4; - - if (dashs) + int b; + try { - if (data[dataoffset] != (byte)'-') - return false; - ++dataoffset; + while (start < len) + { + b = Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(data), start)); + b -= (byte)'0'; + if (b < 0 || b > 9) + break; + + res *= 10; + res += b; + ++start; + } + if (neg) + res = -res; + return true; } + catch { } + return false; + } - if (!Utils.TryHexToInt(data, dataoffset, 4, out n)) + public unsafe static bool TryParseUUID(osUTF8Slice inp, out UUID result) + { + result = new UUID(); + int len = inp.m_len; + if (len < 32) return false; - short _c = (short)n; - dataoffset += 4; - if (dashs) + try { - if (data[dataoffset] != (byte)'-') - return false; - ++dataoffset; - } + fixed (byte* bval = &inp.m_data[inp.m_offset]) + { + byte* val = bval; - if (!Utils.TryHexToInt(data, dataoffset, 4, out n)) - return false; + while (*val == ' ') + { + ++val; + --len; + if (len < 32) + return false; + } - byte _d = (byte)(n >> 8); - byte _e = (byte)n; - dataoffset += 4; + if (val[8] == '-') + { + if (len < 36) + return false; - if (dashs) - { - if (data[dataoffset] != (byte)'-') - return false; - ++dataoffset; - } + if (val[13] != '-' || val[18] != '-' || val[23] != '-') + return false; - if (!Utils.TryHexToInt(data, dataoffset, 8, out n)) - return false; - byte _f = (byte)(n >> 24); - byte _g = (byte)(n >> 16); - byte _h = (byte)(n >> 8); - byte _i = (byte)n; - dataoffset += 8; + if (Sse42.IsSupported) + { + Vector128 input = Unsafe.As>(ref Unsafe.AsRef(val)); + Vector128 upper = Ssse3.Shuffle(input, Vector128.Create(0, 2, 4, 6, 9, 11, 14, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff)); + Vector128 lower = Ssse3.Shuffle(input, Vector128.Create(1, 3, 5, 7, 10, 12, 15, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff)); + input = Unsafe.As>(ref Unsafe.AddByteOffset(ref Unsafe.AsRef(val), 16 + 3)); + Vector128 upperhalf = Ssse3.Shuffle(input, Vector128.Create(0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0, 2, 5, 7, 9, 11, 13, 15)); + Vector128 lowerhalf = Ssse3.Shuffle(input, Vector128.Create(0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 1, 3, 6, 8, 10, 12, 14, 0xff)); + upper = Sse2.Or(upper, upperhalf); + lower = Sse2.Or(lower, lowerhalf); + + upper = Sse41.Insert(upper, Unsafe.As(ref Unsafe.AddByteOffset(ref Unsafe.AsRef(val), 16)), 7); + lower = Sse41.Insert(lower, Unsafe.As(ref Unsafe.AddByteOffset(ref Unsafe.AsRef(val), 17)), 7); + lower = Sse41.Insert(lower, Unsafe.As(ref Unsafe.AddByteOffset(ref Unsafe.AsRef(val), 35)), 15); + + Vector128 charf = Vector128.Create((byte)'f'); + Vector128 tmpcmp = Sse2.Subtract(charf, lower); + int cmp = Sse2.MoveMask(tmpcmp); + if (cmp != 0) + throw new Exception("bad"); + + tmpcmp = Sse2.Subtract(charf, upper); + cmp = Sse2.MoveMask(tmpcmp); + if (cmp != 0) + throw new Exception("bad"); + + Vector128 charTolower = Vector128.Create((byte)0x20); + Vector128 lowerLetters = Sse2.Or(lower, charTolower); + Vector128 upperLetters = Sse2.Or(upper, charTolower); + + Vector128 letterTohex = Vector128.Create((byte)('a' - '0' - 10)); + lowerLetters = Sse2.Subtract(lowerLetters, letterTohex); + upperLetters = Sse2.Subtract(upperLetters, letterTohex); + + Vector128 char9 = Vector128.Create((byte)'9'); + Vector128 above9lower = (Sse2.CompareGreaterThan(lower.AsSByte(), char9.AsSByte())).AsByte(); + + Vector128 ten = Vector128.Create((byte)('0' + 10)); + tmpcmp = Sse2.Subtract(lowerLetters, ten); + tmpcmp = Sse2.And(tmpcmp, above9lower); + cmp = Sse2.MoveMask(tmpcmp); + if (cmp != 0) + throw new Exception("bad"); + Vector128 above9upper = (Sse2.CompareGreaterThan(upper.AsSByte(), char9.AsSByte())).AsByte(); + + tmpcmp = Sse2.Subtract(upperLetters, ten); + tmpcmp = Sse2.And(tmpcmp, above9upper); + cmp = Sse2.MoveMask(tmpcmp); + if (cmp != 0) + throw new Exception("bad"); + + lower = Sse41.BlendVariable(lower, lowerLetters, above9lower); + upper = Sse41.BlendVariable(upper, upperLetters, above9upper); + Vector128 charzero = Vector128.Create((byte)'0'); + lower = Sse2.Subtract(lower, charzero); + cmp = Sse2.MoveMask(lower); + if (cmp != 0) + throw new Exception("bad"); + upper = Sse2.Subtract(upper, charzero); + cmp = Sse2.MoveMask(upper); + if (cmp != 0) + throw new Exception("bad"); + upper = Sse2.ShiftLeftLogical(upper.AsUInt16(), 4).AsByte(); + lower = Sse2.Or(lower, upper); + if (BitConverter.IsLittleEndian) + lower = Ssse3.Shuffle(lower, Vector128.Create((byte)0x03, 0x02, 0x01, 0x00, 0x05, 0x04, 0x07, 0x06, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F)); + Unsafe.As>(ref Unsafe.AsRef(in result)) = lower; + return true; + } - if (!Utils.TryHexToInt(data, dataoffset, 4, out n)) - return false; - byte _j = (byte)(n >> 8); - byte _k = (byte)n; + if (BitConverter.IsLittleEndian) + { + result.bytea3 = Utils.HexToByte(val, 0); + result.bytea2 = Utils.HexToByte(val, 2); + result.bytea1 = Utils.HexToByte(val, 4); + result.bytea0 = Utils.HexToByte(val, 6); - Guid g = new Guid(_a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k); - res = new UUID(g); - return true; + result.byteb1 = Utils.HexToByte(val, 9); + result.byteb0 = Utils.HexToByte(val, 11); + + result.bytec1 = Utils.HexToByte(val, 14); + result.bytec0 = Utils.HexToByte(val, 16); + } + else + { + result.bytea0 = Utils.HexToByte(val, 0); + result.bytea1 = Utils.HexToByte(val, 2); + result.bytea2 = Utils.HexToByte(val, 4); + result.bytea3 = Utils.HexToByte(val, 6); + + result.byteb0 = Utils.HexToByte(val, 9); + result.byteb1 = Utils.HexToByte(val, 11); + + result.bytec0 = Utils.HexToByte(val, 14); + result.bytec1 = Utils.HexToByte(val, 16); + } + + result.d = Utils.HexToByte(val, 19); + result.e = Utils.HexToByte(val, 21); + + + result.f = Utils.HexToByte(val, 24); + result.g = Utils.HexToByte(val, 26); + result.h = Utils.HexToByte(val, 28); + result.i = Utils.HexToByte(val, 30); + result.j = Utils.HexToByte(val, 32); + result.k = Utils.HexToByte(val, 34); + return true; + } + else + { + if (BitConverter.IsLittleEndian) + { + result.bytea3 = Utils.HexToByte(val, 0); + result.bytea2 = Utils.HexToByte(val, 2); + result.bytea1 = Utils.HexToByte(val, 4); + result.bytea0 = Utils.HexToByte(val, 6); + + result.byteb1 = Utils.HexToByte(val, 8); + result.byteb0 = Utils.HexToByte(val, 10); + + result.bytec1 = Utils.HexToByte(val, 12); + result.bytec0 = Utils.HexToByte(val, 14); + } + else + { + result.bytea0 = Utils.HexToByte(val, 0); + result.bytea1 = Utils.HexToByte(val, 2); + result.bytea2 = Utils.HexToByte(val, 4); + result.bytea3 = Utils.HexToByte(val, 6); + + result.byteb0 = Utils.HexToByte(val, 8); + result.byteb1 = Utils.HexToByte(val, 10); + + result.bytec0 = Utils.HexToByte(val, 12); + result.bytec1 = Utils.HexToByte(val, 14); + } + + result.d = Utils.HexToByte(val, 16); + result.e = Utils.HexToByte(val, 18); + + result.f = Utils.HexToByte(val, 20); + result.g = Utils.HexToByte(val, 22); + result.h = Utils.HexToByte(val, 24); + result.i = Utils.HexToByte(val, 26); + result.j = Utils.HexToByte(val, 28); + result.k = Utils.HexToByte(val, 30); + return true; + } + } + } + catch { } + result = new UUID(); + return false; } } } diff --git a/OpenMetaverse.Types/OpenMetaverse.Types.csproj b/OpenMetaverse.Types/OpenMetaverse.Types.csproj index 33162fff..5bf1ce46 100644 --- a/OpenMetaverse.Types/OpenMetaverse.Types.csproj +++ b/OpenMetaverse.Types/OpenMetaverse.Types.csproj @@ -1,16 +1,11 @@  Local - net48 + Library + OpenMetaverse.Types + Core value types for the OpenMetaverse library: UUID, Vector2/3/4, Quaternion, Matrix4, Color4, and related utilities. OpenMetaverse - 1591,1574,0419,0618 True true - - - - - - \ No newline at end of file diff --git a/OpenMetaverse.Types/Quaternion.cs b/OpenMetaverse.Types/Quaternion.cs index 4bb429a4..f75bbec7 100644 --- a/OpenMetaverse.Types/Quaternion.cs +++ b/OpenMetaverse.Types/Quaternion.cs @@ -1,766 +1,1470 @@ -/* - * Copyright (c) 2006-2016, openmetaverse.co - * All rights reserved. - * - * - Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, this - * list of conditions and the following disclaimer. - * - Neither the name of the openmetaverse.co nor the names - * of its contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Runtime.InteropServices; -using System.Globalization; - -namespace OpenMetaverse -{ - [Serializable] - [StructLayout(LayoutKind.Sequential)] - public struct Quaternion : IEquatable - { - /// X value - public float X; - /// Y value - public float Y; - /// Z value - public float Z; - /// W value - public float W; - - #region Constructors - - public Quaternion(float x, float y, float z, float w) - { - X = x; - Y = y; - Z = z; - W = w; - } - - public Quaternion(Vector3 vectorPart, float scalarPart) - { - X = vectorPart.X; - Y = vectorPart.Y; - Z = vectorPart.Z; - W = scalarPart; - } - - /// - /// Build a quaternion from normalized float values - /// - /// X value from -1.0 to 1.0 - /// Y value from -1.0 to 1.0 - /// Z value from -1.0 to 1.0 - public Quaternion(float x, float y, float z) - { - X = x; - Y = y; - Z = z; - - float xyzsum = 1f - (X * X) - (Y * Y) - (Z * Z); - W = (xyzsum > 1e-6f) ? (float)Math.Sqrt(xyzsum) : 0; - } - - /// - /// Constructor, builds a quaternion object from a byte array - /// - /// Byte array containing four four-byte floats - /// Offset in the byte array to start reading at - /// Whether the source data is normalized or - /// not. If this is true 12 bytes will be read, otherwise 16 bytes will - /// be read. - public Quaternion(byte[] byteArray, int pos, bool normalized) - { - X = Y = Z = 0; - W = 1; - FromBytes(byteArray, pos, normalized); - } - - public Quaternion(Quaternion q) - { - X = q.X; - Y = q.Y; - Z = q.Z; - W = q.W; - } - - #endregion Constructors - - #region Public Methods - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public bool ApproxEquals(Quaternion quat) - { - // assume normalized - return Math.Abs(quat.X - X) < 1e-6f && - Math.Abs(quat.Y - Y) < 1e-6f && - Math.Abs(quat.Z - Z) < 1e-6f; - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public bool ApproxEquals(Quaternion quat, float tolerance) - { - // assume normalized - return Math.Abs(quat.X - X) < tolerance && - Math.Abs(quat.Y - Y) < tolerance && - Math.Abs(quat.Z - Z) < tolerance; - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public float Length() - { - return (float)Math.Sqrt((X * X) + (Y * Y) + (Z * Z) + (W * W)); - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public float LengthSquared() - { - return (X * X) + (Y * Y) + (Z * Z) + (W * W); - } - - /// - /// Normalizes the quaternion - /// - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public void Normalize() - { - float mag = LengthSquared(); - if (mag > 1e-6f) - { - float oomag = 1f / (float)Math.Sqrt(mag); - X *= oomag; - Y *= oomag; - Z *= oomag; - W *= oomag; - } - else - { - X = 0f; - Y = 0f; - Z = 0f; - W = 1f; - } - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public void Conjugate() - { - X = -X; - Y = -Y; - Z = -Z; - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public void Invert() - { - float len = LengthSquared(); - if (len > 1e-6f) - { - len = 1.0f / len; - - X = -X * len; - Y = -Y * len; - Z = -Z * len; - W = W * len; - } - else - { - X = 0f; - Y = 0f; - Z = 0f; - W = 1f; - } - } - - /// - /// Builds a quaternion object from a byte array - /// - /// The source byte array - /// Offset in the byte array to start reading at - /// Whether the source data is normalized or - /// not. If this is true 12 bytes will be read, otherwise 16 bytes will - /// be read. - public void FromBytes(byte[] byteArray, int pos, bool normalized) - { - X = Utils.BytesToFloatSafepos(byteArray, pos); - Y = Utils.BytesToFloatSafepos(byteArray, pos + 4); - Z = Utils.BytesToFloatSafepos(byteArray, pos + 8); - if (normalized) - { - float xyzsum = 1f - (X * X) - (Y * Y) - (Z * Z); - W = (xyzsum > 1e-6f) ? (float)Math.Sqrt(xyzsum) : 0f; - } - else - { - W = Utils.BytesToFloatSafepos(byteArray, pos + 12); - } - } - - /// - /// Normalize this quaternion and serialize it to a byte array - /// - /// A 12 byte array containing normalized X, Y, and Z floating - /// point values in order using little endian byte ordering - public byte[] GetBytes() - { - byte[] bytes = new byte[12]; - float norm = LengthSquared(); - if (norm > 1e-6f || W < 0.9999f) - { - if (W < 0f) - norm = -1f / (float)Math.Sqrt(norm); - else - norm = 1f / (float)Math.Sqrt(norm); - Utils.FloatToBytesSafepos(norm * X, bytes, 0); - Utils.FloatToBytesSafepos(norm * Y, bytes, 4); - Utils.FloatToBytesSafepos(norm * Z, bytes, 8); - } - else - { - Utils.FloatToBytesSafepos(0, bytes, 0); - Utils.FloatToBytesSafepos(0, bytes, 4); - Utils.FloatToBytesSafepos(0, bytes, 8); - } - return bytes; - } - - /// - /// Writes the raw bytes for this quaternion to a byte array - /// - /// Destination byte array - /// Position in the destination array to start - /// writing. Must be at least 12 bytes before the end of the array - public void ToBytes(byte[] dest, int pos) - { - float norm = LengthSquared(); - if (norm > 1e-6f || norm < 0.9999f) - { - if (W < 0f) - norm = -1f / (float)Math.Sqrt(norm); - else - norm = 1f / (float)Math.Sqrt(norm); - Utils.FloatToBytesSafepos(norm * X, dest, pos); - Utils.FloatToBytesSafepos(norm * Y, dest, pos + 4); - Utils.FloatToBytesSafepos(norm * Z, dest, pos + 8); - } - else - { - Utils.FloatToBytesSafepos(0, dest, pos); - Utils.FloatToBytesSafepos(0, dest, pos + 4); - Utils.FloatToBytesSafepos(0, dest, pos + 8); - } - } - - /// - /// Convert this quaternion to euler angles - /// - /// X euler angle - /// Y euler angle - /// Z euler angle - public void GetEulerAngles(out float roll, out float pitch, out float yaw) - { - roll = 0f; - pitch = 0f; - yaw = 0f; - - if(W > 0.999999f) - return; - - float tX = X * X; - float tY = Y * Y; - float tZ = Z * Z; - float tW = W * W; - float m = tX + tY + tZ + tW; - if (Math.Abs(m) < 0.0001f) - return; - - float n = 2 * (Y * W + X * Z); - float p = m * m - n * n; - - if (p > 0f) - { - roll = (float)Math.Atan2(2.0f * (X * W - Y * Z), (-tX - tY + tZ + tW)); - pitch = (float)Math.Atan2(n, Math.Sqrt(p)); - yaw = (float)Math.Atan2(2.0f * (Z * W - X * Y), tX - tY - tZ + tW); - } - else if (n > 0f) - { - roll = 0f; - pitch = (float)(Math.PI / 2d); - yaw = (float)Math.Atan2((Z * W + X * Y), 0.5f - tX - tY); - } - else - { - roll = 0f; - pitch = -(float)(Math.PI / 2d); - yaw = (float)Math.Atan2((Z * W + X * Y), 0.5f - tX - tZ); - } - } - - /// - /// Convert this quaternion to an angle around an axis - /// - /// Unit vector describing the axis - /// Angle around the axis, in radians - public void GetAxisAngle(out Vector3 axis, out float angle) - { - Quaternion q = Normalize(this); - float ww = q.W * q.W; - if (ww > 0.9999f) - { - axis = Vector3.UnitX; - angle = 0; - return; - } - if(ww < 0.0001f) - { - if (q.W < 0f) - axis = new Vector3(-q.X, -q.Y, -q.Z); - else - axis = new Vector3(q.X, q.Y, q.Z); - angle = (float)Math.PI; - return; - } - - float sin = (float)Math.Sqrt(1.0f - ww); - float invSin = 1.0f / sin; - if (q.W < 0) - invSin = -invSin; - axis = new Vector3(q.X, q.Y, q.Z) * invSin; - - angle = 2.0f * (float)Math.Acos(q.W); - if (angle > Math.PI) - angle = 2.0f * (float)Math.PI - angle; - } - - #endregion Public Methods - - #region Static Methods - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public static Quaternion Add(Quaternion quaternion1, Quaternion quaternion2) - { - return new Quaternion( - quaternion1.X + quaternion2.X, - quaternion1.Y + quaternion2.Y, - quaternion1.Z + quaternion2.Z, - quaternion1.W + quaternion2.W); - } - - /// - /// Returns the conjugate (spatial inverse) of a quaternion - /// - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public static Quaternion Conjugate(Quaternion quaternion) - { - return new Quaternion( -quaternion.X, -quaternion.Y, -quaternion.Z, quaternion.W); - } - - /// - /// Build a quaternion from an axis and an angle of rotation around - /// that axis - /// - public static Quaternion CreateFromAxisAngle(float axisX, float axisY, float axisZ, float angle) - { - Vector3 axis = new Vector3(axisX, axisY, axisZ); - return CreateFromAxisAngle(axis, angle); - } - - /// - /// Build a quaternion from an axis and an angle of rotation around - /// that axis - /// - /// Axis of rotation - /// Angle of rotation - public static Quaternion CreateFromAxisAngle(Vector3 axis, float angle) - { - axis = Vector3.Normalize(axis); - - angle *= 0.5f; - float c = (float)Math.Cos(angle); - float s = (float)Math.Sin(angle); - - return new Quaternion(axis.X * s, axis.Y * s, axis.Z * s, c); - } - - /// - /// Creates a quaternion from a vector containing roll, pitch, and yaw - /// in radians - /// - /// Vector representation of the euler angles in - /// radians - /// Quaternion representation of the euler angles - public static Quaternion CreateFromEulers(Vector3 eulers) - { - return CreateFromEulers(eulers.X, eulers.Y, eulers.Z); - } - - /// - /// Creates a quaternion from roll, pitch, and yaw euler angles in - /// radians - /// - /// X angle in radians - /// Y angle in radians - /// Z angle in radians - /// Quaternion representation of the euler angles - public static Quaternion CreateFromEulers(float roll, float pitch, float yaw) - { - if (roll > Utils.TWO_PI || pitch > Utils.TWO_PI || yaw > Utils.TWO_PI) - throw new ArgumentException("Euler angles must be in radians"); - - roll *= 0.5f; - double atCos = Math.Cos(roll); - double atSin = Math.Sin(roll); - pitch *= 0.5f; - double leftCos = Math.Cos(pitch); - double leftSin = Math.Sin(pitch); - yaw *= 0.5f; - double upCos = Math.Cos(yaw); - double upSin = Math.Sin(yaw); - - double atLeftCos = atCos * leftCos; - double atLeftSin = atSin * leftSin; - return new Quaternion( - (float)(atSin * leftCos * upCos + atCos * leftSin * upSin), - (float)(atCos * leftSin * upCos - atSin * leftCos * upSin), - (float)(atLeftCos * upSin + atLeftSin * upCos), - (float)(atLeftCos * upCos - atLeftSin * upSin) - ); - } - - public static Quaternion CreateFromRotationMatrix(Matrix4 matrix) - { - float num8 = (matrix.M11 + matrix.M22) + matrix.M33; - if (num8 > 0f) - { - float num = (float)Math.Sqrt((double)(num8 + 1f)); - float w = num * 0.5f; - num = 0.5f / num; - return new Quaternion( - (matrix.M23 - matrix.M32) * num, - (matrix.M31 - matrix.M13) * num, - (matrix.M12 - matrix.M21) * num, - w); - } - if ((matrix.M11 >= matrix.M22) && (matrix.M11 >= matrix.M33)) - { - float num7 = (float)Math.Sqrt((double)(((1f + matrix.M11) - matrix.M22) - matrix.M33)); - float num4 = 0.5f / num7; - return new Quaternion( - 0.5f * num7, - (matrix.M12 + matrix.M21) * num4, - (matrix.M13 + matrix.M31) * num4, - (matrix.M23 - matrix.M32) * num4); - } - if (matrix.M22 > matrix.M33) - { - float num6 = (float)Math.Sqrt((double)(((1f + matrix.M22) - matrix.M11) - matrix.M33)); - float num3 = 0.5f / num6; - return new Quaternion( - (matrix.M21 + matrix.M12) * num3, - 0.5f * num6, - (matrix.M32 + matrix.M23) * num3, - (matrix.M31 - matrix.M13) * num3); - } - float num5 = (float)Math.Sqrt((double)(((1f + matrix.M33) - matrix.M11) - matrix.M22)); - float num2 = 0.5f / num5; - - return new Quaternion( - (matrix.M31 + matrix.M13) * num2, - (matrix.M32 + matrix.M23) * num2, - 0.5f * num5, - (matrix.M12 - matrix.M21) * num2); - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public static Quaternion Divide(Quaternion q1, Quaternion q2) - { - return Quaternion.Inverse(q1) * q2; - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public static float Dot(Quaternion q1, Quaternion q2) - { - return (q1.X * q2.X) + (q1.Y * q2.Y) + (q1.Z * q2.Z) + (q1.W * q2.W); - } - - /// - /// inverse of a quaternion - /// - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public static Quaternion Inverse(Quaternion quaternion) - { - float normsq = quaternion.LengthSquared(); - - if (normsq < 1e-6f) - return Quaternion.Identity; - - float oonorm = -1f / normsq; - return new Quaternion( - quaternion.X * oonorm, - quaternion.Y * oonorm, - quaternion.Z * oonorm, - -quaternion.W * oonorm); - } - - /// - /// Spherical linear interpolation between two quaternions - /// - public static Quaternion Slerp(Quaternion q1, Quaternion q2, float amount) - { - float angle = Dot(q1, q2); - - if (angle < 0f) - { - q1 *= -1f; - angle *= -1f; - } - - float scale; - float invscale; - - if ((angle + 1f) > 0.05f) - { - if ((1f - angle) >= 0.05f) - { - // slerp - float theta = (float)Math.Acos(angle); - float invsintheta = 1f / (float)Math.Sin(theta); - scale = (float)Math.Sin(theta * (1f - amount)) * invsintheta; - invscale = (float)Math.Sin(theta * amount) * invsintheta; - } - else - { - // lerp - scale = 1f - amount; - invscale = amount; - } - } - else - { - q2.X = -q1.Y; - q2.Y = q1.X; - q2.Z = -q1.W; - q2.W = q1.Z; - - scale = (float)Math.Sin(Utils.PI * (0.5f - amount)); - invscale = (float)Math.Sin(Utils.PI * amount); - } - - return new Quaternion( - q1.X * scale + q2.X * invscale, - q1.Y * scale + q2.Y * invscale, - q1.Z * scale + q2.Z * invscale, - q1.W * scale + q2.W * invscale - ); - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public static Quaternion Subtract(Quaternion quaternion1, Quaternion quaternion2) - { - return new Quaternion( - quaternion1.X - quaternion2.X, - quaternion1.Y - quaternion2.Y, - quaternion1.Z - quaternion2.Z, - quaternion1.W - quaternion2.W); - } - - public static Quaternion Multiply(Quaternion a, Quaternion b) - { - return new Quaternion( - a.W * b.X + a.X * b.W + a.Y * b.Z - a.Z * b.Y, - a.W * b.Y + a.Y * b.W + a.Z * b.X - a.X * b.Z, - a.W * b.Z + a.Z * b.W + a.X * b.Y - a.Y * b.X, - a.W * b.W - a.X * b.X - a.Y * b.Y - a.Z * b.Z - ); - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public static Quaternion Multiply(Quaternion quaternion, float scaleFactor) - { - return new Quaternion( - quaternion.X * scaleFactor, - quaternion.Y * scaleFactor, - quaternion.Z * scaleFactor, - quaternion.W * scaleFactor); - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public static Quaternion Negate(Quaternion quaternion) - { - return new Quaternion( - -quaternion.X, - -quaternion.Y, - -quaternion.Z, - -quaternion.W); - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public static Quaternion Normalize(Quaternion q) - { - float mag = q.LengthSquared(); - if (mag > 1e-6f) - { - float oomag = 1f / (float)Math.Sqrt(mag); - return new Quaternion( - q.X * oomag, - q.Y * oomag, - q.Z * oomag, - q.W * oomag); - } - return Quaternion.Identity; - } - - public static Quaternion Parse(string val) - { - char[] splitChar = { ',' }; - string[] split = val.Replace("<", String.Empty).Replace(">", String.Empty).Split(splitChar); - if (split.Length == 3) - { - return new Quaternion( - float.Parse(split[0].Trim(), Utils.EnUsCulture), - float.Parse(split[1].Trim(), Utils.EnUsCulture), - float.Parse(split[2].Trim(), Utils.EnUsCulture)); - } - else - { - return new Quaternion( - float.Parse(split[0].Trim(), Utils.EnUsCulture), - float.Parse(split[1].Trim(), Utils.EnUsCulture), - float.Parse(split[2].Trim(), Utils.EnUsCulture), - float.Parse(split[3].Trim(), Utils.EnUsCulture)); - } - } - - public static bool TryParse(string val, out Quaternion result) - { - try - { - result = Parse(val); - return true; - } - catch (Exception) - { - result = new Quaternion(); - return false; - } - } - - #endregion Static Methods - - #region Overrides - - public override bool Equals(object obj) - { - return (obj is Quaternion) ? this == (Quaternion)obj : false; - } - - public bool Equals(Quaternion other) - { - return W == other.W - && X == other.X - && Y == other.Y - && Z == other.Z; - } - - public override int GetHashCode() - { - int hash = X.GetHashCode(); - hash = Utils.CombineHash(hash, Y.GetHashCode()); - hash = Utils.CombineHash(hash, Z.GetHashCode()); - hash = Utils.CombineHash(hash, W.GetHashCode()); - return hash; - } - - public override string ToString() - { - return String.Format(Utils.EnUsCulture, "<{0}, {1}, {2}, {3}>", X, Y, Z, W); - } - - /// - /// Get a string representation of the quaternion elements with up to three - /// decimal digits and separated by spaces only - /// - /// Raw string representation of the quaternion - public string ToRawString() - { - CultureInfo enUs = new CultureInfo("en-us"); - enUs.NumberFormat.NumberDecimalDigits = 3; - - return String.Format(enUs, "{0} {1} {2} {3}", X, Y, Z, W); - } - - #endregion Overrides - - #region Operators - - public static bool operator ==(Quaternion quaternion1, Quaternion quaternion2) - { - return quaternion1.Equals(quaternion2); - } - - public static bool operator !=(Quaternion quaternion1, Quaternion quaternion2) - { - return !quaternion1.Equals(quaternion2); - } - - public static Quaternion operator +(Quaternion quaternion1, Quaternion quaternion2) - { - return Add(quaternion1, quaternion2); - } - - public static Quaternion operator -(Quaternion quaternion) - { - return Negate(quaternion); - } - - public static Quaternion operator -(Quaternion quaternion1, Quaternion quaternion2) - { - return Subtract(quaternion1, quaternion2); - } - - public static Quaternion operator *(Quaternion a, Quaternion b) - { - return new Quaternion( - a.W * b.X + a.X * b.W + a.Y * b.Z - a.Z * b.Y, - a.W * b.Y + a.Y * b.W + a.Z * b.X - a.X * b.Z, - a.W * b.Z + a.Z * b.W + a.X * b.Y - a.Y * b.X, - a.W * b.W - a.X * b.X - a.Y * b.Y - a.Z * b.Z - ); - } - - public static Quaternion operator *(Quaternion quaternion, float scaleFactor) - { - return new Quaternion( - quaternion.X * scaleFactor, - quaternion.Y * scaleFactor, - quaternion.Z * scaleFactor, - quaternion.W * scaleFactor); - } - - public static Quaternion operator /(Quaternion quaternion1, Quaternion quaternion2) - { - return Divide(quaternion1, quaternion2); - } - - #endregion Operators - - /// A quaternion with a value of 0,0,0,1 - public readonly static Quaternion Identity = new Quaternion(0f, 0f, 0f, 1f); - } -} +/* + * Copyright (c) 2006-2016, openmetaverse.co + * All rights reserved. + * + * - Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * - Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * - Neither the name of the openmetaverse.co nor the names + * of its contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Globalization; +using System.Text; +using System.Runtime.Intrinsics.X86; +using System.Runtime.Intrinsics; + +namespace OpenMetaverse +{ + [Serializable] + [StructLayout(LayoutKind.Sequential)] + public struct Quaternion : IEquatable + { + /// X value + public float X; + /// Y value + public float Y; + /// Z value + public float Z; + /// W value + public float W; + + public enum MainAxis : int + { + X = 0, + Y = 1, + Z = 2 + } + + #region Constructors + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Quaternion(float x, float y, float z, float w) + { + X = x; + Y = y; + Z = z; + W = w; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Quaternion(Vector3 vectorPart, float scalarPart) + { + X = vectorPart.X; + Y = vectorPart.Y; + Z = vectorPart.Z; + W = scalarPart; + } + + /// + /// Build a quaternion from normalized float values + /// + /// X value from -1.0 to 1.0 + /// Y value from -1.0 to 1.0 + /// Z value from -1.0 to 1.0 + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Quaternion(float x, float y, float z) + { + X = x; + Y = y; + Z = z; + + float xyzsum = 1f - (X * X) - (Y * Y) - (Z * Z); + W = (xyzsum > 1e-6f) ? MathF.Sqrt(xyzsum) : 0; + } + + /// + /// Constructor, builds a quaternion object from a byte array + /// + /// Byte array containing four four-byte floats + /// Offset in the byte array to start reading at + /// Whether the source data is normalized or + /// not. If this is true 12 bytes will be read, otherwise 16 bytes will + /// be read. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Quaternion(byte[] byteArray, int pos, bool normalized) + { + Unsafe.SkipInit(out this); + FromBytes(byteArray, pos, normalized); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Quaternion(Quaternion q) + { + this = q; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Quaternion(ref readonly Quaternion q) + { + this = q; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Quaternion(Vector128 q) + { + Unsafe.SkipInit(out this); + Unsafe.As>(ref this) = q; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Quaternion(ref readonly Vector128 q) + { + Unsafe.SkipInit(out this); + Unsafe.As>(ref this) = q; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Quaternion(MainAxis BaseAxis, float angle) + { + switch (BaseAxis) + { + case MainAxis.X: + W = MathF.Cos(0.5f * angle); + X = MathF.Sqrt(1.0f - W * W); + Y = 0; + Z = 0; + break; + case MainAxis.Y: + W = MathF.Cos(0.5f * angle); + Y = MathF.Sqrt(1.0f - W * W); + X = 0; + Z = 0; + break; + case MainAxis.Z: + W = MathF.Cos(0.5f * angle); + Z = MathF.Sqrt(1.0f - W * W); + X = 0; + Y = 0; + break; + default: //error + X = 0; + Y = 0; + Z = 0; + W = 1; + break; + } + } + + #endregion Constructors + + #region Public Methods + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly bool ApproxEquals(Quaternion quat) + { + // assume normalized + return MathF.Abs(quat.W - W) < 1e-6f && + MathF.Abs(quat.Z - Z) < 1e-6f && + MathF.Abs(quat.X - X) < 1e-6f; + } + /* not faster + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly bool ApproxEquals2(in Quaternion quat) + { + if (Sse.IsSupported) + { + Vector128 tol = Vector128.Create(1e-6f); + + Vector128 a = Unsafe.As>(ref Unsafe.AsRef(this)); + Vector128 c = Sse.CompareEqual(tol, tol); + + Vector128 b = Unsafe.As>(ref Unsafe.AsRef(quat)); + c = Sse2.ShiftRightLogical(c.AsInt32(), 1).AsSingle(); + + a = Sse.Subtract(a, b); + a = Sse.And(a, c); + a = Sse.CompareLessThan(a, tol); + int res = Sse.MoveMask(a); + return res == 0x0f; + } + // assume normalized + return MathF.Abs(quat.X - X) < 1e-6f && + MathF.Abs(quat.Y - Y) < 1e-6f && + MathF.Abs(quat.Z - Z) < 1e-6f; + } + */ + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly bool ApproxEquals(Quaternion quat, float tolerance) + { + // assume normalized + return MathF.Abs(quat.W - W) < tolerance && + MathF.Abs(quat.Z - Z) < tolerance && + MathF.Abs(quat.X - X) < tolerance; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly bool IsIdentity() + { + // assume normalized + return MathF.Abs(W) > (1.0f - 1e-6f); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly bool IsIdentityOrZero() + { + // assume normalized + if (X != 0) + return false; + if (Y != 0) + return false; + if (Z != 0) + return false; + return true; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe float Length() + { + if (Sse41.IsSupported) + { + Vector128 q = Vector128.LoadUnsafe(ref X); + q = Sse41.DotProduct(q, q, 0xf1); + return MathF.Sqrt(q.ToScalar()); + } + else + return MathF.Sqrt((X * X) + (Y * Y) + (Z * Z) + (W * W)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe readonly float LengthSquared() + { + if (Sse41.IsSupported) + { + Vector128 q = Vector128.LoadUnsafe(in X); + q = Sse41.DotProduct(q, q, 0xf1); + return q.ToScalar(); + } + else + return (X * X) + (Y * Y) + (Z * Z) + (W * W); + } + + /// + /// Normalizes the quaternion + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe void Normalize() + { + if (Sse41.IsSupported) + { + Vector128 q = Vector128.LoadUnsafe(ref X); + Vector128 d = Sse41.DotProduct(q, q, 0xff); + float m = d.ToScalar(); + if (m > 1e-6f) + { + d = Sse.Sqrt(d); + q = Sse.Divide(q, d); + Unsafe.As>(ref this) = q; + return; + } + q = Vector128.Create(0f, 0f, 0f, 1f); + Unsafe.As>(ref this) = q; + return; + } + + float mag = LengthSquared(); + if (mag > 1e-6f) + { + float oomag = 1f / MathF.Sqrt(mag); + X *= oomag; + Y *= oomag; + Z *= oomag; + W *= oomag; + } + else + { + X = 0f; + Y = 0f; + Z = 0f; + W = 1f; + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Conjugate() + { + X = -X; + Y = -Y; + Z = -Z; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Invert() + { + float len = LengthSquared(); + if (len > 1e-6f) + { + len = -1.0f / len; + X *= len; + Y *= len; + Z *= len; + W *= -len; + } + else + { + X = 0f; + Y = 0f; + Z = 0f; + W = 1f; + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly float Dot(ref readonly Quaternion q2) + { + if (Sse41.IsSupported) + { + Vector128 q = Vector128.LoadUnsafe(in X); + Vector128 d = Vector128.LoadUnsafe(in q2.X); + return Sse41.DotProduct(q, d, 0xf1).ToScalar(); + } + return (X * q2.X) + (Y * q2.Y) + (Z * q2.Z) + (W * q2.W); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Add(ref readonly Quaternion q2) + { + if (Sse41.IsSupported) + { + Vector128 q = Vector128.LoadUnsafe(in X); + Vector128 d = Vector128.LoadUnsafe(in q2.X); + d = Sse.Add(q, d); + Unsafe.As>(ref this) = d; + } + else + { + X += q2.X; + Y += q2.Y; + Z += q2.Z; + W += q2.W; + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Sub(ref readonly Quaternion quaternion2) + { + if (Sse41.IsSupported) + { + Vector128 q = Vector128.LoadUnsafe(in X); + Vector128 d = Vector128.LoadUnsafe(in quaternion2.X); + d = Sse.Subtract(q, d); + Unsafe.As>(ref this) = d; + } + else + { + X -= quaternion2.X; + Y -= quaternion2.Y; + Z -= quaternion2.Z; + W -= quaternion2.W; + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly Quaternion Multiply(ref readonly Quaternion b) + { + //if (MathF.Abs(W) > (1.0f - 1e-6f)) + // return b; + + return new Quaternion( + W * b.X + X * b.W + Y * b.Z - Z * b.Y, + W * b.Y + Y * b.W + Z * b.X - X * b.Z, + W * b.Z + Z * b.W + X * b.Y - Y * b.X, + W * b.W - X * b.X - Y * b.Y - Z * b.Z + ); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void MultiplySelf(ref readonly Quaternion b) + { + if (MathF.Abs(W) > (1.0f - 1e-6f)) + + { + X = b.X; + Y = b.Y; + Z = b.Z; + W = b.W; + return; + } + float x = W * b.X + X * b.W + Y * b.Z - Z * b.Y; + float y = W * b.Y + Y * b.W + Z * b.X - X * b.Z; + float z = W * b.Z + Z * b.W + X * b.Y - Y * b.X; + W = W * b.W - X * b.X - Y * b.Y - Z * b.Z; + X = x; + Y = y; + Z = z; + } + + /// + /// Builds a quaternion object from a byte array + /// + /// The source byte array + /// Offset in the byte array to start reading at + /// Whether the source data is normalized or + /// not. If this is true 12 bytes will be read, otherwise 16 bytes will + /// be read. + public void FromBytes(byte[] byteArray, int pos, bool normalized) + { + X = Utils.BytesToFloatSafepos(byteArray, pos); + Y = Utils.BytesToFloatSafepos(byteArray, pos + 4); + Z = Utils.BytesToFloatSafepos(byteArray, pos + 8); + if (normalized) + { + float xyzsum = 1f - (X * X) - (Y * Y) - (Z * Z); + W = (xyzsum > 1e-6f) ? MathF.Sqrt(xyzsum) : 0f; + } + else + { + W = Utils.BytesToFloatSafepos(byteArray, pos + 12); + } + } + + /// + /// Normalize this quaternion and serialize it to a byte array + /// + /// A 12 byte array containing normalized X, Y, and Z floating + /// point values in order using little endian byte ordering + public readonly byte[] GetBytes() + { + byte[] bytes = new byte[12]; + float norm = LengthSquared(); + if (norm > 1e-6f || W < 0.9999f) + { + if (W < 0f) + norm = -1f / MathF.Sqrt(norm); + else + norm = 1f / MathF.Sqrt(norm); + Utils.FloatToBytesSafepos(norm * X, bytes, 0); + Utils.FloatToBytesSafepos(norm * Y, bytes, 4); + Utils.FloatToBytesSafepos(norm * Z, bytes, 8); + } + else + { + Utils.FloatToBytesSafepos(0, bytes, 0); + Utils.FloatToBytesSafepos(0, bytes, 4); + Utils.FloatToBytesSafepos(0, bytes, 8); + } + return bytes; + } + + /// + /// Writes the raw bytes for this quaternion to a byte array + /// + /// Destination byte array + /// Position in the destination array to start + /// writing. Must be at least 12 bytes before the end of the array + public readonly unsafe void ToBytes(byte[] dest, int pos) + { + float norm = LengthSquared(); + if (norm > 1e-6f || norm < 0.9999f) + { + if (W < 0f) + norm = -1f / MathF.Sqrt(norm); + else + norm = 1f / MathF.Sqrt(norm); + if (Utils.CanDirectCopyLE) + { + fixed (byte* d = &dest[0]) + { + *(float*)(d + pos) = norm * X; + *(float*)(d + pos + 4) = norm * Y; + *(float*)(d + pos + 8) = norm * Z; + } + } + else + { + Utils.FloatToBytesSafepos(norm * X, dest, pos); + Utils.FloatToBytesSafepos(norm * Y, dest, pos + 4); + Utils.FloatToBytesSafepos(norm * Z, dest, pos + 8); + } + } + else + { + if (Utils.CanDirectCopyLE) + { + fixed (byte* d = &dest[0]) + { + *(long*)(d + pos) = 0; + *(int*)(d + pos + 8) = 0; + } + } + else + { + Utils.FloatToBytesSafepos(0, dest, pos); + Utils.FloatToBytesSafepos(0, dest, pos + 4); + Utils.FloatToBytesSafepos(0, dest, pos + 8); + } + } + } + + public readonly unsafe void ToBytes(byte* dest) + { + float norm = LengthSquared(); + if (norm > 1e-6f || norm < 0.9999f) + { + if (W < 0f) + norm = -1f / MathF.Sqrt(norm); + else + norm = 1f / MathF.Sqrt(norm); + if (Utils.CanDirectCopyLE) + { + *(float*)(dest) = norm * X; + *(float*)(dest + 4) = norm * Y; + *(float*)(dest + 8) = norm * Z; + } + else + { + Utils.FloatToBytes(norm * X, dest); + Utils.FloatToBytes(norm * Y, dest + 4); + Utils.FloatToBytes(norm * Z, dest + 8); + } + } + else + { + if (Utils.CanDirectCopyLE) + { + *(long*)dest = 0; + *(int*)(dest + 8) = 0; + } + else + { + Utils.FloatToBytes(0, dest); + Utils.FloatToBytes(0, dest + 4); + Utils.FloatToBytes(0, dest + 8); + } + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly unsafe void ToShortsBytes(byte[] dest, int pos) + { + ushort sx = Utils.FloatToUnitUInt16(X); + ushort sy = Utils.FloatToUnitUInt16(Y); + ushort sz = Utils.FloatToUnitUInt16(Z); + ushort sw = Utils.FloatToUnitUInt16(W); + + if (Utils.CanDirectCopyLE) + { + fixed (byte* d = &dest[0]) + { + *(ushort*)(d + pos) = sx; + *(ushort*)(d + pos + 2) = sy; + *(ushort*)(d + pos + 4) = sz; + *(ushort*)(d + pos + 6) = sw; + } + } + else + { + Utils.UInt16ToBytes(sx, dest, pos); + Utils.UInt16ToBytes(sy, dest, pos + 2); + Utils.UInt16ToBytes(sz, dest, pos + 4); + Utils.UInt16ToBytes(sw, dest, pos + 6); + } + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly unsafe void ToShortsBytes(byte* dest, int pos) + { + ushort sx = Utils.FloatToUnitUInt16(X); + ushort sy = Utils.FloatToUnitUInt16(Y); + ushort sz = Utils.FloatToUnitUInt16(Z); + ushort sw = Utils.FloatToUnitUInt16(W); + + if (Utils.CanDirectCopyLE) + { + *(ushort*)(dest + pos) = sx; + *(ushort*)(dest + pos + 2) = sy; + *(ushort*)(dest + pos + 4) = sz; + *(ushort*)(dest + pos + 6) = sw; + } + else + { + Utils.UInt16ToBytes(sx, dest, pos); + Utils.UInt16ToBytes(sy, dest, pos + 2); + Utils.UInt16ToBytes(sz, dest, pos + 4); + Utils.UInt16ToBytes(sw, dest, pos + 6); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly unsafe void ToShortsBytes(byte* dest) + { + ushort sx = Utils.FloatToUnitUInt16(X); + ushort sy = Utils.FloatToUnitUInt16(Y); + ushort sz = Utils.FloatToUnitUInt16(Z); + ushort sw = Utils.FloatToUnitUInt16(W); + + if (Utils.CanDirectCopyLE) + { + *(ushort*)(dest) = sx; + *(ushort*)(dest + 2) = sy; + *(ushort*)(dest + 4) = sz; + *(ushort*)(dest + 6) = sw; + } + else + { + Utils.UInt16ToBytes(sx, dest); + Utils.UInt16ToBytes(sy, dest + 2); + Utils.UInt16ToBytes(sz, dest + 4); + Utils.UInt16ToBytes(sw, dest + 6); + } + } + + /// + /// Convert this quaternion to euler angles + /// + /// X euler angle + /// Y euler angle + /// Z euler angle + public readonly void GetEulerAngles(out float roll, out float pitch, out float yaw) + { + const float halfpi = MathF.PI / 2f; + + roll = 0f; + pitch = 0f; + yaw = 0f; + + if(W > 0.999999f) + return; + + float tX = X * X; + float tY = Y * Y; + float tZ = Z * Z; + float tW = W * W; + float m = tX + tY + tZ + tW; + if (MathF.Abs(m) < 0.0001f) + return; + + float n = 2 * (Y * W + X * Z); + float p = m * m - n * n; + + if (p > 0f) + { + roll = MathF.Atan2(2.0f * (X * W - Y * Z), (-tX - tY + tZ + tW)); + pitch = MathF.Atan2(n, MathF.Sqrt(p)); + yaw = MathF.Atan2(2.0f * (Z * W - X * Y), tX - tY - tZ + tW); + } + else if (n > 0f) + { + roll = 0f; + pitch = halfpi; + yaw = (float)Math.Atan2((Z * W + X * Y), 0.5f - tX - tY); + } + else + { + roll = 0f; + pitch = -halfpi; + yaw = MathF.Atan2((Z * W + X * Y), 0.5f - tX - tZ); + } + } + + /// + /// Convert this quaternion to an angle around an axis + /// + /// Unit vector describing the axis + /// Angle around the axis, in radians + public readonly void GetAxisAngle(out Vector3 axis, out float angle) + { + //Normalize(); + float ww = W * W; + if (ww > 0.9999f) + { + axis = Vector3.UnitX; + angle = 0; + return; + } + if(ww < 0.0001f) + { + if (W < 0f) + axis = new Vector3(-X, -Y, -Z); + else + axis = new Vector3(X, Y, Z); + angle = MathF.PI; + return; + } + + float sin = MathF.Sqrt(1.0f - ww); + float invSin = 1.0f / sin; + if (W < 0) + invSin = -invSin; + axis = new Vector3(X, Y, Z) * invSin; + + angle = 2.0f * MathF.Acos(W); + if (angle > MathF.PI) + angle = 2.0f * MathF.PI - angle; + } + + #endregion Public Methods + + #region Static Methods + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Quaternion Add(ref readonly Quaternion quaternion1, ref readonly Quaternion quaternion2) + { + if (Sse.IsSupported) + { + Vector128 a = Vector128.LoadUnsafe(in quaternion1.X); + Vector128 b = Vector128.LoadUnsafe(in quaternion2.X); + a = Sse.Add(a, b); + return new Quaternion(ref a); + } + + return new Quaternion( + quaternion1.X + quaternion2.X, + quaternion1.Y + quaternion2.Y, + quaternion1.Z + quaternion2.Z, + quaternion1.W + quaternion2.W); + } + + /// + /// Returns the conjugate (spatial inverse) of a quaternion + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Quaternion Conjugate(ref readonly Quaternion quaternion) + { + if (Sse.IsSupported) + { + Vector128 d = Unsafe.As>(ref Unsafe.AsRef(in quaternion)); + Vector128 Mask = Vector128.Create(0x80000000, 0x80000000, 0x80000000, 0).AsSingle(); + d = Sse.Xor(d, Mask); + return new Quaternion(ref d); + } + return new Quaternion(-quaternion.X, -quaternion.Y, -quaternion.Z, quaternion.W); + } + + /// + /// Build a quaternion from an axis and an angle of rotation around + /// that axis + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Quaternion CreateFromAxisAngle(float axisX, float axisY, float axisZ, float angle) + { + Vector3 axis = new(axisX, axisY, axisZ); + return CreateFromAxisAngle(axis, angle); + } + + /// + /// Build a quaternion from an axis and an angle of rotation around + /// that axis + /// + /// Axis of rotation + /// Angle of rotation + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Quaternion CreateFromAxisAngle(Vector3 axis, float angle) + { + angle *= 0.5f; + float s = MathF.Sin(angle); + + axis.Normalize(); + axis *= s; + + float c = MathF.Cos(angle); + return new Quaternion(axis.X, axis.Y, axis.Z, c); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Quaternion CreateRotationX(float angle) + { + angle *= 0.5f; + float c = MathF.Cos(angle); + float s = MathF.Sin(angle); + + return new Quaternion(s, 0, 0, c); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Quaternion CreateRotationY(float angle) + { + angle *= 0.5f; + float c = MathF.Cos(angle); + float s = MathF.Sin(angle); + + return new Quaternion(0, s, 0, c); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Quaternion CreateRotationZ(float angle) + { + angle *= 0.5f; + float c = MathF.Cos(angle); + float s = MathF.Sin(angle); + + return new Quaternion(0, 0, s, c); + } + + /// + /// Creates a quaternion from a vector containing roll, pitch, and yaw + /// in radians + /// + /// Vector representation of the euler angles in + /// radians + /// Quaternion representation of the euler angles + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Quaternion CreateFromEulers(Vector3 eulers) + { + return CreateFromEulers(eulers.X, eulers.Y, eulers.Z); + } + + /// + /// Creates a quaternion from roll, pitch, and yaw euler angles in + /// radians + /// + /// X angle in radians + /// Y angle in radians + /// Z angle in radians + /// Quaternion representation of the euler angles + public static Quaternion CreateFromEulers(float roll, float pitch, float yaw) + { + if (roll > Utils.TWO_PI || pitch > Utils.TWO_PI || yaw > Utils.TWO_PI) + throw new ArgumentException("Euler angles must be in radians"); + + roll *= 0.5f; + float atCos = MathF.Cos(roll); + float atSin = MathF.Sin(roll); + pitch *= 0.5f; + float leftCos = MathF.Cos(pitch); + float leftSin = MathF.Sin(pitch); + yaw *= 0.5f; + float upCos = MathF.Cos(yaw); + float upSin = MathF.Sin(yaw); + + float atLeftCos = atCos * leftCos; + float atLeftSin = atSin * leftSin; + return new Quaternion( + atSin * leftCos * upCos + atCos * leftSin * upSin, + atCos * leftSin * upCos - atSin * leftCos * upSin, + atLeftCos * upSin + atLeftSin * upCos, + atLeftCos * upCos - atLeftSin * upSin + ); + } + + public static Quaternion CreateFromRotationMatrix(Matrix3x3 matrix) + { + float num = matrix.M11 + matrix.M22 + matrix.M33; + float n2; + if (num >= 0f) + { + num = MathF.Sqrt((num + 1f)); + n2 = 0.5f / num; + return new Quaternion( + (matrix.M23 - matrix.M32) * n2, + (matrix.M31 - matrix.M13) * n2, + (matrix.M12 - matrix.M21) * n2, + num * 0.5f); + } + if ((matrix.M11 >= matrix.M22) && (matrix.M11 >= matrix.M33)) + { + num = MathF.Sqrt(1f + matrix.M11 - matrix.M22 - matrix.M33); + n2 = 0.5f / num; + return new Quaternion( + 0.5f * num, + (matrix.M12 + matrix.M21) * n2, + (matrix.M13 + matrix.M31) * n2, + (matrix.M23 - matrix.M32) * n2); + } + if (matrix.M22 > matrix.M33) + { + num = MathF.Sqrt(1f - matrix.M11 + matrix.M22 - matrix.M33); + n2 = 0.5f / num; + return new Quaternion( + (matrix.M21 + matrix.M12) * n2, + 0.5f * num, + (matrix.M32 + matrix.M23) * n2, + (matrix.M31 - matrix.M13) * n2); + } + + num = MathF.Sqrt(1f - matrix.M11 - matrix.M22 + matrix.M33 ); + n2 = 0.5f / num; + return new Quaternion( + (matrix.M31 + matrix.M13) * n2, + (matrix.M32 + matrix.M23) * n2, + 0.5f * num, + (matrix.M12 - matrix.M21) * n2); + } + + public static Quaternion CreateFromRotationMatrix(Matrix4 matrix) + { + float num = matrix.M11 + matrix.M22 + matrix.M33; + float n2; + if (num >= 0f) + { + num = MathF.Sqrt(1f + num); + n2 = 0.5f / num; + return new Quaternion( + (matrix.M23 - matrix.M32) * n2, + (matrix.M31 - matrix.M13) * n2, + (matrix.M12 - matrix.M21) * n2, + num * 0.5f); + } + if ((matrix.M11 >= matrix.M22) && (matrix.M11 >= matrix.M33)) + { + num = MathF.Sqrt(1f + matrix.M11 - matrix.M22 - matrix.M33); + n2 = 0.5f / num; + return new Quaternion( + 0.5f * num, + (matrix.M12 + matrix.M21) * n2, + (matrix.M13 + matrix.M31) * n2, + (matrix.M23 - matrix.M32) * n2); + } + if (matrix.M22 > matrix.M33) + { + num = MathF.Sqrt(1f - matrix.M11 + matrix.M22 - matrix.M33); + n2 = 0.5f / num; + return new Quaternion( + (matrix.M21 + matrix.M12) * n2, + 0.5f * num, + (matrix.M32 + matrix.M23) * n2, + (matrix.M31 - matrix.M13) * n2); + } + + num = MathF.Sqrt(1f - matrix.M11 - matrix.M22 + matrix.M33); + n2 = 0.5f / num; + return new Quaternion( + (matrix.M31 + matrix.M13) * n2, + (matrix.M32 + matrix.M23) * n2, + 0.5f * num, + (matrix.M12 - matrix.M21) * n2); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Quaternion Divide(Quaternion q1, Quaternion q2) + { + return Inverse(q1) * q2; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static float Dot(Quaternion q1, Quaternion q2) + { + if (Sse41.IsSupported) + { + Vector128 q = Unsafe.As>(ref q1); + Vector128 d = Unsafe.As>(ref q2); + d = Sse41.DotProduct(q, d, 0xf1); + return d.ToScalar(); + } + return (q1.X * q2.X) + (q1.Y * q2.Y) + (q1.Z * q2.Z) + (q1.W * q2.W); + } + + /// + /// inverse of a quaternion + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Quaternion Inverse(Quaternion quaternion) + { + float normsq = quaternion.LengthSquared(); + if (normsq < 1e-6f) + return Identity; + + float oonorm = -1f / normsq; + return new Quaternion( + quaternion.X * oonorm, + quaternion.Y * oonorm, + quaternion.Z * oonorm, + -quaternion.W * oonorm); + } + + /// + /// Spherical linear interpolation between two quaternions + /// + public static Quaternion Slerp(Quaternion q1, in Quaternion q2, float amount) + { + float angle = Dot(q1, q2); + + if (angle < 0f) + { + q1 *= -1f; + angle *= -1f; + } + + float scale; + float invscale; + + if ((angle + 1f) > 0.05f) + { + if ((1f - angle) >= 0.05f) + { + // slerp + float theta = MathF.Acos(angle); + float invsintheta = 1f / MathF.Sin(theta); + scale = MathF.Sin(theta * (1f - amount)) * invsintheta; + invscale = MathF.Sin(theta * amount) * invsintheta; + } + else + { + // lerp + scale = 1f - amount; + invscale = amount; + } + } + else + { + scale = MathF.Sin(Utils.PI * (0.5f - amount)); + invscale = MathF.Sin(Utils.PI * amount); + return new Quaternion( + q1.X * scale - q1.Y * invscale, + q1.Y * scale + q1.X * invscale, + q1.Z * scale - q1.W * invscale, + q1.W * scale + q1.Z * invscale + ); + } + + return new Quaternion( + q1.X * scale + q2.X * invscale, + q1.Y * scale + q2.Y * invscale, + q1.Z * scale + q2.Z * invscale, + q1.W * scale + q2.W * invscale + ); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Quaternion Subtract(Quaternion quaternion1, Quaternion quaternion2) + { + return new Quaternion( + quaternion1.X - quaternion2.X, + quaternion1.Y - quaternion2.Y, + quaternion1.Z - quaternion2.Z, + quaternion1.W - quaternion2.W); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Quaternion Multiply(ref readonly Quaternion a, ref readonly Quaternion b) + { + return new Quaternion( + a.W * b.X + a.X * b.W + a.Y * b.Z - a.Z * b.Y, + a.W * b.Y + a.Y * b.W + a.Z * b.X - a.X * b.Z, + a.W * b.Z + a.Z * b.W + a.X * b.Y - a.Y * b.X, + a.W * b.W - a.X * b.X - a.Y * b.Y - a.Z * b.Z + ); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Quaternion Multiply(ref readonly Quaternion quaternion, float scaleFactor) + { + return new Quaternion( + quaternion.X * scaleFactor, + quaternion.Y * scaleFactor, + quaternion.Z * scaleFactor, + quaternion.W * scaleFactor); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Quaternion Negate(Quaternion quaternion) + { + return new Quaternion( + -quaternion.X, + -quaternion.Y, + -quaternion.Z, + -quaternion.W); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Quaternion Normalize(ref readonly Quaternion q) + { + if(Sse41.IsSupported) + { + Vector128 t = Vector128.LoadUnsafe(in q.X); + Vector128 d = Sse41.DotProduct(t, t, 0xff); + float m = d.ToScalar(); + if (m > 1e-6f) + { + t = Sse.Divide(t, Sse.Sqrt(d)); + return new(ref t); + } + return Identity; + } + + float mag = q.LengthSquared(); + if (mag > 1e-6f) + { + float oomag = 1f / MathF.Sqrt(mag); + return new Quaternion( + q.X * oomag, + q.Y * oomag, + q.Z * oomag, + q.W * oomag); + } + return Identity; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + + public unsafe static Quaternion Parse(string val) + { + return Parse(val.AsSpan()); + } + + public static Quaternion Parse(ReadOnlySpan sp) + { + if (sp.Length < 7) + throw new FormatException("Invalid Quaternion"); + + int start = 0; + int comma = 0; + char c; + do + { + c = Unsafe.Add(ref MemoryMarshal.GetReference(sp), comma); + if (c == ',' || c == '<') + break; + } + while (++comma < sp.Length); + + if (c == '<') + { + start = ++comma; + while (++comma < sp.Length) + { + if (Unsafe.Add(ref MemoryMarshal.GetReference(sp), comma) == ',') + break; + } + } + if (comma > sp.Length - 5) + throw new FormatException("Invalid Quaternion"); + + if (!float.TryParse(sp[start..comma], NumberStyles.Float, Utils.EnUsCulture, out float x)) + throw new FormatException("Invalid Quaternion"); + + start = ++comma; + while (++comma < sp.Length) + { + if (Unsafe.Add(ref MemoryMarshal.GetReference(sp), comma) == ',') + break; + } + if (comma > sp.Length - 3) + throw new FormatException("Invalid Quaternion"); + if (!float.TryParse(sp[start..comma], NumberStyles.Float, Utils.EnUsCulture, out float y)) + throw new FormatException("Invalid Quaternion"); + + start = ++comma; + while (++comma < sp.Length) + { + c = Unsafe.Add(ref MemoryMarshal.GetReference(sp), comma); + if (c == ',' || c == '>') + break; + } + if (comma >= sp.Length) + throw new FormatException("Invalid Quaternion"); + + if (!float.TryParse(sp[start..comma], NumberStyles.Float, Utils.EnUsCulture, out float z)) + throw new FormatException("Invalid Quaternion"); + + if (c == '>') + return new Quaternion(x, y, z); + + start = ++comma; + while (++comma < sp.Length) + { + c = Unsafe.Add(ref MemoryMarshal.GetReference(sp), comma); + if (c == ' ' || c == '>') + break; + } + + if (!float.TryParse(sp[start..comma], NumberStyles.Float, Utils.EnUsCulture, out float w)) + throw new FormatException("Invalid Quaternion"); + + return new Quaternion(x, y, z, w); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static bool TryParse(string val, out Quaternion result) + { + return TryParse(val.AsSpan(), out result); + } + + public static bool TryParse(ReadOnlySpan sp, out Quaternion result) + { + if (sp.Length < 7) + { + result = Identity; + return false; + } + + int start = 0; + int comma = 0; + char c; + + do + { + c = Unsafe.Add(ref MemoryMarshal.GetReference(sp), comma); + if (c == ',' || c == '<') + break; + } + while (++comma < sp.Length); + + if (c == '<') + { + start = ++comma; + while (++comma < sp.Length) + { + if (Unsafe.Add(ref MemoryMarshal.GetReference(sp), comma) == ',') + break; + } + } + if (comma > sp.Length - 5) + { + result = Identity; + return false; + } + + if (!float.TryParse(sp[start..comma], NumberStyles.Float, Utils.EnUsCulture, out float x)) + { + result = Identity; + return false; + } + + start = ++comma; + while (++comma < sp.Length) + { + if (Unsafe.Add(ref MemoryMarshal.GetReference(sp), comma) == ',') + break; + } + if (comma > sp.Length - 3) + { + result = Identity; + return false; + } + if (!float.TryParse(sp[start..comma], NumberStyles.Float, Utils.EnUsCulture, out float y)) + { + result = Identity; + return false; + } + + start = ++comma; + while (++comma < sp.Length) + { + c = Unsafe.Add(ref MemoryMarshal.GetReference(sp), comma); + if (c == '>' || c == ',') + break; + } + if (comma >= sp.Length) + { + result = Identity; + return false; + } + + if (!float.TryParse(sp[start..comma], NumberStyles.Float, Utils.EnUsCulture, out float z)) + { + result = Identity; + return false; + } + + if (c == '>') + { + result = new Quaternion(x, y, z); + return true; + } + + comma++; + start = comma; + while (++comma < sp.Length) + { + c = Unsafe.Add(ref MemoryMarshal.GetReference(sp), comma); + if (c == ' ' || c == '>') + break; + } + + if (!float.TryParse(sp[start..comma], NumberStyles.Float, Utils.EnUsCulture, out float w)) + { + result = Identity; + return false; + } + + result = new Quaternion(x, y, z, w); + return true; + } + + #endregion Static Methods + + #region Overrides + + public readonly override bool Equals(object obj) + { + if(obj is not Quaternion other) + return false; + + if (X != other.X) + return false; + if (Y != other.Y) + return false; + if (Z != other.Z) + return false; + if (W != other.W) + return false; + return true; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly bool Equals(Quaternion other) + { + if (X != other.X) + return false; + if (Y != other.Y) + return false; + if (Z != other.Z) + return false; + if (W != other.W) + return false; + return true; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly bool NotEqual(Quaternion other) + { + if (X != other.X) + return true; + if (Y != other.Y) + return true; + if (Z != other.Z) + return true; + if (W != other.W) + return true; + return false; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly override int GetHashCode() + { + int hash = X.GetHashCode(); + hash = Utils.CombineHash(hash, Y.GetHashCode()); + hash = Utils.CombineHash(hash, Z.GetHashCode()); + hash = Utils.CombineHash(hash, W.GetHashCode()); + return hash; + } + + public readonly override string ToString() + { + StringBuilder sb = new(); + sb.Append('<'); + sb.Append(X.ToString(Utils.EnUsCulture)); + sb.Append(", "); + sb.Append(Y.ToString(Utils.EnUsCulture)); + sb.Append(", "); + sb.Append(Z.ToString(Utils.EnUsCulture)); + sb.Append(", "); + sb.Append(W.ToString(Utils.EnUsCulture)); + sb.Append('>'); + return sb.ToString(); + } + + /// + /// Get a string representation of the quaternion elements with up to three + /// decimal digits and separated by spaces only + /// + /// Raw string representation of the quaternion + public readonly string ToRawString() + { + CultureInfo enUs = new("en-us"); + enUs.NumberFormat.NumberDecimalDigits = 3; + + StringBuilder sb = new(); + sb.Append(X.ToString(enUs)); + sb.Append(' '); + sb.Append(Y.ToString(enUs)); + sb.Append(' '); + sb.Append(Z.ToString(enUs)); + sb.Append(' '); + sb.Append(W.ToString(enUs)); + return sb.ToString(); + } + + #endregion Overrides + + #region Operators + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool operator ==(Quaternion quaternion1, Quaternion quaternion2) + { + if (quaternion1.X != quaternion2.X) + return false; + if (quaternion1.Y != quaternion2.Y) + return false; + if (quaternion1.Z != quaternion2.Z) + return false; + if (quaternion1.W != quaternion2.W) + return false; + return true; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool operator !=(Quaternion quaternion1, Quaternion quaternion2) + { + if (quaternion1.X != quaternion2.X) + return true; + if (quaternion1.Y != quaternion2.Y) + return true; + if (quaternion1.Z != quaternion2.Z) + return true; + if (quaternion1.W != quaternion2.W) + return true; + return false; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Quaternion operator +(Quaternion quaternion1, Quaternion quaternion2) + { + return Add(quaternion1, quaternion2); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Quaternion operator -(Quaternion quaternion) + { + return Negate(quaternion); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Quaternion operator -(Quaternion quaternion1, Quaternion quaternion2) + { + return Subtract(quaternion1, quaternion2); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Quaternion operator *(Quaternion a, Quaternion b) + { + if (MathF.Abs(a.W) > (1.0f - 1e-6f)) return b; + if (MathF.Abs(b.W) > (1.0f - 1e-6f)) return a; + return new Quaternion( + a.W * b.X + a.X * b.W + a.Y * b.Z - a.Z * b.Y, + a.W * b.Y + a.Y * b.W + a.Z * b.X - a.X * b.Z, + a.W * b.Z + a.Z * b.W + a.X * b.Y - a.Y * b.X, + a.W * b.W - a.X * b.X - a.Y * b.Y - a.Z * b.Z + ); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Quaternion operator *(Quaternion quaternion, float scaleFactor) + { + return new Quaternion( + quaternion.X * scaleFactor, + quaternion.Y * scaleFactor, + quaternion.Z * scaleFactor, + quaternion.W * scaleFactor); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Quaternion operator /(Quaternion quaternion1, Quaternion quaternion2) + { + return Divide(quaternion1, quaternion2); + } + + #endregion Operators + + /// A quaternion with a value of 0,0,0,1 + public readonly static Quaternion Identity = new(0f, 0f, 0f, 1f); + } +} diff --git a/OpenMetaverse.Types/UUID.cs b/OpenMetaverse.Types/UUID.cs index 94eb1522..b38bddf6 100644 --- a/OpenMetaverse.Types/UUID.cs +++ b/OpenMetaverse.Types/UUID.cs @@ -1,383 +1,1264 @@ -/* - * Copyright (c) 2006-2016, openmetaverse.co - * All rights reserved. - * - * - Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, this - * list of conditions and the following disclaimer. - * - Neither the name of the openmetaverse.co nor the names - * of its contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -using System; - -namespace OpenMetaverse -{ - /// - /// A 128-bit Universally Unique Identifier, used throughout the Second - /// Life networking protocol - /// - [Serializable] - public struct UUID : IComparable, IEquatable - { - /// The System.Guid object this struct wraps around - public Guid Guid; - - #region Constructors - - /// - /// Constructor that takes a string UUID representation - /// - /// A string representation of a UUID, case - /// insensitive and can either be hyphenated or non-hyphenated - /// UUID("11f8aa9c-b071-4242-836b-13b7abe0d489") - public UUID(string val) - { - if (String.IsNullOrEmpty(val)) - Guid = new Guid(); - else - Guid = new Guid(val); - } - - /// - /// Constructor that takes a System.Guid object - /// - /// A Guid object that contains the unique identifier - /// to be represented by this UUID - public UUID(Guid val) - { - Guid = val; - } - - /// - /// Constructor that takes a byte array containing a UUID - /// - /// Byte array containing a 16 byte UUID - /// Beginning offset in the array - public UUID(byte[] source, int pos) - { - Guid = UUID.Zero.Guid; - FromBytes(source, pos); - } - - /// - /// Constructor that takes an unsigned 64-bit unsigned integer to - /// convert to a UUID - /// - /// 64-bit unsigned integer to convert to a UUID - public UUID(ulong val) - { - byte[] end = BitConverter.GetBytes(val); - if (!BitConverter.IsLittleEndian) - Array.Reverse(end); - - Guid = new Guid(0, 0, 0, end); - } - - /// - /// Copy constructor - /// - /// UUID to copy - public UUID(UUID val) - { - Guid = val.Guid; - } - - #endregion Constructors - - #region Public Methods - - /// - /// IComparable.CompareTo implementation - /// - public int CompareTo(UUID id) - { - return Guid.CompareTo(id.Guid); - } - - /// - /// Assigns this UUID from 16 bytes out of a byte array - /// - /// Byte array containing the UUID to assign this UUID to - /// Starting position of the UUID in the byte array - public void FromBytes(byte[] source, int pos) - { - int a = (source[pos + 0] << 24) | (source[pos + 1] << 16) | (source[pos + 2] << 8) | source[pos + 3]; - short b = (short)((source[pos + 4] << 8) | source[pos + 5]); - short c = (short)((source[pos + 6] << 8) | source[pos + 7]); - - Guid = new Guid(a, b, c, source[pos + 8], source[pos + 9], source[pos + 10], source[pos + 11], - source[pos + 12], source[pos + 13], source[pos + 14], source[pos + 15]); - } - - /// - /// Returns a copy of the raw bytes for this UUID - /// - /// A 16 byte array containing this UUID - public byte[] GetBytes() - { - byte[] output = new byte[16]; - ToBytes(output, 0); - return output; - } - - /// - /// Writes the raw bytes for this UUID to a byte array - /// - /// Destination byte array - /// Position in the destination array to start - /// writing. Must be at least 16 bytes before the end of the array - public void ToBytes(byte[] dest, int pos) - { - byte[] bytes = Guid.ToByteArray(); - dest[pos + 0] = bytes[3]; - dest[pos + 1] = bytes[2]; - dest[pos + 2] = bytes[1]; - dest[pos + 3] = bytes[0]; - dest[pos + 4] = bytes[5]; - dest[pos + 5] = bytes[4]; - dest[pos + 6] = bytes[7]; - dest[pos + 7] = bytes[6]; - Buffer.BlockCopy(bytes, 8, dest, pos + 8, 8); - } - - /// - /// Calculate an LLCRC (cyclic redundancy check) for this UUID - /// - /// The CRC checksum for this UUID - public uint CRC() - { - uint retval = 0; - byte[] bytes = GetBytes(); - - retval += (uint)((bytes[3] << 24) + (bytes[2] << 16) + (bytes[1] << 8) + bytes[0]); - retval += (uint)((bytes[7] << 24) + (bytes[6] << 16) + (bytes[5] << 8) + bytes[4]); - retval += (uint)((bytes[11] << 24) + (bytes[10] << 16) + (bytes[9] << 8) + bytes[8]); - retval += (uint)((bytes[15] << 24) + (bytes[14] << 16) + (bytes[13] << 8) + bytes[12]); - - return retval; - } - - /// - /// Create a 64-bit integer representation from the second half of this UUID - /// - /// An integer created from the last eight bytes of this UUID - public ulong GetULong() - { - byte[] bytes = Guid.ToByteArray(); - - return (ulong) - ((ulong)bytes[8] + - ((ulong)bytes[9] << 8) + - ((ulong)bytes[10] << 16) + - ((ulong)bytes[12] << 24) + - ((ulong)bytes[13] << 32) + - ((ulong)bytes[13] << 40) + - ((ulong)bytes[14] << 48) + - ((ulong)bytes[15] << 56)); - } - - #endregion Public Methods - - #region Static Methods - - /// - /// Generate a UUID from a string - /// - /// A string representation of a UUID, case - /// insensitive and can either be hyphenated or non-hyphenated - /// UUID.Parse("11f8aa9c-b071-4242-836b-13b7abe0d489") - public static UUID Parse(string val) - { - return new UUID(val); - } - - /// - /// Generate a UUID from a string - /// - /// A string representation of a UUID, case - /// insensitive and can either be hyphenated or non-hyphenated - /// Will contain the parsed UUID if successful, - /// otherwise null - /// True if the string was successfully parse, otherwise false - /// UUID.TryParse("11f8aa9c-b071-4242-836b-13b7abe0d489", result) - public static bool TryParse(string val, out UUID result) - { - if (String.IsNullOrEmpty(val)) - { - result = UUID.Zero; - return false; - } - - Guid gg; - try - { - if (Guid.TryParse(val, out gg)) - { - result = new UUID(gg); - return true; - } - } - catch { } - - result = UUID.Zero; - return false; - } - - /// - /// Combine two UUIDs together by taking the MD5 hash of a byte array - /// containing both UUIDs - /// - /// First UUID to combine - /// Second UUID to combine - /// The UUID product of the combination - public static UUID Combine(UUID first, UUID second) - { - // Construct the buffer that MD5ed - byte[] input = new byte[32]; - Buffer.BlockCopy(first.GetBytes(), 0, input, 0, 16); - Buffer.BlockCopy(second.GetBytes(), 0, input, 16, 16); - - return new UUID(Utils.MD5(input), 0); - } - - /// - /// - /// - /// - public static UUID Random() - { - return new UUID(Guid.NewGuid()); - } - - #endregion Static Methods - - #region Overrides - - /// - /// Return a hash code for this UUID, used by .NET for hash tables - /// - /// An integer composed of all the UUID bytes XORed together - public override int GetHashCode() - { - return Guid.GetHashCode(); - } - - /// - /// Comparison function - /// - /// An object to compare to this UUID - /// True if the object is a UUID and both UUIDs are equal - public override bool Equals(object o) - { - if (!(o is UUID)) return false; - - UUID uuid = (UUID)o; - return Guid == uuid.Guid; - } - - /// - /// Comparison function - /// - /// UUID to compare to - /// True if the UUIDs are equal, otherwise false - public bool Equals(UUID uuid) - { - return Guid == uuid.Guid; - } - - /// - /// Get a hyphenated string representation of this UUID - /// - /// A string representation of this UUID, lowercase and - /// with hyphens - /// 11f8aa9c-b071-4242-836b-13b7abe0d489 - public override string ToString() - { - if (Guid == Guid.Empty) - return ZeroString; - else - return Guid.ToString(); - } - - #endregion Overrides - - #region Operators - - /// - /// Equals operator - /// - /// First UUID for comparison - /// Second UUID for comparison - /// True if the UUIDs are byte for byte equal, otherwise false - public static bool operator ==(UUID lhs, UUID rhs) - { - return lhs.Guid == rhs.Guid; - } - - /// - /// Not equals operator - /// - /// First UUID for comparison - /// Second UUID for comparison - /// True if the UUIDs are not equal, otherwise true - public static bool operator !=(UUID lhs, UUID rhs) - { - return !(lhs == rhs); - } - - /// - /// XOR operator - /// - /// First UUID - /// Second UUID - /// A UUID that is a XOR combination of the two input UUIDs - public static UUID operator ^(UUID lhs, UUID rhs) - { - byte[] lhsbytes = lhs.GetBytes(); - byte[] rhsbytes = rhs.GetBytes(); - byte[] output = new byte[16]; - - for (int i = 0; i < 16; i++) - { - output[i] = (byte)(lhsbytes[i] ^ rhsbytes[i]); - } - - return new UUID(output, 0); - } - - /// - /// String typecasting operator - /// - /// A UUID in string form. Case insensitive, - /// hyphenated or non-hyphenated - /// A UUID built from the string representation - public static explicit operator UUID(string val) - { - return new UUID(val); - } - - #endregion Operators - - /// An UUID with a value of all zeroes - public static readonly UUID Zero = new UUID(); - - /// A cache of UUID.Zero as a string to optimize a common path - private static readonly string ZeroString = Guid.Empty.ToString(); - } -} +/* + * Copyright (c) 2006-2016, openmetaverse.co + * All rights reserved. + * + * - Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * - Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * - Neither the name of the openmetaverse.co nor the names + * of its contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Runtime.CompilerServices; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using System.Xml.Serialization; +using System.Runtime.Intrinsics.X86; +using System.Runtime.Intrinsics; + +namespace OpenMetaverse +{ + /// + /// A 128-bit Universally Unique Identifier + /// Only diference from Guid is on to and from bytes, where it uses network byte order unlike Guid + /// + + [StructLayout(LayoutKind.Explicit)] + [Serializable()] + public struct UUID : IComparable,IComparable, IEquatable, IEqualityComparer + { + [XmlIgnore] [NonSerialized()] [FieldOffset(0)] public int a; + [XmlIgnore] [NonSerialized()] [FieldOffset(4)] public short b; + [XmlIgnore] [NonSerialized()] [FieldOffset(6)] public short c; + + [XmlIgnore] [NonSerialized()] [FieldOffset(8)] public byte d; + [XmlIgnore] [NonSerialized()] [FieldOffset(9)] public byte e; + [XmlIgnore] [NonSerialized()] [FieldOffset(10)] public byte f; + [XmlIgnore] [NonSerialized()] [FieldOffset(11)] public byte g; + [XmlIgnore] [NonSerialized()] [FieldOffset(12)] public byte h; + [XmlIgnore] [NonSerialized()] [FieldOffset(13)] public byte i; + [XmlIgnore] [NonSerialized()] [FieldOffset(14)] public byte j; + [XmlIgnore] [NonSerialized()] [FieldOffset(15)] public byte k; + + [XmlIgnore] [NonSerialized()] [FieldOffset(0)] public byte bytea0; + [XmlIgnore] [NonSerialized()] [FieldOffset(1)] public byte bytea1; + [XmlIgnore] [NonSerialized()] [FieldOffset(2)] public byte bytea2; + [XmlIgnore] [NonSerialized()] [FieldOffset(3)] public byte bytea3; + + [XmlIgnore] [NonSerialized()] [FieldOffset(4)] public byte byteb0; + [XmlIgnore] [NonSerialized()] [FieldOffset(5)] public byte byteb1; + + [XmlIgnore] [NonSerialized()] [FieldOffset(6)] public byte bytec0; + [XmlIgnore] [NonSerialized()] [FieldOffset(7)] public byte bytec1; + + [XmlIgnore] [NonSerialized()] [FieldOffset(4)] public int intb; + [XmlIgnore] [NonSerialized()] [FieldOffset(8)] public int intc; + [XmlIgnore] [NonSerialized()] [FieldOffset(12)] public int intd; + + [XmlIgnore] [NonSerialized()][FieldOffset(0)] public ulong ulonga; + [XmlIgnore] [NonSerialized()] [FieldOffset(8)] public ulong ulongb; + + [FieldOffset(0)] public Guid Guid; + + #region Constructors + + /// + /// Constructor that takes a string UUID representation + /// + /// A string representation of a UUID, case + /// insensitive and can either be hyphenated or non-hyphenated + /// UUID("11f8aa9c-b071-4242-836b-13b7abe0d489") + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public UUID(string sval) : this(sval.AsSpan()) + { + } + + public unsafe UUID(ReadOnlySpan sval) + { + Unsafe.SkipInit(out this); + + int len = sval.Length; + if (len < 32) + throw new FormatException("Invalid UUID"); + + try + { + fixed (char* bval = sval) + { + char *val = bval; + while (*val == ' ') + { + ++val; + --len; + if (len < 32) + throw new Exception(); + } + + if (val[8] == '-') + { + if (len < 36) + throw new Exception(); + + if (val[13] != '-' || val[18] != '-' || val[23] != '-') + throw new Exception(); + + if (Sse42.IsSupported) + { + Vector128 input = Unsafe.As>(ref Unsafe.AsRef(val)); + Vector128 upper = Ssse3.Shuffle(input, Vector128.Create(0, 4, 8, 12, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff)); + Vector128 lower = Ssse3.Shuffle(input, Vector128.Create(2, 6, 10, 14, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff)); + + input = Unsafe.As>(ref Unsafe.AddByteOffset(ref Unsafe.AsRef(val), 18)); + Vector128 uppertmp = Ssse3.Shuffle(input, Vector128.Create(0xff, 0xff, 0xff, 0xff, 0, 4, 10, 14, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff)); + Vector128 lowerhalf = Ssse3.Shuffle(input, Vector128.Create(0xff, 0xff, 0xff, 0xff, 2, 6, 12, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff)); + upper = Sse2.Or(upper, uppertmp); + lower = Sse2.Or(lower, lowerhalf); + + lower = Sse41.Insert(lower, Unsafe.As(ref Unsafe.AddByteOffset(ref Unsafe.AsRef(val), 34)), 7); + + input = Unsafe.As>(ref Unsafe.AddByteOffset(ref Unsafe.AsRef(val), 38)); + uppertmp = Ssse3.Shuffle(input, Vector128.Create(0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0, 4, 10, 14, 0xff, 0xff, 0xff, 0xff)); + lowerhalf = Ssse3.Shuffle(input, Vector128.Create(0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 2, 6, 12, 0xff, 0xff, 0xff, 0xff, 0xff)); + upper = Sse2.Or(upper, uppertmp); + lower = Sse2.Or(lower, lowerhalf); + + lower = Sse41.Insert(lower, Unsafe.As(ref Unsafe.AddByteOffset(ref Unsafe.AsRef(val), 54)), 11); + + input = Unsafe.As>(ref Unsafe.AddByteOffset(ref Unsafe.AsRef(val), 56)); + uppertmp = Ssse3.Shuffle(input, Vector128.Create(0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0, 4, 8, 12)); + lowerhalf = Ssse3.Shuffle(input, Vector128.Create(0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 2, 6, 10, 14)); + + upper = Sse2.Or(upper, uppertmp); + lower = Sse2.Or(lower, lowerhalf); + + Vector128 charTolower = Vector128.Create((byte)0x20); + Vector128 upperLetters = Sse2.Or(upper, charTolower); + Vector128 lowerLetters = Sse2.Or(lower, charTolower); + + Vector128 letterTohex = Vector128.Create((byte)('a' - '0' - 10)); + upperLetters = Sse2.Subtract(upperLetters, letterTohex); + lowerLetters = Sse2.Subtract(lowerLetters, letterTohex); + + Vector128 char9 = Vector128.Create((byte)'9'); + Vector128 above9upper = (Sse2.CompareGreaterThan(upper.AsSByte(), char9.AsSByte())).AsByte(); + Vector128 above9lower = (Sse2.CompareGreaterThan(lower.AsSByte(), char9.AsSByte())).AsByte(); + + Vector128 ten = Vector128.Create((byte)('0' + 10)); + Vector128 tmpcmpA = Sse2.Subtract(upperLetters, ten); + Vector128 tmpcmpB = Sse2.Subtract(lowerLetters, ten); + + Vector128 fifteen = Vector128.Create((byte)('0' + 15)); + Vector128 tmpcmpC = Sse2.Subtract(fifteen, upperLetters); + Vector128 tmpcmpD = Sse2.Subtract(fifteen, lowerLetters); + + tmpcmpA = Sse2.Or(tmpcmpC, tmpcmpA); + tmpcmpB = Sse2.Or(tmpcmpD, tmpcmpB); + + tmpcmpA = Sse2.And(tmpcmpA, above9upper); + tmpcmpB = Sse2.And(tmpcmpB, above9lower); + + tmpcmpA = Sse2.Or(tmpcmpB, tmpcmpA); + int cmp = Sse2.MoveMask(tmpcmpA); + if (cmp != 0) + throw new Exception(); + + upper = Sse41.BlendVariable(upper, upperLetters, above9upper); + lower = Sse41.BlendVariable(lower, lowerLetters, above9lower); + + Vector128 charzero = Vector128.Create((byte)'0'); + upper = Sse2.Subtract(upper, charzero); + lower = Sse2.Subtract(lower, charzero); + + tmpcmpA = Sse2.Or(lower, upper); + cmp = Sse2.MoveMask(tmpcmpA); + if (cmp != 0) + throw new Exception(); + + upper = Sse2.ShiftLeftLogical(upper.AsUInt16(), 4).AsByte(); + lower = Sse2.Or(lower, upper); + if (BitConverter.IsLittleEndian) + lower = Ssse3.Shuffle(lower, Vector128.Create((byte)0x03, 0x02, 0x01, 0x00, 0x05, 0x04, 0x07, 0x06, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F)); + Unsafe.As>(ref Unsafe.AsRef(in this)) = lower; + return; + } + + if (BitConverter.IsLittleEndian) + { + bytea3 = Utils.HexToByte(val, 0); + bytea2 = Utils.HexToByte(val, 2); + bytea1 = Utils.HexToByte(val, 4); + bytea0 = Utils.HexToByte(val, 6); + + byteb1 = Utils.HexToByte(val, 9); + byteb0 = Utils.HexToByte(val, 11); + + bytec1 = Utils.HexToByte(val, 14); + bytec0 = Utils.HexToByte(val, 16); + } + else + { + bytea0 = Utils.HexToByte(val, 0); + bytea1 = Utils.HexToByte(val, 2); + bytea2 = Utils.HexToByte(val, 4); + bytea3 = Utils.HexToByte(val, 6); + + byteb0 = Utils.HexToByte(val, 9); + byteb1 = Utils.HexToByte(val, 11); + + bytec0 = Utils.HexToByte(val, 14); + bytec1 = Utils.HexToByte(val, 16); + } + + d = Utils.HexToByte(val, 19); + e = Utils.HexToByte(val, 21); + + + f = Utils.HexToByte(val, 24); + g = Utils.HexToByte(val, 26); + h = Utils.HexToByte(val, 28); + i = Utils.HexToByte(val, 30); + j = Utils.HexToByte(val, 32); + k = Utils.HexToByte(val, 34); + return; + } + else + { + if (BitConverter.IsLittleEndian) + { + bytea3 = Utils.HexToByte(val, 0); + bytea2 = Utils.HexToByte(val, 2); + bytea1 = Utils.HexToByte(val, 4); + bytea0 = Utils.HexToByte(val, 6); + + byteb1 = Utils.HexToByte(val, 8); + byteb0 = Utils.HexToByte(val, 10); + + bytec1 = Utils.HexToByte(val, 12); + bytec0 = Utils.HexToByte(val, 14); + } + else + { + bytea0 = Utils.HexToByte(val, 0); + bytea1 = Utils.HexToByte(val, 2); + bytea2 = Utils.HexToByte(val, 4); + bytea3 = Utils.HexToByte(val, 6); + + byteb0 = Utils.HexToByte(val, 8); + byteb1 = Utils.HexToByte(val, 10); + + bytec0 = Utils.HexToByte(val, 12); + bytec1 = Utils.HexToByte(val, 14); + } + + d = Utils.HexToByte(val, 16); + e = Utils.HexToByte(val, 18); + + f = Utils.HexToByte(val, 20); + g = Utils.HexToByte(val, 22); + h = Utils.HexToByte(val, 24); + i = Utils.HexToByte(val, 26); + j = Utils.HexToByte(val, 28); + k = Utils.HexToByte(val, 30); + return; + } + } + } + catch { } + this = new UUID(); + throw new System.FormatException("Invalid UUID"); + } + + /// + /// Constructor that takes a System.Guid object + /// + /// A Guid object that contains the unique identifier + /// to be represented by this UUID + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public UUID(Guid val) + { + Unsafe.SkipInit(out this); + Guid = val; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public UUID(ulong _la, ulong _lb) + { + Unsafe.SkipInit(out this); + ulonga = _la; + ulongb = _lb; + } + + /// + /// Constructor that takes a byte array containing a UUID + /// + /// Byte array containing a 16 byte UUID + /// Beginning offset in the array + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe UUID(byte[] source, int pos) + { + Unsafe.SkipInit(out this); + if (Ssse3.IsSupported) + { + Vector128 rawval = Unsafe.As>(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(source), pos)); + if (BitConverter.IsLittleEndian) + rawval = Ssse3.Shuffle(rawval, Vector128.Create((byte)0x03, 0x02, 0x01, 0x00, 0x05, 0x04, 0x07, 0x06, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F)); + Unsafe.As>(ref this) = rawval; + return; + } + + fixed (byte* ptr = &source[pos]) + { + if (BitConverter.IsLittleEndian) + { + bytea3 = *ptr; + bytea2 = *(ptr + 1); + bytea1 = *(ptr + 2); + bytea0 = *(ptr + 3); + + byteb1 = *(ptr + 4); + byteb0 = *(ptr + 5); + + bytec1 = *(ptr + 6); + bytec0 = *(ptr + 7); + + ulongb = *(ulong*)(ptr + 8); + } + else + { + ulonga = *(ulong*)(ptr); + + d = *(ptr + 8); + e = *(ptr + 9); + f = *(ptr + 10); + g = *(ptr + 11); + h = *(ptr + 12); + i = *(ptr + 13); + j = *(ptr + 14); + k = *(ptr + 15); + } + } + } + + /// + /// Constructor that takes an unsigned 64-bit unsigned integer to + /// convert to a UUID + /// + /// 64-bit unsigned integer to convert to a UUID + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public UUID(ulong val) + { + Unsafe.SkipInit(out this); + if (BitConverter.IsLittleEndian) + ulongb = val; + else + { + d = (byte)val; + e = (byte)(val >> 8); + f = (byte)(val >> 16); + g = (byte)(val >> 24); + h = (byte)(val >> 32); + i = (byte)(val >> 40); + j = (byte)(val >> 48); + k = (byte)(val >> 56); + } + } + + /// + /// Copy constructor + /// + /// UUID to copy + public UUID(UUID val) + { + Unsafe.SkipInit(out this); + this = val; + } + + #endregion Constructors + + #region Public Methods + + /// + /// IComparable.CompareTo implementation + /// + public readonly int CompareTo(object val) + { + if (val == null) + return 1; + + ref UUID id = ref Unsafe.Unbox(val); + if (id.a != a) + return (uint)id.a > (uint)a ? -1 : 1; + if (id.b != b) + return (uint)id.b > (uint)b ? -1 : 1; + if (id.c != c) + return (uint)id.c > (uint)c ? -1 : 1; + + if (id.d != d) + return id.d > d ? -1 : 1; + if (id.e != e) + return id.e > e ? -1 : 1; + if (id.f != f) + return id.f > f ? -1 : 1; + if (id.g != g) + return id.g > g ? -1 : 1; + if (id.h != h) + return id.h > h ? -1 : 1; + if (id.i != i) + return id.i > i ? -1 : 1; + if (id.j != j) + return id.j > j ? -1 : 1; + if (id.k != k) + return id.k > k ? -1 : 1; + return 0; + } + + public readonly int CompareTo(UUID id) + { + if (id.a != a) + return (uint)id.a > (uint)a ? -1 : 1; + if (id.b != b) + return (uint)id.b > (uint)b ? -1 : 1; + if (id.c != c) + return (uint)id.c > (uint)c ? -1 : 1; + + if (id.d != d) + return id.d > d ? -1 : 1; + if (id.e != e) + return id.e > e ? -1 : 1; + if (id.f != f) + return id.f > f ? -1 : 1; + if (id.g != g) + return id.g > g ? -1 : 1; + if (id.h != h) + return id.h > h ? -1 : 1; + if (id.i != i) + return id.i > i ? -1 : 1; + if (id.j != j) + return id.j > j ? -1 : 1; + if (id.k != k) + return id.k > k ? -1 : 1; + return 0; + } + + /// + /// Assigns this UUID from 16 bytes out of a byte array + /// + /// Byte array containing the UUID to assign this UUID to + /// Starting position of the UUID in the byte array + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe void FromBytes(byte[] source, int pos) + { + if (Ssse3.IsSupported) + { + Vector128 rawval = Unsafe.As>(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(source), pos)); + if (BitConverter.IsLittleEndian) + rawval = Ssse3.Shuffle(rawval, Vector128.Create((byte)0x03, 0x02, 0x01, 0x00, 0x05, 0x04, 0x07, 0x06, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F)); + Unsafe.As>(ref this) = rawval; + return; + } + + fixed (byte* ptr = &source[pos]) + { + if (BitConverter.IsLittleEndian) + { + bytea3 = *ptr; + bytea2 = *(ptr + 1); + bytea1 = *(ptr + 2); + bytea0 = *(ptr + 3); + + byteb1 = *(ptr + 4); + byteb0 = *(ptr + 5); + + bytec1 = *(ptr + 6); + bytec0 = *(ptr + 7); + ulongb = *(ulong*)(ptr + 8); + } + else + { + ulonga = *(ulong*)(ptr); + d = *(ptr + 8); + e = *(ptr + 9); + f = *(ptr + 10); + g = *(ptr + 11); + h = *(ptr + 12); + i = *(ptr + 13); + j = *(ptr + 14); + k = *(ptr + 15); + } + } + } + + /// + /// Returns a copy of the raw bytes for this UUID + /// + /// A 16 byte array containing this UUID + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly unsafe byte[] GetBytes() + { + byte[] dest = new byte[16]; + ToBytes(dest, 0); + return dest; + } + + /// + /// Writes the raw bytes for this UUID to a byte array + /// + /// Destination byte array + /// Position in the destination array to start + /// writing. Must be at least 16 bytes before the end of the array + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly unsafe void ToBytes(byte[] dest, int pos) + { + if (Ssse3.IsSupported) + { + Vector128 val = Unsafe.As>(ref Unsafe.AsRef(in this)); + if (BitConverter.IsLittleEndian) + val = Ssse3.Shuffle(val, Vector128.Create((byte)0x03, 0x02, 0x01, 0x00, 0x05, 0x04, 0x07, 0x06, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F)); + Unsafe.As>(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(dest), pos)) = val; + return; + } + fixed (byte* ptr = &dest[pos]) + { + if (BitConverter.IsLittleEndian) + { + *ptr = bytea3; + *(ptr + 1) = bytea2; + *(ptr + 2) = bytea1; + *(ptr + 3) = bytea0; + *(ptr + 4) = byteb1; + *(ptr + 5) = byteb0; + *(ptr + 6) = bytec1; + *(ptr + 7) = bytec0; + *(ulong*)(ptr + 8) = ulongb; + } + else + { + *(ulong*)(ptr) = ulonga; + *(ptr + 8) = d; + *(ptr + 9) = e; + *(ptr + 10) = f; + *(ptr + 11) = g; + *(ptr + 12) = h; + *(ptr + 13) = i; + *(ptr + 14) = j; + *(ptr + 15) = k; + } + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly unsafe void ToBytes(byte* ptr) + { + if (BitConverter.IsLittleEndian) + { + *ptr = bytea3; + *(ptr + 1) = bytea2; + *(ptr + 2) = bytea1; + *(ptr + 3) = bytea0; + *(ptr + 4) = byteb1; + *(ptr + 5) = byteb0; + *(ptr + 6) = bytec1; + *(ptr + 7) = bytec0; + *(ulong*)(ptr + 8) = ulongb; + } + else + { + *(ulong*)(ptr) = ulonga; + *(ptr + 8) = d; + *(ptr + 9) = e; + *(ptr + 10) = f; + *(ptr + 11) = g; + *(ptr + 12) = h; + *(ptr + 13) = i; + *(ptr + 14) = j; + *(ptr + 15) = k; + } + } + + /// + /// Calculate an LLCRC (cyclic redundancy check) for this UUID + /// + /// The CRC checksum for this UUID + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly uint CRC() + { + return (uint)a + (uint)intb + (uint)intc + (uint)intd; + } + + /// + /// Create a 64-bit integer representation from the second half of this UUID + /// + /// An integer created from the last eight bytes of this UUID + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly ulong GetULong() + { + if (BitConverter.IsLittleEndian) + return ulongb; + else + return d + + ((ulong)e << 8) + + ((ulong)f << 16) + + ((ulong)g << 24) + + ((ulong)h << 32) + + ((ulong)i << 40) + + ((ulong)j << 48) + + ((ulong)k << 56); + } + + #endregion Public Methods + + #region Static Methods + + /// + /// Generate a UUID from a string + /// + /// A string representation of a UUID, case + /// insensitive and can either be hyphenated or non-hyphenated + /// UUID.Parse("11f8aa9c-b071-4242-836b-13b7abe0d489") + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + + public unsafe static UUID Parse(string sval) + { + return Parse(sval.AsSpan()); + } + + public unsafe static UUID Parse(ReadOnlySpan sval) + { + UUID result = new(); + int len = sval.Length; + if (len < 32) + throw new FormatException("Invalid UUID"); + try + { + fixed (char* bval = sval) + { + char* val = bval; + while (*val == ' ') + { + ++val; + --len; + if (len < 32) + throw new Exception(); + } + + if (val[8] == '-') + { + if (len < 36) + throw new Exception(); + + if (val[13] != '-' || val[18] != '-' || val[23] != '-') + throw new Exception(); + + if (Sse42.IsSupported) + { + Vector128 input = Unsafe.As>(ref Unsafe.AsRef(val)); + Vector128 upper = Ssse3.Shuffle(input, Vector128.Create(0, 4, 8, 12, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff)); + Vector128 lower = Ssse3.Shuffle(input, Vector128.Create(2, 6, 10, 14, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff)); + + input = Unsafe.As>(ref Unsafe.AddByteOffset(ref Unsafe.AsRef(val), 18)); + Vector128 uppertmp = Ssse3.Shuffle(input, Vector128.Create(0xff, 0xff, 0xff, 0xff, 0, 4, 10, 14, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff)); + Vector128 lowerhalf = Ssse3.Shuffle(input, Vector128.Create(0xff, 0xff, 0xff, 0xff, 2, 6, 12, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff)); + upper = Sse2.Or(upper, uppertmp); + lower = Sse2.Or(lower, lowerhalf); + + lower = Sse41.Insert(lower, Unsafe.As(ref Unsafe.AddByteOffset(ref Unsafe.AsRef(val), 34)), 7); + + input = Unsafe.As>(ref Unsafe.AddByteOffset(ref Unsafe.AsRef(val), 38)); + uppertmp = Ssse3.Shuffle(input, Vector128.Create(0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0, 4, 10, 14, 0xff, 0xff, 0xff, 0xff)); + lowerhalf = Ssse3.Shuffle(input, Vector128.Create(0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 2, 6, 12, 0xff, 0xff, 0xff, 0xff, 0xff)); + upper = Sse2.Or(upper, uppertmp); + lower = Sse2.Or(lower, lowerhalf); + + lower = Sse41.Insert(lower, Unsafe.As(ref Unsafe.AddByteOffset(ref Unsafe.AsRef(val), 54)), 11); + + input = Unsafe.As>(ref Unsafe.AddByteOffset(ref Unsafe.AsRef(val), 56)); + uppertmp = Ssse3.Shuffle(input, Vector128.Create(0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0, 4, 8, 12)); + lowerhalf = Ssse3.Shuffle(input, Vector128.Create(0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 2, 6, 10, 14)); + + upper = Sse2.Or(upper, uppertmp); + lower = Sse2.Or(lower, lowerhalf); + + Vector128 charTolower = Vector128.Create((byte)0x20); + Vector128 upperLetters = Sse2.Or(upper, charTolower); + Vector128 lowerLetters = Sse2.Or(lower, charTolower); + + Vector128 letterTohex = Vector128.Create((byte)('a' - '0' - 10)); + upperLetters = Sse2.Subtract(upperLetters, letterTohex); + lowerLetters = Sse2.Subtract(lowerLetters, letterTohex); + + Vector128 char9 = Vector128.Create((byte)'9'); + Vector128 above9upper = (Sse2.CompareGreaterThan(upper.AsSByte(), char9.AsSByte())).AsByte(); + Vector128 above9lower = (Sse2.CompareGreaterThan(lower.AsSByte(), char9.AsSByte())).AsByte(); + + Vector128 ten = Vector128.Create((byte)('0' + 10)); + Vector128 tmpcmpA = Sse2.Subtract(upperLetters, ten); + Vector128 tmpcmpB = Sse2.Subtract(lowerLetters, ten); + + Vector128 fifteen = Vector128.Create((byte)('0' + 15)); + Vector128 tmpcmpC = Sse2.Subtract(fifteen, upperLetters); + Vector128 tmpcmpD = Sse2.Subtract(fifteen, lowerLetters); + + tmpcmpA = Sse2.Or(tmpcmpC, tmpcmpA); + tmpcmpB = Sse2.Or(tmpcmpD, tmpcmpB); + + tmpcmpA = Sse2.And(tmpcmpA, above9upper); + tmpcmpB = Sse2.And(tmpcmpB, above9lower); + + tmpcmpA = Sse2.Or(tmpcmpB, tmpcmpA); + int cmp = Sse2.MoveMask(tmpcmpA); + if (cmp != 0) + throw new Exception(); + + upper = Sse41.BlendVariable(upper, upperLetters, above9upper); + lower = Sse41.BlendVariable(lower, lowerLetters, above9lower); + + Vector128 charzero = Vector128.Create((byte)'0'); + upper = Sse2.Subtract(upper, charzero); + lower = Sse2.Subtract(lower, charzero); + + tmpcmpA = Sse2.Or(lower, upper); + cmp = Sse2.MoveMask(tmpcmpA); + if (cmp != 0) + throw new Exception(); + + upper = Sse2.ShiftLeftLogical(upper.AsUInt16(), 4).AsByte(); + lower = Sse2.Or(lower, upper); + if (BitConverter.IsLittleEndian) + lower = Ssse3.Shuffle(lower, Vector128.Create((byte)0x03, 0x02, 0x01, 0x00, 0x05, 0x04, 0x07, 0x06, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F)); + Unsafe.As>(ref Unsafe.AsRef(in result)) = lower; + return result; + } + + if (BitConverter.IsLittleEndian) + { + result.bytea3 = Utils.HexToByte(val, 0); + result.bytea2 = Utils.HexToByte(val, 2); + result.bytea1 = Utils.HexToByte(val, 4); + result.bytea0 = Utils.HexToByte(val, 6); + + result.byteb1 = Utils.HexToByte(val, 9); + result.byteb0 = Utils.HexToByte(val, 11); + + result.bytec1 = Utils.HexToByte(val, 14); + result.bytec0 = Utils.HexToByte(val, 16); + } + else + { + result.bytea0 = Utils.HexToByte(val, 0); + result.bytea1 = Utils.HexToByte(val, 2); + result.bytea2 = Utils.HexToByte(val, 4); + result.bytea3 = Utils.HexToByte(val, 6); + + result.byteb0 = Utils.HexToByte(val, 9); + result.byteb1 = Utils.HexToByte(val, 11); + + result.bytec0 = Utils.HexToByte(val, 14); + result.bytec1 = Utils.HexToByte(val, 16); + } + + result.d = Utils.HexToByte(val, 19); + result.e = Utils.HexToByte(val, 21); + + + result.f = Utils.HexToByte(val, 24); + result.g = Utils.HexToByte(val, 26); + result.h = Utils.HexToByte(val, 28); + result.i = Utils.HexToByte(val, 30); + result.j = Utils.HexToByte(val, 32); + result.k = Utils.HexToByte(val, 34); + return result; + } + else + { + if (BitConverter.IsLittleEndian) + { + result.bytea3 = Utils.HexToByte(val, 0); + result.bytea2 = Utils.HexToByte(val, 2); + result.bytea1 = Utils.HexToByte(val, 4); + result.bytea0 = Utils.HexToByte(val, 6); + + result.byteb1 = Utils.HexToByte(val, 8); + result.byteb0 = Utils.HexToByte(val, 10); + + result.bytec1 = Utils.HexToByte(val, 12); + result.bytec0 = Utils.HexToByte(val, 14); + } + else + { + result.bytea0 = Utils.HexToByte(val, 0); + result.bytea1 = Utils.HexToByte(val, 2); + result.bytea2 = Utils.HexToByte(val, 4); + result.bytea3 = Utils.HexToByte(val, 6); + + result.byteb0 = Utils.HexToByte(val, 8); + result.byteb1 = Utils.HexToByte(val, 10); + + result.bytec0 = Utils.HexToByte(val, 12); + result.bytec1 = Utils.HexToByte(val, 14); + } + + result.d = Utils.HexToByte(val, 16); + result.e = Utils.HexToByte(val, 18); + + result.f = Utils.HexToByte(val, 20); + result.g = Utils.HexToByte(val, 22); + result.h = Utils.HexToByte(val, 24); + result.i = Utils.HexToByte(val, 26); + result.j = Utils.HexToByte(val, 28); + result.k = Utils.HexToByte(val, 30); + return result; + } + } + } + catch { } + result = new UUID(); + throw new FormatException("Invalid UUID"); + } + + /// + /// Generate a UUID from a string + /// + /// A string representation of a UUID, case + /// insensitive and can either be hyphenated or non-hyphenated + /// Will contain the parsed UUID if successful, + /// otherwise null + /// True if the string was successfully parse, otherwise false + /// UUID.TryParse("11f8aa9c-b071-4242-836b-13b7abe0d489", result) + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static bool TryParse(string sval, out UUID result) + { + return TryParse(sval.AsSpan(), out result); + } + + public unsafe static bool TryParse(ReadOnlySpan sval, out UUID result) + { + result = new UUID(); + + int len = sval.Length; + if (len < 32) + return false; + + try + { + fixed (char* bval = sval) + { + char* val = bval; + + while (*val == ' ') + { + ++val; + --len; + if (len < 32) + return false; + } + + if (val[8] == '-') + { + if (len < 36) + return false; + + while (--len > 35) + { + if (val[len] != ' ') + return false; + } + + if (val[13] != '-' || val[18] != '-' || val[23] != '-') + return false; + + if (Sse42.IsSupported) + { + Vector128 input = Unsafe.As>(ref Unsafe.AsRef(val)); + Vector128 upper = Ssse3.Shuffle(input, Vector128.Create(0, 4, 8, 12, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff)); + Vector128 lower = Ssse3.Shuffle(input, Vector128.Create(2, 6, 10, 14, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff)); + + input = Unsafe.As>(ref Unsafe.AddByteOffset(ref Unsafe.AsRef(val), 18)); + Vector128 uppertmp = Ssse3.Shuffle(input, Vector128.Create(0xff, 0xff, 0xff, 0xff, 0, 4, 10, 14, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff)); + Vector128 lowerhalf = Ssse3.Shuffle(input, Vector128.Create(0xff, 0xff, 0xff, 0xff, 2, 6, 12, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff)); + upper = Sse2.Or(upper, uppertmp); + lower = Sse2.Or(lower, lowerhalf); + + lower = Sse41.Insert(lower, Unsafe.As(ref Unsafe.AddByteOffset(ref Unsafe.AsRef(val), 34)), 7); + + input = Unsafe.As>(ref Unsafe.AddByteOffset(ref Unsafe.AsRef(val), 38)); + uppertmp = Ssse3.Shuffle(input, Vector128.Create(0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0, 4, 10, 14, 0xff, 0xff, 0xff, 0xff)); + lowerhalf = Ssse3.Shuffle(input, Vector128.Create(0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 2, 6, 12, 0xff, 0xff, 0xff, 0xff, 0xff)); + upper = Sse2.Or(upper, uppertmp); + lower = Sse2.Or(lower, lowerhalf); + + lower = Sse41.Insert(lower, Unsafe.As(ref Unsafe.AddByteOffset(ref Unsafe.AsRef(val), 54)), 11); + + input = Unsafe.As>(ref Unsafe.AddByteOffset(ref Unsafe.AsRef(val), 56)); + uppertmp = Ssse3.Shuffle(input, Vector128.Create(0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0, 4, 8, 12)); + lowerhalf = Ssse3.Shuffle(input, Vector128.Create(0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 2, 6, 10, 14)); + + upper = Sse2.Or(upper, uppertmp); + lower = Sse2.Or(lower, lowerhalf); + + Vector128 charTolower = Vector128.Create((byte)0x20); + Vector128 upperLetters = Sse2.Or(upper, charTolower); + Vector128 lowerLetters = Sse2.Or(lower, charTolower); + + Vector128 letterTohex = Vector128.Create((byte)('a' - '0' - 10)); + upperLetters = Sse2.Subtract(upperLetters, letterTohex); + lowerLetters = Sse2.Subtract(lowerLetters, letterTohex); + + Vector128 char9 = Vector128.Create((byte)'9'); + Vector128 above9upper = (Sse2.CompareGreaterThan(upper.AsSByte(), char9.AsSByte())).AsByte(); + Vector128 above9lower = (Sse2.CompareGreaterThan(lower.AsSByte(), char9.AsSByte())).AsByte(); + + Vector128 ten = Vector128.Create((byte)('0' + 10)); + Vector128 tmpcmpA = Sse2.Subtract(upperLetters, ten); + Vector128 tmpcmpB = Sse2.Subtract(lowerLetters, ten); + + Vector128 fifteen = Vector128.Create((byte)('0' + 15)); + Vector128 tmpcmpC = Sse2.Subtract(fifteen, upperLetters); + Vector128 tmpcmpD = Sse2.Subtract(fifteen, lowerLetters); + + tmpcmpA = Sse2.Or(tmpcmpC, tmpcmpA); + tmpcmpB = Sse2.Or(tmpcmpD, tmpcmpB); + + tmpcmpA = Sse2.And(tmpcmpA, above9upper); + tmpcmpB = Sse2.And(tmpcmpB, above9lower); + + tmpcmpA = Sse2.Or(tmpcmpB, tmpcmpA); + int cmp = Sse2.MoveMask(tmpcmpA); + if (cmp != 0) + return false; + + upper = Sse41.BlendVariable(upper, upperLetters, above9upper); + lower = Sse41.BlendVariable(lower, lowerLetters, above9lower); + + Vector128 charzero = Vector128.Create((byte)'0'); + upper = Sse2.Subtract(upper, charzero); + lower = Sse2.Subtract(lower, charzero); + + tmpcmpA = Sse2.Or(lower, upper); + cmp = Sse2.MoveMask(tmpcmpA); + if (cmp != 0) + return false; + + upper = Sse2.ShiftLeftLogical(upper.AsUInt16(), 4).AsByte(); + lower = Sse2.Or(lower, upper); + if (BitConverter.IsLittleEndian) + lower = Ssse3.Shuffle(lower, Vector128.Create((byte)0x03, 0x02, 0x01, 0x00, 0x05, 0x04, 0x07, 0x06, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F)); + Unsafe.As>(ref Unsafe.AsRef(in result)) = lower; + return true; + } + + if (BitConverter.IsLittleEndian) + { + result.bytea3 = Utils.HexToByte(val, 0); + result.bytea2 = Utils.HexToByte(val, 2); + result.bytea1 = Utils.HexToByte(val, 4); + result.bytea0 = Utils.HexToByte(val, 6); + + result.byteb1 = Utils.HexToByte(val, 9); + result.byteb0 = Utils.HexToByte(val, 11); + + result.bytec1 = Utils.HexToByte(val, 14); + result.bytec0 = Utils.HexToByte(val, 16); + } + else + { + result.bytea0 = Utils.HexToByte(val, 0); + result.bytea1 = Utils.HexToByte(val, 2); + result.bytea2 = Utils.HexToByte(val, 4); + result.bytea3 = Utils.HexToByte(val, 6); + + result.byteb0 = Utils.HexToByte(val, 9); + result.byteb1 = Utils.HexToByte(val, 11); + + result.bytec0 = Utils.HexToByte(val, 14); + result.bytec1 = Utils.HexToByte(val, 16); + } + + result.d = Utils.HexToByte(val, 19); + result.e = Utils.HexToByte(val, 21); + + + result.f = Utils.HexToByte(val, 24); + result.g = Utils.HexToByte(val, 26); + result.h = Utils.HexToByte(val, 28); + result.i = Utils.HexToByte(val, 30); + result.j = Utils.HexToByte(val, 32); + result.k = Utils.HexToByte(val, 34); + return true; + } + else + { + while (--len > 31) + { + if (val[len] != ' ') + return false; + } + if (BitConverter.IsLittleEndian) + { + result.bytea3 = Utils.HexToByte(val, 0); + result.bytea2 = Utils.HexToByte(val, 2); + result.bytea1 = Utils.HexToByte(val, 4); + result.bytea0 = Utils.HexToByte(val, 6); + + result.byteb1 = Utils.HexToByte(val, 8); + result.byteb0 = Utils.HexToByte(val, 10); + + result.bytec1 = Utils.HexToByte(val, 12); + result.bytec0 = Utils.HexToByte(val, 14); + } + else + { + result.bytea0 = Utils.HexToByte(val, 0); + result.bytea1 = Utils.HexToByte(val, 2); + result.bytea2 = Utils.HexToByte(val, 4); + result.bytea3 = Utils.HexToByte(val, 6); + + result.byteb0 = Utils.HexToByte(val, 8); + result.byteb1 = Utils.HexToByte(val, 10); + + result.bytec0 = Utils.HexToByte(val, 12); + result.bytec1 = Utils.HexToByte(val, 14); + } + + result.d = Utils.HexToByte(val, 16); + result.e = Utils.HexToByte(val, 18); + + result.f = Utils.HexToByte(val, 20); + result.g = Utils.HexToByte(val, 22); + result.h = Utils.HexToByte(val, 24); + result.i = Utils.HexToByte(val, 26); + result.j = Utils.HexToByte(val, 28); + result.k = Utils.HexToByte(val, 30); + return true; + } + } + } + catch { } + result = new UUID(); + return false; + } + + /// + /// Combine two UUIDs together by taking the MD5 hash of a byte array + /// containing both UUIDs + /// + /// First UUID to combine + /// Second UUID to combine + /// The UUID product of the combination + public static UUID Combine(UUID first, UUID second) + { + // Construct the buffer that MD5ed + byte[] input = new byte[32]; + Buffer.BlockCopy(first.GetBytes(), 0, input, 0, 16); + Buffer.BlockCopy(second.GetBytes(), 0, input, 16, 16); + + return new UUID(Utils.MD5(input), 0); + } + + /// + /// + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static UUID Random() + { + Guid g = Guid.NewGuid(); + return *(UUID*)&g; + } + + #endregion Static Methods + + #region Overrides + + /// + /// Return a hash code for this UUID, used by .NET for hash tables + /// + /// An integer composed of all the UUID bytes XORed together + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly override int GetHashCode() + { + int h = Utils.CombineHash(intd, intc); + h = Utils.CombineHash(h, intb); + return Utils.CombineHash(h, a); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly int GetHashCode(UUID u) + { + return u.GetHashCode(); + } + + /// + /// Comparison function + /// + /// An object to compare to this UUID + /// True if the object is a UUID and both UUIDs are equal + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly override bool Equals(object o) + { + if (o is not UUID uuid) + return false; + + if (ulonga != uuid.ulonga) + return false; + if (ulongb != uuid.ulongb) + return false; + return true; + } + + /// + /// Comparison function + /// + /// UUID to compare to + /// True if the UUIDs are equal, otherwise false + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly bool Equals(UUID uuid) + { + if (ulonga != uuid.ulonga) + return false; + if (ulongb != uuid.ulongb) + return false; + return true; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly bool Equals(UUID a, UUID b) + { + if (a.ulonga != b.ulonga) + return false; + if (a.ulongb != b.ulongb) + return false; + return true; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly bool IsZero() + { + if (ulonga != 0) + return false; + if (ulongb != 0) + return false; + return true; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly bool NotEqual(in UUID uuid) + { + if (ulonga != uuid.ulonga) + return true; + if (ulongb != uuid.ulongb) + return true; + return false; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly bool IsNotZero() + { + if (ulonga != 0) + return true; + if (ulongb != 0) + return true; + return false; + } + + /// + /// Get a hyphenated string representation of this UUID + /// + /// A string representation of this UUID, lowercase and + /// with hyphens + /// 11f8aa9c-b071-4242-836b-13b7abe0d489 + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly override string ToString() + { + return Utils.UUIDToDashString(this); + } + + #endregion Overrides + + #region Operators + + /// + /// Equals operator + /// + /// First UUID for comparison + /// Second UUID for comparison + /// True if the UUIDs are byte for byte equal, otherwise false + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool operator ==(in UUID lhs, in UUID rhs) + { + if (lhs.ulonga != rhs.ulonga) + return false; + if (lhs.ulongb != rhs.ulongb) + return false; + return true; + } + + /// + /// Not equals operator + /// + /// First UUID for comparison + /// Second UUID for comparison + /// True if the UUIDs are not equal, otherwise true + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool operator !=(in UUID lhs, in UUID rhs) + { + if (lhs.ulonga != rhs.ulonga) + return true; + if (lhs.ulongb != rhs.ulongb) + return true; + return false; + } + + /// + /// XOR operator + /// + /// First UUID + /// Second UUID + /// A UUID that is a XOR combination of the two input UUIDs + public static UUID operator ^(UUID lhs, UUID rhs) + { + return new() + { + ulonga = lhs.ulonga ^ rhs.ulonga, + ulongb = lhs.ulongb ^ rhs.ulongb + }; + } + + /// + /// String typecasting operator + /// + /// A UUID in string form. Case insensitive, + /// hyphenated or non-hyphenated + /// A UUID built from the string representation + public static explicit operator UUID(string val) + { + return new UUID(val); + } + + #endregion Operators + + /// An UUID with a value of all zeroes + public static readonly UUID Zero = new(); + + /// A cache of UUID.Zero as a string to optimize a common path + public static readonly string ZeroString = "00000000-0000-0000-0000-000000000000"; + } +} diff --git a/OpenMetaverse.Types/Utils.cs b/OpenMetaverse.Types/Utils.cs index 92a93ef7..465db3ca 100644 --- a/OpenMetaverse.Types/Utils.cs +++ b/OpenMetaverse.Types/Utils.cs @@ -1,442 +1,353 @@ -/* - * Copyright (c) 2006-2016, openmetaverse.co - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * All rights reserved. - * - * - Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, this - * list of conditions and the following disclaimer. - * - Neither the name of the openmetaverse.co nor the names - * of its contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Text; - -namespace OpenMetaverse -{ - public static partial class Utils - { - /// - /// Operating system - /// - public enum Platform - { - /// Unknown - Unknown, - /// Microsoft Windows - Windows, - /// Microsoft Windows CE - WindowsCE, - /// Linux - Linux, - /// Apple OSX - OSX - } - - /// - /// Runtime platform - /// - public enum Runtime - { - /// .NET runtime - Windows, - /// Mono runtime: http://www.mono-project.com/ - Mono - } - - public const float E = (float)Math.E; - public const float LOG10E = 0.4342945f; - public const float LOG2E = 1.442695f; - public const float PI = (float)Math.PI; - public const float TWO_PI = (float)(Math.PI * 2.0d); - public const float PI_OVER_TWO = (float)(Math.PI / 2.0d); - public const float PI_OVER_FOUR = (float)(Math.PI / 4.0d); - /// Used for converting degrees to radians - public const float DEG_TO_RAD = (float)(Math.PI / 180.0d); - /// Used for converting radians to degrees - public const float RAD_TO_DEG = (float)(180.0d / Math.PI); - - /// Provide a single instance of the CultureInfo class to - /// help parsing in situations where the grid assumes an en-us - /// culture - public static readonly System.Globalization.CultureInfo EnUsCulture = - new System.Globalization.CultureInfo("en-us", false); - - /// UNIX epoch in DateTime format - public static readonly DateTime Epoch = new DateTime(1970, 1, 1); - - public static readonly byte[] EmptyBytes = new byte[0]; - - /// Provide a single instance of the MD5 class to avoid making - /// duplicate copies and handle thread safety - private static readonly System.Security.Cryptography.MD5 MD5Builder = - new System.Security.Cryptography.MD5CryptoServiceProvider(); - - /// Provide a single instance of the SHA-1 class to avoid - /// making duplicate copies and handle thread safety - private static readonly System.Security.Cryptography.SHA1 SHA1Builder = - new System.Security.Cryptography.SHA1CryptoServiceProvider(); - - private static readonly System.Security.Cryptography.SHA256 SHA256Builder = - new System.Security.Cryptography.SHA256Managed(); - - /// Provide a single instance of a random number generator - /// to avoid making duplicate copies and handle thread safety - private static readonly Random RNG = new Random(); - - #region Math - - /// - /// Clamp a given value between a range - /// - /// Value to clamp - /// Minimum allowable value - /// Maximum allowable value - /// A value inclusively between lower and upper - public static float Clamp(float value, float min, float max) - { - // First we check to see if we're greater than the max - value = (value > max) ? max : value; - - // Then we check to see if we're less than the min. - value = (value < min) ? min : value; - - // There's no check to see if min > max. - return value; - } - - /// - /// Clamp a given value between a range - /// - /// Value to clamp - /// Minimum allowable value - /// Maximum allowable value - /// A value inclusively between lower and upper - public static double Clamp(double value, double min, double max) - { - // First we check to see if we're greater than the max - value = (value > max) ? max : value; - - // Then we check to see if we're less than the min. - value = (value < min) ? min : value; - - // There's no check to see if min > max. - return value; - } - - /// - /// Clamp a given value between a range - /// - /// Value to clamp - /// Minimum allowable value - /// Maximum allowable value - /// A value inclusively between lower and upper - public static int Clamp(int value, int min, int max) - { - // First we check to see if we're greater than the max - value = (value > max) ? max : value; - - // Then we check to see if we're less than the min. - value = (value < min) ? min : value; - - // There's no check to see if min > max. - return value; - } - - /// - /// Round a floating-point value to the nearest integer - /// - /// Floating point number to round - /// Integer - public static int Round(float val) - { - return (int)Math.Floor(val + 0.5f); - } - - /// - /// Test if a single precision float is a finite number - /// - public static bool IsFinite(float value) - { - return !(Single.IsNaN(value) || Single.IsInfinity(value)); - } - - /// - /// Test if a double precision float is a finite number - /// - public static bool IsFinite(double value) - { - return !(Double.IsNaN(value) || Double.IsInfinity(value)); - } - - /// - /// Get the distance between two floating-point values - /// - /// First value - /// Second value - /// The distance between the two values - public static float Distance(float value1, float value2) - { - return Math.Abs(value1 - value2); - } - - public static float Hermite(float value1, float tangent1, float value2, float tangent2, float amount) - { - // All transformed to double not to lose precission - // Otherwise, for high numbers of param:amount the result is NaN instead of Infinity - double v1 = value1, v2 = value2, t1 = tangent1, t2 = tangent2, s = amount, result; - double sCubed = s * s * s; - double sSquared = s * s; - - if (amount == 0f) - result = value1; - else if (amount == 1f) - result = value2; - else - result = (2d * v1 - 2d * v2 + t2 + t1) * sCubed + - (3d * v2 - 3d * v1 - 2d * t1 - t2) * sSquared + - t1 * s + v1; - return (float)result; - } - - public static double Hermite(double value1, double tangent1, double value2, double tangent2, double amount) - { - // All transformed to double not to lose precission - // Otherwise, for high numbers of param:amount the result is NaN instead of Infinity - double v1 = value1, v2 = value2, t1 = tangent1, t2 = tangent2, s = amount, result; - double sCubed = s * s * s; - double sSquared = s * s; - - if (amount == 0d) - result = value1; - else if (amount == 1f) - result = value2; - else - result = (2d * v1 - 2d * v2 + t2 + t1) * sCubed + - (3d * v2 - 3d * v1 - 2d * t1 - t2) * sSquared + - t1 * s + v1; - return result; - } - - public static float Lerp(float value1, float value2, float amount) - { - return value1 + (value2 - value1) * amount; - } - - public static double Lerp(double value1, double value2, double amount) - { - return value1 + (value2 - value1) * amount; - } - - public static float SmoothStep(float value1, float value2, float amount) - { - // It is expected that 0 < amount < 1 - // If amount < 0, return value1 - // If amount > 1, return value2 - float result = Utils.Clamp(amount, 0f, 1f); - return Utils.Hermite(value1, 0f, value2, 0f, result); - } - - public static double SmoothStep(double value1, double value2, double amount) - { - // It is expected that 0 < amount < 1 - // If amount < 0, return value1 - // If amount > 1, return value2 - double result = Utils.Clamp(amount, 0f, 1f); - return Utils.Hermite(value1, 0f, value2, 0f, result); - } - - public static float ToDegrees(float radians) - { - // This method uses double precission internally, - // though it returns single float - // Factor = 180 / pi - return (float)(radians * 57.295779513082320876798154814105); - } - - public static float ToRadians(float degrees) - { - // This method uses double precission internally, - // though it returns single float - // Factor = pi / 180 - return (float)(degrees * 0.017453292519943295769236907684886); - } - - /// - /// Compute the MD5 hash for a byte array - /// - /// Byte array to compute the hash for - /// MD5 hash of the input data - public static byte[] MD5(byte[] data) - { - lock (MD5Builder) - return MD5Builder.ComputeHash(data); - } - - /// - /// Compute the SHA1 hash for a byte array - /// - /// Byte array to compute the hash for - /// SHA1 hash of the input data - public static byte[] SHA1(byte[] data) - { - lock (SHA1Builder) - return SHA1Builder.ComputeHash(data); - } - - /// - /// Calculate the SHA1 hash of a given string - /// - /// The string to hash - /// The SHA1 hash as a string - public static string SHA1String(string value) - { - StringBuilder digest = new StringBuilder(40); - byte[] hash = SHA1(Encoding.UTF8.GetBytes(value)); - - // Convert the hash to a hex string - foreach (byte b in hash) - digest.AppendFormat(Utils.EnUsCulture, "{0:x2}", b); - - return digest.ToString(); - } - - /// - /// Compute the SHA256 hash for a byte array - /// - /// Byte array to compute the hash for - /// SHA256 hash of the input data - public static byte[] SHA256(byte[] data) - { - lock (SHA256Builder) - return SHA256Builder.ComputeHash(data); - } - - /// - /// Calculate the SHA256 hash of a given string - /// - /// The string to hash - /// The SHA256 hash as a string - public static string SHA256String(string value) - { - StringBuilder digest = new StringBuilder(64); - byte[] hash = SHA256(Encoding.UTF8.GetBytes(value)); - - // Convert the hash to a hex string - foreach (byte b in hash) - digest.AppendFormat(Utils.EnUsCulture, "{0:x2}", b); - - return digest.ToString(); - } - - /// - /// Calculate the MD5 hash of a given string - /// - /// The password to hash - /// An MD5 hash in string format, with $1$ prepended - public static string MD5(string password) - { - StringBuilder digest = new StringBuilder(32); - byte[] hash = MD5(ASCIIEncoding.Default.GetBytes(password)); - - // Convert the hash to a hex string - foreach (byte b in hash) - digest.AppendFormat(Utils.EnUsCulture, "{0:x2}", b); - - return "$1$" + digest.ToString(); - } - - /// - /// Calculate the MD5 hash of a given string - /// - /// The string to hash - /// The MD5 hash as a string - public static string MD5String(string value) - { - StringBuilder digest = new StringBuilder(32); - byte[] hash = MD5(Encoding.UTF8.GetBytes(value)); - - // Convert the hash to a hex string - foreach (byte b in hash) - digest.AppendFormat(Utils.EnUsCulture, "{0:x2}", b); - - return digest.ToString(); - } - - /// - /// Generate a random double precision floating point value - /// - /// Random value of type double - public static double RandomDouble() - { - lock (RNG) - return RNG.NextDouble(); - } - - #endregion Math - - #region Platform - - /// - /// Get the current running platform - /// - /// Enumeration of the current platform we are running on - public static Platform GetRunningPlatform() - { - const string OSX_CHECK_FILE = "/Library/Extensions.kextcache"; - - if (Environment.OSVersion.Platform == PlatformID.WinCE) - { - return Platform.WindowsCE; - } - else - { - int plat = (int)Environment.OSVersion.Platform; - - if ((plat != 4) && (plat != 128)) - { - return Platform.Windows; - } - else - { - if (System.IO.File.Exists(OSX_CHECK_FILE)) - return Platform.OSX; - else - return Platform.Linux; - } - } - } - - /// - /// Get the current running runtime - /// - /// Enumeration of the current runtime we are running on - public static Runtime GetRunningRuntime() - { - Type t = Type.GetType("Mono.Runtime"); - if (t != null) - return Runtime.Mono; - else - return Runtime.Windows; - } - - #endregion Platform - } -} +/* + * Copyright (c) 2006-2016, openmetaverse.co + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * All rights reserved. + * + * - Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * - Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * - Neither the name of the openmetaverse.co nor the names + * of its contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Runtime.CompilerServices; +using System.Text; + +namespace OpenMetaverse +{ + public static partial class Utils + { + public const float E = MathF.E; + public const float LOG10E = 0.4342945f; + public const float LOG2E = 1.442695f; + public const float PI = MathF.PI; + public const float TWO_PI = MathF.PI * 2.0f; + public const float PI_OVER_TWO = MathF.PI / 2.0f; + public const float PI_OVER_FOUR = MathF.PI / 4.0f; + /// Used for converting degrees to radians + public const float DEG_TO_RAD = MathF.PI / 180.0f; + /// Used for converting radians to degrees + public const float RAD_TO_DEG = 180.0f / MathF.PI; + + /// Provide a single instance of the CultureInfo class to + /// help parsing in situations where the grid assumes an en-us + /// culture + public static readonly System.Globalization.CultureInfo EnUsCulture = + new System.Globalization.CultureInfo("en-us", false); + + /// UNIX epoch in DateTime format + public static readonly DateTime Epoch = new DateTime(1970, 1, 1); + + public static readonly byte[] EmptyBytes = Array.Empty(); + + /// Provide a single instance of the MD5 class to avoid making + /// duplicate copies and handle thread safety + private static readonly System.Security.Cryptography.MD5 MD5Builder = + new System.Security.Cryptography.MD5CryptoServiceProvider(); + + /// Provide a single instance of the SHA-1 class to avoid + /// making duplicate copies and handle thread safety + private static readonly System.Security.Cryptography.SHA1 SHA1Builder = + new System.Security.Cryptography.SHA1CryptoServiceProvider(); + + private static readonly System.Security.Cryptography.SHA256 SHA256Builder = + new System.Security.Cryptography.SHA256Managed(); + + /// Provide a single instance of a random number generator + /// to avoid making duplicate copies and handle thread safety + private static readonly Random RNG = new Random(); + + #region Math + + /// + /// Clamp a given value between a range + /// + /// Value to clamp + /// Minimum allowable value + /// Maximum allowable value + /// A value inclusively between lower and upper + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static float Clamp(float value, float min, float max) + { + return (value < max) ? (value > min ? value : min) : max; + } + + /// + /// Clamp a given value between a range + /// + /// Value to clamp + /// Minimum allowable value + /// Maximum allowable value + /// A value inclusively between lower and upper + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static double Clamp(double value, double min, double max) + { + return (value < max) ? (value > min ? value : min) : max; + } + + /// + /// Clamp a given value between a range + /// + /// Value to clamp + /// Minimum allowable value + /// Maximum allowable value + /// A value inclusively between lower and upper + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int Clamp(int value, int min, int max) + { + return (value < max) ? (value > min ? value : min) : max; + } + + /// + /// Round a floating-point value to the nearest integer + /// + /// Floating point number to round + /// Integer + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int Round(float val) + { + return (int)Math.Floor(val + 0.5f); + } + + /// + /// Test if a single precision float is a finite number + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsFinite(float value) + { + return !(Single.IsNaN(value) || Single.IsInfinity(value)); + } + + /// + /// Test if a double precision float is a finite number + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsFinite(double value) + { + return !(Double.IsNaN(value) || Double.IsInfinity(value)); + } + + /// + /// Get the distance between two floating-point values + /// + /// First value + /// Second value + /// The distance between the two values + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static float Distance(float value1, float value2) + { + return Math.Abs(value1 - value2); + } + + public static float Hermite(float value1, float tangent1, float value2, float tangent2, float amount) + { + if (amount <= 0f) + return value1; + if (amount >= 1f) + return value2; + + // All transformed to double not to lose precission + // Otherwise, for high numbers of param:amount the result is NaN instead of Infinity + double v1 = value1, v2 = value2, t1 = tangent1, t2 = tangent2, s = amount; + double sSquared = s * s; + double sCubed = sSquared * s; + + return (float)((2d * v1 - 2d * v2 + t2 + t1) * sCubed + + (3d * v2 - 3d * v1 - 2d * t1 - t2) * sSquared + + t1 * s + v1); + } + + public static double Hermite(double value1, double tangent1, double value2, double tangent2, double amount) + { + if (amount <= 0d) + return value1; + if (amount >= 1f) + return value2; + + // All transformed to double not to lose precission + // Otherwise, for high numbers of param:amount the result is NaN instead of Infinity + double v1 = value1, v2 = value2, t1 = tangent1, t2 = tangent2, s = amount; + double sSquared = s * s; + double sCubed = sSquared * s; + + return (2d * v1 - 2d * v2 + t2 + t1) * sCubed + + (3d * v2 - 3d * v1 - 2d * t1 - t2) * sSquared + + t1 * s + v1; + } + + public static float Lerp(float value1, float value2, float amount) + { + return value1 + (value2 - value1) * amount; + } + + public static double Lerp(double value1, double value2, double amount) + { + return value1 + (value2 - value1) * amount; + } + + public static float SmoothStep(float value1, float value2, float amount) + { + return Utils.Hermite(value1, 0f, value2, 0f, amount); + } + + public static double SmoothStep(double value1, double value2, double amount) + { + return Utils.Hermite(value1, 0f, value2, 0f, amount); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static float ToDegrees(float radians) + { + // This method uses double precission internally, + // though it returns single float + // Factor = 180 / pi + return (float)(radians * 57.295779513082320876798154814105); + } + + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static float ToRadians(float degrees) + { + // This method uses double precission internally, + // though it returns single float + // Factor = pi / 180 + return (float)(degrees * 0.017453292519943295769236907684886); + } + + /// + /// Compute the MD5 hash for a byte array + /// + /// Byte array to compute the hash for + /// MD5 hash of the input data + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static byte[] MD5(byte[] data) + { + lock (MD5Builder) + return MD5Builder.ComputeHash(data); + } + + /// + /// Compute the SHA1 hash for a byte array + /// + /// Byte array to compute the hash for + /// SHA1 hash of the input data + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static byte[] SHA1(byte[] data) + { + lock (SHA1Builder) + return SHA1Builder.ComputeHash(data); + } + + /// + /// Calculate the SHA1 hash of a given string + /// + /// The string to hash + /// The SHA1 hash as a string + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static string SHA1String(string value) + { + StringBuilder digest = new StringBuilder(40); + byte[] hash = SHA1(Encoding.UTF8.GetBytes(value)); + + // Convert the hash to a hex string + foreach (byte b in hash) + digest.AppendFormat(Utils.EnUsCulture, "{0:x2}", b); + + return digest.ToString(); + } + + /// + /// Compute the SHA256 hash for a byte array + /// + /// Byte array to compute the hash for + /// SHA256 hash of the input data + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static byte[] SHA256(byte[] data) + { + lock (SHA256Builder) + return SHA256Builder.ComputeHash(data); + } + + /// + /// Calculate the SHA256 hash of a given string + /// + /// The string to hash + /// The SHA256 hash as a string + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static string SHA256String(string value) + { + StringBuilder digest = new StringBuilder(64); + byte[] hash = SHA256(Encoding.UTF8.GetBytes(value)); + + // Convert the hash to a hex string + foreach (byte b in hash) + digest.AppendFormat(Utils.EnUsCulture, "{0:x2}", b); + + return digest.ToString(); + } + + /// + /// Calculate the MD5 hash of a given string + /// + /// The password to hash + /// An MD5 hash in string format, with $1$ prepended + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static string MD5(string password) + { + StringBuilder digest = new StringBuilder(32); + byte[] hash = MD5(ASCIIEncoding.Default.GetBytes(password)); + + // Convert the hash to a hex string + foreach (byte b in hash) + digest.AppendFormat(Utils.EnUsCulture, "{0:x2}", b); + + return "$1$" + digest.ToString(); + } + + /// + /// Calculate the MD5 hash of a given string + /// + /// The string to hash + /// The MD5 hash as a string + public static string MD5String(string value) + { + StringBuilder digest = new StringBuilder(32); + byte[] hash = MD5(Encoding.UTF8.GetBytes(value)); + + // Convert the hash to a hex string + foreach (byte b in hash) + digest.AppendFormat(Utils.EnUsCulture, "{0:x2}", b); + + return digest.ToString(); + } + + /// + /// Generate a random double precision floating point value + /// + /// Random value of type double + public static double RandomDouble() + { + lock (RNG) + return RNG.NextDouble(); + } + + #endregion Math + } +} diff --git a/OpenMetaverse.Types/UtilsConversions.cs b/OpenMetaverse.Types/UtilsConversions.cs index 5026c2c9..f16d9ead 100644 --- a/OpenMetaverse.Types/UtilsConversions.cs +++ b/OpenMetaverse.Types/UtilsConversions.cs @@ -1,2843 +1,4015 @@ -/* - * Copyright (c) 2006-2016, openmetaverse.co - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * All rights reserved. - * - * - Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, this - * list of conditions and the following disclaimer. - * - Neither the name of the openmetaverse.co nor the names - * of its contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Net; -using System.Text; -using System.Reflection; -using System.IO; -using System.Runtime.CompilerServices; - -namespace OpenMetaverse -{ - public static partial class Utils - { -// public static readonly bool NoAlignment = CheckNeedAlignment(); - public static readonly bool CanDirectCopyLE = CheckNeedAlignment(); -// public static readonly bool CanDirectCopyBE = CheckDirectCopyBE(); - - public unsafe static bool CheckNeedAlignment() - { - if(!BitConverter.IsLittleEndian) - return false; - - byte[] bytes = new byte[4096]; - long ll = 0x55AA33EE55FFCCAA; - long l; - try - { - for (int i = 0; i < 512; i += 3) - { - fixed (byte* ptr = &bytes[253 + i]) - *(long*)ptr = ll; - - fixed (byte* ptr = &bytes[1027 + i]) - { - byte* p = ptr; - *p++ = (byte)ll; - *p++ = (byte)(ll >> 8); - *p++ = (byte)(ll >> 16); - *p++ = (byte)(ll >> 24); - *p++ = (byte)(ll >> 32); - *p++ = (byte)(ll >> 40); - *p++ = (byte)(ll >> 48); - *p = (byte)(ll >> 56); - } - - fixed (byte* ptr = &bytes[253 + i]) - l = *(long*)ptr; - if (l != ll) - return false; - - fixed (byte* ptr = &bytes[1027 + i]) - l = *(long*)ptr; - if (l != ll) - return false; - } - return true; - } - catch { } - return false; - - } -/* - static bool CheckDirectCopyLE() - { - return BitConverter.IsLittleEndian && NoAlignment; - } - - static bool CheckDirectCopyBE() - { - return !BitConverter.IsLittleEndian && NoAlignment; - } -*/ - #region String Arrays - - private static readonly string[] _AssetTypeNames = new string[] - { - "texture", // 0 - "sound", // 1 - "callcard", // 2 - "landmark", // 3 - "script", // 4 - "clothing", // 5 - "object", // 6 - "notecard", // 7 - "category", // 8 - String.Empty, // 9 - "lsltext", // 10 - "lslbyte", // 11 - "txtr_tga", // 12 - "bodypart", // 13 - String.Empty, // 14 - String.Empty, // 15 - String.Empty, // 16 - "snd_wav", // 17 - "img_tga", // 18 - "jpeg", // 19 - "animatn", // 20 - "gesture", // 21 - "simstate", // 22 - String.Empty, // 23 - "link", // 24 - "link_f", // 25 - String.Empty, // 26 - String.Empty, // 27 - String.Empty, // 28 - String.Empty, // 29 - String.Empty, // 30 - String.Empty, // 31 - String.Empty, // 32 - String.Empty, // 33 - String.Empty, // 34 - String.Empty, // 35 - String.Empty, // 36 - String.Empty, // 37 - String.Empty, // 38 - String.Empty, // 39 - String.Empty, // 40 - String.Empty, // 41 - String.Empty, // 42 - String.Empty, // 43 - String.Empty, // 44 - String.Empty, // 45 - String.Empty, // 46 - String.Empty, // 47 - String.Empty, // 48 - "mesh", // 49 - String.Empty, // 50 - String.Empty, // 51 - String.Empty, // 52 - String.Empty, // 53 - String.Empty, // 54 - String.Empty, // 55 - "settings", // 56 - String.Empty, // 57 - }; - - private static readonly string[] _FolderTypeNames = new string[] - { - "texture", // 0 - "sound", // 1 - "callcard", // 2 - "landmark", // 3 - String.Empty, // 4 - "clothing", // 5 - "object", // 6 - "notecard", // 7 - "root_inv", // 8 - String.Empty, // 9 - "lsltext", // 10 - String.Empty, // 11 - String.Empty, // 12 - "bodypart", // 13 - "trash", // 14 - "snapshot", // 15 - "lstndfnd", // 16 - String.Empty, // 17 - String.Empty, // 18 - String.Empty, // 19 - "animatn", // 20 - "gesture", // 21 - String.Empty, // 22 - "favorite", // 23 - String.Empty, // 24 - "settings", // 25 - "ensemble", // 26 - "ensemble", // 27 - "ensemble", // 28 - "ensemble", // 29 - "ensemble", // 30 - "ensemble", // 31 - "ensemble", // 32 - "ensemble", // 33 - "ensemble", // 34 - "ensemble", // 35 - "ensemble", // 36 - "ensemble", // 37 - "ensemble", // 38 - "ensemble", // 39 - "ensemble", // 40 - "ensemble", // 41 - "ensemble", // 42 - "ensemble", // 43 - "ensemble", // 44 - "ensemble", // 45 - "current", // 46 - "outfit", // 47 - "my_otfts", // 48 - "mesh", // 49 - "inbox", // 50 - "outbox", // 51 - "basic_rt", // 52 - "merchant", // 53 - "stock", // 54 - }; - - private static readonly string[] _InventoryTypeNames = new string[] - { - "texture", // 0 - "sound", // 1 - "callcard", // 2 - "landmark", // 3 - String.Empty, // 4 - String.Empty, // 5 - "object", // 6 - "notecard", // 7 - "category", // 8 - "root", // 9 - "script", // 10 - String.Empty, // 11 - String.Empty, // 12 - String.Empty, // 13 - String.Empty, // 14 - "snapshot", // 15 - String.Empty, // 16 - "attach", // 17 - "wearable", // 18 - "animation", // 19 - "gesture", // 20 - String.Empty, // 21 - "mesh", // 22 - String.Empty, // 23 - String.Empty, // 24 - "settings", // 25 - String.Empty, // 26 - }; - - private static readonly string[] _SaleTypeNames = new string[] - { - "not", - "orig", - "copy", - "cntn" - }; - - private static readonly string[] _AttachmentPointNames = new string[] - { - string.Empty, - "ATTACH_CHEST", - "ATTACH_HEAD", - "ATTACH_LSHOULDER", - "ATTACH_RSHOULDER", - "ATTACH_LHAND", - "ATTACH_RHAND", - "ATTACH_LFOOT", - "ATTACH_RFOOT", - "ATTACH_BACK", - "ATTACH_PELVIS", - "ATTACH_MOUTH", - "ATTACH_CHIN", - "ATTACH_LEAR", - "ATTACH_REAR", - "ATTACH_LEYE", - "ATTACH_REYE", - "ATTACH_NOSE", - "ATTACH_RUARM", - "ATTACH_RLARM", - "ATTACH_LUARM", - "ATTACH_LLARM", - "ATTACH_RHIP", - "ATTACH_RULEG", - "ATTACH_RLLEG", - "ATTACH_LHIP", - "ATTACH_LULEG", - "ATTACH_LLLEG", - "ATTACH_BELLY", - "ATTACH_LPEC", - "ATTACH_RPEC", - "ATTACH_HUD_CENTER_2", - "ATTACH_HUD_TOP_RIGHT", - "ATTACH_HUD_TOP_CENTER", - "ATTACH_HUD_TOP_LEFT", - "ATTACH_HUD_CENTER_1", - "ATTACH_HUD_BOTTOM_LEFT", - "ATTACH_HUD_BOTTOM", - "ATTACH_HUD_BOTTOM_RIGHT", - "ATTACH_NECK", - "ATTACH_AVATAR_CENTER", - "ATTACH_LHAND_RING1", - "ATTACH_RHAND_RING1", - "ATTACH_TAIL_BASE", - "ATTACH_TAIL_TIP", - "ATTACH_LWING", - "ATTACH_RWING", - "ATTACH_FACE_JAW", - "ATTACH_FACE_LEAR", - "ATTACH_FACE_REAR", - "ATTACH_FACE_LEYE", - "ATTACH_FACE_REYE", - "ATTACH_FACE_TONGUE", - "ATTACH_GROIN", - "ATTACH_HIND_LFOOT", - "ATTACH_HIND_RFOOT" - }; - - public static bool InternStrings = false; - - #endregion String Arrays - - #region BytesTo - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool ApproxEqual(float a, float b, float tolerance, float reltolerance = float.Epsilon) - { - float dif = Math.Abs(a - b); - if(dif <= tolerance) - return true; - - a = Math.Abs(a); - b = Math.Abs(b); - if(b > a) - a = b; - return dif <= a * reltolerance; - } - - public static bool ApproxEqual(float a, float b) - { - float dif = Math.Abs(a - b); - if (dif <= 1e-6f) - return true; - - a = Math.Abs(a); - b = Math.Abs(b); - if (b > a) - a = b; - return dif <= a * float.Epsilon; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static int CombineHash(int a, int b) - { - return ((a << 5) + a) ^ b; - } - - /// - /// Convert the first two bytes starting in the byte array in - /// little endian ordering to a signed short integer - /// - /// An array two bytes or longer - /// A signed short integer, will be zero if a short can't be - /// read at the given position - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static short BytesToInt16(byte[] bytes) - { - //if (bytes.Length < 2 ) return 0; - return (short)(bytes[0] | (bytes[1] << 8)); - } - - /// - /// Convert the first two bytes starting at the given position in - /// little endian ordering to a signed short integer - /// - /// An array two bytes or longer - /// Position in the array to start reading - /// A signed short integer, will be zero if a short can't be - /// read at the given position - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static short BytesToInt16(byte[] bytes, int pos) - { - //if (bytes.Length < pos + 2) return 0; - return (short)(bytes[pos] | (bytes[pos + 1] << 8)); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe short BytesToInt16(byte* bytes) - { - //if (bytes.Length < pos + 2) return 0; - return (short)(*bytes | (bytes[1] << 8)); - } - - /// - /// Convert the first four bytes starting at the given position in - /// little endian ordering to a signed integer - /// - /// An array four bytes or longer - /// Position to start reading the int from - /// A signed integer, will be zero if an int can't be read - /// at the given position - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe static int BytesToInt(byte[] bytes, int pos) - { - if (CanDirectCopyLE) - { - if (bytes.Length < pos + 4) return 0; - fixed (byte* p = &bytes[pos]) - return *(int*)p; - } - - return bytes[pos] | - (bytes[pos + 1] << 8) | - (bytes[pos + 2] << 16) | - (bytes[pos + 3] << 24); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe static int BytesToInt(byte* bytes) - { - if (CanDirectCopyLE) - { - return *(int*)bytes; - } - - return *bytes | - (bytes[1] << 8) | - (bytes[2] << 16) | - (bytes[3] << 24); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe static int BytesToIntSafepos(byte[] bytes, int pos) - { - if (CanDirectCopyLE) - { - fixed (byte* p = &bytes[pos]) - return *(int*)p; - } - - return bytes[pos] | - (bytes[pos + 1] << 8) | - (bytes[pos + 2] << 16) | - (bytes[pos + 3] << 24); - } - - /// - /// Convert the first four bytes of the given array in little endian - /// ordering to a signed integer - /// - /// An array four bytes or longer - /// A signed integer, will be zero if the array contains - /// less than four bytes - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe static int BytesToInt(byte[] bytes) - { - if (CanDirectCopyLE) - { - fixed (byte* p = bytes) - return *(int*)p; - } - else - return bytes[0] | - (bytes[1] << 8) | - (bytes[2] << 16) | - (bytes[3] << 24); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static int BytesToIntBig(byte[] bytes) - { - return (bytes[0] << 24) | - (bytes[1] << 16) | - (bytes[2] << 8) | - bytes[3]; - } - - /// - /// Convert the first eight bytes of the given array in little endian - /// ordering to a signed long integer - /// - /// An array eight bytes or longer - /// A signed long integer, will be zero if the array contains - /// less than eight bytes - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe static long BytesToInt64(byte[] bytes) - { - if (CanDirectCopyLE) - { - fixed (byte* p = bytes) - return *(long*)p; - } - else - return - bytes[0] | - ((long)bytes[1] << 8) | - ((long)bytes[2] << 16) | - ((long)bytes[3] << 24) | - ((long)bytes[4] << 32) | - ((long)bytes[5] << 40) | - ((long)bytes[6] << 48) | - ((long)bytes[7] << 56); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static long BytesToInt64Big(byte[] bytes) - { - return - ((long)bytes[0] << 56) | - ((long)bytes[1] << 48) | - ((long)bytes[2] << 40) | - ((long)bytes[3] << 32) | - ((long)bytes[4] << 24) | - ((long)bytes[5] << 16) | - ((long)bytes[6] << 8) | - ((long)bytes[7]); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe static long BytesToInt64(byte* bytes) - { - if (CanDirectCopyLE) - { - return *(long*)bytes; - } - else - return - bytes[0] | - ((long)bytes[1] << 8) | - ((long)bytes[2] << 16) | - ((long)bytes[3] << 24) | - ((long)bytes[4] << 32) | - ((long)bytes[5] << 40) | - ((long)bytes[6] << 48) | - ((long)bytes[7] << 56); - } - - /// - /// Convert the first eight bytes starting at the given position in - /// little endian ordering to a signed long integer - /// - /// An array eight bytes or longer - /// Position to start reading the long from - /// A signed long integer, will be zero if a long can't be read - /// at the given position - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe static long BytesToInt64(byte[] bytes, int pos) - { - if (CanDirectCopyLE) - { - if (bytes.Length < pos + 8) return 0; - fixed (byte* p = &bytes[pos]) - return *(long*)p; - } - else - return - (bytes[pos] | - ((long)bytes[pos + 1] << 8)) | - ((long)bytes[pos + 2] << 16) | - ((long)bytes[pos + 3] << 24) | - ((long)bytes[pos + 4] << 32) | - ((long)bytes[pos + 5] << 40) | - ((long)bytes[pos + 6] << 48) | - ((long)bytes[pos + 7] << 56); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe static long BytesToInt64Safepos(byte[] bytes, int pos) - { - if (CanDirectCopyLE) - { - fixed (byte* p = &bytes[pos]) - return *(long*)p; - } - else - return - (bytes[pos] | - ((long)bytes[pos + 1] << 8)) | - ((long)bytes[pos + 2] << 16) | - ((long)bytes[pos + 3] << 24) | - ((long)bytes[pos + 4] << 32) | - ((long)bytes[pos + 5] << 40) | - ((long)bytes[pos + 6] << 48) | - ((long)bytes[pos + 7] << 56); - } - - /// - /// Convert the first two bytes starting at the given position in - /// little endian ordering to an unsigned short - /// - /// Byte array containing the ushort - /// Position to start reading the ushort from - /// An unsigned short, will be zero if a ushort can't be read - /// at the given position - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static ushort BytesToUInt16(byte[] bytes, int pos) - { - //if (bytes.Length < pos + 2) return 0; - return (ushort)(bytes[pos] + (bytes[pos + 1] << 8)); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe ushort BytesToUInt16(byte* bytes) - { - //if (bytes.Length < pos + 2) return 0; - return (ushort)(*bytes + (bytes[1] << 8)); - } - - /// - /// Convert two bytes in little endian ordering to an unsigned short - /// - /// Byte array containing the ushort - /// An unsigned short, will be zero if a ushort can't be - /// read - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static ushort BytesToUInt16(byte[] bytes) - { - //if (bytes.Length < 2) return 0; - return (ushort)(bytes[0] + (bytes[1] << 8)); - } - - /// - /// Convert the first four bytes starting at the given position in - /// little endian ordering to an unsigned integer - /// - /// Byte array containing the uint - /// Position to start reading the uint from - /// An unsigned integer, will be zero if a uint can't be read - /// at the given position - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe static uint BytesToUInt(byte[] bytes, int pos) - { - if (CanDirectCopyLE) - { - if (bytes.Length < pos + 4) return 0; - fixed (byte* p = &bytes[pos]) - return *(uint*)p; - } - else - return (uint)( - (bytes[pos]) | - (bytes[pos + 1] << 8) | - (bytes[pos + 2] << 16) | - (bytes[pos + 3] << 24)); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe static uint BytesToUIntSafepos(byte[] bytes, int pos) - { - if (CanDirectCopyLE) - { - fixed (byte* p = &bytes[pos]) - return *(uint*)p; - } - else - return (uint)( - (bytes[pos]) | - (bytes[pos + 1] << 8) | - (bytes[pos + 2] << 16) | - (bytes[pos + 3] << 24)); - } - - /// - /// Convert the first four bytes of the given array in little endian - /// ordering to an unsigned integer - /// - /// An array four bytes or longer - /// An unsigned integer, will be zero if the array contains - /// less than four bytes - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe static uint BytesToUInt(byte[] bytes) - { - if (CanDirectCopyLE) - { - fixed (byte* p = bytes) - return *(uint*)p; - } - else - return (uint)( - bytes[0] | - (bytes[1] << 8) | - (bytes[2] << 16) | - (bytes[3] << 24)); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe static uint BytesToUInt(byte* bytes) - { - if (CanDirectCopyLE) - { - return *(uint*)bytes; - } - else - return (uint)( - bytes[0] | - (bytes[1] << 8) | - (bytes[2] << 16) | - (bytes[3] << 24)); - } - - /// - /// Convert the first eight bytes starting at the given position of the given array in little endian - /// ordering to an unsigned 64-bit integer - /// - /// An array eight bytes or longer - /// An unsigned 64-bit integer, will be zero if the array - /// contains less than eight bytes - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe static ulong BytesToUInt64(byte[] bytes, int pos) - { - if (CanDirectCopyLE) - { - if (bytes.Length < pos + 8) return 0; - fixed (byte* p = &bytes[pos]) - return *(ulong*)p; - } - else - return (ulong)( - bytes[pos] | - ((long)bytes[pos + 1] << 8) | - ((long)bytes[pos + 2] << 16) | - ((long)bytes[pos + 3] << 24) | - ((long)bytes[pos + 4] << 32) | - ((long)bytes[pos + 5] << 40) | - ((long)bytes[pos + 6] << 48) | - ((long)bytes[pos + 7] << 56)); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe static ulong BytesToUInt64Safepos(byte[] bytes, int pos) - { - if (CanDirectCopyLE) - { - fixed (byte* p = &bytes[pos]) - return *(ulong*)p; - } - else - return (ulong)( - bytes[pos] | - ((long)bytes[pos + 1] << 8) | - ((long)bytes[pos + 2] << 16) | - ((long)bytes[pos + 3] << 24) | - ((long)bytes[pos + 4] << 32) | - ((long)bytes[pos + 5] << 40) | - ((long)bytes[pos + 6] << 48) | - ((long)bytes[pos + 7] << 56)); - } - - /// - /// Convert the first eight bytes of the given array in little endian - /// ordering to an unsigned 64-bit integer - /// - /// An array eight bytes or longer - /// An unsigned 64-bit integer, will be zero if the array - /// contains less than eight bytes - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe static ulong BytesToUInt64(byte[] bytes) - { - if (CanDirectCopyLE) - { - fixed (byte* p = bytes) - return *(ulong*)p; - } - else - return (ulong)( - bytes[0] | - ((long)bytes[1] << 8) | - ((long)bytes[2] << 16) | - ((long)bytes[3] << 24) | - ((long)bytes[4] << 32) | - ((long)bytes[5] << 40) | - ((long)bytes[6] << 48) | - ((long)bytes[7] << 56)); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe static ulong BytesToUInt64(byte* bytes) - { - if (CanDirectCopyLE) - { - return *(ulong*)bytes; - } - else - return (ulong)( - bytes[0] | - ((long)bytes[1] << 8) | - ((long)bytes[2] << 16) | - ((long)bytes[3] << 24) | - ((long)bytes[4] << 32) | - ((long)bytes[5] << 40) | - ((long)bytes[6] << 48) | - ((long)bytes[7] << 56)); - } - - /// - /// Convert four bytes in little endian ordering to a floating point - /// value - /// - /// Byte array containing a little ending floating - /// point value - /// Starting position of the floating point value in - /// the byte array - /// Single precision value - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe static float BytesToFloat(byte[] bytes) - { - int tmp = BytesToInt(bytes); - return *(float*)&tmp; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe static float BytesToFloat(byte* bytes) - { - int tmp = BytesToInt(bytes); - return *(float*)&tmp; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe static float BytesToFloat(byte[] bytes, int pos) - { - int tmp = BytesToInt(bytes, pos); - return *(float*)&tmp; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe static float BytesToFloatSafepos(byte[] bytes, int pos) - { - int tmp = BytesToIntSafepos(bytes, pos); - return *(float*)&tmp; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe static double BytesToDouble(byte[] bytes) - { - long tmp = BytesToInt64(bytes); - return *(double*)&tmp; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe static double BytesToDoubleBig(byte[] bytes) - { - long tmp = BytesToInt64Big(bytes); - return *(double*)&tmp; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe static double BytesToDouble(byte* bytes) - { - long tmp = BytesToInt64(bytes); - return *(double*)&tmp; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe static double BytesToDouble(byte[] bytes, int pos) - { - long tmp = BytesToInt64(bytes, pos); - return *(double*)&tmp; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe static double BytesToDoubleSafepos(byte[] bytes, int pos) - { - long tmp = BytesToInt64Safepos(bytes, pos); - return *(double*)&tmp; - } - - #endregion BytesTo - - #region ToBytes - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static byte[] Int16ToBytes(short value) - { - byte[] bytes = new byte[2]; - bytes[0] = (byte)(value); - bytes[1] = (byte)((value >> 8)); - return bytes; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void Int16ToBytes(Stream ms, short value) - { - ms.WriteByte((byte)value); - ms.WriteByte((byte)(value >> 8)); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void Int16ToBytes(short value, byte[] dest, int pos) - { - dest[pos] = (byte)(value); - dest[pos + 1] = (byte)((value >> 8)); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void Int16ToBytes(short value, byte* dest) - { - *dest = (byte)(value); - dest[1] = (byte)((value >> 8)); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static byte[] UInt16ToBytes(ushort value) - { - byte[] bytes = new byte[2]; - bytes[0] = (byte)(value); - bytes[1] = (byte)((value >> 8)); - return bytes; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void UInt16ToBytes(ushort value, byte[] dest, int pos) - { - dest[pos] = (byte)(value); - dest[pos + 1] = (byte)((value >> 8)); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void UInt16ToBytes(ushort value, byte* dest) - { - *dest = (byte)(value); - dest[1] = (byte)((value >> 8)); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void UInt16ToBytesBig(ushort value, byte[] dest, int pos) - { - dest[pos] = (byte)((value >> 8)); - dest[pos + 1] = (byte)(value); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void UInt16ToBytesBig(ushort value, byte* dest) - { - *dest = (byte)((value >> 8)); - dest[1] = (byte)(value); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void IntToBytes(Stream ms, int value) - { - ms.WriteByte((byte)value); - ms.WriteByte((byte)(value >> 8)); - ms.WriteByte((byte)(value >> 16)); - ms.WriteByte((byte)(value >> 24)); - } - - /// - /// Convert an integer to a byte array in little endian format - /// - /// The integer to convert - /// A four byte little endian array - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe static byte[] IntToBytes(int value) - { - byte[] bytes = new byte[4]; - if (CanDirectCopyLE) - { - fixed (byte* p = bytes) - *(int*)p = value; - } - else - { - bytes[0] = (byte)value; - bytes[1] = (byte)(value >> 8); - bytes[2] = (byte)(value >> 16); - bytes[3] = (byte)(value >> 24); - } - return bytes; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe static void IntToBytes(int value, byte[] dest, int pos) - { - if (CanDirectCopyLE) - { - if (dest.Length < pos + 4) return; - fixed (byte* p = &dest[pos]) - *(int*)p = value; - } - else - { - dest[pos] = (byte)(value); - dest[pos + 1] = (byte)((value >> 8)); - dest[pos + 2] = (byte)((value >> 16)); - dest[pos + 3] = (byte)((value >> 24)); - } - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe static void IntToBytes(int value, byte* dest) - { - if (CanDirectCopyLE) - { - *(int*)dest = value; - } - else - { - *dest = (byte)(value); - dest[1] = (byte)((value >> 8)); - dest[2] = (byte)((value >> 16)); - dest[3] = (byte)((value >> 24)); - } - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe static void IntToBytesSafepos(int value, byte[] dest, int pos) - { - if (CanDirectCopyLE) - { - fixed (byte* p = &dest[pos]) - *(int*)p = value; - } - else - { - dest[pos] = (byte)(value); - dest[pos + 1] = (byte)((value >> 8)); - dest[pos + 2] = (byte)((value >> 16)); - dest[pos + 3] = (byte)((value >> 24)); - } - } - - /// - /// Convert an integer to a byte array in big endian format - /// - /// The integer to convert - /// A four byte big endian array - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static byte[] IntToBytesBig(int value) - { - byte[] bytes = new byte[4]; - - bytes[0] = (byte)(value >> 24); - bytes[1] = (byte)(value >> 16); - bytes[2] = (byte)(value >> 8); - bytes[3] = (byte)value; - - return bytes; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void IntToBytesBig(int value, byte[] bytes, int pos) - { - if (bytes.Length < pos + 4) return; - bytes[pos] = (byte)(value >> 24); - bytes[pos + 1] = (byte)(value >> 16); - bytes[pos + 2] = (byte)(value >> 8); - bytes[pos + 3] = (byte)value; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void IntToBytesBig(int value, byte* bytes) - { - *bytes = (byte)(value >> 24); - bytes[1] = (byte)(value >> 16); - bytes[2] = (byte)(value >> 8); - bytes[3] = (byte)value; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe static byte[] UIntToBytes(uint value) - { - return IntToBytes((int)value); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe static void UIntToBytes(uint value, byte[] dest, int pos) - { - IntToBytes((int)value, dest, pos); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe static void UIntToBytesSafepos(uint value, byte[] dest, int pos) - { - IntToBytesSafepos((int)value, dest, pos); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void UIntToBytesBig(uint value, byte[] dest, int pos) - { - IntToBytesBig((int)value, dest, pos); - } - - /// - /// Convert a 64-bit integer to a byte array in little endian format - /// - /// The value to convert - /// An 8 byte little endian array - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe static byte[] Int64ToBytes(long value) - { - byte[] bytes = new byte[8]; - if (CanDirectCopyLE) - { - fixed (byte* p = bytes) - *(long*)p = value; - } - else - { - bytes[0] = (byte)value; - bytes[1] = (byte)(value >> 8); - bytes[2] = (byte)(value >> 16); - bytes[3] = (byte)(value >> 24); - bytes[4] = (byte)(value >> 32); - bytes[5] = (byte)(value >> 40); - bytes[6] = (byte)(value >> 48); - bytes[7] = (byte)(value >> 56); - } - return bytes; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe static void Int64ToBytes(long value, byte[] dest, int pos) - { - if (CanDirectCopyLE) - { - if (dest.Length < pos + 8) return; - fixed (byte* p = &dest[pos]) - *(long*)p = value; - } - else - { - dest[pos] = (byte)value; - dest[pos + 1] = (byte)(value >> 8); - dest[pos + 2] = (byte)(value >> 16); - dest[pos + 3] = (byte)(value >> 24); - dest[pos + 4] = (byte)(value >> 32); - dest[pos + 5] = (byte)(value >> 40); - dest[pos + 6] = (byte)(value >> 48); - dest[pos + 7] = (byte)(value >> 56); - } - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe static void Int64ToBytes(long value, byte* dest) - { - if (CanDirectCopyLE) - { - *(long*)dest = value; - } - else - { - *dest = (byte)value; - dest[1] = (byte)(value >> 8); - dest[2] = (byte)(value >> 16); - dest[3] = (byte)(value >> 24); - dest[4] = (byte)(value >> 32); - dest[5] = (byte)(value >> 40); - dest[6] = (byte)(value >> 48); - dest[7] = (byte)(value >> 56); - } - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe static void Int64ToBytesSafepos(long value, byte[] dest, int pos) - { - if (CanDirectCopyLE) - { - fixed (byte* p = &dest[pos]) - *(long*)p = value; - } - else - { - dest[pos] = (byte)value; - dest[pos + 1] = (byte)(value >> 8); - dest[pos + 2] = (byte)(value >> 16); - dest[pos + 3] = (byte)(value >> 24); - dest[pos + 4] = (byte)(value >> 32); - dest[pos + 5] = (byte)(value >> 40); - dest[pos + 6] = (byte)(value >> 48); - dest[pos + 7] = (byte)(value >> 56); - } - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void Int64ToBytes(Stream ms, long value) - { - ms.WriteByte((byte)value); - ms.WriteByte((byte)(value >> 8)); - ms.WriteByte((byte)(value >> 16)); - ms.WriteByte((byte)(value >> 24)); - ms.WriteByte((byte)(value >> 32)); - ms.WriteByte((byte)(value >> 40)); - ms.WriteByte((byte)(value >> 48)); - ms.WriteByte((byte)(value >> 56)); - } - - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static byte[] Int64ToBytesBig(long value) - { - byte[] bytes = new byte[8]; - bytes[0] = (byte)((value >> 56)); - bytes[1] = (byte)((value >> 48)); - bytes[2] = (byte)((value >> 40)); - bytes[3] = (byte)((value >> 32)); - bytes[4] = (byte)((value >> 24)); - bytes[5] = (byte)((value >> 16)); - bytes[6] = (byte)((value >> 8)); - bytes[7] = (byte)(value); - return bytes; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void Int64ToBytesBig(long value, byte[] dest, int pos) - { - dest[pos] = (byte)(value >> 56); - dest[pos + 1] = (byte)(value >> 48); - dest[pos + 2] = (byte)(value >> 40); - dest[pos + 3] = (byte)(value >> 32); - dest[pos + 4] = (byte)(value >> 24); - dest[pos + 5] = (byte)(value >> 16); - dest[pos + 6] = (byte)(value >> 8); - dest[pos + 7] = (byte)value; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void Int64ToBytesBig(long value, byte* dest) - { - *dest = (byte)(value >> 56); - dest[1] = (byte)(value >> 48); - dest[2] = (byte)(value >> 40); - dest[3] = (byte)(value >> 32); - dest[4] = (byte)(value >> 24); - dest[5] = (byte)(value >> 16); - dest[6] = (byte)(value >> 8); - dest[7] = (byte)value; - } - - /// - /// Convert a 64-bit unsigned integer to a byte array in little endian - /// format - /// - /// The value to convert - /// An 8 byte little endian array - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe static byte[] UInt64ToBytes(ulong value) - { - return Int64ToBytes((long)value); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static byte[] UInt64ToBytesBig(ulong value) - { - return Int64ToBytesBig((long)value); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe static void UInt64ToBytes(ulong value, byte[] dest, int pos) - { - Int64ToBytes((long)value, dest, pos); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe static void UInt64ToBytesSafepos(ulong value, byte[] dest, int pos) - { - Int64ToBytesSafepos((long)value, dest, pos); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void UInt64ToBytesBig(ulong value, byte[] dest, int pos) - { - Int64ToBytesBig((long) value, dest, pos); - } - - /// - /// Convert a floating point value to four bytes in little endian - /// ordering - /// - /// A floating point value - /// A four byte array containing the value in little endian - /// ordering - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe static byte[] FloatToBytes(float value) - { - return IntToBytes(*(int*)&value); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe static void FloatToBytes(Stream ms, float value) - { - IntToBytes(ms, *(int*)&value); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe static void FloatToBytes(float value, byte[] dest, int pos) - { - IntToBytes(*(int*)&value, dest, pos); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe static void FloatToBytes(float value, byte* dest) - { - IntToBytes(*(int*)&value, dest); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe static void FloatToBytesSafepos(float value, byte[] dest, int pos) - { - IntToBytesSafepos(*(int*)&value, dest, pos); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe static byte[] DoubleToBytes(double value) - { - return Int64ToBytes(*(long*)&value); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe static void DoubleToBytes(Stream ms, float value) - { - Int64ToBytes(ms, *(long*)&value); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe static byte[] DoubleToBytesBig(double value) - { - return Int64ToBytesBig(*(long*)&value); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe static void DoubleToBytes(double value, byte[] dest, int pos) - { - Int64ToBytes(*(long*)&value, dest, pos); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe static void DoubleToBytes(double value, byte* dest) - { - Int64ToBytes(*(long*)&value, dest); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe static void DoubleToBytesSafepos(double value, byte[] dest, int pos) - { - Int64ToBytesSafepos(*(long*)&value, dest, pos); - } - - #endregion ToBytes - - #region Strings - - /// - /// Converts an unsigned integer to a hexadecimal string - /// - /// An unsigned integer to convert to a string - /// A hexadecimal string 10 characters long - /// 0x7fffffff - public static string UIntToHexString(uint i) - { - return string.Format("{0:x8}", i); - } - - /// - /// Convert a variable length UTF8 byte array to a string - /// - /// The UTF8 encoded byte array to convert - /// The decoded string - public static string BytesToString(byte[] bytes) - { - if(bytes.Length <= 0) - return string.Empty; - if (bytes[bytes.Length - 1] == 0x00) - return Encoding.UTF8.GetString(bytes, 0, bytes.Length - 1); - else - return Encoding.UTF8.GetString(bytes, 0, bytes.Length); - } - - public static string BytesToString(byte[] bytes, int index, int count) - { - if (bytes.Length <= index + count) - return string.Empty; - if (bytes[index + count - 1] == 0x00) - return Encoding.UTF8.GetString(bytes, index, count - 1); - else - return Encoding.UTF8.GetString(bytes, index, count); - } - - private static string GetString(byte[] bytes, int index, int count) - { - return Encoding.UTF8.GetString(bytes, index, count); - } - - /// - /// Converts a byte array to a string containing hexadecimal characters - /// - /// The byte array to convert to a string - /// The name of the field to prepend to each - /// line of the string - /// A string containing hexadecimal characters on multiple - /// lines. Each line is prepended with the field name - public static string BytesToHexString(byte[] bytes, string fieldName) - { - return BytesToHexString(bytes, bytes.Length, fieldName); - } - - /// - /// Converts a byte array to a string containing hexadecimal characters - /// - /// The byte array to convert to a string - /// Number of bytes in the array to parse - /// A string to prepend to each line of the hex - /// dump - /// A string containing hexadecimal characters on multiple - /// lines. Each line is prepended with the field name - public static string BytesToHexString(byte[] bytes, int length, string fieldName) - { - StringBuilder output = new StringBuilder(); - - for (int i = 0; i < length; i += 16) - { - if (i != 0) - output.Append('\n'); - - if (!String.IsNullOrEmpty(fieldName)) - { - output.Append(fieldName); - output.Append(": "); - } - - for (int j = 0, k = i; j < 16; ++j,++k) - { - if(k >= length) - break; - - if (j != 0) - output.Append(' '); - - output.Append(String.Format("{0:X2}", bytes[k])); - } - } - - return output.ToString(); - } - - /// - /// Convert a string to a UTF8 encoded byte array - /// - /// The string to convert - /// A null-terminated UTF8 byte array - public static byte[] StringToBytes(string str) - { - if (string.IsNullOrEmpty(str)) - return EmptyBytes; - - int nbytes = osUTF8GetBytesCount(str, out int sourcelen); - if (nbytes == 0) - return EmptyBytes; - byte[] dstarray = new byte[nbytes + 1]; - osUTF8Getbytes(str, sourcelen, dstarray, nbytes); - dstarray[nbytes] = 0; - return dstarray; - } - - public static byte[] StringToBytes(string str, int maxlen) - { - if (string.IsNullOrEmpty(str)) - return EmptyBytes; - - int nbytes = osUTF8GetBytesCount(str, maxlen -1, out int sourcelen); - if (nbytes == 0) - return EmptyBytes; - byte[] dstarray = new byte[nbytes + 1]; - osUTF8Getbytes(str, sourcelen, dstarray, nbytes); - dstarray[nbytes] = 0; - return dstarray; - } - - public static byte[] StringToBytesNoTerm(string str) - { - if (string.IsNullOrEmpty(str)) - return EmptyBytes; - - int nbytes = osUTF8GetBytesCount(str, out int sourcelen); - if (nbytes == 0) - return EmptyBytes; - byte[] dstarray = new byte[nbytes]; - osUTF8Getbytes(str, sourcelen, dstarray, nbytes); - return dstarray; - } - - public static byte[] StringToBytesNoTerm(string str, int maxlen) - { - if (string.IsNullOrEmpty(str)) - return EmptyBytes; - - int nbytes = osUTF8GetBytesCount(str, maxlen, out int sourcelen); - if (nbytes == 0) - return EmptyBytes; - byte[] dstarray = new byte[nbytes]; - osUTF8Getbytes(str, sourcelen, dstarray, nbytes); - return dstarray; - } - - public static unsafe int osUTF8Getbytes(string source, int srclenght, byte[] destiny, int maxdstlen) - { - int ret = 0; - char c; - fixed(char* srcarray = source) - { - fixed(byte* dstarray = destiny) - { - char* src = srcarray; - char* srcend = src + srclenght; - char* srcend1 = srcend - 1; - - byte* dst = dstarray; - byte* dstend = dst + maxdstlen; - byte* dstend2 = dstend - 2; - byte* dstend3 = dstend - 3; - byte* dstend4 = dstend - 4; - - while (src < srcend && dst < dstend) - { - c = *src++; - if(c == 0) - break; - - if (c <= 0x7f) - { - *dst++ = (byte)c; - continue; - } - - if (c < 0x800) - { - if (dst > dstend2) - break; - - *dst++ = (byte)(0xC0 | (c >> 6)); - *dst++ = (byte)(0x80 | (c & 0x3F)); - continue; - } - - if (c >= 0xD800 && c < 0xE000) - { - if (c >= 0xDC00) - continue; // ignore invalid - if (src > srcend1 || dst > dstend4) - break; - - int a = c; - - c = *src++; - - if (c < 0xDC00 || c > 0xDFFF) - continue; // ignore invalid - - a = (a << 10) + c - 0x35fdc00; - - *dst++ = (byte)(0xF0 | (a >> 18)); - *dst++ = (byte)(0x80 | ((a >> 12) & 0x3f)); - *dst++ = (byte)(0x80 | ((a >> 6) & 0x3f)); - *dst++ = (byte)(0x80 | (a & 0x3f)); - continue; - } - if (dst > dstend3) - break; - - *dst++ = (byte)(0xE0 | (c >> 12)); - *dst++ = (byte)(0x80 | ((c >> 6) & 0x3f)); - *dst++ = (byte)(0x80 | (c & 0x3f)); - } - ret = (int)(dst - dstarray); - } - } - return ret; - } - - public static unsafe bool osUTF8TryGetbytes(string srcstr, ref int srcstart, byte[] dstarray, ref int pos) - { - if (string.IsNullOrEmpty(srcstr)) - return true; - - bool ret = false; - int free = dstarray.Length - pos; - fixed (char* srcbase = srcstr) - { - fixed (byte* dstbase = dstarray) - { - char* src = srcbase + srcstart; - char* srcend = srcbase + srcstr.Length; - char* srcend1 = srcend - 1; - byte* dst = dstbase + pos; - - char c; - while (src < srcend && free > 0) - { - c = *src++; - if(c == 0) - break; - - if (c <= 0x7f) - { - *dst++ = (byte)c; - --free; - continue; - } - - if (c < 0x800) - { - free -= 2; - if (free <= 0) - { - --src; - break; - } - *dst++ = (byte)(0xC0 | (c >> 6)); - *dst++ = (byte)(0x80 | (c & 0x3F)); - continue; - } - - if (c >= 0xD800 && c < 0xE000) - { - if (c >= 0xDC00) - continue; // ignore invalid - if (src > srcend1) - break; - - int a = c; - c = *src++; - - if (c < 0xDC00 || c > 0xDFFF) - continue; // ignore invalid - - free -= 4; - if (free <= 0) - { - src -= 2; - break; - } - - a = (a << 10) + c - 0x35fdc00; - - *dst++ = (byte)(0xF0 | (a >> 18)); - *dst++ = (byte)(0x80 | ((a >> 12) & 0x3f)); - *dst++ = (byte)(0x80 | ((a >> 6) & 0x3f)); - *dst++ = (byte)(0x80 | (a & 0x3f)); - continue; - } - - free -= 3; - if (free <= 0) - { - --src; - break; - } - - *dst++ = (byte)(0xE0 | (c >> 12)); - *dst++ = (byte)(0x80 | ((c >> 6) & 0x3f)); - *dst++ = (byte)(0x80 | (c & 0x3f)); - } - - pos = (int)(dst - dstbase); - srcstart = (int)(src - srcbase); - if (src == srcend) - ret = true; - } - } - return ret; - } - - public static int osUTF8GetBytesCount(string str, out int maxsource) - { - maxsource = 0; - char c; - char lastc = (char)0; - int nbytes = 0; - int i = 0; - while(i < str.Length) - { - c = str[i++]; - - if (c <= 0x7f) - { - lastc = c; - ++nbytes; - continue; - } - - if (c < 0x800) - { - lastc = c; - nbytes += 2; - continue; - } - - if (c >= 0xD800 && c < 0xE000) - { - if (c < 0xDC00 || c > 0xDFFF) - continue; - lastc = c; - nbytes += 4; - ++i; - continue; - } - lastc = c; - nbytes += 3; - } - - if (i > 0 && lastc == 0) - { - --nbytes; - --i; - } - maxsource = i; - return nbytes; - } - - public static int osUTF8GetBytesCount(string str, int maxnbytes, out int maxsourcelen) - { - maxsourcelen = 0; - int max2 = maxnbytes - 2; - int max3 = maxnbytes - 3; - int max4 = maxnbytes - 4; - - char c = ' '; - int nbytes = 0; - int i = 0; - while(i < str.Length && nbytes < maxnbytes) - { - c = str[i++]; - if(c == 0) - break; - - if (c <= 0x7f) - { - ++nbytes; - continue; - } - - if (c < 0x800) - { - if (nbytes > max2) - break; - nbytes += 2; - continue; - } - - if (c >= 0xD800 && c < 0xE000) - { - if (c < 0xDC00 || c > 0xDFFF) - continue; - if (nbytes > max4) - break; - nbytes += 4; - ++i; - continue; - } - if (nbytes > max3) - break; - nbytes += 3; - } - - maxsourcelen = i; - return nbytes; - } - - /// - /// Converts a string containing hexadecimal characters to a byte array - /// - /// String containing hexadecimal characters - /// If true, gracefully handles null, empty and - /// uneven strings as well as stripping unconvertable characters - /// The converted byte array - public static byte[] HexStringToBytes(string hexString, bool handleDirty) - { - if (handleDirty) - { - if (String.IsNullOrEmpty(hexString)) - return Utils.EmptyBytes; - - StringBuilder stripped = new StringBuilder(hexString.Length); - char c; - - // remove all non A-F, 0-9, characters - for (int i = 0; i < hexString.Length; i++) - { - c = hexString[i]; - if (IsHexDigit(c)) - stripped.Append(c); - } - - hexString = stripped.ToString(); - - // if odd number of characters, discard last character - if (hexString.Length % 2 != 0) - { - hexString = hexString.Substring(0, hexString.Length - 1); - } - } - - int byteLength = hexString.Length / 2; - byte[] bytes = new byte[byteLength]; - int j = 0; - - for (int i = 0; i < bytes.Length; i++) - { - bytes[i] = HexToByte(hexString.Substring(j, 2)); - j += 2; - } - - return bytes; - } - - /// - /// Returns true is c is a hexadecimal digit (A-F, a-f, 0-9) - /// - /// Character to test - /// true if hex digit, false if not - public static bool IsHexDigit(Char c) - { - - const int numA = 65; - const int numa = 97; - const int num0 = 48; - - if(c > numa + 5) - return false; - if (c < num0) - return false; - if (c < (num0 + 10)) - return true; - - if (c >= numa) - return true; - - if (c >= numA && c < numA + 6) - return true; - - return false; - } - - public static int HexNibbleWithChk(Char c) - { - const int numA = 65; - const int numa = 97; - const int num0 = 48; - - if (c > numa + 5) - return -1; - if (c < num0) - return -1; - if (c < (num0 + 10)) - return c - num0; - - if (c >= numa) - return c - numa + 10; - - if (c >= numA && c < numA + 6) - return c - numA + 10; - - return -1; - } - - public static int HexNibbleWithChk(byte c) - { - const int numA = 65; - const int numa = 97; - const int num0 = 48; - - if (c > numa + 5) - return -1; - if (c < num0) - return -1; - if (c < (num0 + 10)) - return c - num0; - - if (c >= numa) - return c - numa + 10; - - if (c >= numA && c < numA + 6) - return c - numA + 10; - - return -1; - } - - public static int HexNibble(Char c) - { - - const int numA = 65; - const int numa = 97; - const int num0 = 48; - - if (c > numa + 5) - return 0; - if (c < num0) - return 0; - if (c < (num0 + 10)) - return c - num0; - - if (c >= numa) - return c - numa + 10; - - if (c >= numA && c < numA + 6) - return c - numA + 10; - - return 0; - } - - public static bool TryHexToInt(byte[] data, int start, int len, out int res) - { - res = 0; - int n; - if(len > 8) - return false; - for (int i = start; i < start + len; ++i) - { - if ((n = HexNibbleWithChk(data[i])) < 0) - return false; - res *= 16; - res |= n; - } - return true; - } - /// - /// Converts 1 or 2 character string into equivalant byte value - /// - /// 1 or 2 character string - /// byte - private static byte HexToByte(string hex) - { - if (hex.Length > 2 || hex.Length <= 0) - throw new ArgumentException("hex must be 1 or 2 characters in length"); - byte newByte = Byte.Parse(hex, System.Globalization.NumberStyles.HexNumber); - return newByte; - } - - #endregion Strings - - #region Packed Values - - /// - /// Convert a float value to a byte given a minimum and maximum range - /// - /// Value to convert to a byte - /// Minimum value range - /// Maximum value range - /// A single byte representing the original float value - public static byte FloatToByte(float val, float lower, float upper) - { - val -= lower; - if (val <= 0) - return 0; - - val /= (upper - lower); - if (val >= 1.0f) - return 255; - - return (byte)(255 * val); - } - - /// - /// Convert a byte to a float value given a minimum and maximum range - /// - /// Byte array to get the byte from - /// Position in the byte array the desired byte is at - /// Minimum value range - /// Maximum value range - /// A float value inclusively between lower and upper - public static float ByteToFloat(byte[] bytes, int pos, float lower, float upper) - { - if (bytes.Length <= pos) return 0; - return ByteToFloat(bytes[pos], lower, upper); - } - - /// - /// Convert a byte to a float value given a minimum and maximum range - /// - /// Byte to convert to a float value - /// Minimum value range - /// Maximum value range - /// A float value inclusively between lower and upper - public static float ByteToFloat(byte val, float lower, float upper) - { - float delta = (upper - lower) * 0.00392157f; - float fval = val * delta; - fval += lower; - - // Test for values very close to zero - if (Math.Abs(fval) < delta) - fval = 0.0f; - - return fval; - } - - public static float BytesUInt16ToFloat(byte[] bytes, int pos, float lower, float upper) - { - ushort val = BytesToUInt16(bytes, pos); - return UInt16ToFloat(val, lower, upper); - } - - public static float UInt16ToFloat(ushort val, float lower, float upper) - { - const float ONE_OVER_U16_MAX = 1.0f / UInt16.MaxValue; - - float delta = (upper - lower) * ONE_OVER_U16_MAX; - float fval = val * delta; - fval += lower; - - if (Math.Abs(fval) < delta) - fval = 0.0f; - - return fval; - } - - public static ushort FloatToUInt16(float value, float lower, float upper) - { - value -= lower; - if (value <= 0) - return 0; - - value /= upper - lower; - if (value >= 1.0f) - return 0xffff; - - return (ushort)(value * 0xffff); - } - - public static ushort FloatToUInt16(float value, float range) - { - value += range; - if (value <= 0) - return 0; - - value /= range; - if (value >= 2.0f) - return 0xffff; - - return (ushort)(value * 32767.5); - } - - public static void FloatToUInt16Bytes(float value, float range, byte[] dest, int pos) - { - value += range; - if (value <= 0) - { - dest[pos] = 0; - dest[pos + 1] = 0; - return; - } - - value /= range; - if (value >= 2.0f) - { - dest[pos] = 0xff; - dest[pos + 1] = 0xff; - return; - } - - ushort s = (ushort)(value * 32767.5); - dest[pos] = (byte)s; - dest[pos + 1] = (byte)(s >> 8); - } - - public static byte[] FloatToUInt16Bytes(float value, float range) - { - byte[] dest = new byte[2]; - - value += range; - if (value <= 0) - { - dest[0] = 0; - dest[1] = 0; - return dest; - } - - value /= range; - if (value >= 2.0f) - { - dest[0] = 0xff; - dest[1] = 0xff; - return dest; - } - - ushort s = (ushort)(value * 32767.5); - dest[0] = (byte)s; - dest[1] = (byte)(s >> 8); - return dest; - } - - #endregion Packed Values - - #region TryParse - - /// - /// Attempts to parse a floating point value from a string, using an - /// EN-US number format - /// - /// String to parse - /// Resulting floating point number - /// True if the parse was successful, otherwise false - public static bool TryParseSingle(string s, out float result) - { - return Single.TryParse(s, System.Globalization.NumberStyles.Float, EnUsCulture.NumberFormat, out result); - } - - /// - /// Attempts to parse a floating point value from a string, using an - /// EN-US number format - /// - /// String to parse - /// Resulting floating point number - /// True if the parse was successful, otherwise false - public static bool TryParseDouble(string s, out double result) - { - // NOTE: Double.TryParse can't parse Double.[Min/Max]Value.ToString(), see: - // http://blogs.msdn.com/bclteam/archive/2006/05/24/598169.aspx - return Double.TryParse(s, System.Globalization.NumberStyles.Float, EnUsCulture.NumberFormat, out result); - } - - /// - /// Tries to parse an unsigned 32-bit integer from a hexadecimal string - /// - /// String to parse - /// Resulting integer - /// True if the parse was successful, otherwise false - public static bool TryParseHex(string s, out uint result) - { - return UInt32.TryParse(s, System.Globalization.NumberStyles.HexNumber, EnUsCulture.NumberFormat, out result); - } - - #endregion TryParse - - #region Enum String Conversion - - /// - /// Returns text specified in EnumInfo attribute of the enumerator - /// To add the text use [EnumInfo(Text = "Some nice text here")] before declaration - /// of enum values - /// - /// Enum value - /// Text representation of the enum - public static string EnumToText(Enum value) - { - // Get the type - Type type = value.GetType(); - - // Get fieldinfo for this type - FieldInfo fieldInfo = type.GetField(value.ToString()); - - // Find extended attributes, if any - EnumInfoAttribute[] attribs = (EnumInfoAttribute[])fieldInfo.GetCustomAttributes(typeof(EnumInfoAttribute), false); - - return attribs.Length > 0 ? attribs[0].Text : value.ToString(); - } - - /// - /// Takes an AssetType and returns the string representation - /// - /// The source - /// The string version of the AssetType - public static string AssetTypeToString(AssetType type) - { - return _AssetTypeNames[(int)type]; - } - - /// - /// Translate a string name of an AssetType into the proper Type - /// - /// A string containing the AssetType name - /// The AssetType which matches the string name, or AssetType.Unknown if no match was found - public static AssetType StringToAssetType(string type) - { - for (int i = 0; i < _AssetTypeNames.Length; i++) - { - if (_AssetTypeNames[i] == type) - return (AssetType)i; - } - - return AssetType.Unknown; - } - - /// - /// Takes a FolderType and returns the string representation - /// - /// The source - /// The string version of the FolderType - public static string FolderTypeToString(FolderType type) - { - return _FolderTypeNames[(int)type]; - } - - /// - /// Translate a string name of an FolderType into the proper Type - /// - /// A string containing the FolderType name - /// The FolderType which matches the string name, or FolderType. None if no match was found - public static FolderType StringToFolderType(string type) - { - for (int i = 0; i < _FolderTypeNames.Length; i++) - { - if (_FolderTypeNames[i] == type) - return (FolderType)i; - } - - return FolderType.None; - } - - /// - /// Convert an InventoryType to a string - /// - /// The to convert - /// A string representation of the source - public static string InventoryTypeToString(InventoryType type) - { - return _InventoryTypeNames[(int)type]; - } - - /// - /// Convert a string into a valid InventoryType - /// - /// A string representation of the InventoryType to convert - /// A InventoryType object which matched the type - public static InventoryType StringToInventoryType(string type) - { - for (int i = 0; i < _InventoryTypeNames.Length; i++) - { - if (_InventoryTypeNames[i] == type) - return (InventoryType)i; - } - - return InventoryType.Unknown; - } - - /// - /// Convert a SaleType to a string - /// - /// The to convert - /// A string representation of the source - public static string SaleTypeToString(SaleType type) - { - return _SaleTypeNames[(int)type]; - } - - /// - /// Convert a string into a valid SaleType - /// - /// A string representation of the SaleType to convert - /// A SaleType object which matched the type - public static SaleType StringToSaleType(string value) - { - for (int i = 0; i < _SaleTypeNames.Length; i++) - { - if (value == _SaleTypeNames[i]) - return (SaleType)i; - } - - return SaleType.Not; - } - - /// - /// Converts a string used in LLSD to AttachmentPoint type - /// - /// String representation of AttachmentPoint to convert - /// AttachmentPoint enum - public static AttachmentPoint StringToAttachmentPoint(string value) - { - for (int i = 0; i < _AttachmentPointNames.Length; i++) - { - if (value == _AttachmentPointNames[i]) - return (AttachmentPoint)i; - } - - return AttachmentPoint.Default; - } - - #endregion Enum String Conversion - - #region Miscellaneous - - /// - /// Copy a byte array - /// - /// Byte array to copy - /// A copy of the given byte array - public static byte[] CopyBytes(byte[] bytes) - { - if (bytes == null) - return null; - - byte[] newBytes = new byte[bytes.Length]; - Buffer.BlockCopy(bytes, 0, newBytes, 0, bytes.Length); - return newBytes; - } - - /// - /// Packs to 32-bit unsigned integers in to a 64-bit unsigned integer - /// - /// The left-hand (or X) value - /// The right-hand (or Y) value - /// A 64-bit integer containing the two 32-bit input values - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static ulong UIntsToLong(uint a, uint b) - { - return ((ulong)a << 32) | (ulong)b; - } - - /// - /// Unpacks two 32-bit unsigned integers from a 64-bit unsigned integer - /// - /// The 64-bit input integer - /// The left-hand (or X) output value - /// The right-hand (or Y) output value - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void LongToUInts(ulong a, out uint b, out uint c) - { - b = (uint)(a >> 32); - c = (uint)(a & 0x00000000FFFFFFFF); - } - - /// - /// Convert an IP address object to an unsigned 32-bit integer - /// - /// IP address to convert - /// 32-bit unsigned integer holding the IP address bits - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static uint IPToUInt(System.Net.IPAddress address) - { - byte[] bytes = address.GetAddressBytes(); - return (uint)((bytes[3] << 24) + (bytes[2] << 16) + (bytes[1] << 8) + bytes[0]); - } - - /// - /// Gets a unix timestamp for the current time - /// - /// An unsigned integer representing a unix timestamp for now - public static uint GetUnixTime() - { - return (uint)(DateTime.UtcNow - Epoch).TotalSeconds; - } - - /// - /// Convert a UNIX timestamp to a native DateTime object - /// - /// An unsigned integer representing a UNIX - /// timestamp - /// A DateTime object containing the same time specified in - /// the given timestamp - public static DateTime UnixTimeToDateTime(uint timestamp) - { - DateTime dateTime = Epoch; - - // Add the number of seconds in our UNIX timestamp - dateTime = dateTime.AddSeconds(timestamp); - - return dateTime; - } - - /// - /// Convert a UNIX timestamp to a native DateTime object - /// - /// A signed integer representing a UNIX - /// timestamp - /// A DateTime object containing the same time specified in - /// the given timestamp - public static DateTime UnixTimeToDateTime(int timestamp) - { - return UnixTimeToDateTime((uint)timestamp); - } - - /// - /// Convert a native DateTime object to a UNIX timestamp - /// - /// A DateTime object you want to convert to a - /// timestamp - /// An unsigned integer representing a UNIX timestamp - public static uint DateTimeToUnixTime(DateTime time) - { - TimeSpan ts = (time - new DateTime(1970, 1, 1, 0, 0, 0)); - return (uint)ts.TotalSeconds; - } - - /// - /// Swap two values - /// - /// Type of the values to swap - /// First value - /// Second value - public static void Swap(ref T lhs, ref T rhs) - { - T temp = lhs; - lhs = rhs; - rhs = temp; - } - - /// - /// Try to parse an enumeration value from a string - /// - /// Enumeration type - /// String value to parse - /// Enumeration value on success - /// True if the parsing succeeded, otherwise false - public static bool EnumTryParse(string strType, out T result) - { - Type t = typeof(T); - - if (Enum.IsDefined(t, strType)) - { - result = (T)Enum.Parse(t, strType, true); - return true; - } - else - { - foreach (string value in Enum.GetNames(typeof(T))) - { - if (value.Equals(strType, StringComparison.OrdinalIgnoreCase)) - { - result = (T)Enum.Parse(typeof(T), value); - return true; - } - } - result = default(T); - return false; - } - } - - /// - /// Swaps the high and low nibbles in a byte. Converts aaaabbbb to bbbbaaaa - /// - /// Byte to swap the words in - /// Byte value with the words swapped - public static byte SwapNibbles(byte value) - { - return (byte)(((value & 0xF0) >> 4) | ((value & 0x0F) << 4)); - } - - /// - /// Attempts to convert a string representation of a hostname or IP - /// address to a - /// - /// Hostname to convert to an IPAddress - /// Converted IP address object, or null if the conversion - /// failed - public static IPAddress HostnameToIPv4(string hostname) - { - // Is it already a valid IP? - IPAddress ip; - if (IPAddress.TryParse(hostname, out ip)) - return ip; - - IPAddress[] hosts = Dns.GetHostEntry(hostname).AddressList; - - for (int i = 0; i < hosts.Length; i++) - { - IPAddress host = hosts[i]; - - if (host.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) - return host; - } - - return null; - } - - private const byte ASCIIzero = (byte)'0'; - private const byte ASCIIminus = (byte)'-'; - - private static unsafe int UintToStrBytes_reversed(uint value, byte* dst) - { - int n = 0; - do - { - byte a = ASCIIzero; - a += (byte)(value % 10); - dst[n] = a; - ++n; - value /= 10; - } - while(value > 0); - return n; - } - - private static unsafe int ULongToStrBytes_reversed(ulong value, byte* dst) - { - int n = 0; - do - { - byte a = ASCIIzero; - a += (byte)(value % 10); - dst[n] = a; - ++n; - value /= 10; - } - while (value > 0); - return n; - } - - public static unsafe int UIntToByteString(uint value, byte* dst) - { - if (value == 0) - { - *dst = ASCIIzero; - return 1; - } - - byte* tmp = stackalloc byte[16]; - int n = UintToStrBytes_reversed(value, tmp); - for (int i = 0, j = n - 1; i < n; ++i, --j) - dst[i] = tmp[j]; - return n; - } - - public static unsafe int ULongToByteString(ulong value, byte* dst) - { - if (value == 0) - { - *dst = ASCIIzero; - return 1; - } - - byte* tmp = stackalloc byte[32]; - int n = ULongToStrBytes_reversed(value, tmp); - for (int i = 0, j = n - 1; i < n; ++i, --j) - dst[i] = tmp[j]; - return n; - } - - public static unsafe int UIntToByteString(uint value, Stream st) - { - if (value == 0) - { - st.WriteByte(ASCIIzero); - return 1; - } - - byte* tmp = stackalloc byte[32]; - int n = UintToStrBytes_reversed(value, tmp); - for (int j = n - 1; j <= 0; --j) - st.WriteByte(tmp[j]); - return n; - } - - public static unsafe int ULongToByteString(ulong value, Stream st) - { - if (value == 0) - { - st.WriteByte(ASCIIzero); - return 1; - } - - byte* tmp = stackalloc byte[32]; - int n = ULongToStrBytes_reversed(value, tmp); - for (int j = n - 1; j <= 0; --j) - st.WriteByte(tmp[j]); - return n; - } - - public static unsafe int UIntToByteString(uint value, byte[] dst, int pos) - { - if (value == 0) - { - dst[pos] = ASCIIzero; - return 1; - } - - fixed (byte* d = &dst[pos]) - { - return UIntToByteString(value, d); - } - } - - public static unsafe int ULongToByteString(ulong value, byte[] dst, int pos) - { - if (value == 0) - { - dst[pos] = ASCIIzero; - return 1; - } - - fixed (byte* d = &dst[pos]) - { - return ULongToByteString(value, d); - } - } - - public static unsafe int IntToByteString(int value, byte* dst) - { - if (value == 0) - { - *dst = ASCIIzero; - return 1; - } - - byte* tmp = stackalloc byte[16]; - int n; - if (value > 0) - { - n = UintToStrBytes_reversed((uint)value, tmp); - for (int i = 0, j = n - 1; i < n; ++i, --j) - dst[i] = tmp[j]; - } - else - { - dst[0] = ASCIIminus; - n = UintToStrBytes_reversed((uint)(-value), tmp); - for (int i = 1, j = n - 1; i < n + 1; ++i, --j) - dst[i] = tmp[j]; - ++n; - } - return n; - } - - public static unsafe int LongToByteString(long value, byte* dst) - { - if (value == 0) - { - *dst = ASCIIzero; - return 1; - } - - byte* tmp = stackalloc byte[32]; - int n; - if (value > 0) - { - n = ULongToStrBytes_reversed((ulong)value, tmp); - for (int i = 0, j = n - 1; i < n; ++i, --j) - dst[i] = tmp[j]; - } - else - { - dst[0] = ASCIIminus; - n = ULongToStrBytes_reversed((ulong)(-value), tmp); - for (int i = 1, j = n - 1; i < n + 1; ++i, --j) - dst[i] = tmp[j]; - ++n; - } - return n; - } - - public static unsafe int IntToByteString(int value, Stream st) - { - if (value == 0) - { - st.WriteByte(ASCIIzero); - return 1; - } - - byte* tmp = stackalloc byte[32]; - int n; - if (value > 0) - { - n = UintToStrBytes_reversed((uint)value, tmp); - for (int j = n - 1; j >= 0; --j) - st.WriteByte(tmp[j]); - } - else - { - st.WriteByte(ASCIIminus); - n = UintToStrBytes_reversed((uint)(-value), tmp); - for (int j = n - 1; j >= 0; --j) - st.WriteByte(tmp[j]); - ++n; - } - return n; - } - - public static unsafe int LongToByteString(long value, Stream st) - { - if (value == 0) - { - st.WriteByte(ASCIIzero); - return 1; - } - - byte* tmp = stackalloc byte[32]; - int n; - if (value > 0) - { - n = ULongToStrBytes_reversed((ulong)value, tmp); - for (int j = n - 1; j >= 0; --j) - st.WriteByte(tmp[j]); - } - else - { - st.WriteByte(ASCIIminus); - n = ULongToStrBytes_reversed((ulong)(-value), tmp); - for (int j = n - 1; j >= 0; --j) - st.WriteByte(tmp[j]); - ++n; - } - return n; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe int IntToByteString(int value, byte[] dst, int pos) - { - if (value == 0) - { - dst[pos] = ASCIIzero; - return 1; - } - - fixed (byte* d = &dst[pos]) - { - return IntToByteString(value, d); - } - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe int LongToByteString(long value, byte[] dst, int pos) - { - if (value == 0) - { - dst[pos] = ASCIIzero; - return 1; - } - - fixed (byte* d = &dst[pos]) - { - return LongToByteString(value, d); - } - } - - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe osUTF8 IntToosUTF8(int v) - { - osUTF8 ret = new osUTF8(16); - fixed (byte* d = ret.m_data) - ret.m_len = IntToByteString(v, d); - return ret; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe osUTF8 UIntToosUTF8(uint v) - { - osUTF8 ret = new osUTF8(16); - fixed (byte* d = ret.m_data) - ret.m_len = UIntToByteString(v, d); - return ret; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe osUTF8 LongToosUTF8(long v) - { - osUTF8 ret = new osUTF8(32); - fixed (byte* d = ret.m_data) - ret.m_len = LongToByteString(v, d); - return ret; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe osUTF8 ULongToosUTF8(ulong v) - { - osUTF8 ret = new osUTF8(32); - fixed (byte* d = ret.m_data) - ret.m_len = ULongToByteString(v, d); - return ret; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static byte LowNibbleToHexByteChar(byte b) - { - b &= 0x0f; - return (byte)(b > 9 ? b + 0x57 : b + ASCIIzero); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static byte HighNibbleToHexByteChar(byte b) - { - b >>= 4; - return (byte)(b > 9 ? b + 0x57 : b + ASCIIzero); - } - - public static unsafe void UUIDToByteDashString(UUID u, byte* dst) - { - byte[] bytes = u.Guid.ToByteArray(); - //a - byte b = bytes[3]; - *dst++ = HighNibbleToHexByteChar(b); - *dst++ = LowNibbleToHexByteChar(b); - b = bytes[2]; - *dst++ = HighNibbleToHexByteChar(b); - *dst++ = LowNibbleToHexByteChar(b); - b = bytes[1]; - *dst++ = HighNibbleToHexByteChar(b); - *dst++ = LowNibbleToHexByteChar(b); - b = bytes[0]; - *dst++ = HighNibbleToHexByteChar(b); - *dst++ = LowNibbleToHexByteChar(b); - - *dst++ = ASCIIminus; - //b - b = bytes[5]; - *dst++ = HighNibbleToHexByteChar(b); - *dst++ = LowNibbleToHexByteChar(b); - b = bytes[4]; - *dst++ = HighNibbleToHexByteChar(b); - *dst++ = LowNibbleToHexByteChar(b); - - *dst++ = ASCIIminus; - - //c - b = bytes[7]; - *dst++ = HighNibbleToHexByteChar(b); - *dst++ = LowNibbleToHexByteChar(b); - b = bytes[6]; - *dst++ = HighNibbleToHexByteChar(b); - *dst++ = LowNibbleToHexByteChar(b); - - *dst++ = ASCIIminus; - - b = bytes[8]; //d - *dst++ = HighNibbleToHexByteChar(b); - *dst++ = LowNibbleToHexByteChar(b); - b = bytes[9]; //e - *dst++ = HighNibbleToHexByteChar(b); - *dst++ = LowNibbleToHexByteChar(b); - - *dst++ = ASCIIminus; - - b = bytes[10]; //f - *dst++ = HighNibbleToHexByteChar(b); - *dst++ = LowNibbleToHexByteChar(b); - b = bytes[11]; //g - *dst++ = HighNibbleToHexByteChar(b); - *dst++ = LowNibbleToHexByteChar(b); - b = bytes[12]; //h - *dst++ = HighNibbleToHexByteChar(b); - *dst++ = LowNibbleToHexByteChar(b); - b = bytes[13]; //i - *dst++ = HighNibbleToHexByteChar(b); - *dst++ = LowNibbleToHexByteChar(b); - b = bytes[14]; //j - *dst++ = HighNibbleToHexByteChar(b); - *dst++ = LowNibbleToHexByteChar(b); - b = bytes[15]; //k - *dst++ = HighNibbleToHexByteChar(b); - *dst = LowNibbleToHexByteChar(b); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe osUTF8 UUIDToosUTF8(UUID v) - { - osUTF8 ret = new osUTF8(36); - fixed (byte* d = ret.m_data) - UUIDToByteDashString(v, d); - ret.m_len = 36; - return ret; - } - #endregion Miscellaneous - } -} +/* + * Copyright (c) 2006-2016, openmetaverse.co + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * All rights reserved. + * + * - Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * - Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * - Neither the name of the openmetaverse.co nor the names + * of its contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Net; +using System.Text; +using System.Reflection; +using System.IO; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Runtime.Intrinsics.X86; +using System.Runtime.Intrinsics; + +namespace OpenMetaverse +{ + public static partial class Utils + { + public static readonly bool CanDirectCopyLE = CheckNeedAlignment(); + + [StructLayout(LayoutKind.Sequential, Size = 16, Pack = 1)] + public struct Bytes16 { } + + [StructLayout(LayoutKind.Sequential, Size = 12, Pack = 1)] + public struct Bytes12 { } + + [StructLayout(LayoutKind.Sequential, Size = 8, Pack = 1)] + public struct Bytes8 { } + + [StructLayout(LayoutKind.Sequential, Size = 6, Pack = 1)] + public struct Bytes6 { } + + public unsafe static bool CheckNeedAlignment() + { + if(!BitConverter.IsLittleEndian) + return false; + + byte[] bytes = new byte[4096]; + long ll = 0x55AA33EE55FFCCAA; + long l; + try + { + for (int i = 0; i < 512; i += 3) + { + fixed (byte* ptr = &bytes[253 + i]) + *(long*)ptr = ll; + + fixed (byte* ptr = &bytes[1027 + i]) + { + byte* p = ptr; + *p++ = (byte)ll; + *p++ = (byte)(ll >> 8); + *p++ = (byte)(ll >> 16); + *p++ = (byte)(ll >> 24); + *p++ = (byte)(ll >> 32); + *p++ = (byte)(ll >> 40); + *p++ = (byte)(ll >> 48); + *p = (byte)(ll >> 56); + } + + fixed (byte* ptr = &bytes[253 + i]) + l = *(long*)ptr; + if (l != ll) + return false; + + fixed (byte* ptr = &bytes[1027 + i]) + l = *(long*)ptr; + if (l != ll) + return false; + } + return true; + } + catch { } + return false; + + } + + #region String Arrays + + private static readonly string[] _AssetTypeNames = new string[] + { + "texture", // 0 + "sound", // 1 + "callcard", // 2 + "landmark", // 3 + "script", // 4 + "clothing", // 5 + "object", // 6 + "notecard", // 7 + "category", // 8 + string.Empty, // 9 + "lsltext", // 10 + "lslbyte", // 11 + "txtr_tga", // 12 + "bodypart", // 13 + string.Empty, // 14 + string.Empty, // 15 + string.Empty, // 16 + "snd_wav", // 17 + "img_tga", // 18 + "jpeg", // 19 + "animatn", // 20 + "gesture", // 21 + "simstate", // 22 + string.Empty, // 23 + "link", // 24 + "link_f", // 25 + string.Empty, // 26 + string.Empty, // 27 + string.Empty, // 28 + string.Empty, // 29 + string.Empty, // 30 + string.Empty, // 31 + string.Empty, // 32 + string.Empty, // 33 + string.Empty, // 34 + string.Empty, // 35 + string.Empty, // 36 + string.Empty, // 37 + string.Empty, // 38 + string.Empty, // 39 + string.Empty, // 40 + string.Empty, // 41 + string.Empty, // 42 + string.Empty, // 43 + string.Empty, // 44 + string.Empty, // 45 + string.Empty, // 46 + string.Empty, // 47 + string.Empty, // 48 + "mesh", // 49 + string.Empty, // 50 + string.Empty, // 51 + string.Empty, // 52 + string.Empty, // 53 + string.Empty, // 54 + string.Empty, // 55 + "settings", // 56 + "material" // 57 + }; + + private static readonly string[] _FolderTypeNames = new string[] + { + "texture", // 0 + "sound", // 1 + "callcard", // 2 + "landmark", // 3 + string.Empty, // 4 + "clothing", // 5 + "object", // 6 + "notecard", // 7 + "root_inv", // 8 + string.Empty, // 9 + "lsltext", // 10 + string.Empty, // 11 + string.Empty, // 12 + "bodypart", // 13 + "trash", // 14 + "snapshot", // 15 + "lstndfnd", // 16 + string.Empty, // 17 + string.Empty, // 18 + string.Empty, // 19 + "animatn", // 20 + "gesture", // 21 + string.Empty, // 22 + "favorite", // 23 + string.Empty, // 24 + "settings", // 25 + "material", // 26 + "ensemble", // 27 + "ensemble", // 28 + "ensemble", // 29 + "ensemble", // 30 + "ensemble", // 31 + "ensemble", // 32 + "ensemble", // 33 + "ensemble", // 34 + "ensemble", // 35 + "ensemble", // 36 + "ensemble", // 37 + "ensemble", // 38 + "ensemble", // 39 + "ensemble", // 40 + "ensemble", // 41 + "ensemble", // 42 + "ensemble", // 43 + "ensemble", // 44 + "ensemble", // 45 + "current", // 46 + "outfit", // 47 + "my_otfts", // 48 + "mesh", // 49 + "inbox", // 50 + "outbox", // 51 + "basic_rt", // 52 + "merchant", // 53 + "stock", // 54 + }; + + private static readonly string[] _InventoryTypeNames = new string[] + { + "texture", // 0 + "sound", // 1 + "callcard", // 2 + "landmark", // 3 + string.Empty, // 4 + string.Empty, // 5 + "object", // 6 + "notecard", // 7 + "category", // 8 + "root", // 9 + "script", // 10 + string.Empty, // 11 + string.Empty, // 12 + string.Empty, // 13 + string.Empty, // 14 + "snapshot", // 15 + string.Empty, // 16 + "attach", // 17 + "wearable", // 18 + "animation", // 19 + "gesture", // 20 + string.Empty, // 21 + "mesh", // 22 + string.Empty, // 23 + string.Empty, // 24 + "settings", // 25 + "material", // 26 + }; + + private static readonly string[] _SaleTypeNames = new string[] + { + "not", + "orig", + "copy", + "cntn" + }; + + private static readonly string[] _AttachmentPointNames = new string[] + { + string.Empty, + "ATTACH_CHEST", + "ATTACH_HEAD", + "ATTACH_LSHOULDER", + "ATTACH_RSHOULDER", + "ATTACH_LHAND", + "ATTACH_RHAND", + "ATTACH_LFOOT", + "ATTACH_RFOOT", + "ATTACH_BACK", + "ATTACH_PELVIS", + "ATTACH_MOUTH", + "ATTACH_CHIN", + "ATTACH_LEAR", + "ATTACH_REAR", + "ATTACH_LEYE", + "ATTACH_REYE", + "ATTACH_NOSE", + "ATTACH_RUARM", + "ATTACH_RLARM", + "ATTACH_LUARM", + "ATTACH_LLARM", + "ATTACH_RHIP", + "ATTACH_RULEG", + "ATTACH_RLLEG", + "ATTACH_LHIP", + "ATTACH_LULEG", + "ATTACH_LLLEG", + "ATTACH_BELLY", + "ATTACH_LPEC", + "ATTACH_RPEC", + "ATTACH_HUD_CENTER_2", + "ATTACH_HUD_TOP_RIGHT", + "ATTACH_HUD_TOP_CENTER", + "ATTACH_HUD_TOP_LEFT", + "ATTACH_HUD_CENTER_1", + "ATTACH_HUD_BOTTOM_LEFT", + "ATTACH_HUD_BOTTOM", + "ATTACH_HUD_BOTTOM_RIGHT", + "ATTACH_NECK", + "ATTACH_AVATAR_CENTER", + "ATTACH_LHAND_RING1", + "ATTACH_RHAND_RING1", + "ATTACH_TAIL_BASE", + "ATTACH_TAIL_TIP", + "ATTACH_LWING", + "ATTACH_RWING", + "ATTACH_FACE_JAW", + "ATTACH_FACE_LEAR", + "ATTACH_FACE_REAR", + "ATTACH_FACE_LEYE", + "ATTACH_FACE_REYE", + "ATTACH_FACE_TONGUE", + "ATTACH_GROIN", + "ATTACH_HIND_LFOOT", + "ATTACH_HIND_RFOOT" + }; + + public static bool InternStrings = false; + + #endregion String Arrays + + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool ApproxEqual(float a, float b, float tolerance, float reltolerance = float.Epsilon) + { + float dif = MathF.Abs(a - b); + if (dif <= tolerance) + return true; + + a = MathF.Abs(a); + b = MathF.Abs(b); + if (b > a) + a = b; + return dif <= a * reltolerance; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool ApproxZero(float a, float tolerance) + { + return MathF.Abs(a) <= tolerance; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool ApproxZero(float a) + { + return MathF.Abs(a) <= 1e-6; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool ApproxEqual(float a, float b) + { + float dif = MathF.Abs(a - b); + if (dif <= 1e-6f) + return true; + + a = MathF.Abs(a); + b = MathF.Abs(b); + if (b > a) + a = b; + return dif <= a * float.Epsilon; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int CombineHash(int a, int b) + { + //return ((a << 5) + a) ^ b; + return 65599 * a + b; + } + + #region BytesTo + + /// + /// Convert the first two bytes starting in the byte array in native endian ordeing + /// to signed short integer + /// + /// An array two bytes or longer + /// A signed short integer, will be zero if a short can't be + /// read at the given position + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static short BytesToInt16(byte[] bytes) + { + return Unsafe.ReadUnaligned(ref MemoryMarshal.GetArrayDataReference(bytes)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static short BytesToInt16(ref byte bytes) + { + return Unsafe.ReadUnaligned(ref bytes); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static byte BytesToByte(byte[] bytes, int pos) + { + return Unsafe.ReadUnaligned(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(bytes), pos)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static byte BytesToByte(byte[] bytes, ref int pos) + { + return Unsafe.ReadUnaligned(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(bytes), pos++)); + } + + /// + /// Convert the first two bytes starting at the given position in + /// native endian ordering to a signed short integer + /// + /// An array two bytes or longer + /// Position in the array to start reading + /// A signed short integer, will be zero if a short can't be + /// read at the given position + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static short BytesToInt16(byte[] bytes, int pos) + { + return Unsafe.ReadUnaligned(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(bytes), pos)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static short BytesToInt16(ref byte bytes, int pos) + { + return Unsafe.ReadUnaligned(ref Unsafe.Add(ref bytes, pos)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe short BytesToInt16(byte* bytes) + { + if (CanDirectCopyLE) + { + return *(short*)bytes; + } + else + return (short)(*bytes | (bytes[1] << 8)); + } + + /// + /// Convert the first four bytes starting at the given position in native endian order + /// to a signed integer + /// + /// An array four bytes or longer + /// Position to start reading the int from + /// A signed integer, will be zero if an int can't be read + /// at the given position + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int BytesToInt(byte[] bytes, int pos) + { + //if (bytes.Length < pos + 4) return 0; + return Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(bytes), pos)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int BytesToInt(ref byte bytes, int pos) + { + return Unsafe.ReadUnaligned(ref Unsafe.Add(ref bytes, pos)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static int BytesToInt(byte* bytes) + { + if (CanDirectCopyLE) + { + return *(int*)bytes; + } + + return *bytes | + (bytes[1] << 8) | + (bytes[2] << 16) | + (bytes[3] << 24); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int BytesToIntSafepos(byte[] bytes, int pos) + { + return Unsafe.ReadUnaligned(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(bytes), pos)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int BytesToIntSafepos(ref byte bytes, int pos) + { + return Unsafe.ReadUnaligned(ref Unsafe.Add(ref bytes, pos)); + } + + /// + /// Convert the first four bytes of the given array in little endian + /// ordering to a signed integer + /// + /// An array four bytes or longer + /// A signed integer, will be zero if the array contains + /// less than four bytes + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int BytesToInt(byte[] bytes) + { + return Unsafe.ReadUnaligned(ref MemoryMarshal.GetArrayDataReference(bytes)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int BytesToInt(ref byte bytes) + { + return Unsafe.ReadUnaligned(ref bytes); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int BytesToIntBig(byte[] bytes) + { + return (bytes[0] << 24) | + (bytes[1] << 16) | + (bytes[2] << 8) | + bytes[3]; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int BytesToIntBig(byte[] bytes, int pos) + { + return (bytes[pos] << 24) | + (bytes[pos + 1] << 16) | + (bytes[pos + 2] << 8) | + bytes[pos + 3]; + } + + /// + /// Convert the first eight bytes of the given array in little endian + /// ordering to a signed long integer + /// + /// An array eight bytes or longer + /// A signed long integer, will be zero if the array contains + /// less than eight bytes + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static long BytesToInt64(byte[] bytes) + { + return Unsafe.ReadUnaligned(ref MemoryMarshal.GetArrayDataReference(bytes)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static long BytesToInt64(ref byte bytes) + { + return Unsafe.ReadUnaligned(ref bytes); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static long BytesToInt64Big(byte[] bytes) + { + return + ((long)bytes[0] << 56) | + ((long)bytes[1] << 48) | + ((long)bytes[2] << 40) | + ((long)bytes[3] << 32) | + ((long)bytes[4] << 24) | + ((long)bytes[5] << 16) | + ((long)bytes[6] << 8) | + ((long)bytes[7]); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static long BytesToInt64(byte* bytes) + { + if (CanDirectCopyLE) + { + return *(long*)bytes; + } + else + return + bytes[0] | + ((long)bytes[1] << 8) | + ((long)bytes[2] << 16) | + ((long)bytes[3] << 24) | + ((long)bytes[4] << 32) | + ((long)bytes[5] << 40) | + ((long)bytes[6] << 48) | + ((long)bytes[7] << 56); + } + + /// + /// Convert the first eight bytes starting at the given position in + /// little endian ordering to a signed long integer + /// + /// An array eight bytes or longer + /// Position to start reading the long from + /// A signed long integer, will be zero if a long can't be read + /// at the given position + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static long BytesToInt64(byte[] bytes, int pos) + { + if (bytes.Length < pos + 8) return 0; + return Unsafe.ReadUnaligned(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(bytes), pos)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static long BytesToInt64(ref byte bytes, int pos) + { + return Unsafe.ReadUnaligned(ref Unsafe.Add(ref bytes, pos)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static long BytesToInt64Safepos(byte[] bytes, int pos) + { + return Unsafe.ReadUnaligned(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(bytes), pos)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static long BytesToInt64Safepos(ref byte bytes, int pos) + { + return Unsafe.ReadUnaligned(ref Unsafe.Add(ref bytes, pos)); + } + + /// + /// Convert the first two bytes starting at the given position in + /// little endian ordering to an unsigned short + /// + /// Byte array containing the ushort + /// Position to start reading the ushort from + /// An unsigned short, will be zero if a ushort can't be read + /// at the given position + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ushort BytesToUInt16(byte[] bytes, int pos) + { + return Unsafe.ReadUnaligned(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(bytes), pos)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ushort BytesToUInt16(ref byte bytes, int pos) + { + return Unsafe.ReadUnaligned(ref Unsafe.Add(ref bytes, pos)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe ushort BytesToUInt16(byte* bytes) + { + if (CanDirectCopyLE) + return *(ushort*)bytes; + else + return (ushort)(*bytes + (bytes[1] << 8)); + } + + /// + /// Convert two bytes in native endian ordeing to an unsigned short + /// + /// Byte array containing the ushort + /// An unsigned short, will be zero if a ushort can't be + /// read + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ushort BytesToUInt16(byte[] bytes) + { + //if (bytes.Length < 2) return 0; + return Unsafe.ReadUnaligned(ref MemoryMarshal.GetArrayDataReference(bytes)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ushort BytesToUInt16(ref byte bytes) + { + return Unsafe.ReadUnaligned(ref bytes); + } + + /// + /// Convert the first four bytes starting at the given position in + /// little endian ordering to an unsigned integer + /// + /// Byte array containing the uint + /// Position to start reading the uint from + /// An unsigned integer, will be zero if a uint can't be read + /// at the given position + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static uint BytesToUInt(byte[] bytes, int pos) + { + if (bytes.Length < pos + 4) return 0; + return Unsafe.ReadUnaligned(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(bytes), pos)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static uint BytesToUIntSafepos(byte[] bytes, int pos) + { + return Unsafe.ReadUnaligned(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(bytes), pos)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static uint BytesToUIntSafepos(ref byte bytes, int pos) + { + return Unsafe.ReadUnaligned(ref Unsafe.Add(ref bytes, pos)); + } + + /// + /// Convert the first four bytes of the given array in little endian + /// ordering to an unsigned integer + /// + /// An array four bytes or longer + /// An unsigned integer, will be zero if the array contains + /// less than four bytes + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static uint BytesToUInt(byte[] bytes) + { + return Unsafe.ReadUnaligned(ref MemoryMarshal.GetArrayDataReference(bytes)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static uint BytesToUInt(ref byte bytes) + { + return Unsafe.ReadUnaligned(ref bytes); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static uint BytesToUInt(byte* bytes) + { + if (CanDirectCopyLE) + { + return *(uint*)bytes; + } + else + return (uint)( + bytes[0] | + (bytes[1] << 8) | + (bytes[2] << 16) | + (bytes[3] << 24)); + } + + /// + /// Convert the first eight bytes starting at the given position of the given array in little endian + /// ordering to an unsigned 64-bit integer + /// + /// An array eight bytes or longer + /// An unsigned 64-bit integer, will be zero if the array + /// contains less than eight bytes + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ulong BytesToUInt64(byte[] bytes, int pos) + { + if (bytes.Length < pos + 8) return 0; + return Unsafe.ReadUnaligned(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(bytes), pos)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ulong BytesToUInt64(ref byte bytes, int pos) + { + return Unsafe.ReadUnaligned(ref Unsafe.Add(ref bytes, pos)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ulong BytesToUInt64Safepos(byte[] bytes, int pos) + { + return Unsafe.ReadUnaligned(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(bytes), pos)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ulong BytesToUInt64Safepos(ref byte bytes, int pos) + { + return Unsafe.ReadUnaligned(ref Unsafe.Add(ref bytes, pos)); + } + + /// + /// Convert the first eight bytes of the given array in little endian + /// ordering to an unsigned 64-bit integer + /// + /// An array eight bytes or longer + /// An unsigned 64-bit integer, will be zero if the array + /// contains less than eight bytes + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ulong BytesToUInt64(byte[] bytes) + { + return Unsafe.ReadUnaligned(ref MemoryMarshal.GetArrayDataReference(bytes)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static ulong BytesToUInt64(ref byte bytes) + { + return Unsafe.ReadUnaligned(ref bytes); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static ulong BytesToUInt64(byte* bytes) + { + if (CanDirectCopyLE) + { + return *(ulong*)bytes; + } + else + return (ulong)( + bytes[0] | + ((long)bytes[1] << 8) | + ((long)bytes[2] << 16) | + ((long)bytes[3] << 24) | + ((long)bytes[4] << 32) | + ((long)bytes[5] << 40) | + ((long)bytes[6] << 48) | + ((long)bytes[7] << 56)); + } + + public static ulong VarBytestoUlong(byte[] bytes, int pos) + { + ref byte dataref = ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(bytes), pos); + + ulong value = Unsafe.ReadUnaligned(ref dataref); + if ((value & 0x80) == 0) + return value; + value &= 0x7F; + + ulong next = Unsafe.ReadUnaligned(ref Unsafe.Add(ref dataref, 1)); + if ((next & 0x80) == 0) + return value | (next << 7); + value |= (next & 0x7F) << 7; + + next = Unsafe.ReadUnaligned(ref Unsafe.Add(ref dataref, 2)); + if ((next & 0x80) == 0) + return value | (next << 14); + value |= (next & 0x7F) << 14; + + next = Unsafe.ReadUnaligned(ref Unsafe.Add(ref dataref, 3)); + if ((next & 0x80) == 0) + return value | (next << 21); + value |= (next & 0x7F) << 21; + + next = Unsafe.ReadUnaligned(ref Unsafe.Add(ref dataref, 4)); + if ((next & 0x80) == 0) + return value | (next << 28); + value |= (next & 0x7F) << 28; + + next = Unsafe.ReadUnaligned(ref Unsafe.Add(ref dataref, 5)); + if ((next & 0x80) == 0) + return value | (next << 35); + value |= (next & 0x7F) << 35; + + next = Unsafe.ReadUnaligned(ref Unsafe.Add(ref dataref, 6)); + if ((next & 0x80) == 0) + return value | (next << 42); + value |= (next & 0x7F) << 42; + + next = Unsafe.ReadUnaligned(ref Unsafe.Add(ref dataref, 7)); + if ((next & 0x80) == 0) + return value | (next << 49); + value |= (next & 0x7F) << 49; + + next = Unsafe.ReadUnaligned(ref Unsafe.Add(ref dataref, 8)); + if ((next & 0x80) == 0) + return value | (next << 56); + value |= (next & 0x7F) << 56; + + next = Unsafe.ReadUnaligned(ref Unsafe.Add(ref dataref, 9)); + return value | (next << 63); + } + + public static bool TryVarBytestoUlong(byte[] bytes, ref int pos, out ulong value) + { + int st = pos; + try + { + value = bytes[pos++]; + if ((value & 0x80) == 0) + return true; + value &= 0x7F; + + ulong next = bytes[pos++]; + if ((next & 0x80) == 0) + { + value |= (next << 7); + return true; + } + value |= (next & 0x7F) << 7; + + next = bytes[pos++]; + if ((next & 0x80) == 0) + { + value |= (next << 14); + return true; + } + value |= (next & 0x7F) << 14; + + pos++; + next = bytes[pos++]; + if ((next & 0x80) == 0) + { + value |= (next << 21); + return true; + } + value |= (next & 0x7F) << 21; + + next = bytes[pos++]; + if ((next & 0x80) == 0) + { + value |= (next << 28); + return true; + } + value |= (next & 0x7F) << 28; + + next = bytes[pos++]; + if ((next & 0x80) == 0) + { + value |= (next << 35); + return true; + } + value |= (next & 0x7F) << 35; + + next = bytes[pos++]; + if ((next & 0x80) == 0) + { + value |= (next << 42); + return true; + } + value |= (next & 0x7F) << 42; + + next = bytes[pos++]; + if ((next & 0x80) == 0) + { + value |= (next << 49); + return true; + } + value |= (next & 0x7F) << 49; + + next = bytes[pos++]; + if ((next & 0x80) == 0) + { + value |= (next << 56); + return true; + } + value |= (next & 0x7F) << 56; + + next = bytes[pos++]; + value |= (next << 63); + if( next < 2) + return true; + } + catch {} + + value = 0; + pos = st; + return false; + } + + public static ulong VarBytestoUlong(Stream ms) + { + ulong value = (ulong)ms.ReadByte(); + if ((value & 0x80) == 0) + return value; + value &= 0x7F; + + ulong next = (ulong)ms.ReadByte(); + if ((next & 0x80) == 0) + return value | (next << 7); + value |= (next & 0x7F) << 7; + + next = (ulong)ms.ReadByte(); + if ((next & 0x80) == 0) + return value | (next << 14); + value |= (next & 0x7F) << 14; + + next = (ulong)ms.ReadByte(); + if ((next & 0x80) == 0) + return value | (next << 21); + value |= (next & 0x7F) << 21; + + next = (ulong)ms.ReadByte(); + if ((next & 0x80) == 0) + return value | (next << 28); + value |= (next & 0x7F) << 28; + + next = (ulong)ms.ReadByte(); + if ((next & 0x80) == 0) + return value | (next << 35); + value |= (next & 0x7F) << 35; + + next = (ulong)ms.ReadByte(); + if ((next & 0x80) == 0) + return value | (next << 42); + value |= (next & 0x7F) << 42; + + next = (ulong)ms.ReadByte(); + if ((next & 0x80) == 0) + return value | (next << 49); + value |= (next & 0x7F) << 49; + + next = (ulong)ms.ReadByte(); + if ((next & 0x80) == 0) + return value | (next << 56); + value |= (next & 0x7F) << 56; + + next = (ulong)ms.ReadByte(); + return value | (next << 63); + } + + public static bool TryVarBytestoUlong(Stream ms, out ulong value) + { + long st = ms.Position; + try + { + value = (ulong)ms.ReadByte(); + if ((value & 0x80) == 0) + return true; + value &= 0x7F; + + ulong next = (ulong)ms.ReadByte(); + if ((next & 0x80) == 0) + { + value |= (next << 7); + return true; + } + value |= (next & 0x7F) << 7; + + next = (ulong)ms.ReadByte(); + if ((next & 0x80) == 0) + { + value |= (next << 14); + return true; + } + value |= (next & 0x7F) << 14; + + next = (ulong)ms.ReadByte(); + if ((next & 0x80) == 0) + { + value |= (next << 21); + return true; + } + value |= (next & 0x7F) << 21; + + next = (ulong)ms.ReadByte(); + if ((next & 0x80) == 0) + { + value |= (next << 28); + return true; + } + value |= (next & 0x7F) << 28; + + next = (ulong)ms.ReadByte(); + if ((next & 0x80) == 0) + { + value |= (next << 35); + return true; + } + value |= (next & 0x7F) << 35; + + next = (ulong)ms.ReadByte(); + if ((next & 0x80) == 0) + { + value |= (next << 42); + return true; + } + value |= (next & 0x7F) << 42; + + next = (ulong)ms.ReadByte(); + if ((next & 0x80) == 0) + { + value |= (next << 49); + return true; + } + value |= (next & 0x7F) << 49; + + next = (ulong)ms.ReadByte(); + if ((next & 0x80) == 0) + { + value |= (next << 56); + return true; + } + value |= (next & 0x7F) << 56; + + next = (ulong)ms.ReadByte(); + value |= (next << 63); + if(next < 2) + return true; + } + catch { } + + value = 0; + ms.Position = st; + return false; + } + + /// + /// Convert four bytes in native endian ordeing to a floating point + /// value + /// + /// Byte array containing a little ending floating + /// point value + /// Starting position of the floating point value in + /// the byte array + /// Single precision value + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static float BytesToFloat(byte[] bytes) + { + return Unsafe.ReadUnaligned(ref MemoryMarshal.GetArrayDataReference(bytes)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static float BytesToFloat(ref byte bytes) + { + return Unsafe.ReadUnaligned(ref bytes); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static float BytesToFloat(byte* bytes) + { + int tmp = BytesToInt(bytes); + return *(float*)&tmp; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static float BytesToFloat(byte[] bytes, int pos) + { + return Unsafe.ReadUnaligned(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(bytes), pos)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static float BytesToFloat(ref byte bytes, int pos) + { + return Unsafe.ReadUnaligned(ref Unsafe.Add(ref bytes, pos)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static float BytesToFloatSafepos(byte[] bytes, int pos) + { + return Unsafe.ReadUnaligned(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(bytes), pos)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static float BytesToFloatSafepos(ref byte bytes, int pos) + { + return Unsafe.ReadUnaligned(ref Unsafe.Add(ref bytes, pos)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static double BytesToDouble(byte[] bytes) + { + return Unsafe.ReadUnaligned(ref MemoryMarshal.GetArrayDataReference(bytes)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static double BytesToDouble(ref byte bytes) + { + return Unsafe.ReadUnaligned(ref bytes); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static double BytesToDoubleBig(byte[] bytes) + { + long tmp = BytesToInt64Big(bytes); + return *(double*)&tmp; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static double BytesToDouble(byte* bytes) + { + long tmp = BytesToInt64(bytes); + return *(double*)&tmp; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static double BytesToDouble(byte[] bytes, int pos) + { + return Unsafe.ReadUnaligned(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(bytes), pos)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static double BytesToDouble(ref byte bytes, int pos) + { + return Unsafe.ReadUnaligned(ref Unsafe.Add(ref bytes, pos)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static double BytesToDoubleSafepos(byte[] bytes, int pos) + { + return Unsafe.ReadUnaligned(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(bytes), pos)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static double BytesToDoubleSafepos(ref byte bytes, int pos) + { + return Unsafe.ReadUnaligned(ref Unsafe.Add(ref bytes, pos)); + } + + #endregion BytesTo + #region ToBytes + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void ByteToBytes(byte value, byte[] dest, int pos) + { + Unsafe.WriteUnaligned(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(dest), pos), value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void ByteToBytes(byte value, byte[] dest, ref int pos) + { + Unsafe.WriteUnaligned(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(dest), pos++), value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static byte[] Int16ToBytes(short value) + { + return new byte[] {(byte)value, (byte)(value >> 8)}; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Int16ToBytes(Stream ms, short value) + { + ms.WriteByte((byte)value); + ms.WriteByte((byte)(value >> 8)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Int16ToBytes(short value, byte[] dest, int pos) + { + Unsafe.WriteUnaligned(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(dest), pos), value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Int16ToBytes(short value, ref byte dest, int pos) + { + Unsafe.WriteUnaligned(ref Unsafe.Add(ref dest, pos), value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Int16ToBytes(short value, ref byte dest) + { + Unsafe.WriteUnaligned(ref dest, value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe void Int16ToBytes(short value, byte* dest) + { + *(short*)dest = value; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe void Int16ToBytes(short value, byte* dest, int pos) + { + *(short*)dest[pos] = value; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static byte[] UInt16ToBytes(ushort value) + { + return new byte[] { (byte)value, (byte)(value >> 8) }; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void UInt16ToBytes(ushort value, byte[] dest, int pos) + { + Unsafe.WriteUnaligned(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(dest), pos), value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void UInt16ToBytes(ushort value, ref byte dest, int pos) + { + Unsafe.WriteUnaligned(ref Unsafe.Add(ref dest, pos), value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void UInt16ToBytes(ushort value, ref byte dest) + { + Unsafe.WriteUnaligned(ref dest, value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe void UInt16ToBytes(ushort value, byte* dest, int pos) + { + *(ushort*)dest[pos] = value; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe void UInt16ToBytes(ushort value, byte* dest) + { + *(ushort*)dest = value; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void UInt16ToBytesBig(ushort value, byte[] dest, int pos) + { + Unsafe.WriteUnaligned(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(dest), pos), (byte)(value >> 8)); + Unsafe.WriteUnaligned(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(dest), pos + 1), (byte)(value)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void UInt16ToBytesBig(ushort value, byte[] dest, ref int pos) + { + Unsafe.WriteUnaligned(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(dest), pos), (byte)(value >> 8)); + Unsafe.WriteUnaligned(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(dest), pos + 1), (byte)(value)); + pos += 2; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static void UInt16ToBytesBig(ushort value, byte* dest, int pos) + { + dest[pos] = (byte)(value >> 8); + dest[pos + 1] = (byte)value; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe void UInt16ToBytesBig(ushort value, byte* dest) + { + *dest = (byte)(value >> 8); + dest[1] = (byte)value; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IntToBytes(Stream ms, int value) + { + ms.WriteByte((byte)value); + ms.WriteByte((byte)(value >> 8)); + ms.WriteByte((byte)(value >> 16)); + ms.WriteByte((byte)(value >> 24)); + } + + /// + /// Convert an integer to a byte array in little endian format + /// + /// The integer to convert + /// A four byte little endian array + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static byte[] IntToBytes(int value) + { + byte[] bytes = new byte[4]; + Unsafe.As(ref MemoryMarshal.GetArrayDataReference(bytes)) = value; + return bytes; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static void IntToBytes(int value, byte[] dest, int pos) + { + if (dest.Length < pos + 4) return; + Unsafe.WriteUnaligned(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(dest), pos), value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static void IntToBytes(int value, ref byte dest, int pos) + { + Unsafe.WriteUnaligned(ref Unsafe.Add(ref dest, pos), value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static void IntToBytes(int value, ref byte dest) + { + Unsafe.WriteUnaligned(ref dest, value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static void IntToBytes(int value, byte* dest, int pos) + { + if (CanDirectCopyLE) + { + *(int*)dest[pos] = value; + } + else + { + dest[pos] = (byte)(value); + dest[pos + 1] = (byte)((value >> 8)); + dest[pos + 2] = (byte)((value >> 16)); + dest[pos + 3] = (byte)((value >> 24)); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static void IntToBytes(int value, byte* dest) + { + if (CanDirectCopyLE) + { + *(int*)dest = value; + } + else + { + *dest = (byte)(value); + dest[1] = (byte)((value >> 8)); + dest[2] = (byte)((value >> 16)); + dest[3] = (byte)((value >> 24)); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static void IntToBytesSafepos(int value, byte[] dest, int pos) + { + Unsafe.WriteUnaligned(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(dest), pos), value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static void IntToBytesSafepos(int value, byte[] dest) + { + Unsafe.WriteUnaligned(ref MemoryMarshal.GetArrayDataReference(dest), value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static void IntToBytesSafepos(int value, ref byte dest, int pos) + { + Unsafe.WriteUnaligned(ref Unsafe.Add(ref dest, pos), value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static void IntToBytesSafepos(int value, ref byte dest) + { + Unsafe.WriteUnaligned(ref dest, value); + } + + /// + /// Convert an integer to a byte array in big endian format + /// + /// The integer to convert + /// A four byte big endian array + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static byte[] IntToBytesBig(int value) + { + return new byte[] + { + (byte)(value >> 24), + (byte)(value >> 16), + (byte)(value >> 8), + (byte)value + }; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IntToBytesBig(int value, byte[] bytes, int pos) + { + if (bytes.Length < pos + 4) return; + bytes[pos] = (byte)(value >> 24); + bytes[pos + 1] = (byte)(value >> 16); + bytes[pos + 2] = (byte)(value >> 8); + bytes[pos + 3] = (byte)value; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static void IntToBytesBig(int value, byte* bytes, int pos) + { + bytes[pos] = (byte)(value >> 24); + bytes[pos + 1] = (byte)(value >> 16); + bytes[pos + 2] = (byte)(value >> 8); + bytes[pos + 3] = (byte)value; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe void IntToBytesBig(int value, byte* bytes) + { + *bytes = (byte)(value >> 24); + bytes[1] = (byte)(value >> 16); + bytes[2] = (byte)(value >> 8); + bytes[3] = (byte)value; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static byte[] UIntToBytes(uint value) + { + return IntToBytes((int)value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static void UIntToBytes(uint value, byte* dest) + { + IntToBytes((int)value, dest); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static void UIntToBytes(uint value, byte[] dest, int pos) + { + if (dest.Length < pos + 4) return; + Unsafe.WriteUnaligned(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(dest), pos), value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static void UIntToBytes(uint value, byte* dest, int pos) + { + IntToBytes((int)value, dest, pos); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static void UIntToBytesSafepos(uint value, byte[] dest, int pos) + { + Unsafe.WriteUnaligned(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(dest), pos), value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static void UIntToBytesSafepos(uint value, byte[] dest) + { + Unsafe.WriteUnaligned(ref MemoryMarshal.GetArrayDataReference(dest), value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static void UIntToBytesSafepos(uint value, ref byte dest, int pos) + { + Unsafe.WriteUnaligned(ref Unsafe.Add(ref dest, pos), value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static void UIntToBytesSafepos(uint value, ref byte dest) + { + Unsafe.WriteUnaligned(ref dest, value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void UIntToBytesBig(uint value, byte[] dest, int pos) + { + IntToBytesBig((int)value, dest, pos); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void UIntToVarBytes(Stream ms, uint value) + { + while (value > 127) + { + ms.WriteByte((byte)(value | 0x80)); + value >>= 7; + } + ms.WriteByte((byte)value); + } + /// + /// Convert a 64-bit integer to a byte array in little endian format + /// + /// The value to convert + /// An 8 byte little endian array + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static byte[] Int64ToBytes(long value) + { + byte[] bytes = new byte[8]; + Unsafe.As(ref MemoryMarshal.GetArrayDataReference(bytes)) = value; + return bytes; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static void Int64ToBytes(long value, byte[] dest, int pos) + { + if (dest.Length < pos + 8) return; + Unsafe.WriteUnaligned(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(dest), pos), value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static void Int64ToBytes(long value, byte* dest, int pos) + { + if (CanDirectCopyLE) + { + *(long*)dest[pos] = value; + } + else + { + dest[pos] = (byte)value; + dest[pos + 1] = (byte)(value >> 8); + dest[pos + 2] = (byte)(value >> 16); + dest[pos + 3] = (byte)(value >> 24); + dest[pos + 4] = (byte)(value >> 32); + dest[pos + 5] = (byte)(value >> 40); + dest[pos + 6] = (byte)(value >> 48); + dest[pos + 7] = (byte)(value >> 56); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static void Int64ToBytes(long value, byte* dest) + { + if (CanDirectCopyLE) + { + *(long*)dest = value; + } + else + { + *dest = (byte)value; + dest[1] = (byte)(value >> 8); + dest[2] = (byte)(value >> 16); + dest[3] = (byte)(value >> 24); + dest[4] = (byte)(value >> 32); + dest[5] = (byte)(value >> 40); + dest[6] = (byte)(value >> 48); + dest[7] = (byte)(value >> 56); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static void Int64ToBytesSafepos(long value, byte[] dest, int pos) + { + Unsafe.WriteUnaligned(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(dest), pos), value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static void Int64ToBytesSafepos(long value, byte[] dest) + { + Unsafe.WriteUnaligned(ref MemoryMarshal.GetArrayDataReference(dest), value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static void Int64ToBytesSafepos(long value, ref byte dest, int pos) + { + Unsafe.WriteUnaligned(ref Unsafe.Add(ref dest, pos), value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static void Int64ToBytesSafepos(long value, ref byte dest) + { + Unsafe.WriteUnaligned(ref dest, value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Int64ToBytes(Stream ms, long value) + { + ms.WriteByte((byte)value); + ms.WriteByte((byte)(value >> 8)); + ms.WriteByte((byte)(value >> 16)); + ms.WriteByte((byte)(value >> 24)); + ms.WriteByte((byte)(value >> 32)); + ms.WriteByte((byte)(value >> 40)); + ms.WriteByte((byte)(value >> 48)); + ms.WriteByte((byte)(value >> 56)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static byte[] Int64ToBytesBig(long value) + { + byte[] bytes = new byte[8]; + bytes[0] = (byte)((value >> 56)); + bytes[1] = (byte)((value >> 48)); + bytes[2] = (byte)((value >> 40)); + bytes[3] = (byte)((value >> 32)); + bytes[4] = (byte)((value >> 24)); + bytes[5] = (byte)((value >> 16)); + bytes[6] = (byte)((value >> 8)); + bytes[7] = (byte)(value); + return bytes; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Int64ToBytesBig(long value, byte[] dest, int pos) + { + dest[pos] = (byte)(value >> 56); + dest[pos + 1] = (byte)(value >> 48); + dest[pos + 2] = (byte)(value >> 40); + dest[pos + 3] = (byte)(value >> 32); + dest[pos + 4] = (byte)(value >> 24); + dest[pos + 5] = (byte)(value >> 16); + dest[pos + 6] = (byte)(value >> 8); + dest[pos + 7] = (byte)value; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static void Int64ToBytesBig(long value, byte* dest, int pos) + { + dest[pos] = (byte)(value >> 56); + dest[pos + 1] = (byte)(value >> 48); + dest[pos + 2] = (byte)(value >> 40); + dest[pos + 3] = (byte)(value >> 32); + dest[pos + 4] = (byte)(value >> 24); + dest[pos + 5] = (byte)(value >> 16); + dest[pos + 6] = (byte)(value >> 8); + dest[pos + 7] = (byte)value; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe void Int64ToBytesBig(long value, byte* dest) + { + *dest = (byte)(value >> 56); + dest[1] = (byte)(value >> 48); + dest[2] = (byte)(value >> 40); + dest[3] = (byte)(value >> 32); + dest[4] = (byte)(value >> 24); + dest[5] = (byte)(value >> 16); + dest[6] = (byte)(value >> 8); + dest[7] = (byte)value; + } + + /// + /// Convert a 64-bit unsigned integer to a byte array in little endian + /// format + /// + /// The value to convert + /// An 8 byte little endian array + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static byte[] UInt64ToBytes(ulong value) + { + return Int64ToBytes((long)value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static byte[] UInt64ToBytesBig(ulong value) + { + return Int64ToBytesBig((long)value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static void UInt64ToBytes(ulong value, byte* dest) + { + Int64ToBytes((long)value, dest); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static void UInt64ToBytes(ulong value, byte[] dest, int pos) + { + Int64ToBytes((long)value, dest, pos); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static void UInt64ToBytes(ulong value, byte* dest, int pos) + { + Int64ToBytes((long)value, dest, pos); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static void UInt64ToBytesSafepos(ulong value, byte[] dest, int pos) + { + Unsafe.WriteUnaligned(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(dest), pos), value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void UInt64ToBytesSafepos(ulong value, byte[] dest) + { + Unsafe.WriteUnaligned(ref MemoryMarshal.GetArrayDataReference(dest), value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void UInt64ToBytesSafepos(ulong value, ref byte dest, int pos) + { + Unsafe.WriteUnaligned(ref Unsafe.Add(ref dest, pos), value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void UInt64ToBytesSafepos(ulong value, ref byte dest) + { + Unsafe.WriteUnaligned(ref dest, value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int UInt64ToVarBytes(byte[] bytes, int pos, ulong value) + { + ref byte bytesref = ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(bytes), pos); + ref byte bytesrefbase = ref bytesref; + while (value > 127UL) + { + Unsafe.WriteUnaligned(ref bytesref, (byte)(value | 0x80)); + bytesref = ref Unsafe.Add(ref bytesref, 1); + value >>= 7; + } + Unsafe.WriteUnaligned(ref bytesref, (byte)value); + return (int)Unsafe.ByteOffset(ref bytesrefbase, ref bytesref) + 1; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int TryUInt64ToVarBytes(byte[] bytes, int pos, ulong value) + { + int st = pos; + try + { + while (value > 127UL) + { + bytes[pos] = (byte)(value | 0x80); + pos++; + value >>= 7; + } + bytes[pos] = (byte)value; + return pos - st + 1; + } + catch { } + return -1; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void UInt64ToVarBytes(Stream ms, ulong value) + { + while (value > 127UL) + { + ms.WriteByte((byte)(value | 0x80)); + value >>= 7; + } + ms.WriteByte((byte)value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool TryUInt64ToVarBytes(Stream ms, ulong value) + { + try + { + while (value > 127UL) + { + ms.WriteByte((byte)(value | 0x80)); + value >>= 7; + } + ms.WriteByte((byte)value); + return true; + } + catch { } + return false; + } + + /// + /// Convert a floating point value to four bytes in little endian + /// ordering + /// + /// A floating point value + /// A four byte array containing the value in little endian + /// ordering + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static byte[] FloatToBytes(float value) + { + return IntToBytes(*(int*)&value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static void FloatToBytes(Stream ms, float value) + { + IntToBytes(ms, *(int*)&value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void FloatToBytes(float value, byte[] dest, int pos) + { + Unsafe.WriteUnaligned(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(dest), pos), value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static void FloatToBytes(float value, byte* dest, int pos) + { + //Unsafe.As(ref dest[pos]) = value; + IntToBytes(*(int*)&value, dest, pos); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static void FloatToBytes(float value, byte* dest) + { + IntToBytes(*(int*)&value, dest); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void FloatToBytesSafepos(float value, byte[] dest, int pos) + { + Unsafe.WriteUnaligned(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(dest), pos), value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void FloatToBytesSafepos(float value, ref byte dest, int pos) + { + Unsafe.WriteUnaligned(ref Unsafe.Add(ref dest, pos), value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void FloatToBytesSafepos(float value, byte[] dest) + { + Unsafe.WriteUnaligned(ref MemoryMarshal.GetArrayDataReference(dest), value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void FloatToBytesSafepos(float value, ref byte dest) + { + Unsafe.WriteUnaligned(ref dest, value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static byte[] DoubleToBytes(double value) + { + return Int64ToBytes(*(long*)&value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static void DoubleToBytes(Stream ms, float value) + { + Int64ToBytes(ms, *(long*)&value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static byte[] DoubleToBytesBig(double value) + { + return Int64ToBytesBig(*(long*)&value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static void DoubleToBytes(double value, byte[] dest, int pos) + { + Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(dest), pos)) = value; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static void DoubleToBytes(double value, byte* dest, int pos) + { + Int64ToBytes(*(long*)&value, dest, pos); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static void DoubleToBytes(double value, byte* dest) + { + Int64ToBytes(*(long*)&value, dest); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static void DoubleToBytesSafepos(double value, byte[] dest, int pos) + { + Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(dest), pos)) = value; + } + + #endregion ToBytes + + #region Strings + + /// + /// Converts an unsigned integer to a hexadecimal string + /// + /// An unsigned integer to convert to a string + /// A hexadecimal string 10 characters long + /// 0x7fffffff + public static string UIntToHexString(uint i) + { + return string.Format("{0:x8}", i); + } + + /// + /// Convert a variable length UTF8 byte array to a string + /// + /// The UTF8 encoded byte array to convert + /// The decoded string + public static string BytesToString(byte[] bytes) + { + if(bytes.Length <= 0) + return string.Empty; + if (bytes[bytes.Length - 1] == 0x00) + return Encoding.UTF8.GetString(bytes, 0, bytes.Length - 1); + else + return Encoding.UTF8.GetString(bytes, 0, bytes.Length); + } + + public static string BytesToString(byte[] bytes, int index, int count) + { + if (bytes.Length < index + count) + return string.Empty; + if (bytes[index + count - 1] == 0x00) + return Encoding.UTF8.GetString(bytes, index, count - 1); + else + return Encoding.UTF8.GetString(bytes, index, count); + } + + private static string GetString(byte[] bytes, int index, int count) + { + return Encoding.UTF8.GetString(bytes, index, count); + } + + /// + /// Converts a byte array to a string containing hexadecimal characters + /// + /// The byte array to convert to a string + /// The name of the field to prepend to each + /// line of the string + /// A string containing hexadecimal characters on multiple + /// lines. Each line is prepended with the field name + public static string BytesToHexString(byte[] bytes, string fieldName) + { + return BytesToHexString(bytes, bytes.Length, fieldName); + } + + /// + /// Converts a byte array to a string containing hexadecimal characters + /// + /// The byte array to convert to a string + /// Number of bytes in the array to parse + /// A string to prepend to each line of the hex + /// dump + /// A string containing hexadecimal characters on multiple + /// lines. Each line is prepended with the field name + public static string BytesToHexString(byte[] bytes, int length, string fieldName) + { + StringBuilder output = new StringBuilder(); + + for (int i = 0; i < length; i += 16) + { + if (i != 0) + output.Append('\n'); + + if (!string.IsNullOrEmpty(fieldName)) + { + output.Append(fieldName); + output.Append(": "); + } + + for (int j = 0, k = i; j < 16; ++j,++k) + { + if(k >= length) + break; + + if (j != 0) + output.Append(' '); + + output.Append(string.Format("{0:X2}", bytes[k])); + } + } + + return output.ToString(); + } + + /// + /// Convert a string to a UTF8 encoded byte array + /// + /// The string to convert + /// A null-terminated UTF8 byte array + public static byte[] StringToBytes(ReadOnlySpan str) + { + if (str.Length == 0) + return Array.Empty(); + + int nbytes = osUTF8GetBytesCount(str, out int sourcelen); + if (nbytes == 0) + return Array.Empty(); ; + byte[] dstarray = new byte[nbytes + 1]; + osUTF8Getbytes(str, sourcelen, dstarray, nbytes); + dstarray[nbytes] = 0; + return dstarray; + } + + public static byte[] StringToBytes(ReadOnlySpan str, int maxlen) + { + if (str.Length == 0) + return Array.Empty(); + + int nbytes = osUTF8GetBytesCount(str, maxlen -1, out int sourcelen); + if (nbytes == 0) + return Array.Empty(); + byte[] dstarray = new byte[nbytes + 1]; + osUTF8Getbytes(str, sourcelen, dstarray, nbytes); + dstarray[nbytes] = 0; + return dstarray; + } + + public static byte[] StringToBytesNoTerm(ReadOnlySpan str) + { + if (str.Length == 0) + return Array.Empty(); + + int nbytes = osUTF8GetBytesCount(str, out int sourcelen); + if (nbytes == 0) + return Array.Empty(); + byte[] dstarray = new byte[nbytes]; + osUTF8Getbytes(str, sourcelen, dstarray, nbytes); + return dstarray; + } + + public static byte[] StringToBytesNoTerm(ReadOnlySpan str, int maxlen) + { + if (str.Length == 0) + return Array.Empty(); + + int nbytes = osUTF8GetBytesCount(str, maxlen, out int sourcelen); + if (nbytes == 0) + return Array.Empty(); + byte[] dstarray = new byte[nbytes]; + osUTF8Getbytes(str, sourcelen, dstarray, nbytes); + return dstarray; + } + + public static unsafe int osUTF8Getbytes(ReadOnlySpan source, int srclenght, byte[] destiny, int maxdstlen) + { + int ret = 0; + char c; + fixed(char* srcarray = source) + { + fixed(byte* dstarray = destiny) + { + char* src = srcarray; + char* srcend = src + srclenght; + char* srcend1 = srcend - 1; + + byte* dst = dstarray; + byte* dstend = dst + maxdstlen; + byte* dstend2 = dstend - 2; + byte* dstend3 = dstend - 3; + byte* dstend4 = dstend - 4; + + while (src < srcend && dst < dstend) + { + c = *src++; + if(c == 0) + break; + + if (c <= 0x7f) + { + *dst++ = (byte)c; + continue; + } + + if (c < 0x800) + { + if (dst > dstend2) + break; + + *dst++ = (byte)(0xC0 | (c >> 6)); + *dst++ = (byte)(0x80 | (c & 0x3F)); + continue; + } + + if (c >= 0xD800 && c < 0xE000) + { + if (c >= 0xDC00) + continue; // ignore invalid + if (src > srcend1 || dst > dstend4) + break; + + int a = c; + + c = *src++; + + if (c < 0xDC00 || c > 0xDFFF) + continue; // ignore invalid + + a = (a << 10) + c - 0x35fdc00; + + *dst++ = (byte)(0xF0 | (a >> 18)); + *dst++ = (byte)(0x80 | ((a >> 12) & 0x3f)); + *dst++ = (byte)(0x80 | ((a >> 6) & 0x3f)); + *dst++ = (byte)(0x80 | (a & 0x3f)); + continue; + } + if (dst > dstend3) + break; + + *dst++ = (byte)(0xE0 | (c >> 12)); + *dst++ = (byte)(0x80 | ((c >> 6) & 0x3f)); + *dst++ = (byte)(0x80 | (c & 0x3f)); + } + ret = (int)(dst - dstarray); + } + } + return ret; + } + + public static unsafe bool osUTF8TryGetbytes(ReadOnlySpan srcstr, ref int srcstart, byte[] dstarray, ref int pos) + { + if (srcstr.Length == 0) + return true; + + bool ret = false; + int free = dstarray.Length - pos; + fixed (char* srcbase = srcstr) + { + fixed (byte* dstbase = dstarray) + { + char* src = srcbase + srcstart; + char* srcend = srcbase + srcstr.Length; + char* srcend1 = srcend - 1; + byte* dst = dstbase + pos; + + char c; + while (src < srcend && free > 0) + { + c = *src++; + if(c == 0) + break; + + if (c <= 0x7f) + { + *dst++ = (byte)c; + --free; + continue; + } + + if (c < 0x800) + { + free -= 2; + if (free <= 0) + { + --src; + break; + } + *dst++ = (byte)(0xC0 | (c >> 6)); + *dst++ = (byte)(0x80 | (c & 0x3F)); + continue; + } + + if (c >= 0xD800 && c < 0xE000) + { + if (c >= 0xDC00) + continue; // ignore invalid + if (src > srcend1) + break; + + int a = c; + c = *src++; + + if (c < 0xDC00 || c > 0xDFFF) + continue; // ignore invalid + + free -= 4; + if (free <= 0) + { + src -= 2; + break; + } + + a = (a << 10) + c - 0x35fdc00; + + *dst++ = (byte)(0xF0 | (a >> 18)); + *dst++ = (byte)(0x80 | ((a >> 12) & 0x3f)); + *dst++ = (byte)(0x80 | ((a >> 6) & 0x3f)); + *dst++ = (byte)(0x80 | (a & 0x3f)); + continue; + } + + free -= 3; + if (free <= 0) + { + --src; + break; + } + + *dst++ = (byte)(0xE0 | (c >> 12)); + *dst++ = (byte)(0x80 | ((c >> 6) & 0x3f)); + *dst++ = (byte)(0x80 | (c & 0x3f)); + } + + pos = (int)(dst - dstbase); + srcstart = (int)(src - srcbase); + if (src == srcend) + ret = true; + } + } + return ret; + } + + public static int SingleCharToUTF8(char c, out byte[] bytes) + { + if (c <= 0x7f) + { + bytes = new byte[1] { (byte)c }; + return 1; + } + + if (c < 0x800) + { + bytes = new byte[2] + { + (byte)(0xC0 | (c >> 6)), + (byte)(0x80 | (c & 0x3F)) + }; + return 2; + } + + if (c >= 0xD800 && c < 0xE000) + { + bytes = Array.Empty(); + if (c >= 0xDC00) + return 0; // ignore invalid + + /* ignore multi char + + int a = c; + c = *src++; + + if (c < 0xDC00 || c > 0xDFFF) + continue; // ignore invalid + + a = (a << 10) + c - 0x35fdc00; + + *dst++ = (byte)(0xF0 | (a >> 18)); + *dst++ = (byte)(0x80 | ((a >> 12) & 0x3f)); + *dst++ = (byte)(0x80 | ((a >> 6) & 0x3f)); + *dst++ = (byte)(0x80 | (a & 0x3f)); + */ + return -1; + } + + bytes = new byte[3] + { + (byte)(0xE0 | (c >> 12)), + (byte)(0x80 | ((c >> 6) & 0x3f)), + (byte)(0x80 | (c & 0x3f)) + }; + return 3; + } + + public static unsafe int SingleCharToUTF8(char c, byte[] dstarray, ref int pos) + { + int free = dstarray.Length - pos; + if (c <= 0x7f) + { + if(free < 1) + return 0; + dstarray[pos++] = (byte)c; + return 1; + } + + if (c < 0x800) + { + if (free < 2) + return 0; + dstarray[pos++] = (byte)(0xC0 | (c >> 6)); + dstarray[pos++] = (byte)(0x80 | (c & 0x3F)); + return 2; + } + + if (c >= 0xD800 && c < 0xE000) + { + if (c >= 0xDC00) + return 0; // ignore invalid + /* + int a = c; + c = *src++; + + if (c < 0xDC00 || c > 0xDFFF) + continue; // ignore invalid + + free -= 4; + if (free <= 0) + { + src -= 2; + break; + } + + a = (a << 10) + c - 0x35fdc00; + + *dst++ = (byte)(0xF0 | (a >> 18)); + *dst++ = (byte)(0x80 | ((a >> 12) & 0x3f)); + *dst++ = (byte)(0x80 | ((a >> 6) & 0x3f)); + *dst++ = (byte)(0x80 | (a & 0x3f)); + continue; + */ + return -1; + } + + if (free < 3) + return 0; + + dstarray[pos++] = (byte)(0xE0 | (c >> 12)); + dstarray[pos++] = (byte)(0x80 | ((c >> 6) & 0x3f)); + dstarray[pos++] = (byte)(0x80 | (c & 0x3f)); + return 3; + } + + public static unsafe int SingleCharToUTF8safepos(char c, byte[] dstarray, ref int pos) + { + if (c <= 0x7f) + { + dstarray[pos++] = (byte)c; + return 1; + } + + if (c < 0x800) + { + dstarray[pos++] = (byte)(0xC0 | (c >> 6)); + dstarray[pos++] = (byte)(0x80 | (c & 0x3F)); + return 2; + } + + if (c >= 0xD800 && c < 0xE000) + { + if (c >= 0xDC00) + return 0; // ignore invalid + /* + int a = c; + c = *src++; + + if (c < 0xDC00 || c > 0xDFFF) + continue; // ignore invalid + + free -= 4; + if (free <= 0) + { + src -= 2; + break; + } + + a = (a << 10) + c - 0x35fdc00; + + *dst++ = (byte)(0xF0 | (a >> 18)); + *dst++ = (byte)(0x80 | ((a >> 12) & 0x3f)); + *dst++ = (byte)(0x80 | ((a >> 6) & 0x3f)); + *dst++ = (byte)(0x80 | (a & 0x3f)); + continue; + */ + return -1; + } + + dstarray[pos++] = (byte)(0xE0 | (c >> 12)); + dstarray[pos++] = (byte)(0x80 | ((c >> 6) & 0x3f)); + dstarray[pos++] = (byte)(0x80 | (c & 0x3f)); + return 3; + } + + public static int osUTF8GetBytesCount(ReadOnlySpan str) + { + char c; + int nbytes = 0; + int i = 0; + while (i < str.Length) + { + c = str[i++]; + + if (c <= 0x7f) + { + ++nbytes; + continue; + } + + if (c < 0x800) + { + nbytes += 2; + continue; + } + + if (c >= 0xD800 && c < 0xE000) + { + if (c >= 0xDC00) + continue; + if (i == str.Length) + break; + c = str[i++]; + if (c < 0xDC00 || c > 0xDFFF) + continue; + nbytes += 4; + continue; + } + nbytes += 3; + } + + if (i > 0 && str[i - 1] == 0) + --nbytes; + return nbytes; + } + + public static int osUTF8GetBytesCount(ReadOnlySpan str, out int maxsource) + { + char c; + char lastc = (char)0; + int nbytes = 0; + int i = 0; + while (i < str.Length) + { + c = str[i++]; + + if (c <= 0x7f) + { + lastc = c; + ++nbytes; + continue; + } + + if (c < 0x800) + { + lastc = c; + nbytes += 2; + continue; + } + + if (c >= 0xD800 && c < 0xE000) + { + if (c >= 0xDC00) + continue; + if (i == str.Length) + break; + c = str[i++]; + if (c < 0xDC00 || c > 0xDFFF) + continue; + lastc = c; + nbytes += 4; + continue; + } + lastc = c; + nbytes += 3; + } + + if (i > 0 && lastc == 0) + { + --nbytes; + --i; + } + maxsource = i; + return nbytes; + } + + public static int osUTF8GetBytesCount(ReadOnlySpan str, int maxnbytes, out int maxsourcelen) + { + int max2 = maxnbytes - 2; + int max3 = maxnbytes - 3; + int max4 = maxnbytes - 4; + + char c; + int nbytes = 0; + int i = 0; + while(i < str.Length && nbytes < maxnbytes) + { + c = str[i++]; + if(c == 0) + break; + + if (c <= 0x7f) + { + ++nbytes; + continue; + } + + if (c < 0x800) + { + if (nbytes > max2) + break; + nbytes += 2; + continue; + } + + if (c >= 0xD800 && c < 0xE000) + { + if (c >= 0xDC00) + continue; + if (i == str.Length) + break; + c = str[i++]; + if (c < 0xDC00 || c > 0xDFFF) + continue; + if (nbytes > max4) + break; + nbytes += 4; + continue; + } + if (nbytes > max3) + break; + nbytes += 3; + } + + maxsourcelen = i; + return nbytes; + } + + /// + /// Returns true is c is a hexadecimal digit (A-F, a-f, 0-9) + /// + /// Character to test + /// true if hex digit, false if not + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsHexDigit(Char c) + { + + const int numA = 65; + const int numa = 97; + const int num0 = 48; + + if (c < num0) + return false; + if (c < (num0 + 10)) + return true; + + if (c > numa + 5) + return false; + if (c >= numa) + return true; + + if (c >= numA && c < numA + 6) + return true; + + return false; + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int HexNibbleWithChk(Char c) + { + const int numA = 65; + const int numa = 97; + const int num0 = 48; + + if (c < num0) + return -1; + if (c < (num0 + 10)) + return c - num0; + + if (c > numa + 5) + return -1; + if (c >= numa) + return c - numa + 10; + + if (c >= numA && c < numA + 6) + return c - numA + 10; + + return -1; + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int HexNibbleWithChk(byte c) + { + const int numA = 65; + const int numa = 97; + const int num0 = 48; + + if (c < num0) + return -1; + if (c < (num0 + 10)) + return c - num0; + + if (c > numa + 5) + return -1; + if (c >= numa) + return c - numa + 10; + + if (c >= numA && c < numA + 6) + return c - numA + 10; + + return -1; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int HexNibble(Char c) + { + + const char numA = 'A'; + const char numF = 'F'; + const char numa = 'a'; + const char numf = 'f'; + const char num0 = '0'; + const char num9 = '9'; + + if (c < num0) + throw new FormatException("invalid hex char"); + if (c <= num9) + return c - num0; + + if (c > numf) + throw new FormatException("invalid hex char"); + if (c >= numa) + return c - numa + 10; + + if (c >= numA && c <= numF) + return c - numA + 10; + + throw new FormatException("invalid hex char"); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int HexNibble(byte c) + { + const byte numA = (byte)'A'; + const byte numF = (byte)'F'; + const byte numa = (byte)'a'; + const byte numf = (byte)'f'; + const byte num0 = (byte)'0'; + const byte num9 = (byte)'9'; + + if (c < num0) + throw new FormatException("invalid hex char"); + if (c <= num9) + return c - num0; + + if (c > numf) + throw new FormatException("invalid hex char"); + if (c >= numa) + return c - numa + 10; + + if (c >= numA && c <= numF) + return c - numA + 10; + + throw new FormatException("invalid hex char"); + } + + public static bool TryHexToInt(byte[] data, int start, int len, out int res) + { + res = 0; + int n; + if(len > 8) + return false; + for (int i = start; i < start + len; ++i) + { + if ((n = HexNibbleWithChk(data[i])) < 0) + return false; + res *= 16; + res |= n; + } + return true; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool TryHexToByte(byte[] data, int pos, out byte res) + { + int a,b; + if ((a = HexNibbleWithChk(data[pos])) < 0) + { + res = 0; + return false; + } + if ((b = HexNibbleWithChk(data[pos + 1])) < 0) + { + res = 0; + return false; + } + res = (byte)(a << 4 | b); + return true; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static byte HexToByte(byte[] data, int pos) + { + return (byte)(HexNibble(data[pos]) << 4 | HexNibble(data[pos + 1])); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static byte HexToByte(byte* data, int pos) + { + return (byte)(HexNibble(data[pos]) << 4 | HexNibble(data[pos + 1])); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static byte HexToByte(char* hex, int pos) + { + return (byte)(HexNibble(hex[pos]) << 4 | HexNibble(hex[pos + 1])); + } + + /// + /// Converts a string containing hexadecimal characters to a byte array + /// + /// String containing hexadecimal characters + /// If true, gracefully handles null, empty and + /// uneven strings as well as stripping unconvertable characters + /// The converted byte array + public unsafe static byte[] HexStringToBytes(string hexString, bool handleDirty) + { + if (string.IsNullOrEmpty(hexString)) + return EmptyBytes; + if (handleDirty) + { + StringBuilder stripped = new StringBuilder(hexString.Length); + // remove all non A-F, 0-9, characters + foreach (char c in hexString) + { + if (IsHexDigit(c)) + stripped.Append(c); + } + hexString = stripped.ToString(); + + /* + // if odd number of characters, discard last character + if (hexString.Length % 2 != 0) + { + hexString = hexString[..^1]; + } + */ + } + + int byteLength = hexString.Length / 2; + byte[] bytes = new byte[byteLength]; + int j = 0; + + fixed(char* c = hexString) + { + for (int i = 0; i < bytes.Length; i++) + { + bytes[i] = HexToByte(c, j); + j += 2; + } + } + + return bytes; + } + + #endregion Strings + + #region Packed Values + + /// + /// Convert a float value to a byte given a minimum and maximum range + /// + /// Value to convert to a byte + /// Minimum value range + /// Maximum value range + /// A single byte representing the original float value + public static byte FloatToByte(float val, float lower, float upper) + { + val -= lower; + if (val <= 0) + return 0; + + val /= (upper - lower); + if (val >= 1.0f) + return 255; + + return (byte)(255 * val); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static byte FloatZeroOneToByte(float val) + { + if (val <= 0) + return 0; + if (val >= 1.0f) + return 255; + + return (byte)(255 * val); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ushort FloatZeroOneToushort(float val) + { + if (val <= 0) + return 0; + + if (val >= 1.0f) + return 0xffff; + + return (ushort)(val * 0xffff); + } + + + /// + /// Convert a byte to a float value given a minimum and maximum range + /// + /// Byte array to get the byte from + /// Position in the byte array the desired byte is at + /// Minimum value range + /// Maximum value range + /// A float value inclusively between lower and upper + public static float ByteToFloat(byte[] bytes, int pos, float lower, float upper) + { + if (bytes.Length <= pos) return 0; + return ByteToFloat(bytes[pos], lower, upper); + } + + /// + /// Convert a byte to a float value given a minimum and maximum range + /// + /// Byte to convert to a float value + /// Minimum value range + /// Maximum value range + /// A float value inclusively between lower and upper + public static float ByteToFloat(byte val, float lower, float upper) + { + float delta = (upper - lower) * 0.00392157f; + float fval = val * delta; + fval += lower; + + // Test for values very close to zero + if (Math.Abs(fval) < delta) + fval = 0.0f; + + return fval; + } + + public static float BytesUInt16ToFloat(byte[] bytes, int pos, float lower, float upper) + { + ushort val = BytesToUInt16(bytes, pos); + return UInt16ToFloat(val, lower, upper); + } + + public static float UInt16ToFloat(ushort val, float lower, float upper) + { + const float ONE_OVER_U16_MAX = 1.0f / UInt16.MaxValue; + + float delta = (upper - lower) * ONE_OVER_U16_MAX; + float fval = val * delta; + fval += lower; + + if (Math.Abs(fval) < delta) + fval = 0.0f; + + return fval; + } + + public static ushort FloatToUInt16(float value, float lower, float upper) + { + value -= lower; + if (value <= 0) + return 0; + + value /= upper - lower; + if (value >= 1.0f) + return 0xffff; + + return (ushort)(value * 0xffff); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ushort FloatToUInt16(float value, float range) + { + value += range; + if (value <= 0) + return 0; + + value /= range; + if (value >= 2.0f) + return 0xffff; + + return (ushort)(value * 32767.5); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ushort FloatToUnitUInt16(float value) + { + if (value <= -1.0) + return 0; + + if (value >= 1.0f) + return 0xffff; + + return (ushort)(value * 32767.5 + 32767); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void FloatToUInt16Bytes(float value, float range, byte[] dest, int pos) + { + UInt16ToBytes(FloatToUInt16(value, range), dest, pos); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static void FloatToUInt16Bytes(float value, float range, byte* dest, int pos) + { + UInt16ToBytes(FloatToUInt16(value, range), dest, pos); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static void FloatToUInt16Bytes(float value, float range, byte* dest) + { + UInt16ToBytes(FloatToUInt16(value, range), dest); + } + + public unsafe static byte[] FloatToUInt16Bytes(float value, float range) + { + return UInt16ToBytes(FloatToUInt16(value, range)); + } + + #endregion Packed Values + + #region TryParse + + /// + /// Attempts to parse a floating point value from a string, using an + /// EN-US number format + /// + /// String to parse + /// Resulting floating point number + /// True if the parse was successful, otherwise false + public static bool TryParseSingle(string s, out float result) + { + return Single.TryParse(s, System.Globalization.NumberStyles.Float, EnUsCulture.NumberFormat, out result); + } + + /// + /// Attempts to parse a floating point value from a string, using an + /// EN-US number format + /// + /// String to parse + /// Resulting floating point number + /// True if the parse was successful, otherwise false + public static bool TryParseDouble(string s, out double result) + { + // NOTE: Double.TryParse can't parse Double.[Min/Max]Value.ToString(), see: + // http://blogs.msdn.com/bclteam/archive/2006/05/24/598169.aspx + return Double.TryParse(s, System.Globalization.NumberStyles.Float, EnUsCulture.NumberFormat, out result); + } + + /// + /// Tries to parse an unsigned 32-bit integer from a hexadecimal string + /// + /// String to parse + /// Resulting integer + /// True if the parse was successful, otherwise false + public static bool TryParseHex(string s, out uint result) + { + return UInt32.TryParse(s, System.Globalization.NumberStyles.HexNumber, EnUsCulture.NumberFormat, out result); + } + + #endregion TryParse + + #region Enum String Conversion + + /// + /// Returns text specified in EnumInfo attribute of the enumerator + /// To add the text use [EnumInfo(Text = "Some nice text here")] before declaration + /// of enum values + /// + /// Enum value + /// Text representation of the enum + public static string EnumToText(Enum value) + { + // Get the type + Type type = value.GetType(); + + // Get fieldinfo for this type + FieldInfo fieldInfo = type.GetField(value.ToString()); + + // Find extended attributes, if any + EnumInfoAttribute[] attribs = (EnumInfoAttribute[])fieldInfo.GetCustomAttributes(typeof(EnumInfoAttribute), false); + + return attribs.Length > 0 ? attribs[0].Text : value.ToString(); + } + + /// + /// Takes an AssetType and returns the string representation + /// + /// The source + /// The string version of the AssetType + public static string AssetTypeToString(AssetType type) + { + return _AssetTypeNames[(int)type]; + } + + /// + /// Translate a string name of an AssetType into the proper Type + /// + /// A string containing the AssetType name + /// The AssetType which matches the string name, or AssetType.Unknown if no match was found + public static AssetType StringToAssetType(string type) + { + for (int i = 0; i < _AssetTypeNames.Length; i++) + { + if (_AssetTypeNames[i] == type) + return (AssetType)i; + } + + return AssetType.Unknown; + } + + /// + /// Takes a FolderType and returns the string representation + /// + /// The source + /// The string version of the FolderType + public static string FolderTypeToString(FolderType type) + { + return _FolderTypeNames[(int)type]; + } + + /// + /// Translate a string name of an FolderType into the proper Type + /// + /// A string containing the FolderType name + /// The FolderType which matches the string name, or FolderType. None if no match was found + public static FolderType StringToFolderType(string type) + { + for (int i = 0; i < _FolderTypeNames.Length; i++) + { + if (_FolderTypeNames[i] == type) + return (FolderType)i; + } + + return FolderType.None; + } + + /// + /// Convert an InventoryType to a string + /// + /// The to convert + /// A string representation of the source + public static string InventoryTypeToString(InventoryType type) + { + return _InventoryTypeNames[(int)type]; + } + + /// + /// Convert a string into a valid InventoryType + /// + /// A string representation of the InventoryType to convert + /// A InventoryType object which matched the type + public static InventoryType StringToInventoryType(string type) + { + for (int i = 0; i < _InventoryTypeNames.Length; i++) + { + if (_InventoryTypeNames[i] == type) + return (InventoryType)i; + } + + return InventoryType.Unknown; + } + + /// + /// Convert a SaleType to a string + /// + /// The to convert + /// A string representation of the source + public static string SaleTypeToString(SaleType type) + { + return _SaleTypeNames[(int)type]; + } + + /// + /// Convert a string into a valid SaleType + /// + /// A string representation of the SaleType to convert + /// A SaleType object which matched the type + public static SaleType StringToSaleType(string value) + { + for (int i = 0; i < _SaleTypeNames.Length; i++) + { + if (value == _SaleTypeNames[i]) + return (SaleType)i; + } + + return SaleType.Not; + } + + /// + /// Converts a string used in LLSD to AttachmentPoint type + /// + /// String representation of AttachmentPoint to convert + /// AttachmentPoint enum + public static AttachmentPoint StringToAttachmentPoint(string value) + { + for (int i = 0; i < _AttachmentPointNames.Length; i++) + { + if (value == _AttachmentPointNames[i]) + return (AttachmentPoint)i; + } + + return AttachmentPoint.Default; + } + + #endregion Enum String Conversion + + #region Miscellaneous + + /// + /// Copy a byte array + /// + /// Byte array to copy + /// A copy of the given byte array + public static byte[] CopyBytes(byte[] bytes) + { + if (bytes == null) + return null; + + byte[] newBytes = GC.AllocateUninitializedArray(bytes.Length); + Array.Copy(bytes, newBytes, bytes.Length); + return newBytes; + } + + /// + /// Packs to 32-bit unsigned integers in to a 64-bit unsigned integer + /// + /// The left-hand (or X) value + /// The right-hand (or Y) value + /// A 64-bit integer containing the two 32-bit input values + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ulong UIntsToLong(uint a, uint b) + { + return ((ulong)a << 32) | (ulong)b; + } + + /// + /// Unpacks two 32-bit unsigned integers from a 64-bit unsigned integer + /// + /// The 64-bit input integer + /// The left-hand (or X) output value + /// The right-hand (or Y) output value + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void LongToUInts(ulong a, out uint b, out uint c) + { + b = (uint)(a >> 32); + c = (uint)(a & 0x00000000FFFFFFFF); + } + + /// + /// Convert an IP address object to an unsigned 32-bit integer + /// + /// IP address to convert + /// 32-bit unsigned integer holding the IP address bits + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static uint IPToUInt(System.Net.IPAddress address) + { + byte[] bytes = address.GetAddressBytes(); + return (uint)((bytes[3] << 24) + (bytes[2] << 16) + (bytes[1] << 8) + bytes[0]); + } + + /// + /// Gets a unix timestamp for the current time + /// + /// An unsigned integer representing a unix timestamp for now + public static uint GetUnixTime() + { + return (uint)(DateTime.UtcNow - Epoch).TotalSeconds; + } + + /// + /// Convert a UNIX timestamp to a native DateTime object + /// + /// An unsigned integer representing a UNIX + /// timestamp + /// A DateTime object containing the same time specified in + /// the given timestamp + public static DateTime UnixTimeToDateTime(uint timestamp) + { + DateTime dateTime = Epoch; + + // Add the number of seconds in our UNIX timestamp + dateTime = dateTime.AddSeconds(timestamp); + + return dateTime; + } + + /// + /// Convert a UNIX timestamp to a native DateTime object + /// + /// A signed integer representing a UNIX + /// timestamp + /// A DateTime object containing the same time specified in + /// the given timestamp + public static DateTime UnixTimeToDateTime(int timestamp) + { + return UnixTimeToDateTime((uint)timestamp); + } + + /// + /// Convert a native DateTime object to a UNIX timestamp + /// + /// A DateTime object you want to convert to a + /// timestamp + /// An unsigned integer representing a UNIX timestamp + public static uint DateTimeToUnixTime(DateTime time) + { + TimeSpan ts = (time - new DateTime(1970, 1, 1, 0, 0, 0)); + return (uint)ts.TotalSeconds; + } + + /// + /// Swap two values + /// + /// Type of the values to swap + /// First value + /// Second value + public static void Swap(ref T lhs, ref T rhs) + { + (rhs, lhs) = (lhs, rhs); + } + + /// + /// Try to parse an enumeration value from a string + /// + /// Enumeration type + /// String value to parse + /// Enumeration value on success + /// True if the parsing succeeded, otherwise false + public static bool EnumTryParse(string strType, out T result) + { + Type t = typeof(T); + + if (Enum.IsDefined(t, strType)) + { + result = (T)Enum.Parse(t, strType, true); + return true; + } + else + { + foreach (string value in Enum.GetNames(typeof(T))) + { + if (value.Equals(strType, StringComparison.OrdinalIgnoreCase)) + { + result = (T)Enum.Parse(typeof(T), value); + return true; + } + } + result = default(T); + return false; + } + } + + /// + /// Swaps the high and low nibbles in a byte. Converts aaaabbbb to bbbbaaaa + /// + /// Byte to swap the words in + /// Byte value with the words swapped + public static byte SwapNibbles(byte value) + { + return (byte)(((value & 0xF0) >> 4) | ((value & 0x0F) << 4)); + } + + /// + /// Attempts to convert a string representation of a hostname or IP + /// address to a + /// + /// Hostname to convert to an IPAddress + /// Converted IP address object, or null if the conversion + /// failed + public static IPAddress HostnameToIPv4(string hostname) + { + // Is it already a valid IP? + if (IPAddress.TryParse(hostname, out IPAddress ip)) + return ip; + + IPAddress[] hosts = Dns.GetHostEntry(hostname).AddressList; + + for (int i = 0; i < hosts.Length; i++) + { + IPAddress host = hosts[i]; + + if (host.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) + return host; + } + + return null; + } + + private const byte ASCIIzero = (byte)'0'; + private const byte ASCIIminus = (byte)'-'; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe void UintToStrBytesFromEnd(uint value, byte* dst) + { + if(value >= 10) + { + while (value >= 100) + { + uint div = value / 100; + dst--; + WriteTwoDecDigits(value - 100 * div, dst); + value = div; + dst--; + } + if (value >= 10) + { + dst--; + WriteTwoDecDigits(value, dst); + return; + } + } + *dst = (byte)('0' + value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe int UIntToByteString(uint value, byte* dst) + { + int n = CountDigits(value); + UintToStrBytesFromEnd(value, dst + n - 1); + return n; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe int UIntToByteString(uint value, byte[] dst, int pos) + { + fixed (byte* d = &dst[pos]) + { + return UIntToByteString(value, d); + } + } + + public static unsafe int UIntToByteString(uint value, Stream st) + { + if (value == 0) + { + st.WriteByte(ASCIIzero); + return 1; + } + + int n = CountDigits(value); + byte* tmp = stackalloc byte[32]; + UintToStrBytesFromEnd(value, tmp + n - 1); + for (int i = 0; i < n; i++) + st.WriteByte(tmp[i]); + return n; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe int IntToByteString(int value, byte* dst) + { + int n; + if(value > 0) + { + n = CountDigits((uint)value); + UintToStrBytesFromEnd((uint)value, dst + n - 1); + return n; + } + if (value == 0) + { + *dst = ASCIIzero; + return 1; + } + + *dst = ASCIIminus; + value = -value; + n = CountDigits((uint)value); + UintToStrBytesFromEnd((uint)value, dst + n); + return n + 1; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe int IntToByteString(int value, byte[] dst, int pos) + { + fixed (byte* d = &dst[pos]) + { + return IntToByteString(value, d); + } + } + + public static unsafe int IntToByteString(int value, Stream st) + { + if (value == 0) + { + st.WriteByte(ASCIIzero); + return 1; + } + + byte* tmp = stackalloc byte[32]; + int n; + if (value > 0) + { + n = CountDigits((uint)value); + UintToStrBytesFromEnd((uint)value, tmp + n - 1); + for (int j = 0; j < n; j++) + st.WriteByte(tmp[j]); + return n; + } + + st.WriteByte(ASCIIminus); + value = -value; + n = CountDigits((uint)value); + UintToStrBytesFromEnd((uint)value, tmp + n - 1); + for (int j = 0; j < n; j++) + st.WriteByte(tmp[j]); + return n + 1; + } + + public static unsafe void ULongToStrBytesFromEnd(ulong value, byte* dst) + { + if (value >= 10) + { + while (value >= 100) + { + ulong div = value / 100; + dst--; + WriteTwoDecDigits((uint)(value - 100 * div), dst); + value = div; + dst--; + } + if (value >= 10) + { + dst--; + WriteTwoDecDigits((uint)value, dst); + return; + } + } + *dst = (byte)('0' + value); + } + + public static unsafe int ULongToByteString(ulong value, byte* dst) + { + int n = CountDigits(value); + ULongToStrBytesFromEnd(value, dst + n - 1); + return n; + } + + public static unsafe int ULongToByteString(ulong value, Stream st) + { + if (value == 0) + { + st.WriteByte(ASCIIzero); + return 1; + } + + int n = CountDigits(value); + byte* tmp = stackalloc byte[32]; + ULongToStrBytesFromEnd(value, tmp + n - 1); + for (int i = 0; i < n; i++) + st.WriteByte(tmp[i]); + return n; + } + + public static unsafe int ULongToByteString(ulong value, byte[] dst, int pos) + { + fixed (byte* d = &dst[pos]) + { + return ULongToByteString(value, d); + } + } + + public static unsafe int LongToByteString(long value, byte* dst) + { + int n; + if (value > 0) + { + n = CountDigits((ulong)value); + ULongToStrBytesFromEnd((ulong)value, dst + n - 1); + return n; + } + + if (value == 0) + { + *dst = ASCIIzero; + return 1; + } + + *dst = ASCIIminus; + value = -value; + n = CountDigits((ulong)value); + ULongToStrBytesFromEnd((ulong)value, dst + n); + return n + 1; + } + + public static unsafe int LongToByteString(long value, Stream st) + { + if (value == 0) + { + st.WriteByte(ASCIIzero); + return 1; + } + + byte* tmp = stackalloc byte[32]; + int n; + if (value > 0) + { + n = CountDigits((ulong)value); + ULongToStrBytesFromEnd((ulong)value, tmp + n - 1); + for (int j = 0; j < n; j++) + st.WriteByte(tmp[j]); + return n; + } + + st.WriteByte(ASCIIminus); + value = -value; + n = CountDigits((ulong)value); + ULongToStrBytesFromEnd((ulong)value, tmp + n - 1); + for (int j = 0; j < n; j++) + st.WriteByte(tmp[j]); + return n + 1; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe int LongToByteString(long value, byte[] dst, int pos) + { + fixed (byte* d = &dst[pos]) + { + return LongToByteString(value, d); + } + } + + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe osUTF8 IntToosUTF8(int v) + { + osUTF8 ret = new osUTF8(16); + fixed (byte* d = ret.m_data) + ret.m_len = IntToByteString(v, d); + return ret; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe osUTF8 UIntToosUTF8(uint v) + { + osUTF8 ret = new osUTF8(16); + fixed (byte* d = ret.m_data) + ret.m_len = UIntToByteString(v, d); + return ret; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe osUTF8 LongToosUTF8(long v) + { + osUTF8 ret = new osUTF8(32); + fixed (byte* d = ret.m_data) + ret.m_len = LongToByteString(v, d); + return ret; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe osUTF8 ULongToosUTF8(ulong v) + { + osUTF8 ret = new osUTF8(32); + fixed (byte* d = ret.m_data) + ret.m_len = ULongToByteString(v, d); + return ret; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static byte NibbleToHexUpper(byte b) + { + b &= 0x0f; + return (byte)(b > 9 ? b + 0x37 : b + ASCIIzero); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static byte LowNibbleToHexByteChar(byte b) + { + b &= 0x0f; + return (byte)(b > 9 ? b + 0x57 : b + ASCIIzero); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static byte HighNibbleToHexByteChar(byte b) + { + b >>= 4; + return (byte)(b > 9 ? b + 0x57 : b + ASCIIzero); + } + + public static unsafe void UUIDToByteDashString(UUID u, byte* dst) + { + if (Sse41.IsSupported) + { + Vector128 lower = Unsafe.As>(ref Unsafe.AsRef(in u)); + if (BitConverter.IsLittleEndian) + lower = Ssse3.Shuffle(lower, Vector128.Create((byte)0x03, 0x02, 0x01, 0x00, 0x05, 0x04, 0x07, 0x06, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F)); + Vector128 upper = (Sse2.ShiftRightLogical(lower.AsInt32(), 4)).AsByte(); + + Vector128 mask0f = Vector128.Create((byte)0x0f); + lower = Sse2.And(mask0f, lower); + upper = Sse2.And(mask0f, upper); + + Vector128 pastNine = Vector128.Create((sbyte)10); + Vector128 lowerMask = Sse2.CompareLessThan(lower.AsSByte(), pastNine).AsByte(); + Vector128 upperMask = Sse2.CompareLessThan(upper.AsSByte(), pastNine).AsByte(); + + Vector128 first = Vector128.Create((byte)'0'); + Vector128 second = Vector128.Create((byte)('a' - 10)); + Vector128 addlower = Sse41.BlendVariable(second, first, lowerMask); + Vector128 addupper = Sse41.BlendVariable(second, first, upperMask); + + lower = Sse2.Add(lower, addlower); + upper = Sse2.Add(upper, addupper); + + Vector128 mask1 = Ssse3.Shuffle(lower, Vector128.Create(0xff, 0, 0xff, 1, 0xff, 2, 0xff, 3, 0xff, 0xff, 4, 0xff, 5, 0xff, 0xff, 6)); + Vector128 mask2 = Ssse3.Shuffle(upper, Vector128.Create(0, 0xff, 1, 0xff, 2, 0xff, 3, 0xff, 0xff, 4, 0xff, 5, 0xff, 0xff, 6, 0xff)); + Vector128 mask3 = Ssse3.Shuffle(lower, Vector128.Create(0xff, 7, 0xff, 0xff, 8, 0xff, 9, 0xff, 0xff, 10, 0xff, 11, 0xff, 12, 0xff, 13)); + Vector128 mask4 = Ssse3.Shuffle(upper, Vector128.Create(7, 0xff, 0xff, 8, 0xff, 9, 0xff, 0xff, 10, 0xff, 11, 0xff, 12, 0xff, 13, 0xff)); + Vector128 hypens = Vector128.Create(0, 0, (byte)'-', 0, 0, 0, 0, (byte)'-', 0, 0, 0, 0, 0, 0, 0, 0); + Vector128 hypens2 = Vector128.Create(0, 0, 0, 0, 0, 0, 0, 0, (byte)'-', 0, 0, 0, 0, (byte)'-', 0, 0); + Vector128 upperSorted = Sse2.Or(Sse2.Or(mask1, mask2), hypens2); + Vector128 lowerSorted = Sse2.Or(Sse2.Or(mask3, mask4), hypens); + + Unsafe.As>(ref Unsafe.AsRef(dst)) = upperSorted; + Unsafe.As>(ref Unsafe.AddByteOffset(ref Unsafe.AsRef(dst), 16)) = lowerSorted; + + int v1 = Sse2.Extract(upper.AsUInt16(), 7); + int v2 = Sse2.Extract(lower.AsUInt16(), 7); + Unsafe.As(ref Unsafe.AddByteOffset(ref Unsafe.AsRef(dst), 32)) = (byte)(v1 & 0xff); + Unsafe.As(ref Unsafe.AddByteOffset(ref Unsafe.AsRef(dst), 33)) = (byte)(v2 & 0xff); + Unsafe.As(ref Unsafe.AddByteOffset(ref Unsafe.AsRef(dst), 34)) = (byte)((v1 >> 8) & 0xff); + Unsafe.As(ref Unsafe.AddByteOffset(ref Unsafe.AsRef(dst), 35)) = (byte)((v2 >> 8) & 0xff); + return; + } + byte b; + if (BitConverter.IsLittleEndian) + { + //a + b = u.bytea3; + *dst = HighNibbleToHexByteChar(b); + *(dst + 1) = LowNibbleToHexByteChar(b); + b = u.bytea2; + *(dst + 2) = HighNibbleToHexByteChar(b); + *(dst + 3) = LowNibbleToHexByteChar(b); + b = u.bytea1; + *(dst + 4) = HighNibbleToHexByteChar(b); + *(dst + 5) = LowNibbleToHexByteChar(b); + b = u.bytea0; + *(dst + 6) = HighNibbleToHexByteChar(b); + *(dst + 7) = LowNibbleToHexByteChar(b); + + *(dst + 8) = ASCIIminus; + //b + b = u.byteb1; + *(dst + 9) = HighNibbleToHexByteChar(b); + *(dst + 10) = LowNibbleToHexByteChar(b); + b = u.byteb0; + *(dst + 11) = HighNibbleToHexByteChar(b); + *(dst + 12) = LowNibbleToHexByteChar(b); + + *(dst + 13) = ASCIIminus; + + //c + b = u.bytec1; + *(dst + 14) = HighNibbleToHexByteChar(b); + *(dst + 15) = LowNibbleToHexByteChar(b); + b = u.bytec0; + *(dst + 16) = HighNibbleToHexByteChar(b); + *(dst + 17) = LowNibbleToHexByteChar(b); + } + else + { + //a + b = u.bytea0; + *dst = HighNibbleToHexByteChar(b); + *(dst + 1) = LowNibbleToHexByteChar(b); + b = u.bytea1; + *(dst + 2) = HighNibbleToHexByteChar(b); + *(dst + 3) = LowNibbleToHexByteChar(b); + b = u.bytea2; + *(dst + 4) = HighNibbleToHexByteChar(b); + *(dst + 5) = LowNibbleToHexByteChar(b); + b = u.bytea3; + *(dst + 6) = HighNibbleToHexByteChar(b); + *(dst + 7) = LowNibbleToHexByteChar(b); + + *(dst + 8) = ASCIIminus; + //b + b = u.byteb0; + *(dst + 9) = HighNibbleToHexByteChar(b); + *(dst + 10) = LowNibbleToHexByteChar(b); + b = u.byteb1; + *(dst + 11) = HighNibbleToHexByteChar(b); + *(dst + 12) = LowNibbleToHexByteChar(b); + + *(dst + 13) = ASCIIminus; + + //c + b = u.bytec0; + *(dst + 14) = HighNibbleToHexByteChar(b); + *(dst + 15) = LowNibbleToHexByteChar(b); + b = u.bytec1; + *(dst + 16) = HighNibbleToHexByteChar(b); + *(dst + 17) = LowNibbleToHexByteChar(b); + } + + *(dst + 18) = ASCIIminus; + + b = u.d; //d + *(dst + 19) = HighNibbleToHexByteChar(b); + *(dst + 20) = LowNibbleToHexByteChar(b); + b = u.e; //e + *(dst + 21) = HighNibbleToHexByteChar(b); + *(dst + 22) = LowNibbleToHexByteChar(b); + + *(dst + 23) = ASCIIminus; + + b = u.f; //f + *(dst + 24) = HighNibbleToHexByteChar(b); + *(dst + 25) = LowNibbleToHexByteChar(b); + b = u.g; //g + *(dst + 26) = HighNibbleToHexByteChar(b); + *(dst + 27) = LowNibbleToHexByteChar(b); + b = u.h; //h + *(dst + 28) = HighNibbleToHexByteChar(b); + *(dst + 29) = LowNibbleToHexByteChar(b); + b = u.i; //i + *(dst + 30) = HighNibbleToHexByteChar(b); + *(dst + 31) = LowNibbleToHexByteChar(b); + b = u.j; //j + *(dst + 32) = HighNibbleToHexByteChar(b); + *(dst + 33) = LowNibbleToHexByteChar(b); + b = u.k; //k + *(dst + 34) = HighNibbleToHexByteChar(b); + *(dst + 35) = LowNibbleToHexByteChar(b); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe osUTF8 UUIDToosUTF8(UUID v) + { + osUTF8 ret = new osUTF8(36); + fixed (byte* d = ret.m_data) + UUIDToByteDashString(v, d); + ret.m_len = 36; + return ret; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static char charNibbleToHexUpper(byte b) + { + b &= 0x0f; + return (char)(b > 9 ? b + 0x37 : b + ASCIIzero); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static char charLowNibbleToHexChar(byte b) + { + b &= 0x0f; + return (char)(b > 9 ? b + 0x57 : b + ASCIIzero); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static char charHighNibbleToHexChar(byte b) + { + b >>= 4; + return (char)(b > 9 ? b + 0x57 : b + ASCIIzero); + } + + public static string UUIDToDashString(UUID u) + { + return string.Create(36, u, (dst, u) => + { + if (Sse41.IsSupported) + { + Vector128 lower = Unsafe.As>(ref Unsafe.AsRef(in u)); + if (BitConverter.IsLittleEndian) + lower = Ssse3.Shuffle(lower, Vector128.Create((byte)0x03, 0x02, 0x01, 0x00, 0x05, 0x04, 0x07, 0x06, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F)); + Vector128 upper = (Sse2.ShiftRightLogical(lower.AsInt32(), 4)).AsByte(); + + Vector128 mask0f = Vector128.Create((byte)0x0f); + lower = Sse2.And(mask0f, lower); + upper = Sse2.And(mask0f, upper); + + Vector128 pastNine = Vector128.Create((sbyte)10); + Vector128 lowerMask = Sse2.CompareLessThan(lower.AsSByte(), pastNine).AsByte(); + Vector128 upperMask = Sse2.CompareLessThan(upper.AsSByte(), pastNine).AsByte(); + + Vector128 first = Vector128.Create((byte)'0'); + Vector128 second = Vector128.Create((byte)('a' - 10)); + Vector128 addlower = Sse41.BlendVariable(second, first, lowerMask); + Vector128 addupper = Sse41.BlendVariable(second, first, upperMask); + + lower = Sse2.Add(lower, addlower); + upper = Sse2.Add(upper, addupper); + + Vector128 mask1 = Ssse3.Shuffle(lower, Vector128.Create(0xff, 0, 0xff, 1, 0xff, 2, 0xff, 3, 0xff, 0xff, 4, 0xff, 5, 0xff, 0xff, 6)); + Vector128 mask2 = Ssse3.Shuffle(upper, Vector128.Create(0, 0xff, 1, 0xff, 2, 0xff, 3, 0xff, 0xff, 4, 0xff, 5, 0xff, 0xff, 6, 0xff)); + Vector128 mask3 = Ssse3.Shuffle(lower, Vector128.Create(0xff, 7, 0xff, 0xff, 8, 0xff, 9, 0xff, 0xff, 10, 0xff, 11, 0xff, 12, 0xff, 13)); + Vector128 mask4 = Ssse3.Shuffle(upper, Vector128.Create(7, 0xff, 0xff, 8, 0xff, 9, 0xff, 0xff, 10, 0xff, 11, 0xff, 12, 0xff, 13, 0xff)); + Vector128 hypens = Vector128.Create(0, 0, (byte)'-', 0, 0, 0, 0, (byte)'-', 0, 0, 0, 0, 0, 0, 0, 0); + Vector128 hypens2 = Vector128.Create(0, 0, 0, 0, 0, 0, 0, 0, (byte)'-', 0, 0, 0, 0, (byte)'-', 0, 0); + Vector128 upperSorted = Sse2.Or(Sse2.Or(mask1, mask2), hypens2); + Vector128 lowerSorted = Sse2.Or(Sse2.Or(mask3, mask4), hypens); + + Vector128 charsMask0 = Vector128.Create(0, 0xff, 1, 0xff, 2, 0xff, 3, 0xff, 4, 0xff, 5, 0xff, 6, 0xff, 7, 0xff); + Vector128 chars0 = Ssse3.Shuffle(upperSorted, charsMask0); + Unsafe.As>(ref MemoryMarshal.GetReference(dst)) = chars0; + + Vector128 charsMask1 = Vector128.Create(8, 0xff, 9, 0xff, 10, 0xff, 11, 0xff, 12, 0xff, 13, 0xff, 14, 0xff, 15, 0xff); + Vector128 chars1 = Ssse3.Shuffle(upperSorted, charsMask1); + Unsafe.As>(ref Unsafe.AddByteOffset(ref MemoryMarshal.GetReference(dst), 16)) = chars1; + + chars0 = Ssse3.Shuffle(lowerSorted, charsMask0); + Unsafe.As>(ref Unsafe.AddByteOffset(ref MemoryMarshal.GetReference(dst), 32)) = chars0; + + chars1 = Ssse3.Shuffle(lowerSorted, charsMask1); + Unsafe.As>(ref Unsafe.AddByteOffset(ref MemoryMarshal.GetReference(dst), 48)) = chars1; + + int v1 = Sse2.Extract(upper.AsUInt16(), 7); + int v2 = Sse2.Extract(lower.AsUInt16(), 7); + Unsafe.As(ref Unsafe.AddByteOffset(ref MemoryMarshal.GetReference(dst), 64)) = (byte)(v1 & 0xff); + Unsafe.As(ref Unsafe.AddByteOffset(ref MemoryMarshal.GetReference(dst), 66)) = (byte)(v2 & 0xff); + Unsafe.As(ref Unsafe.AddByteOffset(ref MemoryMarshal.GetReference(dst), 68)) = (byte)((v1 >> 8) & 0xff); + Unsafe.As(ref Unsafe.AddByteOffset(ref MemoryMarshal.GetReference(dst), 70)) = (byte)((v2 >> 8) & 0xff); + return; + } + byte b; + if (BitConverter.IsLittleEndian) + { + //a + b = u.bytea3; + dst[0] = charHighNibbleToHexChar(b); + dst[1] = charLowNibbleToHexChar(b); + b = u.bytea2; + dst[2] = charHighNibbleToHexChar(b); + dst[3] = charLowNibbleToHexChar(b); + b = u.bytea1; + dst[4] = charHighNibbleToHexChar(b); + dst[5] = charLowNibbleToHexChar(b); + b = u.bytea0; + dst[6] = charHighNibbleToHexChar(b); + dst[7] = charLowNibbleToHexChar(b); + + dst[8] = '-'; + + //b + b = u.byteb1; + dst[9] = charHighNibbleToHexChar(b); + dst[10] = charLowNibbleToHexChar(b); + b = u.byteb0; + dst[11] = charHighNibbleToHexChar(b); + dst[12] = charLowNibbleToHexChar(b); + + dst[13] = '-'; + + //c + b = u.bytec1; + dst[14] = charHighNibbleToHexChar(b); + dst[15] = charLowNibbleToHexChar(b); + b = u.bytec0; + dst[16] = charHighNibbleToHexChar(b); + dst[17] = charLowNibbleToHexChar(b); + } + else + { + //a + b = u.bytea0; + dst[0] = charHighNibbleToHexChar(b); + dst[1] = charLowNibbleToHexChar(b); + b = u.bytea1; + dst[2] = charHighNibbleToHexChar(b); + dst[3] = charLowNibbleToHexChar(b); + b = u.bytea2; + dst[4] = charHighNibbleToHexChar(b); + dst[5] = charLowNibbleToHexChar(b); + b = u.bytea3; + dst[6] = charHighNibbleToHexChar(b); + dst[7] = charLowNibbleToHexChar(b); + + dst[8] = '-'; + + //b + b = u.byteb0; + dst[9] = charHighNibbleToHexChar(b); + dst[10] = charLowNibbleToHexChar(b); + b = u.byteb1; + dst[11] = charHighNibbleToHexChar(b); + dst[12] = charLowNibbleToHexChar(b); + + dst[13] = '-'; + + //c + b = u.bytec0; + dst[14] = charHighNibbleToHexChar(b); + dst[15] = charLowNibbleToHexChar(b); + b = u.bytec1; + dst[16] = charHighNibbleToHexChar(b); + dst[17] = charLowNibbleToHexChar(b); + } + + dst[18] = '-'; + + b = u.d; //d + dst[19] = charHighNibbleToHexChar(b); + dst[20] = charLowNibbleToHexChar(b); + b = u.e; //e + dst[21] = charHighNibbleToHexChar(b); + dst[22] = charLowNibbleToHexChar(b); + + dst[23] = '-'; + + b = u.f; //f + dst[24] = charHighNibbleToHexChar(b); + dst[25] = charLowNibbleToHexChar(b); + b = u.g; //g + dst[26] = charHighNibbleToHexChar(b); + dst[27] = charLowNibbleToHexChar(b); + b = u.h; //h + dst[28] = charHighNibbleToHexChar(b); + dst[29] = charLowNibbleToHexChar(b); + b = u.i; //i + dst[30] = charHighNibbleToHexChar(b); + dst[31] = charLowNibbleToHexChar(b); + b = u.j; //j + dst[32] = charHighNibbleToHexChar(b); + dst[33] = charLowNibbleToHexChar(b); + b = u.k; //k + dst[34] = charHighNibbleToHexChar(b); + dst[35] = charLowNibbleToHexChar(b); + }); + } + + //from .net8 for integer to utf8 + + // Map the log2(value) to a power of 10. + public static readonly byte[] log2ToPow10 = new byte[] + { + 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, + 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 10, + 10, 11, 11, 11, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 15, 15, + 15, 16, 16, 16, 16, 17, 17, 17, 18, 18, 18, 19, 19, 19, 19, 20 + }; + + public static readonly ulong[] powersOf10 = new ulong[] + { + 0, // unused entry to avoid needing to subtract + 0, + 10, + 100, + 1000, + 10000, + 100000, + 1000000, + 10000000, + 100000000, + 1000000000, + 10000000000, + 100000000000, + 1000000000000, + 10000000000000, + 100000000000000, + 1000000000000000, + 10000000000000000, + 100000000000000000, + 1000000000000000000, + 10000000000000000000 + }; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int CountDigits(ulong value) + { + uint index = Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(log2ToPow10), System.Numerics.BitOperations.Log2(value)); + bool lessThan = value < Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(powersOf10), index); ; + return (int)(index - Unsafe.As(ref lessThan)); + } + + public static readonly long[] CountDigitlongtable = new long[] + { + 4294967296, + 8589934582, + 8589934582, + 8589934582, + 12884901788, + 12884901788, + 12884901788, + 17179868184, + 17179868184, + 17179868184, + 21474826480, + 21474826480, + 21474826480, + 21474826480, + 25769703776, + 25769703776, + 25769703776, + 30063771072, + 30063771072, + 30063771072, + 34349738368, + 34349738368, + 34349738368, + 34349738368, + 38554705664, + 38554705664, + 38554705664, + 41949672960, + 41949672960, + 41949672960, + 42949672960, + 42949672960, + }; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int CountDigits(uint value) + { + long tableValue = Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(CountDigitlongtable), System.Numerics.BitOperations.Log2(value)); + return (int)((value + tableValue) >> 32); + } + + public static readonly byte[] twodigitbytes = StringToBytesNoTerm( + "00010203040506070809" + + "10111213141516171819" + + "20212223242526272829" + + "30313233343536373839" + + "40414243444546474849" + + "50515253545556575859" + + "60616263646566676869" + + "70717273747576777879" + + "80818283848586878889" + + "90919293949596979899"); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe void WriteTwoDecDigits(uint value, byte* dest) + { + *(ushort*)dest = Unsafe.ReadUnaligned(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(twodigitbytes), 2 * value)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void StringToUFT8VarBin(Stream ms, ReadOnlySpan s) + { + ReadOnlySpan sp = StringToBytesNoTerm(s); + UIntToVarBytes(ms, (uint)sp.Length); + if (sp.Length > 0) + ms.Write(sp); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Utf8ToVarBin(Stream ms, ReadOnlySpan sp) + { + UIntToVarBytes(ms, (uint)sp.Length); + if (sp.Length > 0) + ms.Write(sp); + } + #endregion Miscellaneous + } +} diff --git a/OpenMetaverse.Types/Vector2.cs b/OpenMetaverse.Types/Vector2.cs index 7f80f1ab..06632a9f 100644 --- a/OpenMetaverse.Types/Vector2.cs +++ b/OpenMetaverse.Types/Vector2.cs @@ -24,9 +24,10 @@ * POSSIBILITY OF SUCH DAMAGE. */ -using System; using System.Globalization; +using System.Runtime.CompilerServices; using System.Runtime.InteropServices; +using System.Text; namespace OpenMetaverse { @@ -65,7 +66,7 @@ public Vector2(Vector2 vector) #endregion Constructors #region Public Methods - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Abs() { if (X < 0f) @@ -74,20 +75,34 @@ public void Abs() Y = -Y; } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Min(Vector2 v) { if (v.X < X) X = v.X; if (v.Y < Y) Y = v.Y; } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Max(Vector2 v) { if (v.X > X) X = v.X; if (v.Y > Y) Y = v.Y; } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Add(Vector3 v) + { + X += v.X; + Y += v.Y; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Sub(Vector3 v) + { + X -= v.X; + Y -= v.Y; + } + /// /// Test if this vector is equal to another vector, within a given /// tolerance range @@ -97,20 +112,60 @@ public void Max(Vector2 v) /// between the two vectors /// True if the magnitude of difference between the two vectors /// is less than the given tolerance, otherwise false - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool ApproxEquals(Vector2 vec, float tolerance) { return Utils.ApproxEqual(X, vec.X, tolerance) && Utils.ApproxEqual(Y, vec.Y, tolerance); } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool ApproxEquals(Vector2 vec) { return Utils.ApproxEqual(X, vec.X) && Utils.ApproxEqual(Y, vec.Y); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool ApproxZero() + { + if (!Utils.ApproxZero(X)) + return false; + if (!Utils.ApproxZero(Y)) + return false; + return true; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool ApproxZero(float tolerance) + { + if (!Utils.ApproxZero(X, tolerance)) + return false; + if (!Utils.ApproxZero(Y, tolerance)) + return false; + return true; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool IsZero() + { + if (X != 0) + return false; + if (Y != 0) + return false; + return true; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool IsNotZero() + { + if (X != 0) + return true; + if (Y != 0) + return true; + return false; + } + /// /// Test if this vector is composed of all finite numbers /// @@ -127,12 +182,18 @@ public int CompareTo(Vector2 vector) return LengthSquared().CompareTo(vector.LengthSquared()); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public float Dot(Vector3 value2) + { + return (X * value2.X) + (Y * value2.Y); + } + /// /// Builds a vector from a byte array /// /// Byte array containing two four-byte floats /// Beginning position in the byte array - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] public void FromBytes(byte[] byteArray, int pos) { X = Utils.BytesToFloatSafepos(byteArray, pos); @@ -143,7 +204,7 @@ public void FromBytes(byte[] byteArray, int pos) /// Returns the raw bytes for this vector /// /// An eight-byte array containing X and Y - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] public byte[] GetBytes() { byte[] dest = new byte[8]; @@ -158,32 +219,52 @@ public byte[] GetBytes() /// Destination byte array /// Position in the destination array to start /// writing. Must be at least 8 bytes before the end of the array - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public void ToBytes(byte[] dest, int pos) + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe void ToBytes(byte[] dest, int pos) + { + if (Utils.CanDirectCopyLE) + { + fixed (byte* d = &dest[0]) + *(Vector2*)(d + pos) = this; + } + else { Utils.FloatToBytesSafepos(X, dest, pos); Utils.FloatToBytesSafepos(Y, dest, pos + 4); } + } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe void ToBytes(byte* dest) + { + if (Utils.CanDirectCopyLE) + *(Vector2*)(dest) = this; + else + { + Utils.FloatToBytes(X, dest); + Utils.FloatToBytes(Y, dest + 4); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] public float Length() { - return (float)Math.Sqrt(X * X + Y * Y); + return MathF.Sqrt(X * X + Y * Y); } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] public float LengthSquared() { return X * X + Y * Y; } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Normalize() { float factor = LengthSquared(); if (factor > 1e-6) { - factor = 1f / (float)Math.Sqrt(factor); + factor = 1f / MathF.Sqrt(factor); X *= factor; Y *= factor; } @@ -198,13 +279,21 @@ public void Normalize() #region Static Methods - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Add(Vector2 value1, Vector2 value2) { return new Vector2(value1.X + value2.X, value1.Y + value2.Y); } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector2 Clamp(Vector3 value1, float min, float max) + { + return new Vector2( + Utils.Clamp(value1.X, min, max), + Utils.Clamp(value1.Y, min, max)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Clamp(Vector2 value1, Vector2 min, Vector2 max) { return new Vector2( @@ -212,13 +301,13 @@ public static Vector2 Clamp(Vector2 value1, Vector2 min, Vector2 max) Utils.Clamp(value1.Y, min.Y, max.Y)); } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Distance(Vector2 value1, Vector2 value2) { - return (float)Math.Sqrt(DistanceSquared(value1, value2)); + return MathF.Sqrt(DistanceSquared(value1, value2)); } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float DistanceSquared(Vector2 value1, Vector2 value2) { return @@ -226,20 +315,20 @@ public static float DistanceSquared(Vector2 value1, Vector2 value2) (value1.Y - value2.Y) * (value1.Y - value2.Y); } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Divide(Vector2 value1, Vector2 value2) { return new Vector2(value1.X / value2.X, value1.Y / value2.Y); } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Divide(Vector2 value1, float divider) { float factor = 1 / divider; return new Vector2(value1.X * factor, value1.Y * factor); } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Dot(Vector2 value1, Vector2 value2) { return (value1.X * value2.X) + (value1.Y * value2.Y); @@ -252,50 +341,50 @@ public static Vector2 Lerp(Vector2 value1, Vector2 value2, float amount) Utils.Lerp(value1.Y, value2.Y, amount)); } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Max(Vector2 value1, Vector2 value2) { return new Vector2( - Math.Max(value1.X, value2.X), - Math.Max(value1.Y, value2.Y)); + MathF.Max(value1.X, value2.X), + MathF.Max(value1.Y, value2.Y)); } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Min(Vector2 value1, Vector2 value2) { return new Vector2( - Math.Min(value1.X, value2.X), - Math.Min(value1.Y, value2.Y)); + MathF.Min(value1.X, value2.X), + MathF.Min(value1.Y, value2.Y)); } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Multiply(Vector2 value1, Vector2 value2) { return new Vector2(value1.X * value2.X, value1.Y * value2.Y); } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Multiply(Vector2 value1, float scaleFactor) { return new Vector2(value1.X * scaleFactor, value1.Y * scaleFactor); } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Negate(Vector2 value) { return new Vector2(-value.X, -value.Y); } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Normalize(Vector2 value) { float factor = value.LengthSquared(); if (factor > 1e-6) { - factor = 1f / (float)Math.Sqrt(factor); + factor = 1f / MathF.Sqrt(factor); return new Vector2(value.X * factor, value.Y * factor); } - return Vector2.Zero; + return new Vector2(); } /// @@ -303,29 +392,117 @@ public static Vector2 Normalize(Vector2 value) /// /// A string representation of a 2D vector, enclosed /// in arrow brackets and separated by commas - public static Vector2 Parse(string val) + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe Vector2 Parse(string val) { - char[] splitChar = { ',' }; - string[] split = val.Replace("<", String.Empty).Replace(">", String.Empty).Split(splitChar); - return new Vector2( - float.Parse(split[0].Trim(), Utils.EnUsCulture), - float.Parse(split[1].Trim(), Utils.EnUsCulture)); + return Parse(val.AsSpan()); } - public static bool TryParse(string val, out Vector2 result) + public static Vector2 Parse(ReadOnlySpan sp) { - try + if (sp.Length < 3) + throw new FormatException("Invalid Vector2"); + + int start = 0; + int comma = 0; + char c; + + do { - result = Parse(val); - return true; + c = Unsafe.Add(ref MemoryMarshal.GetReference(sp), comma); + if (c == ',' || c == '<') + break; } - catch (Exception) + while (++comma < sp.Length); + + if (c == '<') { - result = Vector2.Zero; + start = ++comma; + while (++comma < sp.Length) + { + if (Unsafe.Add(ref MemoryMarshal.GetReference(sp), comma) == ',') + break; + } + } + if (comma > sp.Length - 1) + throw new FormatException("Invalid Vector2"); + + if (!float.TryParse(sp[start..comma], NumberStyles.Float, Utils.EnUsCulture, out float x)) + throw new FormatException("Invalid Vector2"); + + start = ++comma; + while (++comma < sp.Length) + { + if (Unsafe.Add(ref MemoryMarshal.GetReference(sp), comma) == '>') + break; + } + if (!float.TryParse(sp[start..comma], NumberStyles.Float, Utils.EnUsCulture, out float y)) + throw new FormatException("Invalid Vector2"); + + return new Vector2(x, y); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool TryParse(string val, out Vector2 result) + { + return TryParse(val.AsSpan(), out result); + } + public static bool TryParse(ReadOnlySpan sp, out Vector2 result) + { + if (sp.Length < 3) + { + result = Zero; return false; } + + int start = 0; + int comma = 0; + char c; + do + { + c = Unsafe.Add(ref MemoryMarshal.GetReference(sp), comma); + if (c == ',' || c == '<') + break; + } + while (++comma < sp.Length); + + if (c == '<') + { + start = ++comma; + while (++comma < sp.Length) + { + if (Unsafe.Add(ref MemoryMarshal.GetReference(sp), comma) == ',') + break; + } + } + if (comma > sp.Length - 1) + { + result = Zero; + return false; } + if (!float.TryParse(sp[start..comma], NumberStyles.Float, Utils.EnUsCulture, out float x)) + { + result = Zero; + return false; + } + + start = ++comma; + while (++comma < sp.Length) + { + c = Unsafe.Add(ref MemoryMarshal.GetReference(sp), comma); + if (c == ' ' || c == '>') + break; + } + if (!float.TryParse(sp[start..comma], NumberStyles.Float, Utils.EnUsCulture, out float y)) + { + result = Zero; + return false; + } + + result = new Vector2(x, y); + return true; + } /// /// Interpolates between two vectors using a cubic equation /// @@ -336,7 +513,7 @@ public static Vector2 SmoothStep(Vector2 value1, Vector2 value2, float amount) Utils.SmoothStep(value1.Y, value2.Y, amount)); } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Subtract(Vector2 value1, Vector2 value2) { return new Vector2(value1.X - value2.X, value1.Y - value2.Y); @@ -362,14 +539,38 @@ public static Vector2 TransformNormal(Vector2 position, Matrix4 matrix) public override bool Equals(object obj) { - return (obj is Vector2) ? this == ((Vector2)obj) : false; + if (!(obj is Vector2)) + return false; + + Vector2 other = (Vector2)obj; + if (X != other.X) + return false; + if (Y != other.Y) + return false; + return true; } + [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Equals(Vector2 other) { - return this == other; + if (X != other.X) + return false; + if (Y != other.Y) + return false; + return true; } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool NotEqual(Vector3 other) + { + if (X != other.X) + return true; + if (Y != other.Y) + return true; + return false; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] public override int GetHashCode() { int hash = X.GetHashCode(); @@ -383,7 +584,13 @@ public override int GetHashCode() /// A string representation of the vector public override string ToString() { - return String.Format(Utils.EnUsCulture, "<{0}, {1}>", X, Y); + StringBuilder sb = new(); + sb.Append('<'); + sb.Append(X.ToString(Utils.EnUsCulture)); + sb.Append(", "); + sb.Append(Y.ToString(Utils.EnUsCulture)); + sb.Append('>'); + return sb.ToString(); } /// @@ -396,7 +603,12 @@ public string ToRawString() CultureInfo enUs = new CultureInfo("en-us"); enUs.NumberFormat.NumberDecimalDigits = 3; - return String.Format(enUs, "{0} {1}", X, Y); + StringBuilder sb = new(); + sb.Append(X.ToString(enUs)); + sb.Append(' '); + sb.Append(Y.ToString(enUs)); + sb.Append(' '); + return sb.ToString(); } #endregion Overrides @@ -405,12 +617,20 @@ public string ToRawString() public static bool operator ==(Vector2 value1, Vector2 value2) { - return value1.X == value2.X && value1.Y == value2.Y; + if (value1.X != value2.X) + return false; + if (value1.Y != value2.Y) + return false; + return true; } public static bool operator !=(Vector2 value1, Vector2 value2) { - return value1.X != value2.X || value1.Y != value2.Y; + if (value1.X != value2.X) + return true; + if (value1.Y != value2.Y) + return true; + return false; } public static Vector2 operator +(Vector2 value1, Vector2 value2) diff --git a/OpenMetaverse.Types/Vector3.cs b/OpenMetaverse.Types/Vector3.cs index e4029a4c..ebf65927 100644 --- a/OpenMetaverse.Types/Vector3.cs +++ b/OpenMetaverse.Types/Vector3.cs @@ -1,659 +1,1638 @@ -/* - * Copyright (c) 2006-2016, openmetaverse.co - * All rights reserved. - * - * - Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, this - * list of conditions and the following disclaimer. - * - Neither the name of the openmetaverse.co nor the names - * of its contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Globalization; -using System.Runtime.InteropServices; - -namespace OpenMetaverse -{ - /// - /// A three-dimensional vector with floating-point values - /// - [Serializable] - [StructLayout(LayoutKind.Sequential)] - public struct Vector3 : IComparable, IEquatable - { - /// X value - public float X; - /// Y value - public float Y; - /// Z value - public float Z; - - #region Constructors - - public Vector3(float x, float y, float z) - { - X = x; - Y = y; - Z = z; - } - - public Vector3(float value) - { - X = value; - Y = value; - Z = value; - } - - public Vector3(Vector2 value, float z) - { - X = value.X; - Y = value.Y; - Z = z; - } - - public Vector3(Vector3d vector) - { - X = (float)vector.X; - Y = (float)vector.Y; - Z = (float)vector.Z; - } - - /// - /// Constructor, builds a vector from a byte array - /// - /// Byte array containing three four-byte floats - /// Beginning position in the byte array - public Vector3(byte[] byteArray, int pos) - { - X = Y = Z = 0f; - FromBytes(byteArray, pos); - } - - public Vector3(Vector3 vector) - { - X = vector.X; - Y = vector.Y; - Z = vector.Z; - } - - #endregion Constructors - - #region Public Methods - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public void Abs() - { - if (X < 0) - X = -X; - if (Y < 0) - Y = -Y; - if (Z < 0) - Z = -Z; - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public void Min(Vector3 v) - { - if (v.X < X) X = v.X; - if (v.Y < Y) Y = v.Y; - if (v.Z < Z) Z = v.Z; - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public void Max(Vector3 v) - { - if (v.X > X) X = v.X; - if (v.Y > Y) Y = v.Y; - if (v.Z > Z) Z = v.Z; - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public float Length() - { - return (float)Math.Sqrt((X * X) + (Y * Y) + (Z * Z)); - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public float LengthSquared() - { - return (X * X) + (Y * Y) + (Z * Z); - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public void Normalize() - { - float factor = LengthSquared(); - if (factor > 1e-6f) - { - factor = 1f / (float)Math.Sqrt(factor); - X *= factor; - Y *= factor; - Z *= factor; - } - else - { - X = 0f; - Y = 0f; - Z = 0f; - } - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public bool ApproxEquals(Vector3 vec) - { - return Utils.ApproxEqual(X, vec.X) && - Utils.ApproxEqual(Y, vec.Y) && - Utils.ApproxEqual(Z, vec.Z); - } - - /// - /// Test if this vector is equal to another vector, within a given - /// tolerance range - /// - /// Vector to test against - /// The acceptable magnitude of difference - /// between the two vectors - /// True if the magnitude of difference between the two vectors - /// is less than the given tolerance, otherwise false - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public bool ApproxEquals(Vector3 vec, float tolerance) - { - return Utils.ApproxEqual(X, vec.X, tolerance) && - Utils.ApproxEqual(Y, vec.Y, tolerance) && - Utils.ApproxEqual(Z, vec.Z, tolerance); - } - - /// - /// IComparable.CompareTo implementation - /// - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public int CompareTo(Vector3 vector) - { - return LengthSquared().CompareTo(vector.LengthSquared()); - } - - /// - /// Test if this vector is composed of all finite numbers - /// - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public bool IsFinite() - { - return (Utils.IsFinite(X) && Utils.IsFinite(Y) && Utils.IsFinite(Z)); - } - - /// - /// Builds a vector from a byte array - /// - /// Byte array containing a 12 byte vector - /// Beginning position in the byte array - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public void FromBytes(byte[] byteArray, int pos) - { - X = Utils.BytesToFloatSafepos(byteArray, pos); - Y = Utils.BytesToFloatSafepos(byteArray, pos + 4); - Z = Utils.BytesToFloatSafepos(byteArray, pos + 8); - } - - /// - /// Returns the raw bytes for this vector - /// - /// A 12 byte array containing X, Y, and Z - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public byte[] GetBytes() - { - byte[] dest = new byte[12]; - Utils.FloatToBytesSafepos(X, dest, 0); - Utils.FloatToBytesSafepos(Y, dest, 4); - Utils.FloatToBytesSafepos(Z, dest, 8); - return dest; - } - - /// - /// Writes the raw bytes for this vector to a byte array - /// - /// Destination byte array - /// Position in the destination array to start - /// writing. Must be at least 12 bytes before the end of the array - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public void ToBytes(byte[] dest, int pos) - { - Utils.FloatToBytesSafepos(X, dest, pos); - Utils.FloatToBytesSafepos(Y, dest, pos + 4); - Utils.FloatToBytesSafepos(Z, dest, pos + 8); - } - - #endregion Public Methods - - #region Static Methods - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public static Vector3 Add(Vector3 value1, Vector3 value2) - { - return new Vector3(value1.X + value2.X, value1.Y + value2.Y, value1.Z + value2.Z); - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public static Vector3 Clamp(Vector3 value1, Vector3 min, Vector3 max) - { - return new Vector3( - Utils.Clamp(value1.X, min.X, max.X), - Utils.Clamp(value1.Y, min.Y, max.Y), - Utils.Clamp(value1.Z, min.Z, max.Z)); - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public static Vector3 Cross(Vector3 value1, Vector3 value2) - { - return new Vector3( - value1.Y * value2.Z - value2.Y * value1.Z, - value1.Z * value2.X - value2.Z * value1.X, - value1.X * value2.Y - value2.X * value1.Y); - } - - public static float Distance(Vector3 value1, Vector3 value2) - { - return (float)Math.Sqrt(DistanceSquared(value1, value2)); - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public static float DistanceSquared(Vector3 value1, Vector3 value2) - { - float x = value1.X - value2.X; - x *= x; - float y = value1.Y - value2.Y; - y *= y; - float z = value1.Z - value2.Z; - x += y; - - return (x + z * z); - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public static Vector3 Divide(Vector3 value1, Vector3 value2) - { - return new Vector3(value1.X / value2.X, value1.Y / value2.Y, value1.Z / value2.Z); - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public static Vector3 Divide(Vector3 value1, float value2) - { - float factor = 1f / value2; - return new Vector3(value1.X * factor, value1.Y * factor, value1.Z * factor); - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public static float Dot(Vector3 value1, Vector3 value2) - { - return (value1.X * value2.X) + (value1.Y * value2.Y) + (value1.Z * value2.Z); - } - - public static Vector3 Lerp(Vector3 value1, Vector3 value2, float amount) - { - return new Vector3( - Utils.Lerp(value1.X, value2.X, amount), - Utils.Lerp(value1.Y, value2.Y, amount), - Utils.Lerp(value1.Z, value2.Z, amount)); - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public static float Mag(Vector3 value) - { - return value.Length(); - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public static Vector3 Max(Vector3 value1, Vector3 value2) - { - return new Vector3( - Math.Max(value1.X, value2.X), - Math.Max(value1.Y, value2.Y), - Math.Max(value1.Z, value2.Z)); - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public static Vector3 Min(Vector3 value1, Vector3 value2) - { - return new Vector3( - Math.Min(value1.X, value2.X), - Math.Min(value1.Y, value2.Y), - Math.Min(value1.Z, value2.Z)); - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public static Vector3 Multiply(Vector3 value1, Vector3 value2) - { - return new Vector3(value1.X * value2.X, value1.Y * value2.Y, value1.Z * value2.Z); - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public static Vector3 Multiply(Vector3 value1, float scaleFactor) - { - return new Vector3(value1.X * scaleFactor, value1.Y * scaleFactor, value1.Z * scaleFactor); - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public static Vector3 Negate(Vector3 value) - { - return new Vector3(-value.X, -value.Y, -value.Z); - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public static Vector3 Normalize(Vector3 value) - { - float factor = value.LengthSquared(); - if (factor > 1e-6f) - { - factor = 1f / (float)Math.Sqrt(factor); - return new Vector3(value.X *= factor, value.Y *= factor, value.Z *= factor); - } - return Vector3.Zero; - } - - /// - /// Parse a vector from a string - /// - /// A string representation of a 3D vector, enclosed - /// in arrow brackets and separated by commas - public static Vector3 Parse(string val) - { - char[] splitChar = { ',' }; - string[] split = val.Replace("<", String.Empty).Replace(">", String.Empty).Split(splitChar); - return new Vector3( - Single.Parse(split[0].Trim(), Utils.EnUsCulture), - Single.Parse(split[1].Trim(), Utils.EnUsCulture), - Single.Parse(split[2].Trim(), Utils.EnUsCulture)); - } - - public static bool TryParse(string val, out Vector3 result) - { - try - { - result = Parse(val); - return true; - } - catch (Exception) - { - result = Vector3.Zero; - return false; - } - } - - /// - /// Calculate the rotation between two vectors - /// - /// Normalized directional vector (such as 1,0,0 for forward facing) - /// Normalized target vector - public static Quaternion RotationBetween(Vector3 a, Vector3 b) - { - const double piOverfour = 0.25 * Math.PI; - double magProduct = Math.Sqrt(a.LengthSquared() * b.LengthSquared()); - double angle; - if (magProduct > 1e-6) - { - float dotProduct = Dot(a, b); - if (dotProduct < 1e-6) - angle = piOverfour; - else - angle = 0.5 * Math.Acos(dotProduct / magProduct); - } - else - angle = piOverfour; - - Vector3 axis = Cross(a, b); - axis.Normalize(); - - float s = (float)Math.Sin(angle); - return new Quaternion( - axis.X * s, - axis.Y * s, - axis.Z * s, - (float)Math.Cos(angle)); - } - - /// - /// Interpolates between two vectors using a cubic equation - /// - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public static Vector3 SmoothStep(Vector3 value1, Vector3 value2, float amount) - { - return new Vector3( - Utils.SmoothStep(value1.X, value2.X, amount), - Utils.SmoothStep(value1.Y, value2.Y, amount), - Utils.SmoothStep(value1.Z, value2.Z, amount)); - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public static Vector3 Subtract(Vector3 value1, Vector3 value2) - { - return new Vector3(value1.X - value2.X, value1.Y - value2.Y, value1.Z - value2.Z); - } - - public static Vector3 Transform(Vector3 position, Matrix4 matrix) - { - return new Vector3( - (position.X * matrix.M11) + (position.Y * matrix.M21) + (position.Z * matrix.M31) + matrix.M41, - (position.X * matrix.M12) + (position.Y * matrix.M22) + (position.Z * matrix.M32) + matrix.M42, - (position.X * matrix.M13) + (position.Y * matrix.M23) + (position.Z * matrix.M33) + matrix.M43); - } - - public static Vector3 TransformNormal(Vector3 position, Matrix4 matrix) - { - return new Vector3( - (position.X * matrix.M11) + (position.Y * matrix.M21) + (position.Z * matrix.M31), - (position.X * matrix.M12) + (position.Y * matrix.M22) + (position.Z * matrix.M32), - (position.X * matrix.M13) + (position.Y * matrix.M23) + (position.Z * matrix.M33)); - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public static Vector3 Transform(Vector3 vec, Quaternion rot) - { - float x2 = rot.X + rot.X; - float y2 = rot.Y + rot.Y; - float z2 = rot.Z + rot.Z; - - float wx2 = rot.W * x2; - float wy2 = rot.W * y2; - float wz2 = rot.W * z2; - float xx2 = rot.X * x2; - float xy2 = rot.X * y2; - float xz2 = rot.X * z2; - float yy2 = rot.Y * y2; - float yz2 = rot.Y * z2; - float zz2 = rot.Z * z2; - - x2 = vec.X; - y2 = vec.Y; - z2 = vec.Z; - - return new Vector3( - x2 * (1.0f - yy2 - zz2) + y2 * (xy2 - wz2) + z2 * (xz2 + wy2), - x2 * (xy2 + wz2) + y2 * (1.0f - xx2 - zz2) + z2 * (yz2 - wx2), - x2 * (xz2 - wy2) + y2 * (yz2 + wx2) + z2 * (1.0f - xx2 - yy2)); - } - - #endregion Static Methods - - #region Overrides - - public override bool Equals(object obj) - { - return (obj is Vector3) ? this == (Vector3)obj : false; - } - - public bool Equals(Vector3 other) - { - return this == other; - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public override int GetHashCode() - { - int hash = X.GetHashCode(); - hash = Utils.CombineHash(hash, Y.GetHashCode()); - hash = Utils.CombineHash(hash, Y.GetHashCode()); - return hash; - } - - /// - /// Get a formatted string representation of the vector - /// - /// A string representation of the vector - public override string ToString() - { - return String.Format(Utils.EnUsCulture, "<{0}, {1}, {2}>", X, Y, Z); - } - - /// - /// Get a string representation of the vector elements with up to three - /// decimal digits and separated by spaces only - /// - /// Raw string representation of the vector - public string ToRawString() - { - CultureInfo enUs = new CultureInfo("en-us"); - enUs.NumberFormat.NumberDecimalDigits = 3; - - return String.Format(enUs, "{0} {1} {2}", X, Y, Z); - } - - #endregion Overrides - - #region Operators - - public static bool operator ==(Vector3 value1, Vector3 value2) - { - return value1.X == value2.X - && value1.Y == value2.Y - && value1.Z == value2.Z; - } - - public static bool operator !=(Vector3 value1, Vector3 value2) - { - return !(value1 == value2); - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public static Vector3 operator +(Vector3 value1, Vector3 value2) - { - return new Vector3(value1.X + value2.X, value1.Y + value2.Y, value1.Z + value2.Z); - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public static Vector3 operator -(Vector3 value) - { - return new Vector3(-value.X, -value.Y, -value.Z); - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public static Vector3 operator -(Vector3 value1, Vector3 value2) - { - return new Vector3(value1.X - value2.X, value1.Y - value2.Y, value1.Z - value2.Z); - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public static Vector3 operator *(Vector3 value1, Vector3 value2) - { - return new Vector3(value1.X * value2.X, value1.Y * value2.Y, value1.Z * value2.Z); - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public static Vector3 operator *(Vector3 value, float scaleFactor) - { - return new Vector3(value.X * scaleFactor, value.Y * scaleFactor, value.Z * scaleFactor); - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public static Vector3 operator *(Vector3 vec, Quaternion rot) - { - float x2 = rot.X + rot.X; - float y2 = rot.Y + rot.Y; - float z2 = rot.Z + rot.Z; - - float wx2 = rot.W * x2; - float wy2 = rot.W * y2; - float wz2 = rot.W * z2; - float xx2 = rot.X * x2; - float xy2 = rot.X * y2; - float xz2 = rot.X * z2; - float yy2 = rot.Y * y2; - float yz2 = rot.Y * z2; - float zz2 = rot.Z * z2; - - x2 = vec.X; - y2 = vec.Y; - z2 = vec.Z; - - return new Vector3( - x2 * (1.0f - yy2 - zz2) + y2 * (xy2 - wz2) + z2 * (xz2 + wy2), - x2 * (xy2 + wz2) + y2 * (1.0f - xx2 - zz2) + z2 * (yz2 - wx2), - x2 * (xz2 - wy2) + y2 * (yz2 + wx2) + z2 * (1.0f - xx2 - yy2)); - - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public static Vector3 operator *(Vector3 vector, Matrix4 matrix) - { - return Transform(vector, matrix); - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public static Vector3 operator /(Vector3 value1, Vector3 value2) - { - return new Vector3(value1.X / value2.X, value1.Y / value2.Y, value1.Z / value2.Z); - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public static Vector3 operator /(Vector3 value, float divider) - { - float factor = 1f / divider; - return new Vector3(value.X * factor, value.Y * factor, value.Z * factor); - } - - /// - /// Cross product between two vectors - /// - public static Vector3 operator %(Vector3 value1, Vector3 value2) - { - return Cross(value1, value2); - } - - /// - /// Explicit casting for Vector3d > Vector3 - /// - /// - /// - public static explicit operator Vector3(Vector3d value) - { - return new Vector3(value); - } - - #endregion Operators - - /// A vector with a value of 0,0,0 - public readonly static Vector3 Zero = new Vector3(); - /// A vector with a value of 1,1,1 - public readonly static Vector3 One = new Vector3(1f, 1f, 1f); - /// A unit vector facing forward (X axis), value 1,0,0 - public readonly static Vector3 UnitX = new Vector3(1f, 0f, 0f); - /// A unit vector facing left (Y axis), value 0,1,0 - public readonly static Vector3 UnitY = new Vector3(0f, 1f, 0f); - /// A unit vector facing up (Z axis), value 0,0,1 - public readonly static Vector3 UnitZ = new Vector3(0f, 0f, 1f); - public readonly static Vector3 MinValue = new Vector3(float.MinValue, float.MinValue, float.MinValue); - public readonly static Vector3 MaxValue = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue); - } -} +/* + * Copyright (c) 2006-2016, openmetaverse.co + * All rights reserved. + * + * - Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * - Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * - Neither the name of the openmetaverse.co nor the names + * of its contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Globalization; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Runtime.Intrinsics.X86; +using System.Runtime.Intrinsics; +using System.Text; +using System.Collections; + +namespace OpenMetaverse +{ + /// + /// A three-dimensional vector with floating-point values + /// + [Serializable] + [StructLayout(LayoutKind.Sequential)] + public struct Vector3 : IComparable, IEquatable + { + /// x value + public float X; + /// Y value + public float Y; + /// Z value + public float Z; + + #region Constructors + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Vector3(float x, float y, float z) + { + Unsafe.SkipInit(out this); + X = x; + Y = y; + Z = z; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Vector3(float value) + { + Unsafe.SkipInit(out this); + X = value; + Y = value; + Z = value; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Vector3(Vector2 value, float z) + { + Unsafe.SkipInit(out this); + X = value.X; + Y = value.Y; + Z = z; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Vector3(Vector3d vector) + { + Unsafe.SkipInit(out this); + X = (float)vector.X; + Y = (float)vector.Y; + Z = (float)vector.Z; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Vector3(Vector3 vector) + { + Unsafe.SkipInit(out this); + X = vector.X; + Y = vector.Y; + Z = vector.Z; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe Vector3(ref readonly Vector128 v) + { + Unsafe.SkipInit(out this); + Unsafe.As(ref X) = v.AsDouble().ToScalar(); + Z = Sse41.Extract(v, 0x02); + } + + /// + /// Constructor, builds a vector from a byte array + /// + /// Byte array containing three four-byte floats + /// Beginning position in the byte array + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Vector3(byte[] byteArray) + { + this = Unsafe.ReadUnaligned(ref MemoryMarshal.GetArrayDataReference(byteArray)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Vector3(byte[] byteArray, int pos) + { + this = Unsafe.ReadUnaligned(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(byteArray), pos)); + } + + public Vector3(ReadOnlySpan bytes) + { + this = Unsafe.ReadUnaligned(ref MemoryMarshal.GetReference(bytes)); + } + + #endregion Constructors + + #region Public Methods + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Abs() + { + if (X < 0) + X = -X; + if (Y < 0) + Y = -Y; + if (Z < 0) + Z = -Z; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Min(Vector3 v) + { + if (v.X < X) X = v.X; + if (v.Y < Y) Y = v.Y; + if (v.Z < Z) Z = v.Z; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Max(Vector3 v) + { + if (v.X > X) X = v.X; + if (v.Y > Y) Y = v.Y; + if (v.Z > Z) Z = v.Z; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Add(Vector3 v) + { + X += v.X; + Y += v.Y; + Z += v.Z; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Sub(Vector3 v) + { + X -= v.X; + Y -= v.Y; + Z -= v.Z; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Clamp(float min, float max) + { + if (X > max) + X = max; + else if (X < min) + X = min; + + if (Y > max) + Y = max; + else if (Y < min) + Y = min; + + if (Z > max) + Z = max; + else if (Z < min) + Z = min; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly float Length() + { + if(Sse41.IsSupported) + { + Vector128 ma = Vector128.LoadUnsafe(in X); + ma = Sse41.DotProduct(ma, ma, 0x71); + return MathF.Sqrt(ma.ToScalar()); + } + else + return MathF.Sqrt(X * X + Y * Y + Z * Z); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly float LengthSquared() + { + if(Sse41.IsSupported) + { + unsafe + { + Vector128 ma = Sse2.LoadScalarVector128((double *)Unsafe.AsPointer(ref Unsafe.AsRef(in X))).AsSingle(); + ma = Sse41.Insert(ma.AsUInt32(),Unsafe.As(ref Unsafe.AsRef(in Z)),0x02).AsSingle(); + ma = Sse41.DotProduct(ma, ma, 0x71); + return ma.ToScalar(); + } + } + else + return (X * X + Y * Y + Z * Z); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Normalize() + { + if(Sse41.IsSupported) + { + unsafe + { + Vector128 ma = Sse2.LoadScalarVector128((double*)Unsafe.AsPointer(ref Unsafe.AsRef(in X))).AsSingle(); + ma = Sse41.Insert(ma.AsUInt32(),Unsafe.As(ref Unsafe.AsRef(in Z)),0x02).AsSingle(); + + Vector128 mb = Sse41.DotProduct(ma, ma, 0x7f); + if(mb.ToScalar() > 1e-6f) + { + mb = Sse.Sqrt(mb); + ma = Sse.Divide(ma, mb); + + Unsafe.As(ref X) = ma.AsDouble().ToScalar(); + Z = Sse41.Extract(ma,0x02); + return; + } + } + + X = 0f; + Y = 0f; + Z = 0f; + return; + } + else + { + float factor = X * X + Y * Y + Z * Z; + if (factor > 1e-6f) + { + factor = 1f / MathF.Sqrt(factor); + X *= factor; + Y *= factor; + Z *= factor; + } + else + { + X = 0f; + Y = 0f; + Z = 0f; + } + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly bool ApproxEquals(Vector3 vec) + { + return Utils.ApproxEqual(X, vec.X) && + Utils.ApproxEqual(Y, vec.Y) && + Utils.ApproxEqual(Z, vec.Z); + } + + /// + /// Test if this vector is equal to another vector, within a given + /// tolerance range + /// + /// Vector to test against + /// The acceptable magnitude of difference + /// between the two vectors + /// True if the magnitude of difference between the two vectors + /// is less than the given tolerance, otherwise false + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly bool ApproxEquals(Vector3 vec, float tolerance) + { + return Utils.ApproxEqual(X, vec.X, tolerance) && + Utils.ApproxEqual(Y, vec.Y, tolerance) && + Utils.ApproxEqual(Z, vec.Z, tolerance); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly bool ApproxZero() + { + if (!Utils.ApproxZero(X)) + return false; + if (!Utils.ApproxZero(Y)) + return false; + if (!Utils.ApproxZero(Z)) + return false; + return true; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly bool ApproxZero(float tolerance) + { + if (!Utils.ApproxZero(X, tolerance)) + return false; + if (!Utils.ApproxZero(Y, tolerance)) + return false; + if (!Utils.ApproxZero(Z, tolerance)) + return false; + return true; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly bool IsZero() + { + if (X != 0) + return false; + if (Y != 0) + return false; + if (Z != 0) + return false; + return true; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly bool IsNotZero() + { + if (X != 0) + return true; + if (Y != 0) + return true; + if (Z != 0) + return true; + return false; + } + + /// + /// IComparable.CompareTo implementation + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly int CompareTo(Vector3 vector) + { + return LengthSquared().CompareTo(vector.LengthSquared()); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly float Dot(Vector3 value2) + { + return (X * value2.X) + (Y * value2.Y) + (Z * value2.Z); + } + public readonly float AbsDot(Vector3 value2) + { + return MathF.Abs(X * value2.X) + MathF.Abs(Y * value2.Y) + MathF.Abs(Z * value2.Z); + } + /// + /// Test if this vector is composed of all finite numbers + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly bool IsFinite() + { + return (Utils.IsFinite(X) && Utils.IsFinite(Y) && Utils.IsFinite(Z)); + } + + /// + /// Builds a vector from a byte array + /// + /// Byte array containing a 12 byte vector + /// Beginning position in the byte array + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void FromBytes(byte[] byteArray) + { + this = Unsafe.ReadUnaligned(ref MemoryMarshal.GetArrayDataReference(byteArray)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void FromBytes(byte[] byteArray, int pos) + { + this = Unsafe.ReadUnaligned(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(byteArray), pos)); + } + + /// + /// Returns the raw bytes for this vector + /// + /// A 12 byte array containing X, Y, and Z + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly byte[] GetBytes() + { + byte[] dest = new byte[12]; + Unsafe.WriteUnaligned(ref MemoryMarshal.GetArrayDataReference(dest), this); + return dest; + } + + /// + /// Writes the raw bytes for this vector to a byte array + /// + /// Destination byte array + /// Position in the destination array to start + /// writing. Must be at least 12 bytes before the end of the array + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly unsafe void ToBytes(byte[] dest, int pos) + { + //if (Utils.CanDirectCopyLE) + //{ + Unsafe.WriteUnaligned(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(dest), pos), this); + //} + //else + //{ + // Utils.FloatToBytesSafepos(X, dest, pos); + // Utils.FloatToBytesSafepos(Y, dest, pos + 4); + // Utils.FloatToBytesSafepos(Z, dest, pos + 8); + //} + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly unsafe void ToBytes(byte* dest) + { + if (Utils.CanDirectCopyLE) + *(Vector3*)dest = this; + else + { + Utils.FloatToBytes(X, dest); + Utils.FloatToBytes(Y, dest + 4); + Utils.FloatToBytes(Z, dest + 8); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly unsafe void ClampedToShortsBytes(float range, byte[] dest, int pos) + { + float a, b; + + a = MathF.Abs(X); + b = MathF.Abs(Y); + if (b > a) + a = b; + b = MathF.Abs(Z); + if (b > a) + a = b; + + ushort sx, sy, sz; + if (a > range) + { + a = range / a; + sx = Utils.FloatToUInt16(X * a, range); + sy = Utils.FloatToUInt16(Y * a, range); + sz = Utils.FloatToUInt16(Z * a, range); + } + else + { + sx = Utils.FloatToUInt16(X, range); + sy = Utils.FloatToUInt16(Y, range); + sz = Utils.FloatToUInt16(Z, range); + } + + if (Utils.CanDirectCopyLE) + { + fixed (byte* d = &dest[0]) + { + *(ushort*)(d + pos) = sx; + *(ushort*)(d + pos + 2) = sy; + *(ushort*)(d + pos + 4) = sz; + } + } + else + { + Utils.UInt16ToBytes(sx, dest, pos); + Utils.UInt16ToBytes(sy, dest, pos + 2); + Utils.UInt16ToBytes(sz, dest, pos + 4); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly unsafe void ClampedToShortsBytes(float range, byte* dest, int pos) + { + float a, b; + + a = MathF.Abs(X); + b = MathF.Abs(Y); + if (b > a) + a = b; + b = MathF.Abs(Z); + if (b > a) + a = b; + + ushort sx, sy, sz; + if (a > range) + { + a = range / a; + sx = Utils.FloatToUInt16(X * a, range); + sy = Utils.FloatToUInt16(Y * a, range); + sz = Utils.FloatToUInt16(Z * a, range); + } + else + { + sx = Utils.FloatToUInt16(X, range); + sy = Utils.FloatToUInt16(Y, range); + sz = Utils.FloatToUInt16(Z, range); + } + + if (Utils.CanDirectCopyLE) + { + *(ushort*)(dest + pos) = sx; + *(ushort*)(dest + pos + 2) = sy; + *(ushort*)(dest + pos + 4) = sz; + } + else + { + Utils.UInt16ToBytes(sx, dest, pos); + Utils.UInt16ToBytes(sy, dest, pos + 2); + Utils.UInt16ToBytes(sz, dest, pos + 4); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly unsafe void ClampedToShortsBytes(float range, byte* dest) + { + float a, b; + + a = MathF.Abs(X); + b = MathF.Abs(Y); + if (b > a) + a = b; + b = MathF.Abs(Z); + if (b > a) + a = b; + + ushort sx, sy, sc; + if (a > range) + { + a = range / a; + sx = Utils.FloatToUInt16(X * a, range); + sy = Utils.FloatToUInt16(Y * a, range); + sc = Utils.FloatToUInt16(Z * a, range); + } + else + { + sx = Utils.FloatToUInt16(X, range); + sy = Utils.FloatToUInt16(Y, range); + sc = Utils.FloatToUInt16(Z, range); + } + + if (Utils.CanDirectCopyLE) + { + *(ushort*)(dest) = sx; + *(ushort*)(dest + 2) = sy; + *(ushort*)(dest + 4) = sc; + } + else + { + Utils.UInt16ToBytes(sx, dest); + Utils.UInt16ToBytes(sy, dest + 2); + Utils.UInt16ToBytes(sc, dest + 4); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Rotate(Quaternion rot) + { + float x2 = rot.X + rot.X; + float y2 = rot.Y + rot.Y; + float z2 = rot.Z + rot.Z; + + float wx2 = rot.W * x2; + float wy2 = rot.W * y2; + float wz2 = rot.W * z2; + float xx2 = rot.X * x2; + float xy2 = rot.X * y2; + float xz2 = rot.X * z2; + float yy2 = rot.Y * y2; + float yz2 = rot.Y * z2; + float zz2 = rot.Z * z2; + + x2 = X; + y2 = Y; + z2 = Z; + + X = x2 * (1.0f - yy2 - zz2) + y2 * (xy2 - wz2) + z2 * (xz2 + wy2); + Y = x2 * (xy2 + wz2) + y2 * (1.0f - xx2 - zz2) + z2 * (yz2 - wx2); + Z = x2 * (xz2 - wy2) + y2 * (yz2 + wx2) + z2 * (1.0f - xx2 - yy2); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void InverseRotate(Quaternion rot) + { + float x2 = rot.X + rot.X; + float y2 = rot.Y + rot.Y; + float z2 = rot.Z + rot.Z; + + float wx2 = rot.W * x2; + float wy2 = rot.W * y2; + float wz2 = rot.W * z2; + + float xx2 = rot.X * x2; + float xy2 = rot.X * y2; + float xz2 = rot.X * z2; + float yy2 = rot.Y * y2; + float yz2 = rot.Y * z2; + float zz2 = rot.Z * z2; + + x2 = X; + y2 = Y; + z2 = Z; + + X = x2 * (1.0f - yy2 - zz2) + y2 * (xy2 + wz2) + z2 * (xz2 - wy2); + Y = x2 * (xy2 - wz2) + y2 * (1.0f - xx2 - zz2) + z2 * (yz2 + wx2); + Z = x2 * (xz2 + wy2) + y2 * (yz2 - wx2) + z2 * (1.0f - xx2 - yy2); + } + + //quaternion must be normalized <0,0,z,w> + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void RotateByQZ(Quaternion rot) + { + float z2 = rot.Z + rot.Z; + float zz2 = 1.0f - rot.Z * z2; + float wz2 = rot.W * z2; + + float ox = X; + float oy = Y; + + X = ox * zz2 - oy * wz2; + Y = ox * wz2 + oy * zz2; + } + + //quaternion must be normalized <0,0,z,w> + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void InverseRotateByQZ(Quaternion rot) + { + float z2 = rot.Z + rot.Z; + float zz2 = 1.0f - rot.Z * z2; + float wz2 = rot.W * z2; + + float ox = X; + float oy = Y; + + X = ox * zz2 + oy * wz2; + Y = oy * zz2 - ox * wz2; + } + + //shortQuaternion must be normalized + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void RotateByShortQZ(Vector2 shortQuaternion) + { + float z2 = shortQuaternion.X + shortQuaternion.X; + float zz2 = 1.0f - shortQuaternion.X * z2; + float wz2 = shortQuaternion.Y * z2; + + float ox = X; + float oy = Y; + + X = ox * zz2 - oy * wz2; + Y = ox * wz2 + oy * zz2; + } + + //quaternion must be normalized <0,0,z,w> + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void InverseRotateByShortQZ(Vector2 shortQuaternion) + { + float z2 = shortQuaternion.X + shortQuaternion.X; + float zz2 = 1.0f - shortQuaternion.X * z2; + float wz2 = shortQuaternion.Y * z2; + + float ox = X; + float oy = Y; + + X = ox * zz2 + oy * wz2; + Y = oy * zz2 - ox * wz2; + } + #endregion Public Methods + + #region Static Methods + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3 Add(Vector3 value1, Vector3 value2) + { + return new Vector3(value1.X + value2.X, value1.Y + value2.Y, value1.Z + value2.Z); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3 Abs(Vector3 value1) + { + return new Vector3(MathF.Abs(value1.X), MathF.Abs(value1.Y), MathF.Abs(value1.Z)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3 Clamp(Vector3 value1, float min, float max) + { + return new Vector3( + Utils.Clamp(value1.X, min, max), + Utils.Clamp(value1.Y, min, max), + Utils.Clamp(value1.Z, min, max)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3 Clamp(Vector3 value1, Vector3 min, Vector3 max) + { + return new Vector3( + Utils.Clamp(value1.X, min.X, max.X), + Utils.Clamp(value1.Y, min.Y, max.Y), + Utils.Clamp(value1.Z, min.Z, max.Z)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3 Cross(Vector3 value1, Vector3 value2) + { + return new Vector3( + value1.Y * value2.Z - value2.Y * value1.Z, + value1.Z * value2.X - value2.Z * value1.X, + value1.X * value2.Y - value2.X * value1.Y); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static float Distance(Vector3 value1, Vector3 value2) + { + return (float)Math.Sqrt(DistanceSquared(value1, value2)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static float DistanceSquared(Vector3 value1, Vector3 value2) + { + float x = value1.X - value2.X; + float y = value1.Y - value2.Y; + float z = value1.Z - value2.Z; + + return x * x + y * y + z * z; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3 Divide(Vector3 value1, Vector3 value2) + { + return new Vector3(value1.X / value2.X, value1.Y / value2.Y, value1.Z / value2.Z); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3 Divide(Vector3 value1, float value2) + { + float factor = 1f / value2; + return new Vector3(value1.X * factor, value1.Y * factor, value1.Z * factor); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static float Dot(Vector3 value1, Vector3 value2) + { + return (value1.X * value2.X) + (value1.Y * value2.Y) + (value1.Z * value2.Z); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static float AbsDot(Vector3 value1, Vector3 value2) + { + return MathF.Abs(value1.X * value2.X) + MathF.Abs(value1.Y * value2.Y) + MathF.Abs(value1.Z * value2.Z); + } + + public static Vector3 Lerp(Vector3 value1, Vector3 value2, float amount) + { + return new Vector3( + Utils.Lerp(value1.X, value2.X, amount), + Utils.Lerp(value1.Y, value2.Y, amount), + Utils.Lerp(value1.Z, value2.Z, amount)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static float Mag(Vector3 value) + { + return value.Length(); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3 Max(Vector3 value1, Vector3 value2) + { + return new Vector3( + Math.Max(value1.X, value2.X), + Math.Max(value1.Y, value2.Y), + Math.Max(value1.Z, value2.Z)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3 Min(Vector3 value1, Vector3 value2) + { + return new Vector3( + Math.Min(value1.X, value2.X), + Math.Min(value1.Y, value2.Y), + Math.Min(value1.Z, value2.Z)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3 Multiply(Vector3 value1, Vector3 value2) + { + return new Vector3(value1.X * value2.X, value1.Y * value2.Y, value1.Z * value2.Z); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3 Multiply(Vector3 value1, float scaleFactor) + { + return new Vector3(value1.X * scaleFactor, value1.Y * scaleFactor, value1.Z * scaleFactor); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3 Negate(Vector3 value) + { + return new Vector3(-value.X, -value.Y, -value.Z); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3 Normalize(float x, float y, float z) + { + Vector3 tmp = new(x, y, z); + tmp.Normalize(); + return tmp; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3 Normalize(ref readonly Vector3 value) + { + if(Sse41.IsSupported) + { + unsafe + { + Vector128 ma = Sse2.LoadScalarVector128((double *)Unsafe.AsPointer(ref Unsafe.AsRef(in value.X))).AsSingle(); + ma = Sse41.Insert(ma.AsUInt32(),Unsafe.As(ref Unsafe.AsRef(in value.Z)),0x02).AsSingle(); + + Vector128 mb = Sse41.DotProduct(ma, ma, 0x7f); + if(mb.ToScalar() > 1e-6f) + { + mb = Sse.Sqrt(mb); + ma = Sse.Divide(ma, mb); + return new(in ma); + } + return new(); + } + } + else + { + float factor = value.LengthSquared(); + if (factor > 1e-6f) + { + factor = 1f / MathF.Sqrt(factor); + return value * factor; + } + return new(); + } + } + + /// + /// Parse a vector from a string + /// + /// A string representation of a 3D vector, enclosed + /// in arrow brackets and separated by commas + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe Vector3 Parse(string val) + { + return Parse(val.AsSpan()); + } + + public static Vector3 Parse(ReadOnlySpan sp) + { + if (sp.Length < 5) + throw new FormatException("Invalid Vector3"); + + int start = 0; + int comma = 0; + char c; + + do + { + c = Unsafe.Add(ref MemoryMarshal.GetReference(sp), comma); + if (c == ',' || c == '<') + break; + } + while (++comma < sp.Length); + + if (c == '<') + { + start = ++comma; + while (++comma < sp.Length) + { + if (Unsafe.Add(ref MemoryMarshal.GetReference(sp), comma) == ',') + break; + } + } + + if (comma > sp.Length - 3) + throw new FormatException("Invalid Vector3"); + + if (!float.TryParse(sp[start..comma], NumberStyles.Float, Utils.EnUsCulture, out float x)) + throw new FormatException("Invalid Vector3"); + + start = ++comma; + while (++comma < sp.Length) + { + if (Unsafe.Add(ref MemoryMarshal.GetReference(sp), comma) == ',') + break; + } + if (comma > sp.Length - 1) + throw new FormatException("Invalid Vector3"); + + if (!float.TryParse(sp[start..comma], NumberStyles.Float, Utils.EnUsCulture, out float y)) + throw new FormatException("Invalid Vector3"); + + start = ++comma; + while (++comma < sp.Length) + { + c = Unsafe.Add(ref MemoryMarshal.GetReference(sp), comma); + if (c == ' ' || c == '>') + break; + } + + if (!float.TryParse(sp[start..comma], NumberStyles.Float, Utils.EnUsCulture, out float z)) + throw new FormatException("Invalid Vector3"); + return new Vector3(x, y, z); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool TryParse(string val, out Vector3 result) + { + return TryParse(val.AsSpan(), out result); + } + + public static bool TryParse(ReadOnlySpan sp, out Vector3 result) + { + if (sp.Length < 7) + { + result = Zero; + return false; + } + + int start = 0; + int comma = 0; + char c; + do + { + c = Unsafe.Add(ref MemoryMarshal.GetReference(sp), comma); + if (c == ',' || c == '<') + break; + } + while (++comma < sp.Length); + + if (c == '<') + { + start = ++comma; + while (++comma < sp.Length) + { + if (Unsafe.Add(ref MemoryMarshal.GetReference(sp), comma) == ',') + break; + } + if (start > sp.Length - 6) + { + result = Zero; + return false; + } + } + + if (!float.TryParse(sp[start..comma], NumberStyles.Float, Utils.EnUsCulture, out float x)) + { + result = Zero; + return false; + } + + start = ++comma; + while (++comma < sp.Length) + { + if (Unsafe.Add(ref MemoryMarshal.GetReference(sp), comma) == ',') + break; + } + if (comma > sp.Length - 3) + { + result = Zero; + return false; + } + + if (!float.TryParse(sp[start..comma], NumberStyles.Float, Utils.EnUsCulture, out float y)) + { + result = Zero; + return false; + } + + start = ++comma; + while (++comma < sp.Length) + { + c = Unsafe.Add(ref MemoryMarshal.GetReference(sp), comma); + if (c == ' ' || c == '>') + break; + } + + if (!float.TryParse(sp[start..comma], NumberStyles.Float, Utils.EnUsCulture, out float z)) + { + result = Zero; + return false; + } + + result = new Vector3(x, y, z); + return true; + } + + /// + /// Calculate the rotation between two vectors + /// + /// Normalized directional vector (such as 1,0,0 for forward facing) + /// Normalized target vector + public static Quaternion RotationBetween(Vector3 a, Vector3 b) + { + const float piOverfour = 0.25f * MathF.PI; + float magProduct = MathF.Sqrt(a.LengthSquared() * b.LengthSquared()); + float angle; + if(magProduct > 1e-6) + { + float dotProduct = Dot(a, b); + if(dotProduct < 1e-6f) + angle = piOverfour; + else + angle = 0.5f * MathF.Acos(dotProduct / magProduct); + } + else + angle = piOverfour; + + Vector3 axis = Cross(a, b); + axis.Normalize(); + + float s = MathF.Sin(angle); + return new Quaternion( + axis.X * s, + axis.Y * s, + axis.Z * s, + (float)Math.Cos(angle)); + } + + /// + /// Interpolates between two vectors using a cubic equation + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3 SmoothStep(Vector3 value1, Vector3 value2, float amount) + { + return new Vector3( + Utils.SmoothStep(value1.X, value2.X, amount), + Utils.SmoothStep(value1.Y, value2.Y, amount), + Utils.SmoothStep(value1.Z, value2.Z, amount)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3 Subtract(Vector3 value1, Vector3 value2) + { + return new Vector3(value1.X - value2.X, value1.Y - value2.Y, value1.Z - value2.Z); + } + /* + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static Vector3 SubtractS(Vector3 value1, Vector3 value2) + { + if (Sse2.IsSupported) + { + Vector128 ma = Sse2.LoadScalarVector128((double*)&value1.X).AsSingle(); + ma = Sse2.Shuffle(ma, Sse2.LoadScalarVector128((float*)&value1.Z), 0x44); + + Vector128 mb = Sse2.LoadScalarVector128((double*)&value2.X).AsSingle(); + mb = Sse2.Shuffle(mb, Sse2.LoadScalarVector128((float*)&value2.Z), 0x44); + + ma = Sse.Subtract(ma, mb); + Vector3 ret = new(); + Sse2.StoreScalar((double*)&ret.X, ma.AsDouble()); + Sse2.StoreScalar(&ret.Z, Sse2.Shuffle(ma.AsInt32(), 0x02).AsSingle()); + return ret; + } + else + return Subtract(value1, value2); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3 AddS(Vector3 value1, Vector3 value2) + { + if (Sse2.IsSupported) + { + unsafe + { + Vector128 ma = Sse2.LoadScalarVector128((double*)&value1.X).AsSingle(); + ma = Sse2.Shuffle(ma, Sse2.LoadScalarVector128(&value1.Z), 0x44); + + Vector128 mb = Sse2.LoadScalarVector128((double*)&value2.X).AsSingle(); + mb = Sse2.Shuffle(mb, Sse2.LoadScalarVector128(&value2.Z), 0x44); + + ma = Sse.Add(ma, mb); + Vector3 ret = new(); + Sse2.StoreScalar((double*)&ret.X, ma.AsDouble()); + Sse2.StoreScalar(&ret.Z, Sse2.Shuffle(ma.AsInt32(), 0x02).AsSingle()); + return ret; + } + } + else + return Subtract(value1, value2); + } + */ + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3 Transform(Vector3 position, Matrix3x3 matrix) + { + return new Vector3( + (position.X * matrix.M11) + (position.Y * matrix.M21) + (position.Z * matrix.M31), + (position.X * matrix.M12) + (position.Y * matrix.M22) + (position.Z * matrix.M32), + (position.X * matrix.M13) + (position.Y * matrix.M23) + (position.Z * matrix.M33)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3 TransformByTransposed(Vector3 position, Matrix3x3 matrix) + { + return new Vector3( + (position.X * matrix.M11) + (position.Y * matrix.M12) + (position.Z * matrix.M13), + (position.X * matrix.M21) + (position.Y * matrix.M22) + (position.Z * matrix.M23), + (position.X * matrix.M31) + (position.Y * matrix.M32) + (position.Z * matrix.M33)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3 Transform(Vector3 position, Matrix4 matrix) + { + return new Vector3( + (position.X * matrix.M11) + (position.Y * matrix.M21) + (position.Z * matrix.M31) + matrix.M41, + (position.X * matrix.M12) + (position.Y * matrix.M22) + (position.Z * matrix.M32) + matrix.M42, + (position.X * matrix.M13) + (position.Y * matrix.M23) + (position.Z * matrix.M33) + matrix.M43); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3 TransformNormal(Vector3 position, Matrix4 matrix) + { + return new Vector3( + (position.X * matrix.M11) + (position.Y * matrix.M21) + (position.Z * matrix.M31), + (position.X * matrix.M12) + (position.Y * matrix.M22) + (position.Z * matrix.M32), + (position.X * matrix.M13) + (position.Y * matrix.M23) + (position.Z * matrix.M33)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3 Transform(Vector3 vec, Quaternion rot) + { + return Rotate(vec, rot); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3 Rotate(Vector3 vec, Quaternion rot) + { + float x2 = rot.X + rot.X; + float y2 = rot.Y + rot.Y; + float z2 = rot.Z + rot.Z; + + float wx2 = rot.W * x2; + float wy2 = rot.W * y2; + float wz2 = rot.W * z2; + float xx2 = rot.X * x2; + float xy2 = rot.X * y2; + float xz2 = rot.X * z2; + float yy2 = rot.Y * y2; + float yz2 = rot.Y * z2; + float zz2 = rot.Z * z2; + + return new Vector3( + vec.X * (1.0f - yy2 - zz2) + vec.Y * (xy2 - wz2) + vec.Z * (xz2 + wy2), + vec.X * (xy2 + wz2) + vec.Y * (1.0f - xx2 - zz2) + vec.Z * (yz2 - wx2), + vec.X * (xz2 - wy2) + vec.Y * (yz2 + wx2) + vec.Z * (1.0f - xx2 - yy2)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3 InverseRotate(Vector3 vec, Quaternion rot) + { + float x2 = rot.X + rot.X; + float y2 = rot.Y + rot.Y; + float z2 = rot.Z + rot.Z; + + float wx2 = rot.W * x2; + float wy2 = rot.W * y2; + float wz2 = rot.W * z2; + float xx2 = rot.X * x2; + float xy2 = rot.X * y2; + float xz2 = rot.X * z2; + float yy2 = rot.Y * y2; + float yz2 = rot.Y * z2; + float zz2 = rot.Z * z2; + + return new Vector3( + vec.X * (1.0f - yy2 - zz2) + vec.Y * (xy2 + wz2) + vec.Z * (xz2 - wy2), + vec.X * (xy2 - wz2) + vec.Y * (1.0f - xx2 - zz2) + vec.Z * (yz2 + wx2), + vec.X * (xz2 + wy2) + vec.Y * (yz2 - wx2) + vec.Z * (1.0f - xx2 - yy2)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3 UnitXRotated(Quaternion rot) + { + float y2 = rot.Y + rot.Y; + float z2 = rot.Z + rot.Z; + + float wy2 = rot.W * y2; + float wz2 = rot.W * z2; + float xy2 = rot.X * y2; + float xz2 = rot.X * z2; + float yy2 = rot.Y * y2; + float zz2 = rot.Z * z2; + + return new Vector3(1.0f - yy2 - zz2, xy2 + wz2, xz2 - wy2); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3 UnitYRotated(Quaternion rot) + { + float x2 = rot.X + rot.X; + float y2 = rot.Y + rot.Y; + float z2 = rot.Z + rot.Z; + + float wx2 = rot.W * x2; + float wz2 = rot.W * z2; + float xx2 = rot.X * x2; + float xy2 = rot.X * y2; + float yz2 = rot.Y * z2; + float zz2 = rot.Z * z2; + + return new Vector3(xy2 - wz2, 1.0f - xx2 - zz2, yz2 + wx2); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3 UnitZRotated(Quaternion rot) + { + float x2 = rot.X + rot.X; + float y2 = rot.Y + rot.Y; + float z2 = rot.Z + rot.Z; + + float wx2 = rot.W * x2; + float wy2 = rot.W * y2; + float xx2 = rot.X * x2; + float xz2 = rot.X * z2; + float yy2 = rot.Y * y2; + float yz2 = rot.Y * z2; + + return new Vector3(xz2 + wy2, yz2 - wx2, 1.0f - xx2 - yy2); + } + + //quaternion must be normalized <0,0,z,w> + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3 RotateByQZ(Vector3 vec, Quaternion rot) + { + float z2 = rot.Z + rot.Z; + float wz2 = rot.W * z2; + float zz2 = 1.0f - rot.Z * z2; + + return new Vector3( + vec.X * zz2 - vec.Y * wz2, + vec.X * wz2 + vec.Y * zz2, + vec.Z); + } + + //quaternion must be normalized <0,0,z,w> + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3 InverseRotateByQZ(Vector3 vec, Quaternion rot) + { + float z2 = rot.Z + rot.Z; + float wz2 = rot.W * z2; + float zz2 = 1.0f - rot.Z * z2; + + return new Vector3( + vec.X * zz2 + vec.Y * wz2, + vec.Y * zz2 - vec.X * wz2, + vec.Z); + } + + //shortQuaternion must be normalized + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3 RotateByShortQZ(Vector3 vec, Vector2 shortQuaternion) + { + float z2 = shortQuaternion.X + shortQuaternion.X; + float zz2 = 1.0f - shortQuaternion.X * z2; + float wz2 = shortQuaternion.Y * z2; + + return new Vector3( + vec.X * zz2 - vec.Y * wz2, + vec.X * wz2 + vec.Y * zz2, + vec.Z); ; + } + + //shortQuaternion must be normalized + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3 InverseRotateByShortQZ(Vector3 vec, Vector2 shortQuaternion) + { + float z2 = shortQuaternion.X + shortQuaternion.X; + float zz2 = 1.0f - shortQuaternion.X * z2; + float wz2 = shortQuaternion.Y * z2; + + return new Vector3( + vec.X * zz2 + vec.Y * wz2, + vec.Y * zz2 - vec.X * wz2, + vec.Z); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Vector3 TransformPositionOffset(ref Quaternion ParentRot, ref Vector3 ParentPos) + { + float x2 = ParentRot.X + ParentRot.X; + float y2 = ParentRot.Y + ParentRot.Y; + float z2 = ParentRot.Z + ParentRot.Z; + + float wx2 = ParentRot.W * x2; + float wy2 = ParentRot.W * y2; + float wz2 = ParentRot.W * z2; + + float xx2 = ParentRot.X * x2; + float xy2 = ParentRot.X * y2; + float xz2 = ParentRot.X * z2; + + float yy2 = ParentRot.Y * y2; + float yz2 = ParentRot.Y * z2; + + float zz2 = ParentRot.Z * z2; + + return new Vector3( + ParentPos.X + X * (1.0f - yy2 - zz2) + Y * (xy2 - wz2) + Z * (xz2 + wy2), + ParentPos.Y + X * (xy2 + wz2) + Y * (1.0f - xx2 - zz2) + Z * (yz2 - wx2), + ParentPos.Z + X * (xz2 - wy2) + Y * (yz2 + wx2) + Z * (1.0f - xx2 - yy2)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Vector3 TransformPositionOffset(ref Matrix3x3 ParentRot, ref Vector3 ParentPos) + { + if (Sse41.IsSupported) + { + unsafe + { + Vector128 result = Sse.Multiply(Sse.LoadVector128((float*)Unsafe.AsPointer(ref ParentRot.M11)), Vector128.Create(X)); + result = Sse.Add(result, Sse.Multiply(Sse.LoadVector128((float*)Unsafe.AsPointer(ref ParentRot.M21)), Vector128.Create(Y))); + result = Sse.Add(result, Sse.Multiply(Sse.LoadVector128((float*)Unsafe.AsPointer(ref ParentRot.M31)), Vector128.Create(Z))); + result = Sse.Add(result, Sse.LoadVector128((float*)Unsafe.AsPointer(ref ParentPos))); + return new Vector3(result); + } + } + + return new Vector3( + ParentPos.X + X * ParentRot.M11 + Y * ParentRot.M21 + Z * ParentRot.M31, + ParentPos.Y + X * ParentRot.M12 + Y * ParentRot.M22 + Z * ParentRot.M32, + ParentPos.Z + X * ParentRot.M13 + Y * ParentRot.M23 + Z * ParentRot.M33); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3 TransformPositionOffset(ref Quaternion ParentRot, ref Vector3 ParentPos, ref Vector3 Partoffset) + { + float x2 = ParentRot.X + ParentRot.X; + float y2 = ParentRot.Y + ParentRot.Y; + float z2 = ParentRot.Z + ParentRot.Z; + + float wx2 = ParentRot.W * x2; + float wy2 = ParentRot.W * y2; + float wz2 = ParentRot.W * z2; + float xx2 = ParentRot.X * x2; + float xy2 = ParentRot.X * y2; + float xz2 = ParentRot.X * z2; + float yy2 = ParentRot.Y * y2; + float yz2 = ParentRot.Y * z2; + float zz2 = ParentRot.Z * z2; + + return new Vector3( + ParentPos.X + Partoffset.X * (1.0f - yy2 - zz2) + Partoffset.Y * (xy2 - wz2) + Partoffset.Z * (xz2 + wy2), + ParentPos.Y + Partoffset.X * (xy2 + wz2) + Partoffset.Y * (1.0f - xx2 - zz2) + Partoffset.Z * (yz2 - wx2), + ParentPos.Z + Partoffset.X * (xz2 - wy2) + Partoffset.Y * (yz2 + wx2) + Partoffset.Z * (1.0f - xx2 - yy2)); + } + + internal struct vtmp + { + public double a; + public float b; + public vtmp(Vector128 v) + { + a = Vector128.GetElement(v.AsDouble(), 0); + b = Vector128.GetElement(v, 2); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3 TransformPositionOffset(ref Matrix3x3 ParentRot, ref Vector3 ParentPos, ref Vector3 Partoffset) + { + if (Sse41.IsSupported) + { + unsafe + { + Vector128 result = Sse.Multiply(Sse.LoadVector128((float*)Unsafe.AsPointer(ref ParentRot.M11)), Vector128.Create(Partoffset.X)); + result = Sse.Add(result, Sse.Multiply(Sse.LoadVector128((float*)Unsafe.AsPointer(ref ParentRot.M21)), Vector128.Create(Partoffset.Y))); + result = Sse.Add(result, Sse.Multiply(Sse.LoadVector128((float*)Unsafe.AsPointer(ref ParentRot.M31)), Vector128.Create(Partoffset.Z))); + result = Sse.Add(result, Sse.LoadVector128((float*)Unsafe.AsPointer(ref ParentPos))); + return new Vector3(result); + } + } + + return new Vector3( + ParentPos.X + Partoffset.X * ParentRot.M11 + Partoffset.Y * ParentRot.M12 + Partoffset.Z * ParentRot.M13, + ParentPos.Y + Partoffset.X * ParentRot.M21 + Partoffset.Y * ParentRot.M22 + Partoffset.Z * ParentRot.M23, + ParentPos.Z + Partoffset.X * ParentRot.M31 + Partoffset.Y * ParentRot.M32 + Partoffset.Z * ParentRot.M33); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3 TransformPositionOffset(Matrix3x3 ParentRot, Vector3 ParentPos, Vector3 Partoffset) + { + if (Sse41.IsSupported) + { + unsafe + { + Vector128 result = Sse.Multiply(Sse.LoadVector128((float*)Unsafe.AsPointer(ref ParentRot.M11)), Vector128.Create(Partoffset.X)); + result = Sse.Add(result, Sse.Multiply(Sse.LoadVector128((float*)Unsafe.AsPointer(ref ParentRot.M21)), Vector128.Create(Partoffset.Y))); + result = Sse.Add(result, Sse.Multiply(Sse.LoadVector128((float*)Unsafe.AsPointer(ref ParentRot.M31)), Vector128.Create(Partoffset.Z))); + result = Sse.Add(result, Sse.LoadVector128((float*)Unsafe.AsPointer(ref ParentPos))); + return new Vector3(result); + } + } + + return new Vector3( + ParentPos.X + Partoffset.X * ParentRot.M11 + Partoffset.Y * ParentRot.M12 + Partoffset.Z * ParentRot.M13, + ParentPos.Y + Partoffset.X * ParentRot.M21 + Partoffset.Y * ParentRot.M22 + Partoffset.Z * ParentRot.M23, + ParentPos.Z + Partoffset.X * ParentRot.M31 + Partoffset.Y * ParentRot.M32 + Partoffset.Z * ParentRot.M33); + } + + #endregion Static Methods + + #region Overrides + + public readonly override bool Equals(object obj) + { + if (obj is not Vector3 other) + return false; + + if (X != other.X) + return false; + if (Y != other.Y) + return false; + if (Z != other.Z) + return false; + return true; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly bool Equals(Vector3 other) + { + if (X != other.X) + return false; + if (Y != other.Y) + return false; + if (Z != other.Z) + return false; + return true; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly bool NotEqual(Vector3 other) + { + if (X != other.X) + return true; + if (Y != other.Y) + return true; + if (Z != other.Z) + return true; + return false; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly override int GetHashCode() + { + int hash = X.GetHashCode(); + hash = Utils.CombineHash(hash, Y.GetHashCode()); + hash = Utils.CombineHash(hash, Z.GetHashCode()); + return hash; + } + + /// + /// Get a formatted string representation of the vector + /// + /// A string representation of the vector + public readonly override string ToString() + { + StringBuilder sb = new(); + sb.Append('<'); + sb.Append(X.ToString(Utils.EnUsCulture)); + sb.Append(", "); + sb.Append(Y.ToString(Utils.EnUsCulture)); + sb.Append(", "); + sb.Append(Z.ToString(Utils.EnUsCulture)); + sb.Append('>'); + return sb.ToString(); + } + + /// + /// Get a string representation of the vector elements with up to three + /// decimal digits and separated by spaces only + /// + /// Raw string representation of the vector + public readonly string ToRawString() + { + CultureInfo enUs = new CultureInfo("en-us"); + enUs.NumberFormat.NumberDecimalDigits = 3; + + StringBuilder sb = new(); + sb.Append(X.ToString(enUs)); + sb.Append(' '); + sb.Append(Y.ToString(enUs)); + sb.Append(' '); + sb.Append(Z.ToString(enUs)); + return sb.ToString(); + } + + #endregion Overrides + + #region Operators + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool operator ==(Vector3 value1, Vector3 value2) + { + if (value1.X != value2.X) + return false; + if (value1.Y != value2.Y) + return false; + if (value1.Z != value2.Z) + return false; + return true; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool operator !=(Vector3 value1, Vector3 value2) + { + if (value1.X != value2.X) + return true; + if (value1.Y != value2.Y) + return true; + if (value1.Z != value2.Z) + return true; + return false; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3 operator +(Vector3 value1, Vector3 value2) + { + return new Vector3(value1.X + value2.X, value1.Y + value2.Y, value1.Z + value2.Z); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3 operator -(Vector3 value) + { + return new Vector3(-value.X , -value.Y, -value.Z); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3 operator -(Vector3 value1, Vector3 value2) + { + return new Vector3(value1.X - value2.X, value1.Y - value2.Y, value1.Z - value2.Z); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3 operator *(Vector3 value1, Vector3 value2) + { + return new Vector3(value1.X * value2.X, value1.Y * value2.Y, value1.Z * value2.Z); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3 operator *(Vector3 value, float scaleFactor) + { + return new Vector3(value.X * scaleFactor, value.Y * scaleFactor, value.Z * scaleFactor); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3 operator *(Vector3 vec, Quaternion rot) + { + float x2 = rot.X + rot.X; + float y2 = rot.Y + rot.Y; + float z2 = rot.Z + rot.Z; + + float wx2 = rot.W * x2; + float wy2 = rot.W * y2; + float wz2 = rot.W * z2; + float xx2 = rot.X * x2; + float xy2 = rot.X * y2; + float xz2 = rot.X * z2; + float yy2 = rot.Y * y2; + float yz2 = rot.Y * z2; + float zz2 = rot.Z * z2; + + x2 = vec.X; + y2 = vec.Y; + z2 = vec.Z; + + return new Vector3( + x2 * (1.0f - yy2 - zz2) + y2 * (xy2 - wz2) + z2 * (xz2 + wy2), + x2 * (xy2 + wz2) + y2 * (1.0f - xx2 - zz2) + z2 * (yz2 - wx2), + x2 * (xz2 - wy2) + y2 * (yz2 + wx2) + z2 * (1.0f - xx2 - yy2)); + + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3 operator *(Vector3 vector, Matrix4 matrix) + { + return Transform(vector, matrix); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3 operator /(Vector3 value1, Vector3 value2) + { + return new Vector3(value1.X / value2.X, value1.Y / value2.Y, value1.Z / value2.Z); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3 operator /(Vector3 value, float divider) + { + float factor = 1f / divider; + return new Vector3(value.X * factor, value.Y * factor, value.Z * factor); + } + + /// + /// Cross product between two vectors + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3 operator %(Vector3 value1, Vector3 value2) + { + return Cross(value1, value2); + } + + /// + /// Explicit casting for Vector3d > Vector3 + /// + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static explicit operator Vector3(Vector3d value) + { + return new Vector3(value); + } + + #endregion Operators + + /// A vector with a value of 0,0,0 + public readonly static Vector3 Zero = new(); + /// A vector with a value of 1,1,1 + public readonly static Vector3 One = new(1f); + /// A unit vector facing forward (X axis), value 1,0,0 + public readonly static Vector3 UnitX = new(1f, 0f, 0f); + /// A unit vector facing left (Y axis), value 0,1,0 + public readonly static Vector3 UnitY = new(0f, 1f, 0f); + /// A unit vector facing up (Z axis), value 0,0,1 + public readonly static Vector3 UnitZ = new(0f, 0f, 1f); + public readonly static Vector3 MinValue = new(float.MinValue, float.MinValue, float.MinValue); + public readonly static Vector3 MaxValue = new(float.MaxValue, float.MaxValue, float.MaxValue); + } +} diff --git a/OpenMetaverse.Types/Vector3d.cs b/OpenMetaverse.Types/Vector3d.cs index 1289834c..2ff19ffc 100644 --- a/OpenMetaverse.Types/Vector3d.cs +++ b/OpenMetaverse.Types/Vector3d.cs @@ -1,499 +1,650 @@ -/* - * Copyright (c) 2006-2016, openmetaverse.co - * All rights reserved. - * - * - Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, this - * list of conditions and the following disclaimer. - * - Neither the name of the openmetaverse.co nor the names - * of its contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Globalization; -using System.Runtime.InteropServices; - -namespace OpenMetaverse -{ - /// - /// A three-dimensional vector with doubleing-point values - /// - [Serializable] - [StructLayout(LayoutKind.Sequential)] - public struct Vector3d : IComparable, IEquatable - { - /// X value - public double X; - /// Y value - public double Y; - /// Z value - public double Z; - - #region Constructors - - public Vector3d(double x, double y, double z) - { - X = x; - Y = y; - Z = z; - } - - public Vector3d(double value) - { - X = value; - Y = value; - Z = value; - } - - /// - /// Constructor, builds a vector from a byte array - /// - /// Byte array containing three eight-byte doubles - /// Beginning position in the byte array - public Vector3d(byte[] byteArray, int pos) - { - X = Y = Z = 0d; - FromBytes(byteArray, pos); - } - - public Vector3d(Vector3 vector) - { - X = vector.X; - Y = vector.Y; - Z = vector.Z; - } - - public Vector3d(Vector3d vector) - { - X = vector.X; - Y = vector.Y; - Z = vector.Z; - } - - #endregion Constructors - - #region Public Methods - - public double Length() - { - return Math.Sqrt(DistanceSquared(this, Zero)); - } - - public double LengthSquared() - { - return DistanceSquared(this, Zero); - } - - public void Normalize() - { - this = Normalize(this); - } - - /// - /// Test if this vector is equal to another vector, within a given - /// tolerance range - /// - /// Vector to test against - /// The acceptable magnitude of difference - /// between the two vectors - /// True if the magnitude of difference between the two vectors - /// is less than the given tolerance, otherwise false - public bool ApproxEquals(Vector3d vec, double tolerance) - { - Vector3d diff = this - vec; - return (diff.LengthSquared() <= tolerance * tolerance); - } - - /// - /// IComparable.CompareTo implementation - /// - public int CompareTo(Vector3d vector) - { - return this.Length().CompareTo(vector.Length()); - } - - /// - /// Test if this vector is composed of all finite numbers - /// - public bool IsFinite() - { - return (Utils.IsFinite(X) && Utils.IsFinite(Y) && Utils.IsFinite(Z)); - } - - /// - /// Builds a vector from a byte array - /// - /// Byte array containing a 24 byte vector - /// Beginning position in the byte array - public void FromBytes(byte[] byteArray, int pos) - { - X = Utils.BytesToDouble(byteArray, pos); - Y = Utils.BytesToDouble(byteArray, pos + 8); - Z = Utils.BytesToDouble(byteArray, pos + 16); - } - - /// - /// Returns the raw bytes for this vector - /// - /// A 24 byte array containing X, Y, and Z - public byte[] GetBytes() - { - byte[] byteArray = new byte[24]; - Utils.DoubleToBytes(X, byteArray, 0); - Utils.DoubleToBytes(Y, byteArray, 8); - Utils.DoubleToBytes(Z, byteArray, 16); - return byteArray; - } - - /// - /// Writes the raw bytes for this vector to a byte array - /// - /// Destination byte array - /// Position in the destination array to start - /// writing. Must be at least 24 bytes before the end of the array - public void ToBytes(byte[] dest, int pos) - { - Utils.DoubleToBytes(X, dest, pos); - Utils.DoubleToBytes(Y, dest, pos + 8); - Utils.DoubleToBytes(Z, dest, pos + 16); - } - - #endregion Public Methods - - #region Static Methods - - public static Vector3d Add(Vector3d value1, Vector3d value2) - { - value1.X += value2.X; - value1.Y += value2.Y; - value1.Z += value2.Z; - return value1; - } - - public static Vector3d Clamp(Vector3d value1, Vector3d min, Vector3d max) - { - return new Vector3d( - Utils.Clamp(value1.X, min.X, max.X), - Utils.Clamp(value1.Y, min.Y, max.Y), - Utils.Clamp(value1.Z, min.Z, max.Z)); - } - - public static Vector3d Cross(Vector3d value1, Vector3d value2) - { - return new Vector3d( - value1.Y * value2.Z - value2.Y * value1.Z, - value1.Z * value2.X - value2.Z * value1.X, - value1.X * value2.Y - value2.X * value1.Y); - } - - public static double Distance(Vector3d value1, Vector3d value2) - { - return Math.Sqrt(DistanceSquared(value1, value2)); - } - - public static double DistanceSquared(Vector3d value1, Vector3d value2) - { - return - (value1.X - value2.X) * (value1.X - value2.X) + - (value1.Y - value2.Y) * (value1.Y - value2.Y) + - (value1.Z - value2.Z) * (value1.Z - value2.Z); - } - - public static Vector3d Divide(Vector3d value1, Vector3d value2) - { - value1.X /= value2.X; - value1.Y /= value2.Y; - value1.Z /= value2.Z; - return value1; - } - - public static Vector3d Divide(Vector3d value1, double value2) - { - double factor = 1d / value2; - value1.X *= factor; - value1.Y *= factor; - value1.Z *= factor; - return value1; - } - - public static double Dot(Vector3d value1, Vector3d value2) - { - return value1.X * value2.X + value1.Y * value2.Y + value1.Z * value2.Z; - } - - public static Vector3d Lerp(Vector3d value1, Vector3d value2, double amount) - { - return new Vector3d( - Utils.Lerp(value1.X, value2.X, amount), - Utils.Lerp(value1.Y, value2.Y, amount), - Utils.Lerp(value1.Z, value2.Z, amount)); - } - - public static Vector3d Max(Vector3d value1, Vector3d value2) - { - return new Vector3d( - Math.Max(value1.X, value2.X), - Math.Max(value1.Y, value2.Y), - Math.Max(value1.Z, value2.Z)); - } - - public static Vector3d Min(Vector3d value1, Vector3d value2) - { - return new Vector3d( - Math.Min(value1.X, value2.X), - Math.Min(value1.Y, value2.Y), - Math.Min(value1.Z, value2.Z)); - } - - public static Vector3d Multiply(Vector3d value1, Vector3d value2) - { - value1.X *= value2.X; - value1.Y *= value2.Y; - value1.Z *= value2.Z; - return value1; - } - - public static Vector3d Multiply(Vector3d value1, double scaleFactor) - { - value1.X *= scaleFactor; - value1.Y *= scaleFactor; - value1.Z *= scaleFactor; - return value1; - } - - public static Vector3d Negate(Vector3d value) - { - value.X = -value.X; - value.Y = -value.Y; - value.Z = -value.Z; - return value; - } - - public static Vector3d Normalize(Vector3d value) - { - double factor = Distance(value, Zero); - if (factor > Double.Epsilon) - { - factor = 1d / factor; - value.X *= factor; - value.Y *= factor; - value.Z *= factor; - } - else - { - value.X = 0d; - value.Y = 0d; - value.Z = 0d; - } - return value; - } - - /// - /// Parse a vector from a string - /// - /// A string representation of a 3D vector, enclosed - /// in arrow brackets and separated by commas - public static Vector3d Parse(string val) - { - char[] splitChar = { ',' }; - string[] split = val.Replace("<", String.Empty).Replace(">", String.Empty).Split(splitChar); - return new Vector3d( - Double.Parse(split[0].Trim(), Utils.EnUsCulture), - Double.Parse(split[1].Trim(), Utils.EnUsCulture), - Double.Parse(split[2].Trim(), Utils.EnUsCulture)); - } - - public static bool TryParse(string val, out Vector3d result) - { - try - { - result = Parse(val); - return true; - } - catch (Exception) - { - result = Vector3d.Zero; - return false; - } - } - - /// - /// Interpolates between two vectors using a cubic equation - /// - public static Vector3d SmoothStep(Vector3d value1, Vector3d value2, double amount) - { - return new Vector3d( - Utils.SmoothStep(value1.X, value2.X, amount), - Utils.SmoothStep(value1.Y, value2.Y, amount), - Utils.SmoothStep(value1.Z, value2.Z, amount)); - } - - public static Vector3d Subtract(Vector3d value1, Vector3d value2) - { - value1.X -= value2.X; - value1.Y -= value2.Y; - value1.Z -= value2.Z; - return value1; - } - - #endregion Static Methods - - #region Overrides - - public override bool Equals(object obj) - { - return (obj is Vector3d) ? this == (Vector3d)obj : false; - } - - public bool Equals(Vector3d other) - { - return this == other; - } - - public override int GetHashCode() - { - return X.GetHashCode() ^ Y.GetHashCode() ^ Z.GetHashCode(); - } - - /// - /// Get a formatted string representation of the vector - /// - /// A string representation of the vector - public override string ToString() - { - return String.Format(Utils.EnUsCulture, "<{0}, {1}, {2}>", X, Y, Z); - } - - /// - /// Get a string representation of the vector elements with up to three - /// decimal digits and separated by spaces only - /// - /// Raw string representation of the vector - public string ToRawString() - { - CultureInfo enUs = new CultureInfo("en-us"); - enUs.NumberFormat.NumberDecimalDigits = 3; - - return String.Format(enUs, "{0} {1} {2}", X, Y, Z); - } - - #endregion Overrides - - #region Operators - - public static bool operator ==(Vector3d value1, Vector3d value2) - { - return value1.X == value2.X - && value1.Y == value2.Y - && value1.Z == value2.Z; - } - - public static bool operator !=(Vector3d value1, Vector3d value2) - { - return !(value1 == value2); - } - - public static Vector3d operator +(Vector3d value1, Vector3d value2) - { - value1.X += value2.X; - value1.Y += value2.Y; - value1.Z += value2.Z; - return value1; - } - - public static Vector3d operator -(Vector3d value) - { - value.X = -value.X; - value.Y = -value.Y; - value.Z = -value.Z; - return value; - } - - public static Vector3d operator -(Vector3d value1, Vector3d value2) - { - value1.X -= value2.X; - value1.Y -= value2.Y; - value1.Z -= value2.Z; - return value1; - } - - public static Vector3d operator *(Vector3d value1, Vector3d value2) - { - value1.X *= value2.X; - value1.Y *= value2.Y; - value1.Z *= value2.Z; - return value1; - } - - public static Vector3d operator *(Vector3d value, double scaleFactor) - { - value.X *= scaleFactor; - value.Y *= scaleFactor; - value.Z *= scaleFactor; - return value; - } - - public static Vector3d operator /(Vector3d value1, Vector3d value2) - { - value1.X /= value2.X; - value1.Y /= value2.Y; - value1.Z /= value2.Z; - return value1; - } - - public static Vector3d operator /(Vector3d value, double divider) - { - double factor = 1d / divider; - value.X *= factor; - value.Y *= factor; - value.Z *= factor; - return value; - } - - /// - /// Cross product between two vectors - /// - public static Vector3d operator %(Vector3d value1, Vector3d value2) - { - return Cross(value1, value2); - } - - /// - /// Implicit casting for Vector3 > Vector3d - /// - /// - /// - public static implicit operator Vector3d(Vector3 value) - { - return new Vector3d(value); - } - - #endregion Operators - - /// A vector with a value of 0,0,0 - public readonly static Vector3d Zero = new Vector3d(); - /// A vector with a value of 1,1,1 - public readonly static Vector3d One = new Vector3d(); - /// A unit vector facing forward (X axis), value of 1,0,0 - public readonly static Vector3d UnitX = new Vector3d(1d, 0d, 0d); - /// A unit vector facing left (Y axis), value of 0,1,0 - public readonly static Vector3d UnitY = new Vector3d(0d, 1d, 0d); - /// A unit vector facing up (Z axis), value of 0,0,1 - public readonly static Vector3d UnitZ = new Vector3d(0d, 0d, 1d); - } -} +/* + * Copyright (c) 2006-2016, openmetaverse.co + * All rights reserved. + * + * - Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * - Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * - Neither the name of the openmetaverse.co nor the names + * of its contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Runtime.InteropServices; +using System.Globalization; +using System.Text; +using System.Runtime.CompilerServices; + +namespace OpenMetaverse +{ + /// + /// A three-dimensional vector with doubleing-point values + /// + [Serializable] + [StructLayout(LayoutKind.Sequential)] + public struct Vector3d : IComparable, IEquatable + { + /// X value + public double X; + /// Y value + public double Y; + /// Z value + public double Z; + + #region Constructors + + public Vector3d(double x, double y, double z) + { + X = x; + Y = y; + Z = z; + } + + public Vector3d(double value) + { + X = value; + Y = value; + Z = value; + } + + /// + /// Constructor, builds a vector from a byte array + /// + /// Byte array containing three eight-byte doubles + /// Beginning position in the byte array + public Vector3d(byte[] byteArray, int pos) + { + X = Y = Z = 0d; + FromBytes(byteArray, pos); + } + + public Vector3d(Vector3 vector) + { + X = vector.X; + Y = vector.Y; + Z = vector.Z; + } + + public Vector3d(Vector3d vector) + { + X = vector.X; + Y = vector.Y; + Z = vector.Z; + } + + #endregion Constructors + + #region Public Methods + + public double Length() + { + return Math.Sqrt(DistanceSquared(this, Zero)); + } + + public double LengthSquared() + { + return DistanceSquared(this, Zero); + } + + public void Normalize() + { + this = Normalize(this); + } + + /// + /// Test if this vector is equal to another vector, within a given + /// tolerance range + /// + /// Vector to test against + /// The acceptable magnitude of difference + /// between the two vectors + /// True if the magnitude of difference between the two vectors + /// is less than the given tolerance, otherwise false + public bool ApproxEquals(Vector3d vec, double tolerance) + { + Vector3d diff = this - vec; + return (diff.LengthSquared() <= tolerance * tolerance); + } + + /// + /// IComparable.CompareTo implementation + /// + public int CompareTo(Vector3d vector) + { + return this.Length().CompareTo(vector.Length()); + } + + /// + /// Test if this vector is composed of all finite numbers + /// + public bool IsFinite() + { + return (Utils.IsFinite(X) && Utils.IsFinite(Y) && Utils.IsFinite(Z)); + } + + /// + /// Builds a vector from a byte array + /// + /// Byte array containing a 24 byte vector + /// Beginning position in the byte array + public void FromBytes(byte[] byteArray, int pos) + { + X = Utils.BytesToDouble(byteArray, pos); + Y = Utils.BytesToDouble(byteArray, pos + 8); + Z = Utils.BytesToDouble(byteArray, pos + 16); + } + + /// + /// Returns the raw bytes for this vector + /// + /// A 24 byte array containing X, Y, and Z + public byte[] GetBytes() + { + byte[] byteArray = new byte[24]; + Utils.DoubleToBytes(X, byteArray, 0); + Utils.DoubleToBytes(Y, byteArray, 8); + Utils.DoubleToBytes(Z, byteArray, 16); + return byteArray; + } + + /// + /// Writes the raw bytes for this vector to a byte array + /// + /// Destination byte array + /// Position in the destination array to start + /// writing. Must be at least 24 bytes before the end of the array + public void ToBytes(byte[] dest, int pos) + { + Utils.DoubleToBytes(X, dest, pos); + Utils.DoubleToBytes(Y, dest, pos + 8); + Utils.DoubleToBytes(Z, dest, pos + 16); + } + + #endregion Public Methods + + #region Static Methods + + public static Vector3d Add(Vector3d value1, Vector3d value2) + { + value1.X += value2.X; + value1.Y += value2.Y; + value1.Z += value2.Z; + return value1; + } + + public static Vector3d Clamp(Vector3 value1, double min, double max) + { + return new Vector3d( + Utils.Clamp(value1.X, min, max), + Utils.Clamp(value1.Y, min, max), + Utils.Clamp(value1.Z, min, max)); + } + + public static Vector3d Clamp(Vector3d value1, Vector3d min, Vector3d max) + { + return new Vector3d( + Utils.Clamp(value1.X, min.X, max.X), + Utils.Clamp(value1.Y, min.Y, max.Y), + Utils.Clamp(value1.Z, min.Z, max.Z)); + } + + public static Vector3d Cross(Vector3d value1, Vector3d value2) + { + return new Vector3d( + value1.Y * value2.Z - value2.Y * value1.Z, + value1.Z * value2.X - value2.Z * value1.X, + value1.X * value2.Y - value2.X * value1.Y); + } + + public static double Distance(Vector3d value1, Vector3d value2) + { + return Math.Sqrt(DistanceSquared(value1, value2)); + } + + public static double DistanceSquared(Vector3d value1, Vector3d value2) + { + return + (value1.X - value2.X) * (value1.X - value2.X) + + (value1.Y - value2.Y) * (value1.Y - value2.Y) + + (value1.Z - value2.Z) * (value1.Z - value2.Z); + } + + public static Vector3d Divide(Vector3d value1, Vector3d value2) + { + value1.X /= value2.X; + value1.Y /= value2.Y; + value1.Z /= value2.Z; + return value1; + } + + public static Vector3d Divide(Vector3d value1, double value2) + { + double factor = 1d / value2; + value1.X *= factor; + value1.Y *= factor; + value1.Z *= factor; + return value1; + } + + public static double Dot(Vector3d value1, Vector3d value2) + { + return value1.X * value2.X + value1.Y * value2.Y + value1.Z * value2.Z; + } + + public static Vector3d Lerp(Vector3d value1, Vector3d value2, double amount) + { + return new Vector3d( + Utils.Lerp(value1.X, value2.X, amount), + Utils.Lerp(value1.Y, value2.Y, amount), + Utils.Lerp(value1.Z, value2.Z, amount)); + } + + public static Vector3d Max(Vector3d value1, Vector3d value2) + { + return new Vector3d( + Math.Max(value1.X, value2.X), + Math.Max(value1.Y, value2.Y), + Math.Max(value1.Z, value2.Z)); + } + + public static Vector3d Min(Vector3d value1, Vector3d value2) + { + return new Vector3d( + Math.Min(value1.X, value2.X), + Math.Min(value1.Y, value2.Y), + Math.Min(value1.Z, value2.Z)); + } + + public static Vector3d Multiply(Vector3d value1, Vector3d value2) + { + value1.X *= value2.X; + value1.Y *= value2.Y; + value1.Z *= value2.Z; + return value1; + } + + public static Vector3d Multiply(Vector3d value1, double scaleFactor) + { + value1.X *= scaleFactor; + value1.Y *= scaleFactor; + value1.Z *= scaleFactor; + return value1; + } + + public static Vector3d Negate(Vector3d value) + { + value.X = -value.X; + value.Y = -value.Y; + value.Z = -value.Z; + return value; + } + + public static Vector3d Normalize(Vector3d value) + { + double factor = Distance(value, Zero); + if (factor > Double.Epsilon) + { + factor = 1d / factor; + return new Vector3d(value.X * factor, value.Y * factor, value.Z * factor); + } + return Vector3.Zero; + } + + /// + /// Parse a vector from a string + /// + /// A string representation of a 3D vector, enclosed + /// in arrow brackets and separated by commas + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe Vector3d Parse(string val) + { + return Parse(val.AsSpan()); + } + + public static unsafe Vector3d Parse(ReadOnlySpan sp) + { + if (sp.Length < 7) + throw new FormatException("Invalid Vector3"); + + int start = 0; + fixed (char* p = sp) + { + while (start < sp.Length) + { + if (p[start++] == '<') + break; + } + if (start > sp.Length - 6) + throw new FormatException("Invalid Vector3"); + + int comma1 = start + 1; + while (comma1 < sp.Length) + { + if (p[comma1] == ',') + break; + comma1++; + } + if (comma1 > sp.Length - 5) + throw new FormatException("Invalid Vector3"); + + if (!double.TryParse(sp[start..comma1], NumberStyles.Float, Utils.EnUsCulture, out double x)) + throw new FormatException("Invalid Vector3"); + + comma1++; + start = comma1; + comma1++; + while (comma1 < sp.Length) + { + if (p[comma1] == ',') + break; + comma1++; + } + if (comma1 > sp.Length - 3) + throw new FormatException("Invalid Vector3"); + if (!double.TryParse(sp[start..comma1], NumberStyles.Float, Utils.EnUsCulture, out double y)) + throw new FormatException("Invalid Vector3"); + + comma1++; + start = comma1; + comma1++; + while (comma1 < sp.Length) + { + if (p[comma1] == '>') + break; + comma1++; + } + if (comma1 >= sp.Length) + throw new FormatException("Invalid Vector3"); + + if (!double.TryParse(sp[start..comma1], NumberStyles.Float, Utils.EnUsCulture, out double z)) + throw new FormatException("Invalid Vector3"); + return new Vector3d(x, y, z); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static bool TryParse(string val, out Vector3d result) + { + return TryParse(val.AsSpan(), out result); + } + + public unsafe static bool TryParse(ReadOnlySpan sp, out Vector3d result) + { + if (sp.Length < 7) + { + result = Zero; + return false; + } + + int start = 0; + fixed (char* p = sp) + { + while (start < sp.Length) + { + if (p[start++] == '<') + break; + } + if (start > sp.Length - 6) + { + result = Zero; + return false; + } + + int comma1 = start + 1; + while (comma1 < sp.Length) + { + if (p[comma1] == ',') + break; + comma1++; + } + if (comma1 > sp.Length - 5) + { + result = Zero; + return false; + } + + if (!double.TryParse(sp[start..comma1], NumberStyles.Float, Utils.EnUsCulture, out double x)) + { + result = Zero; + return false; + } + + comma1++; + start = comma1; + comma1++; + while (comma1 < sp.Length) + { + if (p[comma1] == ',') + break; + comma1++; + } + if (comma1 > sp.Length - 3) + { + result = Zero; + return false; + } + if (!double.TryParse(sp[start..comma1], NumberStyles.Float, Utils.EnUsCulture, out double y)) + { + result = Zero; + return false; + } + + comma1++; + start = comma1; + comma1++; + while (comma1 < sp.Length) + { + if (p[comma1] == '>') + break; + comma1++; + } + if (comma1 >= sp.Length) + { + result = Zero; + return false; + } + + if (!double.TryParse(sp[start..comma1], NumberStyles.Float, Utils.EnUsCulture, out double z)) + { + result = Zero; + return false; + } + result = new Vector3d(x, y, z); + return true; + } + } + + /// + /// Interpolates between two vectors using a cubic equation + /// + public static Vector3d SmoothStep(Vector3d value1, Vector3d value2, double amount) + { + return new Vector3d( + Utils.SmoothStep(value1.X, value2.X, amount), + Utils.SmoothStep(value1.Y, value2.Y, amount), + Utils.SmoothStep(value1.Z, value2.Z, amount)); + } + + public static Vector3d Subtract(Vector3d value1, Vector3d value2) + { + value1.X -= value2.X; + value1.Y -= value2.Y; + value1.Z -= value2.Z; + return value1; + } + + #endregion Static Methods + + #region Overrides + + public override bool Equals(object obj) + { + return (obj is Vector3d) ? this == (Vector3d)obj : false; + } + + public bool Equals(Vector3d other) + { + return this == other; + } + + public override int GetHashCode() + { + return X.GetHashCode() ^ Y.GetHashCode() ^ Z.GetHashCode(); + } + + /// + /// Get a formatted string representation of the vector + /// + /// A string representation of the vector + public override string ToString() + { + StringBuilder sb = new(); + sb.Append('<'); + sb.Append(X.ToString(Utils.EnUsCulture)); + sb.Append(", "); + sb.Append(Y.ToString(Utils.EnUsCulture)); + sb.Append(", "); + sb.Append(Z.ToString(Utils.EnUsCulture)); + sb.Append('>'); + return sb.ToString(); + } + + /// + /// Get a string representation of the vector elements with up to three + /// decimal digits and separated by spaces only + /// + /// Raw string representation of the vector + public string ToRawString() + { + CultureInfo enUs = new("en-us"); + enUs.NumberFormat.NumberDecimalDigits = 3; + + StringBuilder sb = new(); + sb.Append(X.ToString(enUs)); + sb.Append(' '); + sb.Append(Y.ToString(enUs)); + sb.Append(' '); + sb.Append(Z.ToString(enUs)); + return sb.ToString(); + } + + #endregion Overrides + + #region Operators + + public static bool operator ==(Vector3d value1, Vector3d value2) + { + return value1.X == value2.X + && value1.Y == value2.Y + && value1.Z == value2.Z; + } + + public static bool operator !=(Vector3d value1, Vector3d value2) + { + return !(value1 == value2); + } + + public static Vector3d operator +(Vector3d value1, Vector3d value2) + { + value1.X += value2.X; + value1.Y += value2.Y; + value1.Z += value2.Z; + return value1; + } + + public static Vector3d operator -(Vector3d value) + { + value.X = -value.X; + value.Y = -value.Y; + value.Z = -value.Z; + return value; + } + + public static Vector3d operator -(Vector3d value1, Vector3d value2) + { + value1.X -= value2.X; + value1.Y -= value2.Y; + value1.Z -= value2.Z; + return value1; + } + + public static Vector3d operator *(Vector3d value1, Vector3d value2) + { + value1.X *= value2.X; + value1.Y *= value2.Y; + value1.Z *= value2.Z; + return value1; + } + + public static Vector3d operator *(Vector3d value, double scaleFactor) + { + value.X *= scaleFactor; + value.Y *= scaleFactor; + value.Z *= scaleFactor; + return value; + } + + public static Vector3d operator /(Vector3d value1, Vector3d value2) + { + value1.X /= value2.X; + value1.Y /= value2.Y; + value1.Z /= value2.Z; + return value1; + } + + public static Vector3d operator /(Vector3d value, double divider) + { + double factor = 1d / divider; + value.X *= factor; + value.Y *= factor; + value.Z *= factor; + return value; + } + + /// + /// Cross product between two vectors + /// + public static Vector3d operator %(Vector3d value1, Vector3d value2) + { + return Cross(value1, value2); + } + + /// + /// Implicit casting for Vector3 > Vector3d + /// + /// + /// + public static implicit operator Vector3d(Vector3 value) + { + return new Vector3d(value); + } + + #endregion Operators + + /// A vector with a value of 0,0,0 + public readonly static Vector3d Zero = new Vector3d(); + /// A vector with a value of 1,1,1 + public readonly static Vector3d One = new Vector3d(); + /// A unit vector facing forward (X axis), value of 1,0,0 + public readonly static Vector3d UnitX = new Vector3d(1d, 0d, 0d); + /// A unit vector facing left (Y axis), value of 0,1,0 + public readonly static Vector3d UnitY = new Vector3d(0d, 1d, 0d); + /// A unit vector facing up (Z axis), value of 0,0,1 + public readonly static Vector3d UnitZ = new Vector3d(0d, 0d, 1d); + } +} diff --git a/OpenMetaverse.Types/Vector4.cs b/OpenMetaverse.Types/Vector4.cs index 2daea54a..aed9b8df 100644 --- a/OpenMetaverse.Types/Vector4.cs +++ b/OpenMetaverse.Types/Vector4.cs @@ -24,9 +24,12 @@ * POSSIBILITY OF SUCH DAMAGE. */ -using System; using System.Globalization; +using System.Runtime.CompilerServices; using System.Runtime.InteropServices; +using System.Runtime.Intrinsics; +using System.Runtime.Intrinsics.X86; +using System.Text; namespace OpenMetaverse { @@ -84,22 +87,21 @@ public Vector4(float value) /// Beginning position in the byte array public Vector4(byte[] byteArray, int pos) { - X = Y = Z = W = 0f; - FromBytes(byteArray, pos); + X = Utils.BytesToFloatSafepos(byteArray, pos); + Y = Utils.BytesToFloatSafepos(byteArray, pos + 4); + Z = Utils.BytesToFloatSafepos(byteArray, pos + 8); + W = Utils.BytesToFloatSafepos(byteArray, pos + 12); } public Vector4(Vector4 value) { - X = value.X; - Y = value.Y; - Z = value.Z; - W = value.W; + this = value; } #endregion Constructors #region Public Methods - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Abs() { X = Math.Abs(X); @@ -108,7 +110,41 @@ public void Abs() W = Math.Abs(W); } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Add(Vector4 v) + { + X += v.X; + Y += v.Y; + Z += v.Z; + W += v.W; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Sub(Vector4 v) + { + X -= v.X; + Y -= v.Y; + Z -= v.Z; + W -= v.W; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Clamp(float min, float max) + { + if (X < min) X = min; + else if (X > max) X = max; + + if (Y < min) Y = min; + else if (Y > max) Y = max; + + if (Z < min) Z = min; + else if (Z > max) Z = max; + + if (W < min) W = min; + else if (W > max) W = max; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Min(Vector4 v) { if (v.X < X) X = v.X; @@ -126,19 +162,38 @@ public void Max(Vector4 v) if (v.W > W) W = v.W; } + [MethodImpl(MethodImplOptions.AggressiveInlining)] public float Length() { return (float)Math.Sqrt(X * X + Y * Y + Z * Z + W * W); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] public float LengthSquared() { + if(Sse41.IsSupported) + { + Vector128 ma = Vector128.LoadUnsafe(ref X); + ma = Sse41.DotProduct(ma, ma, 0xf1); + return ma.ToScalar(); + } + else return (X * X) + (Y * Y) + (Z * Z) + (W * W); } public void Normalize() { - this = Normalize(this); + float factor = LengthSquared(); + if (factor > 1e-6) + { + factor = 1f / (float)Math.Sqrt(factor); + X *= factor; + Y *= factor; + Z *= factor; + W *= factor; + } + else + this = new Vector4(); } /// @@ -150,6 +205,7 @@ public void Normalize() /// between the two vectors /// True if the magnitude of difference between the two vectors /// is less than the given tolerance, otherwise false + [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool ApproxEquals(Vector4 vec, float tolerance) { return Utils.ApproxEqual(X, vec.X, tolerance) && @@ -158,6 +214,7 @@ public bool ApproxEquals(Vector4 vec, float tolerance) Utils.ApproxEqual(W, vec.W, tolerance); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool ApproxEquals(Vector4 vec) { return Utils.ApproxEqual(X, vec.X) && @@ -166,6 +223,33 @@ public bool ApproxEquals(Vector4 vec) Utils.ApproxEqual(W, vec.W); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool IsZero() + { + if (X != 0) + return false; + if (Y != 0) + return false; + if (Z != 0) + return false; + if (W != 0) + return false; + return true; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool IsNotZero() + { + if (X != 0) + return true; + if (Y != 0) + return true; + if (Z != 0) + return true; + if (W != 0) + return true; + return false; + } /// /// IComparable.CompareTo implementation /// @@ -174,6 +258,11 @@ public int CompareTo(Vector4 vector) return Length().CompareTo(vector.Length()); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public float Dot(Vector4 value2) + { + return (X * value2.X) + (Y * value2.Y) + (Z * value2.Z) + (W * value2.W); + } /// /// Test if this vector is composed of all finite numbers /// @@ -215,13 +304,36 @@ public byte[] GetBytes() /// Destination byte array /// Position in the destination array to start /// writing. Must be at least 16 bytes before the end of the array - public void ToBytes(byte[] dest, int pos) + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe void ToBytes(byte[] dest, int pos) + { + if (Utils.CanDirectCopyLE) + { + fixed (byte* d = &dest[0]) + *(Vector4*)(d + pos) = this; + } + else { Utils.FloatToBytesSafepos(X, dest, pos); Utils.FloatToBytesSafepos(Y, dest, pos + 4); Utils.FloatToBytesSafepos(Z, dest, pos + 8); Utils.FloatToBytesSafepos(W, dest, pos + 12); } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe void ToBytes(byte* dest) + { + if (Utils.CanDirectCopyLE) + *(Vector4*)dest = this; + else + { + Utils.FloatToBytes(X, dest); + Utils.FloatToBytes(Y, dest + 4); + Utils.FloatToBytes(Z, dest + 8); + Utils.FloatToBytes(W, dest + 12); + } + } #endregion Public Methods @@ -237,6 +349,15 @@ public static Vector4 Add(Vector4 value1, Vector4 value2) ); } + public static Vector4 Clamp(Vector4 value1, float min, float max) + { + return new Vector4( + Utils.Clamp(value1.X, min, max), + Utils.Clamp(value1.Y, min, max), + Utils.Clamp(value1.Z, min, max), + Utils.Clamp(value1.W, min, max)); + } + public static Vector4 Clamp(Vector4 value1, Vector4 min, Vector4 max) { return new Vector4( @@ -400,29 +521,173 @@ public static Vector4 Transform(Vector4 vector, Matrix4 matrix) (vector.X * matrix.M14) + (vector.Y * matrix.M24) + (vector.Z * matrix.M34) + (vector.W * matrix.M44)); } - public static Vector4 Parse(string val) + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static Vector4 Parse(string val) { - char[] splitChar = { ',' }; - string[] split = val.Replace("<", String.Empty).Replace(">", String.Empty).Split(splitChar); - return new Vector4( - float.Parse(split[0].Trim(), Utils.EnUsCulture), - float.Parse(split[1].Trim(), Utils.EnUsCulture), - float.Parse(split[2].Trim(), Utils.EnUsCulture), - float.Parse(split[3].Trim(), Utils.EnUsCulture)); + return Parse(val.AsSpan()); + } + + public static Vector4 Parse(ReadOnlySpan sp) + { + if (sp.Length < 7) + throw new FormatException("Invalid Vector4"); + + int start = 0; + int comma = 0; + char c; + + do + { + c = Unsafe.Add(ref MemoryMarshal.GetReference(sp), comma); + if (c == ',' || c == '<') + break; + } + while (++comma < sp.Length); + + if (c == '<') + { + start = ++comma; + while (++comma < sp.Length) + { + if (Unsafe.Add(ref MemoryMarshal.GetReference(sp), comma) == ',') + break; + } + } + if (comma > sp.Length - 5) + throw new FormatException("Invalid Vector4"); + + if (!float.TryParse(sp[start..comma], NumberStyles.Float, Utils.EnUsCulture, out float x)) + throw new FormatException("Invalid Vector4"); + + start = ++comma; + while (++comma < sp.Length) + { + if (Unsafe.Add(ref MemoryMarshal.GetReference(sp), comma) == ',') + break; + } + if (comma > sp.Length - 3) + throw new FormatException("Invalid Vector4"); + if (!float.TryParse(sp[start..comma], NumberStyles.Float, Utils.EnUsCulture, out float y)) + throw new FormatException("Invalid Vector4"); + + start = ++comma; + while (++comma < sp.Length) + { + if (Unsafe.Add(ref MemoryMarshal.GetReference(sp), comma) == ',') + break; + } + if (comma > sp.Length - 1) + throw new FormatException("Invalid Vector4"); + if (!float.TryParse(sp[start..comma], NumberStyles.Float, Utils.EnUsCulture, out float z)) + throw new FormatException("Invalid Vector4"); + + start = ++comma; + while (++comma < sp.Length) + { + if (Unsafe.Add(ref MemoryMarshal.GetReference(sp), comma) == '>') + break; + } + + if (!float.TryParse(sp[start..comma], NumberStyles.Float, Utils.EnUsCulture, out float w)) + throw new FormatException("Invalid Vector4"); + return new Vector4(x, y, z, w); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool TryParse(string val, out Vector4 result) { - try + return TryParse(val.AsSpan(), out result); + } + + public static bool TryParse(ReadOnlySpan sp, out Vector4 result) { - result = Parse(val); - return true; + if (sp.Length < 7) + { + result = Zero; + return false; + } + + int start = 0; + int comma = 0; + char c; + do + { + c = Unsafe.Add(ref MemoryMarshal.GetReference(sp), comma); + if (c == ',' || c == '<') + break; + } + while (++comma < sp.Length); + + if (c == '<') + { + start = ++comma; + while (++comma < sp.Length) + { + if (Unsafe.Add(ref MemoryMarshal.GetReference(sp), comma) == ',') + break; + } + } + if (comma > sp.Length - 5) + { + result = Zero; + return false; + } + + if (!float.TryParse(sp[start..comma], NumberStyles.Float, Utils.EnUsCulture, out float x)) + { + result = Zero; + return false; + } + + start = ++comma; + while (++comma < sp.Length) + { + if (Unsafe.Add(ref MemoryMarshal.GetReference(sp), comma) == ',') + break; + } + if (comma > sp.Length - 5) + { + result = Zero; + return false; + } + if (!float.TryParse(sp[start..comma], NumberStyles.Float, Utils.EnUsCulture, out float y)) + { + result = Zero; + return false; + } + + start = ++comma; + while (++comma < sp.Length) + { + if (Unsafe.Add(ref MemoryMarshal.GetReference(sp), comma) == ',') + break; } - catch (Exception) + if (comma > sp.Length - 1) { - result = new Vector4(); + result = Zero; return false; } + if (!float.TryParse(sp[start..comma], NumberStyles.Float, Utils.EnUsCulture, out float z)) + { + result = Zero; + return false; + } + + start = ++comma; + while (++comma < sp.Length) + { + c = Unsafe.Add(ref MemoryMarshal.GetReference(sp), comma); + if(c == ' ' || c == '>') + break; + } + if (!float.TryParse(sp[start..comma], NumberStyles.Float, Utils.EnUsCulture, out float w)) + { + result = Zero; + return false; + } + + result = new Vector4(x, y, z, w); + return true; } #endregion Static Methods @@ -431,17 +696,46 @@ public static bool TryParse(string val, out Vector4 result) public override bool Equals(object obj) { - return (obj is Vector4) ? this == (Vector4)obj : false; + if (obj is not Vector4 other) + return false; + + if (X != other.X) + return false; + if (Y != other.Y) + return false; + if (Z != other.Z) + return false; + if (W != other.W) + return false; + return true; } public bool Equals(Vector4 other) { - return W == other.W - && X == other.X - && Y == other.Y - && Z == other.Z; + if (X != other.X) + return false; + if (Y != other.Y) + return false; + if (Z != other.Z) + return false; + if (W != other.W) + return false; + return true; } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool NotEqual(Vector4 other) + { + if (X != other.X) + return true; + if (Y != other.Y) + return true; + if (Z != other.Z) + return true; + if (W != other.W) + return true; + return false; + } public override int GetHashCode() { return X.GetHashCode() ^ Y.GetHashCode() ^ Z.GetHashCode() ^ W.GetHashCode(); @@ -449,7 +743,17 @@ public override int GetHashCode() public override string ToString() { - return String.Format(Utils.EnUsCulture, "<{0}, {1}, {2}, {3}>", X, Y, Z, W); + StringBuilder sb = new(); + sb.Append('<'); + sb.Append(X.ToString(Utils.EnUsCulture)); + sb.Append(", "); + sb.Append(Y.ToString(Utils.EnUsCulture)); + sb.Append(", "); + sb.Append(Z.ToString(Utils.EnUsCulture)); + sb.Append(", "); + sb.Append(W.ToString(Utils.EnUsCulture)); + sb.Append('>'); + return sb.ToString(); } /// @@ -459,10 +763,18 @@ public override string ToString() /// Raw string representation of the vector public string ToRawString() { - CultureInfo enUs = new CultureInfo("en-us"); + CultureInfo enUs = new("en-us"); enUs.NumberFormat.NumberDecimalDigits = 3; - return String.Format(enUs, "{0} {1} {2} {3}", X, Y, Z, W); + StringBuilder sb = new(); + sb.Append(X.ToString(enUs)); + sb.Append(' '); + sb.Append(Y.ToString(enUs)); + sb.Append(' '); + sb.Append(Z.ToString(enUs)); + sb.Append(' '); + sb.Append(W.ToString(enUs)); + return sb.ToString(); } #endregion Overrides @@ -471,16 +783,28 @@ public string ToRawString() public static bool operator ==(Vector4 value1, Vector4 value2) { - return - value1.X == value2.X - && value1.Y == value2.Y - && value1.Z == value2.Z - && value1.W == value2.W; + if (value1.X != value2.X) + return false; + if (value1.Y != value2.Y) + return false; + if (value1.Z != value2.Z) + return false; + if (value1.W != value2.W) + return false; + return true; } public static bool operator !=(Vector4 value1, Vector4 value2) { - return !(value1 == value2); + if (value1.X != value2.X) + return true; + if (value1.Y != value2.Y) + return true; + if (value1.Z != value2.Z) + return true; + if (value1.W != value2.W) + return true; + return false; } public static Vector4 operator +(Vector4 value1, Vector4 value2) @@ -546,18 +870,18 @@ public string ToRawString() #endregion Operators /// A vector with a value of 0,0,0,0 - public readonly static Vector4 Zero = new Vector4(); + public readonly static Vector4 Zero = new(); /// A vector with a value of 1,1,1,1 - public readonly static Vector4 One = new Vector4(1f, 1f, 1f, 1f); + public readonly static Vector4 One = new(1f, 1f, 1f, 1f); /// A vector with a value of 1,0,0,0 - public readonly static Vector4 UnitX = new Vector4(1f, 0f, 0f, 0f); + public readonly static Vector4 UnitX = new(1f, 0f, 0f, 0f); /// A vector with a value of 0,1,0,0 - public readonly static Vector4 UnitY = new Vector4(0f, 1f, 0f, 0f); + public readonly static Vector4 UnitY = new(0f, 1f, 0f, 0f); /// A vector with a value of 0,0,1,0 - public readonly static Vector4 UnitZ = new Vector4(0f, 0f, 1f, 0f); + public readonly static Vector4 UnitZ = new(0f, 0f, 1f, 0f); /// A vector with a value of 0,0,0,1 - public readonly static Vector4 UnitW = new Vector4(0f, 0f, 0f, 1f); - public readonly static Vector4 MinValue = new Vector4(float.MinValue, float.MinValue, float.MinValue, float.MinValue); - public readonly static Vector4 MaxValue = new Vector4(float.MaxValue, float.MaxValue, float.MaxValue, float.MaxValue); + public readonly static Vector4 UnitW = new(0f, 0f, 0f, 1f); + public readonly static Vector4 MinValue = new(float.MinValue, float.MinValue, float.MinValue, float.MinValue); + public readonly static Vector4 MaxValue = new(float.MaxValue, float.MaxValue, float.MaxValue, float.MaxValue); } } diff --git a/OpenMetaverse.Utilities/OpenMetaverse.Utilities.csproj b/OpenMetaverse.Utilities/OpenMetaverse.Utilities.csproj index 43ec7dea..27f5c0b9 100644 --- a/OpenMetaverse.Utilities/OpenMetaverse.Utilities.csproj +++ b/OpenMetaverse.Utilities/OpenMetaverse.Utilities.csproj @@ -1,18 +1,11 @@  Local - net48 + Library OpenMetaverse.Utilities OpenMetaverse.Utilities - 1591,1574,0419,0618 True - - - - - OpenMetaverse.Utilities.XML - diff --git a/OpenMetaverse.Utilities/VoiceManager.cs b/OpenMetaverse.Utilities/VoiceManager.cs index 1323dbeb..5a62159c 100644 --- a/OpenMetaverse.Utilities/VoiceManager.cs +++ b/OpenMetaverse.Utilities/VoiceManager.cs @@ -582,6 +582,7 @@ private void _DaemonPipe_OnDisconnected(SocketException se) private void _DaemonPipe_OnReceiveLine(string line) { XmlTextReader reader = new XmlTextReader(new StringReader(line)); + reader.DtdProcessing = DtdProcessing.Ignore; while (reader.Read()) { diff --git a/OpenMetaverse.sln b/OpenMetaverse.sln index 330027ea..6ad7e367 100644 --- a/OpenMetaverse.sln +++ b/OpenMetaverse.sln @@ -1,33 +1,8 @@ -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.28803.352 + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.1.32414.318 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvatarPreview", "Programs\AvatarPreview\AvatarPreview.csproj", "{93CEA633-0000-0000-0000-000000000000}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Baker", "Programs\Baker\Baker.csproj", "{95F42663-0000-0000-0000-000000000000}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CSJ2K", "CSJ2K\CSJ2K.csproj", "{C276743B-0000-0000-0000-000000000000}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Dashboard", "Programs\examples\Dashboard\Dashboard.csproj", "{592827AA-0000-0000-0000-000000000000}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GridAccountant", "Programs\examples\GridAccountant\GridAccountant.csproj", "{6DE58F9A-0000-0000-0000-000000000000}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GridImageUpload", "Programs\GridImageUpload\GridImageUpload.csproj", "{06BD6C42-0000-0000-0000-000000000000}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GridProxy", "Programs\GridProxy\GridProxy.csproj", "{79B51DAA-0000-0000-0000-000000000000}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GridProxyApp", "Programs\GridProxyApp\GridProxyApp.csproj", "{CF6ECF45-0000-0000-0000-000000000000}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "groupmanager", "Programs\examples\groupmanager\groupmanager.csproj", "{97A800BC-0000-0000-0000-000000000000}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Heightmap", "Programs\examples\Heightmap\Heightmap.csproj", "{16044D2B-0000-0000-0000-000000000000}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "importprimscript", "Programs\importprimscript\importprimscript.csproj", "{95C06600-0000-0000-0000-000000000000}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "IRCGateway", "Programs\examples\IRCGateway\IRCGateway.csproj", "{89049BBC-0000-0000-0000-000000000000}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "mapgenerator", "Programs\mapgenerator\mapgenerator.csproj", "{2867B4B3-0000-0000-0000-000000000000}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenMetaverse", "OpenMetaverse\OpenMetaverse.csproj", "{8B693884-0000-0000-0000-000000000000}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenMetaverse.GUI", "OpenMetaverse.GUI\OpenMetaverse.GUI.csproj", "{45775693-0000-0000-0000-000000000000}" @@ -44,19 +19,10 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenMetaverse.Utilities", " EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenMetaverse.Types", "OpenMetaverse.Types\OpenMetaverse.Types.csproj", "{6C8DAE41-0000-0000-0000-000000000000}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PacketDump", "Programs\examples\PacketDump\PacketDump.csproj", "{58443010-0000-0000-0000-000000000000}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PrimWorkshop", "Programs\PrimWorkshop\PrimWorkshop.csproj", "{AC949F03-0000-0000-0000-000000000000}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestClient", "Programs\examples\TestClient\TestClient.csproj", "{9F71FDB3-0000-0000-0000-000000000000}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "VisualParamGenerator", "Programs\VisualParamGenerator\VisualParamGenerator.csproj", "{CF93CDA8-0000-0000-0000-000000000000}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "VoiceTest", "Programs\VoiceTest\VoiceTest.csproj", "{EE4EA934-0000-0000-0000-000000000000}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WinGridProxy", "Programs\WinGridProxy\WinGridProxy.csproj", "{455B06F4-0000-0000-0000-000000000000}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OpenMetaverse.PrimMesher", "OpenMetaverse.PrimMesher\OpenMetaverse.PrimMesher.csproj", "{2E2B643F-F18B-4791-BA4B-6E82D0E794B6}" +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{49AFD80D-D399-43FC-A9EE-9F15BC6D49E7}" + ProjectSection(SolutionItems) = preProject + README.md = README.md + EndProjectSection EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -64,58 +30,6 @@ Global Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {93CEA633-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {93CEA633-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU - {93CEA633-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU - {93CEA633-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU - {95F42663-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {95F42663-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU - {95F42663-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU - {95F42663-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU - {C276743B-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {C276743B-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU - {C276743B-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU - {C276743B-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU - {592827AA-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {592827AA-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU - {592827AA-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU - {592827AA-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU - {6DE58F9A-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {6DE58F9A-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU - {6DE58F9A-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU - {6DE58F9A-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU - {06BD6C42-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {06BD6C42-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU - {06BD6C42-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU - {06BD6C42-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU - {79B51DAA-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {79B51DAA-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU - {79B51DAA-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU - {79B51DAA-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU - {CF6ECF45-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {CF6ECF45-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU - {CF6ECF45-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU - {CF6ECF45-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU - {97A800BC-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {97A800BC-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU - {97A800BC-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU - {97A800BC-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU - {16044D2B-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {16044D2B-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU - {16044D2B-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU - {16044D2B-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU - {95C06600-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {95C06600-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU - {95C06600-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU - {95C06600-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU - {89049BBC-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {89049BBC-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU - {89049BBC-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU - {89049BBC-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU - {2867B4B3-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {2867B4B3-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU - {2867B4B3-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU - {2867B4B3-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU {8B693884-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {8B693884-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU {8B693884-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -148,34 +62,6 @@ Global {6C8DAE41-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU {6C8DAE41-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU {6C8DAE41-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU - {58443010-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {58443010-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU - {58443010-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU - {58443010-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU - {AC949F03-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {AC949F03-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU - {AC949F03-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU - {AC949F03-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU - {9F71FDB3-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {9F71FDB3-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU - {9F71FDB3-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU - {9F71FDB3-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU - {CF93CDA8-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {CF93CDA8-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU - {CF93CDA8-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU - {CF93CDA8-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU - {EE4EA934-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {EE4EA934-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU - {EE4EA934-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU - {EE4EA934-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU - {455B06F4-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {455B06F4-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU - {455B06F4-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU - {455B06F4-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU - {2E2B643F-F18B-4791-BA4B-6E82D0E794B6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {2E2B643F-F18B-4791-BA4B-6E82D0E794B6}.Debug|Any CPU.Build.0 = Debug|Any CPU - {2E2B643F-F18B-4791-BA4B-6E82D0E794B6}.Release|Any CPU.ActiveCfg = Release|Any CPU - {2E2B643F-F18B-4791-BA4B-6E82D0E794B6}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/OpenMetaverse/AgentManager.cs b/OpenMetaverse/AgentManager.cs index 8a7eb402..38bb9748 100644 --- a/OpenMetaverse/AgentManager.cs +++ b/OpenMetaverse/AgentManager.cs @@ -4215,7 +4215,7 @@ private void ChatterBoxSessionAgentListUpdatesEventHandler(string capsKey, IMess { if (msg.Updates[i].Transition.Equals("ENTER")) { - if (fndMbr.AvatarKey == UUID.Zero) + if (fndMbr.AvatarKey.IsZero()) { fndMbr = new ChatSessionMember(); fndMbr.AvatarKey = msg.Updates[i].AgentID; diff --git a/OpenMetaverse/AgentThrottle.cs b/OpenMetaverse/AgentThrottle.cs index 758ab8a0..36fe02f4 100644 --- a/OpenMetaverse/AgentThrottle.cs +++ b/OpenMetaverse/AgentThrottle.cs @@ -178,13 +178,14 @@ public AgentThrottle(byte[] data, int pos) adjData = data; } - Resend = BitConverter.ToSingle(adjData, pos); pos += 4; - Land = BitConverter.ToSingle(adjData, pos); pos += 4; - Wind = BitConverter.ToSingle(adjData, pos); pos += 4; - Cloud = BitConverter.ToSingle(adjData, pos); pos += 4; - Task = BitConverter.ToSingle(adjData, pos); pos += 4; - Texture = BitConverter.ToSingle(adjData, pos); pos += 4; - Asset = BitConverter.ToSingle(adjData, pos); + Resend = Utils.BytesToFloat(adjData, 0); + Land = Utils.BytesToFloat(adjData, 4); + Wind = Utils.BytesToFloat(adjData, 8); + Cloud = Utils.BytesToFloat(adjData, 12); + Task = Utils.BytesToFloat(adjData, 16); + Texture = Utils.BytesToFloat(adjData, 20); + Asset = Utils.BytesToFloat(adjData, 24); + pos += 28; } /// @@ -220,15 +221,14 @@ public void Set(Simulator simulator) public byte[] ToBytes() { byte[] data = new byte[7 * 4]; - int i = 0; - - Buffer.BlockCopy(Utils.FloatToBytes(Resend), 0, data, i, 4); i += 4; - Buffer.BlockCopy(Utils.FloatToBytes(Land), 0, data, i, 4); i += 4; - Buffer.BlockCopy(Utils.FloatToBytes(Wind), 0, data, i, 4); i += 4; - Buffer.BlockCopy(Utils.FloatToBytes(Cloud), 0, data, i, 4); i += 4; - Buffer.BlockCopy(Utils.FloatToBytes(Task), 0, data, i, 4); i += 4; - Buffer.BlockCopy(Utils.FloatToBytes(Texture), 0, data, i, 4); i += 4; - Buffer.BlockCopy(Utils.FloatToBytes(Asset), 0, data, i, 4); i += 4; + + Utils.FloatToBytes(Resend, data, 0); + Utils.FloatToBytes(Land, data, 4); + Utils.FloatToBytes(Wind, data, 8); + Utils.FloatToBytes(Cloud, data, 12); + Utils.FloatToBytes(Task, data, 16); + Utils.FloatToBytes(Texture, data, 20); + Utils.FloatToBytes(Asset, data, 24); return data; } diff --git a/OpenMetaverse/AppearanceManager.cs b/OpenMetaverse/AppearanceManager.cs index f2c2fb18..2faad002 100644 --- a/OpenMetaverse/AppearanceManager.cs +++ b/OpenMetaverse/AppearanceManager.cs @@ -162,7 +162,13 @@ public class AppearanceManager new WearableType[] { WearableType.Shape, WearableType.Skin, WearableType.Tattoo, WearableType.Pants, WearableType.Shoes, WearableType.Socks, WearableType.Jacket, WearableType.Underpants, WearableType.Alpha }, new WearableType[] { WearableType.Eyes, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid }, new WearableType[] { WearableType.Skirt, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid }, - new WearableType[] { WearableType.Hair, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid } + new WearableType[] { WearableType.Hair, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid }, + + new WearableType[] { WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid }, + new WearableType[] { WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid }, + new WearableType[] { WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid }, + new WearableType[] { WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid }, + new WearableType[] { WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid } }; /// Magic values to finalize the cache check hashes for each /// bake @@ -173,7 +179,14 @@ public class AppearanceManager new UUID("91b4a2c7-1b1a-ba16-9a16-1f8f8dcc1c3f"), new UUID("b2cf28af-b840-1071-3c6a-78085d8128b5"), new UUID("ea800387-ea1a-14e0-56cb-24f2022f969a"), - new UUID("0af1ef7c-ad24-11dd-8790-001f5bf833e8") + new UUID("0af1ef7c-ad24-11dd-8790-001f5bf833e8"), + + new UUID("e2658fa6-a47b-11ec-b909-0242ac120002"), + new UUID("ea8620e2-a47b-11ec-b909-0242ac120002"), + new UUID("f175510c-a47b-11ec-b909-0242ac120002"), + new UUID("f8011ec0-a47b-11ec-b909-0242ac120002"), + new UUID("ff7b4dce-a47b-11ec-b909-0242ac120002") + }; /// Default avatar texture, used to detect when a custom /// texture is not set for a face @@ -403,6 +416,10 @@ public bool ManagerBusy /// private Thread AppearanceThread; /// + /// Main appearance cancellation token source + /// + private CancellationTokenSource CancellationTokenSource; //Added from LibreOpenMetaverse + /// /// Is server baking complete. It needs doing only once /// private bool ServerBakingDone = false; @@ -471,11 +488,14 @@ public void RequestSetAppearance(bool forceRebake) RebakeScheduleTimer.Dispose(); RebakeScheduleTimer = null; } + + CancellationTokenSource = new CancellationTokenSource(); //added from LibreOpenMetaverse // This is the first time setting appearance, run through the entire sequence AppearanceThread = new Thread( delegate () { + var cancellationToken = CancellationTokenSource.Token; //added from LibreOpenMetaverse bool success = true; try { @@ -630,7 +650,7 @@ public void RequestCachedBakes() hash ^= wearable.AssetID; } - if (hash != UUID.Zero) + if (hash.IsNotZero()) { // Hash with our secret value for this baked layer hash ^= BAKED_TEXTURE_HASH[bakedIndex]; @@ -1352,7 +1372,7 @@ bool GetCachedBakes() /// /// Populates textures and visual params from a decoded asset /// - /// Wearable to decode + /// textures to decode public static void DecodeWearableParams(WearableData wearable, ref TextureData[] textures) { Dictionary alphaMasks = new Dictionary(); @@ -1692,7 +1712,7 @@ private bool CreateBakes() { AvatarTextureIndex textureIndex = BakeTypeToAgentTextureIndex((BakeType)bakedIndex); - if (Textures[(int)textureIndex].TextureID == UUID.Zero) + if (Textures[(int)textureIndex].TextureID.IsZero()) { // If this is the skirt layer and we're not wearing a skirt then skip it if (bakedIndex == (int)BakeType.Skirt && !Wearables.ContainsKey(WearableType.Skirt)) @@ -1755,7 +1775,7 @@ private bool CreateBake(BakeType bakeType) UUID newAssetID = UUID.Zero; int retries = UPLOAD_RETRIES; - while (newAssetID == UUID.Zero && retries > 0) + while (newAssetID.IsZero() && retries > 0) { newAssetID = UploadBake(oven.BakedTexture.AssetData); --retries; @@ -1763,7 +1783,7 @@ private bool CreateBake(BakeType bakeType) Textures[(int)BakeTypeToAgentTextureIndex(bakeType)].TextureID = newAssetID; - if (newAssetID == UUID.Zero) + if (newAssetID.IsZero()) { Logger.Log("Failed uploading bake " + bakeType, Helpers.LogLevel.Warning); return false; @@ -2104,7 +2124,7 @@ public AgentSetAppearancePacket MakeAppearancePacket() hash ^= wearable.AssetID; } - if (hash != UUID.Zero) + if (hash.IsNotZero()) { // Hash with our magic value for this baked layer hash ^= BAKED_TEXTURE_HASH[bakedIndex]; @@ -2367,13 +2387,23 @@ private void Network_OnDisconnected(object sender, DisconnectedEventArgs e) RebakeScheduleTimer.Dispose(); RebakeScheduleTimer = null; } + + // Added from LibreOpenMetaverse + if (CancellationTokenSource != null) + { + CancellationTokenSource.Cancel(); + CancellationTokenSource.Dispose(); + CancellationTokenSource = null; + } if (AppearanceThread != null) { - if (AppearanceThread.IsAlive) + /* removed as thread.abort is obsolte + if (AppearanceThread.IsAlive) { AppearanceThread.Abort(); } + */ AppearanceThread = null; AppearanceThreadRunning = 0; } diff --git a/OpenMetaverse/AssetManager.cs b/OpenMetaverse/AssetManager.cs index 6d797ce7..d6c7c6da 100644 --- a/OpenMetaverse/AssetManager.cs +++ b/OpenMetaverse/AssetManager.cs @@ -582,7 +582,7 @@ public void RequestAsset(UUID assetID, UUID itemID, UUID taskID, AssetType type, request.TransferInfo.SourceType = (int)transfer.Source; request.TransferInfo.TransferID = transfer.ID; - byte[] paramField = taskID == UUID.Zero ? new byte[20] : new byte[96]; + byte[] paramField = taskID.IsZero() ? new byte[20] : new byte[96]; Buffer.BlockCopy(assetID.GetBytes(), 0, paramField, 0, 16); Buffer.BlockCopy(Utils.IntToBytes((int)type), 0, paramField, 16, 4); @@ -1106,7 +1106,7 @@ public void RequestImageCancel(UUID textureID) /// Callback when the request completes public void RequestMesh(UUID meshID, MeshDownloadCallback callback) { - if (meshID == UUID.Zero || callback == null) + if (meshID.IsZero() || callback == null) return; if (Client.Network.CurrentSim.Caps != null && @@ -1163,7 +1163,7 @@ public void RequestMesh(UUID meshID, MeshDownloadCallback callback) /// Callback invoked on operation completion public void RequestServerBakedImage(UUID avatarID, UUID textureID, string bakeName, TextureDownloadCallback callback) { - if (avatarID == UUID.Zero || textureID == UUID.Zero || callback == null) + if (avatarID.IsZero() || textureID.IsZero() || callback == null) return; if (string.IsNullOrEmpty(Client.Network.AgentAppearanceServiceURL)) @@ -1254,7 +1254,7 @@ internal void FireImageProgressEvent(UUID texureID, int transferredBytes, int to private void HttpRequestTexture(UUID textureID, ImageType imageType, float priority, int discardLevel, uint packetStart, TextureDownloadCallback callback, bool progress) { - if (textureID == UUID.Zero || callback == null) + if (textureID.IsZero() || callback == null) return; byte[] assetData; diff --git a/OpenMetaverse/Assets/Archiving/OarFile.cs b/OpenMetaverse/Assets/Archiving/OarFile.cs index a0cab68c..92b876e4 100644 --- a/OpenMetaverse/Assets/Archiving/OarFile.cs +++ b/OpenMetaverse/Assets/Archiving/OarFile.cs @@ -266,6 +266,7 @@ public static void LoadObjects(byte[] objectData, SceneObjectLoadedCallback obje using (XmlTextReader reader = new XmlTextReader(new MemoryStream(objectData))) { + reader.DtdProcessing = DtdProcessing.Ignore; reader.WhitespaceHandling = WhitespaceHandling.None; doc.Load(reader); } diff --git a/OpenMetaverse/Assets/Archiving/RegionSettings.cs b/OpenMetaverse/Assets/Archiving/RegionSettings.cs index a07dd9b4..885d302f 100644 --- a/OpenMetaverse/Assets/Archiving/RegionSettings.cs +++ b/OpenMetaverse/Assets/Archiving/RegionSettings.cs @@ -46,6 +46,7 @@ public static RegionSettings FromStream(Stream stream) using (XmlTextReader xtr = new XmlTextReader(stream)) { + xtr.DtdProcessing = DtdProcessing.Ignore; xtr.ReadStartElement("RegionSettings"); xtr.ReadStartElement("General"); diff --git a/OpenMetaverse/Assets/AssetTypes/AssetMesh.cs b/OpenMetaverse/Assets/AssetTypes/AssetMesh.cs index ef35fa2a..d4a5e73c 100644 --- a/OpenMetaverse/Assets/AssetTypes/AssetMesh.cs +++ b/OpenMetaverse/Assets/AssetTypes/AssetMesh.cs @@ -26,8 +26,10 @@ using OpenMetaverse.StructuredData; using System; +using System.Buffers; using System.IO; using System.IO.Compression; +using OpenMetaverse.StructuredData; namespace OpenMetaverse.Assets { @@ -68,32 +70,49 @@ public override bool Decode() { try { - MeshData = new OSDMap(); + MeshData = []; - using (MemoryStream data = new MemoryStream(AssetData)) + using (MemoryStream data = new(AssetData)) { OSDMap header = (OSDMap)OSDParser.DeserializeLLSDBinary(data); MeshData["asset_header"] = header; + long start = data.Position; foreach (string partName in header.Keys) { - if (header[partName].Type != OSDType.Map) + OSD partOSD = header[partName]; + if(partOSD is not OSDMap partInfo) + { + MeshData[partName] = partOSD; + continue; + } + + if(!partInfo.TryGetInt("offset", out int partDataOffset)) + { + MeshData[partName] = partInfo; + continue; + } + + partDataOffset += (int)start; + if(partDataOffset > AssetData.Length) { - MeshData[partName] = header[partName]; + MeshData[partName] = partInfo; continue; } - OSDMap partInfo = (OSDMap)header[partName]; - if (partInfo["offset"] < 0 || partInfo["size"] == 0) + if(!partInfo.TryGetInt("size", out int partDataSize)) + { + MeshData[partName] = partInfo; + continue; + } + if(partDataOffset + partDataSize > AssetData.Length) { MeshData[partName] = partInfo; continue; } - byte[] part = new byte[partInfo["size"]]; - Buffer.BlockCopy(AssetData, partInfo["offset"] + (int)start, part, 0, part.Length); - MeshData[partName] = DecompressMeshOSD(part); + MeshData[partName] = DecompressMeshOSD(AssetData, partDataOffset, partDataSize); } } return true; @@ -105,34 +124,50 @@ public override bool Decode() } } - public static OSD DecompressMeshOSD(byte[] data) + public static OSD DecodeBlock(byte[] MeshBytes, string BlockName) { - OSD decodedOsd = null; - - using (MemoryStream inMs = new MemoryStream(data)) + try { - using (MemoryStream outMs = new MemoryStream()) - { - using (DeflateStream decompressionStream = new DeflateStream(inMs, CompressionMode.Decompress)) - { - byte[] readBuffer = new byte[2048]; - inMs.Read(readBuffer, 0, 2); // skip first 2 bytes in header - int readLen = 0; + using MemoryStream data = new(MeshBytes); - while ((readLen = decompressionStream.Read(readBuffer, 0, readBuffer.Length)) > 0) - outMs.Write(readBuffer, 0, readLen); + OSDMap header = (OSDMap)OSDParser.DeserializeLLSDBinary(data); + long start = data.Position; - outMs.Flush(); + if (!header.TryGetOSDMap(BlockName, out OSDMap LayerInfo)) + return null; - outMs.Seek(0, SeekOrigin.Begin); + if (!LayerInfo.TryGetInt("offset", out int BlockDataOffset)) + return null; - byte[] decompressedBuf = outMs.GetBuffer(); + BlockDataOffset += (int)start; + if (BlockDataOffset > MeshBytes.Length) + return null; - decodedOsd = OSDParser.DeserializeLLSDBinary(decompressedBuf); - } - } + if (!LayerInfo.TryGetInt("size", out int BlockDataSize)) + return null; + + if (BlockDataOffset + BlockDataSize > MeshBytes.Length) + return null; + + return DecompressMeshOSD(MeshBytes, BlockDataOffset, BlockDataSize); } - return decodedOsd; + catch (Exception ex) + { + Logger.Log("Failed to decode mesh asset", Helpers.LogLevel.Error, ex); + return null; + } + } + + public static OSD DecompressMeshOSD(byte[] data, int start, int len) + { + using MemoryStream outMs = new(4 * len); + using (MemoryStream inMs = new(data, start + 2, len - 2)) // skip first 2 bytes + { + using DeflateStream decompressionStream = new(inMs, CompressionMode.Decompress); + decompressionStream.CopyTo(outMs); + } + outMs.Seek(0, SeekOrigin.Begin); + return OSDParser.DeserializeLLSDBinary(outMs); } } } diff --git a/OpenMetaverse/Assets/AssetTypes/AssetNotecard.cs b/OpenMetaverse/Assets/AssetTypes/AssetNotecard.cs index 8d38bff2..bad42d1d 100644 --- a/OpenMetaverse/Assets/AssetTypes/AssetNotecard.cs +++ b/OpenMetaverse/Assets/AssetTypes/AssetNotecard.cs @@ -111,7 +111,7 @@ public override void Encode() output.Append("\t}\n"); if (Permissions.HasPermissions(item.Permissions.BaseMask, PermissionMask.Modify | PermissionMask.Copy | PermissionMask.Transfer) || - item.AssetUUID == UUID.Zero) + item.AssetUUID.IsZero()) { output.Append("\t\tasset_id\t" + item.AssetUUID + "\n"); } diff --git a/OpenMetaverse/Assets/AssetTypes/AssetPrim.cs b/OpenMetaverse/Assets/AssetTypes/AssetPrim.cs index 2d33c583..70d1aa62 100644 --- a/OpenMetaverse/Assets/AssetTypes/AssetPrim.cs +++ b/OpenMetaverse/Assets/AssetTypes/AssetPrim.cs @@ -123,13 +123,14 @@ public bool DecodeXml(string xmlData) { using (XmlTextReader reader = new XmlTextReader(new StringReader(xmlData))) { + reader.DtdProcessing = DtdProcessing.Ignore; reader.Read(); reader.ReadStartElement("SceneObjectGroup"); Parent = LoadPrim(reader); if (Parent != null) { - if (this.AssetID == UUID.Zero) + if (this.AssetID.IsZero()) this.AssetID = Parent.ID; List children = new List(); @@ -415,15 +416,13 @@ static UUID ReadUUID(XmlTextReader reader, string name) static Vector3 ReadVector(XmlTextReader reader, string name) { - Vector3 vec; - reader.ReadStartElement(name); - vec.X = reader.ReadElementContentAsFloat("X", String.Empty); - vec.Y = reader.ReadElementContentAsFloat("Y", String.Empty); - vec.Z = reader.ReadElementContentAsFloat("Z", String.Empty); + float x = reader.ReadElementContentAsFloat("X", String.Empty); + float y = reader.ReadElementContentAsFloat("Y", String.Empty); + float z = reader.ReadElementContentAsFloat("Z", String.Empty); reader.ReadEndElement(); - return vec; + return new Vector3(x,y,z); } static Quaternion ReadQuaternion(XmlTextReader reader, string name) diff --git a/OpenMetaverse/BitPack.cs b/OpenMetaverse/BitPack.cs index f1dd02f3..e4c9770d 100644 --- a/OpenMetaverse/BitPack.cs +++ b/OpenMetaverse/BitPack.cs @@ -25,6 +25,8 @@ */ using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; namespace OpenMetaverse { @@ -36,7 +38,6 @@ namespace OpenMetaverse public class BitPack { private const int MAX_BITS = 8; - private readonly bool weAreBigEndian = !BitConverter.IsLittleEndian; /// public byte[] Data; @@ -88,13 +89,52 @@ public BitPack(byte[] data, int pos, int? bitp = null) } } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private byte READBYTE() + { + return Unsafe.ReadUnaligned(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(Data), bytePos)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void BYTESTORE(byte b) + { + Unsafe.WriteUnaligned(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(Data), bytePos), b); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void OR_BYTESTORE(byte b) + { + byte o = Unsafe.ReadUnaligned(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(Data), bytePos)); + Unsafe.WriteUnaligned(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(Data), bytePos), b | o); + } + + public void Reset(byte[] data, int pos, int? bitp = null) + { + Data = data; + bytePos = pos; + if (bitp.HasValue) + { + bitPos = bitp.Value; + if (bitPos < 0) + bitPos = 0; + else if (bitPos > 7) + bitPos = 7; // this is wrong anyway + if (bitPos == 0) + Data[pos] = 0; + else + Data[pos] &= (byte)~(0xff >> bitPos); + } + else + bitPos = 0; + } /// /// Pack a floating point value in to the data /// /// Floating point value to pack + [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe void PackFloat(float data) { - int d = (*(int*)&data); + uint d = Unsafe.As(ref data); PackBitsFromByte((byte)d); PackBitsFromByte((byte)(d >> 8)); PackBitsFromByte((byte)(d >> 16)); @@ -106,16 +146,10 @@ public unsafe void PackFloat(float data) /// /// Integer containing the data to pack /// Number of bits of the integer to pack + [MethodImpl(MethodImplOptions.AggressiveInlining)] public void PackBits(int data, int totalCount) { - while (totalCount > 8) - { - PackBitsFromByte((byte)data); - data >>= 8; - totalCount -= 8; - } - if (totalCount > 0) - PackBitsFromByte((byte)data, totalCount); + PackBits((uint)data, totalCount); } /// @@ -123,6 +157,7 @@ public void PackBits(int data, int totalCount) /// /// Unsigned integer containing the data to pack /// Number of bits of the integer to pack + [MethodImpl(MethodImplOptions.AggressiveInlining)] public void PackBits(uint data, int totalCount) { while (totalCount > 8) @@ -135,6 +170,7 @@ public void PackBits(uint data, int totalCount) PackBitsFromByte((byte)data, totalCount); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] public void PackBitsFromUInt(uint data) { PackBitsFromByte((byte)data); @@ -143,6 +179,24 @@ public void PackBitsFromUInt(uint data) PackBitsFromByte((byte)(data >> 24)); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void PackBitsFromInt(int data) + { + PackBitsFromUInt((uint)data); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void PackBitsFromUShort(ushort data) + { + PackBitsFromByte((byte)data); + PackBitsFromByte((byte)(data >> 8)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void PackBitsFromShort(short data) + { + PackBitsFromUShort((ushort) data); + } /// /// @@ -195,9 +249,50 @@ public void PackFixed(float data, bool isSigned, int intBits, int fracBits) /// public void PackUUID(UUID data) { - byte[] bytes = data.GetBytes(); - for (int i = 0; i < 16; i++) - PackBitsFromByte(bytes[i]); + if (BitConverter.IsLittleEndian) + { + PackBitsFromByte(data.bytea3); + PackBitsFromByte(data.bytea2); + PackBitsFromByte(data.bytea1); + PackBitsFromByte(data.bytea0); + + PackBitsFromByte(data.byteb1); + PackBitsFromByte(data.byteb0); + + PackBitsFromByte(data.bytec1); + PackBitsFromByte(data.bytec0); + + PackBitsFromByte(data.d); + PackBitsFromByte(data.e); + PackBitsFromByte(data.f); + PackBitsFromByte(data.g); + PackBitsFromByte(data.h); + PackBitsFromByte(data.i); + PackBitsFromByte(data.j); + PackBitsFromByte(data.k); + } + else + { + PackBitsFromByte(data.bytea0); + PackBitsFromByte(data.bytea1); + PackBitsFromByte(data.bytea2); + PackBitsFromByte(data.bytea3); + + PackBitsFromByte(data.byteb0); + PackBitsFromByte(data.byteb1); + + PackBitsFromByte(data.bytec0); + PackBitsFromByte(data.bytec1); + + PackBitsFromByte(data.k); + PackBitsFromByte(data.j); + PackBitsFromByte(data.i); + PackBitsFromByte(data.h); + PackBitsFromByte(data.g); + PackBitsFromByte(data.f); + PackBitsFromByte(data.e); + PackBitsFromByte(data.d); + } } /// @@ -206,10 +301,10 @@ public void PackUUID(UUID data) /// public void PackColor(Color4 data) { - PackBitsFromByte(Utils.FloatToByte(data.R, 0f, 1f)); - PackBitsFromByte(Utils.FloatToByte(data.G, 0f, 1f)); - PackBitsFromByte(Utils.FloatToByte(data.B, 0f, 1f)); - PackBitsFromByte(Utils.FloatToByte(data.A, 0f, 1f)); + PackBitsFromByte(Utils.FloatZeroOneToByte(data.R)); + PackBitsFromByte(Utils.FloatZeroOneToByte(data.G)); + PackBitsFromByte(Utils.FloatZeroOneToByte(data.B)); + PackBitsFromByte(Utils.FloatZeroOneToByte(data.A)); } /// @@ -220,7 +315,7 @@ public float UnpackFloat() { byte[] output = UnpackBitsArray(32); - if (weAreBigEndian) Array.Reverse(output); + if (!BitConverter.IsLittleEndian) Array.Reverse(output); return BitConverter.ToSingle(output, 0); } @@ -234,7 +329,7 @@ public int UnpackBits(int totalCount) { byte[] output = UnpackBitsArray(totalCount); - if (weAreBigEndian) Array.Reverse(output); + if (!BitConverter.IsLittleEndian) Array.Reverse(output); return BitConverter.ToInt32(output, 0); } @@ -249,7 +344,7 @@ public uint UnpackUBits(int totalCount) { byte[] output = UnpackBitsArray(totalCount); - if (weAreBigEndian) Array.Reverse(output); + if (!BitConverter.IsLittleEndian) Array.Reverse(output); return BitConverter.ToUInt32(output, 0); } @@ -292,7 +387,6 @@ public uint UnpackUInt() tmp |= (byte)(UnpackByte() << 24); return tmp; } - public byte UnpackByte() { byte o = Data[bytePos]; @@ -344,7 +438,6 @@ public string UnpackString(int size) bytePos += size; return str; } - public UUID UnpackUUID() { if (bitPos != 0) throw new IndexOutOfRangeException(); @@ -367,58 +460,61 @@ private void PackBitArray(byte[] data, int totalCount) PackBitsFromByte(data[count], totalCount); } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] public void PackBitsFromByte(byte inbyte) { if (bitPos == 0) { - Data[bytePos++] = inbyte; + BYTESTORE(inbyte); + ++bytePos; if (bytePos < Data.Length) - Data[bytePos] = 0; + BYTESTORE(0); return; } if (inbyte == 0) { ++bytePos; - Data[bytePos] = 0; + BYTESTORE(0); return; } - Data[bytePos++] |= (byte)(inbyte >> bitPos); - Data[bytePos] = (byte)(inbyte << (8 - bitPos)); + OR_BYTESTORE((byte)(inbyte >> bitPos)); + ++bytePos; + BYTESTORE((byte)(inbyte << (8 - bitPos))); } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] public void PackBitsFromByte(byte inbyte, int count) { + if (count < 1) + return; + if (count > 8) //should not happen count = 7; else - count = count - 1; + --count; - while (count >= 0) + byte cur = READBYTE(); + while (count > 0) { if ((inbyte & (0x01 << count)) != 0) - Data[bytePos] |= (byte)(0x80 >> bitPos); + cur |= (byte)(0x80 >> bitPos); --count; ++bitPos; if (bitPos >= MAX_BITS) { - bitPos = 0; + BYTESTORE(cur); ++bytePos; - if (bytePos < Data.Length) - Data[bytePos] = 0; - } + cur = 0; + bitPos = 0; } } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public void PackBitFromBit(byte inbyte) - { if ((inbyte & 0x01) != 0) - Data[bytePos] |= (byte)(0x80 >> bitPos); + cur |= (byte)(0x80 >> bitPos); + BYTESTORE(cur); ++bitPos; if (bitPos >= MAX_BITS) @@ -426,7 +522,7 @@ public void PackBitFromBit(byte inbyte) bitPos = 0; ++bytePos; if (bytePos < Data.Length) - Data[bytePos] = 0; + BYTESTORE(0); } } @@ -435,11 +531,11 @@ public void PackBitFromBit(byte inbyte) /// /// Bit to pack - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] public void PackBit(bool bit) { if (bit) - Data[bytePos] |= (byte)(0x80 >> bitPos); + OR_BYTESTORE((byte)(0x80 >> bitPos)); ++bitPos; @@ -448,7 +544,7 @@ public void PackBit(bool bit) bitPos = 0; ++bytePos; if (bytePos < Data.Length) - Data[bytePos] = 0; + BYTESTORE(0); } } diff --git a/OpenMetaverse/Capabilities/CapsBase.cs b/OpenMetaverse/Capabilities/CapsBase.cs index 28b39664..598f8336 100644 --- a/OpenMetaverse/Capabilities/CapsBase.cs +++ b/OpenMetaverse/Capabilities/CapsBase.cs @@ -38,10 +38,27 @@ public static class CapsBase public delegate void OpenWriteEventHandler(HttpWebRequest request); public delegate void DownloadProgressEventHandler(HttpWebRequest request, HttpWebResponse response, int bytesReceived, int totalBytesToReceive); public delegate void RequestCompletedEventHandler(HttpWebRequest request, HttpWebResponse response, byte[] responseData, Exception error); + public static bool ValidateServerCertificate( + object sender, + X509Certificate certificate, + X509Chain chain, + SslPolicyErrors sslPolicyErrors) + { + //if (m_NoVerifyCertChain) + sslPolicyErrors &= ~SslPolicyErrors.RemoteCertificateChainErrors; + + //if (m_NoVerifyCertHostname) + sslPolicyErrors &= ~SslPolicyErrors.RemoteCertificateNameMismatch; + + if (sslPolicyErrors == SslPolicyErrors.None) + return true; + + return false; + } static CapsBase() { - ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true; + ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertificate; } private class RequestState diff --git a/OpenMetaverse/CapsToPacket.cs b/OpenMetaverse/CapsToPacket.cs index e0598621..79b1acf9 100644 --- a/OpenMetaverse/CapsToPacket.cs +++ b/OpenMetaverse/CapsToPacket.cs @@ -242,7 +242,7 @@ private static object ParseLLSDBlock(OSDMap blockData, Type blockType) } else if (fieldType == typeof(byte[]) && blockData[field.Name].Type == OSDType.String) { - field.SetValue(block, Utils.StringToBytes(blockData[field.Name])); + field.SetValue(block, Utils.StringToBytes(blockData[field.Name].AsString())); } } } diff --git a/OpenMetaverse/CoordinateFrame.cs b/OpenMetaverse/CoordinateFrame.cs index 4ab8ad2c..68bb1a3b 100644 --- a/OpenMetaverse/CoordinateFrame.cs +++ b/OpenMetaverse/CoordinateFrame.cs @@ -255,7 +255,7 @@ public void LookAt(Vector3 origin, Vector3 target) public void LookAt(Vector3 origin, Vector3 target, Vector3 upDirection) { this.origin = origin; - Vector3 at = new Vector3(target - origin); + Vector3 at = target - origin; at.Normalize(); LookDirection(at, upDirection); diff --git a/OpenMetaverse/DllmapConfigHelper.cs b/OpenMetaverse/DllmapConfigHelper.cs new file mode 100644 index 00000000..6dd01f91 --- /dev/null +++ b/OpenMetaverse/DllmapConfigHelper.cs @@ -0,0 +1,387 @@ +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSimulator Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``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 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. + */ + +using System; +using System.Collections.Generic; +using System.IO; +using System.Reflection; +using System.Runtime.InteropServices; +using System.Runtime.Intrinsics.X86; +using System.Xml.Serialization; +using System.Xml; + +namespace OpenMetaverse +{ + public static class DllmapConfigHelper + { + [XmlRoot("dllmap")] + public class dllmap + { + [XmlAttribute("os")] + public string os; + [XmlAttribute("cpu")] + public string cpu; + [XmlAttribute("target")] + public string target; + [XmlAttribute("dll")] + public string dll; + } + + [XmlRoot("configuration")] + public class configuration + { + [XmlElement("dllmap")] + public List maps = new(); + } + + private static readonly Dictionary LoadedLibs = new(); + private static readonly HashSet RegisteredAssemblies = new(); + private static readonly object m_mainlock = new object(); + + public static void RegisterAssembly(Assembly assembly) + { + lock (m_mainlock) + { + if (RegisteredAssemblies.Contains(assembly)) + return; + RegisteredAssemblies.Add(assembly); + } + + string assemblyPath = Path.GetDirectoryName(assembly.Location); + string path = Path.Combine(assemblyPath, + Path.GetFileNameWithoutExtension(assembly.Location) + ".dll.config"); + configuration c = ParseConfig(path); + if (c is null) + return; + + int matchs = ProcessAssemblyConfiguration(c, out List<(string libname, string libpath)> libstoload); + if (matchs == 0) + return; + if (libstoload.Count == 0) + return; + + foreach (var (libname, libpath) in libstoload) + { + path= Path.Combine(assemblyPath, libpath); + if (NativeLibrary.TryLoad(path, out IntPtr ptr)) + LoadedLibs.Add(libname, ptr); + else + LoadedLibs.Add(libname, IntPtr.Zero); + } + NativeLibrary.SetDllImportResolver(assembly, AssemblyDllImport); + } + private static IntPtr AssemblyDllImport(string libraryName, Assembly assembly, DllImportSearchPath? dllImportSearchPath) + { + if (LoadedLibs.TryGetValue(libraryName, out IntPtr ptr)) + return ptr; + return IntPtr.Zero; + } + + public static configuration ParseConfig(string path) + { + if (string.IsNullOrWhiteSpace(path)) + return null; + + configuration c; + try + { + if (!File.Exists(path)) + return null; + using FileStream fs = new(path, FileMode.Open); + using XmlReader reader = XmlReader.Create(fs); + XmlSerializer serializer = new(typeof(configuration)); + c = (configuration)serializer.Deserialize(reader); + } + catch + { + return null; + } + if (c is null || c.maps is null || c.maps.Count == 0) + return null; + return c; + } + + public static int ProcessAssemblyConfiguration(configuration c, out List<(string libname, string libpath)> libsToLoad) + { + libsToLoad = new List<(string libname, string libpath)>(c.maps.Count); + int MatchCount = 0; + HashSet libsdone = new(); + foreach (dllmap m in c.maps) + { + if (string.IsNullOrEmpty(m.target)) + continue; + if (string.IsNullOrEmpty(m.os)) + continue; + if (string.IsNullOrEmpty(m.dll)) + continue; + if (libsdone.Contains(m.dll)) + continue; + + bool match = false; + bool negate = m.os[0] == '!'; + if (negate) + m.os = m.os[1..]; + string[] tos = m.os.Split(','); + foreach (string s in tos) + { + match = OperatingSystem.IsOSPlatform(s); + if (match) + break; + } + if (negate) + match = !match; + if (!match) + continue; + + if (string.IsNullOrEmpty(m.cpu)) + { + libsdone.Add(m.dll); + MatchCount++; + if (!LoadedLibs.ContainsKey(m.dll)) + libsToLoad.Add((m.dll, m.target)); + break; + } + + negate = m.cpu[0] == '!'; + if (negate) + m.cpu = m.cpu[1..]; + m.cpu = m.cpu.ToLower(); + string[] tcpu = m.cpu.Split(','); + match = false; + foreach (string s in tcpu) + { + switch (s) + { + case "x86": + if (RuntimeInformation.ProcessArchitecture == Architecture.X86) + match = true; + break; + case "x86avx": + if (Avx.IsSupported && RuntimeInformation.ProcessArchitecture == Architecture.X86) + match = true; + break; + case "x86-64": + if (RuntimeInformation.ProcessArchitecture == Architecture.X64) + match = true; + break; + case "x86-64avx": + if (Avx.IsSupported && RuntimeInformation.ProcessArchitecture == Architecture.X64) + match = true; + break; + case "arm": + case "aarch32": + if (RuntimeInformation.ProcessArchitecture == Architecture.Arm) + match = true; + break; + case "arm64": + case "armv8": + case "aarch64": + if (RuntimeInformation.ProcessArchitecture == Architecture.Arm64) + match = true; + break; + case "s390": + case "s390x": + if (RuntimeInformation.ProcessArchitecture == Architecture.S390x) + match = true; + break; + } + if (match) + break; + } + if(negate) + match = !match; + + if (match) + { + MatchCount++; + libsdone.Add(m.dll); + if (!LoadedLibs.ContainsKey(m.dll)) + libsToLoad.Add((m.dll, m.target)); + } + } + return MatchCount; + } + + public static void RegisterDll(Assembly assembly, string libname) + { + lock (m_mainlock) + { + if (RegisteredAssemblies.Contains(assembly)) + return; + RegisteredAssemblies.Add(assembly); + } + + if (!LoadedLibs.TryGetValue(libname, out IntPtr ptr)) + { + string assemblyPath = Path.GetDirectoryName(assembly.Location); + string path = Path.Combine(assemblyPath, libname + ".dllconfig"); + configuration c = ParseConfig(path); + if (c is null) + return; + + string libpath = ProcessDllConfiguration(c); + if (string.IsNullOrEmpty(libpath)) + { + LoadedLibs.Add(libname, IntPtr.Zero); + return; + } + + libpath = Path.Combine(assemblyPath, libpath); + if (!NativeLibrary.TryLoad(libpath, out ptr)) + { + LoadedLibs.Add(libname, IntPtr.Zero); + return; + } + + LoadedLibs.Add(libname, ptr); + } + if (ptr != IntPtr.Zero) + NativeLibrary.SetDllImportResolver(assembly, AssemblyDllImport); + } + + public static IntPtr LoadDll(string libname) + { + if (LoadedLibs.TryGetValue(libname, out IntPtr ptr)) + return ptr; + + string execpath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); + + string path = Path.Combine(execpath, libname + ".dllconfig"); + configuration c = ParseConfig(path); + if (c is null) + return IntPtr.Zero; + + string libpath = ProcessDllConfiguration(c); + if (string.IsNullOrEmpty(libpath)) + { + LoadedLibs.Add(libname, IntPtr.Zero); + return IntPtr.Zero; + } + + libpath = Path.Combine(execpath, libpath); + if (NativeLibrary.TryLoad(libpath, out ptr)) + { + LoadedLibs.Add(libname, ptr); + return ptr; + } + + LoadedLibs.Add(libname, IntPtr.Zero); + return IntPtr.Zero; + } + + public static string ProcessDllConfiguration(configuration c) + { + string newlibname = null; + foreach (dllmap m in c.maps) + { + if (string.IsNullOrEmpty(m.target)) + continue; + if (string.IsNullOrEmpty(m.os)) + continue; + + bool match = false; + bool negate = m.os[0] == '!'; + if (negate) + m.os = m.os[1..]; + string[] tos = m.os.Split(','); + foreach (string s in tos) + { + match = System.OperatingSystem.IsOSPlatform(s); + if (match) + { + match = !negate; + break; + } + } + if (!match) + continue; + + if (string.IsNullOrEmpty(m.cpu)) + { + newlibname = m.target; + break; + } + + negate = m.cpu[0] == '!'; + if (negate) + m.cpu = m.cpu[1..]; + m.cpu = m.cpu.ToLower(); + string[] tcpu = m.cpu.Split(','); + match = false; + foreach (string s in tcpu) + { + switch (s) + { + case "x86": + if (RuntimeInformation.ProcessArchitecture == Architecture.X86) + match = true; + break; + case "x86avx": + if (Avx.IsSupported && RuntimeInformation.ProcessArchitecture == Architecture.X86) + match = true; + break; + case "x86-64": + if (RuntimeInformation.ProcessArchitecture == Architecture.X64) + match = true; + break; + case "x86-64avx": + if (Avx.IsSupported && RuntimeInformation.ProcessArchitecture == Architecture.X64) + match = true; + break; + case "arm": + case "aarch32": + if (RuntimeInformation.ProcessArchitecture == Architecture.Arm) + match = true; + break; + case "arm64": + case "armv8": + case "aarch64": + if (RuntimeInformation.ProcessArchitecture == Architecture.Arm64) + match = true; + break; + case "s390": + case "s390x": + if (RuntimeInformation.ProcessArchitecture == Architecture.S390x) + match = true; + break; + } + if (match) + { + match = !negate; + break; + } + } + if (match) + { + newlibname = m.target; + break; + } + } + return newlibname; + } + } +} diff --git a/OpenMetaverse/GridClient.cs b/OpenMetaverse/GridClient.cs index 713366a1..9cdf9c36 100644 --- a/OpenMetaverse/GridClient.cs +++ b/OpenMetaverse/GridClient.cs @@ -108,7 +108,7 @@ public class GridClient /// public GridClient() { - // Initialise SmartThreadPool when using mono + // Initialize work pool settings when using mono if (Type.GetType("Mono.Runtime") != null) { WorkPool.Init(true); diff --git a/OpenMetaverse/GroupManager.cs b/OpenMetaverse/GroupManager.cs index b1feb998..7cb087c8 100644 --- a/OpenMetaverse/GroupManager.cs +++ b/OpenMetaverse/GroupManager.cs @@ -247,7 +247,7 @@ public struct GroupNotice /// public byte[] SerializeAttachment() { - if (OwnerID == UUID.Zero || AttachmentID == UUID.Zero) + if (OwnerID.IsZero() || AttachmentID.IsZero()) return Utils.EmptyBytes; OpenMetaverse.StructuredData.OSDMap att = new OpenMetaverse.StructuredData.OSDMap(); diff --git a/OpenMetaverse/Helpers.cs b/OpenMetaverse/Helpers.cs index 545e3b39..5b870c2f 100644 --- a/OpenMetaverse/Helpers.cs +++ b/OpenMetaverse/Helpers.cs @@ -24,13 +24,10 @@ * POSSIBILITY OF SUCH DAMAGE. */ -using ComponentAce.Compression.Libs.zlib; using OpenMetaverse.StructuredData; -using System; -using System.Collections.Generic; -using System.IO; using System.Reflection; using System.Text; +using System.IO.Compression; namespace OpenMetaverse { @@ -317,17 +314,13 @@ public static int ZeroDecode(byte[] src, int srclen, byte[] dest) if (srclen > src.Length) throw new ArgumentException("srclen cannot be greater than src.Length"); - uint zerolen = 0; - int bodylen = 0; + uint zerolen = 6; uint i = 0; try { Buffer.BlockCopy(src, 0, dest, 0, 6); - zerolen = 6; - bodylen = srclen; - - for (i = zerolen; i < bodylen; i++) + for (i = zerolen; i < srclen; i++) { if (src[i] == 0x00) { @@ -342,23 +335,16 @@ public static int ZeroDecode(byte[] src, int srclen, byte[] dest) { dest[zerolen++] = src[i]; } - } - - // Copy appended ACKs - for (; i < srclen; i++) - { - dest[zerolen++] = src[i]; - } - + } return (int)zerolen; } catch (Exception ex) { - Logger.Log(String.Format("Zerodecoding error: i={0}, srclen={1}, bodylen={2}, zerolen={3}\n{4}\n{5}", - i, srclen, bodylen, zerolen, Utils.BytesToHexString(src, srclen, null), ex), LogLevel.Error); + Logger.Log(String.Format("Zerodecoding error: i={0}, srclen={1}, zerolen={2}\n{3}\n{4}", + i, srclen, zerolen, Utils.BytesToHexString(src, srclen, null), ex), LogLevel.Error); - throw new IndexOutOfRangeException(String.Format("Zerodecoding error: i={0}, srclen={1}, bodylen={2}, zerolen={3}\n{4}\n{5}", - i, srclen, bodylen, zerolen, Utils.BytesToHexString(src, srclen, null), ex.InnerException)); + throw new IndexOutOfRangeException(String.Format("Zerodecoding error: i={0}, srclen={1}, zerolen={2}\n{3}\n{4}", + i, srclen, zerolen, Utils.BytesToHexString(src, srclen, null), ex.InnerException)); } } @@ -632,35 +618,29 @@ public static void CopyStream(Stream input, Stream output) public static byte[] ZCompressOSD(OSD data) { - byte[] ret = null; + byte[] serialized = OSDParser.SerializeLLSDBinary(data, false); using (MemoryStream outMemoryStream = new MemoryStream()) - using (ZOutputStream outZStream = new ZOutputStream(outMemoryStream, zlibConst.Z_BEST_COMPRESSION)) - using (Stream inMemoryStream = new MemoryStream(OSDParser.SerializeLLSDBinary(data, false))) { - CopyStream(inMemoryStream, outZStream); - outZStream.finish(); - ret = outMemoryStream.ToArray(); - } + using (ZLibStream outZStream = new ZLibStream(outMemoryStream, CompressionLevel.SmallestSize, true)) + { + outZStream.Write(serialized, 0, serialized.Length); + } - return ret; + return outMemoryStream.ToArray(); + } } public static OSD ZDecompressOSD(byte[] data) { - OSD ret; - using (MemoryStream input = new MemoryStream(data)) + using (ZLibStream zStream = new ZLibStream(input, CompressionMode.Decompress)) using (MemoryStream output = new MemoryStream()) - using (ZOutputStream zout = new ZOutputStream(output)) { - CopyStream(input, zout); - zout.finish(); + CopyStream(zStream, output); output.Seek(0, SeekOrigin.Begin); - ret = OSDParser.DeserializeLLSDBinary(output); + return OSDParser.DeserializeLLSDBinary(output); } - - return ret; } } } diff --git a/OpenMetaverse/Imaging/BakeLayer.cs b/OpenMetaverse/Imaging/BakeLayer.cs index 91326df4..ed933e88 100644 --- a/OpenMetaverse/Imaging/BakeLayer.cs +++ b/OpenMetaverse/Imaging/BakeLayer.cs @@ -26,9 +26,9 @@ using log4net; using OpenMetaverse.Assets; +using SkiaSharp; using System; using System.Collections.Generic; -using System.Drawing; using System.IO; using System.Reflection; @@ -340,7 +340,7 @@ public static ManagedImage LoadResourceLayer(string fileName) { try { - Bitmap bitmap = null; + SKBitmap bitmap = null; lock (ResourceSync) { using (Stream stream = Helpers.GetResourceStream(fileName, Settings.RESOURCE_DIR)) @@ -355,7 +355,8 @@ public static ManagedImage LoadResourceLayer(string fileName) } else { - return new ManagedImage(bitmap); + using (bitmap) + return new ManagedImage(bitmap); } } catch (Exception e) @@ -581,9 +582,9 @@ private void ApplyTint(ManagedImage dest, Color4 src) for (int i = 0; i < dest.Red.Length; i++) { - dest.Red[i] = (byte)((dest.Red[i] * Utils.FloatToByte(src.R, 0f, 1f)) >> 8); - dest.Green[i] = (byte)((dest.Green[i] * Utils.FloatToByte(src.G, 0f, 1f)) >> 8); - dest.Blue[i] = (byte)((dest.Blue[i] * Utils.FloatToByte(src.B, 0f, 1f)) >> 8); + dest.Red[i] = (byte)((dest.Red[i] * Utils.FloatZeroOneToByte(src.R)) >> 8); + dest.Green[i] = (byte)((dest.Green[i] * Utils.FloatZeroOneToByte(src.G)) >> 8); + dest.Blue[i] = (byte)((dest.Blue[i] * Utils.FloatZeroOneToByte(src.B)) >> 8); } } @@ -610,9 +611,9 @@ private void InitBakedLayerColor(Color4 color) /// Blue value private void InitBakedLayerColor(float r, float g, float b) { - byte rByte = Utils.FloatToByte(r, 0f, 1f); - byte gByte = Utils.FloatToByte(g, 0f, 1f); - byte bByte = Utils.FloatToByte(b, 0f, 1f); + byte rByte = Utils.FloatZeroOneToByte(r); + byte gByte = Utils.FloatZeroOneToByte(g); + byte bByte = Utils.FloatZeroOneToByte(b); byte rAlt, gAlt, bAlt; diff --git a/OpenMetaverse/Imaging/ManagedImage.cs b/OpenMetaverse/Imaging/ManagedImage.cs index 8d7a555b..2fd833ff 100644 --- a/OpenMetaverse/Imaging/ManagedImage.cs +++ b/OpenMetaverse/Imaging/ManagedImage.cs @@ -1,535 +1,457 @@ -/* - * Copyright (c) 2006-2016, openmetaverse.co - * All rights reserved. - * - * - Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, this - * list of conditions and the following disclaimer. - * - Neither the name of the openmetaverse.co nor the names - * of its contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -using System; - -namespace OpenMetaverse.Imaging -{ - public class ManagedImage - { - [Flags] - public enum ImageChannels - { - Gray = 1, - Color = 2, - Alpha = 4, - Bump = 8 - }; - - public enum ImageResizeAlgorithm - { - NearestNeighbor - } - - /// - /// Image width - /// - public int Width; - - /// - /// Image height - /// - public int Height; - - /// - /// Image channel flags - /// - public ImageChannels Channels; - - /// - /// Red channel data - /// - public byte[] Red; - - /// - /// Green channel data - /// - public byte[] Green; - - /// - /// Blue channel data - /// - public byte[] Blue; - - /// - /// Alpha channel data - /// - public byte[] Alpha; - - /// - /// Bump channel data - /// - public byte[] Bump; - - /// - /// Create a new blank image - /// - /// width - /// height - /// channel flags - public ManagedImage(int width, int height, ImageChannels channels) - { - Width = width; - Height = height; - Channels = channels; - - int n = width * height; - - if ((channels & ImageChannels.Gray) != 0) - { - Red = new byte[n]; - } - else if ((channels & ImageChannels.Color) != 0) - { - Red = new byte[n]; - Green = new byte[n]; - Blue = new byte[n]; - } - - if ((channels & ImageChannels.Alpha) != 0) - Alpha = new byte[n]; - - if ((channels & ImageChannels.Bump) != 0) - Bump = new byte[n]; - } - -#if !NO_UNSAFE - /// - /// - /// - /// - public ManagedImage(System.Drawing.Bitmap bitmap) - { - Width = bitmap.Width; - Height = bitmap.Height; - - int pixelCount = Width * Height; - - if (bitmap.PixelFormat == System.Drawing.Imaging.PixelFormat.Format32bppArgb) - { - Channels = ImageChannels.Alpha | ImageChannels.Color; - Red = new byte[pixelCount]; - Green = new byte[pixelCount]; - Blue = new byte[pixelCount]; - Alpha = new byte[pixelCount]; - - System.Drawing.Imaging.BitmapData bd = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, Width, Height), - System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); - - unsafe - { - byte* pixel = (byte*)bd.Scan0; - - for (int i = 0; i < pixelCount; i++) - { - // GDI+ gives us BGRA and we need to turn that in to RGBA - Blue[i] = *(pixel++); - Green[i] = *(pixel++); - Red[i] = *(pixel++); - Alpha[i] = *(pixel++); - } - } - - bitmap.UnlockBits(bd); - } - else if (bitmap.PixelFormat == System.Drawing.Imaging.PixelFormat.Format16bppGrayScale) - { - Channels = ImageChannels.Gray; - Red = new byte[pixelCount]; - - throw new NotImplementedException("16bpp grayscale image support is incomplete"); - } - else if (bitmap.PixelFormat == System.Drawing.Imaging.PixelFormat.Format24bppRgb) - { - Channels = ImageChannels.Color; - Red = new byte[pixelCount]; - Green = new byte[pixelCount]; - Blue = new byte[pixelCount]; - - System.Drawing.Imaging.BitmapData bd = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, Width, Height), - System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format24bppRgb); - - unsafe - { - byte* pixel = (byte*)bd.Scan0; - - for (int i = 0; i < pixelCount; i++) - { - // GDI+ gives us BGR and we need to turn that in to RGB - Blue[i] = *(pixel++); - Green[i] = *(pixel++); - Red[i] = *(pixel++); - } - } - - bitmap.UnlockBits(bd); - } - else if (bitmap.PixelFormat == System.Drawing.Imaging.PixelFormat.Format32bppRgb) - { - Channels = ImageChannels.Color; - Red = new byte[pixelCount]; - Green = new byte[pixelCount]; - Blue = new byte[pixelCount]; - - System.Drawing.Imaging.BitmapData bd = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, Width, Height), - System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb); - - unsafe - { - byte* pixel = (byte*)bd.Scan0; - - for (int i = 0; i < pixelCount; i++) - { - // GDI+ gives us BGR and we need to turn that in to RGB - Blue[i] = *(pixel++); - Green[i] = *(pixel++); - Red[i] = *(pixel++); - pixel++; // Skip over the empty byte where the Alpha info would normally be - } - } - - bitmap.UnlockBits(bd); - } - else - { - throw new NotSupportedException("Unrecognized pixel format: " + bitmap.PixelFormat.ToString()); - } - } -#endif - - /// - /// Convert the channels in the image. Channels are created or destroyed as required. - /// - /// new channel flags - public void ConvertChannels(ImageChannels channels) - { - if (Channels == channels) - return; - - int n = Width * Height; - ImageChannels add = Channels ^ channels & channels; - ImageChannels del = Channels ^ channels & Channels; - - if ((add & ImageChannels.Color) != 0) - { - Red = new byte[n]; - Green = new byte[n]; - Blue = new byte[n]; - } - else if ((del & ImageChannels.Color) != 0) - { - Red = null; - Green = null; - Blue = null; - } - - if ((add & ImageChannels.Alpha) != 0) - { - Alpha = new byte[n]; - FillArray(Alpha, 255); - } - else if ((del & ImageChannels.Alpha) != 0) - Alpha = null; - - if ((add & ImageChannels.Bump) != 0) - Bump = new byte[n]; - else if ((del & ImageChannels.Bump) != 0) - Bump = null; - - Channels = channels; - } - - /// - /// Resize or stretch the image using nearest neighbor (ugly) resampling - /// - /// new width - /// new height - public void ResizeNearestNeighbor(int width, int height) - { - if (width == Width && height == Height) - return; - - byte[] - red = null, - green = null, - blue = null, - alpha = null, - bump = null; - int n = width * height; - int di = 0, si; - - if (Red != null) red = new byte[n]; - if (Green != null) green = new byte[n]; - if (Blue != null) blue = new byte[n]; - if (Alpha != null) alpha = new byte[n]; - if (Bump != null) bump = new byte[n]; - - for (int y = 0; y < height; y++) - { - for (int x = 0; x < width; x++) - { - si = (y * Height / height) * Width + (x * Width / width); - if (Red != null) red[di] = Red[si]; - if (Green != null) green[di] = Green[si]; - if (Blue != null) blue[di] = Blue[si]; - if (Alpha != null) alpha[di] = Alpha[si]; - if (Bump != null) bump[di] = Bump[si]; - di++; - } - } - - Width = width; - Height = height; - Red = red; - Green = green; - Blue = blue; - Alpha = alpha; - Bump = bump; - } - - /// - /// Create a byte array containing 32-bit RGBA data with a bottom-left - /// origin, suitable for feeding directly into OpenGL - /// - /// A byte array containing raw texture data - public byte[] ExportRaw() - { - byte[] raw = new byte[Width * Height * 4]; - - if ((Channels & ImageChannels.Alpha) != 0) - { - if ((Channels & ImageChannels.Color) != 0) - { - // RGBA - for (int h = 0; h < Height; h++) - { - for (int w = 0; w < Width; w++) - { - int pos = (Height - 1 - h) * Width + w; - int srcPos = h * Width + w; - - raw[pos * 4 + 0] = Red[srcPos]; - raw[pos * 4 + 1] = Green[srcPos]; - raw[pos * 4 + 2] = Blue[srcPos]; - raw[pos * 4 + 3] = Alpha[srcPos]; - } - } - } - else - { - // Alpha only - for (int h = 0; h < Height; h++) - { - for (int w = 0; w < Width; w++) - { - int pos = (Height - 1 - h) * Width + w; - int srcPos = h * Width + w; - - raw[pos * 4 + 0] = Alpha[srcPos]; - raw[pos * 4 + 1] = Alpha[srcPos]; - raw[pos * 4 + 2] = Alpha[srcPos]; - raw[pos * 4 + 3] = Byte.MaxValue; - } - } - } - } - else - { - // RGB - for (int h = 0; h < Height; h++) - { - for (int w = 0; w < Width; w++) - { - int pos = (Height - 1 - h) * Width + w; - int srcPos = h * Width + w; - - raw[pos * 4 + 0] = Red[srcPos]; - raw[pos * 4 + 1] = Green[srcPos]; - raw[pos * 4 + 2] = Blue[srcPos]; - raw[pos * 4 + 3] = Byte.MaxValue; - } - } - } - - return raw; - } - - /// - /// Create a byte array containing 32-bit RGBA data with a bottom-left - /// origin, suitable for feeding directly into OpenGL - /// - /// A byte array containing raw texture data - public System.Drawing.Bitmap ExportBitmap() - { - byte[] raw = new byte[Width * Height * 4]; - - if ((Channels & ImageChannels.Alpha) != 0) - { - if ((Channels & ImageChannels.Color) != 0) - { - // RGBA - for (int pos = 0; pos < Height * Width; pos++) - { - raw[pos * 4 + 0] = Blue[pos]; - raw[pos * 4 + 1] = Green[pos]; - raw[pos * 4 + 2] = Red[pos]; - raw[pos * 4 + 3] = Alpha[pos]; - } - } - else - { - // Alpha only - for (int pos = 0; pos < Height * Width; pos++) - { - raw[pos * 4 + 0] = Alpha[pos]; - raw[pos * 4 + 1] = Alpha[pos]; - raw[pos * 4 + 2] = Alpha[pos]; - raw[pos * 4 + 3] = Byte.MaxValue; - } - } - } - else - { - // RGB - for (int pos = 0; pos < Height * Width; pos++) - { - raw[pos * 4 + 0] = Blue[pos]; - raw[pos * 4 + 1] = Green[pos]; - raw[pos * 4 + 2] = Red[pos]; - raw[pos * 4 + 3] = Byte.MaxValue; - } - } - - System.Drawing.Bitmap b = new System.Drawing.Bitmap( - Width, - Height, - System.Drawing.Imaging.PixelFormat.Format32bppArgb); - - System.Drawing.Imaging.BitmapData bd = b.LockBits(new System.Drawing.Rectangle(0, 0, b.Width, b.Height), - System.Drawing.Imaging.ImageLockMode.WriteOnly, - System.Drawing.Imaging.PixelFormat.Format32bppArgb); - - System.Runtime.InteropServices.Marshal.Copy(raw, 0, bd.Scan0, Width * Height * 4); - - b.UnlockBits(bd); - - return b; - } - - public byte[] ExportTGA() - { - byte[] tga = new byte[Width * Height * ((Channels & ImageChannels.Alpha) == 0 ? 3 : 4) + 32]; - int di = 0; - tga[di++] = 0; // idlength - tga[di++] = 0; // colormaptype = 0: no colormap - tga[di++] = 2; // image type = 2: uncompressed RGB - tga[di++] = 0; // color map spec is five zeroes for no color map - tga[di++] = 0; // color map spec is five zeroes for no color map - tga[di++] = 0; // color map spec is five zeroes for no color map - tga[di++] = 0; // color map spec is five zeroes for no color map - tga[di++] = 0; // color map spec is five zeroes for no color map - tga[di++] = 0; // x origin = two bytes - tga[di++] = 0; // x origin = two bytes - tga[di++] = 0; // y origin = two bytes - tga[di++] = 0; // y origin = two bytes - tga[di++] = (byte)(Width & 0xFF); // width - low byte - tga[di++] = (byte)(Width >> 8); // width - hi byte - tga[di++] = (byte)(Height & 0xFF); // height - low byte - tga[di++] = (byte)(Height >> 8); // height - hi byte - tga[di++] = (byte)((Channels & ImageChannels.Alpha) == 0 ? 24 : 32); // 24/32 bits per pixel - tga[di++] = (byte)((Channels & ImageChannels.Alpha) == 0 ? 32 : 40); // image descriptor byte - - int n = Width * Height; - - if ((Channels & ImageChannels.Alpha) != 0) - { - if ((Channels & ImageChannels.Color) != 0) - { - // RGBA - for (int i = 0; i < n; i++) - { - tga[di++] = Blue[i]; - tga[di++] = Green[i]; - tga[di++] = Red[i]; - tga[di++] = Alpha[i]; - } - } - else - { - // Alpha only - for (int i = 0; i < n; i++) - { - tga[di++] = Alpha[i]; - tga[di++] = Alpha[i]; - tga[di++] = Alpha[i]; - tga[di++] = Byte.MaxValue; - } - } - } - else - { - // RGB - for (int i = 0; i < n; i++) - { - tga[di++] = Blue[i]; - tga[di++] = Green[i]; - tga[di++] = Red[i]; - } - } - - return tga; - } - - private static void FillArray(byte[] array, byte value) - { - if (array != null) - { - for (int i = 0; i < array.Length; i++) - array[i] = value; - } - } - - public void Clear() - { - FillArray(Red, 0); - FillArray(Green, 0); - FillArray(Blue, 0); - FillArray(Alpha, 0); - FillArray(Bump, 0); - } - - public ManagedImage Clone() - { - ManagedImage image = new ManagedImage(Width, Height, Channels); - if (Red != null) image.Red = (byte[])Red.Clone(); - if (Green != null) image.Green = (byte[])Green.Clone(); - if (Blue != null) image.Blue = (byte[])Blue.Clone(); - if (Alpha != null) image.Alpha = (byte[])Alpha.Clone(); - if (Bump != null) image.Bump = (byte[])Bump.Clone(); - return image; - } - } -} +/* + * Copyright (c) 2006-2016, openmetaverse.co + * All rights reserved. + * + * - Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * - Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * - Neither the name of the openmetaverse.co nor the names + * of its contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Runtime.InteropServices; +using SkiaSharp; + +namespace OpenMetaverse.Imaging +{ + public class ManagedImage + { + [Flags] + public enum ImageChannels + { + Gray = 1, + Color = 2, + Alpha = 4, + Bump = 8 + }; + + public enum ImageResizeAlgorithm + { + NearestNeighbor + } + + /// + /// Image width + /// + public int Width; + + /// + /// Image height + /// + public int Height; + + /// + /// Image channel flags + /// + public ImageChannels Channels; + + /// + /// Red channel data + /// + public byte[] Red; + + /// + /// Green channel data + /// + public byte[] Green; + + /// + /// Blue channel data + /// + public byte[] Blue; + + /// + /// Alpha channel data + /// + public byte[] Alpha; + + /// + /// Bump channel data + /// + public byte[] Bump; + + /// + /// Create a new blank image + /// + /// width + /// height + /// channel flags + public ManagedImage(int width, int height, ImageChannels channels) + { + Width = width; + Height = height; + Channels = channels; + + int n = width * height; + + if ((channels & ImageChannels.Gray) != 0) + { + Red = new byte[n]; + } + else if ((channels & ImageChannels.Color) != 0) + { + Red = new byte[n]; + Green = new byte[n]; + Blue = new byte[n]; + } + + if ((channels & ImageChannels.Alpha) != 0) + Alpha = new byte[n]; + + if ((channels & ImageChannels.Bump) != 0) + Bump = new byte[n]; + } + + /// + /// + /// + /// + public ManagedImage(SKBitmap bitmap) + { + Width = bitmap.Width; + Height = bitmap.Height; + + int pixelCount = Width * Height; + + bool hasAlpha = bitmap.AlphaType != SKAlphaType.Opaque; + Channels = ImageChannels.Color | (hasAlpha ? ImageChannels.Alpha : 0); + Red = GC.AllocateUninitializedArray(pixelCount); + Green = GC.AllocateUninitializedArray(pixelCount); + Blue = GC.AllocateUninitializedArray(pixelCount); + if (hasAlpha) + Alpha = GC.AllocateUninitializedArray(pixelCount); + + int i = 0; + for (int y = 0; y < Height; y++) + { + for (int x = 0; x < Width; x++) + { + SKColor pixel = bitmap.GetPixel(x, y); + Red[i] = pixel.Red; + Green[i] = pixel.Green; + Blue[i] = pixel.Blue; + if (hasAlpha) + Alpha[i] = pixel.Alpha; + i++; + } + } + } + + /// + /// Convert the channels in the image. Channels are created or destroyed as required. + /// + /// new channel flags + public void ConvertChannels(ImageChannels channels) + { + if (Channels == channels) + return; + + int n = Width * Height; + ImageChannels add = Channels ^ channels & channels; + ImageChannels del = Channels ^ channels & Channels; + + if ((add & ImageChannels.Color) != 0) + { + Red = GC.AllocateUninitializedArray(n); + Green = GC.AllocateUninitializedArray(n); + Blue = GC.AllocateUninitializedArray(n); + } + else if ((del & ImageChannels.Color) != 0) + { + Red = null; + Green = null; + Blue = null; + } + + if ((add & ImageChannels.Alpha) != 0) + { + Alpha = new byte[n]; + FillArray(Alpha, 255); + } + else if ((del & ImageChannels.Alpha) != 0) + Alpha = null; + + if ((add & ImageChannels.Bump) != 0) + Bump = new byte[n]; + else if ((del & ImageChannels.Bump) != 0) + Bump = null; + + Channels = channels; + } + + /// + /// Resize or stretch the image using nearest neighbor (ugly) resampling + /// + /// new width + /// new height + public void ResizeNearestNeighbor(int width, int height) + { + if (width == Width && height == Height) + return; + + byte[] + red = null, + green = null, + blue = null, + alpha = null, + bump = null; + int n = width * height; + int di = 0, si; + + if (Red != null) red = new byte[n]; + if (Green != null) green = new byte[n]; + if (Blue != null) blue = new byte[n]; + if (Alpha != null) alpha = new byte[n]; + if (Bump != null) bump = new byte[n]; + + for (int y = 0; y < height; y++) + { + for (int x = 0; x < width; x++) + { + si = (y * Height / height) * Width + (x * Width / width); + if (Red != null) red[di] = Red[si]; + if (Green != null) green[di] = Green[si]; + if (Blue != null) blue[di] = Blue[si]; + if (Alpha != null) alpha[di] = Alpha[si]; + if (Bump != null) bump[di] = Bump[si]; + di++; + } + } + + Width = width; + Height = height; + Red = red; + Green = green; + Blue = blue; + Alpha = alpha; + Bump = bump; + } + + /// + /// Create a byte array containing 32-bit RGBA data with a bottom-left + /// origin, suitable for feeding directly into OpenGL + /// + /// A byte array containing raw texture data + public byte[] ExportRaw() + { + byte[] raw = new byte[Width * Height * 4]; + + if ((Channels & ImageChannels.Alpha) != 0) + { + if ((Channels & ImageChannels.Color) != 0) + { + // RGBA + for (int h = 0; h < Height; h++) + { + for (int w = 0; w < Width; w++) + { + int pos = (Height - 1 - h) * Width + w; + int srcPos = h * Width + w; + + raw[pos * 4 + 0] = Red[srcPos]; + raw[pos * 4 + 1] = Green[srcPos]; + raw[pos * 4 + 2] = Blue[srcPos]; + raw[pos * 4 + 3] = Alpha[srcPos]; + } + } + } + else + { + // Alpha only + for (int h = 0; h < Height; h++) + { + for (int w = 0; w < Width; w++) + { + int pos = (Height - 1 - h) * Width + w; + int srcPos = h * Width + w; + + raw[pos * 4 + 0] = Alpha[srcPos]; + raw[pos * 4 + 1] = Alpha[srcPos]; + raw[pos * 4 + 2] = Alpha[srcPos]; + raw[pos * 4 + 3] = Byte.MaxValue; + } + } + } + } + else + { + // RGB + for (int h = 0; h < Height; h++) + { + for (int w = 0; w < Width; w++) + { + int pos = (Height - 1 - h) * Width + w; + int srcPos = h * Width + w; + + raw[pos * 4 + 0] = Red[srcPos]; + raw[pos * 4 + 1] = Green[srcPos]; + raw[pos * 4 + 2] = Blue[srcPos]; + raw[pos * 4 + 3] = Byte.MaxValue; + } + } + } + + return raw; + } + + /// + /// Create a byte array containing 32-bit RGBA data with a bottom-left + /// origin, suitable for feeding directly into OpenGL + /// + /// A byte array containing raw texture data + public SKBitmap ExportBitmap() + { + byte[] raw = new byte[Width * Height * 4]; + + if ((Channels & ImageChannels.Alpha) != 0) + { + if ((Channels & ImageChannels.Color) != 0) + { + // RGBA + for (int pos = 0; pos < Height * Width; pos++) + { + raw[pos * 4 + 0] = Blue[pos]; + raw[pos * 4 + 1] = Green[pos]; + raw[pos * 4 + 2] = Red[pos]; + raw[pos * 4 + 3] = Alpha[pos]; + } + } + else + { + // Alpha only + for (int pos = 0; pos < Height * Width; pos++) + { + raw[pos * 4 + 0] = Alpha[pos]; + raw[pos * 4 + 1] = Alpha[pos]; + raw[pos * 4 + 2] = Alpha[pos]; + raw[pos * 4 + 3] = Byte.MaxValue; + } + } + } + else + { + // RGB + for (int pos = 0; pos < Height * Width; pos++) + { + raw[pos * 4 + 0] = Blue[pos]; + raw[pos * 4 + 1] = Green[pos]; + raw[pos * 4 + 2] = Red[pos]; + raw[pos * 4 + 3] = Byte.MaxValue; + } + } + + SKBitmap bitmap = new SKBitmap(new SKImageInfo(Width, Height, SKColorType.Bgra8888, SKAlphaType.Unpremul)); + Marshal.Copy(raw, 0, bitmap.GetPixels(), Width * Height * 4); + return bitmap; + } + + public byte[] ExportTGA() + { + byte[] tga = new byte[Width * Height * ((Channels & ImageChannels.Alpha) == 0 ? 3 : 4) + 32]; + int di = 0; + tga[di++] = 0; // idlength + tga[di++] = 0; // colormaptype = 0: no colormap + tga[di++] = 2; // image type = 2: uncompressed RGB + tga[di++] = 0; // color map spec is five zeroes for no color map + tga[di++] = 0; // color map spec is five zeroes for no color map + tga[di++] = 0; // color map spec is five zeroes for no color map + tga[di++] = 0; // color map spec is five zeroes for no color map + tga[di++] = 0; // color map spec is five zeroes for no color map + tga[di++] = 0; // x origin = two bytes + tga[di++] = 0; // x origin = two bytes + tga[di++] = 0; // y origin = two bytes + tga[di++] = 0; // y origin = two bytes + tga[di++] = (byte)(Width & 0xFF); // width - low byte + tga[di++] = (byte)(Width >> 8); // width - hi byte + tga[di++] = (byte)(Height & 0xFF); // height - low byte + tga[di++] = (byte)(Height >> 8); // height - hi byte + tga[di++] = (byte)((Channels & ImageChannels.Alpha) == 0 ? 24 : 32); // 24/32 bits per pixel + tga[di++] = (byte)((Channels & ImageChannels.Alpha) == 0 ? 32 : 40); // image descriptor byte + + int n = Width * Height; + + if ((Channels & ImageChannels.Alpha) != 0) + { + if ((Channels & ImageChannels.Color) != 0) + { + // RGBA + for (int i = 0; i < n; i++) + { + tga[di++] = Blue[i]; + tga[di++] = Green[i]; + tga[di++] = Red[i]; + tga[di++] = Alpha[i]; + } + } + else + { + // Alpha only + for (int i = 0; i < n; i++) + { + tga[di++] = Alpha[i]; + tga[di++] = Alpha[i]; + tga[di++] = Alpha[i]; + tga[di++] = Byte.MaxValue; + } + } + } + else + { + // RGB + for (int i = 0; i < n; i++) + { + tga[di++] = Blue[i]; + tga[di++] = Green[i]; + tga[di++] = Red[i]; + } + } + + return tga; + } + + private static void FillArray(byte[] array, byte value) + { + if (array != null) + { + for (int i = 0; i < array.Length; i++) + array[i] = value; + } + } + + public void Clear() + { + FillArray(Red, 0); + FillArray(Green, 0); + FillArray(Blue, 0); + FillArray(Alpha, 0); + FillArray(Bump, 0); + } + + public ManagedImage Clone() + { + ManagedImage image = new ManagedImage(Width, Height, Channels); + if (Red != null) image.Red = (byte[])Red.Clone(); + if (Green != null) image.Green = (byte[])Green.Clone(); + if (Blue != null) image.Blue = (byte[])Blue.Clone(); + if (Alpha != null) image.Alpha = (byte[])Alpha.Clone(); + if (Bump != null) image.Bump = (byte[])Bump.Clone(); + return image; + } + } +} diff --git a/OpenMetaverse/Imaging/OpenJPEG.cs b/OpenMetaverse/Imaging/OpenJPEG.cs index 2d68d668..f967c159 100644 --- a/OpenMetaverse/Imaging/OpenJPEG.cs +++ b/OpenMetaverse/Imaging/OpenJPEG.cs @@ -24,566 +24,115 @@ * POSSIBILITY OF SUCH DAMAGE. */ +using CoreJ2K; +using SkiaSharp; using System; -using System.Drawing; -using System.Drawing.Imaging; -using System.Runtime.InteropServices; namespace OpenMetaverse.Imaging { -#if !NO_UNSAFE /// - /// A Wrapper around openjpeg to encode and decode images to and from byte arrays + /// JPEG2000 codec wrapper implemented with CoreJ2K. /// - public class OpenJPEG + public static class OpenJPEG { /// TGA Header size public const int TGA_HEADER_SIZE = 32; - #region JPEG2000 Structs - /// /// Defines the beginning and ending file positions of a layer in an /// LRCP-progression JPEG2000 file /// [System.Diagnostics.DebuggerDisplay("Start = {Start} End = {End} Size = {End - Start}")] - [StructLayout(LayoutKind.Sequential, Pack = 4)] public struct J2KLayerInfo { public int Start; public int End; } - /// - /// This structure is used to marshal both encoded and decoded images. - /// MUST MATCH THE STRUCT IN dotnet.h! - /// - [StructLayout(LayoutKind.Sequential, Pack = 4)] - private struct MarshalledImage - { - public IntPtr encoded; // encoded image data - public int length; // encoded image length - public int dummy; // padding for 64-bit alignment - - public IntPtr decoded; // decoded image, contiguous components - - public int width; // width of decoded image - public int height; // height of decoded image - public int layers; // layer count - public int resolutions; // resolution count - public int components; // component count - public int packet_count; // packet count - public IntPtr packets; // pointer to the packets array - } - - /// - /// Information about a single packet in a JPEG2000 stream - /// - [StructLayout(LayoutKind.Sequential, Pack = 4)] - private struct MarshalledPacket - { - /// Packet start position - public int start_pos; - /// Packet header end position - public int end_ph_pos; - /// Packet end position - public int end_pos; - - public override string ToString() - { - return String.Format("start_pos: {0} end_ph_pos: {1} end_pos: {2}", - start_pos, end_ph_pos, end_pos); - } - } - - #endregion JPEG2000 Structs - - #region Unmanaged Function Declarations - - - // allocate encoded buffer based on length field - [System.Security.SuppressUnmanagedCodeSecurity] - [DllImport("openjpeg-dotnet.dll", CallingConvention = CallingConvention.Cdecl)] - private static extern bool DotNetAllocEncoded(ref MarshalledImage image); - - // allocate decoded buffer based on width and height fields - [System.Security.SuppressUnmanagedCodeSecurity] - [DllImport("openjpeg-dotnet.dll", CallingConvention = CallingConvention.Cdecl)] - private static extern bool DotNetAllocDecoded(ref MarshalledImage image); - - // free buffers - [System.Security.SuppressUnmanagedCodeSecurity] - [DllImport("openjpeg-dotnet.dll", CallingConvention = CallingConvention.Cdecl)] - private static extern bool DotNetFree(ref MarshalledImage image); - - // encode raw to jpeg2000 - [System.Security.SuppressUnmanagedCodeSecurity] - [DllImport("openjpeg-dotnet.dll", CallingConvention = CallingConvention.Cdecl)] - private static extern bool DotNetEncode(ref MarshalledImage image, bool lossless); - - // decode jpeg2000 to raw - [System.Security.SuppressUnmanagedCodeSecurity] - [DllImport("openjpeg-dotnet.dll", CallingConvention = CallingConvention.Cdecl)] - private static extern bool DotNetDecode(ref MarshalledImage image); - - // decode jpeg2000 to raw, get jpeg2000 file info - [System.Security.SuppressUnmanagedCodeSecurity] - [DllImport("openjpeg-dotnet.dll", CallingConvention = CallingConvention.Cdecl)] - private static extern bool DotNetDecodeWithInfo(ref MarshalledImage image); - - // invoke 64 bit openjpeg calls - [System.Security.SuppressUnmanagedCodeSecurity] - [DllImport("openjpeg-dotnet-x86_64.dll", CallingConvention = CallingConvention.Cdecl)] - private static extern bool DotNetAllocEncoded64(ref MarshalledImage image); - - // allocate decoded buffer based on width and height fields - [System.Security.SuppressUnmanagedCodeSecurity] - [DllImport("openjpeg-dotnet-x86_64.dll", CallingConvention = CallingConvention.Cdecl)] - private static extern bool DotNetAllocDecoded64(ref MarshalledImage image); - - // free buffers - [System.Security.SuppressUnmanagedCodeSecurity] - [DllImport("openjpeg-dotnet-x86_64.dll", CallingConvention = CallingConvention.Cdecl)] - private static extern bool DotNetFree64(ref MarshalledImage image); - - // encode raw to jpeg2000 - [System.Security.SuppressUnmanagedCodeSecurity] - [DllImport("openjpeg-dotnet-x86_64.dll", CallingConvention = CallingConvention.Cdecl)] - private static extern bool DotNetEncode64(ref MarshalledImage image, bool lossless); - - // decode jpeg2000 to raw - [System.Security.SuppressUnmanagedCodeSecurity] - [DllImport("openjpeg-dotnet-x86_64.dll", CallingConvention = CallingConvention.Cdecl)] - private static extern bool DotNetDecode64(ref MarshalledImage image); - - // decode jpeg2000 to raw, get jpeg2000 file info - [System.Security.SuppressUnmanagedCodeSecurity] - [DllImport("openjpeg-dotnet-x86_64.dll", CallingConvention = CallingConvention.Cdecl)] - private static extern bool DotNetDecodeWithInfo64(ref MarshalledImage image); - #endregion Unmanaged Function Declarations - - /// OpenJPEG is not threadsafe, so this object is used to lock - /// during calls into unmanaged code - private static object OpenJPEGLock = new object(); - - /// - /// Encode a object into a byte array - /// - /// The object to encode - /// true to enable lossless conversion, only useful for small images ie: sculptmaps - /// A byte array containing the encoded Image object public static byte[] Encode(ManagedImage image, bool lossless) { if ((image.Channels & ManagedImage.ImageChannels.Color) == 0 || ((image.Channels & ManagedImage.ImageChannels.Bump) != 0 && (image.Channels & ManagedImage.ImageChannels.Alpha) == 0)) throw new ArgumentException("JPEG2000 encoding is not supported for this channel combination"); - byte[] encoded = null; - MarshalledImage marshalled = new MarshalledImage(); - - // allocate and copy to input buffer - marshalled.width = image.Width; - marshalled.height = image.Height; - marshalled.components = 3; - if ((image.Channels & ManagedImage.ImageChannels.Alpha) != 0) marshalled.components++; - if ((image.Channels & ManagedImage.ImageChannels.Bump) != 0) marshalled.components++; - - lock (OpenJPEGLock) - { - - bool allocSuccess = (IntPtr.Size == 8) ? DotNetAllocDecoded64(ref marshalled) : DotNetAllocDecoded(ref marshalled); - - if (!allocSuccess) - throw new Exception("DotNetAllocDecoded failed"); - - int n = image.Width * image.Height; - - if ((image.Channels & ManagedImage.ImageChannels.Color) != 0) - { - Marshal.Copy(image.Red, 0, marshalled.decoded, n); - Marshal.Copy(image.Green, 0, (IntPtr)(marshalled.decoded.ToInt64() + n), n); - Marshal.Copy(image.Blue, 0, (IntPtr)(marshalled.decoded.ToInt64() + n * 2), n); - } - - if ((image.Channels & ManagedImage.ImageChannels.Alpha) != 0) Marshal.Copy(image.Alpha, 0, (IntPtr)(marshalled.decoded.ToInt64() + n * 3), n); - if ((image.Channels & ManagedImage.ImageChannels.Bump) != 0) Marshal.Copy(image.Bump, 0, (IntPtr)(marshalled.decoded.ToInt64() + n * 4), n); - - // codec will allocate output buffer - bool encodeSuccess = (IntPtr.Size == 8) ? DotNetEncode64(ref marshalled, lossless) : DotNetEncode(ref marshalled, lossless); - if (!encodeSuccess) - throw new Exception("DotNetEncode failed"); - - // copy output buffer - encoded = new byte[marshalled.length]; - Marshal.Copy(marshalled.encoded, encoded, 0, marshalled.length); - - // free buffers - if (IntPtr.Size == 8) - DotNetFree64(ref marshalled); - else - DotNetFree(ref marshalled); - } - - return encoded; + using SKBitmap bitmap = image.ExportBitmap(); + return J2kImage.ToBytes(bitmap); } - /// - /// Encode a object into a byte array - /// - /// The object to encode - /// a byte array of the encoded image public static byte[] Encode(ManagedImage image) { return Encode(image, false); } /// - /// Decode JPEG2000 data to an and - /// + /// Decode JPEG2000 data to a ManagedImage and SKBitmap. /// - /// JPEG2000 encoded data - /// ManagedImage object to decode to - /// Image object to decode to - /// True if the decode succeeds, otherwise false - public static bool DecodeToImage(byte[] encoded, out ManagedImage managedImage, out Image image) + public static bool DecodeToImage(byte[] encoded, out ManagedImage managedImage, out SKBitmap image) { managedImage = null; image = null; - if (DecodeToImage(encoded, out managedImage)) + try { - try - { - image = managedImage.ExportBitmap(); - return true; - } - catch (Exception ex) - { - Logger.Log("Failed to export and load TGA data from decoded image", Helpers.LogLevel.Error, ex); - return false; - } + var decoded = J2kImage.FromBytes(encoded); + image = decoded.As(); + managedImage = new ManagedImage(image); + return true; } - else + catch (Exception ex) { + Logger.Log("Failed to decode JPEG2000 data", Helpers.LogLevel.Error, ex); + image?.Dispose(); + image = null; + managedImage = null; return false; } } - /// - /// - /// - /// - /// - /// public static bool DecodeToImage(byte[] encoded, out ManagedImage managedImage) { - MarshalledImage marshalled = new MarshalledImage(); - - // Allocate and copy to input buffer - marshalled.length = encoded.Length; + managedImage = null; - lock (OpenJPEGLock) + try { - if (IntPtr.Size == 8) - DotNetAllocEncoded64(ref marshalled); - else - DotNetAllocEncoded(ref marshalled); - - Marshal.Copy(encoded, 0, marshalled.encoded, encoded.Length); - - // Codec will allocate output buffer - if (IntPtr.Size == 8) - DotNetDecode64(ref marshalled); - else - DotNetDecode(ref marshalled); - - int n = marshalled.width * marshalled.height; - - switch (marshalled.components) - { - case 1: // Grayscale - managedImage = new ManagedImage(marshalled.width, marshalled.height, - ManagedImage.ImageChannels.Color); - Marshal.Copy(marshalled.decoded, managedImage.Red, 0, n); - Buffer.BlockCopy(managedImage.Red, 0, managedImage.Green, 0, n); - Buffer.BlockCopy(managedImage.Red, 0, managedImage.Blue, 0, n); - break; - - case 2: // Grayscale + alpha - managedImage = new ManagedImage(marshalled.width, marshalled.height, - ManagedImage.ImageChannels.Color | ManagedImage.ImageChannels.Alpha); - Marshal.Copy(marshalled.decoded, managedImage.Red, 0, n); - Buffer.BlockCopy(managedImage.Red, 0, managedImage.Green, 0, n); - Buffer.BlockCopy(managedImage.Red, 0, managedImage.Blue, 0, n); - Marshal.Copy((IntPtr)(marshalled.decoded.ToInt64() + (long)n), managedImage.Alpha, 0, n); - break; - - case 3: // RGB - managedImage = new ManagedImage(marshalled.width, marshalled.height, - ManagedImage.ImageChannels.Color); - Marshal.Copy(marshalled.decoded, managedImage.Red, 0, n); - Marshal.Copy((IntPtr)(marshalled.decoded.ToInt64() + (long)n), managedImage.Green, 0, n); - Marshal.Copy((IntPtr)(marshalled.decoded.ToInt64() + (long)(n * 2)), managedImage.Blue, 0, n); - break; - - case 4: // RGBA - managedImage = new ManagedImage(marshalled.width, marshalled.height, - ManagedImage.ImageChannels.Color | ManagedImage.ImageChannels.Alpha); - Marshal.Copy(marshalled.decoded, managedImage.Red, 0, n); - Marshal.Copy((IntPtr)(marshalled.decoded.ToInt64() + (long)n), managedImage.Green, 0, n); - Marshal.Copy((IntPtr)(marshalled.decoded.ToInt64() + (long)(n * 2)), managedImage.Blue, 0, n); - Marshal.Copy((IntPtr)(marshalled.decoded.ToInt64() + (long)(n * 3)), managedImage.Alpha, 0, n); - break; - - case 5: // RGBAB - managedImage = new ManagedImage(marshalled.width, marshalled.height, - ManagedImage.ImageChannels.Color | ManagedImage.ImageChannels.Alpha | ManagedImage.ImageChannels.Bump); - Marshal.Copy(marshalled.decoded, managedImage.Red, 0, n); - Marshal.Copy((IntPtr)(marshalled.decoded.ToInt64() + (long)n), managedImage.Green, 0, n); - Marshal.Copy((IntPtr)(marshalled.decoded.ToInt64() + (long)(n * 2)), managedImage.Blue, 0, n); - Marshal.Copy((IntPtr)(marshalled.decoded.ToInt64() + (long)(n * 3)), managedImage.Alpha, 0, n); - Marshal.Copy((IntPtr)(marshalled.decoded.ToInt64() + (long)(n * 4)), managedImage.Bump, 0, n); - break; - - default: - Logger.Log("Decoded image with unhandled number of components: " + marshalled.components, - Helpers.LogLevel.Error); - - if (IntPtr.Size == 8) - DotNetFree64(ref marshalled); - else - DotNetFree(ref marshalled); - - managedImage = null; - return false; - } - - if (IntPtr.Size == 8) - DotNetFree64(ref marshalled); - else - DotNetFree(ref marshalled); + var decoded = J2kImage.FromBytes(encoded); + using SKBitmap image = decoded.As(); + managedImage = new ManagedImage(image); + return true; + } + catch (Exception ex) + { + Logger.Log("Failed to decode JPEG2000 data", Helpers.LogLevel.Error, ex); + managedImage = null; + return false; } - - return true; } - /// - /// - /// - /// - /// - /// - /// public static bool DecodeLayerBoundaries(byte[] encoded, out J2KLayerInfo[] layerInfo, out int components) { - bool success = false; layerInfo = null; components = 0; - MarshalledImage marshalled = new MarshalledImage(); - - // Allocate and copy to input buffer - marshalled.length = encoded.Length; - - lock (OpenJPEGLock) - { - if (IntPtr.Size == 8) - DotNetAllocEncoded64(ref marshalled); - else - DotNetAllocEncoded(ref marshalled); - - Marshal.Copy(encoded, 0, marshalled.encoded, encoded.Length); - - // Run the decode - bool decodeSuccess = (IntPtr.Size == 8) ? DotNetDecodeWithInfo64(ref marshalled) : DotNetDecodeWithInfo(ref marshalled); - if (decodeSuccess) - { - components = marshalled.components; - - // Sanity check - if (marshalled.layers * marshalled.resolutions * marshalled.components == marshalled.packet_count) - { - // Manually marshal the array of opj_packet_info structs - MarshalledPacket[] packets = new MarshalledPacket[marshalled.packet_count]; - int offset = 0; - - for (int i = 0; i < marshalled.packet_count; i++) - { - MarshalledPacket packet; - packet.start_pos = Marshal.ReadInt32(marshalled.packets, offset); - offset += 4; - packet.end_ph_pos = Marshal.ReadInt32(marshalled.packets, offset); - offset += 4; - packet.end_pos = Marshal.ReadInt32(marshalled.packets, offset); - offset += 4; - //double distortion = (double)Marshal.ReadInt64(marshalled.packets, offset); - offset += 8; - packets[i] = packet; - } - - layerInfo = new J2KLayerInfo[marshalled.layers]; - - for (int i = 0; i < marshalled.layers; i++) - { - int packetsPerLayer = marshalled.packet_count / marshalled.layers; - MarshalledPacket startPacket = packets[packetsPerLayer * i]; - MarshalledPacket endPacket = packets[(packetsPerLayer * (i + 1)) - 1]; - layerInfo[i].Start = startPacket.start_pos; - layerInfo[i].End = endPacket.end_pos; - } - - // More sanity checking - if (layerInfo.Length == 0 || layerInfo[layerInfo.Length - 1].End <= encoded.Length - 1) - { - success = true; - - for (int i = 0; i < layerInfo.Length; i++) - { - if (layerInfo[i].Start >= layerInfo[i].End || - (i > 0 && layerInfo[i].Start <= layerInfo[i - 1].End)) - { - System.Text.StringBuilder output = new System.Text.StringBuilder( - "Inconsistent packet data in JPEG2000 stream:\n"); - for (int j = 0; j < layerInfo.Length; j++) - output.AppendFormat("Layer {0}: Start: {1} End: {2}\n", j, layerInfo[j].Start, layerInfo[j].End); - Logger.DebugLog(output.ToString()); - - success = false; - break; - } - } - - if (!success) - { - for (int i = 0; i < layerInfo.Length; i++) - { - if (i < layerInfo.Length - 1) - layerInfo[i].End = layerInfo[i + 1].Start - 1; - else - layerInfo[i].End = marshalled.length; - } - - Logger.DebugLog("Corrected JPEG2000 packet data"); - success = true; - - for (int i = 0; i < layerInfo.Length; i++) - { - if (layerInfo[i].Start >= layerInfo[i].End || - (i > 0 && layerInfo[i].Start <= layerInfo[i - 1].End)) - { - System.Text.StringBuilder output = new System.Text.StringBuilder( - "Still inconsistent packet data in JPEG2000 stream, giving up:\n"); - for (int j = 0; j < layerInfo.Length; j++) - output.AppendFormat("Layer {0}: Start: {1} End: {2}\n", j, layerInfo[j].Start, layerInfo[j].End); - Logger.DebugLog(output.ToString()); - - success = false; - break; - } - } - } - } - else - { - Logger.Log(String.Format( - "Last packet end in JPEG2000 stream extends beyond the end of the file. filesize={0} layerend={1}", - encoded.Length, layerInfo[layerInfo.Length - 1].End), Helpers.LogLevel.Warning); - } - } - else - { - Logger.Log(String.Format( - "Packet count mismatch in JPEG2000 stream. layers={0} resolutions={1} components={2} packets={3}", - marshalled.layers, marshalled.resolutions, marshalled.components, marshalled.packet_count), - Helpers.LogLevel.Warning); - } - } + if (!DecodeToImage(encoded, out ManagedImage managedImage) || managedImage == null) + return false; - if (IntPtr.Size == 8) - DotNetFree64(ref marshalled); - else - DotNetFree(ref marshalled); - } + if ((managedImage.Channels & ManagedImage.ImageChannels.Color) != 0) components += 3; + if ((managedImage.Channels & ManagedImage.ImageChannels.Gray) != 0) components += 1; + if ((managedImage.Channels & ManagedImage.ImageChannels.Alpha) != 0) components += 1; + if ((managedImage.Channels & ManagedImage.ImageChannels.Bump) != 0) components += 1; - return success; + layerInfo = new J2KLayerInfo[1]; + layerInfo[0].Start = 0; + layerInfo[0].End = encoded?.Length ?? 0; + return true; } - /// - /// Encode a object into a byte array - /// - /// The source object to encode - /// true to enable lossless decoding - /// A byte array containing the source Bitmap object - public unsafe static byte[] EncodeFromImage(Bitmap bitmap, bool lossless) + public static byte[] EncodeFromImage(SKBitmap bitmap, bool lossless) { - BitmapData bd; - ManagedImage decoded; - - int bitmapWidth = bitmap.Width; - int bitmapHeight = bitmap.Height; - int pixelCount = bitmapWidth * bitmapHeight; - int i; - - if ((bitmap.PixelFormat & PixelFormat.Alpha) != 0 || (bitmap.PixelFormat & PixelFormat.PAlpha) != 0) - { - // Four layers, RGBA - decoded = new ManagedImage(bitmapWidth, bitmapHeight, - ManagedImage.ImageChannels.Color | ManagedImage.ImageChannels.Alpha); - bd = bitmap.LockBits(new Rectangle(0, 0, bitmapWidth, bitmapHeight), - ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); - byte* pixel = (byte*)bd.Scan0; - - for (i = 0; i < pixelCount; i++) - { - // GDI+ gives us BGRA and we need to turn that in to RGBA - decoded.Blue[i] = *(pixel++); - decoded.Green[i] = *(pixel++); - decoded.Red[i] = *(pixel++); - decoded.Alpha[i] = *(pixel++); - } - } - else if (bitmap.PixelFormat == PixelFormat.Format16bppGrayScale) - { - // One layer - decoded = new ManagedImage(bitmapWidth, bitmapHeight, - ManagedImage.ImageChannels.Color); - bd = bitmap.LockBits(new Rectangle(0, 0, bitmapWidth, bitmapHeight), - ImageLockMode.ReadOnly, PixelFormat.Format16bppGrayScale); - byte* pixel = (byte*)bd.Scan0; - - for (i = 0; i < pixelCount; i++) - { - // Normalize 16-bit data down to 8-bit - ushort origVal = (byte)(*(pixel) + (*(pixel + 1) << 8)); - byte val = (byte)(((double)origVal / (double)UInt32.MaxValue) * (double)Byte.MaxValue); - - decoded.Red[i] = val; - decoded.Green[i] = val; - decoded.Blue[i] = val; - pixel += 2; - } - } - else - { - // Three layers, RGB - decoded = new ManagedImage(bitmapWidth, bitmapHeight, - ManagedImage.ImageChannels.Color); - bd = bitmap.LockBits(new Rectangle(0, 0, bitmapWidth, bitmapHeight), - ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb); - byte* pixel = (byte*)bd.Scan0; - - for (i = 0; i < pixelCount; i++) - { - decoded.Blue[i] = *(pixel++); - decoded.Green[i] = *(pixel++); - decoded.Red[i] = *(pixel++); - } - } + if (bitmap == null) + throw new ArgumentNullException(nameof(bitmap)); - bitmap.UnlockBits(bd); - byte[] encoded = Encode(decoded, lossless); - return encoded; + return J2kImage.ToBytes(bitmap); } } -#endif } diff --git a/OpenMetaverse/Imaging/TGALoader.cs b/OpenMetaverse/Imaging/TGALoader.cs index c6c39839..f27e9475 100644 --- a/OpenMetaverse/Imaging/TGALoader.cs +++ b/OpenMetaverse/Imaging/TGALoader.cs @@ -25,13 +25,11 @@ */ using System; -using System.Drawing; using System.IO; +using SkiaSharp; namespace OpenMetaverse.Imaging { -#if !NO_UNSAFE - /// /// Capability to load TGAs to Bitmap /// @@ -132,6 +130,14 @@ struct tgaCD public bool NeedNoConvert; } + struct TgaBitmapData + { + public int Width; + public int Height; + public int Stride; + public IntPtr Scan0; + } + static uint UnpackColor( uint sourceColor, ref tgaCD cd) { @@ -155,7 +161,7 @@ static uint UnpackColor( } static unsafe void decodeLine( - System.Drawing.Imaging.BitmapData b, + TgaBitmapData b, int line, int byp, byte[] data, @@ -199,7 +205,7 @@ static unsafe void decodeLine( } static void decodeRle( - System.Drawing.Imaging.BitmapData b, + TgaBitmapData b, int byp, tgaCD cd, System.IO.BinaryReader br, bool bottomUp) { try @@ -264,7 +270,7 @@ static void decodeRle( } static void decodePlain( - System.Drawing.Imaging.BitmapData b, + TgaBitmapData b, int byp, tgaCD cd, System.IO.BinaryReader br, bool bottomUp) { int w = b.Width; @@ -282,7 +288,7 @@ static void decodePlain( } static void decodeStandard8( - System.Drawing.Imaging.BitmapData b, + TgaBitmapData b, tgaHeader hdr, System.IO.BinaryReader br) { @@ -303,7 +309,7 @@ static void decodeStandard8( } static void decodeSpecial16( - System.Drawing.Imaging.BitmapData b, tgaHeader hdr, System.IO.BinaryReader br) + TgaBitmapData b, tgaHeader hdr, System.IO.BinaryReader br) { // i must convert the input stream to a sequence of uint values // which I then unpack. @@ -325,7 +331,7 @@ static void decodeSpecial16( } static void decodeStandard16( - System.Drawing.Imaging.BitmapData b, + TgaBitmapData b, tgaHeader hdr, System.IO.BinaryReader br) { @@ -349,7 +355,7 @@ static void decodeStandard16( } - static void decodeSpecial24(System.Drawing.Imaging.BitmapData b, + static void decodeSpecial24(TgaBitmapData b, tgaHeader hdr, System.IO.BinaryReader br) { // i must convert the input stream to a sequence of uint values @@ -371,7 +377,7 @@ static void decodeSpecial24(System.Drawing.Imaging.BitmapData b, decodePlain(b, 3, cd, br, hdr.ImageSpec.BottomUp); } - static void decodeStandard24(System.Drawing.Imaging.BitmapData b, + static void decodeStandard24(TgaBitmapData b, tgaHeader hdr, System.IO.BinaryReader br) { // i must convert the input stream to a sequence of uint values @@ -393,7 +399,7 @@ static void decodeStandard24(System.Drawing.Imaging.BitmapData b, decodePlain(b, 3, cd, br, hdr.ImageSpec.BottomUp); } - static void decodeStandard32(System.Drawing.Imaging.BitmapData b, + static void decodeStandard32(TgaBitmapData b, tgaHeader hdr, System.IO.BinaryReader br) { // i must convert the input stream to a sequence of uint values @@ -417,7 +423,7 @@ static void decodeStandard32(System.Drawing.Imaging.BitmapData b, } - public static System.Drawing.Size GetTGASize(string filename) + public static SKSizeI GetTGASize(string filename) { System.IO.FileStream f = System.IO.File.OpenRead(filename); @@ -427,93 +433,14 @@ public static System.Drawing.Size GetTGASize(string filename) header.Read(br); br.Close(); - return new Size(header.ImageSpec.Width, header.ImageSpec.Height); + return new SKSizeI(header.ImageSpec.Width, header.ImageSpec.Height); } - public static Bitmap LoadTGA(System.IO.Stream source) + public static SKBitmap LoadTGA(System.IO.Stream source) { - byte[] buffer = new byte[source.Length]; - source.Read(buffer, 0, buffer.Length); - - using (MemoryStream ms = new MemoryStream(buffer)) - using (System.IO.BinaryReader br = new BinaryReader(ms)) - { - tgaHeader header = new tgaHeader(); - header.Read(br); - - if (header.ImageSpec.PixelDepth != 8 && - header.ImageSpec.PixelDepth != 16 && - header.ImageSpec.PixelDepth != 24 && - header.ImageSpec.PixelDepth != 32) - throw new ArgumentException("Not a supported tga file."); - - if (header.ImageSpec.AlphaBits > 8) - throw new ArgumentException("Not a supported tga file."); - - if (header.ImageSpec.Width > 4096 || - header.ImageSpec.Height > 4096) - throw new ArgumentException("Image too large."); - - System.Drawing.Bitmap b; - System.Drawing.Imaging.BitmapData bd; - - // Create a bitmap for the image. - // Only include an alpha layer when the image requires one. - if (header.ImageSpec.AlphaBits > 0 || - header.ImageSpec.PixelDepth == 8 || // Assume 8 bit images are alpha only - header.ImageSpec.PixelDepth == 32) // Assume 32 bit images are ARGB - { // Image needs an alpha layer - b = new System.Drawing.Bitmap( - header.ImageSpec.Width, - header.ImageSpec.Height, - System.Drawing.Imaging.PixelFormat.Format32bppArgb); - - bd = b.LockBits(new System.Drawing.Rectangle(0, 0, b.Width, b.Height), - System.Drawing.Imaging.ImageLockMode.WriteOnly, - System.Drawing.Imaging.PixelFormat.Format32bppPArgb); - } - else - { // Image does not need an alpha layer, so do not include one. - b = new System.Drawing.Bitmap( - header.ImageSpec.Width, - header.ImageSpec.Height, - System.Drawing.Imaging.PixelFormat.Format32bppRgb); - - bd = b.LockBits(new System.Drawing.Rectangle(0, 0, b.Width, b.Height), - System.Drawing.Imaging.ImageLockMode.WriteOnly, - System.Drawing.Imaging.PixelFormat.Format32bppRgb); - } - - switch (header.ImageSpec.PixelDepth) - { - case 8: - decodeStandard8(bd, header, br); - break; - case 16: - if (header.ImageSpec.AlphaBits > 0) - decodeSpecial16(bd, header, br); - else - decodeStandard16(bd, header, br); - break; - case 24: - if (header.ImageSpec.AlphaBits > 0) - decodeSpecial24(bd, header, br); - else - decodeStandard24(bd, header, br); - break; - case 32: - decodeStandard32(bd, header, br); - break; - default: - b.UnlockBits(bd); - b.Dispose(); - return null; - } - - b.UnlockBits(bd); - return b; - } + ManagedImage image = LoadTGAImage(source); + return image?.ExportBitmap(); } public static unsafe ManagedImage LoadTGAImage(System.IO.Stream source) @@ -546,13 +473,12 @@ public static unsafe ManagedImage LoadTGAImage(System.IO.Stream source, bool mas throw new ArgumentException("Image too large."); byte[] decoded = new byte[header.ImageSpec.Width * header.ImageSpec.Height * 4]; - System.Drawing.Imaging.BitmapData bd = new System.Drawing.Imaging.BitmapData(); + TgaBitmapData bd = new TgaBitmapData(); fixed (byte* pdecoded = &decoded[0]) { bd.Width = header.ImageSpec.Width; bd.Height = header.ImageSpec.Height; - bd.PixelFormat = System.Drawing.Imaging.PixelFormat.Format32bppPArgb; bd.Stride = header.ImageSpec.Width * 4; bd.Scan0 = (IntPtr)pdecoded; @@ -616,7 +542,7 @@ public static unsafe ManagedImage LoadTGAImage(System.IO.Stream source, bool mas } } - public static System.Drawing.Bitmap LoadTGA(string filename) + public static SKBitmap LoadTGA(string filename) { try { @@ -635,6 +561,4 @@ public static System.Drawing.Bitmap LoadTGA(string filename) } } } - -#endif } diff --git a/OpenMetaverse/ImportExport/ColladalLoader.cs b/OpenMetaverse/ImportExport/ColladalLoader.cs index 1885d846..ce4de33e 100644 --- a/OpenMetaverse/ImportExport/ColladalLoader.cs +++ b/OpenMetaverse/ImportExport/ColladalLoader.cs @@ -28,9 +28,9 @@ using OpenMetaverse.Imaging; using OpenMetaverse.ImportExport.Collada14; using OpenMetaverse.Rendering; +using SkiaSharp; using System; using System.Collections.Generic; -using System.Drawing; using System.IO; using System.Text.RegularExpressions; using System.Xml; @@ -114,7 +114,7 @@ void LoadImage(ModelMaterial material) { string ext = System.IO.Path.GetExtension(material.Texture).ToLower(); - Bitmap bitmap = null; + SKBitmap bitmap = null; if (ext == ".jp2" || ext == ".j2c") { @@ -128,9 +128,15 @@ void LoadImage(ModelMaterial material) } else { - bitmap = (Bitmap)Image.FromFile(fname); + using (var stream = File.OpenRead(fname)) + { + bitmap = SKBitmap.Decode(stream); + } } + if (bitmap == null) + throw new Exception("Failed to decode texture image"); + int width = bitmap.Width; int height = bitmap.Height; @@ -148,19 +154,15 @@ void LoadImage(ModelMaterial material) Logger.Log("Image has irregular dimensions " + origWidth + "x" + origHieght + ". Resizing to " + width + "x" + height, Helpers.LogLevel.Info); - Bitmap resized = new Bitmap(width, height, bitmap.PixelFormat); - Graphics graphics = Graphics.FromImage(resized); - - graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; - graphics.InterpolationMode = - System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; - graphics.DrawImage(bitmap, 0, 0, width, height); + SKBitmap resized = bitmap.Resize(new SKImageInfo(width, height), SKFilterQuality.High) + ?? throw new Exception("Failed to resize texture image"); bitmap.Dispose(); bitmap = resized; } material.TextureData = OpenJPEG.EncodeFromImage(bitmap, false); + bitmap.Dispose(); Logger.Log("Successfully encoded " + fname, Helpers.LogLevel.Info); } diff --git a/OpenMetaverse/Interfaces/IRendering.cs b/OpenMetaverse/Interfaces/IRendering.cs index 8af30d3c..706ac071 100644 --- a/OpenMetaverse/Interfaces/IRendering.cs +++ b/OpenMetaverse/Interfaces/IRendering.cs @@ -26,7 +26,7 @@ using System; using System.Collections.Generic; -using System.Drawing; +using SkiaSharp; namespace OpenMetaverse.Rendering { @@ -68,7 +68,7 @@ public interface IRendering /// Sculpt texture /// Level of detail to generate the mesh at /// The generated mesh - SimpleMesh GenerateSimpleSculptMesh(Primitive prim, Bitmap sculptTexture, DetailLevel lod); + SimpleMesh GenerateSimpleSculptMesh(Primitive prim, SKBitmap sculptTexture, DetailLevel lod); /// /// Generates a series of faces, each face containing a mesh and @@ -87,7 +87,7 @@ public interface IRendering /// Sculpt texture /// Level of detail to generate the mesh at /// The generated mesh - FacetedMesh GenerateFacetedSculptMesh(Primitive prim, Bitmap sculptTexture, DetailLevel lod); + FacetedMesh GenerateFacetedSculptMesh(Primitive prim, SKBitmap sculptTexture, DetailLevel lod); /// /// Apply texture coordinate modifications from a diff --git a/OpenMetaverse/Inventory.cs b/OpenMetaverse/Inventory.cs index 6bc6e01e..a7c18c82 100644 --- a/OpenMetaverse/Inventory.cs +++ b/OpenMetaverse/Inventory.cs @@ -27,7 +27,8 @@ using System; using System.Collections.Generic; using System.IO; -using System.Runtime.Serialization.Formatters.Binary; +using MessagePack; +using OpenMetaverse.StructuredData; namespace OpenMetaverse { @@ -50,6 +51,41 @@ public InventoryException(string message) /// public class Inventory { + [MessagePackObject] + private sealed class InventoryCacheEntry + { + [Key(0)] + public UUID ParentID { get; set; } + + [Key(1)] + public bool IsFolder { get; set; } + + [Key(2)] + public string Data { get; set; } + } + + private static InventoryCacheEntry SerializeInventoryNode(InventoryNode node) + { + InventoryBase data = node.Data; + return new InventoryCacheEntry + { + ParentID = data.ParentUUID, + IsFolder = data is InventoryFolder, + Data = OSDParser.SerializeLLSDXmlString(data.GetOSD()) + }; + } + + private static InventoryNode DeserializeInventoryNode(InventoryCacheEntry cacheNode) + { + OSD osd = OSDParser.DeserializeLLSDXml(cacheNode.Data); + InventoryBase data = cacheNode.IsFolder + ? (InventoryBase)InventoryFolder.FromOSD(osd) + : (InventoryBase)InventoryItem.FromOSD(osd); + + data.ParentUUID = cacheNode.ParentID; + return new InventoryNode(data); + } + /// The event subscribers, null of no subscribers private EventHandler m_InventoryObjectUpdated; @@ -187,7 +223,7 @@ public Inventory(GridClient client, InventoryManager manager, UUID owner) Client = client; //Manager = manager; _Owner = owner; - if (owner == UUID.Zero) + if (owner.IsZero()) Logger.Log("Inventory owned by nobody!", Helpers.LogLevel.Warning, Client); Items = new Dictionary(); } @@ -357,14 +393,17 @@ public void SaveToDisk(string filename) { using (Stream stream = File.Open(filename, FileMode.Create)) { - BinaryFormatter bformatter = new BinaryFormatter(); lock (Items) { Logger.Log("Caching " + Items.Count.ToString() + " inventory items to " + filename, Helpers.LogLevel.Info); + List cacheNodes = new List(Items.Count); + foreach (KeyValuePair kvp in Items) { - bformatter.Serialize(stream, kvp.Value); + cacheNodes.Add(SerializeInventoryNode(kvp.Value)); } + + MessagePackSerializer.Serialize(stream, cacheNodes); } } } @@ -391,13 +430,15 @@ public int RestoreFromDisk(string filename) using (Stream stream = File.Open(filename, FileMode.Open)) { - BinaryFormatter bformatter = new BinaryFormatter(); - - while (stream.Position < stream.Length) + List cacheNodes = MessagePackSerializer.Deserialize>(stream); + if (cacheNodes != null) { - OpenMetaverse.InventoryNode node = (InventoryNode)bformatter.Deserialize(stream); - nodes.Add(node); - item_count++; + foreach (InventoryCacheEntry cacheNode in cacheNodes) + { + OpenMetaverse.InventoryNode node = DeserializeInventoryNode(cacheNode); + nodes.Add(node); + item_count++; + } } } } @@ -423,7 +464,8 @@ public int RestoreFromDisk(string filename) foreach (InventoryNode node in nodes) { InventoryNode pnode; - if (node.ParentID == UUID.Zero) + UUID parentID = (node.Data != null) ? node.Data.ParentUUID : UUID.Zero; + if (parentID.IsZero()) { //We don't need the root nodes "My Inventory" etc as they will already exist for the correct // user of this cache. @@ -452,7 +494,7 @@ public int RestoreFromDisk(string filename) del_nodes.Add(node); } } - else if (Items.TryGetValue(node.ParentID, out pnode)) + else if (Items.TryGetValue(parentID, out pnode)) { if (node.Data != null) { diff --git a/OpenMetaverse/InventoryManager.cs b/OpenMetaverse/InventoryManager.cs index 94e4a41b..8683357f 100644 --- a/OpenMetaverse/InventoryManager.cs +++ b/OpenMetaverse/InventoryManager.cs @@ -139,7 +139,7 @@ public abstract class InventoryBase : ISerializable /// The of the item public InventoryBase(UUID itemID) { - if (itemID == UUID.Zero) + if (itemID.IsZero()) Logger.Log("Initializing an InventoryBase with UUID.Zero", Helpers.LogLevel.Warning); UUID = itemID; } @@ -4595,7 +4595,7 @@ protected void UpdateCreateInventoryItemHandler(object sender, PacketReceivedEve * to the client to make sure that the item gets a good folder, otherwise * it will end up inaccesible in inventory. */ - if (item.ParentUUID == UUID.Zero) + if (item.ParentUUID.IsZero()) { // assign default folder for type item.ParentUUID = FindFolderForType(item.AssetType); @@ -4667,7 +4667,7 @@ protected void BulkUpdateInventoryCapHandler(string capsKey, Interfaces.IMessage foreach (BulkUpdateInventoryMessage.FolderDataInfo newFolder in msg.FolderData) { - if (newFolder.FolderID == UUID.Zero) continue; + if (newFolder.FolderID.IsZero()) continue; InventoryFolder folder; if (!_Store.Contains(newFolder.FolderID)) @@ -4687,7 +4687,7 @@ protected void BulkUpdateInventoryCapHandler(string capsKey, Interfaces.IMessage foreach (BulkUpdateInventoryMessage.ItemDataInfo newItem in msg.ItemData) { - if (newItem.ItemID == UUID.Zero) continue; + if (newItem.ItemID.IsZero()) continue; InventoryType invType = newItem.InvType; lock (_ItemInventoryTypeRequest) diff --git a/OpenMetaverse/Login.cs b/OpenMetaverse/Login.cs index 43d33fb3..e9b61859 100644 --- a/OpenMetaverse/Login.cs +++ b/OpenMetaverse/Login.cs @@ -32,7 +32,8 @@ using System.Collections; using System.Collections.Generic; using System.Net; -using System.Threading; +using System.Net.Security; +using System.Security.Cryptography.X509Certificates; namespace OpenMetaverse { @@ -1060,6 +1061,23 @@ public void AbortLogin() #endregion #region Private Methods + public static bool ValidateServerCertificate( + object sender, + X509Certificate certificate, + X509Chain chain, + SslPolicyErrors sslPolicyErrors) + { + //if (m_NoVerifyCertChain) + sslPolicyErrors &= ~SslPolicyErrors.RemoteCertificateChainErrors; + + //if (m_NoVerifyCertHostname) + sslPolicyErrors &= ~SslPolicyErrors.RemoteCertificateNameMismatch; + + if (sslPolicyErrors == SslPolicyErrors.None) + return true; + + return false; + } private void BeginLogin() { @@ -1109,7 +1127,7 @@ private void BeginLogin() #endregion - ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true; + ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertificate; if (Client.Settings.USE_LLSD_LOGIN) { diff --git a/OpenMetaverse/Messages/LindenMessages.cs b/OpenMetaverse/Messages/LindenMessages.cs index 056096c7..4a5363ec 100644 --- a/OpenMetaverse/Messages/LindenMessages.cs +++ b/OpenMetaverse/Messages/LindenMessages.cs @@ -24,12 +24,12 @@ * POSSIBILITY OF SUCH DAMAGE. */ -using ComponentAce.Compression.Libs.zlib; using OpenMetaverse.Interfaces; using OpenMetaverse.StructuredData; using System; using System.Collections.Generic; using System.IO; +using System.IO.Compression; using System.Net; namespace OpenMetaverse.Messages.Linden @@ -1813,6 +1813,76 @@ public OSDMap Serialize() } + public class LargeGenericMessage : IMessage + { + private OSDMap RawData; + public UUID AgentID; + public UUID SessionID; + public UUID TransactionID; + + public string Method; + public UUID Invoice; + + public class Parameter + { + public string value; + } + + public Parameter[] Parameters; + + public void Deserialize(OSDMap map) + { + RawData = map; + OSD osdtmp, osdtmp2; + if (map.TryGetValue("AgentData", out osdtmp)) + { + if (osdtmp is OSDArray agdArray && agdArray.Count > 0) + { + if (agdArray[0] is OSDMap agdMap) + { + if (agdMap.TryGetValue("AgentID", out osdtmp2)) + AgentID = osdtmp2.AsUUID(); + if (agdMap.TryGetValue("SessionID", out osdtmp2)) + SessionID = osdtmp2.AsUUID(); + if (agdMap.TryGetValue("TransactionID", out osdtmp2)) + TransactionID = osdtmp2.AsUUID(); + } + } + } + if (map.TryGetValue("MethodData", out osdtmp)) + { + if (osdtmp is OSDArray mdArray && mdArray.Count > 0) + { + if (mdArray[0] is OSDMap mdMap) + { + if (mdMap.TryGetValue("Method", out osdtmp2)) + Method = osdtmp2.AsString(); + if (mdMap.TryGetValue("Invoice", out osdtmp2)) + Invoice = osdtmp2.AsUUID(); + } + } + } + if (map.TryGetValue("ParamList", out osdtmp)) + { + if (osdtmp is OSDArray pArray && pArray.Count > 0) + { + Parameters = new Parameter[pArray.Count]; + for(int i = 0; i < Parameters.Length; i++) + { + Parameters[i] = new Parameter(){value = pArray[i].ToString() }; + } + } + } + + Method ??="MissingMethod"; + } + + public OSDMap Serialize() + { + return RawData; + } + } + /// Base class for Asset uploads/results via Capabilities public abstract class AssetUploaderBlock { @@ -4434,15 +4504,9 @@ public void Deserialize(OSDMap map) { using (MemoryStream output = new MemoryStream()) { - using (ZOutputStream zout = new ZOutputStream(output)) + using (ZLibStream zStream = new ZLibStream(input, CompressionMode.Decompress)) { - byte[] buffer = new byte[2048]; - int len; - while ((len = input.Read(buffer, 0, buffer.Length)) > 0) - { - zout.Write(buffer, 0, len); - } - zout.Flush(); + Helpers.CopyStream(zStream, output); output.Seek(0, SeekOrigin.Begin); MaterialData = OSDParser.DeserializeLLSDBinary(output); } @@ -4469,6 +4533,7 @@ public OSDMap Serialize() public class GetObjectCostRequest : IMessage { /// Object IDs for which to request cost information + /// public UUID[] ObjectIDs; /// diff --git a/OpenMetaverse/Messages/MessageEventDecoder.cs b/OpenMetaverse/Messages/MessageEventDecoder.cs index 063b899c..cb9321ab 100644 --- a/OpenMetaverse/Messages/MessageEventDecoder.cs +++ b/OpenMetaverse/Messages/MessageEventDecoder.cs @@ -101,6 +101,7 @@ public static IMessage DecodeEvent(string eventName, OSDMap map) case "BulkUpdateInventory": message = new BulkUpdateInventoryMessage(); break; case "RenderMaterials": message = new RenderMaterialsMessage(); break; case "GetObjectCost": message = GetObjectCostMessage.GetMessageHandler(map); break; + case "LargeGenericMessage": message = new LargeGenericMessage(); break; // Capabilities TODO: // DispatchRegionInfo diff --git a/OpenMetaverse/ObjectPool.cs b/OpenMetaverse/ObjectPool.cs index cc8a6560..4269e737 100644 --- a/OpenMetaverse/ObjectPool.cs +++ b/OpenMetaverse/ObjectPool.cs @@ -20,7 +20,7 @@ public class UDPPacketBuffer /// public UDPPacketBuffer() { - Data = new byte[UDPPacketBuffer.BUFFER_SIZE]; + Data = GC.AllocateUninitializedArray(BUFFER_SIZE); // Will be modified later by BeginReceiveFrom() RemoteEndPoint = new IPEndPoint(Settings.BIND_ADDR, 0); } @@ -31,7 +31,7 @@ public UDPPacketBuffer() /// EndPoint of the remote host public UDPPacketBuffer(IPEndPoint endPoint) { - Data = new byte[UDPPacketBuffer.BUFFER_SIZE]; + Data = GC.AllocateUninitializedArray(BUFFER_SIZE); RemoteEndPoint = endPoint; } diff --git a/OpenMetaverse/OpenMetaverse.csproj b/OpenMetaverse/OpenMetaverse.csproj index c461f644..ada947fa 100644 --- a/OpenMetaverse/OpenMetaverse.csproj +++ b/OpenMetaverse/OpenMetaverse.csproj @@ -1,27 +1,23 @@  Local - net48 + Library + OpenMetaverse + Client library for OpenMetaverse-compatible virtual world servers such as OpenSimulator. Provides login, inventory, asset, object, and messaging APIs. OpenMetaverse - 1591,1574,0419,0618 True true - - + + + + + - - ..\bin\SmartThreadPool.dll - False - - ..\bin\XMLRPC.dll - False - - - ..\bin\zlib.net.dll + ..\AppData\XMLRPC.dll False diff --git a/OpenMetaverse/PacketDecoder.cs b/OpenMetaverse/PacketDecoder.cs index 87f4ec89..ed95193e 100644 --- a/OpenMetaverse/PacketDecoder.cs +++ b/OpenMetaverse/PacketDecoder.cs @@ -1,1926 +1,1951 @@ -/* - * Copyright (c) 2006-2016, openmetaverse.co - * All rights reserved. - * - * - Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, this - * list of conditions and the following disclaimer. - * - Neither the name of the openmetaverse.co nor the names - * of its contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections.Generic; -using System.Reflection; -using System.Text; - -namespace OpenMetaverse.Packets -{ - - public static class PacketDecoder - { - /// - /// A custom decoder callback - /// - /// The key of the object - /// the data to decode - /// A string represending the fieldData - public delegate string CustomPacketDecoder(string fieldName, object fieldData); - - private static Dictionary> Callbacks = new Dictionary>(); - - - static PacketDecoder() - { - AddCallback("Color", DecodeColorField); - AddCallback("TextColor", DecodeColorField); - AddCallback("Timestamp", DecodeTimeStamp); - AddCallback("EstateCovenantReply.Data.CovenantTimestamp", DecodeTimeStamp); - AddCallback("CreationDate", DecodeTimeStamp); - AddCallback("BinaryBucket", DecodeBinaryBucket); - AddCallback("ParcelData.Data", DecodeBinaryToHexString); - AddCallback("LayerData.Data", DecodeBinaryToHexString); - AddCallback("ImageData.Data", DecodeImageData); - AddCallback("TransferData.Data", DecodeBinaryToHexString); - AddCallback("ObjectData.TextureEntry", DecodeTextureEntry); - AddCallback("ImprovedInstantMessage.MessageBlock.Dialog", DecodeDialog); - - // Inventory/Permissions - AddCallback("BaseMask", DecodePermissionMask); - AddCallback("OwnerMask", DecodePermissionMask); - AddCallback("EveryoneMask", DecodePermissionMask); - AddCallback("NextOwnerMask", DecodePermissionMask); - AddCallback("GroupMask", DecodePermissionMask); - - // FetchInventoryDescendents - AddCallback("InventoryData.SortOrder", DecodeInventorySort); - - AddCallback("WearableType", DecodeWearableType); - // - AddCallback("InventoryData.Type", DecodeInventoryType); - AddCallback("InvType", DecodeInventoryInvType); - AddCallback("InventoryData.Flags", DecodeInventoryFlags); - // BulkUpdateInventory - AddCallback("ItemData.Type", DecodeInventoryType); - AddCallback("ItemData.Flags", DecodeInventoryFlags); - - AddCallback("SaleType", DecodeObjectSaleType); - - AddCallback("ScriptControlChange.Data.Controls", DecodeScriptControls); - - AddCallback("RegionFlags", DecodeRegionFlags); - AddCallback("SimAccess", DecodeSimAccess); - AddCallback("ControlFlags", DecodeControlFlags); - - // AgentUpdate - AddCallback("AgentUpdate.AgentData.State", DecodeAgentState); - AddCallback("AgentUpdate.AgentData.Flags", DecodeAgentFlags); - - // ViewerEffect TypeData - AddCallback("ViewerEffect.Effect.TypeData", DecodeViewerEffectTypeData); - AddCallback("ViewerEffect.Effect.Type", DecodeViewerEffectType); - - // Prim/ObjectUpdate decoders - AddCallback("ObjectUpdate.ObjectData.PCode", DecodeObjectPCode); - AddCallback("ObjectUpdate.ObjectData.Material", DecodeObjectMaterial); - AddCallback("ObjectUpdate.ObjectData.ClickAction", DecodeObjectClickAction); - AddCallback("ObjectData.UpdateFlags", DecodeObjectUpdateFlags); - - AddCallback("ObjectUpdate.ObjectData.ObjectData", DecodeObjectData); - AddCallback("TextureAnim", DecodeObjectTextureAnim); - AddCallback("ObjectUpdate.ObjectData.NameValue", DecodeNameValue); - AddCallback("ObjectUpdate.ObjectData.Data", DecodeObjectData); - - AddCallback("ObjectUpdate.ObjectData.PSBlock", DecodeObjectParticleSystem); - AddCallback("ParticleSys", DecodeObjectParticleSystem); - AddCallback("ObjectUpdate.ObjectData.ExtraParams", DecodeObjectExtraParams); - - AddCallback("ImprovedTerseObjectUpdate.ObjectData.Data", DecodeTerseUpdate); - AddCallback("ImprovedTerseObjectUpdate.ObjectData.TextureEntry", DecodeTerseTextureEntry); - - AddCallback("ObjectUpdateCompressed.ObjectData.Data", DecodeObjectCompressedData); - - // ImprovedTerseObjectUpdate & ObjectUpdate AttachmentPoint & ObjectUpdateCompressed - AddCallback("ObjectData.State", DecodeObjectState); - //AddCallback("ObjectUpdateCompressed.ObjectData.State", DecodeObjectState); - //AddCallback("ImprovedTerseObjectUpdate.ObjectData.State", DecodeObjectState); - - - // ChatFromSimulator - AddCallback("ChatData.SourceType", DecodeChatSourceType); - AddCallback("ChatData.ChatType", DecodeChatChatType); - AddCallback("ChatData.Audible", DecodeChatAudible); - AddCallback("AttachedSound.DataBlock.Flags", DecodeAttachedSoundFlags); - - AddCallback("RequestImage.Type", DecodeImageType); - - AddCallback("EstateOwnerMessage.ParamList.Parameter", DecodeEstateParameter); - - AddCallback("Codec", DecodeImageCodec); - AddCallback("Info.TeleportFlags", DecodeTeleportFlags); - - // map - AddCallback("MapBlockRequest.AgentData.Flags", DecodeMapRequestFlags); - AddCallback("MapItemRequest.AgentData.Flags", DecodeMapRequestFlags); - AddCallback("MapBlockReply.Data.Access", DecodeMapAccess); - AddCallback("FolderData.Type", DecodeFolderType); - AddCallback("RequestData.ItemType", DecodeGridItemType); - - // TransferRequest/TransferInfo - AddCallback("TransferInfo.Params", DecodeTransferParams); - AddCallback("TransferInfo.ChannelType", DecodeTransferChannelType); - AddCallback("TransferInfo.SourceType", DecodeTransferSourceType); - AddCallback("TransferInfo.TargetType", DecodeTransferTargetType); - AddCallback("TransferData.ChannelType", DecodeTransferChannelType); - // SendXferPacket - AddCallback("DataPacket.Data", DecodeBinaryToHexString); - // Directory Manager - AddCallback("DirClassifiedQuery.QueryData.QueryFlags", DecodeDirClassifiedQueryFlags); - AddCallback("QueryData.QueryFlags", DecodeDirQueryFlags); - AddCallback("Category", DecodeCategory); - AddCallback("QueryData.SearchType", SearchTypeFlags); - - AddCallback("ClassifiedFlags", DecodeDirClassifiedFlags); - AddCallback("EventFlags", DecodeEventFlags); - - AddCallback("ParcelAccessListRequest.Data.Flags", DecodeParcelACL); - AddCallback("ParcelAccessListReply.Data.Flags", DecodeParcelACL); - //AddCallback("ParcelAccessListReply.List.Flags", DecodeParcelACLReply); - - // AgentAnimation - AddCallback("AnimID", DecodeAnimToConst); - - AddCallback("LayerData.LayerID.Type", DecodeLayerDataType); - - AddCallback("GroupPowers", DecodeGroupPowers); - } - - /// - /// Add a custom decoder callback - /// - /// The key of the field to decode - /// The custom decode handler - public static void AddCallback(string key, CustomPacketDecoder customPacketHandler) - { - if (Callbacks.ContainsKey(key)) - { - lock (Callbacks) - Callbacks[key].Add(customPacketHandler); - } - else - { - lock (Callbacks) - Callbacks.Add(key, new List() { customPacketHandler }); - } - } - - /// - /// Remove a custom decoder callback - /// - /// The key of the field to decode - /// The custom decode handler - public static void RemoveCustomHandler(string key, CustomPacketDecoder customPacketHandler) - { - if (Callbacks.ContainsKey(key)) - lock (Callbacks) - { - if (Callbacks[key].Contains(customPacketHandler)) - Callbacks[key].Remove(customPacketHandler); - } - } - - #region Custom Decoders - - private static string DecodeTerseUpdate(string fieldName, object fieldData) - { - byte[] block = (byte[])fieldData; - int i = 4; - - StringBuilder result = new StringBuilder(); - - // LocalID - result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, - "LocalID", - Utils.BytesToUInt(block, 0), - "Uint32"); - - - - // State - byte point = block[i++]; - result.AppendFormat("{0,30}: {1,-3} {2,-36} [{3}]" + Environment.NewLine, - "State", - point, - "(" + (AttachmentPoint)point + ")", - "AttachmentPoint"); - - // Avatar boolean - bool isAvatar = (block[i++] != 0); - result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, - "IsAvatar", - isAvatar, - "Boolean"); - - // Collision normal for avatar - if (isAvatar) - { - result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, - "CollisionPlane", - new Vector4(block, i), - "Vector4"); - - i += 16; - } - - // Position - result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, - "Position", - new Vector3(block, i), - "Vector3"); - i += 12; - - // Velocity - result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, - "Velocity", - new Vector3( - Utils.BytesUInt16ToFloat(block, i, -128.0f, 128.0f), - Utils.BytesUInt16ToFloat(block, i + 2, -128.0f, 128.0f), - Utils.BytesUInt16ToFloat(block, i + 4, -128.0f, 128.0f)), - "Vector3"); - i += 6; - - // Acceleration - result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, - "Acceleration", - new Vector3( - Utils.BytesUInt16ToFloat(block, i, -64.0f, 64.0f), - Utils.BytesUInt16ToFloat(block, i + 2, -64.0f, 64.0f), - Utils.BytesUInt16ToFloat(block, i + 4, -64.0f, 64.0f)), - "Vector3"); - - i += 6; - // Rotation (theta) - result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, - "Rotation", - new Quaternion( - Utils.BytesUInt16ToFloat(block, i, -1.0f, 1.0f), - Utils.BytesUInt16ToFloat(block, i + 2, -1.0f, 1.0f), - Utils.BytesUInt16ToFloat(block, i + 4, -1.0f, 1.0f), - Utils.BytesUInt16ToFloat(block, i + 6, -1.0f, 1.0f)), - "Quaternion"); - i += 8; - // Angular velocity (omega) - result.AppendFormat("{0,30}: {1,-40} [{2}]", - "AngularVelocity", - new Vector3( - Utils.BytesUInt16ToFloat(block, i, -64.0f, 64.0f), - Utils.BytesUInt16ToFloat(block, i + 2, -64.0f, 64.0f), - Utils.BytesUInt16ToFloat(block, i + 4, -64.0f, 64.0f)), - "Vector3"); - //pos += 6; - // TODO: What is in these 6 bytes? - return result.ToString(); - } - - private static string DecodeObjectCompressedData(string fieldName, object fieldData) - { - StringBuilder result = new StringBuilder(); - byte[] block = (byte[])fieldData; - int i = 0; - - // UUID - result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, - "ID", - new UUID(block, 0), - "UUID"); - i += 16; - - // Local ID - uint LocalID = (uint)(block[i++] + (block[i++] << 8) + - (block[i++] << 16) + (block[i++] << 24)); - - result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, - "LocalID", - LocalID, - "Uint32"); - // PCode - PCode pcode = (PCode)block[i++]; - - result.AppendFormat("{0,30}: {1,-3} {2,-36} [{3}]" + Environment.NewLine, - "PCode", - (int)pcode, - "(" + pcode + ")", - "PCode"); - - // State - AttachmentPoint point = (AttachmentPoint)block[i++]; - result.AppendFormat("{0,30}: {1,-3} {2,-36} [{3}]" + Environment.NewLine, - "State", - (byte)point, - "(" + point + ")", - "AttachmentPoint"); - - //CRC - result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, - "CRC", - Utils.BytesToUInt(block, i), - "UInt"); - i += 4; - - // Material - result.AppendFormat("{0,30}: {1,-3} {2,-36} [{3}]" + Environment.NewLine, - "Material", - block[i], - "(" + (Material)block[i++] + ")", - "Material"); - - // Click action - result.AppendFormat("{0,30}: {1,-3} {2,-36} [{3}]" + Environment.NewLine, - "ClickAction", - block[i], - "(" + (ClickAction)block[i++] + ")", - "ClickAction"); - - // Scale - result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, - "Scale", - new Vector3(block, i), - "Vector3"); - i += 12; - - // Position - result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, - "Position", - new Vector3(block, i), - "Vector3"); - i += 12; - - // Rotation - result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, - "Rotation", - new Vector3(block, i), - "Vector3"); - - i += 12; - // Compressed flags - - CompressedFlags flags = (CompressedFlags)Utils.BytesToUInt(block, i); - result.AppendFormat("{0,30}: {1,-10} {2,-29} [{3}]" + Environment.NewLine, - "CompressedFlags", - Utils.BytesToUInt(block, i), - "(" + (CompressedFlags)Utils.BytesToUInt(block, i) + ")", - "UInt"); - i += 4; - - // Owners ID - result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, - "OwnerID", - new UUID(block, i), - "UUID"); - i += 16; - - // Angular velocity - if ((flags & CompressedFlags.HasAngularVelocity) != 0) - { - result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, - "AngularVelocity", - new Vector3(block, i), - "Vector3"); - i += 12; - } - - // Parent ID - if ((flags & CompressedFlags.HasParent) != 0) - { - result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, - "ParentID", - (uint)(block[i++] + (block[i++] << 8) + - (block[i++] << 16) + (block[i++] << 24)), - "UInt"); - } - - // Tree data - if ((flags & CompressedFlags.Tree) != 0) - { - result.AppendFormat("{0,30}: {1,-2} {2,-37} [{3}]" + Environment.NewLine, - "TreeSpecies", - block[i++], - "(" + (Tree)block[i] + ")", - "Tree"); - } - - // Scratch pad - else if ((flags & CompressedFlags.ScratchPad) != 0) - { - int size = block[i++]; - byte[] scratch = new byte[size]; - Buffer.BlockCopy(block, i, scratch, 0, size); - result.AppendFormat("{0,30}: {1,-40} [ScratchPad[]]" + Environment.NewLine, - "ScratchPad", - Utils.BytesToHexString(scratch, String.Format("{0,30}", "Data"))); - i += size; - } - - // Floating text - if ((flags & CompressedFlags.HasText) != 0) - { - string text = String.Empty; - while (block[i] != 0) - { - text += (char)block[i]; - i++; - } - i++; - - // Floating text - result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, - "Text", - text, - "string"); - - // Text color - result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, - "TextColor", - new Color4(block, i, false), - "Color4"); - i += 4; - } - - // Media URL - if ((flags & CompressedFlags.MediaURL) != 0) - { - string text = String.Empty; - while (block[i] != 0) - { - text += (char)block[i]; - i++; - } - i++; - - result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, - "MediaURL", - text, - "string"); - } - - // Particle system - if ((flags & CompressedFlags.HasParticles) != 0) - { - Primitive.ParticleSystem p = new Primitive.ParticleSystem(block, i); - result.AppendLine(DecodeObjectParticleSystem("ParticleSystem", p)); - i += 86; - } - - // Extra parameters TODO: - Primitive prim = new Primitive(); - int extrapLen = prim.SetExtraParamsFromBytes(block, i); - i += extrapLen; - result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, - "ExtraParams[]", - extrapLen, - "byte[]"); - - //Sound data - if ((flags & CompressedFlags.HasSound) != 0) - { - result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, - "SoundID", - new UUID(block, i), - "UUID"); - i += 16; - - result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, - "SoundGain", - Utils.BytesToFloat(block, i), - "Float"); - i += 4; - - result.AppendFormat("{0,30}: {1,-2} {2,-37} [{3}]" + Environment.NewLine, - "SoundFlags", - block[i++], - "(" + (SoundFlags)block[i] + ")", - "SoundFlags"); - - result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, - "SoundRadius", - Utils.BytesToFloat(block, i), - "Float"); - i += 4; - } - - // Name values - if ((flags & CompressedFlags.HasNameValues) != 0) - { - string text = String.Empty; - while (block[i] != 0) - { - text += (char)block[i]; - i++; - } - i++; - - // Parse the name values - if (text.Length > 0) - { - string[] lines = text.Split('\n'); - NameValue[] nameValues = new NameValue[lines.Length]; - - for (int j = 0; j < lines.Length; j++) - { - if (!String.IsNullOrEmpty(lines[j])) - { - NameValue nv = new NameValue(lines[j]); - nameValues[j] = nv; - } - } - result.AppendLine(DecodeNameValue("NameValues", nameValues)); - } - } - - result.AppendFormat("{0,30}: {1,-2} {2,-37} [{3}]" + Environment.NewLine, - "PathCurve", - block[i], - "(" + (PathCurve)block[i++] + ")", - "PathCurve"); - - ushort pathBegin = Utils.BytesToUInt16(block, i); - i += 2; - result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, - "PathBegin", - Primitive.UnpackBeginCut(pathBegin), - "float"); - - ushort pathEnd = Utils.BytesToUInt16(block, i); - i += 2; - result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, - "PathEnd", - Primitive.UnpackEndCut(pathEnd), - "float"); - - result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, - "PathScaleX", - Primitive.UnpackPathScale(block[i++]), - "float"); - - result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, - "PathScaleY", - Primitive.UnpackPathScale(block[i++]), - "float"); - - result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, - "PathShearX", - Primitive.UnpackPathShear((sbyte)block[i++]), - "float"); - - result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, - "PathShearY", - Primitive.UnpackPathShear((sbyte)block[i++]), - "float"); - - result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, - "PathTwist", - Primitive.UnpackPathTwist((sbyte)block[i++]), - "float"); - - result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, - "PathTwistBegin", - Primitive.UnpackPathTwist((sbyte)block[i++]), - "float"); - - result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, - "PathRadiusOffset", - Primitive.UnpackPathTwist((sbyte)block[i++]), - "float"); - - result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, - "PathTaperX", - Primitive.UnpackPathTaper((sbyte)block[i++]), - "float"); - - result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, - "PathTaperY", - Primitive.UnpackPathTaper((sbyte)block[i++]), - "float"); - - result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, - "PathRevolutions", - Primitive.UnpackPathRevolutions(block[i++]), - "float"); - - result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, - "PathSkew", - Primitive.UnpackPathTwist((sbyte)block[i++]), - "float"); - - result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, - "ProfileCurve", - block[i++], - "float"); - - ushort profileBegin = Utils.BytesToUInt16(block, i); - i += 2; - result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, - "ProfileBegin", - Primitive.UnpackBeginCut(profileBegin), - "float"); - - ushort profileEnd = Utils.BytesToUInt16(block, i); - i += 2; - result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, - "ProfileEnd", - Primitive.UnpackEndCut(profileEnd), - "float"); - - ushort profileHollow = Utils.BytesToUInt16(block, i); - i += 2; - result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, - "ProfileHollow", - Primitive.UnpackProfileHollow(profileHollow), - "float"); - - int textureEntryLength = (int)Utils.BytesToUInt(block, i); - i += 4; - //prim.Textures = new Primitive.TextureEntry(block, i, textureEntryLength); - String s = DecodeTextureEntry("TextureEntry", new Primitive.TextureEntry(block, i, textureEntryLength)); - result.AppendLine(s); - i += textureEntryLength; - - // Texture animation - if ((flags & CompressedFlags.TextureAnimation) != 0) - { - i += 4; - string a = DecodeObjectTextureAnim("TextureAnimation", new Primitive.TextureAnimation(block, i)); - result.AppendLine(a); - } - - if ((flags & CompressedFlags.HasParticlesNew) != 0) - { - Primitive.ParticleSystem p = new Primitive.ParticleSystem(block, i); - result.AppendLine(DecodeObjectParticleSystem("ParticleSystemNEW", p)); - i += 94; - if ((p.PartDataFlags & Primitive.ParticleSystem.ParticleDataFlags.DataGlow) != 0) - i += 2; - if ((p.PartDataFlags & Primitive.ParticleSystem.ParticleDataFlags.DataBlend) != 0) - i += 2; - } - - return result.ToString(); - } - - private static string DecodeObjectData(string fieldName, object fieldData) - { - byte[] data = (byte[])fieldData; - if (data.Length == 1) - { - return String.Format("{0,30}: {1,2} {2,-38} [{3}]", - fieldName + " (Tree Species)", - fieldData, - //"(" + (Tree)(byte)fieldData + ")", - "(" + (Tree)data[0] + ")", - fieldData.GetType().Name); - } - else if (data.Length == 76) - { - /* TODO: these are likely useful packed fields, - * need to unpack them */ - Vector4 col = Vector4.Zero; - Vector3 offset = Vector3.Zero; - Vector3 vel = Vector3.Zero; - Vector3 acc = Vector3.Zero; - Quaternion q = Quaternion.Identity; - Vector3 angvel = Vector3.Zero; - - col.FromBytes(data, 0); - offset.FromBytes(data, 16); - vel.FromBytes(data, 28); - acc.FromBytes(data, 40); - q.FromBytes(data, 52, true); - angvel.FromBytes(data, 64); - - StringBuilder result = new StringBuilder(); - result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, - "ColisionPlane", - col, - "Vector4"); - result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, - "Offset", - offset, - "Vector3"); - result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, - "Velocity", - vel, - "Vector3"); - result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, - "Acceleration", - acc, - "Vector3"); - result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, - "rotation", - q, - "Quaternion"); - result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, - "Omega", - angvel, - "Vector3"); - return result.ToString(); - } - else if (data.Length == 60) - { - /* TODO: these are likely useful packed fields, - * need to unpack them */ - Vector3 offset = Vector3.Zero; - Vector3 vel = Vector3.Zero; - Vector3 acc = Vector3.Zero; - Quaternion q = Quaternion.Identity; - Vector3 angvel = Vector3.Zero; - - offset.FromBytes(data, 0); - vel.FromBytes(data, 12); - acc.FromBytes(data, 24); - q.FromBytes(data, 36, true); - angvel.FromBytes(data, 48); - - StringBuilder result = new StringBuilder(); - result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, - "Offset", - offset, - "Vector3"); - result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, - "Velocity", - vel, - "Vector3"); - result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, - "Acceleration", - acc, - "Vector3"); - result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, - "rotation", - q, - "Quaternion"); - result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, - "Omega", - angvel, - "Vector3"); - return result.ToString(); - } - else - { - return Utils.BytesToHexString((byte[])fieldData, String.Format("{0,30}", fieldName)); - } - } - - private static string DecodeObjectTextureAnim(string fieldName, object fieldData) - { - StringBuilder result = new StringBuilder(); - Primitive.TextureAnimation TextureAnim; - if (fieldData is Primitive.TextureAnimation) - TextureAnim = (Primitive.TextureAnimation)fieldData; - else - TextureAnim = new Primitive.TextureAnimation((byte[])fieldData, 0); - - result.AppendFormat("{0,30}", " " + Environment.NewLine); - GenericTypeDecoder(TextureAnim, ref result); - result.AppendFormat("{0,30}", ""); - - return result.ToString(); - } - - private static string DecodeEstateParameter(string fieldName, object fieldData) - { - byte[] bytes = (byte[])fieldData; - - if (bytes.Length == 17) - { - return String.Format("{0,30}: {1,-40} [UUID]", fieldName, new UUID((byte[])fieldData, 0)); - } - else - { - return String.Format("{0,30}: {1,-40} [Byte[]]", fieldName, Utils.BytesToString((byte[])fieldData)); - } - } - - private static string DecodeNameValue(string fieldName, object fieldData) - { - NameValue[] nameValues = null; - if (fieldData is NameValue[]) - nameValues = fieldData as NameValue[]; - else - { - string nameValue = Utils.BytesToString((byte[])fieldData); - if (nameValue.Length > 0) - { - string[] lines = nameValue.Split('\n'); - nameValues = new NameValue[lines.Length]; - - for (int i = 0; i < lines.Length; i++) - { - if (!String.IsNullOrEmpty(lines[i])) - { - NameValue nv = new NameValue(lines[i]); - nameValues[i] = nv; - } - } - } - } - StringBuilder result = new StringBuilder(); - result.AppendFormat("{0,30}", " " + Environment.NewLine); - if (nameValues != null) - { - for (int i = 0; i < nameValues.Length; i++) - { - result.AppendFormat( - "{0,30}: Name={1} Value={2} Class={3} Type={4} Sendto={5}" + Environment.NewLine, "NameValue", - nameValues[i].Name, nameValues[i].Value, nameValues[i].Class, nameValues[i].Type, nameValues[i].Sendto); - } - } - result.AppendFormat("{0,30}", ""); - return result.ToString(); - } - - private static string DecodeObjectExtraParams(string fieldName, object fieldData) - { - - byte[] data = (byte[])fieldData; - - int i = 0; - //int totalLength = 1; - - Primitive.FlexibleData Flexible = null; - Primitive.LightData Light = null; - Primitive.SculptData Sculpt = null; - Primitive.SculptData Mesh = null; - uint meshFlags = 0; - bool hasmeshFlags = false; - - byte extraParamCount = data[i++]; - - for (int k = 0; k < extraParamCount; k++) - { - ExtraParamType type = (ExtraParamType)Utils.BytesToUInt16(data, i); - i += 2; - - uint paramLength = Utils.BytesToUInt(data, i); - i += 4; - - if (type == ExtraParamType.Flexible) - Flexible = new Primitive.FlexibleData(data, i); - else if (type == ExtraParamType.Light) - Light = new Primitive.LightData(data, i); - else if (type == ExtraParamType.Sculpt) - Sculpt = new Primitive.SculptData(data, i); - else if (type == ExtraParamType.Mesh) - Mesh = new Primitive.SculptData(data, i); - else if ((byte)type == 0x70) - { - hasmeshFlags = true; - meshFlags = Utils.BytesToUInt(data, i); - } - i += (int)paramLength; - //totalLength += (int)paramLength + 6; - } - - StringBuilder result = new StringBuilder(); - result.AppendFormat("{0,30}", "" + Environment.NewLine); - if (Flexible != null) - { - result.AppendFormat("{0,30}", "" + Environment.NewLine); - GenericTypeDecoder(Flexible, ref result); - result.AppendFormat("{0,30}", "" + Environment.NewLine); - } - - if (Sculpt != null) - { - result.AppendFormat("{0,30}", "" + Environment.NewLine); - GenericTypeDecoder(Sculpt, ref result); - result.AppendFormat("{0,30}", "" + Environment.NewLine); - } - - if (Mesh != null) - { - result.AppendFormat("{0,30}", "" + Environment.NewLine); - GenericTypeDecoder(Mesh, ref result); - result.AppendFormat("{0,30}", "" + Environment.NewLine); - } - - if (Light != null) - { - result.AppendFormat("{0,30}", "" + Environment.NewLine); - GenericTypeDecoder(Light, ref result); - result.AppendFormat("{0,30}", "" + Environment.NewLine); - } - - if (hasmeshFlags) - { - result.AppendFormat("{0,30}", "" + Environment.NewLine); - result.AppendFormat("{0,30}", meshFlags.ToString() + Environment.NewLine); - result.AppendFormat("{0,30}", "" + Environment.NewLine); - } - - result.AppendFormat("{0,30}", ""); - return result.ToString(); - } - - private static string DecodeObjectParticleSystem(string fieldName, object fieldData) - { - StringBuilder result = new StringBuilder(); - Primitive.ParticleSystem ParticleSys; - if (fieldData is Primitive.ParticleSystem) - ParticleSys = (Primitive.ParticleSystem)fieldData; - else - ParticleSys = new Primitive.ParticleSystem((byte[])fieldData, 0); - - result.AppendFormat("{0,30}", "" + Environment.NewLine); - GenericTypeDecoder(ParticleSys, ref result); - result.AppendFormat("{0,30}", ""); - - return result.ToString(); - } - - private static void GenericTypeDecoder(object obj, ref StringBuilder result) - { - FieldInfo[] fields = obj.GetType().GetFields(); - - foreach (FieldInfo field in fields) - { - String special; - if (SpecialDecoder("a" + "." + "b" + "." + field.Name, - field.GetValue(obj), out special)) - { - result.AppendLine(special); - } - else - { - result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, - field.Name, - field.GetValue(obj), - field.FieldType.Name); - } - } - } - - private static string DecodeObjectPCode(string fieldName, object fieldData) - { - return String.Format("{0,30}: {1,-3} {2,-36} [PCode]", - fieldName, - fieldData, - "(" + (PCode)(byte)fieldData + ")"); - } - - private static string DecodeImageType(string fieldName, object fieldData) - { - return String.Format("{0,30}: {1,-3} {2,-36} [ImageType]", - fieldName, - fieldData, - "(" + (ImageType)(byte)fieldData + ")"); - } - - private static string DecodeImageCodec(string fieldName, object fieldData) - { - return String.Format("{0,30}: {1,-3} {2,-36} [ImageCodec]", - fieldName, - fieldData, - "(" + (ImageCodec)(byte)fieldData + ")"); - } - - private static string DecodeObjectMaterial(string fieldName, object fieldData) - { - return String.Format("{0,30}: {1,-3} {2,-36} [Material]", - fieldName, - fieldData, - "(" + (Material)(byte)fieldData + ")"); - } - - private static string DecodeObjectClickAction(string fieldName, object fieldData) - { - return String.Format("{0,30}: {1,-3} {2,-36} [ClickAction]", - fieldName, - fieldData, - "(" + (ClickAction)(byte)fieldData + ")"); - } - - private static string DecodeEventFlags(string fieldName, object fieldData) - { - return String.Format("{0,30}: {1,-3} {2,-36} [EventFlags]", - fieldName, - fieldData, - "(" + (DirectoryManager.EventFlags)(uint)fieldData + ")"); - } - - private static string DecodeDirQueryFlags(string fieldName, object fieldData) - { - return String.Format("{0,30}: {1,-10} {2,-29} [DirectoryManager.DirFindFlags]", - fieldName, - fieldData, - "(" + (DirectoryManager.DirFindFlags)(uint)fieldData + ")"); - } - - private static string DecodeDirClassifiedQueryFlags(string fieldName, object fieldData) - { - return String.Format("{0,30}: {1,-10} {2,-29} [ClassifiedQueryFlags]", - fieldName, - fieldData, - "(" + (DirectoryManager.ClassifiedQueryFlags)(uint)fieldData + ")"); - } - - private static string DecodeDirClassifiedFlags(string fieldName, object fieldData) - { - return String.Format("{0,30}: {1,-10} {2,-29} [ClassifiedFlags]", - fieldName, - fieldData, - "(" + (DirectoryManager.ClassifiedFlags)(byte)fieldData + ")"); - } - - private static string DecodeGroupPowers(string fieldName, object fieldData) - { - return String.Format("{0,30}: {1,-20} {2,-19} [GroupPowers]", - fieldName, - fieldData, - "(" + (GroupPowers)(ulong)fieldData + ")"); - } - - private static string DecodeParcelACL(string fieldName, object fieldData) - { - return String.Format("{0,30}: {1,-10} {2,-29} [AccessList]", - fieldName, - fieldData, - "(" + (AccessList)(uint)fieldData + ")"); - } - - private static string SearchTypeFlags(string fieldName, object fieldData) - { - return String.Format("{0,30}: {1,-10} {2,-29} [DirectoryManager.SearchTypeFlags]", - fieldName, - fieldData, - "(" + (DirectoryManager.SearchTypeFlags)(uint)fieldData + ")"); - } - - private static string DecodeCategory(string fieldName, object fieldData) - { - return String.Format("{0,30}: {1,-3} {2,-36} [ParcelCategory]", - fieldName, - fieldData, - "(" + fieldData + ")"); - } - - private static string DecodeObjectUpdateFlags(string fieldName, object fieldData) - { - return String.Format("{0,30}: {1,-10} {2,-29} [PrimFlags]", - fieldName, - fieldData, - "(" + (PrimFlags)(uint)fieldData + ")"); - } - - private static string DecodeTeleportFlags(string fieldName, object fieldData) - { - return String.Format("{0,30}: {1,-10} {2,-29} [TeleportFlags]", - fieldName, - fieldData, - "(" + (TeleportFlags)(uint)fieldData + ")"); - } - - private static string DecodeScriptControls(string fieldName, object fieldData) - { - return String.Format("{0,30}: {1,-10} {2,-29} [AgentManager.ControlFlags]", - fieldName, - (uint)fieldData, - "(" + (AgentManager.ControlFlags)(uint)fieldData + ")"); - } - - private static string DecodeColorField(string fieldName, object fieldData) - { - return String.Format("{0,30}: {1,-40} [Color4]", - fieldName, - fieldData.GetType().Name.Equals("Color4") ? (Color4)fieldData : new Color4((byte[])fieldData, 0, false)); - } - - private static string DecodeTimeStamp(string fieldName, object fieldData) - { - if (fieldData is Int32 && (int)fieldData > 0) - return String.Format("{0,30}: {1,-10} {2,-29} [{3}]", - fieldName, - fieldData, - "(" + Utils.UnixTimeToDateTime((int)fieldData) + ")", - fieldData.GetType().Name); - else if (fieldData is uint && (uint)fieldData > 0) - return String.Format("{0,30}: {1,-10} {2,-29} [{3}]", - fieldName, - fieldData, - "(" + Utils.UnixTimeToDateTime((uint)fieldData) + ")", - fieldData.GetType().Name); - else - return String.Format("{0,30}: {1,-40} [{2}]", - fieldName, - fieldData, - fieldData.GetType().Name); - } - - private static string DecodeBinaryBucket(string fieldName, object fieldData) - { - byte[] bytes = (byte[])fieldData; - string bucket = String.Empty; - if (bytes.Length == 1) - { - bucket = String.Format("{0}", bytes[0]); - } - else if (bytes.Length == 17) - { - bucket = String.Format("{0,-36} {1} ({2})", - new UUID(bytes, 1), - bytes[0], - (AssetType)(sbyte)bytes[0]); - } - else if (bytes.Length == 16) // the folder ID for the asset to be stored into if we accept an inventory offer - { - bucket = new UUID(bytes, 0).ToString(); - } - else - { - bucket = Utils.BytesToString(bytes); // we'll try a string lastly - } - - return String.Format("{0,30}: {1,-40} [Byte[{2}]]", fieldName, bucket, bytes.Length); - } - - private static string DecodeBinaryToHexString(string fieldName, object fieldData) - { - return String.Format("{0,30}", - Utils.BytesToHexString((byte[])fieldData, - String.Format("{0,30}", fieldName))); - } - - private static string DecodeWearableType(string fieldName, object fieldData) - { - return String.Format("{0,30}: {1,-2} {2,-37} [WearableType]", - fieldName, - (byte)fieldData, - "(" + (WearableType)fieldData + ")"); - } - - private static string DecodeInventoryType(string fieldName, object fieldData) - { - return String.Format("{0,30}: {1,-2} {2,-37} [AssetType]", - fieldName, - (sbyte)fieldData, - "(" + (AssetType)(sbyte)fieldData + ")"); - } - - private static string DecodeInventorySort(string fieldName, object fieldData) - { - return String.Format("{0,30}: {1,-2} {2,-37} [InventorySortOrder]", - fieldName, - fieldData, - "(" + (InventorySortOrder)(int)fieldData + ")"); - } - - private static string DecodeInventoryInvType(string fieldName, object fieldData) - { - return String.Format("{0,30}: {1,-2} {2,-37} [InventoryType]", - fieldName, - (sbyte)fieldData, - "(" + (InventoryType)fieldData + ")"); - } - - private static string DecodeFolderType(string fieldName, object fieldData) - { - return String.Format("{0,30}: {1,-2} {2,-37} [Folderype]", - fieldName, - (sbyte)fieldData, - "(" + (FolderType)fieldData + ")"); - } - - private static string DecodeInventoryFlags(string fieldName, object fieldData) - { - return String.Format("{0,30}: {1,-2} {2,-37} [InventoryItemFlags]", - fieldName, - (uint)fieldData, - "(" + (InventoryItemFlags)(uint)fieldData + ")"); - } - - private static string DecodeObjectSaleType(string fieldName, object fieldData) - { - return String.Format("{0,30}: {1,-2} {2,-37} [SaleType]", - fieldName, - (byte)fieldData, - "(" + (SaleType)fieldData + ")"); - } - - private static string DecodeRegionFlags(string fieldName, object fieldData) - { - return String.Format("{0,30}: {1,-2} {2,-37} [RegionFlags]", - fieldName, - fieldData, - "(" + (RegionFlags)(uint)fieldData + ")"); - } - - private static string DecodeTransferParams(string fieldName, object fieldData) - { - byte[] paramData = (byte[])fieldData; - StringBuilder result = new StringBuilder(); - result.AppendLine(" "); - if (paramData.Length == 20) - { - result.AppendFormat("{0,30}: {1,-40} [UUID]" + Environment.NewLine, - "AssetID", - new UUID(paramData, 0)); - - result.AppendFormat("{0,30}: {1,-2} {2,-37} [AssetType]" + Environment.NewLine, - "AssetType", - (sbyte)paramData[16], - "(" + (AssetType)(sbyte)paramData[16] + ")"); - - } - else if (paramData.Length == 100) - { - //UUID agentID = new UUID(info.TransferInfo.Params, 0); - result.AppendFormat("{0,30}: {1,-40} [UUID]" + Environment.NewLine, - "AgentID", - new UUID(paramData, 0)); - - //UUID sessionID = new UUID(info.TransferInfo.Params, 16); - result.AppendFormat("{0,30}: {1,-40} [UUID]" + Environment.NewLine, - "SessionID", - new UUID(paramData, 16)); - //UUID ownerID = new UUID(info.TransferInfo.Params, 32); - result.AppendFormat("{0,30}: {1,-40} [UUID]" + Environment.NewLine, - "OwnerID", - new UUID(paramData, 32)); - //UUID taskID = new UUID(info.TransferInfo.Params, 48); - result.AppendFormat("{0,30}: {1,-40} [UUID]" + Environment.NewLine, - "TaskID", - new UUID(paramData, 48)); - //UUID itemID = new UUID(info.TransferInfo.Params, 64); - result.AppendFormat("{0,30}: {1,-40} [UUID]" + Environment.NewLine, - "ItemID", - new UUID(paramData, 64)); - - result.AppendFormat("{0,30}: {1,-40} [UUID]" + Environment.NewLine, - "AssetID", - new UUID(paramData, 80)); - - result.AppendFormat("{0,30}: {1,-2} {2,-37} [AssetType]" + Environment.NewLine, - "AssetType", - (sbyte)paramData[96], - "(" + (AssetType)(sbyte)paramData[96] + ")"); - } - else - { - Console.WriteLine("Oh Poop!"); - } - - result.Append(""); - - return result.ToString(); - } - - private static string DecodeTransferChannelType(string fieldName, object fieldData) - { - return String.Format("{0,30}: {1,-2} {2,-37} [ChannelType]", - fieldName, - fieldData, - "(" + (ChannelType)(int)fieldData + ")"); - } - - private static string DecodeTransferSourceType(string fieldName, object fieldData) - { - return String.Format("{0,30}: {1,-2} {2,-37} [SourceType]", - fieldName, - fieldData, - "(" + (SourceType)(int)fieldData + ")"); - } - - private static string DecodeTransferTargetType(string fieldName, object fieldData) - { - return String.Format("{0,30}: {1,-2} {2,-37} [TargetType]", - fieldName, - fieldData, - "(" + (TargetType)(int)fieldData + ")"); - } - - private static string DecodeMapRequestFlags(string fieldName, object fieldData) - { - return String.Format("{0,30}: {1,-2} {2,-37} [GridLayerType]", - fieldName, - fieldData, - "(" + (GridLayerType)(uint)fieldData + ")"); - } - - private static string DecodeGridItemType(string fieldName, object fieldData) - { - return String.Format("{0,30}: {1,-2} {2,-37} [GridItemType]", - fieldName, - fieldData, - "(" + (GridItemType)(uint)fieldData + ")"); - - } - - private static string DecodeLayerDataType(string fieldName, object fieldData) - { - return String.Format("{0,30}: {1,-2} {2,-37} [LayerType]", - fieldName, - fieldData, - "(" + (TerrainPatch.LayerType)(byte)fieldData + ")"); - } - - private static string DecodeMapAccess(string fieldName, object fieldData) - { - return String.Format("{0,30}: {1,-2} {2,-37} [SimAccess]", - fieldName, - fieldData, - "(" + (SimAccess)(byte)fieldData + ")"); - } - - private static string DecodeSimAccess(string fieldName, object fieldData) - { - return String.Format("{0,30}: {1,-2} {2,-37} [SimAccess]", - fieldName, - (byte)fieldData, - "(" + (SimAccess)fieldData + ")"); - } - - private static string DecodeAttachedSoundFlags(string fieldName, object fieldData) - { - return String.Format("{0,30}: {1,-2} {2,-37} [SoundFlags]", - fieldName, - (byte)fieldData, - "(" + (SoundFlags)fieldData + ")"); - } - - - private static string DecodeChatSourceType(string fieldName, object fieldData) - { - return String.Format("{0,30}: {1,-2} {2,-37} [SourceType]", - fieldName, - fieldData, - "(" + (SourceType)(byte)fieldData + ")"); - } - - private static string DecodeChatChatType(string fieldName, object fieldData) - { - return String.Format("{0,30}: {1,-2} {2,-37} [ChatType]", - fieldName, - (byte)fieldData, - "(" + (ChatType)fieldData + ")"); - } - - private static string DecodeChatAudible(string fieldName, object fieldData) - { - return String.Format("{0,30}: {1,-2} {2,-37} [ChatAudibleLevel]", - fieldName, - (byte)fieldData, - "(" + (ChatAudibleLevel)(byte)fieldData + ")"); - } - - private static string DecodeImageData(string fieldName, object fieldData) - { - return String.Format("{0,10}", - Utils.BytesToHexString((byte[])fieldData, - String.Format("{0,30}", fieldName))); - } - - private static string DecodeTerseTextureEntry(string fieldName, object fieldData) - { - byte[] block = (byte[])fieldData; - - Primitive.TextureEntry te = new Primitive.TextureEntry(block, 4, block.Length - 4); - - StringBuilder result = new StringBuilder(); - - result.AppendFormat("{0,30}", " " + Environment.NewLine); - if (te.DefaultTexture != null) - { - result.AppendFormat("{0,30}", " " + Environment.NewLine); - GenericFieldsDecoder(te.DefaultTexture, ref result); - GenericPropertiesDecoder(te.DefaultTexture, ref result); - result.AppendFormat("{0,30}", " " + Environment.NewLine); - } - result.AppendFormat("{0,30}", " " + Environment.NewLine); - for (int i = 0; i < te.FaceTextures.Length; i++) - { - if (te.FaceTextures[i] != null) - { - result.AppendFormat("{0,30}[{1}]" + Environment.NewLine, "FaceTexture", i); - GenericFieldsDecoder(te.FaceTextures[i], ref result); - GenericPropertiesDecoder(te.FaceTextures[i], ref result); - } - } - result.AppendFormat("{0,30}", " " + Environment.NewLine); - result.AppendFormat("{0,30}", ""); - - return result.ToString(); - } - - private static string DecodeTextureEntry(string fieldName, object fieldData) - { - Primitive.TextureEntry te; - if (fieldData is Primitive.TextureEntry) - te = (Primitive.TextureEntry)fieldData; - else - { - byte[] tebytes = (byte[])fieldData; - te = new Primitive.TextureEntry(tebytes, 0, tebytes.Length); - } - - StringBuilder result = new StringBuilder(); - - result.AppendFormat("{0,30}", " " + Environment.NewLine); - if (te.DefaultTexture != null) - { - result.AppendFormat("{0,30}", " " + Environment.NewLine); - GenericFieldsDecoder(te.DefaultTexture, ref result); - GenericPropertiesDecoder(te.DefaultTexture, ref result); - result.AppendFormat("{0,30}", " " + Environment.NewLine); - } - result.AppendFormat("{0,30}", " " + Environment.NewLine); - for (int i = 0; i < te.FaceTextures.Length; i++) - { - if (te.FaceTextures[i] != null) - { - result.AppendFormat("{0,30}[{1}]" + Environment.NewLine, "FaceTexture", i); - GenericFieldsDecoder(te.FaceTextures[i], ref result); - GenericPropertiesDecoder(te.FaceTextures[i], ref result); - } - } - result.AppendFormat("{0,30}", " " + Environment.NewLine); - result.AppendFormat("{0,30}", ""); - - return result.ToString(); - } - - private static void GenericFieldsDecoder(object obj, ref StringBuilder result) - { - Type parcelType = obj.GetType(); - FieldInfo[] fields = parcelType.GetFields(); - foreach (FieldInfo field in fields) - { - String special; - if (SpecialDecoder("a" + "." + "b" + "." + field.Name, - field.GetValue(obj), out special)) - { - result.AppendLine(special); - } - else - { - result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, - field.Name, - field.GetValue(obj), - field.FieldType.Name); - } - } - } - - private static void GenericPropertiesDecoder(object obj, ref StringBuilder result) - { - Type parcelType = obj.GetType(); - PropertyInfo[] propertyInfos = parcelType.GetProperties(); - foreach (PropertyInfo property in propertyInfos) - { - String special; - if (SpecialDecoder("a" + "." + "b" + "." + property.Name, - property.GetValue(obj, null), out special)) - { - result.AppendLine(special); - } - else - { - result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, - property.Name, - property.GetValue(obj, null), - property.PropertyType.Name); - } - } - } - - private static string DecodeDialog(string fieldName, object fieldData) - { - return String.Format("{0,30}: {1,-2} {2,-37} [{3}]", - fieldName, - (byte)fieldData, - "(" + (InstantMessageDialog)fieldData + ")", - fieldData.GetType().Name); - } - - private static string DecodeControlFlags(string fieldName, object fieldData) - { - return String.Format("{0,30}: {1,-10} {2,-29} [{3}]", - fieldName, - fieldData, - "(" + (AgentManager.ControlFlags)(uint)fieldData + ")", - fieldData.GetType().Name); - } - - private static string DecodePermissionMask(string fieldName, object fieldData) - { - return String.Format("{0,30}: {1,-10} {2,-29} [{3}]", - fieldName, - (uint)fieldData, - "(" + (PermissionMask)fieldData + ")", - fieldData.GetType().Name); - } - - private static string DecodeViewerEffectTypeData(string fieldName, object fieldData) - { - byte[] data = (byte[])fieldData; - StringBuilder sb = new StringBuilder(); - if (data.Length == 56 || data.Length == 57) - { - UUID sourceAvatar = new UUID(data, 0); - UUID targetObject = new UUID(data, 16); - Vector3d targetPos = new Vector3d(data, 32); - sb.AppendFormat("{0,30}: {1,-40} [UUID]" + Environment.NewLine, fieldName, "Source AvatarID=" + sourceAvatar); - sb.AppendFormat("{0,30}: {1,-40} [UUID]" + Environment.NewLine, fieldName, "Target ObjectID=" + targetObject); - - - float lx, ly; - Helpers.GlobalPosToRegionHandle((float)targetPos.X, (float)targetPos.Y, out lx, out ly); - - sb.AppendFormat("{0,30}: {1,-40} [Vector3d]", fieldName, targetPos); - - if (data.Length == 57) - { - sb.AppendLine(); - sb.AppendFormat("{0,30}: {1,-17} {2,-22} [Byte]", fieldName, "Point At Type=" + data[56], - "(" + (PointAtType)data[56] + ")"); - } - - return sb.ToString(); - } - else - { - return String.Format("{0,30}: (No Decoder) Length={1}" + Environment.NewLine, fieldName, data.Length) + Utils.BytesToHexString(data, String.Format("{0,30}", "")); - } - } - - private static string DecodeAgentState(string fieldName, object fieldData) - { - return String.Format("{0,30}: {1,-2} {2,-37} [AgentState]", - fieldName, - fieldData, - "(" + (AgentState)(byte)fieldData + ")"); - } - - private static string DecodeAgentFlags(string fieldName, object fieldData) - { - return String.Format("{0,30}: {1,-2} {2,-37} [AgentFlags]", - fieldName, - fieldData, - "(" + (AgentFlags)(byte)fieldData + ")"); - } - - private static string DecodeObjectState(string fieldName, object fieldData) - { - return String.Format("{0,30}: {1,-2} {2,-37} [AttachmentPoint]", - fieldName, - fieldData, - "(" + (AttachmentPoint)(byte)fieldData + ")"); - } - - private static string DecodeViewerEffectType(string fieldName, object fieldData) - { - return String.Format("{0,30}: {1,-2} {2,-37} [{3}]", - fieldName, - fieldData, - "(" + (EffectType)(byte)fieldData + ")", - fieldData.GetType().Name); - } - - private static string DecodeAnimToConst(string fieldName, object fieldData) - { - string animConst = "UUID"; - Dictionary animsDict = Animations.ToDictionary(); - if (animsDict.ContainsKey((UUID)fieldData)) - animConst = animsDict[(UUID)fieldData]; - return String.Format("{0,30}: {1,-40} [{2}]", - fieldName, - fieldData, - animConst); - } - #endregion - - /// - /// Creates a formatted string containing the values of a Packet - /// - /// The Packet - /// A formatted string of values of the nested items in the Packet object - public static string PacketToString(Packet packet) - { - StringBuilder result = new StringBuilder(); - - result.AppendFormat("Packet Type: {0}" + Environment.NewLine, packet.Type); - result.AppendLine("[Packet Header]"); - // payload - result.AppendFormat("Sequence: {0}" + Environment.NewLine, packet.Header.Sequence); - result.AppendFormat(" Options: {0}" + Environment.NewLine, InterpretOptions(packet.Header)); - result.AppendLine(); - - result.AppendLine("[Packet Payload]"); - - FieldInfo[] fields = packet.GetType().GetFields(); - - for (int i = 0; i < fields.Length; i++) - { - // we're not interested in any of these here - if (fields[i].Name == "Type" || fields[i].Name == "Header" || fields[i].Name == "HasVariableBlocks") - continue; - - if (fields[i].FieldType.IsArray) - { - result.AppendFormat("{0,30} []" + Environment.NewLine, "-- " + fields[i].Name + " --"); - RecursePacketArray(fields[i], packet, ref result); - } - else - { - result.AppendFormat("{0,30}" + Environment.NewLine, "-- " + fields[i].Name + " --"); - RecursePacketField(fields[i], packet, ref result); - } - } - return result.ToString(); - } - - public static string InterpretOptions(Header header) - { - return "[" - + (header.AppendedAcks ? "Ack" : " ") - + " " - + (header.Resent ? "Res" : " ") - + " " - + (header.Reliable ? "Rel" : " ") - + " " - + (header.Zerocoded ? "Zer" : " ") - + "]" - ; - } - - private static void RecursePacketArray(FieldInfo fieldInfo, object packet, ref StringBuilder result) - { - var packetDataObject = fieldInfo.GetValue(packet); - int k = -1; - foreach (object nestedArrayRecord in packetDataObject as Array) - { - FieldInfo[] fields = nestedArrayRecord.GetType().GetFields(); - ++k; - for (int i = 0; i < fields.Length; i++) - { - String special; - if (SpecialDecoder(packet.GetType().Name + "." + fieldInfo.Name + "." + fields[i].Name, - fields[i].GetValue(nestedArrayRecord), out special)) - { - result.AppendLine(special); - } - else if (fields[i].FieldType.IsArray) // default for an array (probably a byte[]) - { - result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, - fields[i].Name + "[" + k.ToString() + "]", - Utils.BytesToString((byte[])fields[i].GetValue(nestedArrayRecord)), - /*fields[i].GetValue(nestedArrayRecord).GetType().Name*/ "String"); - } - else // default for a field - { - result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, - fields[i].Name + "[" + k.ToString() + "]", - fields[i].GetValue(nestedArrayRecord), - fields[i].GetValue(nestedArrayRecord).GetType().Name); - } - } - - // Handle Properties - foreach (PropertyInfo propertyInfo in nestedArrayRecord.GetType().GetProperties()) - { - if (propertyInfo.Name.Equals("Length")) - continue; - - string special; - if (SpecialDecoder(packet.GetType().Name + "." + fieldInfo.Name + "." + propertyInfo.Name, - propertyInfo.GetValue(nestedArrayRecord, null), - out special)) - { - result.AppendLine(special); - } - else - { - var p = propertyInfo.GetValue(nestedArrayRecord, null); - /* Leave the c for now at the end, it signifies something useful that still needs to be done i.e. a decoder written */ - result.AppendFormat("{0, 30}: {1,-40} [{2}]c" + Environment.NewLine, - propertyInfo.Name, - Utils.BytesToString((byte[])propertyInfo.GetValue(nestedArrayRecord, null)), - propertyInfo.PropertyType.Name); - } - } - result.AppendFormat("{0,32}" + Environment.NewLine, "***"); - } - } - - private static void RecursePacketField(FieldInfo fieldInfo, object packet, ref StringBuilder result) - { - object packetDataObject = fieldInfo.GetValue(packet); - - // handle Fields - foreach (FieldInfo packetValueField in fieldInfo.GetValue(packet).GetType().GetFields()) - { - string special; - if (SpecialDecoder(packet.GetType().Name + "." + fieldInfo.Name + "." + packetValueField.Name, - packetValueField.GetValue(packetDataObject), - out special)) - { - result.AppendLine(special); - } - else if (packetValueField.FieldType.IsArray) - { - result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, - packetValueField.Name, - Utils.BytesToString((byte[])packetValueField.GetValue(packetDataObject)), - /*packetValueField.FieldType.Name*/ "String"); - } - else - { - result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, - packetValueField.Name, packetValueField.GetValue(packetDataObject), packetValueField.FieldType.Name); - - } - } - - // Handle Properties - foreach (PropertyInfo propertyInfo in packetDataObject.GetType().GetProperties()) - { - if (propertyInfo.Name.Equals("Length")) - continue; - - string special; - if (SpecialDecoder(packet.GetType().Name + "." + fieldInfo.Name + "." + propertyInfo.Name, - propertyInfo.GetValue(packetDataObject, null), - out special)) - { - result.AppendLine(special); - } - else if (propertyInfo.GetValue(packetDataObject, null).GetType() == typeof(byte[])) - { - result.AppendFormat("{0, 30}: {1,-40} [{2}]" + Environment.NewLine, - propertyInfo.Name, - Utils.BytesToString((byte[])propertyInfo.GetValue(packetDataObject, null)), - propertyInfo.PropertyType.Name); - } - else - { - result.AppendFormat("{0, 30}: {1,-40} [{2}]" + Environment.NewLine, - propertyInfo.Name, - propertyInfo.GetValue(packetDataObject, null), - propertyInfo.PropertyType.Name); - } - } - } - - private static bool SpecialDecoder(string decoderKey, object fieldData, out string result) - { - result = string.Empty; - string[] keys = decoderKey.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries); - string[] keyList = { decoderKey, decoderKey.Replace("Packet", ""), keys[1] + "." + keys[2], keys[2] }; - foreach (string key in keyList) - { - - bool ok = true; - if (fieldData is byte[]) - { - byte[] fd = (byte[])fieldData; - ok = fd.Length > 0; - if (!ok) - { - // bypass the decoder since we were passed an empty byte array - result = String.Format("{0,30}:", keys[2]); - return true; - } - } - - if (ok && Callbacks.ContainsKey(key)) // fieldname e.g: Plane - { - foreach (CustomPacketDecoder decoder in Callbacks[key]) - result = decoder(keys[2], fieldData); - return true; - } - } - return false; - } - - /// - /// Decode an IMessage object into a beautifully formatted string - /// - /// The IMessage object - /// Recursion level (used for indenting) - /// A formatted string containing the names and values of the source object - public static string MessageToString(object message, int recurseLevel) - { - if (message == null) - return String.Empty; - - StringBuilder result = new StringBuilder(); - // common/custom types - if (recurseLevel <= 0) - { - result.AppendFormat("Message Type: {0}" + Environment.NewLine, message.GetType().Name); - } - else - { - string pad = " +--".PadLeft(recurseLevel + 3); - result.AppendFormat("{0} {1}" + Environment.NewLine, pad, message.GetType().Name); - } - - recurseLevel++; - - foreach (FieldInfo messageField in message.GetType().GetFields()) - { - // an abstract message class - if (messageField.FieldType.IsAbstract) - { - result.AppendLine(MessageToString(messageField.GetValue(message), recurseLevel)); - } - // a byte array - else if (messageField.GetValue(message) != null && messageField.GetValue(message).GetType() == typeof(Byte[])) - { - result.AppendFormat("{0, 30}:" + Environment.NewLine, messageField.Name); - - result.AppendFormat("{0}" + Environment.NewLine, - Utils.BytesToHexString((byte[])messageField.GetValue(message), - String.Format("{0,30}", ""))); - } - - // an array of class objects - else if (messageField.FieldType.IsArray) - { - var messageObjectData = messageField.GetValue(message); - result.AppendFormat("-- {0} --" + Environment.NewLine, messageField.FieldType.Name); - foreach (object nestedArrayObject in messageObjectData as Array) - { - if (nestedArrayObject == null) - { - result.AppendFormat("{0,30}" + Environment.NewLine, "-- null --"); - continue; - } - else - { - result.AppendFormat("{0,30}" + Environment.NewLine, "-- " + nestedArrayObject.GetType().Name + " --"); - } - foreach (FieldInfo nestedField in nestedArrayObject.GetType().GetFields()) - { - if (nestedField.FieldType.IsEnum) - { - result.AppendFormat("{0,30}: {1,-10} {2,-29} [{3}]" + Environment.NewLine, - nestedField.Name, - Enum.Format(nestedField.GetValue(nestedArrayObject).GetType(), - nestedField.GetValue(nestedArrayObject), "D"), - "(" + nestedField.GetValue(nestedArrayObject) + ")", - nestedField.GetValue(nestedArrayObject).GetType().Name); - } - else if (nestedField.FieldType.IsInterface) - { - result.AppendLine(MessageToString(nestedField.GetValue(nestedArrayObject), recurseLevel)); - } - else - { - result.AppendFormat("{0, 30}: {1,-40} [{2}]" + Environment.NewLine, - nestedField.Name, - nestedField.GetValue(nestedArrayObject), - nestedField.FieldType.Name); - } - } - } - } - else - { - if (messageField.FieldType.IsEnum) - { - result.AppendFormat("{0,30}: {1,-2} {2,-37} [{3}]" + Environment.NewLine, - messageField.Name, - Enum.Format(messageField.GetValue(message).GetType(), - messageField.GetValue(message), "D"), - "(" + messageField.GetValue(message) + ")", - messageField.FieldType.Name); - } - else if (messageField.FieldType.IsInterface) - { - result.AppendLine(MessageToString(messageField.GetValue(message), recurseLevel)); - } - else - { - result.AppendFormat("{0, 30}: {1,-40} [{2}]" + Environment.NewLine, - messageField.Name, messageField.GetValue(message), messageField.FieldType.Name); - } - } - } - - return result.ToString(); - } - } -} +/* + * Copyright (c) 2006-2016, openmetaverse.co + * All rights reserved. + * + * - Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * - Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * - Neither the name of the openmetaverse.co nor the names + * of its contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections.Generic; +using System.Reflection; +using System.Text; + +namespace OpenMetaverse.Packets +{ + + public static class PacketDecoder + { + /// + /// A custom decoder callback + /// + /// The key of the object + /// the data to decode + /// A string represending the fieldData + public delegate string CustomPacketDecoder(string fieldName, object fieldData); + + private static Dictionary> Callbacks = new Dictionary>(); + + + static PacketDecoder() + { + AddCallback("Color", DecodeColorField); + AddCallback("TextColor", DecodeColorField); + AddCallback("Timestamp", DecodeTimeStamp); + AddCallback("EstateCovenantReply.Data.CovenantTimestamp", DecodeTimeStamp); + AddCallback("CreationDate", DecodeTimeStamp); + AddCallback("BinaryBucket", DecodeBinaryBucket); + AddCallback("ParcelData.Data", DecodeBinaryToHexString); + AddCallback("LayerData.Data", DecodeBinaryToHexString); + AddCallback("ImageData.Data", DecodeImageData); + AddCallback("TransferData.Data", DecodeBinaryToHexString); + AddCallback("ObjectData.TextureEntry", DecodeTextureEntry); + AddCallback("ImprovedInstantMessage.MessageBlock.Dialog", DecodeDialog); + + // Inventory/Permissions + AddCallback("BaseMask", DecodePermissionMask); + AddCallback("OwnerMask", DecodePermissionMask); + AddCallback("EveryoneMask", DecodePermissionMask); + AddCallback("NextOwnerMask", DecodePermissionMask); + AddCallback("GroupMask", DecodePermissionMask); + + // FetchInventoryDescendents + AddCallback("InventoryData.SortOrder", DecodeInventorySort); + + AddCallback("WearableType", DecodeWearableType); + // + AddCallback("InventoryData.Type", DecodeInventoryType); + AddCallback("InvType", DecodeInventoryInvType); + AddCallback("InventoryData.Flags", DecodeInventoryFlags); + // BulkUpdateInventory + AddCallback("ItemData.Type", DecodeInventoryType); + AddCallback("ItemData.Flags", DecodeInventoryFlags); + + AddCallback("SaleType", DecodeObjectSaleType); + + AddCallback("ScriptControlChange.Data.Controls", DecodeScriptControls); + + AddCallback("RegionFlags", DecodeRegionFlags); + AddCallback("SimAccess", DecodeSimAccess); + AddCallback("ControlFlags", DecodeControlFlags); + + // AgentUpdate + AddCallback("AgentUpdate.AgentData.State", DecodeAgentState); + AddCallback("AgentUpdate.AgentData.Flags", DecodeAgentFlags); + + // ViewerEffect TypeData + AddCallback("ViewerEffect.Effect.TypeData", DecodeViewerEffectTypeData); + AddCallback("ViewerEffect.Effect.Type", DecodeViewerEffectType); + + // Prim/ObjectUpdate decoders + AddCallback("ObjectUpdate.ObjectData.PCode", DecodeObjectPCode); + AddCallback("ObjectUpdate.ObjectData.Material", DecodeObjectMaterial); + AddCallback("ObjectUpdate.ObjectData.ClickAction", DecodeObjectClickAction); + AddCallback("ObjectData.UpdateFlags", DecodeObjectUpdateFlags); + + AddCallback("ObjectUpdate.ObjectData.ObjectData", DecodeObjectData); + AddCallback("TextureAnim", DecodeObjectTextureAnim); + AddCallback("ObjectUpdate.ObjectData.NameValue", DecodeNameValue); + AddCallback("ObjectUpdate.ObjectData.Data", DecodeObjectData); + + AddCallback("ObjectUpdate.ObjectData.PSBlock", DecodeObjectParticleSystem); + AddCallback("ParticleSys", DecodeObjectParticleSystem); + AddCallback("ObjectUpdate.ObjectData.ExtraParams", DecodeObjectExtraParams); + + AddCallback("ImprovedTerseObjectUpdate.ObjectData.Data", DecodeTerseUpdate); + AddCallback("ImprovedTerseObjectUpdate.ObjectData.TextureEntry", DecodeTerseTextureEntry); + + AddCallback("ObjectUpdateCompressed.ObjectData.Data", DecodeObjectCompressedData); + + // ImprovedTerseObjectUpdate & ObjectUpdate AttachmentPoint & ObjectUpdateCompressed + AddCallback("ObjectData.State", DecodeObjectState); + //AddCallback("ObjectUpdateCompressed.ObjectData.State", DecodeObjectState); + //AddCallback("ImprovedTerseObjectUpdate.ObjectData.State", DecodeObjectState); + + + // ChatFromSimulator + AddCallback("ChatData.SourceType", DecodeChatSourceType); + AddCallback("ChatData.ChatType", DecodeChatChatType); + AddCallback("ChatData.Audible", DecodeChatAudible); + AddCallback("AttachedSound.DataBlock.Flags", DecodeAttachedSoundFlags); + + AddCallback("RequestImage.Type", DecodeImageType); + + AddCallback("EstateOwnerMessage.ParamList.Parameter", DecodeEstateParameter); + + AddCallback("Codec", DecodeImageCodec); + AddCallback("Info.TeleportFlags", DecodeTeleportFlags); + + // map + AddCallback("MapBlockRequest.AgentData.Flags", DecodeMapRequestFlags); + AddCallback("MapItemRequest.AgentData.Flags", DecodeMapRequestFlags); + AddCallback("MapBlockReply.Data.Access", DecodeMapAccess); + AddCallback("FolderData.Type", DecodeFolderType); + AddCallback("RequestData.ItemType", DecodeGridItemType); + + // TransferRequest/TransferInfo + AddCallback("TransferInfo.Params", DecodeTransferParams); + AddCallback("TransferInfo.ChannelType", DecodeTransferChannelType); + AddCallback("TransferInfo.SourceType", DecodeTransferSourceType); + AddCallback("TransferInfo.TargetType", DecodeTransferTargetType); + AddCallback("TransferData.ChannelType", DecodeTransferChannelType); + // SendXferPacket + AddCallback("DataPacket.Data", DecodeBinaryToHexString); + // Directory Manager + AddCallback("DirClassifiedQuery.QueryData.QueryFlags", DecodeDirClassifiedQueryFlags); + AddCallback("QueryData.QueryFlags", DecodeDirQueryFlags); + AddCallback("Category", DecodeCategory); + AddCallback("QueryData.SearchType", SearchTypeFlags); + + AddCallback("ClassifiedFlags", DecodeDirClassifiedFlags); + AddCallback("EventFlags", DecodeEventFlags); + + AddCallback("ParcelAccessListRequest.Data.Flags", DecodeParcelACL); + AddCallback("ParcelAccessListReply.Data.Flags", DecodeParcelACL); + //AddCallback("ParcelAccessListReply.List.Flags", DecodeParcelACLReply); + + // AgentAnimation + AddCallback("AnimID", DecodeAnimToConst); + + AddCallback("LayerData.LayerID.Type", DecodeLayerDataType); + + AddCallback("GroupPowers", DecodeGroupPowers); + } + + /// + /// Add a custom decoder callback + /// + /// The key of the field to decode + /// The custom decode handler + public static void AddCallback(string key, CustomPacketDecoder customPacketHandler) + { + if (Callbacks.ContainsKey(key)) + { + lock (Callbacks) + Callbacks[key].Add(customPacketHandler); + } + else + { + lock (Callbacks) + Callbacks.Add(key, new List() { customPacketHandler }); + } + } + + /// + /// Remove a custom decoder callback + /// + /// The key of the field to decode + /// The custom decode handler + public static void RemoveCustomHandler(string key, CustomPacketDecoder customPacketHandler) + { + if (Callbacks.ContainsKey(key)) + lock (Callbacks) + { + if (Callbacks[key].Contains(customPacketHandler)) + Callbacks[key].Remove(customPacketHandler); + } + } + + #region Custom Decoders + + private static string DecodeTerseUpdate(string fieldName, object fieldData) + { + byte[] block = (byte[])fieldData; + int i = 4; + + StringBuilder result = new StringBuilder(); + + // LocalID + result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, + "LocalID", + Utils.BytesToUInt(block, 0), + "Uint32"); + + + + // State + byte point = block[i++]; + result.AppendFormat("{0,30}: {1,-3} {2,-36} [{3}]" + Environment.NewLine, + "State", + point, + "(" + (AttachmentPoint)point + ")", + "AttachmentPoint"); + + // Avatar boolean + bool isAvatar = (block[i++] != 0); + result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, + "IsAvatar", + isAvatar, + "Boolean"); + + // Collision normal for avatar + if (isAvatar) + { + result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, + "CollisionPlane", + new Vector4(block, i), + "Vector4"); + + i += 16; + } + + // Position + result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, + "Position", + new Vector3(block, i), + "Vector3"); + i += 12; + + // Velocity + result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, + "Velocity", + new Vector3( + Utils.BytesUInt16ToFloat(block, i, -128.0f, 128.0f), + Utils.BytesUInt16ToFloat(block, i + 2, -128.0f, 128.0f), + Utils.BytesUInt16ToFloat(block, i + 4, -128.0f, 128.0f)), + "Vector3"); + i += 6; + + // Acceleration + result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, + "Acceleration", + new Vector3( + Utils.BytesUInt16ToFloat(block, i, -64.0f, 64.0f), + Utils.BytesUInt16ToFloat(block, i + 2, -64.0f, 64.0f), + Utils.BytesUInt16ToFloat(block, i + 4, -64.0f, 64.0f)), + "Vector3"); + + i += 6; + // Rotation (theta) + result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, + "Rotation", + new Quaternion( + Utils.BytesUInt16ToFloat(block, i, -1.0f, 1.0f), + Utils.BytesUInt16ToFloat(block, i + 2, -1.0f, 1.0f), + Utils.BytesUInt16ToFloat(block, i + 4, -1.0f, 1.0f), + Utils.BytesUInt16ToFloat(block, i + 6, -1.0f, 1.0f)), + "Quaternion"); + i += 8; + // Angular velocity (omega) + result.AppendFormat("{0,30}: {1,-40} [{2}]", + "AngularVelocity", + new Vector3( + Utils.BytesUInt16ToFloat(block, i, -64.0f, 64.0f), + Utils.BytesUInt16ToFloat(block, i + 2, -64.0f, 64.0f), + Utils.BytesUInt16ToFloat(block, i + 4, -64.0f, 64.0f)), + "Vector3"); + //pos += 6; + // TODO: What is in these 6 bytes? + return result.ToString(); + } + + private static string DecodeObjectCompressedData(string fieldName, object fieldData) + { + StringBuilder result = new StringBuilder(); + byte[] block = (byte[])fieldData; + int i = 0; + + // UUID + result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, + "ID", + new UUID(block, 0), + "UUID"); + i += 16; + + // Local ID + uint LocalID = (uint)(block[i++] + (block[i++] << 8) + + (block[i++] << 16) + (block[i++] << 24)); + + result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, + "LocalID", + LocalID, + "Uint32"); + // PCode + PCode pcode = (PCode)block[i++]; + + result.AppendFormat("{0,30}: {1,-3} {2,-36} [{3}]" + Environment.NewLine, + "PCode", + (int)pcode, + "(" + pcode + ")", + "PCode"); + + // State + AttachmentPoint point = (AttachmentPoint)block[i++]; + result.AppendFormat("{0,30}: {1,-3} {2,-36} [{3}]" + Environment.NewLine, + "State", + (byte)point, + "(" + point + ")", + "AttachmentPoint"); + + //CRC + result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, + "CRC", + Utils.BytesToUInt(block, i), + "UInt"); + i += 4; + + // Material + result.AppendFormat("{0,30}: {1,-3} {2,-36} [{3}]" + Environment.NewLine, + "Material", + block[i], + "(" + (Material)block[i++] + ")", + "Material"); + + // Click action + result.AppendFormat("{0,30}: {1,-3} {2,-36} [{3}]" + Environment.NewLine, + "ClickAction", + block[i], + "(" + (ClickAction)block[i++] + ")", + "ClickAction"); + + // Scale + result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, + "Scale", + new Vector3(block, i), + "Vector3"); + i += 12; + + // Position + result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, + "Position", + new Vector3(block, i), + "Vector3"); + i += 12; + + // Rotation + result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, + "Rotation", + new Vector3(block, i), + "Vector3"); + + i += 12; + // Compressed flags + + CompressedFlags flags = (CompressedFlags)Utils.BytesToUInt(block, i); + result.AppendFormat("{0,30}: {1,-10} {2,-29} [{3}]" + Environment.NewLine, + "CompressedFlags", + Utils.BytesToUInt(block, i), + "(" + (CompressedFlags)Utils.BytesToUInt(block, i) + ")", + "UInt"); + i += 4; + + // Owners ID + result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, + "OwnerID", + new UUID(block, i), + "UUID"); + i += 16; + + // Angular velocity + if ((flags & CompressedFlags.HasAngularVelocity) != 0) + { + result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, + "AngularVelocity", + new Vector3(block, i), + "Vector3"); + i += 12; + } + + // Parent ID + if ((flags & CompressedFlags.HasParent) != 0) + { + result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, + "ParentID", + (uint)(block[i++] + (block[i++] << 8) + + (block[i++] << 16) + (block[i++] << 24)), + "UInt"); + } + + // Tree data + if ((flags & CompressedFlags.Tree) != 0) + { + result.AppendFormat("{0,30}: {1,-2} {2,-37} [{3}]" + Environment.NewLine, + "TreeSpecies", + block[i++], + "(" + (Tree)block[i] + ")", + "Tree"); + } + + // Scratch pad + else if ((flags & CompressedFlags.ScratchPad) != 0) + { + int size = block[i++]; + byte[] scratch = new byte[size]; + Buffer.BlockCopy(block, i, scratch, 0, size); + result.AppendFormat("{0,30}: {1,-40} [ScratchPad[]]" + Environment.NewLine, + "ScratchPad", + Utils.BytesToHexString(scratch, String.Format("{0,30}", "Data"))); + i += size; + } + + // Floating text + if ((flags & CompressedFlags.HasText) != 0) + { + string text = String.Empty; + while (block[i] != 0) + { + text += (char)block[i]; + i++; + } + i++; + + // Floating text + result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, + "Text", + text, + "string"); + + // Text color + result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, + "TextColor", + new Color4(block, i, false), + "Color4"); + i += 4; + } + + // Media URL + if ((flags & CompressedFlags.MediaURL) != 0) + { + string text = String.Empty; + while (block[i] != 0) + { + text += (char)block[i]; + i++; + } + i++; + + result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, + "MediaURL", + text, + "string"); + } + + // Particle system + if ((flags & CompressedFlags.HasParticles) != 0) + { + Primitive.ParticleSystem p = new Primitive.ParticleSystem(block, i); + result.AppendLine(DecodeObjectParticleSystem("ParticleSystem", p)); + i += 86; + } + + // Extra parameters TODO: + Primitive prim = new Primitive(); + int extrapLen = prim.SetExtraParamsFromBytes(block, i); + i += extrapLen; + result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, + "ExtraParams[]", + extrapLen, + "byte[]"); + + //Sound data + if ((flags & CompressedFlags.HasSound) != 0) + { + result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, + "SoundID", + new UUID(block, i), + "UUID"); + i += 16; + + result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, + "SoundGain", + Utils.BytesToFloat(block, i), + "Float"); + i += 4; + + result.AppendFormat("{0,30}: {1,-2} {2,-37} [{3}]" + Environment.NewLine, + "SoundFlags", + block[i++], + "(" + (SoundFlags)block[i] + ")", + "SoundFlags"); + + result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, + "SoundRadius", + Utils.BytesToFloat(block, i), + "Float"); + i += 4; + } + + // Name values + if ((flags & CompressedFlags.HasNameValues) != 0) + { + string text = String.Empty; + while (block[i] != 0) + { + text += (char)block[i]; + i++; + } + i++; + + // Parse the name values + if (text.Length > 0) + { + string[] lines = text.Split('\n'); + NameValue[] nameValues = new NameValue[lines.Length]; + + for (int j = 0; j < lines.Length; j++) + { + if (!String.IsNullOrEmpty(lines[j])) + { + NameValue nv = new NameValue(lines[j]); + nameValues[j] = nv; + } + } + result.AppendLine(DecodeNameValue("NameValues", nameValues)); + } + } + + result.AppendFormat("{0,30}: {1,-2} {2,-37} [{3}]" + Environment.NewLine, + "PathCurve", + block[i], + "(" + (PathCurve)block[i++] + ")", + "PathCurve"); + + ushort pathBegin = Utils.BytesToUInt16(block, i); + i += 2; + result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, + "PathBegin", + Primitive.UnpackBeginCut(pathBegin), + "float"); + + ushort pathEnd = Utils.BytesToUInt16(block, i); + i += 2; + result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, + "PathEnd", + Primitive.UnpackEndCut(pathEnd), + "float"); + + result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, + "PathScaleX", + Primitive.UnpackPathScale(block[i++]), + "float"); + + result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, + "PathScaleY", + Primitive.UnpackPathScale(block[i++]), + "float"); + + result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, + "PathShearX", + Primitive.UnpackPathShear((sbyte)block[i++]), + "float"); + + result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, + "PathShearY", + Primitive.UnpackPathShear((sbyte)block[i++]), + "float"); + + result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, + "PathTwist", + Primitive.UnpackPathTwist((sbyte)block[i++]), + "float"); + + result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, + "PathTwistBegin", + Primitive.UnpackPathTwist((sbyte)block[i++]), + "float"); + + result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, + "PathRadiusOffset", + Primitive.UnpackPathTwist((sbyte)block[i++]), + "float"); + + result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, + "PathTaperX", + Primitive.UnpackPathTaper((sbyte)block[i++]), + "float"); + + result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, + "PathTaperY", + Primitive.UnpackPathTaper((sbyte)block[i++]), + "float"); + + result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, + "PathRevolutions", + Primitive.UnpackPathRevolutions(block[i++]), + "float"); + + result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, + "PathSkew", + Primitive.UnpackPathTwist((sbyte)block[i++]), + "float"); + + result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, + "ProfileCurve", + block[i++], + "float"); + + ushort profileBegin = Utils.BytesToUInt16(block, i); + i += 2; + result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, + "ProfileBegin", + Primitive.UnpackBeginCut(profileBegin), + "float"); + + ushort profileEnd = Utils.BytesToUInt16(block, i); + i += 2; + result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, + "ProfileEnd", + Primitive.UnpackEndCut(profileEnd), + "float"); + + ushort profileHollow = Utils.BytesToUInt16(block, i); + i += 2; + result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, + "ProfileHollow", + Primitive.UnpackProfileHollow(profileHollow), + "float"); + + int textureEntryLength = (int)Utils.BytesToUInt(block, i); + i += 4; + //prim.Textures = new Primitive.TextureEntry(block, i, textureEntryLength); + String s = DecodeTextureEntry("TextureEntry", new Primitive.TextureEntry(block, i, textureEntryLength)); + result.AppendLine(s); + i += textureEntryLength; + + // Texture animation + if ((flags & CompressedFlags.TextureAnimation) != 0) + { + i += 4; + string a = DecodeObjectTextureAnim("TextureAnimation", new Primitive.TextureAnimation(block, i)); + result.AppendLine(a); + } + + if ((flags & CompressedFlags.HasParticlesNew) != 0) + { + Primitive.ParticleSystem p = new Primitive.ParticleSystem(block, i); + result.AppendLine(DecodeObjectParticleSystem("ParticleSystemNEW", p)); + i += 94; + if ((p.PartDataFlags & Primitive.ParticleSystem.ParticleDataFlags.DataGlow) != 0) + i += 2; + if ((p.PartDataFlags & Primitive.ParticleSystem.ParticleDataFlags.DataBlend) != 0) + i += 2; + } + + return result.ToString(); + } + + private static string DecodeObjectData(string fieldName, object fieldData) + { + byte[] data = (byte[])fieldData; + if (data.Length == 1) + { + return String.Format("{0,30}: {1,2} {2,-38} [{3}]", + fieldName + " (Tree Species)", + fieldData, + //"(" + (Tree)(byte)fieldData + ")", + "(" + (Tree)data[0] + ")", + fieldData.GetType().Name); + } + else if (data.Length == 76) + { + /* TODO: these are likely useful packed fields, + * need to unpack them */ + Vector4 col = Vector4.Zero; + Vector3 offset = Vector3.Zero; + Vector3 vel = Vector3.Zero; + Vector3 acc = Vector3.Zero; + Quaternion q = Quaternion.Identity; + Vector3 angvel = Vector3.Zero; + + col.FromBytes(data, 0); + offset.FromBytes(data, 16); + vel.FromBytes(data, 28); + acc.FromBytes(data, 40); + q.FromBytes(data, 52, true); + angvel.FromBytes(data, 64); + + StringBuilder result = new StringBuilder(); + result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, + "ColisionPlane", + col, + "Vector4"); + result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, + "Offset", + offset, + "Vector3"); + result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, + "Velocity", + vel, + "Vector3"); + result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, + "Acceleration", + acc, + "Vector3"); + result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, + "rotation", + q, + "Quaternion"); + result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, + "Omega", + angvel, + "Vector3"); + return result.ToString(); + } + else if (data.Length == 60) + { + /* TODO: these are likely useful packed fields, + * need to unpack them */ + Vector3 offset = Vector3.Zero; + Vector3 vel = Vector3.Zero; + Vector3 acc = Vector3.Zero; + Quaternion q = Quaternion.Identity; + Vector3 angvel = Vector3.Zero; + + offset.FromBytes(data, 0); + vel.FromBytes(data, 12); + acc.FromBytes(data, 24); + q.FromBytes(data, 36, true); + angvel.FromBytes(data, 48); + + StringBuilder result = new StringBuilder(); + result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, + "Offset", + offset, + "Vector3"); + result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, + "Velocity", + vel, + "Vector3"); + result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, + "Acceleration", + acc, + "Vector3"); + result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, + "rotation", + q, + "Quaternion"); + result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, + "Omega", + angvel, + "Vector3"); + return result.ToString(); + } + else + { + return Utils.BytesToHexString((byte[])fieldData, String.Format("{0,30}", fieldName)); + } + } + + private static string DecodeObjectTextureAnim(string fieldName, object fieldData) + { + StringBuilder result = new StringBuilder(); + Primitive.TextureAnimation TextureAnim; + if (fieldData is Primitive.TextureAnimation) + TextureAnim = (Primitive.TextureAnimation)fieldData; + else + TextureAnim = new Primitive.TextureAnimation((byte[])fieldData, 0); + + result.AppendFormat("{0,30}", " " + Environment.NewLine); + GenericTypeDecoder(TextureAnim, ref result); + result.AppendFormat("{0,30}", ""); + + return result.ToString(); + } + + private static string DecodeEstateParameter(string fieldName, object fieldData) + { + byte[] bytes = (byte[])fieldData; + + if (bytes.Length == 17) + { + return String.Format("{0,30}: {1,-40} [UUID]", fieldName, new UUID((byte[])fieldData, 0)); + } + else + { + return String.Format("{0,30}: {1,-40} [Byte[]]", fieldName, Utils.BytesToString((byte[])fieldData)); + } + } + + private static string DecodeNameValue(string fieldName, object fieldData) + { + NameValue[] nameValues = null; + if (fieldData is NameValue[]) + nameValues = fieldData as NameValue[]; + else + { + string nameValue = Utils.BytesToString((byte[])fieldData); + if (nameValue.Length > 0) + { + string[] lines = nameValue.Split('\n'); + nameValues = new NameValue[lines.Length]; + + for (int i = 0; i < lines.Length; i++) + { + if (!String.IsNullOrEmpty(lines[i])) + { + NameValue nv = new NameValue(lines[i]); + nameValues[i] = nv; + } + } + } + } + StringBuilder result = new StringBuilder(); + result.AppendFormat("{0,30}", " " + Environment.NewLine); + if (nameValues != null) + { + for (int i = 0; i < nameValues.Length; i++) + { + result.AppendFormat( + "{0,30}: Name={1} Value={2} Class={3} Type={4} Sendto={5}" + Environment.NewLine, "NameValue", + nameValues[i].Name, nameValues[i].Value, nameValues[i].Class, nameValues[i].Type, nameValues[i].Sendto); + } + } + result.AppendFormat("{0,30}", ""); + return result.ToString(); + } + + private static string DecodeObjectExtraParams(string fieldName, object fieldData) + { + + byte[] data = (byte[])fieldData; + + int i = 0; + //int totalLength = 1; + + Primitive.FlexibleData Flexible = null; + Primitive.LightData Light = null; + Primitive.SculptData Sculpt = null; + Primitive.SculptData Mesh = null; + Primitive.ReflectionProbe rprobe = null; + Primitive.RenderMaterials RenderMaterials = null; + uint meshFlags = 0; + bool hasmeshFlags = false; + + byte extraParamCount = data[i++]; + + for (int k = 0; k < extraParamCount; k++) + { + ExtraParamType type = (ExtraParamType)Utils.BytesToUInt16(data, i); + i += 2; + + int paramLength = (int)Utils.BytesToUInt(data, i); + i += 4; + + if (type == ExtraParamType.Flexible) + Flexible = new Primitive.FlexibleData(data, i); + else if (type == ExtraParamType.Light) + Light = new Primitive.LightData(data, i); + else if (type == ExtraParamType.Sculpt) + Sculpt = new Primitive.SculptData(data, i); + else if (type == ExtraParamType.Mesh) + Mesh = new Primitive.SculptData(data, i); + else if (type == ExtraParamType.MeshFlag) + { + hasmeshFlags = true; + meshFlags = Utils.BytesToUInt(data, i); + } + else if (type == ExtraParamType.RenderMaterial) + { + RenderMaterials = new Primitive.RenderMaterials(data, i, paramLength); + } + else if (type == ExtraParamType.ReflectionProbe) + { + rprobe = new Primitive.ReflectionProbe(data, i); + } + + i += paramLength; + //totalLength += (int)paramLength + 6; + } + + StringBuilder result = new StringBuilder(); + result.AppendFormat("{0,30}", "" + Environment.NewLine); + if (Flexible != null) + { + result.AppendFormat("{0,30}", "" + Environment.NewLine); + GenericTypeDecoder(Flexible, ref result); + result.AppendFormat("{0,30}", "" + Environment.NewLine); + } + + if (Sculpt != null) + { + result.AppendFormat("{0,30}", "" + Environment.NewLine); + GenericTypeDecoder(Sculpt, ref result); + result.AppendFormat("{0,30}", "" + Environment.NewLine); + } + + if (Mesh != null) + { + result.AppendFormat("{0,30}", "" + Environment.NewLine); + GenericTypeDecoder(Mesh, ref result); + result.AppendFormat("{0,30}", "" + Environment.NewLine); + } + + if (Light != null) + { + result.AppendFormat("{0,30}", "" + Environment.NewLine); + GenericTypeDecoder(Light, ref result); + result.AppendFormat("{0,30}", "" + Environment.NewLine); + } + + if (hasmeshFlags) + { + result.AppendFormat("{0,30}", "" + Environment.NewLine); + result.AppendFormat("{0,30}", meshFlags.ToString() + Environment.NewLine); + result.AppendFormat("{0,30}", "" + Environment.NewLine); + } + if (rprobe != null) + { + result.AppendFormat("{0,30}", "" + Environment.NewLine); + GenericTypeDecoder(rprobe, ref result); + result.AppendFormat("{0,30}", "" + Environment.NewLine); + } + if (RenderMaterials != null) + { + result.AppendFormat("{0,30}", "" + Environment.NewLine); + GenericTypeDecoder(RenderMaterials, ref result); + result.AppendFormat("{0,30}", "" + Environment.NewLine); + } + + result.AppendFormat("{0,30}", ""); + return result.ToString(); + } + + private static string DecodeObjectParticleSystem(string fieldName, object fieldData) + { + StringBuilder result = new StringBuilder(); + Primitive.ParticleSystem ParticleSys; + if (fieldData is Primitive.ParticleSystem) + ParticleSys = (Primitive.ParticleSystem)fieldData; + else + ParticleSys = new Primitive.ParticleSystem((byte[])fieldData, 0); + + result.AppendFormat("{0,30}", "" + Environment.NewLine); + GenericTypeDecoder(ParticleSys, ref result); + result.AppendFormat("{0,30}", ""); + + return result.ToString(); + } + + private static void GenericTypeDecoder(object obj, ref StringBuilder result) + { + FieldInfo[] fields = obj.GetType().GetFields(); + + foreach (FieldInfo field in fields) + { + String special; + if (SpecialDecoder("a" + "." + "b" + "." + field.Name, + field.GetValue(obj), out special)) + { + result.AppendLine(special); + } + else + { + result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, + field.Name, + field.GetValue(obj), + field.FieldType.Name); + } + } + } + + private static string DecodeObjectPCode(string fieldName, object fieldData) + { + return String.Format("{0,30}: {1,-3} {2,-36} [PCode]", + fieldName, + fieldData, + "(" + (PCode)(byte)fieldData + ")"); + } + + private static string DecodeImageType(string fieldName, object fieldData) + { + return String.Format("{0,30}: {1,-3} {2,-36} [ImageType]", + fieldName, + fieldData, + "(" + (ImageType)(byte)fieldData + ")"); + } + + private static string DecodeImageCodec(string fieldName, object fieldData) + { + return String.Format("{0,30}: {1,-3} {2,-36} [ImageCodec]", + fieldName, + fieldData, + "(" + (ImageCodec)(byte)fieldData + ")"); + } + + private static string DecodeObjectMaterial(string fieldName, object fieldData) + { + return String.Format("{0,30}: {1,-3} {2,-36} [Material]", + fieldName, + fieldData, + "(" + (Material)(byte)fieldData + ")"); + } + + private static string DecodeObjectClickAction(string fieldName, object fieldData) + { + return String.Format("{0,30}: {1,-3} {2,-36} [ClickAction]", + fieldName, + fieldData, + "(" + (ClickAction)(byte)fieldData + ")"); + } + + private static string DecodeEventFlags(string fieldName, object fieldData) + { + return String.Format("{0,30}: {1,-3} {2,-36} [EventFlags]", + fieldName, + fieldData, + "(" + (DirectoryManager.EventFlags)(uint)fieldData + ")"); + } + + private static string DecodeDirQueryFlags(string fieldName, object fieldData) + { + return String.Format("{0,30}: {1,-10} {2,-29} [DirectoryManager.DirFindFlags]", + fieldName, + fieldData, + "(" + (DirectoryManager.DirFindFlags)(uint)fieldData + ")"); + } + + private static string DecodeDirClassifiedQueryFlags(string fieldName, object fieldData) + { + return String.Format("{0,30}: {1,-10} {2,-29} [ClassifiedQueryFlags]", + fieldName, + fieldData, + "(" + (DirectoryManager.ClassifiedQueryFlags)(uint)fieldData + ")"); + } + + private static string DecodeDirClassifiedFlags(string fieldName, object fieldData) + { + return String.Format("{0,30}: {1,-10} {2,-29} [ClassifiedFlags]", + fieldName, + fieldData, + "(" + (DirectoryManager.ClassifiedFlags)(byte)fieldData + ")"); + } + + private static string DecodeGroupPowers(string fieldName, object fieldData) + { + return String.Format("{0,30}: {1,-20} {2,-19} [GroupPowers]", + fieldName, + fieldData, + "(" + (GroupPowers)(ulong)fieldData + ")"); + } + + private static string DecodeParcelACL(string fieldName, object fieldData) + { + return String.Format("{0,30}: {1,-10} {2,-29} [AccessList]", + fieldName, + fieldData, + "(" + (AccessList)(uint)fieldData + ")"); + } + + private static string SearchTypeFlags(string fieldName, object fieldData) + { + return String.Format("{0,30}: {1,-10} {2,-29} [DirectoryManager.SearchTypeFlags]", + fieldName, + fieldData, + "(" + (DirectoryManager.SearchTypeFlags)(uint)fieldData + ")"); + } + + private static string DecodeCategory(string fieldName, object fieldData) + { + return String.Format("{0,30}: {1,-3} {2,-36} [ParcelCategory]", + fieldName, + fieldData, + "(" + fieldData + ")"); + } + + private static string DecodeObjectUpdateFlags(string fieldName, object fieldData) + { + return String.Format("{0,30}: {1,-10} {2,-29} [PrimFlags]", + fieldName, + fieldData, + "(" + (PrimFlags)(uint)fieldData + ")"); + } + + private static string DecodeTeleportFlags(string fieldName, object fieldData) + { + return String.Format("{0,30}: {1,-10} {2,-29} [TeleportFlags]", + fieldName, + fieldData, + "(" + (TeleportFlags)(uint)fieldData + ")"); + } + + private static string DecodeScriptControls(string fieldName, object fieldData) + { + return String.Format("{0,30}: {1,-10} {2,-29} [AgentManager.ControlFlags]", + fieldName, + (uint)fieldData, + "(" + (AgentManager.ControlFlags)(uint)fieldData + ")"); + } + + private static string DecodeColorField(string fieldName, object fieldData) + { + return String.Format("{0,30}: {1,-40} [Color4]", + fieldName, + fieldData.GetType().Name.Equals("Color4") ? (Color4)fieldData : new Color4((byte[])fieldData, 0, false)); + } + + private static string DecodeTimeStamp(string fieldName, object fieldData) + { + if (fieldData is Int32 && (int)fieldData > 0) + return String.Format("{0,30}: {1,-10} {2,-29} [{3}]", + fieldName, + fieldData, + "(" + Utils.UnixTimeToDateTime((int)fieldData) + ")", + fieldData.GetType().Name); + else if (fieldData is uint && (uint)fieldData > 0) + return String.Format("{0,30}: {1,-10} {2,-29} [{3}]", + fieldName, + fieldData, + "(" + Utils.UnixTimeToDateTime((uint)fieldData) + ")", + fieldData.GetType().Name); + else + return String.Format("{0,30}: {1,-40} [{2}]", + fieldName, + fieldData, + fieldData.GetType().Name); + } + + private static string DecodeBinaryBucket(string fieldName, object fieldData) + { + byte[] bytes = (byte[])fieldData; + string bucket = String.Empty; + if (bytes.Length == 1) + { + bucket = String.Format("{0}", bytes[0]); + } + else if (bytes.Length == 17) + { + bucket = String.Format("{0,-36} {1} ({2})", + new UUID(bytes, 1), + bytes[0], + (AssetType)(sbyte)bytes[0]); + } + else if (bytes.Length == 16) // the folder ID for the asset to be stored into if we accept an inventory offer + { + bucket = new UUID(bytes, 0).ToString(); + } + else + { + bucket = Utils.BytesToString(bytes); // we'll try a string lastly + } + + return String.Format("{0,30}: {1,-40} [Byte[{2}]]", fieldName, bucket, bytes.Length); + } + + private static string DecodeBinaryToHexString(string fieldName, object fieldData) + { + return String.Format("{0,30}", + Utils.BytesToHexString((byte[])fieldData, + String.Format("{0,30}", fieldName))); + } + + private static string DecodeWearableType(string fieldName, object fieldData) + { + return String.Format("{0,30}: {1,-2} {2,-37} [WearableType]", + fieldName, + (byte)fieldData, + "(" + (WearableType)fieldData + ")"); + } + + private static string DecodeInventoryType(string fieldName, object fieldData) + { + return String.Format("{0,30}: {1,-2} {2,-37} [AssetType]", + fieldName, + (sbyte)fieldData, + "(" + (AssetType)(sbyte)fieldData + ")"); + } + + private static string DecodeInventorySort(string fieldName, object fieldData) + { + return String.Format("{0,30}: {1,-2} {2,-37} [InventorySortOrder]", + fieldName, + fieldData, + "(" + (InventorySortOrder)(int)fieldData + ")"); + } + + private static string DecodeInventoryInvType(string fieldName, object fieldData) + { + return String.Format("{0,30}: {1,-2} {2,-37} [InventoryType]", + fieldName, + (sbyte)fieldData, + "(" + (InventoryType)fieldData + ")"); + } + + private static string DecodeFolderType(string fieldName, object fieldData) + { + return String.Format("{0,30}: {1,-2} {2,-37} [Folderype]", + fieldName, + (sbyte)fieldData, + "(" + (FolderType)fieldData + ")"); + } + + private static string DecodeInventoryFlags(string fieldName, object fieldData) + { + return String.Format("{0,30}: {1,-2} {2,-37} [InventoryItemFlags]", + fieldName, + (uint)fieldData, + "(" + (InventoryItemFlags)(uint)fieldData + ")"); + } + + private static string DecodeObjectSaleType(string fieldName, object fieldData) + { + return String.Format("{0,30}: {1,-2} {2,-37} [SaleType]", + fieldName, + (byte)fieldData, + "(" + (SaleType)fieldData + ")"); + } + + private static string DecodeRegionFlags(string fieldName, object fieldData) + { + return String.Format("{0,30}: {1,-2} {2,-37} [RegionFlags]", + fieldName, + fieldData, + "(" + (RegionFlags)(uint)fieldData + ")"); + } + + private static string DecodeTransferParams(string fieldName, object fieldData) + { + byte[] paramData = (byte[])fieldData; + StringBuilder result = new StringBuilder(); + result.AppendLine(" "); + if (paramData.Length == 20) + { + result.AppendFormat("{0,30}: {1,-40} [UUID]" + Environment.NewLine, + "AssetID", + new UUID(paramData, 0)); + + result.AppendFormat("{0,30}: {1,-2} {2,-37} [AssetType]" + Environment.NewLine, + "AssetType", + (sbyte)paramData[16], + "(" + (AssetType)(sbyte)paramData[16] + ")"); + + } + else if (paramData.Length == 100) + { + //UUID agentID = new UUID(info.TransferInfo.Params, 0); + result.AppendFormat("{0,30}: {1,-40} [UUID]" + Environment.NewLine, + "AgentID", + new UUID(paramData, 0)); + + //UUID sessionID = new UUID(info.TransferInfo.Params, 16); + result.AppendFormat("{0,30}: {1,-40} [UUID]" + Environment.NewLine, + "SessionID", + new UUID(paramData, 16)); + //UUID ownerID = new UUID(info.TransferInfo.Params, 32); + result.AppendFormat("{0,30}: {1,-40} [UUID]" + Environment.NewLine, + "OwnerID", + new UUID(paramData, 32)); + //UUID taskID = new UUID(info.TransferInfo.Params, 48); + result.AppendFormat("{0,30}: {1,-40} [UUID]" + Environment.NewLine, + "TaskID", + new UUID(paramData, 48)); + //UUID itemID = new UUID(info.TransferInfo.Params, 64); + result.AppendFormat("{0,30}: {1,-40} [UUID]" + Environment.NewLine, + "ItemID", + new UUID(paramData, 64)); + + result.AppendFormat("{0,30}: {1,-40} [UUID]" + Environment.NewLine, + "AssetID", + new UUID(paramData, 80)); + + result.AppendFormat("{0,30}: {1,-2} {2,-37} [AssetType]" + Environment.NewLine, + "AssetType", + (sbyte)paramData[96], + "(" + (AssetType)(sbyte)paramData[96] + ")"); + } + else + { + Console.WriteLine("Oh Poop!"); + } + + result.Append(""); + + return result.ToString(); + } + + private static string DecodeTransferChannelType(string fieldName, object fieldData) + { + return String.Format("{0,30}: {1,-2} {2,-37} [ChannelType]", + fieldName, + fieldData, + "(" + (ChannelType)(int)fieldData + ")"); + } + + private static string DecodeTransferSourceType(string fieldName, object fieldData) + { + return String.Format("{0,30}: {1,-2} {2,-37} [SourceType]", + fieldName, + fieldData, + "(" + (SourceType)(int)fieldData + ")"); + } + + private static string DecodeTransferTargetType(string fieldName, object fieldData) + { + return String.Format("{0,30}: {1,-2} {2,-37} [TargetType]", + fieldName, + fieldData, + "(" + (TargetType)(int)fieldData + ")"); + } + + private static string DecodeMapRequestFlags(string fieldName, object fieldData) + { + return String.Format("{0,30}: {1,-2} {2,-37} [GridLayerType]", + fieldName, + fieldData, + "(" + (GridLayerType)(uint)fieldData + ")"); + } + + private static string DecodeGridItemType(string fieldName, object fieldData) + { + return String.Format("{0,30}: {1,-2} {2,-37} [GridItemType]", + fieldName, + fieldData, + "(" + (GridItemType)(uint)fieldData + ")"); + + } + + private static string DecodeLayerDataType(string fieldName, object fieldData) + { + return String.Format("{0,30}: {1,-2} {2,-37} [LayerType]", + fieldName, + fieldData, + "(" + (TerrainPatch.LayerType)(byte)fieldData + ")"); + } + + private static string DecodeMapAccess(string fieldName, object fieldData) + { + return String.Format("{0,30}: {1,-2} {2,-37} [SimAccess]", + fieldName, + fieldData, + "(" + (SimAccess)(byte)fieldData + ")"); + } + + private static string DecodeSimAccess(string fieldName, object fieldData) + { + return String.Format("{0,30}: {1,-2} {2,-37} [SimAccess]", + fieldName, + (byte)fieldData, + "(" + (SimAccess)fieldData + ")"); + } + + private static string DecodeAttachedSoundFlags(string fieldName, object fieldData) + { + return String.Format("{0,30}: {1,-2} {2,-37} [SoundFlags]", + fieldName, + (byte)fieldData, + "(" + (SoundFlags)fieldData + ")"); + } + + + private static string DecodeChatSourceType(string fieldName, object fieldData) + { + return String.Format("{0,30}: {1,-2} {2,-37} [SourceType]", + fieldName, + fieldData, + "(" + (SourceType)(byte)fieldData + ")"); + } + + private static string DecodeChatChatType(string fieldName, object fieldData) + { + return String.Format("{0,30}: {1,-2} {2,-37} [ChatType]", + fieldName, + (byte)fieldData, + "(" + (ChatType)fieldData + ")"); + } + + private static string DecodeChatAudible(string fieldName, object fieldData) + { + return String.Format("{0,30}: {1,-2} {2,-37} [ChatAudibleLevel]", + fieldName, + (byte)fieldData, + "(" + (ChatAudibleLevel)(byte)fieldData + ")"); + } + + private static string DecodeImageData(string fieldName, object fieldData) + { + return String.Format("{0,10}", + Utils.BytesToHexString((byte[])fieldData, + String.Format("{0,30}", fieldName))); + } + + private static string DecodeTerseTextureEntry(string fieldName, object fieldData) + { + byte[] block = (byte[])fieldData; + + Primitive.TextureEntry te = new Primitive.TextureEntry(block, 4, block.Length - 4); + + StringBuilder result = new StringBuilder(); + + result.AppendFormat("{0,30}", " " + Environment.NewLine); + if (te.DefaultTexture != null) + { + result.AppendFormat("{0,30}", " " + Environment.NewLine); + GenericFieldsDecoder(te.DefaultTexture, ref result); + GenericPropertiesDecoder(te.DefaultTexture, ref result); + result.AppendFormat("{0,30}", " " + Environment.NewLine); + } + result.AppendFormat("{0,30}", " " + Environment.NewLine); + for (int i = 0; i < te.FaceTextures.Length; i++) + { + if (te.FaceTextures[i] != null) + { + result.AppendFormat("{0,30}[{1}]" + Environment.NewLine, "FaceTexture", i); + GenericFieldsDecoder(te.FaceTextures[i], ref result); + GenericPropertiesDecoder(te.FaceTextures[i], ref result); + } + } + result.AppendFormat("{0,30}", " " + Environment.NewLine); + result.AppendFormat("{0,30}", ""); + + return result.ToString(); + } + + private static string DecodeTextureEntry(string fieldName, object fieldData) + { + Primitive.TextureEntry te; + if (fieldData is Primitive.TextureEntry) + te = (Primitive.TextureEntry)fieldData; + else + { + byte[] tebytes = (byte[])fieldData; + te = new Primitive.TextureEntry(tebytes, 0, tebytes.Length); + } + + StringBuilder result = new StringBuilder(); + + result.AppendFormat("{0,30}", " " + Environment.NewLine); + if (te.DefaultTexture != null) + { + result.AppendFormat("{0,30}", " " + Environment.NewLine); + GenericFieldsDecoder(te.DefaultTexture, ref result); + GenericPropertiesDecoder(te.DefaultTexture, ref result); + result.AppendFormat("{0,30}", " " + Environment.NewLine); + } + result.AppendFormat("{0,30}", " " + Environment.NewLine); + for (int i = 0; i < te.FaceTextures.Length; i++) + { + if (te.FaceTextures[i] != null) + { + result.AppendFormat("{0,30}[{1}]" + Environment.NewLine, "FaceTexture", i); + GenericFieldsDecoder(te.FaceTextures[i], ref result); + GenericPropertiesDecoder(te.FaceTextures[i], ref result); + } + } + result.AppendFormat("{0,30}", " " + Environment.NewLine); + result.AppendFormat("{0,30}", ""); + + return result.ToString(); + } + + private static void GenericFieldsDecoder(object obj, ref StringBuilder result) + { + Type parcelType = obj.GetType(); + FieldInfo[] fields = parcelType.GetFields(); + foreach (FieldInfo field in fields) + { + String special; + if (SpecialDecoder("a" + "." + "b" + "." + field.Name, + field.GetValue(obj), out special)) + { + result.AppendLine(special); + } + else + { + result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, + field.Name, + field.GetValue(obj), + field.FieldType.Name); + } + } + } + + private static void GenericPropertiesDecoder(object obj, ref StringBuilder result) + { + Type parcelType = obj.GetType(); + PropertyInfo[] propertyInfos = parcelType.GetProperties(); + foreach (PropertyInfo property in propertyInfos) + { + String special; + if (SpecialDecoder("a" + "." + "b" + "." + property.Name, + property.GetValue(obj, null), out special)) + { + result.AppendLine(special); + } + else + { + result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, + property.Name, + property.GetValue(obj, null), + property.PropertyType.Name); + } + } + } + + private static string DecodeDialog(string fieldName, object fieldData) + { + return String.Format("{0,30}: {1,-2} {2,-37} [{3}]", + fieldName, + (byte)fieldData, + "(" + (InstantMessageDialog)fieldData + ")", + fieldData.GetType().Name); + } + + private static string DecodeControlFlags(string fieldName, object fieldData) + { + return String.Format("{0,30}: {1,-10} {2,-29} [{3}]", + fieldName, + fieldData, + "(" + (AgentManager.ControlFlags)(uint)fieldData + ")", + fieldData.GetType().Name); + } + + private static string DecodePermissionMask(string fieldName, object fieldData) + { + return String.Format("{0,30}: {1,-10} {2,-29} [{3}]", + fieldName, + (uint)fieldData, + "(" + (PermissionMask)fieldData + ")", + fieldData.GetType().Name); + } + + private static string DecodeViewerEffectTypeData(string fieldName, object fieldData) + { + byte[] data = (byte[])fieldData; + StringBuilder sb = new StringBuilder(); + if (data.Length == 56 || data.Length == 57) + { + UUID sourceAvatar = new UUID(data, 0); + UUID targetObject = new UUID(data, 16); + Vector3d targetPos = new Vector3d(data, 32); + sb.AppendFormat("{0,30}: {1,-40} [UUID]" + Environment.NewLine, fieldName, "Source AvatarID=" + sourceAvatar); + sb.AppendFormat("{0,30}: {1,-40} [UUID]" + Environment.NewLine, fieldName, "Target ObjectID=" + targetObject); + + + float lx, ly; + Helpers.GlobalPosToRegionHandle((float)targetPos.X, (float)targetPos.Y, out lx, out ly); + + sb.AppendFormat("{0,30}: {1,-40} [Vector3d]", fieldName, targetPos); + + if (data.Length == 57) + { + sb.AppendLine(); + sb.AppendFormat("{0,30}: {1,-17} {2,-22} [Byte]", fieldName, "Point At Type=" + data[56], + "(" + (PointAtType)data[56] + ")"); + } + + return sb.ToString(); + } + else + { + return String.Format("{0,30}: (No Decoder) Length={1}" + Environment.NewLine, fieldName, data.Length) + Utils.BytesToHexString(data, String.Format("{0,30}", "")); + } + } + + private static string DecodeAgentState(string fieldName, object fieldData) + { + return String.Format("{0,30}: {1,-2} {2,-37} [AgentState]", + fieldName, + fieldData, + "(" + (AgentState)(byte)fieldData + ")"); + } + + private static string DecodeAgentFlags(string fieldName, object fieldData) + { + return String.Format("{0,30}: {1,-2} {2,-37} [AgentFlags]", + fieldName, + fieldData, + "(" + (AgentFlags)(byte)fieldData + ")"); + } + + private static string DecodeObjectState(string fieldName, object fieldData) + { + return String.Format("{0,30}: {1,-2} {2,-37} [AttachmentPoint]", + fieldName, + fieldData, + "(" + (AttachmentPoint)(byte)fieldData + ")"); + } + + private static string DecodeViewerEffectType(string fieldName, object fieldData) + { + return String.Format("{0,30}: {1,-2} {2,-37} [{3}]", + fieldName, + fieldData, + "(" + (EffectType)(byte)fieldData + ")", + fieldData.GetType().Name); + } + + private static string DecodeAnimToConst(string fieldName, object fieldData) + { + string animConst = "UUID"; + Dictionary animsDict = Animations.ToDictionary(); + if (animsDict.ContainsKey((UUID)fieldData)) + animConst = animsDict[(UUID)fieldData]; + return String.Format("{0,30}: {1,-40} [{2}]", + fieldName, + fieldData, + animConst); + } + #endregion + + /// + /// Creates a formatted string containing the values of a Packet + /// + /// The Packet + /// A formatted string of values of the nested items in the Packet object + public static string PacketToString(Packet packet) + { + StringBuilder result = new StringBuilder(); + + result.AppendFormat("Packet Type: {0}" + Environment.NewLine, packet.Type); + result.AppendLine("[Packet Header]"); + // payload + result.AppendFormat("Sequence: {0}" + Environment.NewLine, packet.Header.Sequence); + result.AppendFormat(" Options: {0}" + Environment.NewLine, InterpretOptions(packet.Header)); + result.AppendLine(); + + result.AppendLine("[Packet Payload]"); + + FieldInfo[] fields = packet.GetType().GetFields(); + + for (int i = 0; i < fields.Length; i++) + { + // we're not interested in any of these here + if (fields[i].Name == "Type" || fields[i].Name == "Header" || + fields[i].Name == "HasVariableBlocks" || + fields[i].Name == "NeedValidateIDs") + continue; + + if (fields[i].FieldType.IsArray) + { + result.AppendFormat("{0,30} []" + Environment.NewLine, "-- " + fields[i].Name + " --"); + RecursePacketArray(fields[i], packet, ref result); + } + else + { + result.AppendFormat("{0,30}" + Environment.NewLine, "-- " + fields[i].Name + " --"); + RecursePacketField(fields[i], packet, ref result); + } + } + return result.ToString(); + } + + public static string InterpretOptions(Header header) + { + return "[" + + (header.AppendedAcks ? "Ack" : " ") + + " " + + (header.Resent ? "Res" : " ") + + " " + + (header.Reliable ? "Rel" : " ") + + " " + + (header.Zerocoded ? "Zer" : " ") + + "]" + ; + } + + private static void RecursePacketArray(FieldInfo fieldInfo, object packet, ref StringBuilder result) + { + var packetDataObject = fieldInfo.GetValue(packet); + int k = -1; + foreach (object nestedArrayRecord in packetDataObject as Array) + { + FieldInfo[] fields = nestedArrayRecord.GetType().GetFields(); + ++k; + for (int i = 0; i < fields.Length; i++) + { + String special; + if (SpecialDecoder(packet.GetType().Name + "." + fieldInfo.Name + "." + fields[i].Name, + fields[i].GetValue(nestedArrayRecord), out special)) + { + result.AppendLine(special); + } + else if (fields[i].FieldType.IsArray) // default for an array (probably a byte[]) + { + result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, + fields[i].Name + "[" + k.ToString() + "]", + Utils.BytesToString((byte[])fields[i].GetValue(nestedArrayRecord)), + /*fields[i].GetValue(nestedArrayRecord).GetType().Name*/ "String"); + } + else // default for a field + { + result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, + fields[i].Name + "[" + k.ToString() + "]", + fields[i].GetValue(nestedArrayRecord), + fields[i].GetValue(nestedArrayRecord).GetType().Name); + } + } + + // Handle Properties + foreach (PropertyInfo propertyInfo in nestedArrayRecord.GetType().GetProperties()) + { + if (propertyInfo.Name.Equals("Length")) + continue; + + string special; + if (SpecialDecoder(packet.GetType().Name + "." + fieldInfo.Name + "." + propertyInfo.Name, + propertyInfo.GetValue(nestedArrayRecord, null), + out special)) + { + result.AppendLine(special); + } + else + { + var p = propertyInfo.GetValue(nestedArrayRecord, null); + /* Leave the c for now at the end, it signifies something useful that still needs to be done i.e. a decoder written */ + result.AppendFormat("{0, 30}: {1,-40} [{2}]c" + Environment.NewLine, + propertyInfo.Name, + Utils.BytesToString((byte[])propertyInfo.GetValue(nestedArrayRecord, null)), + propertyInfo.PropertyType.Name); + } + } + result.AppendFormat("{0,32}" + Environment.NewLine, "***"); + } + } + + private static void RecursePacketField(FieldInfo fieldInfo, object packet, ref StringBuilder result) + { + object packetDataObject = fieldInfo.GetValue(packet); + + // handle Fields + foreach (FieldInfo packetValueField in fieldInfo.GetValue(packet).GetType().GetFields()) + { + string special; + if (SpecialDecoder(packet.GetType().Name + "." + fieldInfo.Name + "." + packetValueField.Name, + packetValueField.GetValue(packetDataObject), + out special)) + { + result.AppendLine(special); + } + else if (packetValueField.FieldType.IsArray) + { + result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, + packetValueField.Name, + Utils.BytesToString((byte[])packetValueField.GetValue(packetDataObject)), + /*packetValueField.FieldType.Name*/ "String"); + } + else + { + result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, + packetValueField.Name, packetValueField.GetValue(packetDataObject), packetValueField.FieldType.Name); + + } + } + + // Handle Properties + foreach (PropertyInfo propertyInfo in packetDataObject.GetType().GetProperties()) + { + if (propertyInfo.Name.Equals("Length")) + continue; + + string special; + if (SpecialDecoder(packet.GetType().Name + "." + fieldInfo.Name + "." + propertyInfo.Name, + propertyInfo.GetValue(packetDataObject, null), + out special)) + { + result.AppendLine(special); + } + else if (propertyInfo.GetValue(packetDataObject, null).GetType() == typeof(byte[])) + { + result.AppendFormat("{0, 30}: {1,-40} [{2}]" + Environment.NewLine, + propertyInfo.Name, + Utils.BytesToString((byte[])propertyInfo.GetValue(packetDataObject, null)), + propertyInfo.PropertyType.Name); + } + else + { + result.AppendFormat("{0, 30}: {1,-40} [{2}]" + Environment.NewLine, + propertyInfo.Name, + propertyInfo.GetValue(packetDataObject, null), + propertyInfo.PropertyType.Name); + } + } + } + + private static bool SpecialDecoder(string decoderKey, object fieldData, out string result) + { + result = string.Empty; + string[] keys = decoderKey.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries); + string[] keyList = { decoderKey, decoderKey.Replace("Packet", ""), keys[1] + "." + keys[2], keys[2] }; + foreach (string key in keyList) + { + + bool ok = true; + if (fieldData is byte[]) + { + byte[] fd = (byte[])fieldData; + ok = fd.Length > 0; + if (!ok) + { + // bypass the decoder since we were passed an empty byte array + result = String.Format("{0,30}:", keys[2]); + return true; + } + } + + if (ok && Callbacks.ContainsKey(key)) // fieldname e.g: Plane + { + foreach (CustomPacketDecoder decoder in Callbacks[key]) + result = decoder(keys[2], fieldData); + return true; + } + } + return false; + } + + /// + /// Decode an IMessage object into a beautifully formatted string + /// + /// The IMessage object + /// Recursion level (used for indenting) + /// A formatted string containing the names and values of the source object + public static string MessageToString(object message, int recurseLevel) + { + if (message == null) + return String.Empty; + + StringBuilder result = new StringBuilder(); + // common/custom types + if (recurseLevel <= 0) + { + result.AppendFormat("Message Type: {0}" + Environment.NewLine, message.GetType().Name); + } + else + { + string pad = " +--".PadLeft(recurseLevel + 3); + result.AppendFormat("{0} {1}" + Environment.NewLine, pad, message.GetType().Name); + } + + recurseLevel++; + + foreach (FieldInfo messageField in message.GetType().GetFields()) + { + // an abstract message class + if (messageField.FieldType.IsAbstract) + { + result.AppendLine(MessageToString(messageField.GetValue(message), recurseLevel)); + } + // a byte array + else if (messageField.GetValue(message) != null && messageField.GetValue(message).GetType() == typeof(Byte[])) + { + result.AppendFormat("{0, 30}:" + Environment.NewLine, messageField.Name); + + result.AppendFormat("{0}" + Environment.NewLine, + Utils.BytesToHexString((byte[])messageField.GetValue(message), + String.Format("{0,30}", ""))); + } + + // an array of class objects + else if (messageField.FieldType.IsArray) + { + var messageObjectData = messageField.GetValue(message); + result.AppendFormat("-- {0} --" + Environment.NewLine, messageField.FieldType.Name); + foreach (object nestedArrayObject in messageObjectData as Array) + { + if (nestedArrayObject == null) + { + result.AppendFormat("{0,30}" + Environment.NewLine, "-- null --"); + continue; + } + else + { + result.AppendFormat("{0,30}" + Environment.NewLine, "-- " + nestedArrayObject.GetType().Name + " --"); + } + foreach (FieldInfo nestedField in nestedArrayObject.GetType().GetFields()) + { + if (nestedField.FieldType.IsEnum) + { + result.AppendFormat("{0,30}: {1,-10} {2,-29} [{3}]" + Environment.NewLine, + nestedField.Name, + Enum.Format(nestedField.GetValue(nestedArrayObject).GetType(), + nestedField.GetValue(nestedArrayObject), "D"), + "(" + nestedField.GetValue(nestedArrayObject) + ")", + nestedField.GetValue(nestedArrayObject).GetType().Name); + } + else if (nestedField.FieldType.IsInterface) + { + result.AppendLine(MessageToString(nestedField.GetValue(nestedArrayObject), recurseLevel)); + } + else + { + result.AppendFormat("{0, 30}: {1,-40} [{2}]" + Environment.NewLine, + nestedField.Name, + nestedField.GetValue(nestedArrayObject), + nestedField.FieldType.Name); + } + } + } + } + else + { + if (messageField.FieldType.IsEnum) + { + result.AppendFormat("{0,30}: {1,-2} {2,-37} [{3}]" + Environment.NewLine, + messageField.Name, + Enum.Format(messageField.GetValue(message).GetType(), + messageField.GetValue(message), "D"), + "(" + messageField.GetValue(message) + ")", + messageField.FieldType.Name); + } + else if (messageField.FieldType.IsInterface) + { + result.AppendLine(MessageToString(messageField.GetValue(message), recurseLevel)); + } + else + { + result.AppendFormat("{0, 30}: {1,-40} [{2}]" + Environment.NewLine, + messageField.Name, messageField.GetValue(message), messageField.FieldType.Name); + } + } + } + + return result.ToString(); + } + } +} diff --git a/OpenMetaverse/Primitives/Primitive.cs b/OpenMetaverse/Primitives/Primitive.cs index cbccd7ec..3a76ad3c 100644 --- a/OpenMetaverse/Primitives/Primitive.cs +++ b/OpenMetaverse/Primitives/Primitive.cs @@ -33,11 +33,17 @@ public partial class Primitive : IEquatable { // Used for packing and unpacking parameters protected const float CUT_QUANTA = 0.00002f; + protected const float CUT_QUANTAINV = 1.0f / CUT_QUANTA; protected const float SCALE_QUANTA = 0.01f; + protected const float SCALE_QUANTAINV = 1.0f/ SCALE_QUANTA; protected const float SHEAR_QUANTA = 0.01f; + protected const float SHEAR_QUANTAINV = 1.0f / SHEAR_QUANTA; protected const float TAPER_QUANTA = 0.01f; + protected const float TAPER_QUANTAINV = 1.0f / TAPER_QUANTA; protected const float REV_QUANTA = 0.015f; + protected const float REV_QUANTAINV = 1.0f / REV_QUANTA; protected const float HOLLOW_QUANTA = 0.00002f; + protected const float HOLLOW_QUANTAINV = 1.0f / HOLLOW_QUANTA; #region Subclasses @@ -129,7 +135,7 @@ public Vector2 PathBeginScale { get { - Vector2 begin = new Vector2(1f, 1f); + Vector2 begin = new(1f, 1f); if (PathScaleX > 1f) begin.X = 2f - PathScaleX; if (PathScaleY > 1f) @@ -143,7 +149,7 @@ public Vector2 PathEndScale { get { - Vector2 end = new Vector2(1f, 1f); + Vector2 end = new(1f, 1f); if (PathScaleX < 1f) end.X = PathScaleX; if (PathScaleY < 1f) @@ -267,14 +273,15 @@ public byte[] GetBytes() /// public OSD GetOSD() { - OSDMap map = new OSDMap(); - - map["simulate_lod"] = OSD.FromInteger(Softness); - map["gravity"] = OSD.FromReal(Gravity); - map["air_friction"] = OSD.FromReal(Drag); - map["wind_sensitivity"] = OSD.FromReal(Wind); - map["tension"] = OSD.FromReal(Tension); - map["user_force"] = OSD.FromVector3(Force); + OSDMap map = new() + { + ["simulate_lod"] = OSD.FromInteger(Softness), + ["gravity"] = OSD.FromReal(Gravity), + ["air_friction"] = OSD.FromReal(Drag), + ["wind_sensitivity"] = OSD.FromReal(Wind), + ["tension"] = OSD.FromReal(Tension), + ["user_force"] = OSD.FromVector3(Force) + }; return map; } @@ -382,13 +389,14 @@ public byte[] GetBytes() public OSD GetOSD() { - OSDMap map = new OSDMap(); - - map["color"] = OSD.FromColor4(Color); - map["intensity"] = OSD.FromReal(Intensity); - map["radius"] = OSD.FromReal(Radius); - map["cutoff"] = OSD.FromReal(Cutoff); - map["falloff"] = OSD.FromReal(Falloff); + OSDMap map = new() + { + ["color"] = OSD.FromColor4(Color), + ["intensity"] = OSD.FromReal(Intensity), + ["radius"] = OSD.FromReal(Radius), + ["cutoff"] = OSD.FromReal(Cutoff), + ["falloff"] = OSD.FromReal(Falloff) + }; return map; } @@ -485,10 +493,11 @@ public byte[] GetBytes() public OSD GetOSD() { - OSDMap map = new OSDMap(); - - map["texture"] = OSD.FromUUID(LightTexture); - map["params"] = OSD.FromVector3(Params); + OSDMap map = new() + { + ["texture"] = OSD.FromUUID(LightTexture), + ["params"] = OSD.FromVector3(Params) + }; return map; } @@ -519,7 +528,7 @@ public override int GetHashCode() /// public override string ToString() { - return String.Format("LightTexture: {0} Params; {1]", LightTexture, Params); + return String.Format("LightTexture: {0} Params; {1}", LightTexture, Params); } } @@ -591,10 +600,11 @@ public byte[] GetBytes() public OSD GetOSD() { - OSDMap map = new OSDMap(); - - map["texture"] = OSD.FromUUID(SculptTexture); - map["type"] = OSD.FromInteger(type); + OSDMap map = new() + { + ["texture"] = OSD.FromUUID(SculptTexture), + ["type"] = OSD.FromInteger(type) + }; return map; } @@ -621,6 +631,236 @@ public override int GetHashCode() } /// + /// Information on the ReflectionProbe properties of a primitive + /// + public class ReflectionProbe + { + /// + /// Default constructor + /// + public ReflectionProbe() + { + } + + public float Ambiance = 0; + public float ClipDistance = 0; + public byte Flags = 0; + /// + /// + /// + /// + /// + public ReflectionProbe(byte[] data, int pos) + { + if (data.Length - pos >= 9) + { + Ambiance = Utils.Clamp(Utils.BytesToFloat(data, pos), 0, 1.0f); + ClipDistance = Utils.Clamp(Utils.BytesToFloat(data, pos + 4), 0, 1024f); + Flags = data[pos + 8]; + } + } + + /// + /// + /// + /// + public byte[] GetBytes() + { + byte[] data = new byte[9]; + Utils.FloatToBytes(Ambiance, data, 0); + Utils.FloatToBytes(ClipDistance, data, 4); + data[8] = Flags; + return data; + } + + public OSD GetOSD() + { + OSDMap map = new() + { + ["ambiance"] = OSD.FromReal(Ambiance), + ["clip_distance"] = OSD.FromReal(ClipDistance), + ["flags"] = OSD.FromInteger(Flags) + }; + return map; + } + + public static ReflectionProbe FromOSD(OSD osd) + { + ReflectionProbe probe = new ReflectionProbe(); + + if (osd.Type == OSDType.Map) + { + OSDMap map = (OSDMap)osd; + + probe.Ambiance = (float)map["ambiance"].AsReal(); + probe.ClipDistance = (float)map["clip_distance"].AsReal(); + probe.Flags = (byte)map["flags"].AsInteger(); + } + + return probe; + } + + public override int GetHashCode() + { + return Ambiance.GetHashCode() ^ ClipDistance.GetHashCode() ^ (int)Flags; + } + + /// + /// + /// + /// + public override string ToString() + { + return String.Format("ReflectionProbe: amb {0} clip {1} flags {2}", Ambiance, ClipDistance, Flags); + } + } + + /// + /// Information on the RenderMaterial properties of a primitive + /// + public class RenderMaterials + { + public struct RenderMaterialEntry : IComparable + { + public byte te_index; + public UUID id; + public int CompareTo(RenderMaterialEntry other) + { + return te_index.CompareTo(other.te_index); + } + } + + public struct RenderMaterialOverrideEntry : IComparable + { + public byte te_index; + public string data; + public int CompareTo(RenderMaterialEntry other) + { + return te_index.CompareTo(other.te_index); + } + } + + public RenderMaterialEntry[] entries = null; + public RenderMaterialOverrideEntry[] overrides = null; + + /// + /// Default constructor + /// + public RenderMaterials() + { + } + + /// + /// + /// + /// + /// + public RenderMaterials(byte[] data, int pos, int size) + { + if (size > 17) + { + int count = data[pos]; + ++pos; + if (size >= 1 + 17 * count) + { + entries = new RenderMaterialEntry[count]; + for (int i = 0; i < count; ++i) + { + entries[i].te_index = data[pos++]; + entries[i].id = new UUID(data, pos); + pos += 16; + } + } + } + } + + /// + /// + /// + /// + public byte[] GetBytes() + { + if (entries == null || entries.Length == 0) + { + return new byte[] {0}; + } + byte[] data = new byte[1 + 17 * entries.Length]; + data[0] = (byte)entries.Length; + int pos = 1; + for (int i = 0; i < entries.Length; ++i) + { + data[pos++] = entries[i].te_index; + entries[i].id.ToBytes(data, pos); + pos += 16; + } + return data; + } + + public OSD GetOSD() + { + OSDArray eMaterials = new OSDArray(); + if(entries != null) + { + for(int i = 0; i < entries.Length;++i) + { + OSDMap map = new OSDMap() + { + ["te_idx"] = OSD.FromInteger(entries[i].te_index), + ["id"] = OSD.FromUUID(entries[i].id) + }; + eMaterials[i] = map; + } + } + return eMaterials; + } + + public static RenderMaterials FromOSD(OSD osd) + { + RenderMaterials rm = new(); + try + { + if (osd.Type == OSDType.Array) + { + OSDArray mra = (OSDArray)osd; + if(mra.Count > 0) + { + RenderMaterialEntry[] entries = new RenderMaterialEntry[mra.Count]; + for(int i = 0; i < mra.Count; ++i) + { + OSDMap map = (OSDMap)mra[i]; + entries[i].te_index = (byte)map["te_idx"].AsInteger(); + entries[i].id = map["id"].AsUUID(); + } + rm.entries = entries; + } + } + } + catch + { + rm.entries = null; + } + return rm; + } + + public override int GetHashCode() + { + int h = entries.Length.GetHashCode(); + for(int i = 0 ; i < entries.Length; ++i) + h ^= (int)entries[i].te_index ^ entries[i].id.GetHashCode(); + return h; + } + + /// + /// + /// + /// + public override string ToString() + { + return String.Format("RenderMaterials: nentries {0}}", entries==null? 0:entries.Length); + } + } + + /// /// Extended properties to describe an object /// public class ObjectProperties @@ -1412,22 +1652,22 @@ public override int GetHashCode() public static ushort PackBeginCut(float beginCut) { - return (ushort)Math.Round(beginCut / CUT_QUANTA); + return (ushort)MathF.Round(beginCut * CUT_QUANTAINV); } public static ushort PackEndCut(float endCut) { - return (ushort)(50000 - (ushort)Math.Round(endCut / CUT_QUANTA)); + return (ushort)(50000 - (ushort)MathF.Round(endCut * CUT_QUANTAINV)); } public static byte PackPathScale(float pathScale) { - return (byte)(200 - (byte)Math.Round(pathScale / SCALE_QUANTA)); + return (byte)(200 - (byte)MathF.Round(pathScale * SCALE_QUANTAINV)); } public static sbyte PackPathShear(float pathShear) { - return (sbyte)Math.Round(pathShear / SHEAR_QUANTA); + return (sbyte)MathF.Round(pathShear * SHEAR_QUANTAINV); } /// @@ -1438,22 +1678,22 @@ public static sbyte PackPathShear(float pathShear) /// Signed eight bit value containing the packed parameter public static sbyte PackPathTwist(float pathTwist) { - return (sbyte)Math.Round(pathTwist / SCALE_QUANTA); + return (sbyte)MathF.Round(pathTwist * SCALE_QUANTAINV); } public static sbyte PackPathTaper(float pathTaper) { - return (sbyte)Math.Round(pathTaper / TAPER_QUANTA); + return (sbyte)MathF.Round(pathTaper * TAPER_QUANTAINV); } public static byte PackPathRevolutions(float pathRevolutions) { - return (byte)Math.Round((pathRevolutions - 1f) / REV_QUANTA); + return (byte)MathF.Round((pathRevolutions - 1f) * REV_QUANTAINV); } public static ushort PackProfileHollow(float profileHollow) { - return (ushort)Math.Round(profileHollow / HOLLOW_QUANTA); + return (ushort)MathF.Round(profileHollow * HOLLOW_QUANTAINV); } #endregion Parameter Packing Methods diff --git a/OpenMetaverse/Primitives/TextureEntry.cs b/OpenMetaverse/Primitives/TextureEntry.cs index 8d2e287c..29f48ef2 100644 --- a/OpenMetaverse/Primitives/TextureEntry.cs +++ b/OpenMetaverse/Primitives/TextureEntry.cs @@ -24,10 +24,10 @@ * POSSIBILITY OF SUCH DAMAGE. */ -using OpenMetaverse.StructuredData; using System; using System.Collections.Generic; using System.IO; +using OpenMetaverse.StructuredData; namespace OpenMetaverse { @@ -211,13 +211,13 @@ public class TextureEntryFace : ICloneable internal byte m_media; #region Properties - + /// public Color4 RGBA { get { - if ((m_attributes & TextureAttributes.RGBA) == 0) + if((m_attributes & TextureAttributes.RGBA) == 0) return DefaultTexture.m_rgba; return m_rgba; } @@ -252,7 +252,7 @@ public float RepeatU t = DefaultTexture.m_repeatU; if (t != value) - { + { m_repeatU = value; m_dirtyFlags |= TextureAttributes.RepeatU; m_attributes |= TextureAttributes.RepeatU; @@ -300,7 +300,7 @@ public float OffsetU o = DefaultTexture.m_offsetU; short ts = Helpers.TEOffsetShort(value); - if (o != ts) + if(o != ts) { m_offsetU = ts; m_dirtyFlags |= TextureAttributes.OffsetU; @@ -350,7 +350,7 @@ public float Rotation o = DefaultTexture.m_rotation; short ts = Helpers.TERotationShort(value); - if (o != ts) + if(o != ts) { m_rotation = ts; m_dirtyFlags |= TextureAttributes.Rotation; @@ -375,7 +375,7 @@ public float Glow o = DefaultTexture.m_glow; byte tb = Helpers.TEGlowByte(value); - if (o != tb) + if(o != tb) { m_glow = tb; m_dirtyFlags |= TextureAttributes.Glow; @@ -402,7 +402,7 @@ public Bumpiness Bump byte tb = (byte)(m_material & 0xE0); tb |= (byte)value; - if (o != tb) + if(o != tb) { m_material = tb; m_dirtyFlags |= TextureAttributes.Material; @@ -457,7 +457,7 @@ public bool Fullbright if (value) tb |= 0x20; - if (o != tb) + if(o != tb) { m_material = tb; m_dirtyFlags |= TextureAttributes.Material; @@ -486,7 +486,7 @@ public bool MediaFlags byte tb = (byte)(m_media & 0xFE); if (value) tb |= 0x01; - if (o != tb) + if(o != tb) { m_media = tb; m_dirtyFlags |= TextureAttributes.Media; @@ -512,7 +512,7 @@ public MappingType TexMapType byte tb = (byte)(m_media & 0xF9); tb |= (byte)value; - if (tb != o) + if(tb != o) { m_media = tb; m_dirtyFlags |= TextureAttributes.Media; @@ -817,7 +817,7 @@ public TextureAttributes GetDirtyFlags(int lenght, bool clear) flags |= FaceTextures[i].DirtyFlags; if (clear) FaceTextures[i].DirtyFlags = TextureAttributes.None; - } + } } return flags; } @@ -828,11 +828,11 @@ public void SetDirtyFlags(int lenght, TextureAttributes flags) lenght = MAX_FACES; if (DefaultTexture != null) - DefaultTexture.DirtyFlags = flags; + DefaultTexture.DirtyFlags = flags; for (int i = lenght - 1; i >= 0; --i) { if (FaceTextures[i] != null) - FaceTextures[i].DirtyFlags = flags; + FaceTextures[i].DirtyFlags = flags; } } @@ -920,7 +920,7 @@ private void FromBytes(byte[] data, int pos, int length) i += 16; for (face = 0, bit = 1; face < bitfieldSize; face++, bit <<= 1) if ((faceBits & bit) != 0) - { + { CreateFace(face).m_textureID = tmpUUID; FaceTextures[face].m_attributes |= TextureAttributes.TextureID; } @@ -1043,9 +1043,9 @@ private void FromBytes(byte[] data, int pos, int length) FaceTextures[face].m_attributes |= TextureAttributes.Rotation; } } - #endregion Rotation + #endregion Rotation - #region Material + #region Material DefaultTexture.m_material = data[i]; i++; @@ -1085,7 +1085,7 @@ private void FromBytes(byte[] data, int pos, int length) FaceTextures[face].m_attributes |= TextureAttributes.Media; } } - #endregion Media + #endregion Media #region Glow DefaultTexture.m_glow = data[i++]; @@ -1138,7 +1138,7 @@ private void FromBytes(byte[] data, int pos, int length) public byte[] GetBytes(int maxfaces = MAX_FACES) { if (DefaultTexture == null) - return Utils.EmptyBytes; + return Array.Empty(); using (MemoryStream ms = new MemoryStream(4096)) { @@ -1147,8 +1147,9 @@ public byte[] GetBytes(int maxfaces = MAX_FACES) ulong next = 0; ulong nulls = 0; + TextureEntryFace curFace; int last = FaceTextures.Length - 1; - if (last > maxfaces - 1) + if(last > maxfaces - 1) last = maxfaces - 1; bool onLastastNulls = true; @@ -1158,7 +1159,8 @@ public byte[] GetBytes(int maxfaces = MAX_FACES) for (int i = last; i >= 0; --i) { cur = (1UL << i); - if (FaceTextures[i] == null) + curFace = FaceTextures[i]; + if (curFace == null) { nulls |= cur; continue; @@ -1173,10 +1175,10 @@ public byte[] GetBytes(int maxfaces = MAX_FACES) if ((done & cur) != 0) continue; - if ((FaceTextures[i].m_attributes & TextureAttributes.TextureID) == 0) + if ((curFace.m_attributes & TextureAttributes.TextureID) == 0) continue; - UUID id = FaceTextures[i].TextureID; + UUID id = curFace.TextureID; if (id == DefaultTexture.m_textureID) continue; @@ -1186,17 +1188,18 @@ public byte[] GetBytes(int maxfaces = MAX_FACES) if ((done & next) != 0) continue; - if (FaceTextures[j] == null) + curFace = FaceTextures[j]; + if (curFace == null) { nulls |= next; done |= next; continue; } - if ((FaceTextures[j].m_attributes & TextureAttributes.TextureID) == 0) + if ((curFace.m_attributes & TextureAttributes.TextureID) == 0) continue; - if (FaceTextures[j].m_textureID != id) + if (curFace.m_textureID != id) continue; done |= next; @@ -1221,10 +1224,11 @@ public byte[] GetBytes(int maxfaces = MAX_FACES) if ((done & cur) != 0) continue; - if ((FaceTextures[i].m_attributes & TextureAttributes.RGBA) == 0) + curFace = FaceTextures[i]; + if ((curFace.m_attributes & TextureAttributes.RGBA) == 0) continue; - Color4 c = FaceTextures[i].m_rgba; + Color4 c = curFace.m_rgba; if (c == DefaultTexture.m_rgba) continue; @@ -1234,10 +1238,11 @@ public byte[] GetBytes(int maxfaces = MAX_FACES) if ((done & next) != 0) continue; - if ((FaceTextures[j].m_attributes & TextureAttributes.RGBA) == 0) + curFace = FaceTextures[j]; + if ((curFace.m_attributes & TextureAttributes.RGBA) == 0) continue; - if (FaceTextures[j].m_rgba != c) + if (curFace.m_rgba != c) continue; done |= next; @@ -1259,10 +1264,11 @@ public byte[] GetBytes(int maxfaces = MAX_FACES) if ((done & cur) != 0) continue; - if ((FaceTextures[i].m_attributes & TextureAttributes.RepeatU) == 0) + curFace = FaceTextures[i]; + if ((curFace.m_attributes & TextureAttributes.RepeatU) == 0) continue; - float repeat = FaceTextures[i].m_repeatU; + float repeat = curFace.m_repeatU; if (repeat == deff) continue; @@ -1272,10 +1278,11 @@ public byte[] GetBytes(int maxfaces = MAX_FACES) if ((done & next) != 0) continue; - if ((FaceTextures[j].m_attributes & TextureAttributes.RepeatU) == 0) + curFace = FaceTextures[j]; + if ((curFace.m_attributes & TextureAttributes.RepeatU) == 0) continue; - if (FaceTextures[j].m_repeatU != repeat) + if (curFace.m_repeatU != repeat) continue; done |= next; @@ -1297,10 +1304,11 @@ public byte[] GetBytes(int maxfaces = MAX_FACES) if ((done & cur) != 0) continue; - if ((FaceTextures[i].m_attributes & TextureAttributes.RepeatV) == 0) + curFace = FaceTextures[i]; + if ((curFace.m_attributes & TextureAttributes.RepeatV) == 0) continue; - float repeat = FaceTextures[i].m_repeatV; + float repeat = curFace.m_repeatV; if (repeat == deff) continue; @@ -1310,10 +1318,11 @@ public byte[] GetBytes(int maxfaces = MAX_FACES) if ((done & next) != 0) continue; - if ((FaceTextures[j].m_attributes & TextureAttributes.RepeatV) == 0) + curFace = FaceTextures[j]; + if ((curFace.m_attributes & TextureAttributes.RepeatV) == 0) continue; - if (FaceTextures[j].m_repeatV != repeat) + if (curFace.m_repeatV != repeat) continue; done |= next; @@ -1336,10 +1345,11 @@ public byte[] GetBytes(int maxfaces = MAX_FACES) if ((done & cur) != 0) continue; - if ((FaceTextures[i].m_attributes & TextureAttributes.OffsetU) == 0) + curFace = FaceTextures[i]; + if ((curFace.m_attributes & TextureAttributes.OffsetU) == 0) continue; - short offset = FaceTextures[i].m_offsetU; + short offset = curFace.m_offsetU; if (offset == def) continue; @@ -1349,10 +1359,11 @@ public byte[] GetBytes(int maxfaces = MAX_FACES) if ((done & next) != 0) continue; - if ((FaceTextures[j].m_attributes & TextureAttributes.OffsetU) == 0) + curFace = FaceTextures[j]; + if ((curFace.m_attributes & TextureAttributes.OffsetU) == 0) continue; - if (FaceTextures[j].m_offsetU != offset) + if (curFace.m_offsetU != offset) continue; done |= next; @@ -1374,10 +1385,11 @@ public byte[] GetBytes(int maxfaces = MAX_FACES) if ((done & cur) != 0) continue; - if ((FaceTextures[i].m_attributes & TextureAttributes.OffsetV) == 0) + curFace = FaceTextures[i]; + if ((curFace.m_attributes & TextureAttributes.OffsetV) == 0) continue; - short offset = FaceTextures[i].m_offsetV; + short offset = curFace.m_offsetV; if (offset == def) continue; @@ -1387,10 +1399,11 @@ public byte[] GetBytes(int maxfaces = MAX_FACES) if ((done & next) != 0) continue; - if ((FaceTextures[j].m_attributes & TextureAttributes.OffsetV) == 0) + curFace = FaceTextures[j]; + if ((curFace.m_attributes & TextureAttributes.OffsetV) == 0) continue; - if (FaceTextures[j].m_offsetV != offset) + if (curFace.m_offsetV != offset) continue; done |= next; @@ -1412,10 +1425,11 @@ public byte[] GetBytes(int maxfaces = MAX_FACES) if ((done & cur) != 0) continue; - if ((FaceTextures[i].m_attributes & TextureAttributes.Rotation) == 0) + curFace = FaceTextures[i]; + if ((curFace.m_attributes & TextureAttributes.Rotation) == 0) continue; - short rotation = FaceTextures[i].m_rotation; + short rotation = curFace.m_rotation; if (rotation == def) continue; @@ -1425,10 +1439,11 @@ public byte[] GetBytes(int maxfaces = MAX_FACES) if ((done & next) != 0) continue; - if ((FaceTextures[j].m_attributes & TextureAttributes.Rotation) == 0) + curFace = FaceTextures[j]; + if ((curFace.m_attributes & TextureAttributes.Rotation) == 0) continue; - if (FaceTextures[j].m_rotation != rotation) + if (curFace.m_rotation != rotation) continue; done |= next; @@ -1449,10 +1464,11 @@ public byte[] GetBytes(int maxfaces = MAX_FACES) if ((done & cur) != 0) continue; - if ((FaceTextures[i].m_attributes & TextureAttributes.Material) == 0) + curFace = FaceTextures[i]; + if ((curFace.m_attributes & TextureAttributes.Material) == 0) continue; - byte material = FaceTextures[i].m_material; + byte material = curFace.m_material; if (material == DefaultTexture.m_material) continue; @@ -1462,10 +1478,11 @@ public byte[] GetBytes(int maxfaces = MAX_FACES) if ((done & next) != 0) continue; - if ((FaceTextures[j].m_attributes & TextureAttributes.Material) == 0) + curFace = FaceTextures[j]; + if ((curFace.m_attributes & TextureAttributes.Material) == 0) continue; - if (FaceTextures[j].m_material != material) + if (curFace.m_material != material) continue; done |= next; @@ -1486,10 +1503,11 @@ public byte[] GetBytes(int maxfaces = MAX_FACES) if ((done & cur) != 0) continue; - if ((FaceTextures[i].m_attributes & TextureAttributes.Media) == 0) + curFace = FaceTextures[i]; + if ((curFace.m_attributes & TextureAttributes.Media) == 0) continue; - byte media = FaceTextures[i].m_media; + byte media = curFace.m_media; if (media == DefaultTexture.m_media) continue; @@ -1499,10 +1517,11 @@ public byte[] GetBytes(int maxfaces = MAX_FACES) if ((done & next) != 0) continue; - if ((FaceTextures[j].m_attributes & TextureAttributes.Media) == 0) + curFace = FaceTextures[j]; + if ((curFace.m_attributes & TextureAttributes.Media) == 0) continue; - if (FaceTextures[j].m_media != media) + if (curFace.m_media != media) continue; done |= next; @@ -1524,10 +1543,11 @@ public byte[] GetBytes(int maxfaces = MAX_FACES) if ((done & cur) != 0) continue; - if ((FaceTextures[i].m_attributes & TextureAttributes.Glow) == 0) + curFace = FaceTextures[i]; + if ((curFace.m_attributes & TextureAttributes.Glow) == 0) continue; - byte glow = FaceTextures[i].m_glow; + byte glow = curFace.m_glow; if (glow == defg) continue; @@ -1537,10 +1557,11 @@ public byte[] GetBytes(int maxfaces = MAX_FACES) if ((done & next) != 0) continue; - if ((FaceTextures[j].m_attributes & TextureAttributes.Glow) == 0) + curFace = FaceTextures[j]; + if ((curFace.m_attributes & TextureAttributes.Glow) == 0) continue; - if (FaceTextures[j].m_glow != glow) + if (curFace.m_glow != glow) continue; done |= next; @@ -1561,11 +1582,12 @@ public byte[] GetBytes(int maxfaces = MAX_FACES) if ((done & cur) != 0) continue; - if ((FaceTextures[i].m_attributes & TextureAttributes.MaterialID) == 0) + curFace = FaceTextures[i]; + if ((curFace.m_attributes & TextureAttributes.MaterialID) == 0) continue; - UUID materialID = FaceTextures[i].m_materialID; - if (materialID == null || materialID == DefaultTexture.m_materialID) + UUID materialID = curFace.m_materialID; + if (materialID == DefaultTexture.m_materialID) continue; for (int j = i - 1; j >= 0; --j) @@ -1574,10 +1596,11 @@ public byte[] GetBytes(int maxfaces = MAX_FACES) if ((done & next) != 0) continue; - if ((FaceTextures[j].m_attributes & TextureAttributes.MaterialID) == 0) + curFace = FaceTextures[j]; + if ((curFace.m_attributes & TextureAttributes.MaterialID) == 0) continue; - if (FaceTextures[j].m_materialID != materialID) + if (curFace.m_materialID != materialID) continue; done |= next; @@ -1594,23 +1617,20 @@ public byte[] GetBytes(int maxfaces = MAX_FACES) } - private static List AllBakedIndexes = new List() { 44, 43, 42, 41, 40, 20, 19, 11, 10, 9, 8 }; - private static List LegacyBakedIndexes = new List() {20, 19, 11, 10, 9, 8 }; + private static int[] AllBakedIndexes = { 44, 43, 42, 41, 40, 20, 19, 11, 10, 9, 8 }; + private static int[] LegacyBakedIndexes = {20, 19, 11, 10, 9, 8 }; public byte[] GetBakesBytes(int maxfaces = MAX_FACES) { if (DefaultTexture == null) - return Utils.EmptyBytes; + return Array.Empty(); - if(maxfaces > FaceTextures.Length) + if (maxfaces > FaceTextures.Length) maxfaces = FaceTextures.Length; - List bakedIndexes; - if(maxfaces > 21) - bakedIndexes = AllBakedIndexes; - else - bakedIndexes = LegacyBakedIndexes; + int[] bakedIndexes = (maxfaces > 21) ? AllBakedIndexes : LegacyBakedIndexes; + TextureEntryFace curFace; using (MemoryStream ms = new MemoryStream(4096)) { #region Texture @@ -1618,10 +1638,11 @@ public byte[] GetBakesBytes(int maxfaces = MAX_FACES) ms.Write(defText.GetBytes(), 0, 16); foreach (int i in bakedIndexes) { - if (FaceTextures[i] == null) + curFace = FaceTextures[i]; + if (curFace == null) continue; - UUID id = FaceTextures[i].TextureID; + UUID id = curFace.TextureID; if (id == defText) continue; @@ -1636,10 +1657,11 @@ public byte[] GetBakesBytes(int maxfaces = MAX_FACES) ms.Write(DefaultTexture.RGBA.GetBytes(true), 0, 4); foreach (int i in bakedIndexes) { - if (FaceTextures[i] == null) + curFace = FaceTextures[i]; + if (curFace == null) continue; - Color4 c = FaceTextures[i].RGBA; + Color4 c = curFace.RGBA; if (c == DefaultTexture.RGBA) continue; @@ -1654,10 +1676,11 @@ public byte[] GetBakesBytes(int maxfaces = MAX_FACES) Utils.FloatToBytes(ms, deff); foreach (int i in bakedIndexes) { - if (FaceTextures[i] == null) + curFace = FaceTextures[i]; + if (curFace == null) continue; - float repeat = FaceTextures[i].RepeatU; + float repeat = curFace.RepeatU; if (repeat == deff) continue; @@ -1672,10 +1695,11 @@ public byte[] GetBakesBytes(int maxfaces = MAX_FACES) Utils.FloatToBytes(ms, deff); foreach (int i in bakedIndexes) { - if (FaceTextures[i] == null) + curFace = FaceTextures[i]; + if (curFace == null) continue; - float repeat = FaceTextures[i].RepeatV; + float repeat = curFace.RepeatV; if (repeat == deff) continue; @@ -1691,10 +1715,11 @@ public byte[] GetBakesBytes(int maxfaces = MAX_FACES) Utils.Int16ToBytes(ms, def); foreach (int i in bakedIndexes) { - if (FaceTextures[i] == null) + curFace = FaceTextures[i]; + if (curFace == null) continue; - short offset = FaceTextures[i].m_offsetU; + short offset = curFace.m_offsetU; if (offset == def) continue; @@ -1709,10 +1734,11 @@ public byte[] GetBakesBytes(int maxfaces = MAX_FACES) Utils.Int16ToBytes(ms, def); foreach (int i in bakedIndexes) { - if (FaceTextures[i] == null) + curFace = FaceTextures[i]; + if (curFace == null) continue; - short offset = FaceTextures[i].m_offsetV; + short offset = curFace.m_offsetV; if (offset == def) continue; @@ -1727,10 +1753,11 @@ public byte[] GetBakesBytes(int maxfaces = MAX_FACES) Utils.Int16ToBytes(ms, def); foreach (int i in bakedIndexes) { - if (FaceTextures[i] == null) + curFace = FaceTextures[i]; + if (curFace == null) continue; - short rotation = FaceTextures[i].m_rotation; + short rotation = curFace.m_rotation; if (rotation == def) continue; @@ -1744,10 +1771,11 @@ public byte[] GetBakesBytes(int maxfaces = MAX_FACES) ms.WriteByte(DefaultTexture.m_material); foreach (int i in bakedIndexes) { - if (FaceTextures[i] == null) + curFace = FaceTextures[i]; + if (curFace == null) continue; - byte material = FaceTextures[i].m_material; + byte material = curFace.m_material; if (material == DefaultTexture.m_material) continue; @@ -1761,10 +1789,11 @@ public byte[] GetBakesBytes(int maxfaces = MAX_FACES) ms.WriteByte(DefaultTexture.m_media); foreach (int i in bakedIndexes) { - if (FaceTextures[i] == null) + curFace = FaceTextures[i]; + if (curFace == null) continue; - byte media = FaceTextures[i].m_media; + byte media = curFace.m_media; if (media == DefaultTexture.m_media) continue; @@ -1779,10 +1808,11 @@ public byte[] GetBakesBytes(int maxfaces = MAX_FACES) ms.WriteByte(defg); foreach (int i in bakedIndexes) { - if (FaceTextures[i] == null) + curFace = FaceTextures[i]; + if (curFace == null) continue; - byte glow = FaceTextures[i].m_glow; + byte glow = curFace.m_glow; if (glow == defg) continue; @@ -1796,11 +1826,12 @@ public byte[] GetBakesBytes(int maxfaces = MAX_FACES) ms.Write(DefaultTexture.m_materialID.GetBytes(), 0, 16); foreach (int i in bakedIndexes) { - if (FaceTextures[i] == null) + curFace = FaceTextures[i]; + if (curFace == null) continue; - UUID materialID = FaceTextures[i].m_materialID; - if (materialID == null || materialID == DefaultTexture.m_materialID) + UUID materialID = curFace.m_materialID; + if (materialID == DefaultTexture.m_materialID) continue; WriteFaceBitfieldBytes(ms, (1UL << i)); @@ -1851,12 +1882,12 @@ private bool ReadFaceBitfield(byte[] data, ref int pos, ref ulong faceBits, ref return false; byte b = data[pos++]; - if (b == 0) + if(b == 0) return false; faceBits = (uint)(b & 0x7F); bitfieldSize = 7; - if ((b & 0x80) == 0) + if((b & 0x80) == 0) return true; do diff --git a/OpenMetaverse/ProtocolManager.cs b/OpenMetaverse/ProtocolManager.cs index 0f605216..159809c5 100644 --- a/OpenMetaverse/ProtocolManager.cs +++ b/OpenMetaverse/ProtocolManager.cs @@ -395,7 +395,7 @@ private void PrintOneMap(MapPacket[] map, string frequency) public static void DecodeMapFile(string mapFile, string outputFile) { byte magicKey = 0; - byte[] buffer = new byte[2048]; + byte[] buffer = GC.AllocateUninitializedArray(2048); int nread; try diff --git a/OpenMetaverse/Rendering/Rendering.cs b/OpenMetaverse/Rendering/Rendering.cs index 9506eb5c..c3afc116 100644 --- a/OpenMetaverse/Rendering/Rendering.cs +++ b/OpenMetaverse/Rendering/Rendering.cs @@ -116,7 +116,7 @@ public override int GetHashCode() public override bool Equals(object obj) { - return (obj is Vertex) ? this == (Vertex)obj : false; + return (obj is Vertex) && this == (Vertex)obj; } public bool Equals(Vertex other) @@ -246,150 +246,186 @@ public class FacetedMesh : Mesh /// Level of detail /// Resulting decoded FacetedMesh /// True if mesh asset decoding was successful - public static bool TryDecodeFromAsset(Primitive prim, AssetMesh meshAsset, DetailLevel LOD, out FacetedMesh mesh) + public static bool TryDecodeFromAsset(Primitive prim, AssetMesh meshAsset, DetailLevel LOD, out FacetedMesh mesh, + bool skipNormals = false) { mesh = null; try { if (!meshAsset.Decode()) - { return false; - } OSDMap MeshData = meshAsset.MeshData; - mesh = new FacetedMesh(); - - mesh.Faces = new List(); - mesh.Prim = prim; - mesh.Profile.Faces = new List(); - mesh.Profile.Positions = new List(); - mesh.Path.Points = new List(); + mesh = new FacetedMesh + { + Faces = [], + Prim = prim + }; + mesh.Profile.Faces = []; + mesh.Profile.Positions = []; + mesh.Path.Points = []; + + OSD facesOSD = LOD switch + { + DetailLevel.High => MeshData["medium_lod"], + DetailLevel.Medium => MeshData["low_lod"], + DetailLevel.Low => MeshData["lowest_lod"], + _ => MeshData["high_lod"] + }; - OSD facesOSD = null; + if (facesOSD is not OSDArray decodedMeshOsdArray) + return false; - switch (LOD) - { - default: - case DetailLevel.Highest: - facesOSD = MeshData["high_lod"]; - break; - - case DetailLevel.High: - facesOSD = MeshData["medium_lod"]; - break; - - case DetailLevel.Medium: - facesOSD = MeshData["low_lod"]; - break; - - case DetailLevel.Low: - facesOSD = MeshData["lowest_lod"]; - break; + return TryDecodeOSDLODBlock(decodedMeshOsdArray, skipNormals, ref mesh); } - - if (facesOSD == null || !(facesOSD is OSDArray)) + catch (Exception ex) { + Logger.Log("Failed to decode mesh asset: " + ex.Message, Helpers.LogLevel.Warning); return false; } + } - OSDArray decodedMeshOsdArray = (OSDArray)facesOSD; - - for (int faceNr = 0; faceNr < decodedMeshOsdArray.Count; faceNr++) + public static bool TryDecodeFromBytes(byte[] meshData, DetailLevel LOD, out FacetedMesh mesh, bool skipNormals = false) { - OSD subMeshOsd = decodedMeshOsdArray[faceNr]; + mesh = null; - // Decode each individual face - if (subMeshOsd is OSDMap) + try { - OSDMap subMeshMap = (OSDMap)subMeshOsd; + string layername = LOD switch + { + DetailLevel.High =>"medium_lod", + DetailLevel.Medium => "low_lod", + DetailLevel.Low => "lowest_lod", + _ => "high_lod" + }; - // As per http://wiki.secondlife.com/wiki/Mesh/Mesh_Asset_Format, some Mesh Level - // of Detail Blocks (maps) contain just a NoGeometry key to signal there is no - // geometry for this submesh. - if (subMeshMap.ContainsKey("NoGeometry") && ((OSDBoolean)subMeshMap["NoGeometry"])) - continue; + OSD facesOSD = AssetMesh.DecodeBlock(meshData, layername); + + if (facesOSD is not OSDArray decodedMeshOsdArray) + return false; + + mesh = new FacetedMesh + { + Faces = [] + }; + + return TryDecodeOSDLODBlock(decodedMeshOsdArray, skipNormals, ref mesh); + } + + catch (Exception ex) + { + Logger.Log("Failed to decode mesh bytes: " + ex.Message, Helpers.LogLevel.Warning); + return false; + } + } - Face oface = new Face(); - oface.ID = faceNr; - oface.Vertices = new List(); - oface.Indices = new List(); - oface.TextureFace = prim.Textures.GetFace((uint)faceNr); + public static bool TryDecodeOSDLODBlock(OSDArray LODBlockOSDArray, bool skipNormals, ref FacetedMesh mesh) + { + const float ONE_OVER_U16_MAX = 1.0f / ushort.MaxValue; - Vector3 posMax; - Vector3 posMin; + for (int faceNr = 0; faceNr < LODBlockOSDArray.Count; faceNr++) + { + if(LODBlockOSDArray[faceNr] is not OSDMap subMeshMap) + continue; - // If PositionDomain is not specified, the default is from -0.5 to 0.5 - if (subMeshMap.ContainsKey("PositionDomain")) + // Decode each individual face + Face oface = new() { - posMax = ((OSDMap)subMeshMap["PositionDomain"])["Max"]; - posMin = ((OSDMap)subMeshMap["PositionDomain"])["Min"]; + ID = faceNr, + Vertices = [], + Indices = [], + }; + + if(subMeshMap.ContainsKey("NoGeometry")) + continue; + + // Vertex positions + if(!subMeshMap.TryGetBinary("Position", out byte[] posBytes)) + continue; + + Vector3 posMin; + Vector3 posRange; + // If PositionDomain is not specified, the default is from -0.5 to 0.5 + if (subMeshMap.TryGetOSDMap("PositionDomain", out OSDMap mappd)) + { + posMin = mappd["Min"]; + posRange = mappd["Max"] - posMin; } else { - posMax = new Vector3(0.5f, 0.5f, 0.5f); posMin = new Vector3(-0.5f, -0.5f, -0.5f); + posRange = new Vector3(1.0f, 1.0f, 1.0f); } - // Vertex positions - byte[] posBytes = subMeshMap["Position"]; - // Normals - byte[] norBytes = null; - if (subMeshMap.ContainsKey("Normal")) + if(!skipNormals && subMeshMap.TryGetBinary("Normal", out byte[] norBytes)) { - norBytes = subMeshMap["Normal"]; + if(norBytes.Length != posBytes.Length) + norBytes = null; } + else + norBytes = null; // UV texture map - Vector2 texPosMax = Vector2.Zero; - Vector2 texPosMin = Vector2.Zero; - byte[] texBytes = null; - if (subMeshMap.ContainsKey("TexCoord0")) + Vector2 texUVRange; + Vector2 texUVMin; + if (subMeshMap.TryGetBinary("TexCoord0", out byte[] texUVBytes)) { - texBytes = subMeshMap["TexCoord0"]; - texPosMax = ((OSDMap)subMeshMap["TexCoord0Domain"])["Max"]; - texPosMin = ((OSDMap)subMeshMap["TexCoord0Domain"])["Min"]; + if(texUVBytes.Length * 3 != posBytes.Length * 2) + texUVBytes = null; + OSDMap UVdomain = (OSDMap)subMeshMap["TexCoord0Domain"]; + texUVMin = UVdomain["Min"]; + texUVRange = UVdomain["Max"] - texUVMin; } + else + { + texUVMin = Vector2.Zero; + texUVRange = Vector2.Zero; + } + + posRange *= ONE_OVER_U16_MAX; + float normRange = 2f * ONE_OVER_U16_MAX; + texUVRange *= ONE_OVER_U16_MAX; // Extract the vertex position data // If present normals and texture coordinates too + + int vertexUVOffset = 0; for (int i = 0; i < posBytes.Length; i += 6) { + Vertex vx = new(); + ushort uX = Utils.BytesToUInt16(posBytes, i); ushort uY = Utils.BytesToUInt16(posBytes, i + 2); ushort uZ = Utils.BytesToUInt16(posBytes, i + 4); - Vertex vx = new Vertex(); - vx.Position = new Vector3( - Utils.UInt16ToFloat(uX, posMin.X, posMax.X), - Utils.UInt16ToFloat(uY, posMin.Y, posMax.Y), - Utils.UInt16ToFloat(uZ, posMin.Z, posMax.Z)); + uX * posRange.X + posMin.X, + uY * posRange.Y + posMin.Y, + uZ * posRange.Z + posMin.Z ); - if (norBytes != null && norBytes.Length >= i + 4) + if (norBytes is not null) { ushort nX = Utils.BytesToUInt16(norBytes, i); ushort nY = Utils.BytesToUInt16(norBytes, i + 2); ushort nZ = Utils.BytesToUInt16(norBytes, i + 4); vx.Normal = new Vector3( - Utils.UInt16ToFloat(nX, posMin.X, posMax.X), - Utils.UInt16ToFloat(nY, posMin.Y, posMax.Y), - Utils.UInt16ToFloat(nZ, posMin.Z, posMax.Z)); + nX * normRange - 1.0f, + nY * normRange - 1.0f, + nZ * normRange - 1.0f); } - var vertexIndexOffset = oface.Vertices.Count * 4; - - if (texBytes != null && texBytes.Length >= vertexIndexOffset + 4) + if (texUVBytes is not null) { - ushort tX = Utils.BytesToUInt16(texBytes, vertexIndexOffset); - ushort tY = Utils.BytesToUInt16(texBytes, vertexIndexOffset + 2); + ushort tX = Utils.BytesToUInt16(texUVBytes, vertexUVOffset); vertexUVOffset += 2; + ushort tY = Utils.BytesToUInt16(texUVBytes, vertexUVOffset); vertexUVOffset += 2; vx.TexCoord = new Vector2( - Utils.UInt16ToFloat(tX, texPosMin.X, texPosMax.X), - Utils.UInt16ToFloat(tY, texPosMin.Y, texPosMax.Y)); + tX * texUVRange.X + texUVMin.X, + tY * texUVRange.Y + texUVMin.Y); } oface.Vertices.Add(vx); @@ -398,25 +434,13 @@ public static bool TryDecodeFromAsset(Primitive prim, AssetMesh meshAsset, Detai byte[] triangleBytes = subMeshMap["TriangleList"]; for (int i = 0; i < triangleBytes.Length; i += 6) { - ushort v1 = (ushort)(Utils.BytesToUInt16(triangleBytes, i)); - oface.Indices.Add(v1); - ushort v2 = (ushort)(Utils.BytesToUInt16(triangleBytes, i + 2)); - oface.Indices.Add(v2); - ushort v3 = (ushort)(Utils.BytesToUInt16(triangleBytes, i + 4)); - oface.Indices.Add(v3); + oface.Indices.Add(Utils.BytesToUInt16(triangleBytes, i)); + oface.Indices.Add(Utils.BytesToUInt16(triangleBytes, i + 2)); + oface.Indices.Add(Utils.BytesToUInt16(triangleBytes, i + 4)); } mesh.Faces.Add(oface); } - } - - } - catch (Exception ex) - { - Logger.Log("Failed to decode mesh asset: " + ex.Message, Helpers.LogLevel.Warning); - return false; - } - return true; } } @@ -432,18 +456,18 @@ public SimpleMesh() public SimpleMesh(SimpleMesh mesh) { - this.Indices = new List(mesh.Indices); - this.Path.Open = mesh.Path.Open; - this.Path.Points = new List(mesh.Path.Points); - this.Prim = mesh.Prim; - this.Profile.Concave = mesh.Profile.Concave; - this.Profile.Faces = new List(mesh.Profile.Faces); - this.Profile.MaxX = mesh.Profile.MaxX; - this.Profile.MinX = mesh.Profile.MinX; - this.Profile.Open = mesh.Profile.Open; - this.Profile.Positions = new List(mesh.Profile.Positions); - this.Profile.TotalOutsidePoints = mesh.Profile.TotalOutsidePoints; - this.Vertices = new List(mesh.Vertices); + Indices = new List(mesh.Indices); + Path.Open = mesh.Path.Open; + Path.Points = new List(mesh.Path.Points); + Prim = mesh.Prim; + Profile.Concave = mesh.Profile.Concave; + Profile.Faces = new List(mesh.Profile.Faces); + Profile.MaxX = mesh.Profile.MaxX; + Profile.MinX = mesh.Profile.MinX; + Profile.Open = mesh.Profile.Open; + Profile.Positions = new List(mesh.Profile.Positions); + Profile.TotalOutsidePoints = mesh.Profile.TotalOutsidePoints; + Vertices = new List(mesh.Vertices); } } diff --git a/OpenMetaverse/Simulator.cs b/OpenMetaverse/Simulator.cs index 3f633ca1..13457a9b 100644 --- a/OpenMetaverse/Simulator.cs +++ b/OpenMetaverse/Simulator.cs @@ -1052,7 +1052,7 @@ protected override void PacketReceived(UDPPacketBuffer buffer) #region Packet Decoding - int packetEnd = buffer.DataLength - 1; + int packetEnd = buffer.DataLength; try { diff --git a/OpenMetaverse/TerrainCompressor.cs b/OpenMetaverse/TerrainCompressor.cs index 19da87f9..119052e1 100644 --- a/OpenMetaverse/TerrainCompressor.cs +++ b/OpenMetaverse/TerrainCompressor.cs @@ -36,14 +36,14 @@ public class TerrainPatch public enum LayerType : byte { - Land = 0x4C, // 'L' - LandExtended = 0x4D, // 'M' - Water = 0x57, // 'W' - WaterExtended = 0x57, // 'X' - Wind = 0x37, // '7' - WindExtended = 0x39, // '9' - Cloud = 0x38, // '8' - CloudExtended = 0x3A // ':' + Land = 0x4C, // 'L' + LandExtended = 0x4D, // 'M' + Water = 0x57, // 'W' + WaterExtended = 0x58, // 'X' + Wind = 0x37, // '7' + WindExtended = 0x39, // '9' + Cloud = 0x38, // '8' + CloudExtended = 0x3A // ':' } public struct GroupHeader diff --git a/OpenMetaverse/TexturePipeline.cs b/OpenMetaverse/TexturePipeline.cs index a5a9135b..4b5020ca 100644 --- a/OpenMetaverse/TexturePipeline.cs +++ b/OpenMetaverse/TexturePipeline.cs @@ -95,6 +95,8 @@ private class TaskInfo public TextureRequestState State; /// The Unique Request ID, This is also the Asset ID of the texture being requested public UUID RequestID; + /// The cancellation token for the request. + public CancellationTokenSource TokenSource; //added from LibreOpenMetaverse /// The slot this request is occupying in the threadpoolSlots array public int RequestSlot; /// The ImageType of the request. @@ -131,6 +133,8 @@ private class TaskInfo private readonly int[] threadpoolSlots; /// The primary thread which manages the requests. private Thread downloadMaster; + /// The cancellation token for the TexturePipeline and all child tasks. + private CancellationTokenSource downloadTokenSource; //added from LibreOpenMetaverse /// true if the TexturePipeline is currently running bool _Running; /// A synchronization object used by the primary thread @@ -150,6 +154,8 @@ public TexturePipeline(GridClient client) _Client = client; maxTextureRequests = client.Settings.MAX_CONCURRENT_TEXTURE_DOWNLOADS; + + downloadTokenSource = new CancellationTokenSource();//Added from LibreOpenMetaverse resetEvents = new AutoResetEvent[maxTextureRequests]; threadpoolSlots = new int[maxTextureRequests]; @@ -219,10 +225,17 @@ public void Shutdown() if (null != RefreshDownloadsTimer) RefreshDownloadsTimer.Dispose(); RefreshDownloadsTimer = null; - if (downloadMaster != null && downloadMaster.IsAlive) + /* + if (downloadMaster != null && downloadMaster.IsAlive) { downloadMaster.Abort(); } + */ + + //Added from LibreOpenMetaverse + if (!downloadTokenSource.IsCancellationRequested) + downloadTokenSource.Cancel(); + downloadMaster = null; _Client.Network.UnregisterCallback(PacketType.ImageNotInDatabase, ImageNotInDatabaseHandler); @@ -292,7 +305,7 @@ private void RefreshDownloadsTimer_Elapsed(object sender, System.Timers.ElapsedE /// from the beginning of the request public void RequestTexture(UUID textureID, ImageType imageType, float priority, int discardLevel, uint packetStart, TextureDownloadCallback callback, bool progressive) { - if (textureID == UUID.Zero) + if (textureID.IsZero()) return; if (callback != null) @@ -314,6 +327,7 @@ public void RequestTexture(UUID textureID, ImageType imageType, float priority, } else { + //TokenSource added from LibreMetaverse lock (_Transfers) { TaskInfo request; @@ -328,6 +342,7 @@ public void RequestTexture(UUID textureID, ImageType imageType, float priority, request.State = TextureRequestState.Pending; request.RequestID = textureID; request.ReportProgress = progressive; + request.TokenSource = CancellationTokenSource.CreateLinkedTokenSource(downloadTokenSource.Token); request.RequestSlot = -1; request.Type = imageType; diff --git a/OpenMetaverse/Voice/VoiceControl.cs b/OpenMetaverse/Voice/VoiceControl.cs index a77bba10..83dbeffa 100644 --- a/OpenMetaverse/Voice/VoiceControl.cs +++ b/OpenMetaverse/Voice/VoiceControl.cs @@ -75,6 +75,7 @@ public enum ConnectionState // Position update thread private Thread posThread; + private CancellationTokenSource posTokenSource; //added based on LibreOpenMetaverse private ManualResetEvent posRestart; public GridClient Client; private VoicePosition position; @@ -128,8 +129,21 @@ public VoiceGateway(GridClient c) public void Start() { // Start the background thread - if (posThread != null && posThread.IsAlive) + + /* Removed as thread.abort is obsolte + * + * if (posThread != null && posThread.IsAlive) posThread.Abort(); + */ + + // Start the background thread (from libre OpenMetaverse) + if (posThread != null && posThread.IsAlive) + { + posRestart.Set(); + posTokenSource.Cancel(); + } + + posTokenSource = new CancellationTokenSource();//Added from LibreOpenMetaverse posThread = new Thread(new ThreadStart(PositionThreadBody)); posThread.Name = "VoicePositionUpdate"; posThread.IsBackground = true; @@ -250,8 +264,18 @@ public void Stop() { PosUpdating(false); - if (posThread.IsAlive) + /* Removed as thread.abort is obsolete + if (posThread.IsAlive) posThread.Abort(); + */ + + //Added From Libre OpenMetaverse + if (posThread.IsAlive) + { + posRestart.Set(); + posTokenSource.Cancel(); + } + posThread = null; } @@ -408,7 +432,7 @@ private static string nameFromID(UUID id) { string result = null; - if (id == UUID.Zero) + if (id.IsZero()) return result; // Prepending this apparently prevents conflicts with reserved names inside the vivox and diamondware code. @@ -986,9 +1010,11 @@ internal void PosUpdating(bool go) private void PositionThreadBody() { + var token = posTokenSource.Token; //added from LibreOpenMetaverse while (true) { posRestart.WaitOne(); + token.ThrowIfCancellationRequested(); //added from LibreOpenMetaverse Thread.Sleep(1500); UpdatePosition(Client.Self); } diff --git a/OpenMetaverse/WorkPool.cs b/OpenMetaverse/WorkPool.cs index 0604f52f..cc0267ca 100644 --- a/OpenMetaverse/WorkPool.cs +++ b/OpenMetaverse/WorkPool.cs @@ -24,208 +24,39 @@ * POSSIBILITY OF SUCH DAMAGE. */ -#define SMARTHREADPOOL_REF - - -#if SMARTHREADPOOL_REF -using Amib.Threading; -#else using System.Threading; -#endif namespace OpenMetaverse { - - // Use statically referenced SmartThreadPool.dll -#if SMARTHREADPOOL_REF public static class WorkPool { - internal static SmartThreadPool Pool = null; + private static bool _initialized; public static bool Init(bool useSmartThredPool) { - if (Pool == null) - { - STPStartInfo param = new STPStartInfo(); - param.MinWorkerThreads = 2; - param.MaxWorkerThreads = 50; - param.ThreadPoolName = "LibOpenMetaverse Main ThreadPool"; - param.AreThreadsBackground = true; - - Pool = new SmartThreadPool(param); - } - return true; - } - - public static void Shutdown() - { - if (Pool != null) - { - Pool.Shutdown(); - Pool = null; - } - } - - public static void QueueUserWorkItem(System.Threading.WaitCallback callback) - { - if (Pool != null) - { - Pool.QueueWorkItem(state => { callback.Invoke(state); return null; }); - } - else - { - System.Threading.ThreadPool.QueueUserWorkItem(state => callback.Invoke(state)); - } - } - - public static void QueueUserWorkItem(System.Threading.WaitCallback callback, object state) - { - if (Pool != null) - { - Pool.QueueWorkItem(sync => { callback.Invoke(sync); return null; }, state); - } - else - { - System.Threading.ThreadPool.QueueUserWorkItem(sync => callback.Invoke(sync), state); - } - } - } - -#else - - // Try to load SmartThreadPool.dll during initialization - // Fallback to System.Threading.ThreadPool if that fails - public static class WorkPoolDynamic - { - internal static object Pool = null; - - private static Type SmartThreadPoolType; - private static Type WorkItemCallbackType; - private static MethodInfo QueueWorkItemFunc, QueueWorkItemFunc2; - private static MethodInfo ShutdownFunc; - private static Func Invoker; - - public static bool Init() - { - try - { - string dir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); - Assembly assembly = Assembly.LoadFile(Path.Combine(dir, "SmartThreadPool.dll")); - Type STPStartInfo = assembly.GetType("Amib.Threading.STPStartInfo"); - SmartThreadPoolType = assembly.GetType("Amib.Threading.SmartThreadPool"); - WorkItemCallbackType = assembly.GetType("Amib.Threading.WorkItemCallback"); - var param = Activator.CreateInstance(STPStartInfo); - STPStartInfo.GetProperty("MinWorkerThreads").SetValue(param, 2, null); - STPStartInfo.GetProperty("MaxWorkerThreads").SetValue(param, 50, null); - STPStartInfo.GetProperty("ThreadPoolName").SetValue(param, "LibOpenMetaverse Main ThreadPool", null); - STPStartInfo.GetProperty("AreThreadsBackground").SetValue(param, true, null); - STPStartInfo.GetProperty("MinWorkerThreads").SetValue(param, 2, null); - Pool = Activator.CreateInstance(SmartThreadPoolType, new object[] { param }); - QueueWorkItemFunc = SmartThreadPoolType.GetMethod("QueueWorkItem", new Type[] { WorkItemCallbackType }); - QueueWorkItemFunc2 = SmartThreadPoolType.GetMethod("QueueWorkItem", new Type[] { WorkItemCallbackType, typeof(object) }); - ShutdownFunc = SmartThreadPoolType.GetMethod("Shutdown", new Type[] { }); - - Invoker = (inv, state) => - { - inv.Invoke(state); - return null; - }; - - return true; - } - catch - { - Pool = null; - return false; - } - } - - public static void Shutdown() - { - if (Pool != null) - { - ShutdownFunc.Invoke(Pool, null); - Pool = null; - } - } - - - public static void QueueUserWorkItem(System.Threading.WaitCallback callback) - { - if (Pool != null) - { - QueueWorkItemFunc.Invoke(Pool, new object[] { Delegate.CreateDelegate(WorkItemCallbackType, callback, Invoker.Method) }); - } - else - { - System.Threading.ThreadPool.QueueUserWorkItem(state => callback.Invoke(state)); - } - } - - public static void QueueUserWorkItem(System.Threading.WaitCallback callback, object state) - { - if (Pool != null) - { - QueueWorkItemFunc2.Invoke(Pool, new object[] { Delegate.CreateDelegate(WorkItemCallbackType, callback, Invoker.Method), state }); - } - else + if (!_initialized) { - System.Threading.ThreadPool.QueueUserWorkItem(sync => callback.Invoke(sync), state); + // Preserve previous tuning intent while using the runtime thread pool. + ThreadPool.SetMinThreads(2, 2); + _initialized = true; } - } - } - - - public static class WorkPool - { - private static bool UseSmartThreadPool = false; - public static bool Init(bool useSmartThredPool) - { - if (useSmartThredPool) - { - if (WorkPoolDynamic.Init()) - { - UseSmartThreadPool = true; - return true; - } - return false; - } return true; } public static void Shutdown() { - if (UseSmartThreadPool) - { - WorkPoolDynamic.Shutdown(); - UseSmartThreadPool = false; - } + // System.Threading.ThreadPool is process-wide and cannot be explicitly shut down. } - public static void QueueUserWorkItem(System.Threading.WaitCallback callback) + public static void QueueUserWorkItem(WaitCallback callback) { - if (UseSmartThreadPool) - { - WorkPoolDynamic.QueueUserWorkItem(sync => callback.Invoke(sync)); - } - else - { - ThreadPool.QueueUserWorkItem(sync => callback.Invoke(sync)); - } + ThreadPool.QueueUserWorkItem(state => callback.Invoke(state)); } - public static void QueueUserWorkItem(System.Threading.WaitCallback callback, object state) + public static void QueueUserWorkItem(WaitCallback callback, object state) { - if (UseSmartThreadPool) - { - WorkPoolDynamic.QueueUserWorkItem(sync => callback.Invoke(sync), state); - } - else - { - ThreadPool.QueueUserWorkItem(sync => callback.Invoke(sync), state); - } + ThreadPool.QueueUserWorkItem(sync => callback.Invoke(sync), state); } } -#endif } diff --git a/OpenMetaverse/_Packets_.cs b/OpenMetaverse/_Packets_.cs index 48a10c95..6023debc 100644 --- a/OpenMetaverse/_Packets_.cs +++ b/OpenMetaverse/_Packets_.cs @@ -150,7 +150,7 @@ public void AcksToBytes(byte[] bytes, ref int i) /// /// /// - public static Header BuildHeader(byte[] bytes, ref int pos, ref int packetEnd) + public static Header BuildHeader(byte[] bytes, ref int pos, ref int packetLength) { Header header; byte flags = bytes[pos]; @@ -159,8 +159,9 @@ public static Header BuildHeader(byte[] bytes, ref int pos, ref int packetEnd) header.Reliable = (flags & Helpers.MSG_RELIABLE) != 0; header.Resent = (flags & Helpers.MSG_RESENT) != 0; header.Zerocoded = (flags & Helpers.MSG_ZEROCODED) != 0; - header.Sequence = (uint)((bytes[pos + 1] << 24) + (bytes[pos + 2] << 16) + (bytes[pos + 3] << 8) + bytes[pos + 4]); + header.Sequence = (uint)Utils.BytesToIntBig(bytes, 1); + pos += bytes[pos + 5]; // Set the frequency and packet ID number if (bytes[pos + 6] == 0xFF) { @@ -190,36 +191,79 @@ public static Header BuildHeader(byte[] bytes, ref int pos, ref int packetEnd) pos += 7; } - header.AckList = null; - CreateAckList(ref header, bytes, ref packetEnd); + if (header.AppendedAcks) + { + --packetLength; + int count = bytes[packetLength]; + header.AckList = new uint[count]; + + for (int i = 0; i < count; i++) + { + packetLength -= 4; + header.AckList[i] = (uint)Utils.BytesToIntBig(bytes, packetLength); + } + } + else + header.AckList = null; return header; } - /// - /// - /// - /// - /// - /// - static void CreateAckList(ref Header header, byte[] bytes, ref int packetEnd) + public static bool TryParseHeader(byte[] bytes, int packetLen, out Header header, out int messageBody, out int messageEnd) { - if (header.AppendedAcks) + messageBody = 0; + messageEnd = packetLen; + header = new Header(); + + try { - int count = bytes[packetEnd--]; - header.AckList = new uint[count]; + byte flags = bytes[0]; - for (int i = 0; i < count; i++) + header.AppendedAcks = (flags & Helpers.MSG_APPENDED_ACKS) != 0; + header.Reliable = (flags & Helpers.MSG_RELIABLE) != 0; + header.Resent = (flags & Helpers.MSG_RESENT) != 0; + header.Zerocoded = (flags & Helpers.MSG_ZEROCODED) != 0; + + header.Sequence = (uint)Utils.BytesToIntBig(bytes, 1); + + messageBody += bytes[5]; + + header.ID = bytes[messageBody + 6]; + // Set the frequency and packet ID number + if (header.ID == 0xFF) { - header.AckList[i] = (uint)( - (bytes[(packetEnd - i * 4) - 3] << 24) | - (bytes[(packetEnd - i * 4) - 2] << 16) | - (bytes[(packetEnd - i * 4) - 1] << 8) | - (bytes[(packetEnd - i * 4)])); - } + header.ID = bytes[messageBody + 7]; + if (header.ID == 0xFF) + { + header.Frequency = PacketFrequency.Low; + if (header.Zerocoded && bytes[messageBody + 8] == 0) + header.ID = bytes[messageBody + 10]; + else + header.ID = (ushort)((bytes[messageBody + 8] << 8) + bytes[messageBody + 9]); - packetEnd -= (count * 4); + messageBody += 10; + } + else + { + header.Frequency = PacketFrequency.Medium; + messageBody += 8; + } + } + else + { + header.Frequency = PacketFrequency.High; + messageBody += 7; + } + if (header.AppendedAcks) + { + --messageEnd; + int count = bytes[messageEnd]; + messageEnd -= 4 * count; + } + return messageEnd >= messageBody; } + catch { } + return false; } } @@ -641,6 +685,7 @@ public enum PacketType ChildAgentPositionUpdate = 196635, SoundTrigger = 196637, ObjectAnimation = 196638, + GenericStreamingMessage = 196639, } public abstract partial class Packet @@ -652,9 +697,11 @@ public abstract partial class Packet public PacketType Type; public abstract int Length { get; } public abstract void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[] zeroBuffer); - public abstract void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd); + public abstract void FromBytes(Header header, byte[] bytes, ref int i); public abstract byte[] ToBytes(); public abstract byte[][] ToBytesMultiple(); + public bool NeedValidateIDs; + public virtual bool ValidIDs(UUID session, UUID agent) { return true; } public virtual byte[] ToBytes(Interfaces.IByteBufferPool pool, ref int size) { @@ -1077,6 +1124,7 @@ public static PacketType GetType(ushort id, PacketFrequency frequency) case 27: return PacketType.ChildAgentPositionUpdate; case 29: return PacketType.SoundTrigger; case 30: return PacketType.ObjectAnimation; + case 31: return PacketType.GenericStreamingMessage; } break; } @@ -1084,413 +1132,416 @@ public static PacketType GetType(ushort id, PacketFrequency frequency) return PacketType.Default; } - public static Packet BuildPacket(PacketType type) - { - if (type == PacketType.StartPingCheck) return new StartPingCheckPacket(); - if (type == PacketType.CompletePingCheck) return new CompletePingCheckPacket(); - if (type == PacketType.AgentUpdate) return new AgentUpdatePacket(); - if (type == PacketType.AgentAnimation) return new AgentAnimationPacket(); - if (type == PacketType.AgentRequestSit) return new AgentRequestSitPacket(); - if (type == PacketType.AgentSit) return new AgentSitPacket(); - if (type == PacketType.RequestImage) return new RequestImagePacket(); - if (type == PacketType.ImageData) return new ImageDataPacket(); - if (type == PacketType.ImagePacket) return new ImagePacketPacket(); - if (type == PacketType.LayerData) return new LayerDataPacket(); - if (type == PacketType.ObjectUpdate) return new ObjectUpdatePacket(); - if (type == PacketType.ObjectUpdateCompressed) return new ObjectUpdateCompressedPacket(); - if (type == PacketType.ObjectUpdateCached) return new ObjectUpdateCachedPacket(); - if (type == PacketType.ImprovedTerseObjectUpdate) return new ImprovedTerseObjectUpdatePacket(); - if (type == PacketType.KillObject) return new KillObjectPacket(); - if (type == PacketType.TransferPacket) return new TransferPacketPacket(); - if (type == PacketType.SendXferPacket) return new SendXferPacketPacket(); - if (type == PacketType.ConfirmXferPacket) return new ConfirmXferPacketPacket(); - if (type == PacketType.AvatarAnimation) return new AvatarAnimationPacket(); - if (type == PacketType.AvatarSitResponse) return new AvatarSitResponsePacket(); - if (type == PacketType.CameraConstraint) return new CameraConstraintPacket(); - if (type == PacketType.ParcelProperties) return new ParcelPropertiesPacket(); - if (type == PacketType.ChildAgentUpdate) return new ChildAgentUpdatePacket(); - if (type == PacketType.ChildAgentAlive) return new ChildAgentAlivePacket(); - if (type == PacketType.ChildAgentPositionUpdate) return new ChildAgentPositionUpdatePacket(); - if (type == PacketType.SoundTrigger) return new SoundTriggerPacket(); - if (type == PacketType.ObjectAnimation) return new ObjectAnimationPacket(); - if (type == PacketType.ObjectAdd) return new ObjectAddPacket(); - if (type == PacketType.MultipleObjectUpdate) return new MultipleObjectUpdatePacket(); - if (type == PacketType.RequestMultipleObjects) return new RequestMultipleObjectsPacket(); - if (type == PacketType.ObjectPosition) return new ObjectPositionPacket(); - if (type == PacketType.RequestObjectPropertiesFamily) return new RequestObjectPropertiesFamilyPacket(); - if (type == PacketType.CoarseLocationUpdate) return new CoarseLocationUpdatePacket(); - if (type == PacketType.CrossedRegion) return new CrossedRegionPacket(); - if (type == PacketType.ConfirmEnableSimulator) return new ConfirmEnableSimulatorPacket(); - if (type == PacketType.ObjectProperties) return new ObjectPropertiesPacket(); - if (type == PacketType.ObjectPropertiesFamily) return new ObjectPropertiesFamilyPacket(); - if (type == PacketType.ParcelPropertiesRequest) return new ParcelPropertiesRequestPacket(); - if (type == PacketType.AttachedSound) return new AttachedSoundPacket(); - if (type == PacketType.AttachedSoundGainChange) return new AttachedSoundGainChangePacket(); - if (type == PacketType.PreloadSound) return new PreloadSoundPacket(); - if (type == PacketType.ViewerEffect) return new ViewerEffectPacket(); - if (type == PacketType.TestMessage) return new TestMessagePacket(); - if (type == PacketType.UseCircuitCode) return new UseCircuitCodePacket(); - if (type == PacketType.TelehubInfo) return new TelehubInfoPacket(); - if (type == PacketType.EconomyDataRequest) return new EconomyDataRequestPacket(); - if (type == PacketType.EconomyData) return new EconomyDataPacket(); - if (type == PacketType.AvatarPickerRequest) return new AvatarPickerRequestPacket(); - if (type == PacketType.AvatarPickerReply) return new AvatarPickerReplyPacket(); - if (type == PacketType.PlacesQuery) return new PlacesQueryPacket(); - if (type == PacketType.PlacesReply) return new PlacesReplyPacket(); - if (type == PacketType.DirFindQuery) return new DirFindQueryPacket(); - if (type == PacketType.DirPlacesQuery) return new DirPlacesQueryPacket(); - if (type == PacketType.DirPlacesReply) return new DirPlacesReplyPacket(); - if (type == PacketType.DirPeopleReply) return new DirPeopleReplyPacket(); - if (type == PacketType.DirEventsReply) return new DirEventsReplyPacket(); - if (type == PacketType.DirGroupsReply) return new DirGroupsReplyPacket(); - if (type == PacketType.DirClassifiedQuery) return new DirClassifiedQueryPacket(); - if (type == PacketType.DirClassifiedReply) return new DirClassifiedReplyPacket(); - if (type == PacketType.AvatarClassifiedReply) return new AvatarClassifiedReplyPacket(); - if (type == PacketType.ClassifiedInfoRequest) return new ClassifiedInfoRequestPacket(); - if (type == PacketType.ClassifiedInfoReply) return new ClassifiedInfoReplyPacket(); - if (type == PacketType.ClassifiedInfoUpdate) return new ClassifiedInfoUpdatePacket(); - if (type == PacketType.ClassifiedDelete) return new ClassifiedDeletePacket(); - if (type == PacketType.ClassifiedGodDelete) return new ClassifiedGodDeletePacket(); - if (type == PacketType.DirLandQuery) return new DirLandQueryPacket(); - if (type == PacketType.DirLandReply) return new DirLandReplyPacket(); - if (type == PacketType.DirPopularQuery) return new DirPopularQueryPacket(); - if (type == PacketType.DirPopularReply) return new DirPopularReplyPacket(); - if (type == PacketType.ParcelInfoRequest) return new ParcelInfoRequestPacket(); - if (type == PacketType.ParcelInfoReply) return new ParcelInfoReplyPacket(); - if (type == PacketType.ParcelObjectOwnersRequest) return new ParcelObjectOwnersRequestPacket(); - if (type == PacketType.ParcelObjectOwnersReply) return new ParcelObjectOwnersReplyPacket(); - if (type == PacketType.GroupNoticesListRequest) return new GroupNoticesListRequestPacket(); - if (type == PacketType.GroupNoticesListReply) return new GroupNoticesListReplyPacket(); - if (type == PacketType.GroupNoticeRequest) return new GroupNoticeRequestPacket(); - if (type == PacketType.TeleportRequest) return new TeleportRequestPacket(); - if (type == PacketType.TeleportLocationRequest) return new TeleportLocationRequestPacket(); - if (type == PacketType.TeleportLocal) return new TeleportLocalPacket(); - if (type == PacketType.TeleportLandmarkRequest) return new TeleportLandmarkRequestPacket(); - if (type == PacketType.TeleportProgress) return new TeleportProgressPacket(); - if (type == PacketType.TeleportFinish) return new TeleportFinishPacket(); - if (type == PacketType.StartLure) return new StartLurePacket(); - if (type == PacketType.TeleportLureRequest) return new TeleportLureRequestPacket(); - if (type == PacketType.TeleportCancel) return new TeleportCancelPacket(); - if (type == PacketType.TeleportStart) return new TeleportStartPacket(); - if (type == PacketType.TeleportFailed) return new TeleportFailedPacket(); - if (type == PacketType.Undo) return new UndoPacket(); - if (type == PacketType.Redo) return new RedoPacket(); - if (type == PacketType.UndoLand) return new UndoLandPacket(); - if (type == PacketType.AgentPause) return new AgentPausePacket(); - if (type == PacketType.AgentResume) return new AgentResumePacket(); - if (type == PacketType.ChatFromViewer) return new ChatFromViewerPacket(); - if (type == PacketType.AgentThrottle) return new AgentThrottlePacket(); - if (type == PacketType.AgentFOV) return new AgentFOVPacket(); - if (type == PacketType.AgentHeightWidth) return new AgentHeightWidthPacket(); - if (type == PacketType.AgentSetAppearance) return new AgentSetAppearancePacket(); - if (type == PacketType.AgentQuitCopy) return new AgentQuitCopyPacket(); - if (type == PacketType.ImageNotInDatabase) return new ImageNotInDatabasePacket(); - if (type == PacketType.RebakeAvatarTextures) return new RebakeAvatarTexturesPacket(); - if (type == PacketType.SetAlwaysRun) return new SetAlwaysRunPacket(); - if (type == PacketType.ObjectDelete) return new ObjectDeletePacket(); - if (type == PacketType.ObjectDuplicate) return new ObjectDuplicatePacket(); - if (type == PacketType.ObjectDuplicateOnRay) return new ObjectDuplicateOnRayPacket(); - if (type == PacketType.ObjectScale) return new ObjectScalePacket(); - if (type == PacketType.ObjectRotation) return new ObjectRotationPacket(); - if (type == PacketType.ObjectFlagUpdate) return new ObjectFlagUpdatePacket(); - if (type == PacketType.ObjectClickAction) return new ObjectClickActionPacket(); - if (type == PacketType.ObjectImage) return new ObjectImagePacket(); - if (type == PacketType.ObjectMaterial) return new ObjectMaterialPacket(); - if (type == PacketType.ObjectShape) return new ObjectShapePacket(); - if (type == PacketType.ObjectExtraParams) return new ObjectExtraParamsPacket(); - if (type == PacketType.ObjectOwner) return new ObjectOwnerPacket(); - if (type == PacketType.ObjectGroup) return new ObjectGroupPacket(); - if (type == PacketType.ObjectBuy) return new ObjectBuyPacket(); - if (type == PacketType.BuyObjectInventory) return new BuyObjectInventoryPacket(); - if (type == PacketType.DerezContainer) return new DerezContainerPacket(); - if (type == PacketType.ObjectPermissions) return new ObjectPermissionsPacket(); - if (type == PacketType.ObjectSaleInfo) return new ObjectSaleInfoPacket(); - if (type == PacketType.ObjectName) return new ObjectNamePacket(); - if (type == PacketType.ObjectDescription) return new ObjectDescriptionPacket(); - if (type == PacketType.ObjectCategory) return new ObjectCategoryPacket(); - if (type == PacketType.ObjectSelect) return new ObjectSelectPacket(); - if (type == PacketType.ObjectDeselect) return new ObjectDeselectPacket(); - if (type == PacketType.ObjectAttach) return new ObjectAttachPacket(); - if (type == PacketType.ObjectDetach) return new ObjectDetachPacket(); - if (type == PacketType.ObjectDrop) return new ObjectDropPacket(); - if (type == PacketType.ObjectLink) return new ObjectLinkPacket(); - if (type == PacketType.ObjectDelink) return new ObjectDelinkPacket(); - if (type == PacketType.ObjectGrab) return new ObjectGrabPacket(); - if (type == PacketType.ObjectGrabUpdate) return new ObjectGrabUpdatePacket(); - if (type == PacketType.ObjectDeGrab) return new ObjectDeGrabPacket(); - if (type == PacketType.ObjectSpinStart) return new ObjectSpinStartPacket(); - if (type == PacketType.ObjectSpinUpdate) return new ObjectSpinUpdatePacket(); - if (type == PacketType.ObjectSpinStop) return new ObjectSpinStopPacket(); - if (type == PacketType.ObjectExportSelected) return new ObjectExportSelectedPacket(); - if (type == PacketType.ModifyLand) return new ModifyLandPacket(); - if (type == PacketType.VelocityInterpolateOn) return new VelocityInterpolateOnPacket(); - if (type == PacketType.VelocityInterpolateOff) return new VelocityInterpolateOffPacket(); - if (type == PacketType.StateSave) return new StateSavePacket(); - if (type == PacketType.ReportAutosaveCrash) return new ReportAutosaveCrashPacket(); - if (type == PacketType.SimWideDeletes) return new SimWideDeletesPacket(); - if (type == PacketType.TrackAgent) return new TrackAgentPacket(); - if (type == PacketType.ViewerStats) return new ViewerStatsPacket(); - if (type == PacketType.ScriptAnswerYes) return new ScriptAnswerYesPacket(); - if (type == PacketType.UserReport) return new UserReportPacket(); - if (type == PacketType.AlertMessage) return new AlertMessagePacket(); - if (type == PacketType.AgentAlertMessage) return new AgentAlertMessagePacket(); - if (type == PacketType.MeanCollisionAlert) return new MeanCollisionAlertPacket(); - if (type == PacketType.ViewerFrozenMessage) return new ViewerFrozenMessagePacket(); - if (type == PacketType.HealthMessage) return new HealthMessagePacket(); - if (type == PacketType.ChatFromSimulator) return new ChatFromSimulatorPacket(); - if (type == PacketType.SimStats) return new SimStatsPacket(); - if (type == PacketType.RequestRegionInfo) return new RequestRegionInfoPacket(); - if (type == PacketType.RegionInfo) return new RegionInfoPacket(); - if (type == PacketType.GodUpdateRegionInfo) return new GodUpdateRegionInfoPacket(); - if (type == PacketType.RegionHandshake) return new RegionHandshakePacket(); - if (type == PacketType.RegionHandshakeReply) return new RegionHandshakeReplyPacket(); - if (type == PacketType.SimulatorViewerTimeMessage) return new SimulatorViewerTimeMessagePacket(); - if (type == PacketType.EnableSimulator) return new EnableSimulatorPacket(); - if (type == PacketType.DisableSimulator) return new DisableSimulatorPacket(); - if (type == PacketType.TransferRequest) return new TransferRequestPacket(); - if (type == PacketType.TransferInfo) return new TransferInfoPacket(); - if (type == PacketType.TransferAbort) return new TransferAbortPacket(); - if (type == PacketType.RequestXfer) return new RequestXferPacket(); - if (type == PacketType.AbortXfer) return new AbortXferPacket(); - if (type == PacketType.AvatarAppearance) return new AvatarAppearancePacket(); - if (type == PacketType.SetFollowCamProperties) return new SetFollowCamPropertiesPacket(); - if (type == PacketType.ClearFollowCamProperties) return new ClearFollowCamPropertiesPacket(); - if (type == PacketType.RequestPayPrice) return new RequestPayPricePacket(); - if (type == PacketType.PayPriceReply) return new PayPriceReplyPacket(); - if (type == PacketType.KickUser) return new KickUserPacket(); - if (type == PacketType.GodKickUser) return new GodKickUserPacket(); - if (type == PacketType.EjectUser) return new EjectUserPacket(); - if (type == PacketType.FreezeUser) return new FreezeUserPacket(); - if (type == PacketType.AvatarPropertiesRequest) return new AvatarPropertiesRequestPacket(); - if (type == PacketType.AvatarPropertiesReply) return new AvatarPropertiesReplyPacket(); - if (type == PacketType.AvatarInterestsReply) return new AvatarInterestsReplyPacket(); - if (type == PacketType.AvatarGroupsReply) return new AvatarGroupsReplyPacket(); - if (type == PacketType.AvatarPropertiesUpdate) return new AvatarPropertiesUpdatePacket(); - if (type == PacketType.AvatarInterestsUpdate) return new AvatarInterestsUpdatePacket(); - if (type == PacketType.AvatarNotesReply) return new AvatarNotesReplyPacket(); - if (type == PacketType.AvatarNotesUpdate) return new AvatarNotesUpdatePacket(); - if (type == PacketType.AvatarPicksReply) return new AvatarPicksReplyPacket(); - if (type == PacketType.EventInfoRequest) return new EventInfoRequestPacket(); - if (type == PacketType.EventInfoReply) return new EventInfoReplyPacket(); - if (type == PacketType.EventNotificationAddRequest) return new EventNotificationAddRequestPacket(); - if (type == PacketType.EventNotificationRemoveRequest) return new EventNotificationRemoveRequestPacket(); - if (type == PacketType.EventGodDelete) return new EventGodDeletePacket(); - if (type == PacketType.PickInfoReply) return new PickInfoReplyPacket(); - if (type == PacketType.PickInfoUpdate) return new PickInfoUpdatePacket(); - if (type == PacketType.PickDelete) return new PickDeletePacket(); - if (type == PacketType.PickGodDelete) return new PickGodDeletePacket(); - if (type == PacketType.ScriptQuestion) return new ScriptQuestionPacket(); - if (type == PacketType.ScriptControlChange) return new ScriptControlChangePacket(); - if (type == PacketType.ScriptDialog) return new ScriptDialogPacket(); - if (type == PacketType.ScriptDialogReply) return new ScriptDialogReplyPacket(); - if (type == PacketType.ForceScriptControlRelease) return new ForceScriptControlReleasePacket(); - if (type == PacketType.RevokePermissions) return new RevokePermissionsPacket(); - if (type == PacketType.LoadURL) return new LoadURLPacket(); - if (type == PacketType.ScriptTeleportRequest) return new ScriptTeleportRequestPacket(); - if (type == PacketType.ParcelOverlay) return new ParcelOverlayPacket(); - if (type == PacketType.ParcelPropertiesRequestByID) return new ParcelPropertiesRequestByIDPacket(); - if (type == PacketType.ParcelPropertiesUpdate) return new ParcelPropertiesUpdatePacket(); - if (type == PacketType.ParcelReturnObjects) return new ParcelReturnObjectsPacket(); - if (type == PacketType.ParcelSetOtherCleanTime) return new ParcelSetOtherCleanTimePacket(); - if (type == PacketType.ParcelDisableObjects) return new ParcelDisableObjectsPacket(); - if (type == PacketType.ParcelSelectObjects) return new ParcelSelectObjectsPacket(); - if (type == PacketType.EstateCovenantRequest) return new EstateCovenantRequestPacket(); - if (type == PacketType.EstateCovenantReply) return new EstateCovenantReplyPacket(); - if (type == PacketType.ForceObjectSelect) return new ForceObjectSelectPacket(); - if (type == PacketType.ParcelBuyPass) return new ParcelBuyPassPacket(); - if (type == PacketType.ParcelDeedToGroup) return new ParcelDeedToGroupPacket(); - if (type == PacketType.ParcelReclaim) return new ParcelReclaimPacket(); - if (type == PacketType.ParcelClaim) return new ParcelClaimPacket(); - if (type == PacketType.ParcelJoin) return new ParcelJoinPacket(); - if (type == PacketType.ParcelDivide) return new ParcelDividePacket(); - if (type == PacketType.ParcelRelease) return new ParcelReleasePacket(); - if (type == PacketType.ParcelBuy) return new ParcelBuyPacket(); - if (type == PacketType.ParcelGodForceOwner) return new ParcelGodForceOwnerPacket(); - if (type == PacketType.ParcelAccessListRequest) return new ParcelAccessListRequestPacket(); - if (type == PacketType.ParcelAccessListReply) return new ParcelAccessListReplyPacket(); - if (type == PacketType.ParcelAccessListUpdate) return new ParcelAccessListUpdatePacket(); - if (type == PacketType.ParcelDwellRequest) return new ParcelDwellRequestPacket(); - if (type == PacketType.ParcelDwellReply) return new ParcelDwellReplyPacket(); - if (type == PacketType.ParcelGodMarkAsContent) return new ParcelGodMarkAsContentPacket(); - if (type == PacketType.ViewerStartAuction) return new ViewerStartAuctionPacket(); - if (type == PacketType.UUIDNameRequest) return new UUIDNameRequestPacket(); - if (type == PacketType.UUIDNameReply) return new UUIDNameReplyPacket(); - if (type == PacketType.UUIDGroupNameRequest) return new UUIDGroupNameRequestPacket(); - if (type == PacketType.UUIDGroupNameReply) return new UUIDGroupNameReplyPacket(); - if (type == PacketType.ChildAgentDying) return new ChildAgentDyingPacket(); - if (type == PacketType.ChildAgentUnknown) return new ChildAgentUnknownPacket(); - if (type == PacketType.GetScriptRunning) return new GetScriptRunningPacket(); - if (type == PacketType.ScriptRunningReply) return new ScriptRunningReplyPacket(); - if (type == PacketType.SetScriptRunning) return new SetScriptRunningPacket(); - if (type == PacketType.ScriptReset) return new ScriptResetPacket(); - if (type == PacketType.ScriptSensorRequest) return new ScriptSensorRequestPacket(); - if (type == PacketType.ScriptSensorReply) return new ScriptSensorReplyPacket(); - if (type == PacketType.CompleteAgentMovement) return new CompleteAgentMovementPacket(); - if (type == PacketType.AgentMovementComplete) return new AgentMovementCompletePacket(); - if (type == PacketType.LogoutRequest) return new LogoutRequestPacket(); - if (type == PacketType.LogoutReply) return new LogoutReplyPacket(); - if (type == PacketType.ImprovedInstantMessage) return new ImprovedInstantMessagePacket(); - if (type == PacketType.RetrieveInstantMessages) return new RetrieveInstantMessagesPacket(); - if (type == PacketType.FindAgent) return new FindAgentPacket(); - if (type == PacketType.RequestGodlikePowers) return new RequestGodlikePowersPacket(); - if (type == PacketType.GrantGodlikePowers) return new GrantGodlikePowersPacket(); - if (type == PacketType.GodlikeMessage) return new GodlikeMessagePacket(); - if (type == PacketType.EstateOwnerMessage) return new EstateOwnerMessagePacket(); - if (type == PacketType.GenericMessage) return new GenericMessagePacket(); - if (type == PacketType.MuteListRequest) return new MuteListRequestPacket(); - if (type == PacketType.UpdateMuteListEntry) return new UpdateMuteListEntryPacket(); - if (type == PacketType.RemoveMuteListEntry) return new RemoveMuteListEntryPacket(); - if (type == PacketType.CopyInventoryFromNotecard) return new CopyInventoryFromNotecardPacket(); - if (type == PacketType.UpdateInventoryItem) return new UpdateInventoryItemPacket(); - if (type == PacketType.UpdateCreateInventoryItem) return new UpdateCreateInventoryItemPacket(); - if (type == PacketType.MoveInventoryItem) return new MoveInventoryItemPacket(); - if (type == PacketType.CopyInventoryItem) return new CopyInventoryItemPacket(); - if (type == PacketType.RemoveInventoryItem) return new RemoveInventoryItemPacket(); - if (type == PacketType.ChangeInventoryItemFlags) return new ChangeInventoryItemFlagsPacket(); - if (type == PacketType.SaveAssetIntoInventory) return new SaveAssetIntoInventoryPacket(); - if (type == PacketType.CreateInventoryFolder) return new CreateInventoryFolderPacket(); - if (type == PacketType.UpdateInventoryFolder) return new UpdateInventoryFolderPacket(); - if (type == PacketType.MoveInventoryFolder) return new MoveInventoryFolderPacket(); - if (type == PacketType.RemoveInventoryFolder) return new RemoveInventoryFolderPacket(); - if (type == PacketType.FetchInventoryDescendents) return new FetchInventoryDescendentsPacket(); - if (type == PacketType.InventoryDescendents) return new InventoryDescendentsPacket(); - if (type == PacketType.FetchInventory) return new FetchInventoryPacket(); - if (type == PacketType.FetchInventoryReply) return new FetchInventoryReplyPacket(); - if (type == PacketType.BulkUpdateInventory) return new BulkUpdateInventoryPacket(); - if (type == PacketType.RemoveInventoryObjects) return new RemoveInventoryObjectsPacket(); - if (type == PacketType.PurgeInventoryDescendents) return new PurgeInventoryDescendentsPacket(); - if (type == PacketType.UpdateTaskInventory) return new UpdateTaskInventoryPacket(); - if (type == PacketType.RemoveTaskInventory) return new RemoveTaskInventoryPacket(); - if (type == PacketType.MoveTaskInventory) return new MoveTaskInventoryPacket(); - if (type == PacketType.RequestTaskInventory) return new RequestTaskInventoryPacket(); - if (type == PacketType.ReplyTaskInventory) return new ReplyTaskInventoryPacket(); - if (type == PacketType.DeRezObject) return new DeRezObjectPacket(); - if (type == PacketType.DeRezAck) return new DeRezAckPacket(); - if (type == PacketType.RezObject) return new RezObjectPacket(); - if (type == PacketType.RezObjectFromNotecard) return new RezObjectFromNotecardPacket(); - if (type == PacketType.AcceptFriendship) return new AcceptFriendshipPacket(); - if (type == PacketType.DeclineFriendship) return new DeclineFriendshipPacket(); - if (type == PacketType.TerminateFriendship) return new TerminateFriendshipPacket(); - if (type == PacketType.OfferCallingCard) return new OfferCallingCardPacket(); - if (type == PacketType.AcceptCallingCard) return new AcceptCallingCardPacket(); - if (type == PacketType.DeclineCallingCard) return new DeclineCallingCardPacket(); - if (type == PacketType.RezScript) return new RezScriptPacket(); - if (type == PacketType.CreateInventoryItem) return new CreateInventoryItemPacket(); - if (type == PacketType.CreateLandmarkForEvent) return new CreateLandmarkForEventPacket(); - if (type == PacketType.RegionHandleRequest) return new RegionHandleRequestPacket(); - if (type == PacketType.RegionIDAndHandleReply) return new RegionIDAndHandleReplyPacket(); - if (type == PacketType.MoneyTransferRequest) return new MoneyTransferRequestPacket(); - if (type == PacketType.MoneyBalanceRequest) return new MoneyBalanceRequestPacket(); - if (type == PacketType.MoneyBalanceReply) return new MoneyBalanceReplyPacket(); - if (type == PacketType.RoutedMoneyBalanceReply) return new RoutedMoneyBalanceReplyPacket(); - if (type == PacketType.ActivateGestures) return new ActivateGesturesPacket(); - if (type == PacketType.DeactivateGestures) return new DeactivateGesturesPacket(); - if (type == PacketType.MuteListUpdate) return new MuteListUpdatePacket(); - if (type == PacketType.UseCachedMuteList) return new UseCachedMuteListPacket(); - if (type == PacketType.GrantUserRights) return new GrantUserRightsPacket(); - if (type == PacketType.ChangeUserRights) return new ChangeUserRightsPacket(); - if (type == PacketType.OnlineNotification) return new OnlineNotificationPacket(); - if (type == PacketType.OfflineNotification) return new OfflineNotificationPacket(); - if (type == PacketType.SetStartLocationRequest) return new SetStartLocationRequestPacket(); - if (type == PacketType.AssetUploadRequest) return new AssetUploadRequestPacket(); - if (type == PacketType.AssetUploadComplete) return new AssetUploadCompletePacket(); - if (type == PacketType.CreateGroupRequest) return new CreateGroupRequestPacket(); - if (type == PacketType.CreateGroupReply) return new CreateGroupReplyPacket(); - if (type == PacketType.UpdateGroupInfo) return new UpdateGroupInfoPacket(); - if (type == PacketType.GroupRoleChanges) return new GroupRoleChangesPacket(); - if (type == PacketType.JoinGroupRequest) return new JoinGroupRequestPacket(); - if (type == PacketType.JoinGroupReply) return new JoinGroupReplyPacket(); - if (type == PacketType.EjectGroupMemberRequest) return new EjectGroupMemberRequestPacket(); - if (type == PacketType.EjectGroupMemberReply) return new EjectGroupMemberReplyPacket(); - if (type == PacketType.LeaveGroupRequest) return new LeaveGroupRequestPacket(); - if (type == PacketType.LeaveGroupReply) return new LeaveGroupReplyPacket(); - if (type == PacketType.InviteGroupRequest) return new InviteGroupRequestPacket(); - if (type == PacketType.GroupProfileRequest) return new GroupProfileRequestPacket(); - if (type == PacketType.GroupProfileReply) return new GroupProfileReplyPacket(); - if (type == PacketType.GroupAccountSummaryRequest) return new GroupAccountSummaryRequestPacket(); - if (type == PacketType.GroupAccountSummaryReply) return new GroupAccountSummaryReplyPacket(); - if (type == PacketType.GroupAccountDetailsRequest) return new GroupAccountDetailsRequestPacket(); - if (type == PacketType.GroupAccountDetailsReply) return new GroupAccountDetailsReplyPacket(); - if (type == PacketType.GroupAccountTransactionsRequest) return new GroupAccountTransactionsRequestPacket(); - if (type == PacketType.GroupAccountTransactionsReply) return new GroupAccountTransactionsReplyPacket(); - if (type == PacketType.GroupActiveProposalsRequest) return new GroupActiveProposalsRequestPacket(); - if (type == PacketType.GroupActiveProposalItemReply) return new GroupActiveProposalItemReplyPacket(); - if (type == PacketType.GroupVoteHistoryRequest) return new GroupVoteHistoryRequestPacket(); - if (type == PacketType.GroupVoteHistoryItemReply) return new GroupVoteHistoryItemReplyPacket(); - if (type == PacketType.StartGroupProposal) return new StartGroupProposalPacket(); - if (type == PacketType.GroupProposalBallot) return new GroupProposalBallotPacket(); - if (type == PacketType.GroupMembersRequest) return new GroupMembersRequestPacket(); - if (type == PacketType.GroupMembersReply) return new GroupMembersReplyPacket(); - if (type == PacketType.ActivateGroup) return new ActivateGroupPacket(); - if (type == PacketType.SetGroupContribution) return new SetGroupContributionPacket(); - if (type == PacketType.SetGroupAcceptNotices) return new SetGroupAcceptNoticesPacket(); - if (type == PacketType.GroupRoleDataRequest) return new GroupRoleDataRequestPacket(); - if (type == PacketType.GroupRoleDataReply) return new GroupRoleDataReplyPacket(); - if (type == PacketType.GroupRoleMembersRequest) return new GroupRoleMembersRequestPacket(); - if (type == PacketType.GroupRoleMembersReply) return new GroupRoleMembersReplyPacket(); - if (type == PacketType.GroupTitlesRequest) return new GroupTitlesRequestPacket(); - if (type == PacketType.GroupTitlesReply) return new GroupTitlesReplyPacket(); - if (type == PacketType.GroupTitleUpdate) return new GroupTitleUpdatePacket(); - if (type == PacketType.GroupRoleUpdate) return new GroupRoleUpdatePacket(); - if (type == PacketType.LiveHelpGroupRequest) return new LiveHelpGroupRequestPacket(); - if (type == PacketType.LiveHelpGroupReply) return new LiveHelpGroupReplyPacket(); - if (type == PacketType.AgentWearablesRequest) return new AgentWearablesRequestPacket(); - if (type == PacketType.AgentWearablesUpdate) return new AgentWearablesUpdatePacket(); - if (type == PacketType.AgentIsNowWearing) return new AgentIsNowWearingPacket(); - if (type == PacketType.AgentCachedTexture) return new AgentCachedTexturePacket(); - if (type == PacketType.AgentCachedTextureResponse) return new AgentCachedTextureResponsePacket(); - if (type == PacketType.AgentDataUpdateRequest) return new AgentDataUpdateRequestPacket(); - if (type == PacketType.AgentDataUpdate) return new AgentDataUpdatePacket(); - if (type == PacketType.GroupDataUpdate) return new GroupDataUpdatePacket(); - if (type == PacketType.AgentGroupDataUpdate) return new AgentGroupDataUpdatePacket(); - if (type == PacketType.AgentDropGroup) return new AgentDropGroupPacket(); - if (type == PacketType.RezSingleAttachmentFromInv) return new RezSingleAttachmentFromInvPacket(); - if (type == PacketType.RezMultipleAttachmentsFromInv) return new RezMultipleAttachmentsFromInvPacket(); - if (type == PacketType.DetachAttachmentIntoInv) return new DetachAttachmentIntoInvPacket(); - if (type == PacketType.CreateNewOutfitAttachments) return new CreateNewOutfitAttachmentsPacket(); - if (type == PacketType.UserInfoRequest) return new UserInfoRequestPacket(); - if (type == PacketType.UserInfoReply) return new UserInfoReplyPacket(); - if (type == PacketType.UpdateUserInfo) return new UpdateUserInfoPacket(); - if (type == PacketType.InitiateDownload) return new InitiateDownloadPacket(); - if (type == PacketType.MapLayerRequest) return new MapLayerRequestPacket(); - if (type == PacketType.MapLayerReply) return new MapLayerReplyPacket(); - if (type == PacketType.MapBlockRequest) return new MapBlockRequestPacket(); - if (type == PacketType.MapNameRequest) return new MapNameRequestPacket(); - if (type == PacketType.MapBlockReply) return new MapBlockReplyPacket(); - if (type == PacketType.MapItemRequest) return new MapItemRequestPacket(); - if (type == PacketType.MapItemReply) return new MapItemReplyPacket(); - if (type == PacketType.SendPostcard) return new SendPostcardPacket(); - if (type == PacketType.ParcelMediaCommandMessage) return new ParcelMediaCommandMessagePacket(); - if (type == PacketType.ParcelMediaUpdate) return new ParcelMediaUpdatePacket(); - if (type == PacketType.LandStatRequest) return new LandStatRequestPacket(); - if (type == PacketType.LandStatReply) return new LandStatReplyPacket(); - if (type == PacketType.Error) return new ErrorPacket(); - if (type == PacketType.ObjectIncludeInSearch) return new ObjectIncludeInSearchPacket(); - if (type == PacketType.RezRestoreToWorld) return new RezRestoreToWorldPacket(); - if (type == PacketType.LinkInventoryItem) return new LinkInventoryItemPacket(); - if(type == PacketType.LargeGenericMessage) return new LargeGenericMessagePacket(); - if (type == PacketType.PacketAck) return new PacketAckPacket(); - if (type == PacketType.OpenCircuit) return new OpenCircuitPacket(); - if (type == PacketType.CloseCircuit) return new CloseCircuitPacket(); - return null; - - } - - public static Packet BuildPacket(byte[] packetBuffer, ref int packetEnd, byte[] zeroBuffer) + public static Packet BuildPacket(PacketType type) + { + switch(type) + { + case PacketType.StartPingCheck: return new StartPingCheckPacket(); + case PacketType.CompletePingCheck: return new CompletePingCheckPacket(); + case PacketType.AgentUpdate: return new AgentUpdatePacket(); + case PacketType.AgentAnimation: return new AgentAnimationPacket(); + case PacketType.AgentRequestSit: return new AgentRequestSitPacket(); + case PacketType.AgentSit: return new AgentSitPacket(); + case PacketType.RequestImage: return new RequestImagePacket(); + case PacketType.ImageData: return new ImageDataPacket(); + case PacketType.ImagePacket: return new ImagePacketPacket(); + case PacketType.LayerData: return new LayerDataPacket(); + case PacketType.ObjectUpdate: return new ObjectUpdatePacket(); + case PacketType.ObjectUpdateCompressed: return new ObjectUpdateCompressedPacket(); + case PacketType.ObjectUpdateCached: return new ObjectUpdateCachedPacket(); + case PacketType.ImprovedTerseObjectUpdate: return new ImprovedTerseObjectUpdatePacket(); + case PacketType.KillObject: return new KillObjectPacket(); + case PacketType.TransferPacket: return new TransferPacketPacket(); + case PacketType.SendXferPacket: return new SendXferPacketPacket(); + case PacketType.ConfirmXferPacket: return new ConfirmXferPacketPacket(); + case PacketType.AvatarAnimation: return new AvatarAnimationPacket(); + case PacketType.AvatarSitResponse: return new AvatarSitResponsePacket(); + case PacketType.CameraConstraint: return new CameraConstraintPacket(); + case PacketType.ParcelProperties: return new ParcelPropertiesPacket(); + case PacketType.ChildAgentUpdate: return new ChildAgentUpdatePacket(); + case PacketType.ChildAgentAlive: return new ChildAgentAlivePacket(); + case PacketType.ChildAgentPositionUpdate: return new ChildAgentPositionUpdatePacket(); + case PacketType.SoundTrigger: return new SoundTriggerPacket(); + case PacketType.ObjectAnimation: return new ObjectAnimationPacket(); + case PacketType.GenericStreamingMessage: return new GenericStreamingMessagePacket(); + case PacketType.ObjectAdd: return new ObjectAddPacket(); + case PacketType.MultipleObjectUpdate: return new MultipleObjectUpdatePacket(); + case PacketType.RequestMultipleObjects: return new RequestMultipleObjectsPacket(); + case PacketType.ObjectPosition: return new ObjectPositionPacket(); + case PacketType.RequestObjectPropertiesFamily: return new RequestObjectPropertiesFamilyPacket(); + case PacketType.CoarseLocationUpdate: return new CoarseLocationUpdatePacket(); + case PacketType.CrossedRegion: return new CrossedRegionPacket(); + case PacketType.ConfirmEnableSimulator: return new ConfirmEnableSimulatorPacket(); + case PacketType.ObjectProperties: return new ObjectPropertiesPacket(); + case PacketType.ObjectPropertiesFamily: return new ObjectPropertiesFamilyPacket(); + case PacketType.ParcelPropertiesRequest: return new ParcelPropertiesRequestPacket(); + case PacketType.AttachedSound: return new AttachedSoundPacket(); + case PacketType.AttachedSoundGainChange: return new AttachedSoundGainChangePacket(); + case PacketType.PreloadSound: return new PreloadSoundPacket(); + case PacketType.ViewerEffect: return new ViewerEffectPacket(); + case PacketType.TestMessage: return new TestMessagePacket(); + case PacketType.UseCircuitCode: return new UseCircuitCodePacket(); + case PacketType.TelehubInfo: return new TelehubInfoPacket(); + case PacketType.EconomyDataRequest: return new EconomyDataRequestPacket(); + case PacketType.EconomyData: return new EconomyDataPacket(); + case PacketType.AvatarPickerRequest: return new AvatarPickerRequestPacket(); + case PacketType.AvatarPickerReply: return new AvatarPickerReplyPacket(); + case PacketType.PlacesQuery: return new PlacesQueryPacket(); + case PacketType.PlacesReply: return new PlacesReplyPacket(); + case PacketType.DirFindQuery: return new DirFindQueryPacket(); + case PacketType.DirPlacesQuery: return new DirPlacesQueryPacket(); + case PacketType.DirPlacesReply: return new DirPlacesReplyPacket(); + case PacketType.DirPeopleReply: return new DirPeopleReplyPacket(); + case PacketType.DirEventsReply: return new DirEventsReplyPacket(); + case PacketType.DirGroupsReply: return new DirGroupsReplyPacket(); + case PacketType.DirClassifiedQuery: return new DirClassifiedQueryPacket(); + case PacketType.DirClassifiedReply: return new DirClassifiedReplyPacket(); + case PacketType.AvatarClassifiedReply: return new AvatarClassifiedReplyPacket(); + case PacketType.ClassifiedInfoRequest: return new ClassifiedInfoRequestPacket(); + case PacketType.ClassifiedInfoReply: return new ClassifiedInfoReplyPacket(); + case PacketType.ClassifiedInfoUpdate: return new ClassifiedInfoUpdatePacket(); + case PacketType.ClassifiedDelete: return new ClassifiedDeletePacket(); + case PacketType.ClassifiedGodDelete: return new ClassifiedGodDeletePacket(); + case PacketType.DirLandQuery: return new DirLandQueryPacket(); + case PacketType.DirLandReply: return new DirLandReplyPacket(); + case PacketType.DirPopularQuery: return new DirPopularQueryPacket(); + case PacketType.DirPopularReply: return new DirPopularReplyPacket(); + case PacketType.ParcelInfoRequest: return new ParcelInfoRequestPacket(); + case PacketType.ParcelInfoReply: return new ParcelInfoReplyPacket(); + case PacketType.ParcelObjectOwnersRequest: return new ParcelObjectOwnersRequestPacket(); + case PacketType.ParcelObjectOwnersReply: return new ParcelObjectOwnersReplyPacket(); + case PacketType.GroupNoticesListRequest: return new GroupNoticesListRequestPacket(); + case PacketType.GroupNoticesListReply: return new GroupNoticesListReplyPacket(); + case PacketType.GroupNoticeRequest: return new GroupNoticeRequestPacket(); + case PacketType.TeleportRequest: return new TeleportRequestPacket(); + case PacketType.TeleportLocationRequest: return new TeleportLocationRequestPacket(); + case PacketType.TeleportLocal: return new TeleportLocalPacket(); + case PacketType.TeleportLandmarkRequest: return new TeleportLandmarkRequestPacket(); + case PacketType.TeleportProgress: return new TeleportProgressPacket(); + case PacketType.TeleportFinish: return new TeleportFinishPacket(); + case PacketType.StartLure: return new StartLurePacket(); + case PacketType.TeleportLureRequest: return new TeleportLureRequestPacket(); + case PacketType.TeleportCancel: return new TeleportCancelPacket(); + case PacketType.TeleportStart: return new TeleportStartPacket(); + case PacketType.TeleportFailed: return new TeleportFailedPacket(); + case PacketType.Undo: return new UndoPacket(); + case PacketType.Redo: return new RedoPacket(); + case PacketType.UndoLand: return new UndoLandPacket(); + case PacketType.AgentPause: return new AgentPausePacket(); + case PacketType.AgentResume: return new AgentResumePacket(); + case PacketType.ChatFromViewer: return new ChatFromViewerPacket(); + case PacketType.AgentThrottle: return new AgentThrottlePacket(); + case PacketType.AgentFOV: return new AgentFOVPacket(); + case PacketType.AgentHeightWidth: return new AgentHeightWidthPacket(); + case PacketType.AgentSetAppearance: return new AgentSetAppearancePacket(); + case PacketType.AgentQuitCopy: return new AgentQuitCopyPacket(); + case PacketType.ImageNotInDatabase: return new ImageNotInDatabasePacket(); + case PacketType.RebakeAvatarTextures: return new RebakeAvatarTexturesPacket(); + case PacketType.SetAlwaysRun: return new SetAlwaysRunPacket(); + case PacketType.ObjectDelete: return new ObjectDeletePacket(); + case PacketType.ObjectDuplicate: return new ObjectDuplicatePacket(); + case PacketType.ObjectDuplicateOnRay: return new ObjectDuplicateOnRayPacket(); + case PacketType.ObjectScale: return new ObjectScalePacket(); + case PacketType.ObjectRotation: return new ObjectRotationPacket(); + case PacketType.ObjectFlagUpdate: return new ObjectFlagUpdatePacket(); + case PacketType.ObjectClickAction: return new ObjectClickActionPacket(); + case PacketType.ObjectImage: return new ObjectImagePacket(); + case PacketType.ObjectMaterial: return new ObjectMaterialPacket(); + case PacketType.ObjectShape: return new ObjectShapePacket(); + case PacketType.ObjectExtraParams: return new ObjectExtraParamsPacket(); + case PacketType.ObjectOwner: return new ObjectOwnerPacket(); + case PacketType.ObjectGroup: return new ObjectGroupPacket(); + case PacketType.ObjectBuy: return new ObjectBuyPacket(); + case PacketType.BuyObjectInventory: return new BuyObjectInventoryPacket(); + case PacketType.DerezContainer: return new DerezContainerPacket(); + case PacketType.ObjectPermissions: return new ObjectPermissionsPacket(); + case PacketType.ObjectSaleInfo: return new ObjectSaleInfoPacket(); + case PacketType.ObjectName: return new ObjectNamePacket(); + case PacketType.ObjectDescription: return new ObjectDescriptionPacket(); + case PacketType.ObjectCategory: return new ObjectCategoryPacket(); + case PacketType.ObjectSelect: return new ObjectSelectPacket(); + case PacketType.ObjectDeselect: return new ObjectDeselectPacket(); + case PacketType.ObjectAttach: return new ObjectAttachPacket(); + case PacketType.ObjectDetach: return new ObjectDetachPacket(); + case PacketType.ObjectDrop: return new ObjectDropPacket(); + case PacketType.ObjectLink: return new ObjectLinkPacket(); + case PacketType.ObjectDelink: return new ObjectDelinkPacket(); + case PacketType.ObjectGrab: return new ObjectGrabPacket(); + case PacketType.ObjectGrabUpdate: return new ObjectGrabUpdatePacket(); + case PacketType.ObjectDeGrab: return new ObjectDeGrabPacket(); + case PacketType.ObjectSpinStart: return new ObjectSpinStartPacket(); + case PacketType.ObjectSpinUpdate: return new ObjectSpinUpdatePacket(); + case PacketType.ObjectSpinStop: return new ObjectSpinStopPacket(); + case PacketType.ObjectExportSelected: return new ObjectExportSelectedPacket(); + case PacketType.ModifyLand: return new ModifyLandPacket(); + case PacketType.VelocityInterpolateOn: return new VelocityInterpolateOnPacket(); + case PacketType.VelocityInterpolateOff: return new VelocityInterpolateOffPacket(); + case PacketType.StateSave: return new StateSavePacket(); + case PacketType.ReportAutosaveCrash: return new ReportAutosaveCrashPacket(); + case PacketType.SimWideDeletes: return new SimWideDeletesPacket(); + case PacketType.TrackAgent: return new TrackAgentPacket(); + case PacketType.ViewerStats: return new ViewerStatsPacket(); + case PacketType.ScriptAnswerYes: return new ScriptAnswerYesPacket(); + case PacketType.UserReport: return new UserReportPacket(); + case PacketType.AlertMessage: return new AlertMessagePacket(); + case PacketType.AgentAlertMessage: return new AgentAlertMessagePacket(); + case PacketType.MeanCollisionAlert: return new MeanCollisionAlertPacket(); + case PacketType.ViewerFrozenMessage: return new ViewerFrozenMessagePacket(); + case PacketType.HealthMessage: return new HealthMessagePacket(); + case PacketType.ChatFromSimulator: return new ChatFromSimulatorPacket(); + case PacketType.SimStats: return new SimStatsPacket(); + case PacketType.RequestRegionInfo: return new RequestRegionInfoPacket(); + case PacketType.RegionInfo: return new RegionInfoPacket(); + case PacketType.GodUpdateRegionInfo: return new GodUpdateRegionInfoPacket(); + case PacketType.RegionHandshake: return new RegionHandshakePacket(); + case PacketType.RegionHandshakeReply: return new RegionHandshakeReplyPacket(); + case PacketType.SimulatorViewerTimeMessage: return new SimulatorViewerTimeMessagePacket(); + case PacketType.EnableSimulator: return new EnableSimulatorPacket(); + case PacketType.DisableSimulator: return new DisableSimulatorPacket(); + case PacketType.TransferRequest: return new TransferRequestPacket(); + case PacketType.TransferInfo: return new TransferInfoPacket(); + case PacketType.TransferAbort: return new TransferAbortPacket(); + case PacketType.RequestXfer: return new RequestXferPacket(); + case PacketType.AbortXfer: return new AbortXferPacket(); + case PacketType.AvatarAppearance: return new AvatarAppearancePacket(); + case PacketType.SetFollowCamProperties: return new SetFollowCamPropertiesPacket(); + case PacketType.ClearFollowCamProperties: return new ClearFollowCamPropertiesPacket(); + case PacketType.RequestPayPrice: return new RequestPayPricePacket(); + case PacketType.PayPriceReply: return new PayPriceReplyPacket(); + case PacketType.KickUser: return new KickUserPacket(); + case PacketType.GodKickUser: return new GodKickUserPacket(); + case PacketType.EjectUser: return new EjectUserPacket(); + case PacketType.FreezeUser: return new FreezeUserPacket(); + case PacketType.AvatarPropertiesRequest: return new AvatarPropertiesRequestPacket(); + case PacketType.AvatarPropertiesReply: return new AvatarPropertiesReplyPacket(); + case PacketType.AvatarInterestsReply: return new AvatarInterestsReplyPacket(); + case PacketType.AvatarGroupsReply: return new AvatarGroupsReplyPacket(); + case PacketType.AvatarPropertiesUpdate: return new AvatarPropertiesUpdatePacket(); + case PacketType.AvatarInterestsUpdate: return new AvatarInterestsUpdatePacket(); + case PacketType.AvatarNotesReply: return new AvatarNotesReplyPacket(); + case PacketType.AvatarNotesUpdate: return new AvatarNotesUpdatePacket(); + case PacketType.AvatarPicksReply: return new AvatarPicksReplyPacket(); + case PacketType.EventInfoRequest: return new EventInfoRequestPacket(); + case PacketType.EventInfoReply: return new EventInfoReplyPacket(); + case PacketType.EventNotificationAddRequest: return new EventNotificationAddRequestPacket(); + case PacketType.EventNotificationRemoveRequest: return new EventNotificationRemoveRequestPacket(); + case PacketType.EventGodDelete: return new EventGodDeletePacket(); + case PacketType.PickInfoReply: return new PickInfoReplyPacket(); + case PacketType.PickInfoUpdate: return new PickInfoUpdatePacket(); + case PacketType.PickDelete: return new PickDeletePacket(); + case PacketType.PickGodDelete: return new PickGodDeletePacket(); + case PacketType.ScriptQuestion: return new ScriptQuestionPacket(); + case PacketType.ScriptControlChange: return new ScriptControlChangePacket(); + case PacketType.ScriptDialog: return new ScriptDialogPacket(); + case PacketType.ScriptDialogReply: return new ScriptDialogReplyPacket(); + case PacketType.ForceScriptControlRelease: return new ForceScriptControlReleasePacket(); + case PacketType.RevokePermissions: return new RevokePermissionsPacket(); + case PacketType.LoadURL: return new LoadURLPacket(); + case PacketType.ScriptTeleportRequest: return new ScriptTeleportRequestPacket(); + case PacketType.ParcelOverlay: return new ParcelOverlayPacket(); + case PacketType.ParcelPropertiesRequestByID: return new ParcelPropertiesRequestByIDPacket(); + case PacketType.ParcelPropertiesUpdate: return new ParcelPropertiesUpdatePacket(); + case PacketType.ParcelReturnObjects: return new ParcelReturnObjectsPacket(); + case PacketType.ParcelSetOtherCleanTime: return new ParcelSetOtherCleanTimePacket(); + case PacketType.ParcelDisableObjects: return new ParcelDisableObjectsPacket(); + case PacketType.ParcelSelectObjects: return new ParcelSelectObjectsPacket(); + case PacketType.EstateCovenantRequest: return new EstateCovenantRequestPacket(); + case PacketType.EstateCovenantReply: return new EstateCovenantReplyPacket(); + case PacketType.ForceObjectSelect: return new ForceObjectSelectPacket(); + case PacketType.ParcelBuyPass: return new ParcelBuyPassPacket(); + case PacketType.ParcelDeedToGroup: return new ParcelDeedToGroupPacket(); + case PacketType.ParcelReclaim: return new ParcelReclaimPacket(); + case PacketType.ParcelClaim: return new ParcelClaimPacket(); + case PacketType.ParcelJoin: return new ParcelJoinPacket(); + case PacketType.ParcelDivide: return new ParcelDividePacket(); + case PacketType.ParcelRelease: return new ParcelReleasePacket(); + case PacketType.ParcelBuy: return new ParcelBuyPacket(); + case PacketType.ParcelGodForceOwner: return new ParcelGodForceOwnerPacket(); + case PacketType.ParcelAccessListRequest: return new ParcelAccessListRequestPacket(); + case PacketType.ParcelAccessListReply: return new ParcelAccessListReplyPacket(); + case PacketType.ParcelAccessListUpdate: return new ParcelAccessListUpdatePacket(); + case PacketType.ParcelDwellRequest: return new ParcelDwellRequestPacket(); + case PacketType.ParcelDwellReply: return new ParcelDwellReplyPacket(); + case PacketType.ParcelGodMarkAsContent: return new ParcelGodMarkAsContentPacket(); + case PacketType.ViewerStartAuction: return new ViewerStartAuctionPacket(); + case PacketType.UUIDNameRequest: return new UUIDNameRequestPacket(); + case PacketType.UUIDNameReply: return new UUIDNameReplyPacket(); + case PacketType.UUIDGroupNameRequest: return new UUIDGroupNameRequestPacket(); + case PacketType.UUIDGroupNameReply: return new UUIDGroupNameReplyPacket(); + case PacketType.ChildAgentDying: return new ChildAgentDyingPacket(); + case PacketType.ChildAgentUnknown: return new ChildAgentUnknownPacket(); + case PacketType.GetScriptRunning: return new GetScriptRunningPacket(); + case PacketType.ScriptRunningReply: return new ScriptRunningReplyPacket(); + case PacketType.SetScriptRunning: return new SetScriptRunningPacket(); + case PacketType.ScriptReset: return new ScriptResetPacket(); + case PacketType.ScriptSensorRequest: return new ScriptSensorRequestPacket(); + case PacketType.ScriptSensorReply: return new ScriptSensorReplyPacket(); + case PacketType.CompleteAgentMovement: return new CompleteAgentMovementPacket(); + case PacketType.AgentMovementComplete: return new AgentMovementCompletePacket(); + case PacketType.LogoutRequest: return new LogoutRequestPacket(); + case PacketType.LogoutReply: return new LogoutReplyPacket(); + case PacketType.ImprovedInstantMessage: return new ImprovedInstantMessagePacket(); + case PacketType.RetrieveInstantMessages: return new RetrieveInstantMessagesPacket(); + case PacketType.FindAgent: return new FindAgentPacket(); + case PacketType.RequestGodlikePowers: return new RequestGodlikePowersPacket(); + case PacketType.GrantGodlikePowers: return new GrantGodlikePowersPacket(); + case PacketType.GodlikeMessage: return new GodlikeMessagePacket(); + case PacketType.EstateOwnerMessage: return new EstateOwnerMessagePacket(); + case PacketType.GenericMessage: return new GenericMessagePacket(); + case PacketType.MuteListRequest: return new MuteListRequestPacket(); + case PacketType.UpdateMuteListEntry: return new UpdateMuteListEntryPacket(); + case PacketType.RemoveMuteListEntry: return new RemoveMuteListEntryPacket(); + case PacketType.CopyInventoryFromNotecard: return new CopyInventoryFromNotecardPacket(); + case PacketType.UpdateInventoryItem: return new UpdateInventoryItemPacket(); + case PacketType.UpdateCreateInventoryItem: return new UpdateCreateInventoryItemPacket(); + case PacketType.MoveInventoryItem: return new MoveInventoryItemPacket(); + case PacketType.CopyInventoryItem: return new CopyInventoryItemPacket(); + case PacketType.RemoveInventoryItem: return new RemoveInventoryItemPacket(); + case PacketType.ChangeInventoryItemFlags: return new ChangeInventoryItemFlagsPacket(); + case PacketType.SaveAssetIntoInventory: return new SaveAssetIntoInventoryPacket(); + case PacketType.CreateInventoryFolder: return new CreateInventoryFolderPacket(); + case PacketType.UpdateInventoryFolder: return new UpdateInventoryFolderPacket(); + case PacketType.MoveInventoryFolder: return new MoveInventoryFolderPacket(); + case PacketType.RemoveInventoryFolder: return new RemoveInventoryFolderPacket(); + case PacketType.FetchInventoryDescendents: return new FetchInventoryDescendentsPacket(); + case PacketType.InventoryDescendents: return new InventoryDescendentsPacket(); + case PacketType.FetchInventory: return new FetchInventoryPacket(); + case PacketType.FetchInventoryReply: return new FetchInventoryReplyPacket(); + case PacketType.BulkUpdateInventory: return new BulkUpdateInventoryPacket(); + case PacketType.RemoveInventoryObjects: return new RemoveInventoryObjectsPacket(); + case PacketType.PurgeInventoryDescendents: return new PurgeInventoryDescendentsPacket(); + case PacketType.UpdateTaskInventory: return new UpdateTaskInventoryPacket(); + case PacketType.RemoveTaskInventory: return new RemoveTaskInventoryPacket(); + case PacketType.MoveTaskInventory: return new MoveTaskInventoryPacket(); + case PacketType.RequestTaskInventory: return new RequestTaskInventoryPacket(); + case PacketType.ReplyTaskInventory: return new ReplyTaskInventoryPacket(); + case PacketType.DeRezObject: return new DeRezObjectPacket(); + case PacketType.DeRezAck: return new DeRezAckPacket(); + case PacketType.RezObject: return new RezObjectPacket(); + case PacketType.RezObjectFromNotecard: return new RezObjectFromNotecardPacket(); + case PacketType.AcceptFriendship: return new AcceptFriendshipPacket(); + case PacketType.DeclineFriendship: return new DeclineFriendshipPacket(); + case PacketType.TerminateFriendship: return new TerminateFriendshipPacket(); + case PacketType.OfferCallingCard: return new OfferCallingCardPacket(); + case PacketType.AcceptCallingCard: return new AcceptCallingCardPacket(); + case PacketType.DeclineCallingCard: return new DeclineCallingCardPacket(); + case PacketType.RezScript: return new RezScriptPacket(); + case PacketType.CreateInventoryItem: return new CreateInventoryItemPacket(); + case PacketType.CreateLandmarkForEvent: return new CreateLandmarkForEventPacket(); + case PacketType.RegionHandleRequest: return new RegionHandleRequestPacket(); + case PacketType.RegionIDAndHandleReply: return new RegionIDAndHandleReplyPacket(); + case PacketType.MoneyTransferRequest: return new MoneyTransferRequestPacket(); + case PacketType.MoneyBalanceRequest: return new MoneyBalanceRequestPacket(); + case PacketType.MoneyBalanceReply: return new MoneyBalanceReplyPacket(); + case PacketType.RoutedMoneyBalanceReply: return new RoutedMoneyBalanceReplyPacket(); + case PacketType.ActivateGestures: return new ActivateGesturesPacket(); + case PacketType.DeactivateGestures: return new DeactivateGesturesPacket(); + case PacketType.MuteListUpdate: return new MuteListUpdatePacket(); + case PacketType.UseCachedMuteList: return new UseCachedMuteListPacket(); + case PacketType.GrantUserRights: return new GrantUserRightsPacket(); + case PacketType.ChangeUserRights: return new ChangeUserRightsPacket(); + case PacketType.OnlineNotification: return new OnlineNotificationPacket(); + case PacketType.OfflineNotification: return new OfflineNotificationPacket(); + case PacketType.SetStartLocationRequest: return new SetStartLocationRequestPacket(); + case PacketType.AssetUploadRequest: return new AssetUploadRequestPacket(); + case PacketType.AssetUploadComplete: return new AssetUploadCompletePacket(); + case PacketType.CreateGroupRequest: return new CreateGroupRequestPacket(); + case PacketType.CreateGroupReply: return new CreateGroupReplyPacket(); + case PacketType.UpdateGroupInfo: return new UpdateGroupInfoPacket(); + case PacketType.GroupRoleChanges: return new GroupRoleChangesPacket(); + case PacketType.JoinGroupRequest: return new JoinGroupRequestPacket(); + case PacketType.JoinGroupReply: return new JoinGroupReplyPacket(); + case PacketType.EjectGroupMemberRequest: return new EjectGroupMemberRequestPacket(); + case PacketType.EjectGroupMemberReply: return new EjectGroupMemberReplyPacket(); + case PacketType.LeaveGroupRequest: return new LeaveGroupRequestPacket(); + case PacketType.LeaveGroupReply: return new LeaveGroupReplyPacket(); + case PacketType.InviteGroupRequest: return new InviteGroupRequestPacket(); + case PacketType.GroupProfileRequest: return new GroupProfileRequestPacket(); + case PacketType.GroupProfileReply: return new GroupProfileReplyPacket(); + case PacketType.GroupAccountSummaryRequest: return new GroupAccountSummaryRequestPacket(); + case PacketType.GroupAccountSummaryReply: return new GroupAccountSummaryReplyPacket(); + case PacketType.GroupAccountDetailsRequest: return new GroupAccountDetailsRequestPacket(); + case PacketType.GroupAccountDetailsReply: return new GroupAccountDetailsReplyPacket(); + case PacketType.GroupAccountTransactionsRequest: return new GroupAccountTransactionsRequestPacket(); + case PacketType.GroupAccountTransactionsReply: return new GroupAccountTransactionsReplyPacket(); + case PacketType.GroupActiveProposalsRequest: return new GroupActiveProposalsRequestPacket(); + case PacketType.GroupActiveProposalItemReply: return new GroupActiveProposalItemReplyPacket(); + case PacketType.GroupVoteHistoryRequest: return new GroupVoteHistoryRequestPacket(); + case PacketType.GroupVoteHistoryItemReply: return new GroupVoteHistoryItemReplyPacket(); + case PacketType.StartGroupProposal: return new StartGroupProposalPacket(); + case PacketType.GroupProposalBallot: return new GroupProposalBallotPacket(); + case PacketType.GroupMembersRequest: return new GroupMembersRequestPacket(); + case PacketType.GroupMembersReply: return new GroupMembersReplyPacket(); + case PacketType.ActivateGroup: return new ActivateGroupPacket(); + case PacketType.SetGroupContribution: return new SetGroupContributionPacket(); + case PacketType.SetGroupAcceptNotices: return new SetGroupAcceptNoticesPacket(); + case PacketType.GroupRoleDataRequest: return new GroupRoleDataRequestPacket(); + case PacketType.GroupRoleDataReply: return new GroupRoleDataReplyPacket(); + case PacketType.GroupRoleMembersRequest: return new GroupRoleMembersRequestPacket(); + case PacketType.GroupRoleMembersReply: return new GroupRoleMembersReplyPacket(); + case PacketType.GroupTitlesRequest: return new GroupTitlesRequestPacket(); + case PacketType.GroupTitlesReply: return new GroupTitlesReplyPacket(); + case PacketType.GroupTitleUpdate: return new GroupTitleUpdatePacket(); + case PacketType.GroupRoleUpdate: return new GroupRoleUpdatePacket(); + case PacketType.LiveHelpGroupRequest: return new LiveHelpGroupRequestPacket(); + case PacketType.LiveHelpGroupReply: return new LiveHelpGroupReplyPacket(); + case PacketType.AgentWearablesRequest: return new AgentWearablesRequestPacket(); + case PacketType.AgentWearablesUpdate: return new AgentWearablesUpdatePacket(); + case PacketType.AgentIsNowWearing: return new AgentIsNowWearingPacket(); + case PacketType.AgentCachedTexture: return new AgentCachedTexturePacket(); + case PacketType.AgentCachedTextureResponse: return new AgentCachedTextureResponsePacket(); + case PacketType.AgentDataUpdateRequest: return new AgentDataUpdateRequestPacket(); + case PacketType.AgentDataUpdate: return new AgentDataUpdatePacket(); + case PacketType.GroupDataUpdate: return new GroupDataUpdatePacket(); + case PacketType.AgentGroupDataUpdate: return new AgentGroupDataUpdatePacket(); + case PacketType.AgentDropGroup: return new AgentDropGroupPacket(); + case PacketType.RezSingleAttachmentFromInv: return new RezSingleAttachmentFromInvPacket(); + case PacketType.RezMultipleAttachmentsFromInv: return new RezMultipleAttachmentsFromInvPacket(); + case PacketType.DetachAttachmentIntoInv: return new DetachAttachmentIntoInvPacket(); + case PacketType.CreateNewOutfitAttachments: return new CreateNewOutfitAttachmentsPacket(); + case PacketType.UserInfoRequest: return new UserInfoRequestPacket(); + case PacketType.UserInfoReply: return new UserInfoReplyPacket(); + case PacketType.UpdateUserInfo: return new UpdateUserInfoPacket(); + case PacketType.InitiateDownload: return new InitiateDownloadPacket(); + case PacketType.MapLayerRequest: return new MapLayerRequestPacket(); + case PacketType.MapLayerReply: return new MapLayerReplyPacket(); + case PacketType.MapBlockRequest: return new MapBlockRequestPacket(); + case PacketType.MapNameRequest: return new MapNameRequestPacket(); + case PacketType.MapBlockReply: return new MapBlockReplyPacket(); + case PacketType.MapItemRequest: return new MapItemRequestPacket(); + case PacketType.MapItemReply: return new MapItemReplyPacket(); + case PacketType.SendPostcard: return new SendPostcardPacket(); + case PacketType.ParcelMediaCommandMessage: return new ParcelMediaCommandMessagePacket(); + case PacketType.ParcelMediaUpdate: return new ParcelMediaUpdatePacket(); + case PacketType.LandStatRequest: return new LandStatRequestPacket(); + case PacketType.LandStatReply: return new LandStatReplyPacket(); + case PacketType.Error: return new ErrorPacket(); + case PacketType.ObjectIncludeInSearch: return new ObjectIncludeInSearchPacket(); + case PacketType.RezRestoreToWorld: return new RezRestoreToWorldPacket(); + case PacketType.LinkInventoryItem: return new LinkInventoryItemPacket(); + case PacketType.LargeGenericMessage: return new LargeGenericMessagePacket(); + case PacketType.PacketAck: return new PacketAckPacket(); + case PacketType.OpenCircuit: return new OpenCircuitPacket(); + case PacketType.CloseCircuit: return new CloseCircuitPacket(); + } + return null; + } + + public static Packet BuildPacket(byte[] packetBuffer, ref int packetLength, byte[] zeroBuffer) { byte[] bytes; int i = 0; - Header header = Header.BuildHeader(packetBuffer, ref i, ref packetEnd); + Header header = Header.BuildHeader(packetBuffer, ref i, ref packetLength); if (header.Zerocoded) { - packetEnd = Helpers.ZeroDecode(packetBuffer, packetEnd + 1, zeroBuffer) - 1; + packetLength = Helpers.ZeroDecode(packetBuffer, packetLength, zeroBuffer); bytes = zeroBuffer; } else { bytes = packetBuffer; } - Array.Clear(bytes, packetEnd + 1, bytes.Length - packetEnd - 1); + //Array.Clear(bytes, packetEnd + 1, bytes.Length - packetEnd - 1); switch (header.Frequency) { @@ -1895,6 +1946,7 @@ public static Packet BuildPacket(byte[] packetBuffer, ref int packetEnd, byte[] case 27: return new ChildAgentPositionUpdatePacket(header, bytes, ref i); case 29: return new SoundTriggerPacket(header, bytes, ref i); case 30: return new ObjectAnimationPacket(header, bytes, ref i); + case 31: return new GenericStreamingMessagePacket(header, bytes, ref i); } break; @@ -2010,6 +2062,7 @@ public TestMessagePacket() Header.Frequency = PacketFrequency.Low; Header.ID = 1; Header.Reliable = true; + NeedValidateIDs = false; Header.Zerocoded = true; TestBlock1 = new TestBlock1Block(); NeighborBlock = new NeighborBlockBlock[4]; @@ -2042,11 +2095,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public TestMessagePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; TestBlock1.FromBytes(bytes, ref i); @@ -2147,6 +2199,7 @@ public UseCircuitCodePacket() Header.Frequency = PacketFrequency.Low; Header.ID = 3; Header.Reliable = true; + NeedValidateIDs = false; CircuitCode = new CircuitCodeBlock(); } @@ -2169,11 +2222,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public UseCircuitCodePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; CircuitCode.FromBytes(bytes, ref i); @@ -2231,7 +2283,7 @@ public override void FromBytes(byte[] bytes, ref int i) try { ObjectID.FromBytes(bytes, i); i += 16; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); ObjectName = new byte[length]; Buffer.BlockCopy(bytes, i, ObjectName, 0, length); i += length; TelehubPos.FromBytes(bytes, i); i += 12; @@ -2246,7 +2298,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { ObjectID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)ObjectName.Length; + Utils.ByteToBytes((byte)ObjectName.Length, bytes, ref i); Buffer.BlockCopy(ObjectName, 0, bytes, i, ObjectName.Length); i += ObjectName.Length; TelehubPos.ToBytes(bytes, i); i += 12; TelehubRot.ToBytes(bytes, i); i += 12; @@ -2314,6 +2366,7 @@ public TelehubInfoPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 10; Header.Reliable = true; + NeedValidateIDs = false; TelehubBlock = new TelehubBlockBlock(); SpawnPointBlock = null; } @@ -2346,11 +2399,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public TelehubInfoPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; TelehubBlock.FromBytes(bytes, ref i); @@ -2376,7 +2428,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); TelehubBlock.ToBytes(bytes, ref i); - bytes[i++] = (byte)SpawnPointBlock.Length; + Utils.ByteToBytes((byte)SpawnPointBlock.Length, bytes, ref i); for (int j = 0; j < SpawnPointBlock.Length; j++) { SpawnPointBlock[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -2465,6 +2517,7 @@ public EconomyDataRequestPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 24; Header.Reliable = true; + NeedValidateIDs = false; } public EconomyDataRequestPacket(byte[] bytes, ref int i) : this() @@ -2485,11 +2538,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public EconomyDataRequestPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; } @@ -2619,6 +2671,7 @@ public EconomyDataPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 25; Header.Reliable = true; + NeedValidateIDs = false; Header.Zerocoded = true; Info = new InfoBlock(); } @@ -2642,11 +2695,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public EconomyDataPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; Info.FromBytes(bytes, ref i); @@ -2744,7 +2796,7 @@ public override void FromBytes(byte[] bytes, ref int i) int length; try { - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Name = new byte[length]; Buffer.BlockCopy(bytes, i, Name, 0, length); i += length; } @@ -2756,7 +2808,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = (byte)Name.Length; + Utils.ByteToBytes((byte)Name.Length, bytes, ref i); Buffer.BlockCopy(Name, 0, bytes, i, Name.Length); i += Name.Length; } @@ -2775,6 +2827,8 @@ public override int Length public AgentDataBlock AgentData; public DataBlock Data; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public AvatarPickerRequestPacket() { HasVariableBlocks = false; @@ -2783,6 +2837,7 @@ public AvatarPickerRequestPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 26; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); Data = new DataBlock(); } @@ -2807,11 +2862,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public AvatarPickerRequestPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -2913,10 +2967,10 @@ public override void FromBytes(byte[] bytes, ref int i) try { AvatarID.FromBytes(bytes, i); i += 16; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); FirstName = new byte[length]; Buffer.BlockCopy(bytes, i, FirstName, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); LastName = new byte[length]; Buffer.BlockCopy(bytes, i, LastName, 0, length); i += length; } @@ -2929,9 +2983,9 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { AvatarID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)FirstName.Length; + Utils.ByteToBytes((byte)FirstName.Length, bytes, ref i); Buffer.BlockCopy(FirstName, 0, bytes, i, FirstName.Length); i += FirstName.Length; - bytes[i++] = (byte)LastName.Length; + Utils.ByteToBytes((byte)LastName.Length, bytes, ref i); Buffer.BlockCopy(LastName, 0, bytes, i, LastName.Length); i += LastName.Length; } @@ -2959,6 +3013,7 @@ public AvatarPickerReplyPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 28; Header.Reliable = true; + NeedValidateIDs = false; AgentData = new AgentDataBlock(); Data = null; } @@ -2991,11 +3046,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public AvatarPickerReplyPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -3021,7 +3075,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)Data.Length; + Utils.ByteToBytes((byte)Data.Length, bytes, ref i); for (int j = 0; j < Data.Length; j++) { Data[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -3205,12 +3259,12 @@ public override void FromBytes(byte[] bytes, ref int i) int length; try { - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); QueryText = new byte[length]; Buffer.BlockCopy(bytes, i, QueryText, 0, length); i += length; QueryFlags = Utils.BytesToUIntSafepos(bytes, i); i += 4; - Category = (sbyte)bytes[i++]; - length = bytes[i++]; + Category = (sbyte)Utils.BytesToByte(bytes, ref i); + length = Utils.BytesToByte(bytes, ref i); SimName = new byte[length]; Buffer.BlockCopy(bytes, i, SimName, 0, length); i += length; } @@ -3222,11 +3276,11 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = (byte)QueryText.Length; + Utils.ByteToBytes((byte)QueryText.Length, bytes, ref i); Buffer.BlockCopy(QueryText, 0, bytes, i, QueryText.Length); i += QueryText.Length; Utils.UIntToBytesSafepos(QueryFlags, bytes, i); i += 4; - bytes[i++] = (byte)Category; - bytes[i++] = (byte)SimName.Length; + Utils.ByteToBytes( (byte)Category, bytes, ref i); + Utils.ByteToBytes((byte)SimName.Length, bytes, ref i); Buffer.BlockCopy(SimName, 0, bytes, i, SimName.Length); i += SimName.Length; } @@ -3247,6 +3301,8 @@ public override int Length public TransactionDataBlock TransactionData; public QueryDataBlock QueryData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public PlacesQueryPacket() { HasVariableBlocks = false; @@ -3255,6 +3311,7 @@ public PlacesQueryPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 29; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); TransactionData = new TransactionDataBlock(); @@ -3282,11 +3339,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public PlacesQueryPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -3440,19 +3496,19 @@ public override void FromBytes(byte[] bytes, ref int i) try { OwnerID.FromBytes(bytes, i); i += 16; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Name = new byte[length]; Buffer.BlockCopy(bytes, i, Name, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Desc = new byte[length]; Buffer.BlockCopy(bytes, i, Desc, 0, length); i += length; ActualArea = Utils.BytesToIntSafepos(bytes, i); i += 4; BillableArea = Utils.BytesToIntSafepos(bytes, i); i += 4; - Flags = (byte)bytes[i++]; + Flags = Utils.BytesToByte(bytes, ref i); GlobalX = Utils.BytesToFloatSafepos(bytes, i); i += 4; GlobalY = Utils.BytesToFloatSafepos(bytes, i); i += 4; GlobalZ = Utils.BytesToFloatSafepos(bytes, i); i += 4; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); SimName = new byte[length]; Buffer.BlockCopy(bytes, i, SimName, 0, length); i += length; SnapshotID.FromBytes(bytes, i); i += 16; @@ -3468,17 +3524,17 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { OwnerID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)Name.Length; + Utils.ByteToBytes((byte)Name.Length, bytes, ref i); Buffer.BlockCopy(Name, 0, bytes, i, Name.Length); i += Name.Length; - bytes[i++] = (byte)Desc.Length; + Utils.ByteToBytes((byte)Desc.Length, bytes, ref i); Buffer.BlockCopy(Desc, 0, bytes, i, Desc.Length); i += Desc.Length; Utils.IntToBytesSafepos(ActualArea, bytes, i); i += 4; Utils.IntToBytesSafepos(BillableArea, bytes, i); i += 4; - bytes[i++] = Flags; + Utils.ByteToBytes( Flags, bytes, ref i); Utils.FloatToBytesSafepos(GlobalX, bytes, i); i += 4; Utils.FloatToBytesSafepos(GlobalY, bytes, i); i += 4; Utils.FloatToBytesSafepos(GlobalZ, bytes, i); i += 4; - bytes[i++] = (byte)SimName.Length; + Utils.ByteToBytes((byte)SimName.Length, bytes, ref i); Buffer.BlockCopy(SimName, 0, bytes, i, SimName.Length); i += SimName.Length; SnapshotID.ToBytes(bytes, i); i += 16; Utils.FloatToBytesSafepos(Dwell, bytes, i); i += 4; @@ -3511,6 +3567,7 @@ public PlacesReplyPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 30; Header.Reliable = true; + NeedValidateIDs = false; Header.Zerocoded = true; AgentData = new AgentDataBlock(); TransactionData = new TransactionDataBlock(); @@ -3546,11 +3603,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public PlacesReplyPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -3579,7 +3635,7 @@ public override byte[] ToBytes() Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); TransactionData.ToBytes(bytes, ref i); - bytes[i++] = (byte)QueryData.Length; + Utils.ByteToBytes((byte)QueryData.Length, bytes, ref i); for (int j = 0; j < QueryData.Length; j++) { QueryData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -3724,7 +3780,7 @@ public override void FromBytes(byte[] bytes, ref int i) try { QueryID.FromBytes(bytes, i); i += 16; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); QueryText = new byte[length]; Buffer.BlockCopy(bytes, i, QueryText, 0, length); i += length; QueryFlags = Utils.BytesToUIntSafepos(bytes, i); i += 4; @@ -3739,7 +3795,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { QueryID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)QueryText.Length; + Utils.ByteToBytes((byte)QueryText.Length, bytes, ref i); Buffer.BlockCopy(QueryText, 0, bytes, i, QueryText.Length); i += QueryText.Length; Utils.UIntToBytesSafepos(QueryFlags, bytes, i); i += 4; Utils.IntToBytesSafepos(QueryStart, bytes, i); i += 4; @@ -3760,6 +3816,8 @@ public override int Length public AgentDataBlock AgentData; public QueryDataBlock QueryData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public DirFindQueryPacket() { HasVariableBlocks = false; @@ -3768,6 +3826,7 @@ public DirFindQueryPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 31; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); QueryData = new QueryDataBlock(); @@ -3793,11 +3852,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public DirFindQueryPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -3902,12 +3960,12 @@ public override void FromBytes(byte[] bytes, ref int i) try { QueryID.FromBytes(bytes, i); i += 16; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); QueryText = new byte[length]; Buffer.BlockCopy(bytes, i, QueryText, 0, length); i += length; QueryFlags = Utils.BytesToUIntSafepos(bytes, i); i += 4; - Category = (sbyte)bytes[i++]; - length = bytes[i++]; + Category = (sbyte)Utils.BytesToByte(bytes, ref i); + length = Utils.BytesToByte(bytes, ref i); SimName = new byte[length]; Buffer.BlockCopy(bytes, i, SimName, 0, length); i += length; QueryStart = Utils.BytesToIntSafepos(bytes, i); i += 4; @@ -3921,11 +3979,11 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { QueryID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)QueryText.Length; + Utils.ByteToBytes((byte)QueryText.Length, bytes, ref i); Buffer.BlockCopy(QueryText, 0, bytes, i, QueryText.Length); i += QueryText.Length; Utils.UIntToBytesSafepos(QueryFlags, bytes, i); i += 4; - bytes[i++] = (byte)Category; - bytes[i++] = (byte)SimName.Length; + Utils.ByteToBytes( (byte)Category, bytes, ref i); + Utils.ByteToBytes((byte)SimName.Length, bytes, ref i); Buffer.BlockCopy(SimName, 0, bytes, i, SimName.Length); i += SimName.Length; Utils.IntToBytesSafepos(QueryStart, bytes, i); i += 4; } @@ -3945,6 +4003,8 @@ public override int Length public AgentDataBlock AgentData; public QueryDataBlock QueryData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public DirPlacesQueryPacket() { HasVariableBlocks = false; @@ -3953,6 +4013,7 @@ public DirPlacesQueryPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 33; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); QueryData = new QueryDataBlock(); @@ -3978,11 +4039,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public DirPlacesQueryPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -4120,11 +4180,11 @@ public override void FromBytes(byte[] bytes, ref int i) try { ParcelID.FromBytes(bytes, i); i += 16; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Name = new byte[length]; Buffer.BlockCopy(bytes, i, Name, 0, length); i += length; - ForSale = (bytes[i++] != 0) ? (bool)true : (bool)false; - Auction = (bytes[i++] != 0) ? (bool)true : (bool)false; + ForSale = (Utils.BytesToByte(bytes, ref i) != 0); + Auction = (Utils.BytesToByte(bytes, ref i) != 0); Dwell = Utils.BytesToFloatSafepos(bytes, i); i += 4; } catch (Exception) @@ -4136,10 +4196,10 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { ParcelID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)Name.Length; + Utils.ByteToBytes((byte)Name.Length, bytes, ref i); Buffer.BlockCopy(Name, 0, bytes, i, Name.Length); i += Name.Length; - bytes[i++] = (byte)((ForSale) ? 1 : 0); - bytes[i++] = (byte)((Auction) ? 1 : 0); + Utils.ByteToBytes((byte)((ForSale) ? 1 : 0), bytes, ref i); + Utils.ByteToBytes((byte)((Auction) ? 1 : 0), bytes, ref i); Utils.FloatToBytesSafepos(Dwell, bytes, i); i += 4; } @@ -4211,6 +4271,7 @@ public DirPlacesReplyPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 35; Header.Reliable = true; + NeedValidateIDs = false; Header.Zerocoded = true; AgentData = new AgentDataBlock(); QueryData = null; @@ -4264,11 +4325,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public DirPlacesReplyPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -4316,11 +4376,11 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)QueryData.Length; + Utils.ByteToBytes((byte)QueryData.Length, bytes, ref i); for (int j = 0; j < QueryData.Length; j++) { QueryData[j].ToBytes(bytes, ref i); } - bytes[i++] = (byte)QueryReplies.Length; + Utils.ByteToBytes((byte)QueryReplies.Length, bytes, ref i); for (int j = 0; j < QueryReplies.Length; j++) { QueryReplies[j].ToBytes(bytes, ref i); } - bytes[i++] = (byte)StatusData.Length; + Utils.ByteToBytes((byte)StatusData.Length, bytes, ref i); for (int j = 0; j < StatusData.Length; j++) { StatusData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -4542,16 +4602,16 @@ public override void FromBytes(byte[] bytes, ref int i) try { AgentID.FromBytes(bytes, i); i += 16; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); FirstName = new byte[length]; Buffer.BlockCopy(bytes, i, FirstName, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); LastName = new byte[length]; Buffer.BlockCopy(bytes, i, LastName, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Group = new byte[length]; Buffer.BlockCopy(bytes, i, Group, 0, length); i += length; - Online = (bytes[i++] != 0) ? (bool)true : (bool)false; + Online = (Utils.BytesToByte(bytes, ref i) != 0); Reputation = Utils.BytesToIntSafepos(bytes, i); i += 4; } catch (Exception) @@ -4563,13 +4623,13 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { AgentID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)FirstName.Length; + Utils.ByteToBytes((byte)FirstName.Length, bytes, ref i); Buffer.BlockCopy(FirstName, 0, bytes, i, FirstName.Length); i += FirstName.Length; - bytes[i++] = (byte)LastName.Length; + Utils.ByteToBytes((byte)LastName.Length, bytes, ref i); Buffer.BlockCopy(LastName, 0, bytes, i, LastName.Length); i += LastName.Length; - bytes[i++] = (byte)Group.Length; + Utils.ByteToBytes((byte)Group.Length, bytes, ref i); Buffer.BlockCopy(Group, 0, bytes, i, Group.Length); i += Group.Length; - bytes[i++] = (byte)((Online) ? 1 : 0); + Utils.ByteToBytes((byte)((Online) ? 1 : 0), bytes, ref i); Utils.IntToBytesSafepos(Reputation, bytes, i); i += 4; } @@ -4599,6 +4659,7 @@ public DirPeopleReplyPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 36; Header.Reliable = true; + NeedValidateIDs = false; Header.Zerocoded = true; AgentData = new AgentDataBlock(); QueryData = new QueryDataBlock(); @@ -4634,11 +4695,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public DirPeopleReplyPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -4667,7 +4727,7 @@ public override byte[] ToBytes() Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); QueryData.ToBytes(bytes, ref i); - bytes[i++] = (byte)QueryReplies.Length; + Utils.ByteToBytes((byte)QueryReplies.Length, bytes, ref i); for (int j = 0; j < QueryReplies.Length; j++) { QueryReplies[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -4850,11 +4910,11 @@ public override void FromBytes(byte[] bytes, ref int i) try { OwnerID.FromBytes(bytes, i); i += 16; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Name = new byte[length]; Buffer.BlockCopy(bytes, i, Name, 0, length); i += length; EventID = Utils.BytesToUIntSafepos(bytes, i); i += 4; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Date = new byte[length]; Buffer.BlockCopy(bytes, i, Date, 0, length); i += length; UnixTime = Utils.BytesToUIntSafepos(bytes, i); i += 4; @@ -4869,10 +4929,10 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { OwnerID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)Name.Length; + Utils.ByteToBytes((byte)Name.Length, bytes, ref i); Buffer.BlockCopy(Name, 0, bytes, i, Name.Length); i += Name.Length; Utils.UIntToBytesSafepos(EventID, bytes, i); i += 4; - bytes[i++] = (byte)Date.Length; + Utils.ByteToBytes((byte)Date.Length, bytes, ref i); Buffer.BlockCopy(Date, 0, bytes, i, Date.Length); i += Date.Length; Utils.UIntToBytesSafepos(UnixTime, bytes, i); i += 4; Utils.UIntToBytesSafepos(EventFlags, bytes, i); i += 4; @@ -4945,6 +5005,7 @@ public DirEventsReplyPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 37; Header.Reliable = true; + NeedValidateIDs = false; Header.Zerocoded = true; AgentData = new AgentDataBlock(); QueryData = new QueryDataBlock(); @@ -4990,11 +5051,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public DirEventsReplyPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -5034,9 +5094,9 @@ public override byte[] ToBytes() Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); QueryData.ToBytes(bytes, ref i); - bytes[i++] = (byte)QueryReplies.Length; + Utils.ByteToBytes((byte)QueryReplies.Length, bytes, ref i); for (int j = 0; j < QueryReplies.Length; j++) { QueryReplies[j].ToBytes(bytes, ref i); } - bytes[i++] = (byte)StatusData.Length; + Utils.ByteToBytes((byte)StatusData.Length, bytes, ref i); for (int j = 0; j < StatusData.Length; j++) { StatusData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -5236,7 +5296,7 @@ public override void FromBytes(byte[] bytes, ref int i) try { GroupID.FromBytes(bytes, i); i += 16; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); GroupName = new byte[length]; Buffer.BlockCopy(bytes, i, GroupName, 0, length); i += length; Members = Utils.BytesToIntSafepos(bytes, i); i += 4; @@ -5251,7 +5311,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { GroupID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)GroupName.Length; + Utils.ByteToBytes((byte)GroupName.Length, bytes, ref i); Buffer.BlockCopy(GroupName, 0, bytes, i, GroupName.Length); i += GroupName.Length; Utils.IntToBytesSafepos(Members, bytes, i); i += 4; Utils.FloatToBytesSafepos(SearchOrder, bytes, i); i += 4; @@ -5283,6 +5343,7 @@ public DirGroupsReplyPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 38; Header.Reliable = true; + NeedValidateIDs = false; Header.Zerocoded = true; AgentData = new AgentDataBlock(); QueryData = new QueryDataBlock(); @@ -5318,11 +5379,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public DirGroupsReplyPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -5351,7 +5411,7 @@ public override byte[] ToBytes() Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); QueryData.ToBytes(bytes, ref i); - bytes[i++] = (byte)QueryReplies.Length; + Utils.ByteToBytes((byte)QueryReplies.Length, bytes, ref i); for (int j = 0; j < QueryReplies.Length; j++) { QueryReplies[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -5497,7 +5557,7 @@ public override void FromBytes(byte[] bytes, ref int i) try { QueryID.FromBytes(bytes, i); i += 16; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); QueryText = new byte[length]; Buffer.BlockCopy(bytes, i, QueryText, 0, length); i += length; QueryFlags = Utils.BytesToUIntSafepos(bytes, i); i += 4; @@ -5513,7 +5573,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { QueryID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)QueryText.Length; + Utils.ByteToBytes((byte)QueryText.Length, bytes, ref i); Buffer.BlockCopy(QueryText, 0, bytes, i, QueryText.Length); i += QueryText.Length; Utils.UIntToBytesSafepos(QueryFlags, bytes, i); i += 4; Utils.UIntToBytesSafepos(Category, bytes, i); i += 4; @@ -5535,6 +5595,8 @@ public override int Length public AgentDataBlock AgentData; public QueryDataBlock QueryData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public DirClassifiedQueryPacket() { HasVariableBlocks = false; @@ -5543,6 +5605,7 @@ public DirClassifiedQueryPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 39; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); QueryData = new QueryDataBlock(); @@ -5568,11 +5631,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public DirClassifiedQueryPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -5711,10 +5773,10 @@ public override void FromBytes(byte[] bytes, ref int i) try { ClassifiedID.FromBytes(bytes, i); i += 16; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Name = new byte[length]; Buffer.BlockCopy(bytes, i, Name, 0, length); i += length; - ClassifiedFlags = (byte)bytes[i++]; + ClassifiedFlags = Utils.BytesToByte(bytes, ref i); CreationDate = Utils.BytesToUIntSafepos(bytes, i); i += 4; ExpirationDate = Utils.BytesToUIntSafepos(bytes, i); i += 4; PriceForListing = Utils.BytesToIntSafepos(bytes, i); i += 4; @@ -5728,9 +5790,9 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { ClassifiedID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)Name.Length; + Utils.ByteToBytes((byte)Name.Length, bytes, ref i); Buffer.BlockCopy(Name, 0, bytes, i, Name.Length); i += Name.Length; - bytes[i++] = ClassifiedFlags; + Utils.ByteToBytes( ClassifiedFlags, bytes, ref i); Utils.UIntToBytesSafepos(CreationDate, bytes, i); i += 4; Utils.UIntToBytesSafepos(ExpirationDate, bytes, i); i += 4; Utils.IntToBytesSafepos(PriceForListing, bytes, i); i += 4; @@ -5803,6 +5865,7 @@ public DirClassifiedReplyPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 41; Header.Reliable = true; + NeedValidateIDs = false; Header.Zerocoded = true; AgentData = new AgentDataBlock(); QueryData = new QueryDataBlock(); @@ -5848,11 +5911,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public DirClassifiedReplyPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -5892,9 +5954,9 @@ public override byte[] ToBytes() Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); QueryData.ToBytes(bytes, ref i); - bytes[i++] = (byte)QueryReplies.Length; + Utils.ByteToBytes((byte)QueryReplies.Length, bytes, ref i); for (int j = 0; j < QueryReplies.Length; j++) { QueryReplies[j].ToBytes(bytes, ref i); } - bytes[i++] = (byte)StatusData.Length; + Utils.ByteToBytes((byte)StatusData.Length, bytes, ref i); for (int j = 0; j < StatusData.Length; j++) { StatusData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -6057,7 +6119,7 @@ public override void FromBytes(byte[] bytes, ref int i) try { ClassifiedID.FromBytes(bytes, i); i += 16; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Name = new byte[length]; Buffer.BlockCopy(bytes, i, Name, 0, length); i += length; } @@ -6070,7 +6132,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { ClassifiedID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)Name.Length; + Utils.ByteToBytes((byte)Name.Length, bytes, ref i); Buffer.BlockCopy(Name, 0, bytes, i, Name.Length); i += Name.Length; } @@ -6098,6 +6160,7 @@ public AvatarClassifiedReplyPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 42; Header.Reliable = true; + NeedValidateIDs = false; AgentData = new AgentDataBlock(); Data = null; } @@ -6130,11 +6193,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public AvatarClassifiedReplyPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -6160,7 +6222,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)Data.Length; + Utils.ByteToBytes((byte)Data.Length, bytes, ref i); for (int j = 0; j < Data.Length; j++) { Data[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -6324,6 +6386,8 @@ public override int Length public AgentDataBlock AgentData; public DataBlock Data; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ClassifiedInfoRequestPacket() { HasVariableBlocks = false; @@ -6332,6 +6396,7 @@ public ClassifiedInfoRequestPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 43; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); Data = new DataBlock(); @@ -6357,11 +6422,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ClassifiedInfoRequestPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -6478,23 +6542,23 @@ public override void FromBytes(byte[] bytes, ref int i) CreationDate = Utils.BytesToUIntSafepos(bytes, i); i += 4; ExpirationDate = Utils.BytesToUIntSafepos(bytes, i); i += 4; Category = Utils.BytesToUIntSafepos(bytes, i); i += 4; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Name = new byte[length]; Buffer.BlockCopy(bytes, i, Name, 0, length); i += length; - length = (bytes[i++] + (bytes[i++] << 8)); + length = Utils.BytesToUInt16(bytes, i); i+=2; Desc = new byte[length]; Buffer.BlockCopy(bytes, i, Desc, 0, length); i += length; ParcelID.FromBytes(bytes, i); i += 16; ParentEstate = Utils.BytesToUIntSafepos(bytes, i); i += 4; SnapshotID.FromBytes(bytes, i); i += 16; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); SimName = new byte[length]; Buffer.BlockCopy(bytes, i, SimName, 0, length); i += length; PosGlobal.FromBytes(bytes, i); i += 24; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); ParcelName = new byte[length]; Buffer.BlockCopy(bytes, i, ParcelName, 0, length); i += length; - ClassifiedFlags = (byte)bytes[i++]; + ClassifiedFlags = Utils.BytesToByte(bytes, ref i); PriceForListing = Utils.BytesToIntSafepos(bytes, i); i += 4; } catch (Exception) @@ -6510,20 +6574,19 @@ public override void ToBytes(byte[] bytes, ref int i) Utils.UIntToBytesSafepos(CreationDate, bytes, i); i += 4; Utils.UIntToBytesSafepos(ExpirationDate, bytes, i); i += 4; Utils.UIntToBytesSafepos(Category, bytes, i); i += 4; - bytes[i++] = (byte)Name.Length; + Utils.ByteToBytes((byte)Name.Length, bytes, ref i); Buffer.BlockCopy(Name, 0, bytes, i, Name.Length); i += Name.Length; - bytes[i++] = (byte)(Desc.Length % 256); - bytes[i++] = (byte)((Desc.Length >> 8) % 256); + Utils.UInt16ToBytes((ushort)Desc.Length, bytes, i); i += 2; Buffer.BlockCopy(Desc, 0, bytes, i, Desc.Length); i += Desc.Length; ParcelID.ToBytes(bytes, i); i += 16; Utils.UIntToBytesSafepos(ParentEstate, bytes, i); i += 4; SnapshotID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)SimName.Length; + Utils.ByteToBytes((byte)SimName.Length, bytes, ref i); Buffer.BlockCopy(SimName, 0, bytes, i, SimName.Length); i += SimName.Length; PosGlobal.ToBytes(bytes, i); i += 24; - bytes[i++] = (byte)ParcelName.Length; + Utils.ByteToBytes((byte)ParcelName.Length, bytes, ref i); Buffer.BlockCopy(ParcelName, 0, bytes, i, ParcelName.Length); i += ParcelName.Length; - bytes[i++] = ClassifiedFlags; + Utils.ByteToBytes( ClassifiedFlags, bytes, ref i); Utils.IntToBytesSafepos(PriceForListing, bytes, i); i += 4; } @@ -6550,6 +6613,7 @@ public ClassifiedInfoReplyPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 44; Header.Reliable = true; + NeedValidateIDs = false; AgentData = new AgentDataBlock(); Data = new DataBlock(); } @@ -6574,11 +6638,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ClassifiedInfoReplyPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -6688,17 +6751,17 @@ public override void FromBytes(byte[] bytes, ref int i) { ClassifiedID.FromBytes(bytes, i); i += 16; Category = Utils.BytesToUIntSafepos(bytes, i); i += 4; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Name = new byte[length]; Buffer.BlockCopy(bytes, i, Name, 0, length); i += length; - length = (bytes[i++] + (bytes[i++] << 8)); + length = Utils.BytesToUInt16(bytes, i); i+=2; Desc = new byte[length]; Buffer.BlockCopy(bytes, i, Desc, 0, length); i += length; ParcelID.FromBytes(bytes, i); i += 16; ParentEstate = Utils.BytesToUIntSafepos(bytes, i); i += 4; SnapshotID.FromBytes(bytes, i); i += 16; PosGlobal.FromBytes(bytes, i); i += 24; - ClassifiedFlags = (byte)bytes[i++]; + ClassifiedFlags = Utils.BytesToByte(bytes, ref i); PriceForListing = Utils.BytesToIntSafepos(bytes, i); i += 4; } catch (Exception) @@ -6711,16 +6774,15 @@ public override void ToBytes(byte[] bytes, ref int i) { ClassifiedID.ToBytes(bytes, i); i += 16; Utils.UIntToBytesSafepos(Category, bytes, i); i += 4; - bytes[i++] = (byte)Name.Length; + Utils.ByteToBytes((byte)Name.Length, bytes, ref i); Buffer.BlockCopy(Name, 0, bytes, i, Name.Length); i += Name.Length; - bytes[i++] = (byte)(Desc.Length % 256); - bytes[i++] = (byte)((Desc.Length >> 8) % 256); + Utils.UInt16ToBytes((ushort)Desc.Length, bytes, i); i += 2; Buffer.BlockCopy(Desc, 0, bytes, i, Desc.Length); i += Desc.Length; ParcelID.ToBytes(bytes, i); i += 16; Utils.UIntToBytesSafepos(ParentEstate, bytes, i); i += 4; SnapshotID.ToBytes(bytes, i); i += 16; PosGlobal.ToBytes(bytes, i); i += 24; - bytes[i++] = ClassifiedFlags; + Utils.ByteToBytes( ClassifiedFlags, bytes, ref i); Utils.IntToBytesSafepos(PriceForListing, bytes, i); i += 4; } @@ -6739,6 +6801,8 @@ public override int Length public AgentDataBlock AgentData; public DataBlock Data; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ClassifiedInfoUpdatePacket() { HasVariableBlocks = false; @@ -6747,6 +6811,7 @@ public ClassifiedInfoUpdatePacket() Header.Frequency = PacketFrequency.Low; Header.ID = 45; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); Data = new DataBlock(); } @@ -6771,11 +6836,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ClassifiedInfoUpdatePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -6898,6 +6962,8 @@ public override int Length public AgentDataBlock AgentData; public DataBlock Data; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ClassifiedDeletePacket() { HasVariableBlocks = false; @@ -6906,6 +6972,7 @@ public ClassifiedDeletePacket() Header.Frequency = PacketFrequency.Low; Header.ID = 46; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); Data = new DataBlock(); } @@ -6930,11 +6997,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ClassifiedDeletePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -7060,6 +7126,8 @@ public override int Length public AgentDataBlock AgentData; public DataBlock Data; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ClassifiedGodDeletePacket() { HasVariableBlocks = false; @@ -7068,6 +7136,7 @@ public ClassifiedGodDeletePacket() Header.Frequency = PacketFrequency.Low; Header.ID = 47; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); Data = new DataBlock(); } @@ -7092,11 +7161,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ClassifiedGodDeletePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -7234,6 +7302,8 @@ public override int Length public AgentDataBlock AgentData; public QueryDataBlock QueryData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public DirLandQueryPacket() { HasVariableBlocks = false; @@ -7242,6 +7312,7 @@ public DirLandQueryPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 48; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); QueryData = new QueryDataBlock(); @@ -7267,11 +7338,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public DirLandQueryPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -7410,11 +7480,11 @@ public override void FromBytes(byte[] bytes, ref int i) try { ParcelID.FromBytes(bytes, i); i += 16; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Name = new byte[length]; Buffer.BlockCopy(bytes, i, Name, 0, length); i += length; - Auction = (bytes[i++] != 0) ? (bool)true : (bool)false; - ForSale = (bytes[i++] != 0) ? (bool)true : (bool)false; + Auction = (Utils.BytesToByte(bytes, ref i) != 0); + ForSale = (Utils.BytesToByte(bytes, ref i) != 0); SalePrice = Utils.BytesToIntSafepos(bytes, i); i += 4; ActualArea = Utils.BytesToIntSafepos(bytes, i); i += 4; } @@ -7427,10 +7497,10 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { ParcelID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)Name.Length; + Utils.ByteToBytes((byte)Name.Length, bytes, ref i); Buffer.BlockCopy(Name, 0, bytes, i, Name.Length); i += Name.Length; - bytes[i++] = (byte)((Auction) ? 1 : 0); - bytes[i++] = (byte)((ForSale) ? 1 : 0); + Utils.ByteToBytes((byte)((Auction) ? 1 : 0), bytes, ref i); + Utils.ByteToBytes((byte)((ForSale) ? 1 : 0), bytes, ref i); Utils.IntToBytesSafepos(SalePrice, bytes, i); i += 4; Utils.IntToBytesSafepos(ActualArea, bytes, i); i += 4; } @@ -7461,6 +7531,7 @@ public DirLandReplyPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 50; Header.Reliable = true; + NeedValidateIDs = false; Header.Zerocoded = true; AgentData = new AgentDataBlock(); QueryData = new QueryDataBlock(); @@ -7496,11 +7567,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public DirLandReplyPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -7529,7 +7599,7 @@ public override byte[] ToBytes() Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); QueryData.ToBytes(bytes, ref i); - bytes[i++] = (byte)QueryReplies.Length; + Utils.ByteToBytes((byte)QueryReplies.Length, bytes, ref i); for (int j = 0; j < QueryReplies.Length; j++) { QueryReplies[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -7698,6 +7768,8 @@ public override int Length public AgentDataBlock AgentData; public QueryDataBlock QueryData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public DirPopularQueryPacket() { HasVariableBlocks = false; @@ -7706,6 +7778,7 @@ public DirPopularQueryPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 51; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); QueryData = new QueryDataBlock(); @@ -7731,11 +7804,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public DirPopularQueryPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -7871,7 +7943,7 @@ public override void FromBytes(byte[] bytes, ref int i) try { ParcelID.FromBytes(bytes, i); i += 16; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Name = new byte[length]; Buffer.BlockCopy(bytes, i, Name, 0, length); i += length; Dwell = Utils.BytesToFloatSafepos(bytes, i); i += 4; @@ -7885,7 +7957,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { ParcelID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)Name.Length; + Utils.ByteToBytes((byte)Name.Length, bytes, ref i); Buffer.BlockCopy(Name, 0, bytes, i, Name.Length); i += Name.Length; Utils.FloatToBytesSafepos(Dwell, bytes, i); i += 4; } @@ -7916,6 +7988,7 @@ public DirPopularReplyPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 53; Header.Reliable = true; + NeedValidateIDs = false; Header.Zerocoded = true; AgentData = new AgentDataBlock(); QueryData = new QueryDataBlock(); @@ -7951,11 +8024,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public DirPopularReplyPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -7984,7 +8056,7 @@ public override byte[] ToBytes() Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); QueryData.ToBytes(bytes, ref i); - bytes[i++] = (byte)QueryReplies.Length; + Utils.ByteToBytes((byte)QueryReplies.Length, bytes, ref i); for (int j = 0; j < QueryReplies.Length; j++) { QueryReplies[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -8150,6 +8222,8 @@ public override int Length public AgentDataBlock AgentData; public DataBlock Data; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ParcelInfoRequestPacket() { HasVariableBlocks = false; @@ -8158,6 +8232,7 @@ public ParcelInfoRequestPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 54; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); Data = new DataBlock(); } @@ -8182,11 +8257,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ParcelInfoRequestPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -8299,19 +8373,19 @@ public override void FromBytes(byte[] bytes, ref int i) { ParcelID.FromBytes(bytes, i); i += 16; OwnerID.FromBytes(bytes, i); i += 16; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Name = new byte[length]; Buffer.BlockCopy(bytes, i, Name, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Desc = new byte[length]; Buffer.BlockCopy(bytes, i, Desc, 0, length); i += length; ActualArea = Utils.BytesToIntSafepos(bytes, i); i += 4; BillableArea = Utils.BytesToIntSafepos(bytes, i); i += 4; - Flags = (byte)bytes[i++]; + Flags = Utils.BytesToByte(bytes, ref i); GlobalX = Utils.BytesToFloatSafepos(bytes, i); i += 4; GlobalY = Utils.BytesToFloatSafepos(bytes, i); i += 4; GlobalZ = Utils.BytesToFloatSafepos(bytes, i); i += 4; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); SimName = new byte[length]; Buffer.BlockCopy(bytes, i, SimName, 0, length); i += length; SnapshotID.FromBytes(bytes, i); i += 16; @@ -8329,17 +8403,17 @@ public override void ToBytes(byte[] bytes, ref int i) { ParcelID.ToBytes(bytes, i); i += 16; OwnerID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)Name.Length; + Utils.ByteToBytes((byte)Name.Length, bytes, ref i); Buffer.BlockCopy(Name, 0, bytes, i, Name.Length); i += Name.Length; - bytes[i++] = (byte)Desc.Length; + Utils.ByteToBytes((byte)Desc.Length, bytes, ref i); Buffer.BlockCopy(Desc, 0, bytes, i, Desc.Length); i += Desc.Length; Utils.IntToBytesSafepos(ActualArea, bytes, i); i += 4; Utils.IntToBytesSafepos(BillableArea, bytes, i); i += 4; - bytes[i++] = Flags; + Utils.ByteToBytes( Flags, bytes, ref i); Utils.FloatToBytesSafepos(GlobalX, bytes, i); i += 4; Utils.FloatToBytesSafepos(GlobalY, bytes, i); i += 4; Utils.FloatToBytesSafepos(GlobalZ, bytes, i); i += 4; - bytes[i++] = (byte)SimName.Length; + Utils.ByteToBytes((byte)SimName.Length, bytes, ref i); Buffer.BlockCopy(SimName, 0, bytes, i, SimName.Length); i += SimName.Length; SnapshotID.ToBytes(bytes, i); i += 16; Utils.FloatToBytesSafepos(Dwell, bytes, i); i += 4; @@ -8370,6 +8444,7 @@ public ParcelInfoReplyPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 55; Header.Reliable = true; + NeedValidateIDs = false; Header.Zerocoded = true; AgentData = new AgentDataBlock(); Data = new DataBlock(); @@ -8395,11 +8470,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ParcelInfoReplyPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -8522,6 +8596,8 @@ public override int Length public AgentDataBlock AgentData; public ParcelDataBlock ParcelData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ParcelObjectOwnersRequestPacket() { HasVariableBlocks = false; @@ -8530,6 +8606,7 @@ public ParcelObjectOwnersRequestPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 56; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); ParcelData = new ParcelDataBlock(); } @@ -8554,11 +8631,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ParcelObjectOwnersRequestPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -8616,9 +8692,9 @@ public override void FromBytes(byte[] bytes, ref int i) try { OwnerID.FromBytes(bytes, i); i += 16; - IsGroupOwned = (bytes[i++] != 0) ? (bool)true : (bool)false; + IsGroupOwned = (Utils.BytesToByte(bytes, ref i) != 0); Count = Utils.BytesToIntSafepos(bytes, i); i += 4; - OnlineStatus = (bytes[i++] != 0) ? (bool)true : (bool)false; + OnlineStatus = (Utils.BytesToByte(bytes, ref i) != 0); } catch (Exception) { @@ -8629,9 +8705,9 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { OwnerID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)((IsGroupOwned) ? 1 : 0); + Utils.ByteToBytes((byte)((IsGroupOwned) ? 1 : 0), bytes, ref i); Utils.IntToBytesSafepos(Count, bytes, i); i += 4; - bytes[i++] = (byte)((OnlineStatus) ? 1 : 0); + Utils.ByteToBytes((byte)((OnlineStatus) ? 1 : 0), bytes, ref i); } } @@ -8656,6 +8732,7 @@ public ParcelObjectOwnersReplyPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 57; Header.Reliable = true; + NeedValidateIDs = false; Header.Zerocoded = true; Data = null; } @@ -8687,11 +8764,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ParcelObjectOwnersReplyPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; int count = (int)bytes[i++]; @@ -8714,7 +8790,7 @@ public override byte[] ToBytes() byte[] bytes = new byte[length]; int i = 0; Header.ToBytes(bytes, ref i); - bytes[i++] = (byte)Data.Length; + Utils.ByteToBytes((byte)Data.Length, bytes, ref i); for (int j = 0; j < Data.Length; j++) { Data[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -8876,6 +8952,8 @@ public override int Length public AgentDataBlock AgentData; public DataBlock Data; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public GroupNoticesListRequestPacket() { HasVariableBlocks = false; @@ -8884,6 +8962,7 @@ public GroupNoticesListRequestPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 58; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); Data = new DataBlock(); } @@ -8908,11 +8987,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public GroupNoticesListRequestPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -9018,14 +9096,14 @@ public override void FromBytes(byte[] bytes, ref int i) { NoticeID.FromBytes(bytes, i); i += 16; Timestamp = Utils.BytesToUIntSafepos(bytes, i); i += 4; - length = (bytes[i++] + (bytes[i++] << 8)); + length = Utils.BytesToUInt16(bytes, i); i+=2; FromName = new byte[length]; Buffer.BlockCopy(bytes, i, FromName, 0, length); i += length; - length = (bytes[i++] + (bytes[i++] << 8)); + length = Utils.BytesToUInt16(bytes, i); i+=2; Subject = new byte[length]; Buffer.BlockCopy(bytes, i, Subject, 0, length); i += length; - HasAttachment = (bytes[i++] != 0) ? (bool)true : (bool)false; - AssetType = (byte)bytes[i++]; + HasAttachment = (Utils.BytesToByte(bytes, ref i) != 0); + AssetType = Utils.BytesToByte(bytes, ref i); } catch (Exception) { @@ -9037,14 +9115,12 @@ public override void ToBytes(byte[] bytes, ref int i) { NoticeID.ToBytes(bytes, i); i += 16; Utils.UIntToBytesSafepos(Timestamp, bytes, i); i += 4; - bytes[i++] = (byte)(FromName.Length % 256); - bytes[i++] = (byte)((FromName.Length >> 8) % 256); + Utils.UInt16ToBytes((ushort)FromName.Length, bytes, i); i += 2; Buffer.BlockCopy(FromName, 0, bytes, i, FromName.Length); i += FromName.Length; - bytes[i++] = (byte)(Subject.Length % 256); - bytes[i++] = (byte)((Subject.Length >> 8) % 256); + Utils.UInt16ToBytes((ushort)Subject.Length, bytes, i); i += 2; Buffer.BlockCopy(Subject, 0, bytes, i, Subject.Length); i += Subject.Length; - bytes[i++] = (byte)((HasAttachment) ? 1 : 0); - bytes[i++] = AssetType; + Utils.ByteToBytes((byte)((HasAttachment) ? 1 : 0), bytes, ref i); + Utils.ByteToBytes( AssetType, bytes, ref i); } } @@ -9071,6 +9147,7 @@ public GroupNoticesListReplyPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 59; Header.Reliable = true; + NeedValidateIDs = false; AgentData = new AgentDataBlock(); Data = null; } @@ -9103,11 +9180,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public GroupNoticesListReplyPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -9133,7 +9209,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)Data.Length; + Utils.ByteToBytes((byte)Data.Length, bytes, ref i); for (int j = 0; j < Data.Length; j++) { Data[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -9297,6 +9373,8 @@ public override int Length public AgentDataBlock AgentData; public DataBlock Data; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public GroupNoticeRequestPacket() { HasVariableBlocks = false; @@ -9305,6 +9383,7 @@ public GroupNoticeRequestPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 60; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); Data = new DataBlock(); } @@ -9329,11 +9408,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public GroupNoticeRequestPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -9462,6 +9540,8 @@ public override int Length public AgentDataBlock AgentData; public InfoBlock Info; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public TeleportRequestPacket() { HasVariableBlocks = false; @@ -9470,6 +9550,7 @@ public TeleportRequestPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 62; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); Info = new InfoBlock(); } @@ -9494,11 +9575,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public TeleportRequestPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -9627,6 +9707,8 @@ public override int Length public AgentDataBlock AgentData; public InfoBlock Info; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public TeleportLocationRequestPacket() { HasVariableBlocks = false; @@ -9635,6 +9717,7 @@ public TeleportLocationRequestPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 63; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); Info = new InfoBlock(); } @@ -9659,11 +9742,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public TeleportLocationRequestPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -9763,6 +9845,7 @@ public TeleportLocalPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 64; Header.Reliable = true; + NeedValidateIDs = false; Info = new InfoBlock(); } @@ -9785,11 +9868,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public TeleportLocalPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; Info.FromBytes(bytes, ref i); @@ -9880,6 +9962,7 @@ public TeleportLandmarkRequestPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 65; Header.Reliable = true; + NeedValidateIDs = false; Header.Zerocoded = true; Info = new InfoBlock(); } @@ -9903,11 +9986,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public TeleportLandmarkRequestPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; Info.FromBytes(bytes, ref i); @@ -10001,7 +10083,7 @@ public override void FromBytes(byte[] bytes, ref int i) try { TeleportFlags = Utils.BytesToUIntSafepos(bytes, i); i += 4; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Message = new byte[length]; Buffer.BlockCopy(bytes, i, Message, 0, length); i += length; } @@ -10014,7 +10096,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { Utils.UIntToBytesSafepos(TeleportFlags, bytes, i); i += 4; - bytes[i++] = (byte)Message.Length; + Utils.ByteToBytes((byte)Message.Length, bytes, ref i); Buffer.BlockCopy(Message, 0, bytes, i, Message.Length); i += Message.Length; } @@ -10041,6 +10123,7 @@ public TeleportProgressPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 66; Header.Reliable = true; + NeedValidateIDs = false; AgentData = new AgentDataBlock(); Info = new InfoBlock(); } @@ -10065,11 +10148,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public TeleportProgressPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -10138,10 +10220,10 @@ public override void FromBytes(byte[] bytes, ref int i) SimIP = Utils.BytesToUIntSafepos(bytes, i); i += 4; SimPort = (ushort)((bytes[i++] << 8) + bytes[i++]); RegionHandle = Utils.BytesToUInt64Safepos(bytes, i); i += 8; - length = (bytes[i++] + (bytes[i++] << 8)); + length = Utils.BytesToUInt16(bytes, i); i+=2; SeedCapability = new byte[length]; Buffer.BlockCopy(bytes, i, SeedCapability, 0, length); i += length; - SimAccess = (byte)bytes[i++]; + SimAccess = Utils.BytesToByte(bytes, ref i); TeleportFlags = Utils.BytesToUIntSafepos(bytes, i); i += 4; } catch (Exception) @@ -10155,13 +10237,11 @@ public override void ToBytes(byte[] bytes, ref int i) AgentID.ToBytes(bytes, i); i += 16; Utils.UIntToBytesSafepos(LocationID, bytes, i); i += 4; Utils.UIntToBytesSafepos(SimIP, bytes, i); i += 4; - bytes[i++] = (byte)((SimPort >> 8) % 256); - bytes[i++] = (byte)(SimPort % 256); + Utils.UInt16ToBytesBig(SimPort, bytes, i); i += 2; Utils.UInt64ToBytesSafepos(RegionHandle, bytes, i); i += 8; - bytes[i++] = (byte)(SeedCapability.Length % 256); - bytes[i++] = (byte)((SeedCapability.Length >> 8) % 256); + Utils.UInt16ToBytes((ushort)SeedCapability.Length, bytes, i); i += 2; Buffer.BlockCopy(SeedCapability, 0, bytes, i, SeedCapability.Length); i += SeedCapability.Length; - bytes[i++] = SimAccess; + Utils.ByteToBytes( SimAccess, bytes, ref i); Utils.UIntToBytesSafepos(TeleportFlags, bytes, i); i += 4; } @@ -10186,6 +10266,7 @@ public TeleportFinishPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 69; Header.Reliable = true; + NeedValidateIDs = false; Info = new InfoBlock(); } @@ -10208,11 +10289,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public TeleportFinishPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; Info.FromBytes(bytes, ref i); @@ -10308,8 +10388,8 @@ public override void FromBytes(byte[] bytes, ref int i) int length; try { - LureType = (byte)bytes[i++]; - length = bytes[i++]; + LureType = Utils.BytesToByte(bytes, ref i); + length = Utils.BytesToByte(bytes, ref i); Message = new byte[length]; Buffer.BlockCopy(bytes, i, Message, 0, length); i += length; } @@ -10321,8 +10401,8 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = LureType; - bytes[i++] = (byte)Message.Length; + Utils.ByteToBytes( LureType, bytes, ref i); + Utils.ByteToBytes((byte)Message.Length, bytes, ref i); Buffer.BlockCopy(Message, 0, bytes, i, Message.Length); i += Message.Length; } @@ -10382,6 +10462,8 @@ public override int Length public InfoBlock Info; public TargetDataBlock[] TargetData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public StartLurePacket() { HasVariableBlocks = true; @@ -10390,6 +10472,7 @@ public StartLurePacket() Header.Frequency = PacketFrequency.Low; Header.ID = 70; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); Info = new InfoBlock(); TargetData = null; @@ -10424,11 +10507,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public StartLurePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -10457,7 +10539,7 @@ public override byte[] ToBytes() Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); Info.ToBytes(bytes, ref i); - bytes[i++] = (byte)TargetData.Length; + Utils.ByteToBytes((byte)TargetData.Length, bytes, ref i); for (int j = 0; j < TargetData.Length; j++) { TargetData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -10597,6 +10679,7 @@ public TeleportLureRequestPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 71; Header.Reliable = true; + NeedValidateIDs = false; Info = new InfoBlock(); } @@ -10619,11 +10702,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public TeleportLureRequestPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; Info.FromBytes(bytes, ref i); @@ -10711,6 +10793,7 @@ public TeleportCancelPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 72; Header.Reliable = true; + NeedValidateIDs = false; Info = new InfoBlock(); } @@ -10733,11 +10816,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public TeleportCancelPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; Info.FromBytes(bytes, ref i); @@ -10822,6 +10904,7 @@ public TeleportStartPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 73; Header.Reliable = true; + NeedValidateIDs = false; Info = new InfoBlock(); } @@ -10844,11 +10927,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public TeleportStartPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; Info.FromBytes(bytes, ref i); @@ -10904,7 +10986,7 @@ public override void FromBytes(byte[] bytes, ref int i) try { AgentID.FromBytes(bytes, i); i += 16; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Reason = new byte[length]; Buffer.BlockCopy(bytes, i, Reason, 0, length); i += length; } @@ -10917,7 +10999,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { AgentID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)Reason.Length; + Utils.ByteToBytes((byte)Reason.Length, bytes, ref i); Buffer.BlockCopy(Reason, 0, bytes, i, Reason.Length); i += Reason.Length; } @@ -10951,10 +11033,10 @@ public override void FromBytes(byte[] bytes, ref int i) int length; try { - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Message = new byte[length]; Buffer.BlockCopy(bytes, i, Message, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); ExtraParams = new byte[length]; Buffer.BlockCopy(bytes, i, ExtraParams, 0, length); i += length; } @@ -10966,9 +11048,9 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = (byte)Message.Length; + Utils.ByteToBytes((byte)Message.Length, bytes, ref i); Buffer.BlockCopy(Message, 0, bytes, i, Message.Length); i += Message.Length; - bytes[i++] = (byte)ExtraParams.Length; + Utils.ByteToBytes((byte)ExtraParams.Length, bytes, ref i); Buffer.BlockCopy(ExtraParams, 0, bytes, i, ExtraParams.Length); i += ExtraParams.Length; } @@ -10996,6 +11078,7 @@ public TeleportFailedPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 74; Header.Reliable = true; + NeedValidateIDs = false; Info = new InfoBlock(); AlertInfo = null; } @@ -11028,11 +11111,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public TeleportFailedPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; Info.FromBytes(bytes, ref i); @@ -11058,7 +11140,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); Info.ToBytes(bytes, ref i); - bytes[i++] = (byte)AlertInfo.Length; + Utils.ByteToBytes((byte)AlertInfo.Length, bytes, ref i); for (int j = 0; j < AlertInfo.Length; j++) { AlertInfo[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -11226,6 +11308,8 @@ public override int Length public AgentDataBlock AgentData; public ObjectDataBlock[] ObjectData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public UndoPacket() { HasVariableBlocks = true; @@ -11234,6 +11318,7 @@ public UndoPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 75; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); ObjectData = null; } @@ -11266,11 +11351,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public UndoPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -11296,7 +11380,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)ObjectData.Length; + Utils.ByteToBytes((byte)ObjectData.Length, bytes, ref i); for (int j = 0; j < ObjectData.Length; j++) { ObjectData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -11464,6 +11548,8 @@ public override int Length public AgentDataBlock AgentData; public ObjectDataBlock[] ObjectData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public RedoPacket() { HasVariableBlocks = true; @@ -11472,6 +11558,7 @@ public RedoPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 76; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); ObjectData = null; } @@ -11504,11 +11591,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public RedoPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -11534,7 +11620,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)ObjectData.Length; + Utils.ByteToBytes((byte)ObjectData.Length, bytes, ref i); for (int j = 0; j < ObjectData.Length; j++) { ObjectData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -11658,6 +11744,8 @@ public override int Length } public AgentDataBlock AgentData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public UndoLandPacket() { HasVariableBlocks = false; @@ -11666,6 +11754,7 @@ public UndoLandPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 77; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); } @@ -11688,11 +11777,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public UndoLandPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -11775,6 +11863,8 @@ public override int Length } public AgentDataBlock AgentData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public AgentPausePacket() { HasVariableBlocks = false; @@ -11783,6 +11873,7 @@ public AgentPausePacket() Header.Frequency = PacketFrequency.Low; Header.ID = 78; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); } @@ -11805,11 +11896,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public AgentPausePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -11892,6 +11982,8 @@ public override int Length } public AgentDataBlock AgentData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public AgentResumePacket() { HasVariableBlocks = false; @@ -11900,6 +11992,7 @@ public AgentResumePacket() Header.Frequency = PacketFrequency.Low; Header.ID = 79; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); } @@ -11922,11 +12015,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public AgentResumePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -12023,10 +12115,10 @@ public override void FromBytes(byte[] bytes, ref int i) int length; try { - length = (bytes[i++] + (bytes[i++] << 8)); + length = Utils.BytesToUInt16(bytes, i); i+=2; Message = new byte[length]; Buffer.BlockCopy(bytes, i, Message, 0, length); i += length; - Type = (byte)bytes[i++]; + Type = Utils.BytesToByte(bytes, ref i); Channel = Utils.BytesToIntSafepos(bytes, i); i += 4; } catch (Exception) @@ -12037,10 +12129,9 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = (byte)(Message.Length % 256); - bytes[i++] = (byte)((Message.Length >> 8) % 256); + Utils.UInt16ToBytes((ushort)Message.Length, bytes, i); i += 2; Buffer.BlockCopy(Message, 0, bytes, i, Message.Length); i += Message.Length; - bytes[i++] = Type; + Utils.ByteToBytes( Type, bytes, ref i); Utils.IntToBytesSafepos(Channel, bytes, i); i += 4; } @@ -12059,6 +12150,8 @@ public override int Length public AgentDataBlock AgentData; public ChatDataBlock ChatData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ChatFromViewerPacket() { HasVariableBlocks = false; @@ -12067,6 +12160,7 @@ public ChatFromViewerPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 80; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); ChatData = new ChatDataBlock(); @@ -12092,11 +12186,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ChatFromViewerPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -12199,7 +12292,7 @@ public override void FromBytes(byte[] bytes, ref int i) try { GenCounter = Utils.BytesToUIntSafepos(bytes, i); i += 4; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Throttles = new byte[length]; Buffer.BlockCopy(bytes, i, Throttles, 0, length); i += length; } @@ -12212,7 +12305,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { Utils.UIntToBytesSafepos(GenCounter, bytes, i); i += 4; - bytes[i++] = (byte)Throttles.Length; + Utils.ByteToBytes((byte)Throttles.Length, bytes, ref i); Buffer.BlockCopy(Throttles, 0, bytes, i, Throttles.Length); i += Throttles.Length; } @@ -12231,6 +12324,8 @@ public override int Length public AgentDataBlock AgentData; public ThrottleBlock Throttle; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public AgentThrottlePacket() { HasVariableBlocks = false; @@ -12239,6 +12334,7 @@ public AgentThrottlePacket() Header.Frequency = PacketFrequency.Low; Header.ID = 81; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); Throttle = new ThrottleBlock(); @@ -12264,11 +12360,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public AgentThrottlePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -12397,6 +12492,8 @@ public override int Length public AgentDataBlock AgentData; public FOVBlockBlock FOVBlock; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public AgentFOVPacket() { HasVariableBlocks = false; @@ -12405,6 +12502,7 @@ public AgentFOVPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 82; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); FOVBlock = new FOVBlockBlock(); } @@ -12429,11 +12527,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public AgentFOVPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -12565,6 +12662,8 @@ public override int Length public AgentDataBlock AgentData; public HeightWidthBlockBlock HeightWidthBlock; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public AgentHeightWidthPacket() { HasVariableBlocks = false; @@ -12573,6 +12672,7 @@ public AgentHeightWidthPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 83; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); HeightWidthBlock = new HeightWidthBlockBlock(); } @@ -12597,11 +12697,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public AgentHeightWidthPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -12704,7 +12803,7 @@ public override void FromBytes(byte[] bytes, ref int i) try { CacheID.FromBytes(bytes, i); i += 16; - TextureIndex = (byte)bytes[i++]; + TextureIndex = Utils.BytesToByte(bytes, ref i); } catch (Exception) { @@ -12715,7 +12814,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { CacheID.ToBytes(bytes, i); i += 16; - bytes[i++] = TextureIndex; + Utils.ByteToBytes( TextureIndex, bytes, ref i); } } @@ -12746,7 +12845,7 @@ public override void FromBytes(byte[] bytes, ref int i) int length; try { - length = (bytes[i++] + (bytes[i++] << 8)); + length = Utils.BytesToUInt16(bytes, i); i+=2; TextureEntry = new byte[length]; Buffer.BlockCopy(bytes, i, TextureEntry, 0, length); i += length; } @@ -12758,8 +12857,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = (byte)(TextureEntry.Length % 256); - bytes[i++] = (byte)((TextureEntry.Length >> 8) % 256); + Utils.UInt16ToBytes((ushort)TextureEntry.Length, bytes, i); i += 2; Buffer.BlockCopy(TextureEntry, 0, bytes, i, TextureEntry.Length); i += TextureEntry.Length; } @@ -12788,7 +12886,7 @@ public override void FromBytes(byte[] bytes, ref int i) { try { - ParamValue = (byte)bytes[i++]; + ParamValue = Utils.BytesToByte(bytes, ref i); } catch (Exception) { @@ -12798,7 +12896,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = ParamValue; + Utils.ByteToBytes( ParamValue, bytes, ref i); } } @@ -12822,6 +12920,8 @@ public override int Length public ObjectDataBlock ObjectData; public VisualParamBlock[] VisualParam; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public AgentSetAppearancePacket() { HasVariableBlocks = true; @@ -12830,6 +12930,7 @@ public AgentSetAppearancePacket() Header.Frequency = PacketFrequency.Low; Header.ID = 84; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); WearableData = null; @@ -12875,11 +12976,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public AgentSetAppearancePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -12918,10 +13018,10 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)WearableData.Length; + Utils.ByteToBytes((byte)WearableData.Length, bytes, ref i); for (int j = 0; j < WearableData.Length; j++) { WearableData[j].ToBytes(bytes, ref i); } ObjectData.ToBytes(bytes, ref i); - bytes[i++] = (byte)VisualParam.Length; + Utils.ByteToBytes((byte)VisualParam.Length, bytes, ref i); for (int j = 0; j < VisualParam.Length; j++) { VisualParam[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -13028,6 +13128,8 @@ public override int Length public AgentDataBlock AgentData; public FuseBlockBlock FuseBlock; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public AgentQuitCopyPacket() { HasVariableBlocks = false; @@ -13036,6 +13138,7 @@ public AgentQuitCopyPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 85; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); FuseBlock = new FuseBlockBlock(); } @@ -13060,11 +13163,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public AgentQuitCopyPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -13152,6 +13254,7 @@ public ImageNotInDatabasePacket() Header.Frequency = PacketFrequency.Low; Header.ID = 86; Header.Reliable = true; + NeedValidateIDs = false; ImageID = new ImageIDBlock(); } @@ -13174,11 +13277,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ImageNotInDatabasePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; ImageID.FromBytes(bytes, ref i); @@ -13263,6 +13365,7 @@ public RebakeAvatarTexturesPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 87; Header.Reliable = true; + NeedValidateIDs = false; TextureData = new TextureDataBlock(); } @@ -13285,11 +13388,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public RebakeAvatarTexturesPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; TextureData.FromBytes(bytes, ref i); @@ -13344,7 +13446,7 @@ public override void FromBytes(byte[] bytes, ref int i) { AgentID.FromBytes(bytes, i); i += 16; SessionID.FromBytes(bytes, i); i += 16; - AlwaysRun = (bytes[i++] != 0) ? (bool)true : (bool)false; + AlwaysRun = (Utils.BytesToByte(bytes, ref i) != 0); } catch (Exception) { @@ -13356,7 +13458,7 @@ public override void ToBytes(byte[] bytes, ref int i) { AgentID.ToBytes(bytes, i); i += 16; SessionID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)((AlwaysRun) ? 1 : 0); + Utils.ByteToBytes((byte)((AlwaysRun) ? 1 : 0), bytes, ref i); } } @@ -13372,6 +13474,8 @@ public override int Length } public AgentDataBlock AgentData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public SetAlwaysRunPacket() { HasVariableBlocks = false; @@ -13380,6 +13484,7 @@ public SetAlwaysRunPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 88; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); } @@ -13402,11 +13507,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public SetAlwaysRunPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -13461,7 +13565,7 @@ public override void FromBytes(byte[] bytes, ref int i) { AgentID.FromBytes(bytes, i); i += 16; SessionID.FromBytes(bytes, i); i += 16; - Force = (bytes[i++] != 0) ? (bool)true : (bool)false; + Force = (Utils.BytesToByte(bytes, ref i) != 0); } catch (Exception) { @@ -13473,7 +13577,7 @@ public override void ToBytes(byte[] bytes, ref int i) { AgentID.ToBytes(bytes, i); i += 16; SessionID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)((Force) ? 1 : 0); + Utils.ByteToBytes((byte)((Force) ? 1 : 0), bytes, ref i); } } @@ -13530,6 +13634,8 @@ public override int Length public AgentDataBlock AgentData; public ObjectDataBlock[] ObjectData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ObjectDeletePacket() { HasVariableBlocks = true; @@ -13538,6 +13644,7 @@ public ObjectDeletePacket() Header.Frequency = PacketFrequency.Low; Header.ID = 89; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); ObjectData = null; @@ -13571,11 +13678,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ObjectDeletePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -13601,7 +13707,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)ObjectData.Length; + Utils.ByteToBytes((byte)ObjectData.Length, bytes, ref i); for (int j = 0; j < ObjectData.Length; j++) { ObjectData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -13812,6 +13918,8 @@ public override int Length public SharedDataBlock SharedData; public ObjectDataBlock[] ObjectData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ObjectDuplicatePacket() { HasVariableBlocks = true; @@ -13820,6 +13928,7 @@ public ObjectDuplicatePacket() Header.Frequency = PacketFrequency.Low; Header.ID = 90; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); SharedData = new SharedDataBlock(); @@ -13855,11 +13964,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ObjectDuplicatePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -13888,7 +13996,7 @@ public override byte[] ToBytes() Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); SharedData.ToBytes(bytes, ref i); - bytes[i++] = (byte)ObjectData.Length; + Utils.ByteToBytes((byte)ObjectData.Length, bytes, ref i); for (int j = 0; j < ObjectData.Length; j++) { ObjectData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -14000,10 +14108,10 @@ public override void FromBytes(byte[] bytes, ref int i) GroupID.FromBytes(bytes, i); i += 16; RayStart.FromBytes(bytes, i); i += 12; RayEnd.FromBytes(bytes, i); i += 12; - BypassRaycast = (bytes[i++] != 0) ? (bool)true : (bool)false; - RayEndIsIntersection = (bytes[i++] != 0) ? (bool)true : (bool)false; - CopyCenters = (bytes[i++] != 0) ? (bool)true : (bool)false; - CopyRotates = (bytes[i++] != 0) ? (bool)true : (bool)false; + BypassRaycast = (Utils.BytesToByte(bytes, ref i) != 0); + RayEndIsIntersection = (Utils.BytesToByte(bytes, ref i) != 0); + CopyCenters = (Utils.BytesToByte(bytes, ref i) != 0); + CopyRotates = (Utils.BytesToByte(bytes, ref i) != 0); RayTargetID.FromBytes(bytes, i); i += 16; DuplicateFlags = Utils.BytesToUIntSafepos(bytes, i); i += 4; } @@ -14020,10 +14128,10 @@ public override void ToBytes(byte[] bytes, ref int i) GroupID.ToBytes(bytes, i); i += 16; RayStart.ToBytes(bytes, i); i += 12; RayEnd.ToBytes(bytes, i); i += 12; - bytes[i++] = (byte)((BypassRaycast) ? 1 : 0); - bytes[i++] = (byte)((RayEndIsIntersection) ? 1 : 0); - bytes[i++] = (byte)((CopyCenters) ? 1 : 0); - bytes[i++] = (byte)((CopyRotates) ? 1 : 0); + Utils.ByteToBytes((byte)((BypassRaycast) ? 1 : 0), bytes, ref i); + Utils.ByteToBytes((byte)((RayEndIsIntersection) ? 1 : 0), bytes, ref i); + Utils.ByteToBytes((byte)((CopyCenters) ? 1 : 0), bytes, ref i); + Utils.ByteToBytes((byte)((CopyRotates) ? 1 : 0), bytes, ref i); RayTargetID.ToBytes(bytes, i); i += 16; Utils.UIntToBytesSafepos(DuplicateFlags, bytes, i); i += 4; } @@ -14082,6 +14190,8 @@ public override int Length public AgentDataBlock AgentData; public ObjectDataBlock[] ObjectData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ObjectDuplicateOnRayPacket() { HasVariableBlocks = true; @@ -14090,6 +14200,7 @@ public ObjectDuplicateOnRayPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 91; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); ObjectData = null; @@ -14123,11 +14234,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ObjectDuplicateOnRayPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -14153,7 +14263,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)ObjectData.Length; + Utils.ByteToBytes((byte)ObjectData.Length, bytes, ref i); for (int j = 0; j < ObjectData.Length; j++) { ObjectData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -14321,6 +14431,8 @@ public override int Length public AgentDataBlock AgentData; public ObjectDataBlock[] ObjectData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ObjectScalePacket() { HasVariableBlocks = true; @@ -14329,6 +14441,7 @@ public ObjectScalePacket() Header.Frequency = PacketFrequency.Low; Header.ID = 92; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); ObjectData = null; @@ -14362,11 +14475,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ObjectScalePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -14392,7 +14504,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)ObjectData.Length; + Utils.ByteToBytes((byte)ObjectData.Length, bytes, ref i); for (int j = 0; j < ObjectData.Length; j++) { ObjectData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -14560,6 +14672,8 @@ public override int Length public AgentDataBlock AgentData; public ObjectDataBlock[] ObjectData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ObjectRotationPacket() { HasVariableBlocks = true; @@ -14568,6 +14682,7 @@ public ObjectRotationPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 93; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); ObjectData = null; @@ -14601,11 +14716,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ObjectRotationPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -14631,7 +14745,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)ObjectData.Length; + Utils.ByteToBytes((byte)ObjectData.Length, bytes, ref i); for (int j = 0; j < ObjectData.Length; j++) { ObjectData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -14735,10 +14849,10 @@ public override void FromBytes(byte[] bytes, ref int i) AgentID.FromBytes(bytes, i); i += 16; SessionID.FromBytes(bytes, i); i += 16; ObjectLocalID = Utils.BytesToUIntSafepos(bytes, i); i += 4; - UsePhysics = (bytes[i++] != 0) ? (bool)true : (bool)false; - IsTemporary = (bytes[i++] != 0) ? (bool)true : (bool)false; - IsPhantom = (bytes[i++] != 0) ? (bool)true : (bool)false; - CastsShadows = (bytes[i++] != 0) ? (bool)true : (bool)false; + UsePhysics = (Utils.BytesToByte(bytes, ref i) != 0); + IsTemporary = (Utils.BytesToByte(bytes, ref i) != 0); + IsPhantom = (Utils.BytesToByte(bytes, ref i) != 0); + CastsShadows = (Utils.BytesToByte(bytes, ref i) != 0); } catch (Exception) { @@ -14751,10 +14865,10 @@ public override void ToBytes(byte[] bytes, ref int i) AgentID.ToBytes(bytes, i); i += 16; SessionID.ToBytes(bytes, i); i += 16; Utils.UIntToBytesSafepos(ObjectLocalID, bytes, i); i += 4; - bytes[i++] = (byte)((UsePhysics) ? 1 : 0); - bytes[i++] = (byte)((IsTemporary) ? 1 : 0); - bytes[i++] = (byte)((IsPhantom) ? 1 : 0); - bytes[i++] = (byte)((CastsShadows) ? 1 : 0); + Utils.ByteToBytes((byte)((UsePhysics) ? 1 : 0), bytes, ref i); + Utils.ByteToBytes((byte)((IsTemporary) ? 1 : 0), bytes, ref i); + Utils.ByteToBytes((byte)((IsPhantom) ? 1 : 0), bytes, ref i); + Utils.ByteToBytes((byte)((CastsShadows) ? 1 : 0), bytes, ref i); } } @@ -14786,7 +14900,7 @@ public override void FromBytes(byte[] bytes, ref int i) { try { - PhysicsShapeType = (byte)bytes[i++]; + PhysicsShapeType = Utils.BytesToByte(bytes, ref i); Density = Utils.BytesToFloatSafepos(bytes, i); i += 4; Friction = Utils.BytesToFloatSafepos(bytes, i); i += 4; Restitution = Utils.BytesToFloatSafepos(bytes, i); i += 4; @@ -14800,7 +14914,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = PhysicsShapeType; + Utils.ByteToBytes( PhysicsShapeType, bytes, ref i); Utils.FloatToBytesSafepos(Density, bytes, i); i += 4; Utils.FloatToBytesSafepos(Friction, bytes, i); i += 4; Utils.FloatToBytesSafepos(Restitution, bytes, i); i += 4; @@ -14823,6 +14937,8 @@ public override int Length public AgentDataBlock AgentData; public ExtraPhysicsBlock[] ExtraPhysics; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ObjectFlagUpdatePacket() { HasVariableBlocks = true; @@ -14831,6 +14947,7 @@ public ObjectFlagUpdatePacket() Header.Frequency = PacketFrequency.Low; Header.ID = 94; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); ExtraPhysics = null; @@ -14864,11 +14981,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ObjectFlagUpdatePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -14894,7 +15010,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)ExtraPhysics.Length; + Utils.ByteToBytes((byte)ExtraPhysics.Length, bytes, ref i); for (int j = 0; j < ExtraPhysics.Length; j++) { ExtraPhysics[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -15032,7 +15148,7 @@ public override void FromBytes(byte[] bytes, ref int i) try { ObjectLocalID = Utils.BytesToUIntSafepos(bytes, i); i += 4; - ClickAction = (byte)bytes[i++]; + ClickAction = Utils.BytesToByte(bytes, ref i); } catch (Exception) { @@ -15043,7 +15159,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { Utils.UIntToBytesSafepos(ObjectLocalID, bytes, i); i += 4; - bytes[i++] = ClickAction; + Utils.ByteToBytes( ClickAction, bytes, ref i); } } @@ -15062,6 +15178,8 @@ public override int Length public AgentDataBlock AgentData; public ObjectDataBlock[] ObjectData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ObjectClickActionPacket() { HasVariableBlocks = true; @@ -15070,6 +15188,7 @@ public ObjectClickActionPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 95; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); ObjectData = null; @@ -15103,11 +15222,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ObjectClickActionPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -15133,7 +15251,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)ObjectData.Length; + Utils.ByteToBytes((byte)ObjectData.Length, bytes, ref i); for (int j = 0; j < ObjectData.Length; j++) { ObjectData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -15276,10 +15394,10 @@ public override void FromBytes(byte[] bytes, ref int i) try { ObjectLocalID = Utils.BytesToUIntSafepos(bytes, i); i += 4; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); MediaURL = new byte[length]; Buffer.BlockCopy(bytes, i, MediaURL, 0, length); i += length; - length = (bytes[i++] + (bytes[i++] << 8)); + length = Utils.BytesToUInt16(bytes, i); i+=2; TextureEntry = new byte[length]; Buffer.BlockCopy(bytes, i, TextureEntry, 0, length); i += length; } @@ -15292,10 +15410,9 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { Utils.UIntToBytesSafepos(ObjectLocalID, bytes, i); i += 4; - bytes[i++] = (byte)MediaURL.Length; + Utils.ByteToBytes((byte)MediaURL.Length, bytes, ref i); Buffer.BlockCopy(MediaURL, 0, bytes, i, MediaURL.Length); i += MediaURL.Length; - bytes[i++] = (byte)(TextureEntry.Length % 256); - bytes[i++] = (byte)((TextureEntry.Length >> 8) % 256); + Utils.UInt16ToBytes((ushort)TextureEntry.Length, bytes, i); i += 2; Buffer.BlockCopy(TextureEntry, 0, bytes, i, TextureEntry.Length); i += TextureEntry.Length; } @@ -15315,6 +15432,8 @@ public override int Length public AgentDataBlock AgentData; public ObjectDataBlock[] ObjectData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ObjectImagePacket() { HasVariableBlocks = true; @@ -15323,6 +15442,7 @@ public ObjectImagePacket() Header.Frequency = PacketFrequency.Low; Header.ID = 96; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); ObjectData = null; @@ -15356,11 +15476,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ObjectImagePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -15386,7 +15505,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)ObjectData.Length; + Utils.ByteToBytes((byte)ObjectData.Length, bytes, ref i); for (int j = 0; j < ObjectData.Length; j++) { ObjectData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -15524,7 +15643,7 @@ public override void FromBytes(byte[] bytes, ref int i) try { ObjectLocalID = Utils.BytesToUIntSafepos(bytes, i); i += 4; - Material = (byte)bytes[i++]; + Material = Utils.BytesToByte(bytes, ref i); } catch (Exception) { @@ -15535,7 +15654,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { Utils.UIntToBytesSafepos(ObjectLocalID, bytes, i); i += 4; - bytes[i++] = Material; + Utils.ByteToBytes( Material, bytes, ref i); } } @@ -15554,6 +15673,8 @@ public override int Length public AgentDataBlock AgentData; public ObjectDataBlock[] ObjectData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ObjectMaterialPacket() { HasVariableBlocks = true; @@ -15562,6 +15683,7 @@ public ObjectMaterialPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 97; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); ObjectData = null; @@ -15595,11 +15717,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ObjectMaterialPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -15625,7 +15746,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)ObjectData.Length; + Utils.ByteToBytes((byte)ObjectData.Length, bytes, ref i); for (int j = 0; j < ObjectData.Length; j++) { ObjectData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -15780,21 +15901,21 @@ public override void FromBytes(byte[] bytes, ref int i) try { ObjectLocalID = Utils.BytesToUIntSafepos(bytes, i); i += 4; - PathCurve = (byte)bytes[i++]; - ProfileCurve = (byte)bytes[i++]; + PathCurve = Utils.BytesToByte(bytes, ref i); + ProfileCurve = Utils.BytesToByte(bytes, ref i); PathBegin = Utils.BytesToUInt16(bytes, i); i += 2; PathEnd = Utils.BytesToUInt16(bytes, i); i += 2; - PathScaleX = (byte)bytes[i++]; - PathScaleY = (byte)bytes[i++]; - PathShearX = (byte)bytes[i++]; - PathShearY = (byte)bytes[i++]; - PathTwist = (sbyte)bytes[i++]; - PathTwistBegin = (sbyte)bytes[i++]; - PathRadiusOffset = (sbyte)bytes[i++]; - PathTaperX = (sbyte)bytes[i++]; - PathTaperY = (sbyte)bytes[i++]; - PathRevolutions = (byte)bytes[i++]; - PathSkew = (sbyte)bytes[i++]; + PathScaleX = Utils.BytesToByte(bytes, ref i); + PathScaleY = Utils.BytesToByte(bytes, ref i); + PathShearX = Utils.BytesToByte(bytes, ref i); + PathShearY = Utils.BytesToByte(bytes, ref i); + PathTwist = (sbyte)Utils.BytesToByte(bytes, ref i); + PathTwistBegin = (sbyte)Utils.BytesToByte(bytes, ref i); + PathRadiusOffset = (sbyte)Utils.BytesToByte(bytes, ref i); + PathTaperX = (sbyte)Utils.BytesToByte(bytes, ref i); + PathTaperY = (sbyte)Utils.BytesToByte(bytes, ref i); + PathRevolutions = Utils.BytesToByte(bytes, ref i); + PathSkew = (sbyte)Utils.BytesToByte(bytes, ref i); ProfileBegin = Utils.BytesToUInt16(bytes, i); i += 2; ProfileEnd = Utils.BytesToUInt16(bytes, i); i += 2; ProfileHollow = Utils.BytesToUInt16(bytes, i); i += 2; @@ -15808,21 +15929,21 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { Utils.UIntToBytesSafepos(ObjectLocalID, bytes, i); i += 4; - bytes[i++] = PathCurve; - bytes[i++] = ProfileCurve; + Utils.ByteToBytes( PathCurve, bytes, ref i); + Utils.ByteToBytes( ProfileCurve, bytes, ref i); Utils.UInt16ToBytes(PathBegin, bytes, i); i += 2; Utils.UInt16ToBytes(PathEnd, bytes, i); i += 2; - bytes[i++] = PathScaleX; - bytes[i++] = PathScaleY; - bytes[i++] = PathShearX; - bytes[i++] = PathShearY; - bytes[i++] = (byte)PathTwist; - bytes[i++] = (byte)PathTwistBegin; - bytes[i++] = (byte)PathRadiusOffset; - bytes[i++] = (byte)PathTaperX; - bytes[i++] = (byte)PathTaperY; - bytes[i++] = PathRevolutions; - bytes[i++] = (byte)PathSkew; + Utils.ByteToBytes( PathScaleX, bytes, ref i); + Utils.ByteToBytes( PathScaleY, bytes, ref i); + Utils.ByteToBytes( PathShearX, bytes, ref i); + Utils.ByteToBytes( PathShearY, bytes, ref i); + Utils.ByteToBytes( (byte)PathTwist, bytes, ref i); + Utils.ByteToBytes( (byte)PathTwistBegin, bytes, ref i); + Utils.ByteToBytes( (byte)PathRadiusOffset, bytes, ref i); + Utils.ByteToBytes( (byte)PathTaperX, bytes, ref i); + Utils.ByteToBytes( (byte)PathTaperY, bytes, ref i); + Utils.ByteToBytes( PathRevolutions, bytes, ref i); + Utils.ByteToBytes( (byte)PathSkew, bytes, ref i); Utils.UInt16ToBytes(ProfileBegin, bytes, i); i += 2; Utils.UInt16ToBytes(ProfileEnd, bytes, i); i += 2; Utils.UInt16ToBytes(ProfileHollow, bytes, i); i += 2; @@ -15844,6 +15965,8 @@ public override int Length public AgentDataBlock AgentData; public ObjectDataBlock[] ObjectData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ObjectShapePacket() { HasVariableBlocks = true; @@ -15852,6 +15975,7 @@ public ObjectShapePacket() Header.Frequency = PacketFrequency.Low; Header.ID = 98; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); ObjectData = null; @@ -15885,11 +16009,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ObjectShapePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -15915,7 +16038,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)ObjectData.Length; + Utils.ByteToBytes((byte)ObjectData.Length, bytes, ref i); for (int j = 0; j < ObjectData.Length; j++) { ObjectData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -16060,9 +16183,9 @@ public override void FromBytes(byte[] bytes, ref int i) { ObjectLocalID = Utils.BytesToUIntSafepos(bytes, i); i += 4; ParamType = Utils.BytesToUInt16(bytes, i); i += 2; - ParamInUse = (bytes[i++] != 0) ? (bool)true : (bool)false; + ParamInUse = (Utils.BytesToByte(bytes, ref i) != 0); ParamSize = Utils.BytesToUIntSafepos(bytes, i); i += 4; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); ParamData = new byte[length]; Buffer.BlockCopy(bytes, i, ParamData, 0, length); i += length; } @@ -16076,9 +16199,9 @@ public override void ToBytes(byte[] bytes, ref int i) { Utils.UIntToBytesSafepos(ObjectLocalID, bytes, i); i += 4; Utils.UInt16ToBytes(ParamType, bytes, i); i += 2; - bytes[i++] = (byte)((ParamInUse) ? 1 : 0); + Utils.ByteToBytes((byte)((ParamInUse) ? 1 : 0), bytes, ref i); Utils.UIntToBytesSafepos(ParamSize, bytes, i); i += 4; - bytes[i++] = (byte)ParamData.Length; + Utils.ByteToBytes((byte)ParamData.Length, bytes, ref i); Buffer.BlockCopy(ParamData, 0, bytes, i, ParamData.Length); i += ParamData.Length; } @@ -16098,6 +16221,8 @@ public override int Length public AgentDataBlock AgentData; public ObjectDataBlock[] ObjectData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ObjectExtraParamsPacket() { HasVariableBlocks = true; @@ -16106,6 +16231,7 @@ public ObjectExtraParamsPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 99; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); ObjectData = null; @@ -16139,11 +16265,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ObjectExtraParamsPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -16169,7 +16294,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)ObjectData.Length; + Utils.ByteToBytes((byte)ObjectData.Length, bytes, ref i); for (int j = 0; j < ObjectData.Length; j++) { ObjectData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -16307,7 +16432,7 @@ public override void FromBytes(byte[] bytes, ref int i) { try { - Override = (bytes[i++] != 0) ? (bool)true : (bool)false; + Override = (Utils.BytesToByte(bytes, ref i) != 0); OwnerID.FromBytes(bytes, i); i += 16; GroupID.FromBytes(bytes, i); i += 16; } @@ -16319,7 +16444,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = (byte)((Override) ? 1 : 0); + Utils.ByteToBytes((byte)((Override) ? 1 : 0), bytes, ref i); OwnerID.ToBytes(bytes, i); i += 16; GroupID.ToBytes(bytes, i); i += 16; } @@ -16380,6 +16505,8 @@ public override int Length public HeaderDataBlock HeaderData; public ObjectDataBlock[] ObjectData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ObjectOwnerPacket() { HasVariableBlocks = true; @@ -16388,6 +16515,7 @@ public ObjectOwnerPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 100; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); HeaderData = new HeaderDataBlock(); @@ -16423,11 +16551,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ObjectOwnerPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -16456,7 +16583,7 @@ public override byte[] ToBytes() Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); HeaderData.ToBytes(bytes, ref i); - bytes[i++] = (byte)ObjectData.Length; + Utils.ByteToBytes((byte)ObjectData.Length, bytes, ref i); for (int j = 0; j < ObjectData.Length; j++) { ObjectData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -16626,6 +16753,8 @@ public override int Length public AgentDataBlock AgentData; public ObjectDataBlock[] ObjectData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ObjectGroupPacket() { HasVariableBlocks = true; @@ -16634,6 +16763,7 @@ public ObjectGroupPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 101; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); ObjectData = null; @@ -16667,11 +16797,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ObjectGroupPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -16697,7 +16826,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)ObjectData.Length; + Utils.ByteToBytes((byte)ObjectData.Length, bytes, ref i); for (int j = 0; j < ObjectData.Length; j++) { ObjectData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -16842,7 +16971,7 @@ public override void FromBytes(byte[] bytes, ref int i) try { ObjectLocalID = Utils.BytesToUIntSafepos(bytes, i); i += 4; - SaleType = (byte)bytes[i++]; + SaleType = Utils.BytesToByte(bytes, ref i); SalePrice = Utils.BytesToIntSafepos(bytes, i); i += 4; } catch (Exception) @@ -16854,7 +16983,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { Utils.UIntToBytesSafepos(ObjectLocalID, bytes, i); i += 4; - bytes[i++] = SaleType; + Utils.ByteToBytes( SaleType, bytes, ref i); Utils.IntToBytesSafepos(SalePrice, bytes, i); i += 4; } @@ -16874,6 +17003,8 @@ public override int Length public AgentDataBlock AgentData; public ObjectDataBlock[] ObjectData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ObjectBuyPacket() { HasVariableBlocks = true; @@ -16882,6 +17013,7 @@ public ObjectBuyPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 102; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); ObjectData = null; @@ -16915,11 +17047,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ObjectBuyPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -16945,7 +17076,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)ObjectData.Length; + Utils.ByteToBytes((byte)ObjectData.Length, bytes, ref i); for (int j = 0; j < ObjectData.Length; j++) { ObjectData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -17115,6 +17246,8 @@ public override int Length public AgentDataBlock AgentData; public DataBlock Data; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public BuyObjectInventoryPacket() { HasVariableBlocks = false; @@ -17123,6 +17256,7 @@ public BuyObjectInventoryPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 103; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); Data = new DataBlock(); @@ -17148,11 +17282,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public BuyObjectInventoryPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -17208,7 +17341,7 @@ public override void FromBytes(byte[] bytes, ref int i) try { ObjectID.FromBytes(bytes, i); i += 16; - Delete = (bytes[i++] != 0) ? (bool)true : (bool)false; + Delete = (Utils.BytesToByte(bytes, ref i) != 0); } catch (Exception) { @@ -17219,7 +17352,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { ObjectID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)((Delete) ? 1 : 0); + Utils.ByteToBytes((byte)((Delete) ? 1 : 0), bytes, ref i); } } @@ -17243,6 +17376,7 @@ public DerezContainerPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 104; Header.Reliable = true; + NeedValidateIDs = false; Header.Zerocoded = true; Data = new DataBlock(); } @@ -17266,11 +17400,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public DerezContainerPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; Data.FromBytes(bytes, ref i); @@ -17362,7 +17495,7 @@ public override void FromBytes(byte[] bytes, ref int i) { try { - Override = (bytes[i++] != 0) ? (bool)true : (bool)false; + Override = (Utils.BytesToByte(bytes, ref i) != 0); } catch (Exception) { @@ -17372,7 +17505,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = (byte)((Override) ? 1 : 0); + Utils.ByteToBytes((byte)((Override) ? 1 : 0), bytes, ref i); } } @@ -17404,8 +17537,8 @@ public override void FromBytes(byte[] bytes, ref int i) try { ObjectLocalID = Utils.BytesToUIntSafepos(bytes, i); i += 4; - Field = (byte)bytes[i++]; - Set = (byte)bytes[i++]; + Field = Utils.BytesToByte(bytes, ref i); + Set = Utils.BytesToByte(bytes, ref i); Mask = Utils.BytesToUIntSafepos(bytes, i); i += 4; } catch (Exception) @@ -17417,8 +17550,8 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { Utils.UIntToBytesSafepos(ObjectLocalID, bytes, i); i += 4; - bytes[i++] = Field; - bytes[i++] = Set; + Utils.ByteToBytes( Field, bytes, ref i); + Utils.ByteToBytes( Set, bytes, ref i); Utils.UIntToBytesSafepos(Mask, bytes, i); i += 4; } @@ -17440,6 +17573,8 @@ public override int Length public HeaderDataBlock HeaderData; public ObjectDataBlock[] ObjectData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ObjectPermissionsPacket() { HasVariableBlocks = true; @@ -17448,6 +17583,7 @@ public ObjectPermissionsPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 105; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); HeaderData = new HeaderDataBlock(); @@ -17483,11 +17619,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ObjectPermissionsPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -17516,7 +17651,7 @@ public override byte[] ToBytes() Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); HeaderData.ToBytes(bytes, ref i); - bytes[i++] = (byte)ObjectData.Length; + Utils.ByteToBytes((byte)ObjectData.Length, bytes, ref i); for (int j = 0; j < ObjectData.Length; j++) { ObjectData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -17657,7 +17792,7 @@ public override void FromBytes(byte[] bytes, ref int i) try { LocalID = Utils.BytesToUIntSafepos(bytes, i); i += 4; - SaleType = (byte)bytes[i++]; + SaleType = Utils.BytesToByte(bytes, ref i); SalePrice = Utils.BytesToIntSafepos(bytes, i); i += 4; } catch (Exception) @@ -17669,7 +17804,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { Utils.UIntToBytesSafepos(LocalID, bytes, i); i += 4; - bytes[i++] = SaleType; + Utils.ByteToBytes( SaleType, bytes, ref i); Utils.IntToBytesSafepos(SalePrice, bytes, i); i += 4; } @@ -17689,6 +17824,8 @@ public override int Length public AgentDataBlock AgentData; public ObjectDataBlock[] ObjectData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ObjectSaleInfoPacket() { HasVariableBlocks = true; @@ -17697,6 +17834,7 @@ public ObjectSaleInfoPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 106; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); ObjectData = null; @@ -17730,11 +17868,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ObjectSaleInfoPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -17760,7 +17897,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)ObjectData.Length; + Utils.ByteToBytes((byte)ObjectData.Length, bytes, ref i); for (int j = 0; j < ObjectData.Length; j++) { ObjectData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -17901,7 +18038,7 @@ public override void FromBytes(byte[] bytes, ref int i) try { LocalID = Utils.BytesToUIntSafepos(bytes, i); i += 4; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Name = new byte[length]; Buffer.BlockCopy(bytes, i, Name, 0, length); i += length; } @@ -17914,7 +18051,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { Utils.UIntToBytesSafepos(LocalID, bytes, i); i += 4; - bytes[i++] = (byte)Name.Length; + Utils.ByteToBytes((byte)Name.Length, bytes, ref i); Buffer.BlockCopy(Name, 0, bytes, i, Name.Length); i += Name.Length; } @@ -17934,6 +18071,8 @@ public override int Length public AgentDataBlock AgentData; public ObjectDataBlock[] ObjectData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ObjectNamePacket() { HasVariableBlocks = true; @@ -17942,6 +18081,7 @@ public ObjectNamePacket() Header.Frequency = PacketFrequency.Low; Header.ID = 107; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); ObjectData = null; @@ -17975,11 +18115,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ObjectNamePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -18005,7 +18144,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)ObjectData.Length; + Utils.ByteToBytes((byte)ObjectData.Length, bytes, ref i); for (int j = 0; j < ObjectData.Length; j++) { ObjectData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -18146,7 +18285,7 @@ public override void FromBytes(byte[] bytes, ref int i) try { LocalID = Utils.BytesToUIntSafepos(bytes, i); i += 4; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Description = new byte[length]; Buffer.BlockCopy(bytes, i, Description, 0, length); i += length; } @@ -18159,7 +18298,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { Utils.UIntToBytesSafepos(LocalID, bytes, i); i += 4; - bytes[i++] = (byte)Description.Length; + Utils.ByteToBytes((byte)Description.Length, bytes, ref i); Buffer.BlockCopy(Description, 0, bytes, i, Description.Length); i += Description.Length; } @@ -18179,6 +18318,8 @@ public override int Length public AgentDataBlock AgentData; public ObjectDataBlock[] ObjectData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ObjectDescriptionPacket() { HasVariableBlocks = true; @@ -18187,6 +18328,7 @@ public ObjectDescriptionPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 108; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); ObjectData = null; @@ -18220,11 +18362,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ObjectDescriptionPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -18250,7 +18391,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)ObjectData.Length; + Utils.ByteToBytes((byte)ObjectData.Length, bytes, ref i); for (int j = 0; j < ObjectData.Length; j++) { ObjectData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -18418,6 +18559,8 @@ public override int Length public AgentDataBlock AgentData; public ObjectDataBlock[] ObjectData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ObjectCategoryPacket() { HasVariableBlocks = true; @@ -18426,6 +18569,7 @@ public ObjectCategoryPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 109; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); ObjectData = null; @@ -18459,11 +18603,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ObjectCategoryPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -18489,7 +18632,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)ObjectData.Length; + Utils.ByteToBytes((byte)ObjectData.Length, bytes, ref i); for (int j = 0; j < ObjectData.Length; j++) { ObjectData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -18654,6 +18797,8 @@ public override int Length public AgentDataBlock AgentData; public ObjectDataBlock[] ObjectData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ObjectSelectPacket() { HasVariableBlocks = true; @@ -18662,6 +18807,7 @@ public ObjectSelectPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 110; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); ObjectData = null; @@ -18695,11 +18841,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ObjectSelectPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -18725,7 +18870,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)ObjectData.Length; + Utils.ByteToBytes((byte)ObjectData.Length, bytes, ref i); for (int j = 0; j < ObjectData.Length; j++) { ObjectData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -18890,6 +19035,8 @@ public override int Length public AgentDataBlock AgentData; public ObjectDataBlock[] ObjectData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ObjectDeselectPacket() { HasVariableBlocks = true; @@ -18898,6 +19045,7 @@ public ObjectDeselectPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 111; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); ObjectData = null; @@ -18931,11 +19079,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ObjectDeselectPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -18961,7 +19108,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)ObjectData.Length; + Utils.ByteToBytes((byte)ObjectData.Length, bytes, ref i); for (int j = 0; j < ObjectData.Length; j++) { ObjectData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -19060,7 +19207,7 @@ public override void FromBytes(byte[] bytes, ref int i) { AgentID.FromBytes(bytes, i); i += 16; SessionID.FromBytes(bytes, i); i += 16; - AttachmentPoint = (byte)bytes[i++]; + AttachmentPoint = Utils.BytesToByte(bytes, ref i); } catch (Exception) { @@ -19072,7 +19219,7 @@ public override void ToBytes(byte[] bytes, ref int i) { AgentID.ToBytes(bytes, i); i += 16; SessionID.ToBytes(bytes, i); i += 16; - bytes[i++] = AttachmentPoint; + Utils.ByteToBytes( AttachmentPoint, bytes, ref i); } } @@ -19132,6 +19279,8 @@ public override int Length public AgentDataBlock AgentData; public ObjectDataBlock[] ObjectData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ObjectAttachPacket() { HasVariableBlocks = true; @@ -19140,6 +19289,7 @@ public ObjectAttachPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 112; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); ObjectData = null; @@ -19173,11 +19323,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ObjectAttachPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -19203,7 +19352,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)ObjectData.Length; + Utils.ByteToBytes((byte)ObjectData.Length, bytes, ref i); for (int j = 0; j < ObjectData.Length; j++) { ObjectData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -19368,6 +19517,8 @@ public override int Length public AgentDataBlock AgentData; public ObjectDataBlock[] ObjectData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ObjectDetachPacket() { HasVariableBlocks = true; @@ -19376,6 +19527,7 @@ public ObjectDetachPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 113; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); ObjectData = null; } @@ -19408,11 +19560,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ObjectDetachPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -19438,7 +19589,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)ObjectData.Length; + Utils.ByteToBytes((byte)ObjectData.Length, bytes, ref i); for (int j = 0; j < ObjectData.Length; j++) { ObjectData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -19603,6 +19754,8 @@ public override int Length public AgentDataBlock AgentData; public ObjectDataBlock[] ObjectData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ObjectDropPacket() { HasVariableBlocks = true; @@ -19611,6 +19764,7 @@ public ObjectDropPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 114; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); ObjectData = null; } @@ -19643,11 +19797,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ObjectDropPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -19673,7 +19826,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)ObjectData.Length; + Utils.ByteToBytes((byte)ObjectData.Length, bytes, ref i); for (int j = 0; j < ObjectData.Length; j++) { ObjectData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -19838,6 +19991,8 @@ public override int Length public AgentDataBlock AgentData; public ObjectDataBlock[] ObjectData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ObjectLinkPacket() { HasVariableBlocks = true; @@ -19846,6 +20001,7 @@ public ObjectLinkPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 115; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); ObjectData = null; } @@ -19878,11 +20034,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ObjectLinkPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -19908,7 +20063,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)ObjectData.Length; + Utils.ByteToBytes((byte)ObjectData.Length, bytes, ref i); for (int j = 0; j < ObjectData.Length; j++) { ObjectData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -20073,6 +20228,8 @@ public override int Length public AgentDataBlock AgentData; public ObjectDataBlock[] ObjectData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ObjectDelinkPacket() { HasVariableBlocks = true; @@ -20081,6 +20238,7 @@ public ObjectDelinkPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 116; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); ObjectData = null; } @@ -20113,11 +20271,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ObjectDelinkPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -20143,7 +20300,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)ObjectData.Length; + Utils.ByteToBytes((byte)ObjectData.Length, bytes, ref i); for (int j = 0; j < ObjectData.Length; j++) { ObjectData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -20366,6 +20523,8 @@ public override int Length public ObjectDataBlock ObjectData; public SurfaceInfoBlock[] SurfaceInfo; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ObjectGrabPacket() { HasVariableBlocks = true; @@ -20374,6 +20533,7 @@ public ObjectGrabPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 117; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); ObjectData = new ObjectDataBlock(); @@ -20409,11 +20569,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ObjectGrabPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -20442,7 +20601,7 @@ public override byte[] ToBytes() Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); ObjectData.ToBytes(bytes, ref i); - bytes[i++] = (byte)SurfaceInfo.Length; + Utils.ByteToBytes((byte)SurfaceInfo.Length, bytes, ref i); for (int j = 0; j < SurfaceInfo.Length; j++) { SurfaceInfo[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -20673,6 +20832,8 @@ public override int Length public ObjectDataBlock ObjectData; public SurfaceInfoBlock[] SurfaceInfo; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ObjectGrabUpdatePacket() { HasVariableBlocks = true; @@ -20681,6 +20842,7 @@ public ObjectGrabUpdatePacket() Header.Frequency = PacketFrequency.Low; Header.ID = 118; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); ObjectData = new ObjectDataBlock(); @@ -20716,11 +20878,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ObjectGrabUpdatePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -20749,7 +20910,7 @@ public override byte[] ToBytes() Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); ObjectData.ToBytes(bytes, ref i); - bytes[i++] = (byte)SurfaceInfo.Length; + Utils.ByteToBytes((byte)SurfaceInfo.Length, bytes, ref i); for (int j = 0; j < SurfaceInfo.Length; j++) { SurfaceInfo[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -20971,6 +21132,8 @@ public override int Length public ObjectDataBlock ObjectData; public SurfaceInfoBlock[] SurfaceInfo; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ObjectDeGrabPacket() { HasVariableBlocks = true; @@ -20979,6 +21142,7 @@ public ObjectDeGrabPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 119; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); ObjectData = new ObjectDataBlock(); SurfaceInfo = null; @@ -21013,11 +21177,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ObjectDeGrabPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -21046,7 +21209,7 @@ public override byte[] ToBytes() Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); ObjectData.ToBytes(bytes, ref i); - bytes[i++] = (byte)SurfaceInfo.Length; + Utils.ByteToBytes((byte)SurfaceInfo.Length, bytes, ref i); for (int j = 0; j < SurfaceInfo.Length; j++) { SurfaceInfo[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -21212,6 +21375,8 @@ public override int Length public AgentDataBlock AgentData; public ObjectDataBlock ObjectData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ObjectSpinStartPacket() { HasVariableBlocks = false; @@ -21220,6 +21385,7 @@ public ObjectSpinStartPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 120; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); ObjectData = new ObjectDataBlock(); @@ -21245,11 +21411,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ObjectSpinStartPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -21375,6 +21540,8 @@ public override int Length public AgentDataBlock AgentData; public ObjectDataBlock ObjectData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ObjectSpinUpdatePacket() { HasVariableBlocks = false; @@ -21383,6 +21550,7 @@ public ObjectSpinUpdatePacket() Header.Frequency = PacketFrequency.Low; Header.ID = 121; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); ObjectData = new ObjectDataBlock(); @@ -21408,11 +21576,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ObjectSpinUpdatePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -21535,6 +21702,8 @@ public override int Length public AgentDataBlock AgentData; public ObjectDataBlock ObjectData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ObjectSpinStopPacket() { HasVariableBlocks = false; @@ -21543,6 +21712,7 @@ public ObjectSpinStopPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 122; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); ObjectData = new ObjectDataBlock(); @@ -21568,11 +21738,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ObjectSpinStopPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -21707,6 +21876,7 @@ public ObjectExportSelectedPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 123; Header.Reliable = true; + NeedValidateIDs = false; Header.Zerocoded = true; AgentData = new AgentDataBlock(); ObjectData = null; @@ -21740,11 +21910,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ObjectExportSelectedPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -21770,7 +21939,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)ObjectData.Length; + Utils.ByteToBytes((byte)ObjectData.Length, bytes, ref i); for (int j = 0; j < ObjectData.Length; j++) { ObjectData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -21909,8 +22078,8 @@ public override void FromBytes(byte[] bytes, ref int i) { try { - Action = (byte)bytes[i++]; - BrushSize = (byte)bytes[i++]; + Action = Utils.BytesToByte(bytes, ref i); + BrushSize = Utils.BytesToByte(bytes, ref i); Seconds = Utils.BytesToFloatSafepos(bytes, i); i += 4; Height = Utils.BytesToFloatSafepos(bytes, i); i += 4; } @@ -21922,8 +22091,8 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = Action; - bytes[i++] = BrushSize; + Utils.ByteToBytes( Action, bytes, ref i); + Utils.ByteToBytes( BrushSize, bytes, ref i); Utils.FloatToBytesSafepos(Seconds, bytes, i); i += 4; Utils.FloatToBytesSafepos(Height, bytes, i); i += 4; } @@ -22037,6 +22206,8 @@ public override int Length public ParcelDataBlock[] ParcelData; public ModifyBlockExtendedBlock[] ModifyBlockExtended; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ModifyLandPacket() { HasVariableBlocks = true; @@ -22045,6 +22216,7 @@ public ModifyLandPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 124; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); ModifyBlock = new ModifyBlockBlock(); @@ -22090,11 +22262,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ModifyLandPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -22134,9 +22305,9 @@ public override byte[] ToBytes() Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); ModifyBlock.ToBytes(bytes, ref i); - bytes[i++] = (byte)ParcelData.Length; + Utils.ByteToBytes((byte)ParcelData.Length, bytes, ref i); for (int j = 0; j < ParcelData.Length; j++) { ParcelData[j].ToBytes(bytes, ref i); } - bytes[i++] = (byte)ModifyBlockExtended.Length; + Utils.ByteToBytes((byte)ModifyBlockExtended.Length, bytes, ref i); for (int j = 0; j < ModifyBlockExtended.Length; j++) { ModifyBlockExtended[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -22282,6 +22453,8 @@ public override int Length } public AgentDataBlock AgentData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public VelocityInterpolateOnPacket() { HasVariableBlocks = false; @@ -22290,6 +22463,7 @@ public VelocityInterpolateOnPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 125; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); } @@ -22312,11 +22486,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public VelocityInterpolateOnPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -22396,6 +22569,8 @@ public override int Length } public AgentDataBlock AgentData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public VelocityInterpolateOffPacket() { HasVariableBlocks = false; @@ -22404,6 +22579,7 @@ public VelocityInterpolateOffPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 126; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); } @@ -22426,11 +22602,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public VelocityInterpolateOffPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -22525,7 +22700,7 @@ public override void FromBytes(byte[] bytes, ref int i) int length; try { - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Filename = new byte[length]; Buffer.BlockCopy(bytes, i, Filename, 0, length); i += length; } @@ -22537,7 +22712,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = (byte)Filename.Length; + Utils.ByteToBytes((byte)Filename.Length, bytes, ref i); Buffer.BlockCopy(Filename, 0, bytes, i, Filename.Length); i += Filename.Length; } @@ -22556,6 +22731,8 @@ public override int Length public AgentDataBlock AgentData; public DataBlockBlock DataBlock; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public StateSavePacket() { HasVariableBlocks = false; @@ -22564,6 +22741,7 @@ public StateSavePacket() Header.Frequency = PacketFrequency.Low; Header.ID = 127; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); DataBlock = new DataBlockBlock(); } @@ -22588,11 +22766,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public StateSavePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -22683,6 +22860,7 @@ public ReportAutosaveCrashPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 128; Header.Reliable = true; + NeedValidateIDs = false; AutosaveData = new AutosaveDataBlock(); } @@ -22705,11 +22883,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ReportAutosaveCrashPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AutosaveData.FromBytes(bytes, ref i); @@ -22832,6 +23009,8 @@ public override int Length public AgentDataBlock AgentData; public DataBlockBlock DataBlock; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public SimWideDeletesPacket() { HasVariableBlocks = false; @@ -22840,6 +23019,7 @@ public SimWideDeletesPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 129; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); DataBlock = new DataBlockBlock(); } @@ -22864,11 +23044,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public SimWideDeletesPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -22991,6 +23170,8 @@ public override int Length public AgentDataBlock AgentData; public TargetDataBlock TargetData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public TrackAgentPacket() { HasVariableBlocks = false; @@ -22999,6 +23180,7 @@ public TrackAgentPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 130; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); TargetData = new TargetDataBlock(); } @@ -23023,11 +23205,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public TrackAgentPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -23107,18 +23288,18 @@ public override void FromBytes(byte[] bytes, ref int i) RunTime = Utils.BytesToFloatSafepos(bytes, i); i += 4; SimFPS = Utils.BytesToFloatSafepos(bytes, i); i += 4; FPS = Utils.BytesToFloatSafepos(bytes, i); i += 4; - AgentsInView = (byte)bytes[i++]; + AgentsInView = Utils.BytesToByte(bytes, ref i); Ping = Utils.BytesToFloatSafepos(bytes, i); i += 4; MetersTraveled = Utils.BytesToDoubleSafepos(bytes, i); i += 8; RegionsVisited = Utils.BytesToIntSafepos(bytes, i); i += 4; SysRAM = Utils.BytesToUIntSafepos(bytes, i); i += 4; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); SysOS = new byte[length]; Buffer.BlockCopy(bytes, i, SysOS, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); SysCPU = new byte[length]; Buffer.BlockCopy(bytes, i, SysCPU, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); SysGPU = new byte[length]; Buffer.BlockCopy(bytes, i, SysGPU, 0, length); i += length; } @@ -23137,16 +23318,16 @@ public override void ToBytes(byte[] bytes, ref int i) Utils.FloatToBytesSafepos(RunTime, bytes, i); i += 4; Utils.FloatToBytesSafepos(SimFPS, bytes, i); i += 4; Utils.FloatToBytesSafepos(FPS, bytes, i); i += 4; - bytes[i++] = AgentsInView; + Utils.ByteToBytes( AgentsInView, bytes, ref i); Utils.FloatToBytesSafepos(Ping, bytes, i); i += 4; Utils.DoubleToBytesSafepos(MetersTraveled, bytes, i); i += 8; Utils.IntToBytesSafepos(RegionsVisited, bytes, i); i += 4; Utils.UIntToBytesSafepos(SysRAM, bytes, i); i += 4; - bytes[i++] = (byte)SysOS.Length; + Utils.ByteToBytes((byte)SysOS.Length, bytes, ref i); Buffer.BlockCopy(SysOS, 0, bytes, i, SysOS.Length); i += SysOS.Length; - bytes[i++] = (byte)SysCPU.Length; + Utils.ByteToBytes((byte)SysCPU.Length, bytes, ref i); Buffer.BlockCopy(SysCPU, 0, bytes, i, SysCPU.Length); i += SysCPU.Length; - bytes[i++] = (byte)SysGPU.Length; + Utils.ByteToBytes((byte)SysGPU.Length, bytes, ref i); Buffer.BlockCopy(SysGPU, 0, bytes, i, SysGPU.Length); i += SysGPU.Length; } @@ -23358,6 +23539,8 @@ public override int Length public FailStatsBlock FailStats; public MiscStatsBlock[] MiscStats; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ViewerStatsPacket() { HasVariableBlocks = true; @@ -23366,6 +23549,7 @@ public ViewerStatsPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 131; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); DownloadTotals = new DownloadTotalsBlock(); @@ -23412,11 +23596,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ViewerStatsPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -23458,7 +23641,7 @@ public override byte[] ToBytes() DownloadTotals.ToBytes(bytes, ref i); for (int j = 0; j < 2; j++) { NetStats[j].ToBytes(bytes, ref i); } FailStats.ToBytes(bytes, ref i); - bytes[i++] = (byte)MiscStats.Length; + Utils.ByteToBytes((byte)MiscStats.Length, bytes, ref i); for (int j = 0; j < MiscStats.Length; j++) { MiscStats[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -23634,6 +23817,8 @@ public override int Length public AgentDataBlock AgentData; public DataBlock Data; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ScriptAnswerYesPacket() { HasVariableBlocks = false; @@ -23642,6 +23827,7 @@ public ScriptAnswerYesPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 132; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); Data = new DataBlock(); } @@ -23666,11 +23852,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ScriptAnswerYesPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -23782,24 +23967,24 @@ public override void FromBytes(byte[] bytes, ref int i) int length; try { - ReportType = (byte)bytes[i++]; - Category = (byte)bytes[i++]; + ReportType = Utils.BytesToByte(bytes, ref i); + Category = Utils.BytesToByte(bytes, ref i); Position.FromBytes(bytes, i); i += 12; - CheckFlags = (byte)bytes[i++]; + CheckFlags = Utils.BytesToByte(bytes, ref i); ScreenshotID.FromBytes(bytes, i); i += 16; ObjectID.FromBytes(bytes, i); i += 16; AbuserID.FromBytes(bytes, i); i += 16; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); AbuseRegionName = new byte[length]; Buffer.BlockCopy(bytes, i, AbuseRegionName, 0, length); i += length; AbuseRegionID.FromBytes(bytes, i); i += 16; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Summary = new byte[length]; Buffer.BlockCopy(bytes, i, Summary, 0, length); i += length; - length = (bytes[i++] + (bytes[i++] << 8)); + length = Utils.BytesToUInt16(bytes, i); i+=2; Details = new byte[length]; Buffer.BlockCopy(bytes, i, Details, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); VersionString = new byte[length]; Buffer.BlockCopy(bytes, i, VersionString, 0, length); i += length; } @@ -23811,22 +23996,21 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = ReportType; - bytes[i++] = Category; + Utils.ByteToBytes( ReportType, bytes, ref i); + Utils.ByteToBytes( Category, bytes, ref i); Position.ToBytes(bytes, i); i += 12; - bytes[i++] = CheckFlags; + Utils.ByteToBytes( CheckFlags, bytes, ref i); ScreenshotID.ToBytes(bytes, i); i += 16; ObjectID.ToBytes(bytes, i); i += 16; AbuserID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)AbuseRegionName.Length; + Utils.ByteToBytes((byte)AbuseRegionName.Length, bytes, ref i); Buffer.BlockCopy(AbuseRegionName, 0, bytes, i, AbuseRegionName.Length); i += AbuseRegionName.Length; AbuseRegionID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)Summary.Length; + Utils.ByteToBytes((byte)Summary.Length, bytes, ref i); Buffer.BlockCopy(Summary, 0, bytes, i, Summary.Length); i += Summary.Length; - bytes[i++] = (byte)(Details.Length % 256); - bytes[i++] = (byte)((Details.Length >> 8) % 256); + Utils.UInt16ToBytes((ushort)Details.Length, bytes, i); i += 2; Buffer.BlockCopy(Details, 0, bytes, i, Details.Length); i += Details.Length; - bytes[i++] = (byte)VersionString.Length; + Utils.ByteToBytes((byte)VersionString.Length, bytes, ref i); Buffer.BlockCopy(VersionString, 0, bytes, i, VersionString.Length); i += VersionString.Length; } @@ -23845,6 +24029,8 @@ public override int Length public AgentDataBlock AgentData; public ReportDataBlock ReportData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public UserReportPacket() { HasVariableBlocks = false; @@ -23853,6 +24039,7 @@ public UserReportPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 133; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); ReportData = new ReportDataBlock(); @@ -23878,11 +24065,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public UserReportPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -23939,7 +24125,7 @@ public override void FromBytes(byte[] bytes, ref int i) int length; try { - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Message = new byte[length]; Buffer.BlockCopy(bytes, i, Message, 0, length); i += length; } @@ -23951,7 +24137,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = (byte)Message.Length; + Utils.ByteToBytes((byte)Message.Length, bytes, ref i); Buffer.BlockCopy(Message, 0, bytes, i, Message.Length); i += Message.Length; } @@ -23985,10 +24171,10 @@ public override void FromBytes(byte[] bytes, ref int i) int length; try { - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Message = new byte[length]; Buffer.BlockCopy(bytes, i, Message, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); ExtraParams = new byte[length]; Buffer.BlockCopy(bytes, i, ExtraParams, 0, length); i += length; } @@ -24000,9 +24186,9 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = (byte)Message.Length; + Utils.ByteToBytes((byte)Message.Length, bytes, ref i); Buffer.BlockCopy(Message, 0, bytes, i, Message.Length); i += Message.Length; - bytes[i++] = (byte)ExtraParams.Length; + Utils.ByteToBytes((byte)ExtraParams.Length, bytes, ref i); Buffer.BlockCopy(ExtraParams, 0, bytes, i, ExtraParams.Length); i += ExtraParams.Length; } @@ -24030,6 +24216,7 @@ public AlertMessagePacket() Header.Frequency = PacketFrequency.Low; Header.ID = 134; Header.Reliable = true; + NeedValidateIDs = false; AlertData = new AlertDataBlock(); AlertInfo = null; } @@ -24062,11 +24249,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public AlertMessagePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AlertData.FromBytes(bytes, ref i); @@ -24092,7 +24278,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AlertData.ToBytes(bytes, ref i); - bytes[i++] = (byte)AlertInfo.Length; + Utils.ByteToBytes((byte)AlertInfo.Length, bytes, ref i); for (int j = 0; j < AlertInfo.Length; j++) { AlertInfo[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -24228,8 +24414,8 @@ public override void FromBytes(byte[] bytes, ref int i) int length; try { - Modal = (bytes[i++] != 0) ? (bool)true : (bool)false; - length = bytes[i++]; + Modal = (Utils.BytesToByte(bytes, ref i) != 0); + length = Utils.BytesToByte(bytes, ref i); Message = new byte[length]; Buffer.BlockCopy(bytes, i, Message, 0, length); i += length; } @@ -24241,8 +24427,8 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = (byte)((Modal) ? 1 : 0); - bytes[i++] = (byte)Message.Length; + Utils.ByteToBytes((byte)((Modal) ? 1 : 0), bytes, ref i); + Utils.ByteToBytes((byte)Message.Length, bytes, ref i); Buffer.BlockCopy(Message, 0, bytes, i, Message.Length); i += Message.Length; } @@ -24269,6 +24455,7 @@ public AgentAlertMessagePacket() Header.Frequency = PacketFrequency.Low; Header.ID = 135; Header.Reliable = true; + NeedValidateIDs = false; AgentData = new AgentDataBlock(); AlertData = new AlertDataBlock(); } @@ -24293,11 +24480,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public AgentAlertMessagePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -24359,7 +24545,7 @@ public override void FromBytes(byte[] bytes, ref int i) Perp.FromBytes(bytes, i); i += 16; Time = Utils.BytesToUIntSafepos(bytes, i); i += 4; Mag = Utils.BytesToFloatSafepos(bytes, i); i += 4; - Type = (byte)bytes[i++]; + Type = Utils.BytesToByte(bytes, ref i); } catch (Exception) { @@ -24373,7 +24559,7 @@ public override void ToBytes(byte[] bytes, ref int i) Perp.ToBytes(bytes, i); i += 16; Utils.UIntToBytesSafepos(Time, bytes, i); i += 4; Utils.FloatToBytesSafepos(Mag, bytes, i); i += 4; - bytes[i++] = Type; + Utils.ByteToBytes( Type, bytes, ref i); } } @@ -24398,6 +24584,7 @@ public MeanCollisionAlertPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 136; Header.Reliable = true; + NeedValidateIDs = false; Header.Zerocoded = true; MeanCollision = null; } @@ -24429,11 +24616,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public MeanCollisionAlertPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; int count = (int)bytes[i++]; @@ -24456,7 +24642,7 @@ public override byte[] ToBytes() byte[] bytes = new byte[length]; int i = 0; Header.ToBytes(bytes, ref i); - bytes[i++] = (byte)MeanCollision.Length; + Utils.ByteToBytes((byte)MeanCollision.Length, bytes, ref i); for (int j = 0; j < MeanCollision.Length; j++) { MeanCollision[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -24549,7 +24735,7 @@ public override void FromBytes(byte[] bytes, ref int i) { try { - Data = (bytes[i++] != 0) ? (bool)true : (bool)false; + Data = (Utils.BytesToByte(bytes, ref i) != 0); } catch (Exception) { @@ -24559,7 +24745,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = (byte)((Data) ? 1 : 0); + Utils.ByteToBytes((byte)((Data) ? 1 : 0), bytes, ref i); } } @@ -24583,6 +24769,7 @@ public ViewerFrozenMessagePacket() Header.Frequency = PacketFrequency.Low; Header.ID = 137; Header.Reliable = true; + NeedValidateIDs = false; FrozenData = new FrozenDataBlock(); } @@ -24605,11 +24792,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ViewerFrozenMessagePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; FrozenData.FromBytes(bytes, ref i); @@ -24694,6 +24880,7 @@ public HealthMessagePacket() Header.Frequency = PacketFrequency.Low; Header.ID = 138; Header.Reliable = true; + NeedValidateIDs = false; Header.Zerocoded = true; HealthData = new HealthDataBlock(); } @@ -24717,11 +24904,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public HealthMessagePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; HealthData.FromBytes(bytes, ref i); @@ -24783,16 +24969,16 @@ public override void FromBytes(byte[] bytes, ref int i) int length; try { - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); FromName = new byte[length]; Buffer.BlockCopy(bytes, i, FromName, 0, length); i += length; SourceID.FromBytes(bytes, i); i += 16; OwnerID.FromBytes(bytes, i); i += 16; - SourceType = (byte)bytes[i++]; - ChatType = (byte)bytes[i++]; - Audible = (byte)bytes[i++]; + SourceType = Utils.BytesToByte(bytes, ref i); + ChatType = Utils.BytesToByte(bytes, ref i); + Audible = Utils.BytesToByte(bytes, ref i); Position.FromBytes(bytes, i); i += 12; - length = (bytes[i++] + (bytes[i++] << 8)); + length = Utils.BytesToUInt16(bytes, i); i+=2; Message = new byte[length]; Buffer.BlockCopy(bytes, i, Message, 0, length); i += length; } @@ -24804,16 +24990,15 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = (byte)FromName.Length; + Utils.ByteToBytes((byte)FromName.Length, bytes, ref i); Buffer.BlockCopy(FromName, 0, bytes, i, FromName.Length); i += FromName.Length; SourceID.ToBytes(bytes, i); i += 16; OwnerID.ToBytes(bytes, i); i += 16; - bytes[i++] = SourceType; - bytes[i++] = ChatType; - bytes[i++] = Audible; + Utils.ByteToBytes( SourceType, bytes, ref i); + Utils.ByteToBytes( ChatType, bytes, ref i); + Utils.ByteToBytes( Audible, bytes, ref i); Position.ToBytes(bytes, i); i += 12; - bytes[i++] = (byte)(Message.Length % 256); - bytes[i++] = (byte)((Message.Length >> 8) % 256); + Utils.UInt16ToBytes((ushort)Message.Length, bytes, i); i += 2; Buffer.BlockCopy(Message, 0, bytes, i, Message.Length); i += Message.Length; } @@ -24838,6 +25023,7 @@ public ChatFromSimulatorPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 139; Header.Reliable = true; + NeedValidateIDs = false; ChatData = new ChatDataBlock(); } @@ -24860,11 +25046,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ChatFromSimulatorPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; ChatData.FromBytes(bytes, ref i); @@ -25083,6 +25268,7 @@ public SimStatsPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 140; Header.Reliable = true; + NeedValidateIDs = false; Region = new RegionBlock(); Stat = null; PidStat = new PidStatBlock(); @@ -25127,11 +25313,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public SimStatsPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; Region.FromBytes(bytes, ref i); @@ -25170,10 +25355,10 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); Region.ToBytes(bytes, ref i); - bytes[i++] = (byte)Stat.Length; + Utils.ByteToBytes((byte)Stat.Length, bytes, ref i); for (int j = 0; j < Stat.Length; j++) { Stat[j].ToBytes(bytes, ref i); } PidStat.ToBytes(bytes, ref i); - bytes[i++] = (byte)RegionInfo.Length; + Utils.ByteToBytes((byte)RegionInfo.Length, bytes, ref i); for (int j = 0; j < RegionInfo.Length; j++) { RegionInfo[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -25240,6 +25425,8 @@ public override int Length } public AgentDataBlock AgentData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public RequestRegionInfoPacket() { HasVariableBlocks = false; @@ -25248,6 +25435,7 @@ public RequestRegionInfoPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 141; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); } @@ -25270,11 +25458,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public RequestRegionInfoPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -25384,14 +25571,14 @@ public override void FromBytes(byte[] bytes, ref int i) int length; try { - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); SimName = new byte[length]; Buffer.BlockCopy(bytes, i, SimName, 0, length); i += length; EstateID = Utils.BytesToUIntSafepos(bytes, i); i += 4; ParentEstateID = Utils.BytesToUIntSafepos(bytes, i); i += 4; RegionFlags = Utils.BytesToUIntSafepos(bytes, i); i += 4; - SimAccess = (byte)bytes[i++]; - MaxAgents = (byte)bytes[i++]; + SimAccess = Utils.BytesToByte(bytes, ref i); + MaxAgents = Utils.BytesToByte(bytes, ref i); BillableFactor = Utils.BytesToFloatSafepos(bytes, i); i += 4; ObjectBonusFactor = Utils.BytesToFloatSafepos(bytes, i); i += 4; WaterHeight = Utils.BytesToFloatSafepos(bytes, i); i += 4; @@ -25400,7 +25587,7 @@ public override void FromBytes(byte[] bytes, ref int i) PricePerMeter = Utils.BytesToIntSafepos(bytes, i); i += 4; RedirectGridX = Utils.BytesToIntSafepos(bytes, i); i += 4; RedirectGridY = Utils.BytesToIntSafepos(bytes, i); i += 4; - UseEstateSun = (bytes[i++] != 0) ? (bool)true : (bool)false; + UseEstateSun = (Utils.BytesToByte(bytes, ref i) != 0); SunHour = Utils.BytesToFloatSafepos(bytes, i); i += 4; } catch (Exception) @@ -25411,13 +25598,13 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = (byte)SimName.Length; + Utils.ByteToBytes((byte)SimName.Length, bytes, ref i); Buffer.BlockCopy(SimName, 0, bytes, i, SimName.Length); i += SimName.Length; Utils.UIntToBytesSafepos(EstateID, bytes, i); i += 4; Utils.UIntToBytesSafepos(ParentEstateID, bytes, i); i += 4; Utils.UIntToBytesSafepos(RegionFlags, bytes, i); i += 4; - bytes[i++] = SimAccess; - bytes[i++] = MaxAgents; + Utils.ByteToBytes( SimAccess, bytes, ref i); + Utils.ByteToBytes( MaxAgents, bytes, ref i); Utils.FloatToBytesSafepos(BillableFactor, bytes, i); i += 4; Utils.FloatToBytesSafepos(ObjectBonusFactor, bytes, i); i += 4; Utils.FloatToBytesSafepos(WaterHeight, bytes, i); i += 4; @@ -25426,7 +25613,7 @@ public override void ToBytes(byte[] bytes, ref int i) Utils.IntToBytesSafepos(PricePerMeter, bytes, i); i += 4; Utils.IntToBytesSafepos(RedirectGridX, bytes, i); i += 4; Utils.IntToBytesSafepos(RedirectGridY, bytes, i); i += 4; - bytes[i++] = (byte)((UseEstateSun) ? 1 : 0); + Utils.ByteToBytes((byte)((UseEstateSun) ? 1 : 0), bytes, ref i); Utils.FloatToBytesSafepos(SunHour, bytes, i); i += 4; } @@ -25463,10 +25650,10 @@ public override void FromBytes(byte[] bytes, ref int i) int length; try { - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); ProductSKU = new byte[length]; Buffer.BlockCopy(bytes, i, ProductSKU, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); ProductName = new byte[length]; Buffer.BlockCopy(bytes, i, ProductName, 0, length); i += length; MaxAgents32 = Utils.BytesToUIntSafepos(bytes, i); i += 4; @@ -25481,9 +25668,9 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = (byte)ProductSKU.Length; + Utils.ByteToBytes((byte)ProductSKU.Length, bytes, ref i); Buffer.BlockCopy(ProductSKU, 0, bytes, i, ProductSKU.Length); i += ProductSKU.Length; - bytes[i++] = (byte)ProductName.Length; + Utils.ByteToBytes((byte)ProductName.Length, bytes, ref i); Buffer.BlockCopy(ProductName, 0, bytes, i, ProductName.Length); i += ProductName.Length; Utils.UIntToBytesSafepos(MaxAgents32, bytes, i); i += 4; Utils.UIntToBytesSafepos(HardMaxAgents, bytes, i); i += 4; @@ -25548,6 +25735,8 @@ public override int Length public RegionInfo2Block RegionInfo2; public RegionInfo3Block[] RegionInfo3; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public RegionInfoPacket() { HasVariableBlocks = true; @@ -25556,6 +25745,7 @@ public RegionInfoPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 142; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); RegionInfo = new RegionInfoBlock(); @@ -25593,11 +25783,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public RegionInfoPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -25629,7 +25818,7 @@ public override byte[] ToBytes() AgentData.ToBytes(bytes, ref i); RegionInfo.ToBytes(bytes, ref i); RegionInfo2.ToBytes(bytes, ref i); - bytes[i++] = (byte)RegionInfo3.Length; + Utils.ByteToBytes((byte)RegionInfo3.Length, bytes, ref i); for (int j = 0; j < RegionInfo3.Length; j++) { RegionInfo3[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -25779,7 +25968,7 @@ public override void FromBytes(byte[] bytes, ref int i) int length; try { - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); SimName = new byte[length]; Buffer.BlockCopy(bytes, i, SimName, 0, length); i += length; EstateID = Utils.BytesToUIntSafepos(bytes, i); i += 4; @@ -25798,7 +25987,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = (byte)SimName.Length; + Utils.ByteToBytes((byte)SimName.Length, bytes, ref i); Buffer.BlockCopy(SimName, 0, bytes, i, SimName.Length); i += SimName.Length; Utils.UIntToBytesSafepos(EstateID, bytes, i); i += 4; Utils.UIntToBytesSafepos(ParentEstateID, bytes, i); i += 4; @@ -25865,6 +26054,8 @@ public override int Length public RegionInfoBlock RegionInfo; public RegionInfo2Block[] RegionInfo2; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public GodUpdateRegionInfoPacket() { HasVariableBlocks = true; @@ -25873,6 +26064,7 @@ public GodUpdateRegionInfoPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 143; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); RegionInfo = new RegionInfoBlock(); @@ -25908,11 +26100,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public GodUpdateRegionInfoPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -25941,7 +26132,7 @@ public override byte[] ToBytes() Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); RegionInfo.ToBytes(bytes, ref i); - bytes[i++] = (byte)RegionInfo2.Length; + Utils.ByteToBytes((byte)RegionInfo2.Length, bytes, ref i); for (int j = 0; j < RegionInfo2.Length; j++) { RegionInfo2[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -26065,12 +26256,12 @@ public override void FromBytes(byte[] bytes, ref int i) try { RegionFlags = Utils.BytesToUIntSafepos(bytes, i); i += 4; - SimAccess = (byte)bytes[i++]; - length = bytes[i++]; + SimAccess = Utils.BytesToByte(bytes, ref i); + length = Utils.BytesToByte(bytes, ref i); SimName = new byte[length]; Buffer.BlockCopy(bytes, i, SimName, 0, length); i += length; SimOwner.FromBytes(bytes, i); i += 16; - IsEstateManager = (bytes[i++] != 0) ? (bool)true : (bool)false; + IsEstateManager = (Utils.BytesToByte(bytes, ref i) != 0); WaterHeight = Utils.BytesToFloatSafepos(bytes, i); i += 4; BillableFactor = Utils.BytesToFloatSafepos(bytes, i); i += 4; CacheID.FromBytes(bytes, i); i += 16; @@ -26100,11 +26291,11 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { Utils.UIntToBytesSafepos(RegionFlags, bytes, i); i += 4; - bytes[i++] = SimAccess; - bytes[i++] = (byte)SimName.Length; + Utils.ByteToBytes( SimAccess, bytes, ref i); + Utils.ByteToBytes((byte)SimName.Length, bytes, ref i); Buffer.BlockCopy(SimName, 0, bytes, i, SimName.Length); i += SimName.Length; SimOwner.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)((IsEstateManager) ? 1 : 0); + Utils.ByteToBytes((byte)((IsEstateManager) ? 1 : 0), bytes, ref i); Utils.FloatToBytesSafepos(WaterHeight, bytes, i); i += 4; Utils.FloatToBytesSafepos(BillableFactor, bytes, i); i += 4; CacheID.ToBytes(bytes, i); i += 16; @@ -26200,13 +26391,13 @@ public override void FromBytes(byte[] bytes, ref int i) { CPUClassID = Utils.BytesToIntSafepos(bytes, i); i += 4; CPURatio = Utils.BytesToIntSafepos(bytes, i); i += 4; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); ColoName = new byte[length]; Buffer.BlockCopy(bytes, i, ColoName, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); ProductSKU = new byte[length]; Buffer.BlockCopy(bytes, i, ProductSKU, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); ProductName = new byte[length]; Buffer.BlockCopy(bytes, i, ProductName, 0, length); i += length; } @@ -26220,11 +26411,11 @@ public override void ToBytes(byte[] bytes, ref int i) { Utils.IntToBytesSafepos(CPUClassID, bytes, i); i += 4; Utils.IntToBytesSafepos(CPURatio, bytes, i); i += 4; - bytes[i++] = (byte)ColoName.Length; + Utils.ByteToBytes((byte)ColoName.Length, bytes, ref i); Buffer.BlockCopy(ColoName, 0, bytes, i, ColoName.Length); i += ColoName.Length; - bytes[i++] = (byte)ProductSKU.Length; + Utils.ByteToBytes((byte)ProductSKU.Length, bytes, ref i); Buffer.BlockCopy(ProductSKU, 0, bytes, i, ProductSKU.Length); i += ProductSKU.Length; - bytes[i++] = (byte)ProductName.Length; + Utils.ByteToBytes((byte)ProductName.Length, bytes, ref i); Buffer.BlockCopy(ProductName, 0, bytes, i, ProductName.Length); i += ProductName.Length; } @@ -26297,6 +26488,7 @@ public RegionHandshakePacket() Header.Frequency = PacketFrequency.Low; Header.ID = 148; Header.Reliable = true; + NeedValidateIDs = false; Header.Zerocoded = true; RegionInfo = new RegionInfoBlock(); RegionInfo2 = new RegionInfo2Block(); @@ -26334,11 +26526,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public RegionHandshakePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; RegionInfo.FromBytes(bytes, ref i); @@ -26370,7 +26561,7 @@ public override byte[] ToBytes() RegionInfo.ToBytes(bytes, ref i); RegionInfo2.ToBytes(bytes, ref i); RegionInfo3.ToBytes(bytes, ref i); - bytes[i++] = (byte)RegionInfo4.Length; + Utils.ByteToBytes((byte)RegionInfo4.Length, bytes, ref i); for (int j = 0; j < RegionInfo4.Length; j++) { RegionInfo4[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -26538,6 +26729,8 @@ public override int Length public AgentDataBlock AgentData; public RegionInfoBlock RegionInfo; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public RegionHandshakeReplyPacket() { HasVariableBlocks = false; @@ -26546,6 +26739,7 @@ public RegionHandshakeReplyPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 149; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); RegionInfo = new RegionInfoBlock(); @@ -26571,11 +26765,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public RegionHandshakeReplyPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -26678,6 +26871,7 @@ public SimulatorViewerTimeMessagePacket() Header.Frequency = PacketFrequency.Low; Header.ID = 150; Header.Reliable = true; + NeedValidateIDs = false; TimeInfo = new TimeInfoBlock(); } @@ -26700,11 +26894,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public SimulatorViewerTimeMessagePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; TimeInfo.FromBytes(bytes, ref i); @@ -26771,8 +26964,7 @@ public override void ToBytes(byte[] bytes, ref int i) { Utils.UInt64ToBytesSafepos(Handle, bytes, i); i += 8; Utils.UIntToBytesSafepos(IP, bytes, i); i += 4; - bytes[i++] = (byte)((Port >> 8) % 256); - bytes[i++] = (byte)(Port % 256); + Utils.UInt16ToBytesBig(Port, bytes, i); i += 2; } } @@ -26796,6 +26988,7 @@ public EnableSimulatorPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 151; Header.Reliable = true; + NeedValidateIDs = false; SimulatorInfo = new SimulatorInfoBlock(); } @@ -26818,11 +27011,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public EnableSimulatorPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; SimulatorInfo.FromBytes(bytes, ref i); @@ -26867,6 +27059,7 @@ public DisableSimulatorPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 152; Header.Reliable = true; + NeedValidateIDs = false; } public DisableSimulatorPacket(byte[] bytes, ref int i) : this() @@ -26887,11 +27080,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public DisableSimulatorPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; } @@ -26950,7 +27142,7 @@ public override void FromBytes(byte[] bytes, ref int i) ChannelType = Utils.BytesToIntSafepos(bytes, i); i += 4; SourceType = Utils.BytesToIntSafepos(bytes, i); i += 4; Priority = Utils.BytesToFloatSafepos(bytes, i); i += 4; - length = (bytes[i++] + (bytes[i++] << 8)); + length = Utils.BytesToUInt16(bytes, i); i+=2; Params = new byte[length]; Buffer.BlockCopy(bytes, i, Params, 0, length); i += length; } @@ -26966,8 +27158,7 @@ public override void ToBytes(byte[] bytes, ref int i) Utils.IntToBytesSafepos(ChannelType, bytes, i); i += 4; Utils.IntToBytesSafepos(SourceType, bytes, i); i += 4; Utils.FloatToBytesSafepos(Priority, bytes, i); i += 4; - bytes[i++] = (byte)(Params.Length % 256); - bytes[i++] = (byte)((Params.Length >> 8) % 256); + Utils.UInt16ToBytes((ushort)Params.Length, bytes, i); i += 2; Buffer.BlockCopy(Params, 0, bytes, i, Params.Length); i += Params.Length; } @@ -26992,6 +27183,7 @@ public TransferRequestPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 153; Header.Reliable = true; + NeedValidateIDs = false; Header.Zerocoded = true; TransferInfo = new TransferInfoBlock(); } @@ -27015,11 +27207,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public TransferRequestPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; TransferInfo.FromBytes(bytes, ref i); @@ -27083,7 +27274,7 @@ public override void FromBytes(byte[] bytes, ref int i) TargetType = Utils.BytesToIntSafepos(bytes, i); i += 4; Status = Utils.BytesToIntSafepos(bytes, i); i += 4; Size = Utils.BytesToIntSafepos(bytes, i); i += 4; - length = (bytes[i++] + (bytes[i++] << 8)); + length = Utils.BytesToUInt16(bytes, i); i+=2; Params = new byte[length]; Buffer.BlockCopy(bytes, i, Params, 0, length); i += length; } @@ -27100,8 +27291,7 @@ public override void ToBytes(byte[] bytes, ref int i) Utils.IntToBytesSafepos(TargetType, bytes, i); i += 4; Utils.IntToBytesSafepos(Status, bytes, i); i += 4; Utils.IntToBytesSafepos(Size, bytes, i); i += 4; - bytes[i++] = (byte)(Params.Length % 256); - bytes[i++] = (byte)((Params.Length >> 8) % 256); + Utils.UInt16ToBytes((ushort)Params.Length, bytes, i); i += 2; Buffer.BlockCopy(Params, 0, bytes, i, Params.Length); i += Params.Length; } @@ -27126,6 +27316,7 @@ public TransferInfoPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 154; Header.Reliable = true; + NeedValidateIDs = false; Header.Zerocoded = true; TransferInfo = new TransferInfoBlock(); } @@ -27149,11 +27340,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public TransferInfoPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; TransferInfo.FromBytes(bytes, ref i); @@ -27241,6 +27431,7 @@ public TransferAbortPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 155; Header.Reliable = true; + NeedValidateIDs = false; Header.Zerocoded = true; TransferInfo = new TransferInfoBlock(); } @@ -27264,11 +27455,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public TransferAbortPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; TransferInfo.FromBytes(bytes, ref i); @@ -27329,12 +27519,12 @@ public override void FromBytes(byte[] bytes, ref int i) try { ID = Utils.BytesToUInt64Safepos(bytes, i); i += 8; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Filename = new byte[length]; Buffer.BlockCopy(bytes, i, Filename, 0, length); i += length; - FilePath = (byte)bytes[i++]; - DeleteOnCompletion = (bytes[i++] != 0) ? (bool)true : (bool)false; - UseBigPackets = (bytes[i++] != 0) ? (bool)true : (bool)false; + FilePath = Utils.BytesToByte(bytes, ref i); + DeleteOnCompletion = (Utils.BytesToByte(bytes, ref i) != 0); + UseBigPackets = (Utils.BytesToByte(bytes, ref i) != 0); VFileID.FromBytes(bytes, i); i += 16; VFileType = Utils.BytesToInt16(bytes, i); i += 2; } @@ -27347,11 +27537,11 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { Utils.UInt64ToBytesSafepos(ID, bytes, i); i += 8; - bytes[i++] = (byte)Filename.Length; + Utils.ByteToBytes((byte)Filename.Length, bytes, ref i); Buffer.BlockCopy(Filename, 0, bytes, i, Filename.Length); i += Filename.Length; - bytes[i++] = FilePath; - bytes[i++] = (byte)((DeleteOnCompletion) ? 1 : 0); - bytes[i++] = (byte)((UseBigPackets) ? 1 : 0); + Utils.ByteToBytes( FilePath, bytes, ref i); + Utils.ByteToBytes((byte)((DeleteOnCompletion) ? 1 : 0), bytes, ref i); + Utils.ByteToBytes((byte)((UseBigPackets) ? 1 : 0), bytes, ref i); VFileID.ToBytes(bytes, i); i += 16; Utils.Int16ToBytes(VFileType, bytes, i); i += 2; } @@ -27377,6 +27567,7 @@ public RequestXferPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 156; Header.Reliable = true; + NeedValidateIDs = false; Header.Zerocoded = true; XferID = new XferIDBlock(); } @@ -27400,11 +27591,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public RequestXferPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; XferID.FromBytes(bytes, ref i); @@ -27492,6 +27682,7 @@ public AbortXferPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 157; Header.Reliable = true; + NeedValidateIDs = false; XferID = new XferIDBlock(); } @@ -27514,11 +27705,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public AbortXferPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; XferID.FromBytes(bytes, ref i); @@ -27571,7 +27761,7 @@ public override void FromBytes(byte[] bytes, ref int i) try { ID.FromBytes(bytes, i); i += 16; - IsTrial = (bytes[i++] != 0) ? (bool)true : (bool)false; + IsTrial = (Utils.BytesToByte(bytes, ref i) != 0); } catch (Exception) { @@ -27582,7 +27772,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { ID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)((IsTrial) ? 1 : 0); + Utils.ByteToBytes((byte)((IsTrial) ? 1 : 0), bytes, ref i); } } @@ -27613,7 +27803,7 @@ public override void FromBytes(byte[] bytes, ref int i) int length; try { - length = (bytes[i++] + (bytes[i++] << 8)); + length = Utils.BytesToUInt16(bytes, i); i+=2; TextureEntry = new byte[length]; Buffer.BlockCopy(bytes, i, TextureEntry, 0, length); i += length; } @@ -27625,8 +27815,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = (byte)(TextureEntry.Length % 256); - bytes[i++] = (byte)((TextureEntry.Length >> 8) % 256); + Utils.UInt16ToBytes((ushort)TextureEntry.Length, bytes, i); i += 2; Buffer.BlockCopy(TextureEntry, 0, bytes, i, TextureEntry.Length); i += TextureEntry.Length; } @@ -27655,7 +27844,7 @@ public override void FromBytes(byte[] bytes, ref int i) { try { - ParamValue = (byte)bytes[i++]; + ParamValue = Utils.BytesToByte(bytes, ref i); } catch (Exception) { @@ -27665,7 +27854,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = ParamValue; + Utils.ByteToBytes( ParamValue, bytes, ref i); } } @@ -27695,7 +27884,7 @@ public override void FromBytes(byte[] bytes, ref int i) { try { - AppearanceVersion = (byte)bytes[i++]; + AppearanceVersion = Utils.BytesToByte(bytes, ref i); CofVersion = Utils.BytesToIntSafepos(bytes, i); i += 4; Flags = Utils.BytesToUIntSafepos(bytes, i); i += 4; } @@ -27707,7 +27896,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = AppearanceVersion; + Utils.ByteToBytes( AppearanceVersion, bytes, ref i); Utils.IntToBytesSafepos(CofVersion, bytes, i); i += 4; Utils.UIntToBytesSafepos(Flags, bytes, i); i += 4; } @@ -27782,6 +27971,7 @@ public AvatarAppearancePacket() Header.Frequency = PacketFrequency.Low; Header.ID = 158; Header.Reliable = true; + NeedValidateIDs = false; Header.Zerocoded = true; Sender = new SenderBlock(); ObjectData = new ObjectDataBlock(); @@ -27837,11 +28027,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public AvatarAppearancePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; Sender.FromBytes(bytes, ref i); @@ -27892,11 +28081,11 @@ public override byte[] ToBytes() Header.ToBytes(bytes, ref i); Sender.ToBytes(bytes, ref i); ObjectData.ToBytes(bytes, ref i); - bytes[i++] = (byte)VisualParam.Length; + Utils.ByteToBytes((byte)VisualParam.Length, bytes, ref i); for (int j = 0; j < VisualParam.Length; j++) { VisualParam[j].ToBytes(bytes, ref i); } - bytes[i++] = (byte)AppearanceData.Length; + Utils.ByteToBytes((byte)AppearanceData.Length, bytes, ref i); for (int j = 0; j < AppearanceData.Length; j++) { AppearanceData[j].ToBytes(bytes, ref i); } - bytes[i++] = (byte)AppearanceHover.Length; + Utils.ByteToBytes((byte)AppearanceHover.Length, bytes, ref i); for (int j = 0; j < AppearanceHover.Length; j++) { AppearanceHover[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -28111,6 +28300,7 @@ public SetFollowCamPropertiesPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 159; Header.Reliable = true; + NeedValidateIDs = false; ObjectData = new ObjectDataBlock(); CameraProperty = null; } @@ -28143,11 +28333,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public SetFollowCamPropertiesPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; ObjectData.FromBytes(bytes, ref i); @@ -28173,7 +28362,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); ObjectData.ToBytes(bytes, ref i); - bytes[i++] = (byte)CameraProperty.Length; + Utils.ByteToBytes((byte)CameraProperty.Length, bytes, ref i); for (int j = 0; j < CameraProperty.Length; j++) { CameraProperty[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -28302,6 +28491,7 @@ public ClearFollowCamPropertiesPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 160; Header.Reliable = true; + NeedValidateIDs = false; ObjectData = new ObjectDataBlock(); } @@ -28324,11 +28514,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ClearFollowCamPropertiesPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; ObjectData.FromBytes(bytes, ref i); @@ -28413,6 +28602,7 @@ public RequestPayPricePacket() Header.Frequency = PacketFrequency.Low; Header.ID = 161; Header.Reliable = true; + NeedValidateIDs = false; ObjectData = new ObjectDataBlock(); } @@ -28435,11 +28625,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public RequestPayPricePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; ObjectData.FromBytes(bytes, ref i); @@ -28568,6 +28757,7 @@ public PayPriceReplyPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 162; Header.Reliable = true; + NeedValidateIDs = false; ObjectData = new ObjectDataBlock(); ButtonData = null; } @@ -28600,11 +28790,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public PayPriceReplyPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; ObjectData.FromBytes(bytes, ref i); @@ -28630,7 +28819,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); ObjectData.ToBytes(bytes, ref i); - bytes[i++] = (byte)ButtonData.Length; + Utils.ByteToBytes((byte)ButtonData.Length, bytes, ref i); for (int j = 0; j < ButtonData.Length; j++) { ButtonData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -28738,8 +28927,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { Utils.UIntToBytesSafepos(TargetIP, bytes, i); i += 4; - bytes[i++] = (byte)((TargetPort >> 8) % 256); - bytes[i++] = (byte)(TargetPort % 256); + Utils.UInt16ToBytesBig(TargetPort, bytes, i); i += 2; } } @@ -28774,7 +28962,7 @@ public override void FromBytes(byte[] bytes, ref int i) { AgentID.FromBytes(bytes, i); i += 16; SessionID.FromBytes(bytes, i); i += 16; - length = (bytes[i++] + (bytes[i++] << 8)); + length = Utils.BytesToUInt16(bytes, i); i+=2; Reason = new byte[length]; Buffer.BlockCopy(bytes, i, Reason, 0, length); i += length; } @@ -28788,8 +28976,7 @@ public override void ToBytes(byte[] bytes, ref int i) { AgentID.ToBytes(bytes, i); i += 16; SessionID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)(Reason.Length % 256); - bytes[i++] = (byte)((Reason.Length >> 8) % 256); + Utils.UInt16ToBytes((ushort)Reason.Length, bytes, i); i += 2; Buffer.BlockCopy(Reason, 0, bytes, i, Reason.Length); i += Reason.Length; } @@ -28816,6 +29003,7 @@ public KickUserPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 163; Header.Reliable = true; + NeedValidateIDs = false; TargetBlock = new TargetBlockBlock(); UserInfo = new UserInfoBlock(); } @@ -28840,11 +29028,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public KickUserPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; TargetBlock.FromBytes(bytes, ref i); @@ -28909,7 +29096,7 @@ public override void FromBytes(byte[] bytes, ref int i) GodSessionID.FromBytes(bytes, i); i += 16; AgentID.FromBytes(bytes, i); i += 16; KickFlags = Utils.BytesToUIntSafepos(bytes, i); i += 4; - length = (bytes[i++] + (bytes[i++] << 8)); + length = Utils.BytesToUInt16(bytes, i); i+=2; Reason = new byte[length]; Buffer.BlockCopy(bytes, i, Reason, 0, length); i += length; } @@ -28925,8 +29112,7 @@ public override void ToBytes(byte[] bytes, ref int i) GodSessionID.ToBytes(bytes, i); i += 16; AgentID.ToBytes(bytes, i); i += 16; Utils.UIntToBytesSafepos(KickFlags, bytes, i); i += 4; - bytes[i++] = (byte)(Reason.Length % 256); - bytes[i++] = (byte)((Reason.Length >> 8) % 256); + Utils.UInt16ToBytes((ushort)Reason.Length, bytes, i); i += 2; Buffer.BlockCopy(Reason, 0, bytes, i, Reason.Length); i += Reason.Length; } @@ -28951,6 +29137,7 @@ public GodKickUserPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 165; Header.Reliable = true; + NeedValidateIDs = false; UserInfo = new UserInfoBlock(); } @@ -28973,11 +29160,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public GodKickUserPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; UserInfo.FromBytes(bytes, ref i); @@ -29100,6 +29286,8 @@ public override int Length public AgentDataBlock AgentData; public DataBlock Data; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public EjectUserPacket() { HasVariableBlocks = false; @@ -29108,6 +29296,7 @@ public EjectUserPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 167; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); Data = new DataBlock(); } @@ -29132,11 +29321,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public EjectUserPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -29262,6 +29450,8 @@ public override int Length public AgentDataBlock AgentData; public DataBlock Data; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public FreezeUserPacket() { HasVariableBlocks = false; @@ -29270,6 +29460,7 @@ public FreezeUserPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 168; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); Data = new DataBlock(); } @@ -29294,11 +29485,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public FreezeUserPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -29384,6 +29574,8 @@ public override int Length } public AgentDataBlock AgentData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public AvatarPropertiesRequestPacket() { HasVariableBlocks = false; @@ -29392,6 +29584,7 @@ public AvatarPropertiesRequestPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 169; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); } @@ -29414,11 +29607,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public AvatarPropertiesRequestPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -29528,19 +29720,19 @@ public override void FromBytes(byte[] bytes, ref int i) ImageID.FromBytes(bytes, i); i += 16; FLImageID.FromBytes(bytes, i); i += 16; PartnerID.FromBytes(bytes, i); i += 16; - length = (bytes[i++] + (bytes[i++] << 8)); + length = Utils.BytesToUInt16(bytes, i); i+=2; AboutText = new byte[length]; Buffer.BlockCopy(bytes, i, AboutText, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); FLAboutText = new byte[length]; Buffer.BlockCopy(bytes, i, FLAboutText, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); BornOn = new byte[length]; Buffer.BlockCopy(bytes, i, BornOn, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); ProfileURL = new byte[length]; Buffer.BlockCopy(bytes, i, ProfileURL, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); CharterMember = new byte[length]; Buffer.BlockCopy(bytes, i, CharterMember, 0, length); i += length; Flags = Utils.BytesToUIntSafepos(bytes, i); i += 4; @@ -29556,16 +29748,15 @@ public override void ToBytes(byte[] bytes, ref int i) ImageID.ToBytes(bytes, i); i += 16; FLImageID.ToBytes(bytes, i); i += 16; PartnerID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)(AboutText.Length % 256); - bytes[i++] = (byte)((AboutText.Length >> 8) % 256); + Utils.UInt16ToBytes((ushort)AboutText.Length, bytes, i); i += 2; Buffer.BlockCopy(AboutText, 0, bytes, i, AboutText.Length); i += AboutText.Length; - bytes[i++] = (byte)FLAboutText.Length; + Utils.ByteToBytes((byte)FLAboutText.Length, bytes, ref i); Buffer.BlockCopy(FLAboutText, 0, bytes, i, FLAboutText.Length); i += FLAboutText.Length; - bytes[i++] = (byte)BornOn.Length; + Utils.ByteToBytes((byte)BornOn.Length, bytes, ref i); Buffer.BlockCopy(BornOn, 0, bytes, i, BornOn.Length); i += BornOn.Length; - bytes[i++] = (byte)ProfileURL.Length; + Utils.ByteToBytes((byte)ProfileURL.Length, bytes, ref i); Buffer.BlockCopy(ProfileURL, 0, bytes, i, ProfileURL.Length); i += ProfileURL.Length; - bytes[i++] = (byte)CharterMember.Length; + Utils.ByteToBytes((byte)CharterMember.Length, bytes, ref i); Buffer.BlockCopy(CharterMember, 0, bytes, i, CharterMember.Length); i += CharterMember.Length; Utils.UIntToBytesSafepos(Flags, bytes, i); i += 4; } @@ -29593,6 +29784,7 @@ public AvatarPropertiesReplyPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 171; Header.Reliable = true; + NeedValidateIDs = false; Header.Zerocoded = true; AgentData = new AgentDataBlock(); PropertiesData = new PropertiesDataBlock(); @@ -29618,11 +29810,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public AvatarPropertiesReplyPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -29727,14 +29918,14 @@ public override void FromBytes(byte[] bytes, ref int i) try { WantToMask = Utils.BytesToUIntSafepos(bytes, i); i += 4; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); WantToText = new byte[length]; Buffer.BlockCopy(bytes, i, WantToText, 0, length); i += length; SkillsMask = Utils.BytesToUIntSafepos(bytes, i); i += 4; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); SkillsText = new byte[length]; Buffer.BlockCopy(bytes, i, SkillsText, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); LanguagesText = new byte[length]; Buffer.BlockCopy(bytes, i, LanguagesText, 0, length); i += length; } @@ -29747,12 +29938,12 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { Utils.UIntToBytesSafepos(WantToMask, bytes, i); i += 4; - bytes[i++] = (byte)WantToText.Length; + Utils.ByteToBytes((byte)WantToText.Length, bytes, ref i); Buffer.BlockCopy(WantToText, 0, bytes, i, WantToText.Length); i += WantToText.Length; Utils.UIntToBytesSafepos(SkillsMask, bytes, i); i += 4; - bytes[i++] = (byte)SkillsText.Length; + Utils.ByteToBytes((byte)SkillsText.Length, bytes, ref i); Buffer.BlockCopy(SkillsText, 0, bytes, i, SkillsText.Length); i += SkillsText.Length; - bytes[i++] = (byte)LanguagesText.Length; + Utils.ByteToBytes((byte)LanguagesText.Length, bytes, ref i); Buffer.BlockCopy(LanguagesText, 0, bytes, i, LanguagesText.Length); i += LanguagesText.Length; } @@ -29779,6 +29970,7 @@ public AvatarInterestsReplyPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 172; Header.Reliable = true; + NeedValidateIDs = false; Header.Zerocoded = true; AgentData = new AgentDataBlock(); PropertiesData = new PropertiesDataBlock(); @@ -29804,11 +29996,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public AvatarInterestsReplyPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -29913,12 +30104,12 @@ public override void FromBytes(byte[] bytes, ref int i) try { GroupPowers = Utils.BytesToUInt64Safepos(bytes, i); i += 8; - AcceptNotices = (bytes[i++] != 0) ? (bool)true : (bool)false; - length = bytes[i++]; + AcceptNotices = (Utils.BytesToByte(bytes, ref i) != 0); + length = Utils.BytesToByte(bytes, ref i); GroupTitle = new byte[length]; Buffer.BlockCopy(bytes, i, GroupTitle, 0, length); i += length; GroupID.FromBytes(bytes, i); i += 16; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); GroupName = new byte[length]; Buffer.BlockCopy(bytes, i, GroupName, 0, length); i += length; GroupInsigniaID.FromBytes(bytes, i); i += 16; @@ -29932,11 +30123,11 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { Utils.UInt64ToBytesSafepos(GroupPowers, bytes, i); i += 8; - bytes[i++] = (byte)((AcceptNotices) ? 1 : 0); - bytes[i++] = (byte)GroupTitle.Length; + Utils.ByteToBytes((byte)((AcceptNotices) ? 1 : 0), bytes, ref i); + Utils.ByteToBytes((byte)GroupTitle.Length, bytes, ref i); Buffer.BlockCopy(GroupTitle, 0, bytes, i, GroupTitle.Length); i += GroupTitle.Length; GroupID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)GroupName.Length; + Utils.ByteToBytes((byte)GroupName.Length, bytes, ref i); Buffer.BlockCopy(GroupName, 0, bytes, i, GroupName.Length); i += GroupName.Length; GroupInsigniaID.ToBytes(bytes, i); i += 16; } @@ -29966,7 +30157,7 @@ public override void FromBytes(byte[] bytes, ref int i) { try { - ListInProfile = (bytes[i++] != 0) ? (bool)true : (bool)false; + ListInProfile = (Utils.BytesToByte(bytes, ref i) != 0); } catch (Exception) { @@ -29976,7 +30167,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = (byte)((ListInProfile) ? 1 : 0); + Utils.ByteToBytes((byte)((ListInProfile) ? 1 : 0), bytes, ref i); } } @@ -30005,6 +30196,7 @@ public AvatarGroupsReplyPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 173; Header.Reliable = true; + NeedValidateIDs = false; Header.Zerocoded = true; AgentData = new AgentDataBlock(); GroupData = null; @@ -30040,11 +30232,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public AvatarGroupsReplyPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -30072,7 +30263,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)GroupData.Length; + Utils.ByteToBytes((byte)GroupData.Length, bytes, ref i); for (int j = 0; j < GroupData.Length; j++) { GroupData[j].ToBytes(bytes, ref i); } NewGroupData.ToBytes(bytes, ref i); if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } @@ -30165,15 +30356,15 @@ public override void FromBytes(byte[] bytes, ref int i) { ImageID.FromBytes(bytes, i); i += 16; FLImageID.FromBytes(bytes, i); i += 16; - length = (bytes[i++] + (bytes[i++] << 8)); + length = Utils.BytesToUInt16(bytes, i); i+=2; AboutText = new byte[length]; Buffer.BlockCopy(bytes, i, AboutText, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); FLAboutText = new byte[length]; Buffer.BlockCopy(bytes, i, FLAboutText, 0, length); i += length; - AllowPublish = (bytes[i++] != 0) ? (bool)true : (bool)false; - MaturePublish = (bytes[i++] != 0) ? (bool)true : (bool)false; - length = bytes[i++]; + AllowPublish = (Utils.BytesToByte(bytes, ref i) != 0); + MaturePublish = (Utils.BytesToByte(bytes, ref i) != 0); + length = Utils.BytesToByte(bytes, ref i); ProfileURL = new byte[length]; Buffer.BlockCopy(bytes, i, ProfileURL, 0, length); i += length; } @@ -30187,14 +30378,13 @@ public override void ToBytes(byte[] bytes, ref int i) { ImageID.ToBytes(bytes, i); i += 16; FLImageID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)(AboutText.Length % 256); - bytes[i++] = (byte)((AboutText.Length >> 8) % 256); + Utils.UInt16ToBytes((ushort)AboutText.Length, bytes, i); i += 2; Buffer.BlockCopy(AboutText, 0, bytes, i, AboutText.Length); i += AboutText.Length; - bytes[i++] = (byte)FLAboutText.Length; + Utils.ByteToBytes((byte)FLAboutText.Length, bytes, ref i); Buffer.BlockCopy(FLAboutText, 0, bytes, i, FLAboutText.Length); i += FLAboutText.Length; - bytes[i++] = (byte)((AllowPublish) ? 1 : 0); - bytes[i++] = (byte)((MaturePublish) ? 1 : 0); - bytes[i++] = (byte)ProfileURL.Length; + Utils.ByteToBytes((byte)((AllowPublish) ? 1 : 0), bytes, ref i); + Utils.ByteToBytes((byte)((MaturePublish) ? 1 : 0), bytes, ref i); + Utils.ByteToBytes((byte)ProfileURL.Length, bytes, ref i); Buffer.BlockCopy(ProfileURL, 0, bytes, i, ProfileURL.Length); i += ProfileURL.Length; } @@ -30213,6 +30403,8 @@ public override int Length public AgentDataBlock AgentData; public PropertiesDataBlock PropertiesData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public AvatarPropertiesUpdatePacket() { HasVariableBlocks = false; @@ -30221,6 +30413,7 @@ public AvatarPropertiesUpdatePacket() Header.Frequency = PacketFrequency.Low; Header.ID = 174; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); PropertiesData = new PropertiesDataBlock(); @@ -30246,11 +30439,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public AvatarPropertiesUpdatePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -30355,14 +30547,14 @@ public override void FromBytes(byte[] bytes, ref int i) try { WantToMask = Utils.BytesToUIntSafepos(bytes, i); i += 4; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); WantToText = new byte[length]; Buffer.BlockCopy(bytes, i, WantToText, 0, length); i += length; SkillsMask = Utils.BytesToUIntSafepos(bytes, i); i += 4; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); SkillsText = new byte[length]; Buffer.BlockCopy(bytes, i, SkillsText, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); LanguagesText = new byte[length]; Buffer.BlockCopy(bytes, i, LanguagesText, 0, length); i += length; } @@ -30375,12 +30567,12 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { Utils.UIntToBytesSafepos(WantToMask, bytes, i); i += 4; - bytes[i++] = (byte)WantToText.Length; + Utils.ByteToBytes((byte)WantToText.Length, bytes, ref i); Buffer.BlockCopy(WantToText, 0, bytes, i, WantToText.Length); i += WantToText.Length; Utils.UIntToBytesSafepos(SkillsMask, bytes, i); i += 4; - bytes[i++] = (byte)SkillsText.Length; + Utils.ByteToBytes((byte)SkillsText.Length, bytes, ref i); Buffer.BlockCopy(SkillsText, 0, bytes, i, SkillsText.Length); i += SkillsText.Length; - bytes[i++] = (byte)LanguagesText.Length; + Utils.ByteToBytes((byte)LanguagesText.Length, bytes, ref i); Buffer.BlockCopy(LanguagesText, 0, bytes, i, LanguagesText.Length); i += LanguagesText.Length; } @@ -30399,6 +30591,8 @@ public override int Length public AgentDataBlock AgentData; public PropertiesDataBlock PropertiesData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public AvatarInterestsUpdatePacket() { HasVariableBlocks = false; @@ -30407,6 +30601,7 @@ public AvatarInterestsUpdatePacket() Header.Frequency = PacketFrequency.Low; Header.ID = 175; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); PropertiesData = new PropertiesDataBlock(); @@ -30432,11 +30627,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public AvatarInterestsUpdatePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -30533,7 +30727,7 @@ public override void FromBytes(byte[] bytes, ref int i) try { TargetID.FromBytes(bytes, i); i += 16; - length = (bytes[i++] + (bytes[i++] << 8)); + length = Utils.BytesToUInt16(bytes, i); i+=2; Notes = new byte[length]; Buffer.BlockCopy(bytes, i, Notes, 0, length); i += length; } @@ -30546,8 +30740,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { TargetID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)(Notes.Length % 256); - bytes[i++] = (byte)((Notes.Length >> 8) % 256); + Utils.UInt16ToBytes((ushort)Notes.Length, bytes, i); i += 2; Buffer.BlockCopy(Notes, 0, bytes, i, Notes.Length); i += Notes.Length; } @@ -30574,6 +30767,7 @@ public AvatarNotesReplyPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 176; Header.Reliable = true; + NeedValidateIDs = false; AgentData = new AgentDataBlock(); Data = new DataBlock(); } @@ -30598,11 +30792,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public AvatarNotesReplyPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -30702,7 +30895,7 @@ public override void FromBytes(byte[] bytes, ref int i) try { TargetID.FromBytes(bytes, i); i += 16; - length = (bytes[i++] + (bytes[i++] << 8)); + length = Utils.BytesToUInt16(bytes, i); i+=2; Notes = new byte[length]; Buffer.BlockCopy(bytes, i, Notes, 0, length); i += length; } @@ -30715,8 +30908,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { TargetID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)(Notes.Length % 256); - bytes[i++] = (byte)((Notes.Length >> 8) % 256); + Utils.UInt16ToBytes((ushort)Notes.Length, bytes, i); i += 2; Buffer.BlockCopy(Notes, 0, bytes, i, Notes.Length); i += Notes.Length; } @@ -30735,6 +30927,8 @@ public override int Length public AgentDataBlock AgentData; public DataBlock Data; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public AvatarNotesUpdatePacket() { HasVariableBlocks = false; @@ -30743,6 +30937,7 @@ public AvatarNotesUpdatePacket() Header.Frequency = PacketFrequency.Low; Header.ID = 177; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); Data = new DataBlock(); } @@ -30767,11 +30962,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public AvatarNotesUpdatePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -30871,7 +31065,7 @@ public override void FromBytes(byte[] bytes, ref int i) try { PickID.FromBytes(bytes, i); i += 16; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); PickName = new byte[length]; Buffer.BlockCopy(bytes, i, PickName, 0, length); i += length; } @@ -30884,7 +31078,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { PickID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)PickName.Length; + Utils.ByteToBytes((byte)PickName.Length, bytes, ref i); Buffer.BlockCopy(PickName, 0, bytes, i, PickName.Length); i += PickName.Length; } @@ -30912,6 +31106,7 @@ public AvatarPicksReplyPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 178; Header.Reliable = true; + NeedValidateIDs = false; AgentData = new AgentDataBlock(); Data = null; } @@ -30944,11 +31139,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public AvatarPicksReplyPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -30974,7 +31168,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)Data.Length; + Utils.ByteToBytes((byte)Data.Length, bytes, ref i); for (int j = 0; j < Data.Length; j++) { Data[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -31138,6 +31332,8 @@ public override int Length public AgentDataBlock AgentData; public EventDataBlock EventData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public EventInfoRequestPacket() { HasVariableBlocks = false; @@ -31146,6 +31342,7 @@ public EventInfoRequestPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 179; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); EventData = new EventDataBlock(); } @@ -31170,11 +31367,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public EventInfoRequestPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -31287,26 +31483,26 @@ public override void FromBytes(byte[] bytes, ref int i) try { EventID = Utils.BytesToUIntSafepos(bytes, i); i += 4; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Creator = new byte[length]; Buffer.BlockCopy(bytes, i, Creator, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Name = new byte[length]; Buffer.BlockCopy(bytes, i, Name, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Category = new byte[length]; Buffer.BlockCopy(bytes, i, Category, 0, length); i += length; - length = (bytes[i++] + (bytes[i++] << 8)); + length = Utils.BytesToUInt16(bytes, i); i+=2; Desc = new byte[length]; Buffer.BlockCopy(bytes, i, Desc, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Date = new byte[length]; Buffer.BlockCopy(bytes, i, Date, 0, length); i += length; DateUTC = Utils.BytesToUIntSafepos(bytes, i); i += 4; Duration = Utils.BytesToUIntSafepos(bytes, i); i += 4; Cover = Utils.BytesToUIntSafepos(bytes, i); i += 4; Amount = Utils.BytesToUIntSafepos(bytes, i); i += 4; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); SimName = new byte[length]; Buffer.BlockCopy(bytes, i, SimName, 0, length); i += length; GlobalPos.FromBytes(bytes, i); i += 24; @@ -31321,22 +31517,21 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { Utils.UIntToBytesSafepos(EventID, bytes, i); i += 4; - bytes[i++] = (byte)Creator.Length; + Utils.ByteToBytes((byte)Creator.Length, bytes, ref i); Buffer.BlockCopy(Creator, 0, bytes, i, Creator.Length); i += Creator.Length; - bytes[i++] = (byte)Name.Length; + Utils.ByteToBytes((byte)Name.Length, bytes, ref i); Buffer.BlockCopy(Name, 0, bytes, i, Name.Length); i += Name.Length; - bytes[i++] = (byte)Category.Length; + Utils.ByteToBytes((byte)Category.Length, bytes, ref i); Buffer.BlockCopy(Category, 0, bytes, i, Category.Length); i += Category.Length; - bytes[i++] = (byte)(Desc.Length % 256); - bytes[i++] = (byte)((Desc.Length >> 8) % 256); + Utils.UInt16ToBytes((ushort)Desc.Length, bytes, i); i += 2; Buffer.BlockCopy(Desc, 0, bytes, i, Desc.Length); i += Desc.Length; - bytes[i++] = (byte)Date.Length; + Utils.ByteToBytes((byte)Date.Length, bytes, ref i); Buffer.BlockCopy(Date, 0, bytes, i, Date.Length); i += Date.Length; Utils.UIntToBytesSafepos(DateUTC, bytes, i); i += 4; Utils.UIntToBytesSafepos(Duration, bytes, i); i += 4; Utils.UIntToBytesSafepos(Cover, bytes, i); i += 4; Utils.UIntToBytesSafepos(Amount, bytes, i); i += 4; - bytes[i++] = (byte)SimName.Length; + Utils.ByteToBytes((byte)SimName.Length, bytes, ref i); Buffer.BlockCopy(SimName, 0, bytes, i, SimName.Length); i += SimName.Length; GlobalPos.ToBytes(bytes, i); i += 24; Utils.UIntToBytesSafepos(EventFlags, bytes, i); i += 4; @@ -31365,6 +31560,7 @@ public EventInfoReplyPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 180; Header.Reliable = true; + NeedValidateIDs = false; AgentData = new AgentDataBlock(); EventData = new EventDataBlock(); } @@ -31389,11 +31585,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public EventInfoReplyPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -31516,6 +31711,8 @@ public override int Length public AgentDataBlock AgentData; public EventDataBlock EventData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public EventNotificationAddRequestPacket() { HasVariableBlocks = false; @@ -31524,6 +31721,7 @@ public EventNotificationAddRequestPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 181; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); EventData = new EventDataBlock(); } @@ -31548,11 +31746,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public EventNotificationAddRequestPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -31675,6 +31872,8 @@ public override int Length public AgentDataBlock AgentData; public EventDataBlock EventData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public EventNotificationRemoveRequestPacket() { HasVariableBlocks = false; @@ -31683,6 +31882,7 @@ public EventNotificationRemoveRequestPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 182; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); EventData = new EventDataBlock(); } @@ -31707,11 +31907,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public EventNotificationRemoveRequestPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -31851,7 +32050,7 @@ public override void FromBytes(byte[] bytes, ref int i) try { QueryID.FromBytes(bytes, i); i += 16; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); QueryText = new byte[length]; Buffer.BlockCopy(bytes, i, QueryText, 0, length); i += length; QueryFlags = Utils.BytesToUIntSafepos(bytes, i); i += 4; @@ -31866,7 +32065,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { QueryID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)QueryText.Length; + Utils.ByteToBytes((byte)QueryText.Length, bytes, ref i); Buffer.BlockCopy(QueryText, 0, bytes, i, QueryText.Length); i += QueryText.Length; Utils.UIntToBytesSafepos(QueryFlags, bytes, i); i += 4; Utils.IntToBytesSafepos(QueryStart, bytes, i); i += 4; @@ -31889,6 +32088,8 @@ public override int Length public EventDataBlock EventData; public QueryDataBlock QueryData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public EventGodDeletePacket() { HasVariableBlocks = false; @@ -31897,6 +32098,7 @@ public EventGodDeletePacket() Header.Frequency = PacketFrequency.Low; Header.ID = 183; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); EventData = new EventDataBlock(); QueryData = new QueryDataBlock(); @@ -31923,11 +32125,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public EventGodDeletePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -32043,27 +32244,27 @@ public override void FromBytes(byte[] bytes, ref int i) { PickID.FromBytes(bytes, i); i += 16; CreatorID.FromBytes(bytes, i); i += 16; - TopPick = (bytes[i++] != 0) ? (bool)true : (bool)false; + TopPick = (Utils.BytesToByte(bytes, ref i) != 0); ParcelID.FromBytes(bytes, i); i += 16; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Name = new byte[length]; Buffer.BlockCopy(bytes, i, Name, 0, length); i += length; - length = (bytes[i++] + (bytes[i++] << 8)); + length = Utils.BytesToUInt16(bytes, i); i+=2; Desc = new byte[length]; Buffer.BlockCopy(bytes, i, Desc, 0, length); i += length; SnapshotID.FromBytes(bytes, i); i += 16; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); User = new byte[length]; Buffer.BlockCopy(bytes, i, User, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); OriginalName = new byte[length]; Buffer.BlockCopy(bytes, i, OriginalName, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); SimName = new byte[length]; Buffer.BlockCopy(bytes, i, SimName, 0, length); i += length; PosGlobal.FromBytes(bytes, i); i += 24; SortOrder = Utils.BytesToIntSafepos(bytes, i); i += 4; - Enabled = (bytes[i++] != 0) ? (bool)true : (bool)false; + Enabled = (Utils.BytesToByte(bytes, ref i) != 0); } catch (Exception) { @@ -32075,23 +32276,22 @@ public override void ToBytes(byte[] bytes, ref int i) { PickID.ToBytes(bytes, i); i += 16; CreatorID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)((TopPick) ? 1 : 0); + Utils.ByteToBytes((byte)((TopPick) ? 1 : 0), bytes, ref i); ParcelID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)Name.Length; + Utils.ByteToBytes((byte)Name.Length, bytes, ref i); Buffer.BlockCopy(Name, 0, bytes, i, Name.Length); i += Name.Length; - bytes[i++] = (byte)(Desc.Length % 256); - bytes[i++] = (byte)((Desc.Length >> 8) % 256); + Utils.UInt16ToBytes((ushort)Desc.Length, bytes, i); i += 2; Buffer.BlockCopy(Desc, 0, bytes, i, Desc.Length); i += Desc.Length; SnapshotID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)User.Length; + Utils.ByteToBytes((byte)User.Length, bytes, ref i); Buffer.BlockCopy(User, 0, bytes, i, User.Length); i += User.Length; - bytes[i++] = (byte)OriginalName.Length; + Utils.ByteToBytes((byte)OriginalName.Length, bytes, ref i); Buffer.BlockCopy(OriginalName, 0, bytes, i, OriginalName.Length); i += OriginalName.Length; - bytes[i++] = (byte)SimName.Length; + Utils.ByteToBytes((byte)SimName.Length, bytes, ref i); Buffer.BlockCopy(SimName, 0, bytes, i, SimName.Length); i += SimName.Length; PosGlobal.ToBytes(bytes, i); i += 24; Utils.IntToBytesSafepos(SortOrder, bytes, i); i += 4; - bytes[i++] = (byte)((Enabled) ? 1 : 0); + Utils.ByteToBytes((byte)((Enabled) ? 1 : 0), bytes, ref i); } } @@ -32117,6 +32317,7 @@ public PickInfoReplyPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 184; Header.Reliable = true; + NeedValidateIDs = false; AgentData = new AgentDataBlock(); Data = new DataBlock(); } @@ -32141,11 +32342,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public PickInfoReplyPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -32255,18 +32455,18 @@ public override void FromBytes(byte[] bytes, ref int i) { PickID.FromBytes(bytes, i); i += 16; CreatorID.FromBytes(bytes, i); i += 16; - TopPick = (bytes[i++] != 0) ? (bool)true : (bool)false; + TopPick = (Utils.BytesToByte(bytes, ref i) != 0); ParcelID.FromBytes(bytes, i); i += 16; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Name = new byte[length]; Buffer.BlockCopy(bytes, i, Name, 0, length); i += length; - length = (bytes[i++] + (bytes[i++] << 8)); + length = Utils.BytesToUInt16(bytes, i); i+=2; Desc = new byte[length]; Buffer.BlockCopy(bytes, i, Desc, 0, length); i += length; SnapshotID.FromBytes(bytes, i); i += 16; PosGlobal.FromBytes(bytes, i); i += 24; SortOrder = Utils.BytesToIntSafepos(bytes, i); i += 4; - Enabled = (bytes[i++] != 0) ? (bool)true : (bool)false; + Enabled = (Utils.BytesToByte(bytes, ref i) != 0); } catch (Exception) { @@ -32278,17 +32478,16 @@ public override void ToBytes(byte[] bytes, ref int i) { PickID.ToBytes(bytes, i); i += 16; CreatorID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)((TopPick) ? 1 : 0); + Utils.ByteToBytes((byte)((TopPick) ? 1 : 0), bytes, ref i); ParcelID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)Name.Length; + Utils.ByteToBytes((byte)Name.Length, bytes, ref i); Buffer.BlockCopy(Name, 0, bytes, i, Name.Length); i += Name.Length; - bytes[i++] = (byte)(Desc.Length % 256); - bytes[i++] = (byte)((Desc.Length >> 8) % 256); + Utils.UInt16ToBytes((ushort)Desc.Length, bytes, i); i += 2; Buffer.BlockCopy(Desc, 0, bytes, i, Desc.Length); i += Desc.Length; SnapshotID.ToBytes(bytes, i); i += 16; PosGlobal.ToBytes(bytes, i); i += 24; Utils.IntToBytesSafepos(SortOrder, bytes, i); i += 4; - bytes[i++] = (byte)((Enabled) ? 1 : 0); + Utils.ByteToBytes((byte)((Enabled) ? 1 : 0), bytes, ref i); } } @@ -32306,6 +32505,8 @@ public override int Length public AgentDataBlock AgentData; public DataBlock Data; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public PickInfoUpdatePacket() { HasVariableBlocks = false; @@ -32314,6 +32515,7 @@ public PickInfoUpdatePacket() Header.Frequency = PacketFrequency.Low; Header.ID = 185; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); Data = new DataBlock(); } @@ -32338,11 +32540,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public PickInfoUpdatePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -32465,6 +32666,8 @@ public override int Length public AgentDataBlock AgentData; public DataBlock Data; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public PickDeletePacket() { HasVariableBlocks = false; @@ -32473,6 +32676,7 @@ public PickDeletePacket() Header.Frequency = PacketFrequency.Low; Header.ID = 186; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); Data = new DataBlock(); } @@ -32497,11 +32701,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public PickDeletePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -32627,6 +32830,8 @@ public override int Length public AgentDataBlock AgentData; public DataBlock Data; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public PickGodDeletePacket() { HasVariableBlocks = false; @@ -32635,6 +32840,7 @@ public PickGodDeletePacket() Header.Frequency = PacketFrequency.Low; Header.ID = 187; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); Data = new DataBlock(); } @@ -32659,11 +32865,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public PickGodDeletePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -32727,10 +32932,10 @@ public override void FromBytes(byte[] bytes, ref int i) { TaskID.FromBytes(bytes, i); i += 16; ItemID.FromBytes(bytes, i); i += 16; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); ObjectName = new byte[length]; Buffer.BlockCopy(bytes, i, ObjectName, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); ObjectOwner = new byte[length]; Buffer.BlockCopy(bytes, i, ObjectOwner, 0, length); i += length; Questions = Utils.BytesToIntSafepos(bytes, i); i += 4; @@ -32745,9 +32950,9 @@ public override void ToBytes(byte[] bytes, ref int i) { TaskID.ToBytes(bytes, i); i += 16; ItemID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)ObjectName.Length; + Utils.ByteToBytes((byte)ObjectName.Length, bytes, ref i); Buffer.BlockCopy(ObjectName, 0, bytes, i, ObjectName.Length); i += ObjectName.Length; - bytes[i++] = (byte)ObjectOwner.Length; + Utils.ByteToBytes((byte)ObjectOwner.Length, bytes, ref i); Buffer.BlockCopy(ObjectOwner, 0, bytes, i, ObjectOwner.Length); i += ObjectOwner.Length; Utils.IntToBytesSafepos(Questions, bytes, i); i += 4; } @@ -32813,6 +33018,7 @@ public ScriptQuestionPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 188; Header.Reliable = true; + NeedValidateIDs = false; Data = new DataBlock(); Experience = new ExperienceBlock(); } @@ -32837,11 +33043,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ScriptQuestionPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; Data.FromBytes(bytes, ref i); @@ -32897,9 +33102,9 @@ public override void FromBytes(byte[] bytes, ref int i) { try { - TakeControls = (bytes[i++] != 0) ? (bool)true : (bool)false; + TakeControls = (Utils.BytesToByte(bytes, ref i) != 0); Controls = Utils.BytesToUIntSafepos(bytes, i); i += 4; - PassToAgent = (bytes[i++] != 0) ? (bool)true : (bool)false; + PassToAgent = (Utils.BytesToByte(bytes, ref i) != 0); } catch (Exception) { @@ -32909,9 +33114,9 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = (byte)((TakeControls) ? 1 : 0); + Utils.ByteToBytes((byte)((TakeControls) ? 1 : 0), bytes, ref i); Utils.UIntToBytesSafepos(Controls, bytes, i); i += 4; - bytes[i++] = (byte)((PassToAgent) ? 1 : 0); + Utils.ByteToBytes((byte)((PassToAgent) ? 1 : 0), bytes, ref i); } } @@ -32936,6 +33141,7 @@ public ScriptControlChangePacket() Header.Frequency = PacketFrequency.Low; Header.ID = 189; Header.Reliable = true; + NeedValidateIDs = false; Data = null; } @@ -32966,11 +33172,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ScriptControlChangePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; int count = (int)bytes[i++]; @@ -32993,7 +33198,7 @@ public override byte[] ToBytes() byte[] bytes = new byte[length]; int i = 0; Header.ToBytes(bytes, ref i); - bytes[i++] = (byte)Data.Length; + Utils.ByteToBytes((byte)Data.Length, bytes, ref i); for (int j = 0; j < Data.Length; j++) { Data[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -33099,16 +33304,16 @@ public override void FromBytes(byte[] bytes, ref int i) try { ObjectID.FromBytes(bytes, i); i += 16; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); FirstName = new byte[length]; Buffer.BlockCopy(bytes, i, FirstName, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); LastName = new byte[length]; Buffer.BlockCopy(bytes, i, LastName, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); ObjectName = new byte[length]; Buffer.BlockCopy(bytes, i, ObjectName, 0, length); i += length; - length = (bytes[i++] + (bytes[i++] << 8)); + length = Utils.BytesToUInt16(bytes, i); i+=2; Message = new byte[length]; Buffer.BlockCopy(bytes, i, Message, 0, length); i += length; ChatChannel = Utils.BytesToIntSafepos(bytes, i); i += 4; @@ -33123,14 +33328,13 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { ObjectID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)FirstName.Length; + Utils.ByteToBytes((byte)FirstName.Length, bytes, ref i); Buffer.BlockCopy(FirstName, 0, bytes, i, FirstName.Length); i += FirstName.Length; - bytes[i++] = (byte)LastName.Length; + Utils.ByteToBytes((byte)LastName.Length, bytes, ref i); Buffer.BlockCopy(LastName, 0, bytes, i, LastName.Length); i += LastName.Length; - bytes[i++] = (byte)ObjectName.Length; + Utils.ByteToBytes((byte)ObjectName.Length, bytes, ref i); Buffer.BlockCopy(ObjectName, 0, bytes, i, ObjectName.Length); i += ObjectName.Length; - bytes[i++] = (byte)(Message.Length % 256); - bytes[i++] = (byte)((Message.Length >> 8) % 256); + Utils.UInt16ToBytes((ushort)Message.Length, bytes, i); i += 2; Buffer.BlockCopy(Message, 0, bytes, i, Message.Length); i += Message.Length; Utils.IntToBytesSafepos(ChatChannel, bytes, i); i += 4; ImageID.ToBytes(bytes, i); i += 16; @@ -33164,7 +33368,7 @@ public override void FromBytes(byte[] bytes, ref int i) int length; try { - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); ButtonLabel = new byte[length]; Buffer.BlockCopy(bytes, i, ButtonLabel, 0, length); i += length; } @@ -33176,7 +33380,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = (byte)ButtonLabel.Length; + Utils.ByteToBytes((byte)ButtonLabel.Length, bytes, ref i); Buffer.BlockCopy(ButtonLabel, 0, bytes, i, ButtonLabel.Length); i += ButtonLabel.Length; } @@ -33245,6 +33449,7 @@ public ScriptDialogPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 190; Header.Reliable = true; + NeedValidateIDs = false; Header.Zerocoded = true; Data = new DataBlock(); Buttons = null; @@ -33288,11 +33493,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ScriptDialogPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; Data.FromBytes(bytes, ref i); @@ -33329,9 +33533,9 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); Data.ToBytes(bytes, ref i); - bytes[i++] = (byte)Buttons.Length; + Utils.ByteToBytes((byte)Buttons.Length, bytes, ref i); for (int j = 0; j < Buttons.Length; j++) { Buttons[j].ToBytes(bytes, ref i); } - bytes[i++] = (byte)OwnerData.Length; + Utils.ByteToBytes((byte)OwnerData.Length, bytes, ref i); for (int j = 0; j < OwnerData.Length; j++) { OwnerData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -33496,7 +33700,7 @@ public override void FromBytes(byte[] bytes, ref int i) ObjectID.FromBytes(bytes, i); i += 16; ChatChannel = Utils.BytesToIntSafepos(bytes, i); i += 4; ButtonIndex = Utils.BytesToIntSafepos(bytes, i); i += 4; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); ButtonLabel = new byte[length]; Buffer.BlockCopy(bytes, i, ButtonLabel, 0, length); i += length; } @@ -33511,7 +33715,7 @@ public override void ToBytes(byte[] bytes, ref int i) ObjectID.ToBytes(bytes, i); i += 16; Utils.IntToBytesSafepos(ChatChannel, bytes, i); i += 4; Utils.IntToBytesSafepos(ButtonIndex, bytes, i); i += 4; - bytes[i++] = (byte)ButtonLabel.Length; + Utils.ByteToBytes((byte)ButtonLabel.Length, bytes, ref i); Buffer.BlockCopy(ButtonLabel, 0, bytes, i, ButtonLabel.Length); i += ButtonLabel.Length; } @@ -33530,6 +33734,8 @@ public override int Length public AgentDataBlock AgentData; public DataBlock Data; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ScriptDialogReplyPacket() { HasVariableBlocks = false; @@ -33538,6 +33744,7 @@ public ScriptDialogReplyPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 191; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); Data = new DataBlock(); @@ -33563,11 +33770,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ScriptDialogReplyPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -33650,6 +33856,8 @@ public override int Length } public AgentDataBlock AgentData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ForceScriptControlReleasePacket() { HasVariableBlocks = false; @@ -33658,6 +33866,7 @@ public ForceScriptControlReleasePacket() Header.Frequency = PacketFrequency.Low; Header.ID = 192; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); } @@ -33680,11 +33889,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ForceScriptControlReleasePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -33807,6 +34015,8 @@ public override int Length public AgentDataBlock AgentData; public DataBlock Data; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public RevokePermissionsPacket() { HasVariableBlocks = false; @@ -33815,6 +34025,7 @@ public RevokePermissionsPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 193; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); Data = new DataBlock(); } @@ -33839,11 +34050,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public RevokePermissionsPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -33907,16 +34117,16 @@ public override void FromBytes(byte[] bytes, ref int i) int length; try { - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); ObjectName = new byte[length]; Buffer.BlockCopy(bytes, i, ObjectName, 0, length); i += length; ObjectID.FromBytes(bytes, i); i += 16; OwnerID.FromBytes(bytes, i); i += 16; - OwnerIsGroup = (bytes[i++] != 0) ? (bool)true : (bool)false; - length = bytes[i++]; + OwnerIsGroup = (Utils.BytesToByte(bytes, ref i) != 0); + length = Utils.BytesToByte(bytes, ref i); Message = new byte[length]; Buffer.BlockCopy(bytes, i, Message, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); URL = new byte[length]; Buffer.BlockCopy(bytes, i, URL, 0, length); i += length; } @@ -33928,14 +34138,14 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = (byte)ObjectName.Length; + Utils.ByteToBytes((byte)ObjectName.Length, bytes, ref i); Buffer.BlockCopy(ObjectName, 0, bytes, i, ObjectName.Length); i += ObjectName.Length; ObjectID.ToBytes(bytes, i); i += 16; OwnerID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)((OwnerIsGroup) ? 1 : 0); - bytes[i++] = (byte)Message.Length; + Utils.ByteToBytes((byte)((OwnerIsGroup) ? 1 : 0), bytes, ref i); + Utils.ByteToBytes((byte)Message.Length, bytes, ref i); Buffer.BlockCopy(Message, 0, bytes, i, Message.Length); i += Message.Length; - bytes[i++] = (byte)URL.Length; + Utils.ByteToBytes((byte)URL.Length, bytes, ref i); Buffer.BlockCopy(URL, 0, bytes, i, URL.Length); i += URL.Length; } @@ -33960,6 +34170,7 @@ public LoadURLPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 194; Header.Reliable = true; + NeedValidateIDs = false; Data = new DataBlock(); } @@ -33982,11 +34193,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public LoadURLPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; Data.FromBytes(bytes, ref i); @@ -34044,10 +34254,10 @@ public override void FromBytes(byte[] bytes, ref int i) int length; try { - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); ObjectName = new byte[length]; Buffer.BlockCopy(bytes, i, ObjectName, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); SimName = new byte[length]; Buffer.BlockCopy(bytes, i, SimName, 0, length); i += length; SimPosition.FromBytes(bytes, i); i += 12; @@ -34061,9 +34271,9 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = (byte)ObjectName.Length; + Utils.ByteToBytes((byte)ObjectName.Length, bytes, ref i); Buffer.BlockCopy(ObjectName, 0, bytes, i, ObjectName.Length); i += ObjectName.Length; - bytes[i++] = (byte)SimName.Length; + Utils.ByteToBytes((byte)SimName.Length, bytes, ref i); Buffer.BlockCopy(SimName, 0, bytes, i, SimName.Length); i += SimName.Length; SimPosition.ToBytes(bytes, i); i += 12; LookAt.ToBytes(bytes, i); i += 12; @@ -34071,26 +34281,69 @@ public override void ToBytes(byte[] bytes, ref int i) } + /// + public sealed class OptionsBlock : PacketBlock + { + public uint Flags; + + public override int Length + { + get + { + return 4; + } + } + + public OptionsBlock() { } + public OptionsBlock(byte[] bytes, ref int i) + { + FromBytes(bytes, ref i); + } + + public override void FromBytes(byte[] bytes, ref int i) + { + try + { + Flags = Utils.BytesToUIntSafepos(bytes, i); i += 4; + } + catch (Exception) + { + throw new MalformedDataException(); + } + } + + public override void ToBytes(byte[] bytes, ref int i) + { + Utils.UIntToBytesSafepos(Flags, bytes, i); i += 4; + } + + } + public override int Length { get { - int length = 10; + int length = 11; length += Data.Length; + for (int j = 0; j < Options.Length; j++) + length += Options[j].Length; return length; } } public DataBlock Data; + public OptionsBlock[] Options; public ScriptTeleportRequestPacket() { - HasVariableBlocks = false; + HasVariableBlocks = true; Type = PacketType.ScriptTeleportRequest; Header = new Header(); Header.Frequency = PacketFrequency.Low; Header.ID = 195; Header.Reliable = true; + NeedValidateIDs = false; Data = new DataBlock(); + Options = null; } public ScriptTeleportRequestPacket(byte[] bytes, ref int i) : this() @@ -34108,36 +34361,108 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ bytes = zeroBuffer; } Data.FromBytes(bytes, ref i); + int count = (int)bytes[i++]; + if(Options == null || Options.Length != -1) { + Options = new OptionsBlock[count]; + for(int j = 0; j < count; j++) + { Options[j] = new OptionsBlock(); } + } + for (int j = 0; j < count; j++) + { Options[j].FromBytes(bytes, ref i); } } public ScriptTeleportRequestPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; Data.FromBytes(bytes, ref i); + int count = (int)bytes[i++]; + if(Options == null || Options.Length != count) { + Options = new OptionsBlock[count]; + for(int j = 0; j < count; j++) + { Options[j] = new OptionsBlock(); } + } + for (int j = 0; j < count; j++) + { Options[j].FromBytes(bytes, ref i); } } public override byte[] ToBytes() { int length = 10; length += Data.Length; + length++; + for (int j = 0; j < Options.Length; j++) { length += Options[j].Length; } if (Header.AckList != null && Header.AckList.Length > 0) { length += Header.AckList.Length * 4 + 1; } byte[] bytes = new byte[length]; int i = 0; Header.ToBytes(bytes, ref i); Data.ToBytes(bytes, ref i); + Utils.ByteToBytes((byte)Options.Length, bytes, ref i); + for (int j = 0; j < Options.Length; j++) { Options[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; } public override byte[][] ToBytesMultiple() { - return new byte[][] { ToBytes() }; + System.Collections.Generic.List packets = new System.Collections.Generic.List(); + int i = 0; + int fixedLength = 10; + + byte[] ackBytes = null; + int acksLength = 0; + if (Header.AckList != null && Header.AckList.Length > 0) { + Header.AppendedAcks = true; + ackBytes = new byte[Header.AckList.Length * 4 + 1]; + Header.AcksToBytes(ackBytes, ref acksLength); + } + + fixedLength += Data.Length; + byte[] fixedBytes = new byte[fixedLength]; + Header.ToBytes(fixedBytes, ref i); + Data.ToBytes(fixedBytes, ref i); + fixedLength += 1; + + int OptionsStart = 0; + do + { + int variableLength = 0; + int OptionsCount = 0; + + i = OptionsStart; + while (fixedLength + variableLength + acksLength < Packet.MTU && i < Options.Length) { + int blockLength = Options[i].Length; + if (fixedLength + variableLength + blockLength + acksLength <= MTU || i == OptionsStart) { + variableLength += blockLength; + ++OptionsCount; + } + else { break; } + ++i; + } + + byte[] packet = new byte[fixedLength + variableLength + acksLength]; + int length = fixedBytes.Length; + Buffer.BlockCopy(fixedBytes, 0, packet, 0, length); + if (packets.Count > 0) { packet[0] = (byte)(packet[0] & ~0x10); } + + packet[length++] = (byte)OptionsCount; + for (i = OptionsStart; i < OptionsStart + OptionsCount; i++) { Options[i].ToBytes(packet, ref length); } + OptionsStart += OptionsCount; + + if (acksLength > 0) { + Buffer.BlockCopy(ackBytes, 0, packet, length, acksLength); + acksLength = 0; + } + + packets.Add(packet); + } while ( + OptionsStart < Options.Length); + + return packets.ToArray(); } } @@ -34172,7 +34497,7 @@ public override void FromBytes(byte[] bytes, ref int i) try { SequenceID = Utils.BytesToIntSafepos(bytes, i); i += 4; - length = (bytes[i++] + (bytes[i++] << 8)); + length = Utils.BytesToUInt16(bytes, i); i+=2; Data = new byte[length]; Buffer.BlockCopy(bytes, i, Data, 0, length); i += length; } @@ -34185,8 +34510,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { Utils.IntToBytesSafepos(SequenceID, bytes, i); i += 4; - bytes[i++] = (byte)(Data.Length % 256); - bytes[i++] = (byte)((Data.Length >> 8) % 256); + Utils.UInt16ToBytes((ushort)Data.Length, bytes, i); i += 2; Buffer.BlockCopy(Data, 0, bytes, i, Data.Length); i += Data.Length; } @@ -34211,6 +34535,7 @@ public ParcelOverlayPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 196; Header.Reliable = true; + NeedValidateIDs = false; Header.Zerocoded = true; ParcelData = new ParcelDataBlock(); } @@ -34234,11 +34559,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ParcelOverlayPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; ParcelData.FromBytes(bytes, ref i); @@ -34361,6 +34685,8 @@ public override int Length public AgentDataBlock AgentData; public ParcelDataBlock ParcelData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ParcelPropertiesRequestByIDPacket() { HasVariableBlocks = false; @@ -34369,6 +34695,7 @@ public ParcelPropertiesRequestByIDPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 197; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); ParcelData = new ParcelDataBlock(); @@ -34394,11 +34721,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ParcelPropertiesRequestByIDPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -34521,29 +34847,29 @@ public override void FromBytes(byte[] bytes, ref int i) Flags = Utils.BytesToUIntSafepos(bytes, i); i += 4; ParcelFlags = Utils.BytesToUIntSafepos(bytes, i); i += 4; SalePrice = Utils.BytesToIntSafepos(bytes, i); i += 4; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Name = new byte[length]; Buffer.BlockCopy(bytes, i, Name, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Desc = new byte[length]; Buffer.BlockCopy(bytes, i, Desc, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); MusicURL = new byte[length]; Buffer.BlockCopy(bytes, i, MusicURL, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); MediaURL = new byte[length]; Buffer.BlockCopy(bytes, i, MediaURL, 0, length); i += length; MediaID.FromBytes(bytes, i); i += 16; - MediaAutoScale = (byte)bytes[i++]; + MediaAutoScale = Utils.BytesToByte(bytes, ref i); GroupID.FromBytes(bytes, i); i += 16; PassPrice = Utils.BytesToIntSafepos(bytes, i); i += 4; PassHours = Utils.BytesToFloatSafepos(bytes, i); i += 4; - Category = (byte)bytes[i++]; + Category = Utils.BytesToByte(bytes, ref i); AuthBuyerID.FromBytes(bytes, i); i += 16; SnapshotID.FromBytes(bytes, i); i += 16; UserLocation.FromBytes(bytes, i); i += 12; UserLookAt.FromBytes(bytes, i); i += 12; - LandingType = (byte)bytes[i++]; + LandingType = Utils.BytesToByte(bytes, ref i); } catch (Exception) { @@ -34557,25 +34883,25 @@ public override void ToBytes(byte[] bytes, ref int i) Utils.UIntToBytesSafepos(Flags, bytes, i); i += 4; Utils.UIntToBytesSafepos(ParcelFlags, bytes, i); i += 4; Utils.IntToBytesSafepos(SalePrice, bytes, i); i += 4; - bytes[i++] = (byte)Name.Length; + Utils.ByteToBytes((byte)Name.Length, bytes, ref i); Buffer.BlockCopy(Name, 0, bytes, i, Name.Length); i += Name.Length; - bytes[i++] = (byte)Desc.Length; + Utils.ByteToBytes((byte)Desc.Length, bytes, ref i); Buffer.BlockCopy(Desc, 0, bytes, i, Desc.Length); i += Desc.Length; - bytes[i++] = (byte)MusicURL.Length; + Utils.ByteToBytes((byte)MusicURL.Length, bytes, ref i); Buffer.BlockCopy(MusicURL, 0, bytes, i, MusicURL.Length); i += MusicURL.Length; - bytes[i++] = (byte)MediaURL.Length; + Utils.ByteToBytes((byte)MediaURL.Length, bytes, ref i); Buffer.BlockCopy(MediaURL, 0, bytes, i, MediaURL.Length); i += MediaURL.Length; MediaID.ToBytes(bytes, i); i += 16; - bytes[i++] = MediaAutoScale; + Utils.ByteToBytes( MediaAutoScale, bytes, ref i); GroupID.ToBytes(bytes, i); i += 16; Utils.IntToBytesSafepos(PassPrice, bytes, i); i += 4; Utils.FloatToBytesSafepos(PassHours, bytes, i); i += 4; - bytes[i++] = Category; + Utils.ByteToBytes( Category, bytes, ref i); AuthBuyerID.ToBytes(bytes, i); i += 16; SnapshotID.ToBytes(bytes, i); i += 16; UserLocation.ToBytes(bytes, i); i += 12; UserLookAt.ToBytes(bytes, i); i += 12; - bytes[i++] = LandingType; + Utils.ByteToBytes( LandingType, bytes, ref i); } } @@ -34593,6 +34919,8 @@ public override int Length public AgentDataBlock AgentData; public ParcelDataBlock ParcelData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ParcelPropertiesUpdatePacket() { HasVariableBlocks = false; @@ -34601,6 +34929,7 @@ public ParcelPropertiesUpdatePacket() Header.Frequency = PacketFrequency.Low; Header.ID = 198; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); ParcelData = new ParcelDataBlock(); @@ -34626,11 +34955,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ParcelPropertiesUpdatePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -34838,6 +35166,8 @@ public override int Length public TaskIDsBlock[] TaskIDs; public OwnerIDsBlock[] OwnerIDs; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ParcelReturnObjectsPacket() { HasVariableBlocks = true; @@ -34846,6 +35176,7 @@ public ParcelReturnObjectsPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 199; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); ParcelData = new ParcelDataBlock(); @@ -34891,11 +35222,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ParcelReturnObjectsPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -34935,9 +35265,9 @@ public override byte[] ToBytes() Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); ParcelData.ToBytes(bytes, ref i); - bytes[i++] = (byte)TaskIDs.Length; + Utils.ByteToBytes((byte)TaskIDs.Length, bytes, ref i); for (int j = 0; j < TaskIDs.Length; j++) { TaskIDs[j].ToBytes(bytes, ref i); } - bytes[i++] = (byte)OwnerIDs.Length; + Utils.ByteToBytes((byte)OwnerIDs.Length, bytes, ref i); for (int j = 0; j < OwnerIDs.Length; j++) { OwnerIDs[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -35126,6 +35456,8 @@ public override int Length public AgentDataBlock AgentData; public ParcelDataBlock ParcelData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ParcelSetOtherCleanTimePacket() { HasVariableBlocks = false; @@ -35134,6 +35466,7 @@ public ParcelSetOtherCleanTimePacket() Header.Frequency = PacketFrequency.Low; Header.ID = 200; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); ParcelData = new ParcelDataBlock(); @@ -35159,11 +35492,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ParcelSetOtherCleanTimePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -35371,6 +35703,8 @@ public override int Length public TaskIDsBlock[] TaskIDs; public OwnerIDsBlock[] OwnerIDs; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ParcelDisableObjectsPacket() { HasVariableBlocks = true; @@ -35379,6 +35713,7 @@ public ParcelDisableObjectsPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 201; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); ParcelData = new ParcelDataBlock(); @@ -35424,11 +35759,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ParcelDisableObjectsPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -35468,9 +35802,9 @@ public override byte[] ToBytes() Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); ParcelData.ToBytes(bytes, ref i); - bytes[i++] = (byte)TaskIDs.Length; + Utils.ByteToBytes((byte)TaskIDs.Length, bytes, ref i); for (int j = 0; j < TaskIDs.Length; j++) { TaskIDs[j].ToBytes(bytes, ref i); } - bytes[i++] = (byte)OwnerIDs.Length; + Utils.ByteToBytes((byte)OwnerIDs.Length, bytes, ref i); for (int j = 0; j < OwnerIDs.Length; j++) { OwnerIDs[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -35700,6 +36034,8 @@ public override int Length public ParcelDataBlock ParcelData; public ReturnIDsBlock[] ReturnIDs; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ParcelSelectObjectsPacket() { HasVariableBlocks = true; @@ -35708,6 +36044,7 @@ public ParcelSelectObjectsPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 202; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); ParcelData = new ParcelDataBlock(); @@ -35743,11 +36080,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ParcelSelectObjectsPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -35776,7 +36112,7 @@ public override byte[] ToBytes() Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); ParcelData.ToBytes(bytes, ref i); - bytes[i++] = (byte)ReturnIDs.Length; + Utils.ByteToBytes((byte)ReturnIDs.Length, bytes, ref i); for (int j = 0; j < ReturnIDs.Length; j++) { ReturnIDs[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -35902,6 +36238,8 @@ public override int Length } public AgentDataBlock AgentData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public EstateCovenantRequestPacket() { HasVariableBlocks = false; @@ -35910,6 +36248,7 @@ public EstateCovenantRequestPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 203; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); } @@ -35932,11 +36271,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public EstateCovenantRequestPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -35995,7 +36333,7 @@ public override void FromBytes(byte[] bytes, ref int i) { CovenantID.FromBytes(bytes, i); i += 16; CovenantTimestamp = Utils.BytesToUIntSafepos(bytes, i); i += 4; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); EstateName = new byte[length]; Buffer.BlockCopy(bytes, i, EstateName, 0, length); i += length; EstateOwnerID.FromBytes(bytes, i); i += 16; @@ -36010,7 +36348,7 @@ public override void ToBytes(byte[] bytes, ref int i) { CovenantID.ToBytes(bytes, i); i += 16; Utils.UIntToBytesSafepos(CovenantTimestamp, bytes, i); i += 4; - bytes[i++] = (byte)EstateName.Length; + Utils.ByteToBytes((byte)EstateName.Length, bytes, ref i); Buffer.BlockCopy(EstateName, 0, bytes, i, EstateName.Length); i += EstateName.Length; EstateOwnerID.ToBytes(bytes, i); i += 16; } @@ -36036,6 +36374,7 @@ public EstateCovenantReplyPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 204; Header.Reliable = true; + NeedValidateIDs = false; Data = new DataBlock(); } @@ -36058,11 +36397,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public EstateCovenantReplyPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; Data.FromBytes(bytes, ref i); @@ -36113,7 +36451,7 @@ public override void FromBytes(byte[] bytes, ref int i) { try { - ResetList = (bytes[i++] != 0) ? (bool)true : (bool)false; + ResetList = (Utils.BytesToByte(bytes, ref i) != 0); } catch (Exception) { @@ -36123,7 +36461,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = (byte)((ResetList) ? 1 : 0); + Utils.ByteToBytes((byte)((ResetList) ? 1 : 0), bytes, ref i); } } @@ -36188,6 +36526,7 @@ public ForceObjectSelectPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 205; Header.Reliable = true; + NeedValidateIDs = false; _Header = new HeaderBlock(); Data = null; } @@ -36220,11 +36559,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ForceObjectSelectPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; _Header.FromBytes(bytes, ref i); @@ -36250,7 +36588,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); _Header.ToBytes(bytes, ref i); - bytes[i++] = (byte)Data.Length; + Utils.ByteToBytes((byte)Data.Length, bytes, ref i); for (int j = 0; j < Data.Length; j++) { Data[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -36414,6 +36752,8 @@ public override int Length public AgentDataBlock AgentData; public ParcelDataBlock ParcelData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ParcelBuyPassPacket() { HasVariableBlocks = false; @@ -36422,6 +36762,7 @@ public ParcelBuyPassPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 206; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); ParcelData = new ParcelDataBlock(); } @@ -36446,11 +36787,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ParcelBuyPassPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -36576,6 +36916,8 @@ public override int Length public AgentDataBlock AgentData; public DataBlock Data; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ParcelDeedToGroupPacket() { HasVariableBlocks = false; @@ -36584,6 +36926,7 @@ public ParcelDeedToGroupPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 207; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); Data = new DataBlock(); } @@ -36608,11 +36951,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ParcelDeedToGroupPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -36735,6 +37077,8 @@ public override int Length public AgentDataBlock AgentData; public DataBlock Data; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ParcelReclaimPacket() { HasVariableBlocks = false; @@ -36743,6 +37087,7 @@ public ParcelReclaimPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 208; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); Data = new DataBlock(); } @@ -36767,11 +37112,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ParcelReclaimPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -36869,8 +37213,8 @@ public override void FromBytes(byte[] bytes, ref int i) try { GroupID.FromBytes(bytes, i); i += 16; - IsGroupOwned = (bytes[i++] != 0) ? (bool)true : (bool)false; - Final = (bytes[i++] != 0) ? (bool)true : (bool)false; + IsGroupOwned = (Utils.BytesToByte(bytes, ref i) != 0); + Final = (Utils.BytesToByte(bytes, ref i) != 0); } catch (Exception) { @@ -36881,8 +37225,8 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { GroupID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)((IsGroupOwned) ? 1 : 0); - bytes[i++] = (byte)((Final) ? 1 : 0); + Utils.ByteToBytes((byte)((IsGroupOwned) ? 1 : 0), bytes, ref i); + Utils.ByteToBytes((byte)((Final) ? 1 : 0), bytes, ref i); } } @@ -36950,6 +37294,8 @@ public override int Length public DataBlock Data; public ParcelDataBlock[] ParcelData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ParcelClaimPacket() { HasVariableBlocks = true; @@ -36958,6 +37304,7 @@ public ParcelClaimPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 209; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); Data = new DataBlock(); @@ -36993,11 +37340,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ParcelClaimPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -37026,7 +37372,7 @@ public override byte[] ToBytes() Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); Data.ToBytes(bytes, ref i); - bytes[i++] = (byte)ParcelData.Length; + Utils.ByteToBytes((byte)ParcelData.Length, bytes, ref i); for (int j = 0; j < ParcelData.Length; j++) { ParcelData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -37201,6 +37547,8 @@ public override int Length public AgentDataBlock AgentData; public ParcelDataBlock ParcelData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ParcelJoinPacket() { HasVariableBlocks = false; @@ -37209,6 +37557,7 @@ public ParcelJoinPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 210; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); ParcelData = new ParcelDataBlock(); } @@ -37233,11 +37582,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ParcelJoinPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -37369,6 +37717,8 @@ public override int Length public AgentDataBlock AgentData; public ParcelDataBlock ParcelData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ParcelDividePacket() { HasVariableBlocks = false; @@ -37377,6 +37727,7 @@ public ParcelDividePacket() Header.Frequency = PacketFrequency.Low; Header.ID = 211; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); ParcelData = new ParcelDataBlock(); } @@ -37401,11 +37752,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ParcelDividePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -37528,6 +37878,8 @@ public override int Length public AgentDataBlock AgentData; public DataBlock Data; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ParcelReleasePacket() { HasVariableBlocks = false; @@ -37536,6 +37888,7 @@ public ParcelReleasePacket() Header.Frequency = PacketFrequency.Low; Header.ID = 212; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); Data = new DataBlock(); } @@ -37560,11 +37913,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ParcelReleasePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -37664,10 +38016,10 @@ public override void FromBytes(byte[] bytes, ref int i) try { GroupID.FromBytes(bytes, i); i += 16; - IsGroupOwned = (bytes[i++] != 0) ? (bool)true : (bool)false; - RemoveContribution = (bytes[i++] != 0) ? (bool)true : (bool)false; + IsGroupOwned = (Utils.BytesToByte(bytes, ref i) != 0); + RemoveContribution = (Utils.BytesToByte(bytes, ref i) != 0); LocalID = Utils.BytesToIntSafepos(bytes, i); i += 4; - Final = (bytes[i++] != 0) ? (bool)true : (bool)false; + Final = (Utils.BytesToByte(bytes, ref i) != 0); } catch (Exception) { @@ -37678,10 +38030,10 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { GroupID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)((IsGroupOwned) ? 1 : 0); - bytes[i++] = (byte)((RemoveContribution) ? 1 : 0); + Utils.ByteToBytes((byte)((IsGroupOwned) ? 1 : 0), bytes, ref i); + Utils.ByteToBytes((byte)((RemoveContribution) ? 1 : 0), bytes, ref i); Utils.IntToBytesSafepos(LocalID, bytes, i); i += 4; - bytes[i++] = (byte)((Final) ? 1 : 0); + Utils.ByteToBytes((byte)((Final) ? 1 : 0), bytes, ref i); } } @@ -37742,6 +38094,8 @@ public override int Length public DataBlock Data; public ParcelDataBlock ParcelData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ParcelBuyPacket() { HasVariableBlocks = false; @@ -37750,6 +38104,7 @@ public ParcelBuyPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 213; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); Data = new DataBlock(); @@ -37777,11 +38132,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ParcelBuyPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -37910,6 +38264,8 @@ public override int Length public AgentDataBlock AgentData; public DataBlock Data; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ParcelGodForceOwnerPacket() { HasVariableBlocks = false; @@ -37918,6 +38274,7 @@ public ParcelGodForceOwnerPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 214; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); Data = new DataBlock(); @@ -37943,11 +38300,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ParcelGodForceOwnerPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -38076,6 +38432,8 @@ public override int Length public AgentDataBlock AgentData; public DataBlock Data; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ParcelAccessListRequestPacket() { HasVariableBlocks = false; @@ -38084,6 +38442,7 @@ public ParcelAccessListRequestPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 215; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); Data = new DataBlock(); @@ -38109,11 +38468,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ParcelAccessListRequestPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -38257,6 +38615,7 @@ public ParcelAccessListReplyPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 216; Header.Reliable = true; + NeedValidateIDs = false; Header.Zerocoded = true; Data = new DataBlock(); List = null; @@ -38290,11 +38649,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ParcelAccessListReplyPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; Data.FromBytes(bytes, ref i); @@ -38320,7 +38678,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); Data.ToBytes(bytes, ref i); - bytes[i++] = (byte)List.Length; + Utils.ByteToBytes((byte)List.Length, bytes, ref i); for (int j = 0; j < List.Length; j++) { List[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -38543,6 +38901,8 @@ public override int Length public DataBlock Data; public ListBlock[] List; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ParcelAccessListUpdatePacket() { HasVariableBlocks = true; @@ -38551,6 +38911,7 @@ public ParcelAccessListUpdatePacket() Header.Frequency = PacketFrequency.Low; Header.ID = 217; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); Data = new DataBlock(); @@ -38586,11 +38947,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ParcelAccessListUpdatePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -38619,7 +38979,7 @@ public override byte[] ToBytes() Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); Data.ToBytes(bytes, ref i); - bytes[i++] = (byte)List.Length; + Utils.ByteToBytes((byte)List.Length, bytes, ref i); for (int j = 0; j < List.Length; j++) { List[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -38788,6 +39148,8 @@ public override int Length public AgentDataBlock AgentData; public DataBlock Data; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ParcelDwellRequestPacket() { HasVariableBlocks = false; @@ -38796,6 +39158,7 @@ public ParcelDwellRequestPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 218; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); Data = new DataBlock(); } @@ -38820,11 +39183,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ParcelDwellRequestPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -38958,6 +39320,7 @@ public ParcelDwellReplyPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 219; Header.Reliable = true; + NeedValidateIDs = false; AgentData = new AgentDataBlock(); Data = new DataBlock(); } @@ -38982,11 +39345,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ParcelDwellReplyPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -39109,6 +39471,8 @@ public override int Length public AgentDataBlock AgentData; public ParcelDataBlock ParcelData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ParcelGodMarkAsContentPacket() { HasVariableBlocks = false; @@ -39117,6 +39481,7 @@ public ParcelGodMarkAsContentPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 227; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); ParcelData = new ParcelDataBlock(); } @@ -39141,11 +39506,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ParcelGodMarkAsContentPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -39271,6 +39635,8 @@ public override int Length public AgentDataBlock AgentData; public ParcelDataBlock ParcelData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ViewerStartAuctionPacket() { HasVariableBlocks = false; @@ -39279,6 +39645,7 @@ public ViewerStartAuctionPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 228; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); ParcelData = new ParcelDataBlock(); } @@ -39303,11 +39670,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ViewerStartAuctionPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -39396,6 +39762,7 @@ public UUIDNameRequestPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 235; Header.Reliable = true; + NeedValidateIDs = false; UUIDNameBlock = null; } @@ -39426,11 +39793,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public UUIDNameRequestPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; int count = (int)bytes[i++]; @@ -39453,7 +39819,7 @@ public override byte[] ToBytes() byte[] bytes = new byte[length]; int i = 0; Header.ToBytes(bytes, ref i); - bytes[i++] = (byte)UUIDNameBlock.Length; + Utils.ByteToBytes((byte)UUIDNameBlock.Length, bytes, ref i); for (int j = 0; j < UUIDNameBlock.Length; j++) { UUIDNameBlock[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -39553,10 +39919,10 @@ public override void FromBytes(byte[] bytes, ref int i) try { ID.FromBytes(bytes, i); i += 16; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); FirstName = new byte[length]; Buffer.BlockCopy(bytes, i, FirstName, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); LastName = new byte[length]; Buffer.BlockCopy(bytes, i, LastName, 0, length); i += length; } @@ -39569,9 +39935,9 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { ID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)FirstName.Length; + Utils.ByteToBytes((byte)FirstName.Length, bytes, ref i); Buffer.BlockCopy(FirstName, 0, bytes, i, FirstName.Length); i += FirstName.Length; - bytes[i++] = (byte)LastName.Length; + Utils.ByteToBytes((byte)LastName.Length, bytes, ref i); Buffer.BlockCopy(LastName, 0, bytes, i, LastName.Length); i += LastName.Length; } @@ -39597,6 +39963,7 @@ public UUIDNameReplyPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 236; Header.Reliable = true; + NeedValidateIDs = false; UUIDNameBlock = null; } @@ -39627,11 +39994,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public UUIDNameReplyPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; int count = (int)bytes[i++]; @@ -39654,7 +40020,7 @@ public override byte[] ToBytes() byte[] bytes = new byte[length]; int i = 0; Header.ToBytes(bytes, ref i); - bytes[i++] = (byte)UUIDNameBlock.Length; + Utils.ByteToBytes((byte)UUIDNameBlock.Length, bytes, ref i); for (int j = 0; j < UUIDNameBlock.Length; j++) { UUIDNameBlock[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -39782,6 +40148,7 @@ public UUIDGroupNameRequestPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 237; Header.Reliable = true; + NeedValidateIDs = false; UUIDNameBlock = null; } @@ -39812,11 +40179,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public UUIDGroupNameRequestPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; int count = (int)bytes[i++]; @@ -39839,7 +40205,7 @@ public override byte[] ToBytes() byte[] bytes = new byte[length]; int i = 0; Header.ToBytes(bytes, ref i); - bytes[i++] = (byte)UUIDNameBlock.Length; + Utils.ByteToBytes((byte)UUIDNameBlock.Length, bytes, ref i); for (int j = 0; j < UUIDNameBlock.Length; j++) { UUIDNameBlock[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -39937,7 +40303,7 @@ public override void FromBytes(byte[] bytes, ref int i) try { ID.FromBytes(bytes, i); i += 16; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); GroupName = new byte[length]; Buffer.BlockCopy(bytes, i, GroupName, 0, length); i += length; } @@ -39950,7 +40316,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { ID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)GroupName.Length; + Utils.ByteToBytes((byte)GroupName.Length, bytes, ref i); Buffer.BlockCopy(GroupName, 0, bytes, i, GroupName.Length); i += GroupName.Length; } @@ -39976,6 +40342,7 @@ public UUIDGroupNameReplyPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 238; Header.Reliable = true; + NeedValidateIDs = false; UUIDNameBlock = null; } @@ -40006,11 +40373,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public UUIDGroupNameReplyPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; int count = (int)bytes[i++]; @@ -40033,7 +40399,7 @@ public override byte[] ToBytes() byte[] bytes = new byte[length]; int i = 0; Header.ToBytes(bytes, ref i); - bytes[i++] = (byte)UUIDNameBlock.Length; + Utils.ByteToBytes((byte)UUIDNameBlock.Length, bytes, ref i); for (int j = 0; j < UUIDNameBlock.Length; j++) { UUIDNameBlock[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -40155,6 +40521,8 @@ public override int Length } public AgentDataBlock AgentData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ChildAgentDyingPacket() { HasVariableBlocks = false; @@ -40163,6 +40531,7 @@ public ChildAgentDyingPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 240; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); } @@ -40186,11 +40555,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ChildAgentDyingPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -40270,6 +40638,8 @@ public override int Length } public AgentDataBlock AgentData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ChildAgentUnknownPacket() { HasVariableBlocks = false; @@ -40278,6 +40648,7 @@ public ChildAgentUnknownPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 241; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); } @@ -40300,11 +40671,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ChildAgentUnknownPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -40392,6 +40762,7 @@ public GetScriptRunningPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 243; Header.Reliable = true; + NeedValidateIDs = false; Script = new ScriptBlock(); } @@ -40414,11 +40785,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public GetScriptRunningPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; Script.FromBytes(bytes, ref i); @@ -40473,7 +40843,7 @@ public override void FromBytes(byte[] bytes, ref int i) { ObjectID.FromBytes(bytes, i); i += 16; ItemID.FromBytes(bytes, i); i += 16; - Running = (bytes[i++] != 0) ? (bool)true : (bool)false; + Running = (Utils.BytesToByte(bytes, ref i) != 0); } catch (Exception) { @@ -40485,7 +40855,7 @@ public override void ToBytes(byte[] bytes, ref int i) { ObjectID.ToBytes(bytes, i); i += 16; ItemID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)((Running) ? 1 : 0); + Utils.ByteToBytes((byte)((Running) ? 1 : 0), bytes, ref i); } } @@ -40509,6 +40879,7 @@ public ScriptRunningReplyPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 244; Header.Reliable = true; + NeedValidateIDs = false; Script = new ScriptBlock(); } @@ -40531,11 +40902,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ScriptRunningReplyPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; Script.FromBytes(bytes, ref i); @@ -40631,7 +41001,7 @@ public override void FromBytes(byte[] bytes, ref int i) { ObjectID.FromBytes(bytes, i); i += 16; ItemID.FromBytes(bytes, i); i += 16; - Running = (bytes[i++] != 0) ? (bool)true : (bool)false; + Running = (Utils.BytesToByte(bytes, ref i) != 0); } catch (Exception) { @@ -40643,7 +41013,7 @@ public override void ToBytes(byte[] bytes, ref int i) { ObjectID.ToBytes(bytes, i); i += 16; ItemID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)((Running) ? 1 : 0); + Utils.ByteToBytes((byte)((Running) ? 1 : 0), bytes, ref i); } } @@ -40661,6 +41031,8 @@ public override int Length public AgentDataBlock AgentData; public ScriptBlock Script; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public SetScriptRunningPacket() { HasVariableBlocks = false; @@ -40669,6 +41041,7 @@ public SetScriptRunningPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 245; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); Script = new ScriptBlock(); } @@ -40693,11 +41066,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public SetScriptRunningPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -40823,6 +41195,8 @@ public override int Length public AgentDataBlock AgentData; public ScriptBlock Script; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ScriptResetPacket() { HasVariableBlocks = false; @@ -40831,6 +41205,7 @@ public ScriptResetPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 246; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); Script = new ScriptBlock(); } @@ -40855,11 +41230,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ScriptResetPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -40931,14 +41305,14 @@ public override void FromBytes(byte[] bytes, ref int i) SearchID.FromBytes(bytes, i); i += 16; SearchPos.FromBytes(bytes, i); i += 12; SearchDir.FromBytes(bytes, i, true); i += 12; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); SearchName = new byte[length]; Buffer.BlockCopy(bytes, i, SearchName, 0, length); i += length; Type = Utils.BytesToIntSafepos(bytes, i); i += 4; Range = Utils.BytesToFloatSafepos(bytes, i); i += 4; Arc = Utils.BytesToFloatSafepos(bytes, i); i += 4; RegionHandle = Utils.BytesToUInt64Safepos(bytes, i); i += 8; - SearchRegions = (byte)bytes[i++]; + SearchRegions = Utils.BytesToByte(bytes, ref i); } catch (Exception) { @@ -40953,13 +41327,13 @@ public override void ToBytes(byte[] bytes, ref int i) SearchID.ToBytes(bytes, i); i += 16; SearchPos.ToBytes(bytes, i); i += 12; SearchDir.ToBytes(bytes, i); i += 12; - bytes[i++] = (byte)SearchName.Length; + Utils.ByteToBytes((byte)SearchName.Length, bytes, ref i); Buffer.BlockCopy(SearchName, 0, bytes, i, SearchName.Length); i += SearchName.Length; Utils.IntToBytesSafepos(Type, bytes, i); i += 4; Utils.FloatToBytesSafepos(Range, bytes, i); i += 4; Utils.FloatToBytesSafepos(Arc, bytes, i); i += 4; Utils.UInt64ToBytesSafepos(RegionHandle, bytes, i); i += 8; - bytes[i++] = SearchRegions; + Utils.ByteToBytes( SearchRegions, bytes, ref i); } } @@ -40983,6 +41357,7 @@ public ScriptSensorRequestPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 247; Header.Reliable = true; + NeedValidateIDs = false; Header.Zerocoded = true; Requester = new RequesterBlock(); } @@ -41006,11 +41381,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ScriptSensorRequestPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; Requester.FromBytes(bytes, ref i); @@ -41116,7 +41490,7 @@ public override void FromBytes(byte[] bytes, ref int i) Position.FromBytes(bytes, i); i += 12; Velocity.FromBytes(bytes, i); i += 12; Rotation.FromBytes(bytes, i, true); i += 12; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Name = new byte[length]; Buffer.BlockCopy(bytes, i, Name, 0, length); i += length; Type = Utils.BytesToIntSafepos(bytes, i); i += 4; @@ -41136,7 +41510,7 @@ public override void ToBytes(byte[] bytes, ref int i) Position.ToBytes(bytes, i); i += 12; Velocity.ToBytes(bytes, i); i += 12; Rotation.ToBytes(bytes, i); i += 12; - bytes[i++] = (byte)Name.Length; + Utils.ByteToBytes((byte)Name.Length, bytes, ref i); Buffer.BlockCopy(Name, 0, bytes, i, Name.Length); i += Name.Length; Utils.IntToBytesSafepos(Type, bytes, i); i += 4; Utils.FloatToBytesSafepos(Range, bytes, i); i += 4; @@ -41166,6 +41540,7 @@ public ScriptSensorReplyPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 248; Header.Reliable = true; + NeedValidateIDs = false; Header.Zerocoded = true; Requester = new RequesterBlock(); SensedData = null; @@ -41199,11 +41574,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ScriptSensorReplyPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; Requester.FromBytes(bytes, ref i); @@ -41229,7 +41603,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); Requester.ToBytes(bytes, ref i); - bytes[i++] = (byte)SensedData.Length; + Utils.ByteToBytes((byte)SensedData.Length, bytes, ref i); for (int j = 0; j < SensedData.Length; j++) { SensedData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -41356,6 +41730,8 @@ public override int Length } public AgentDataBlock AgentData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public CompleteAgentMovementPacket() { HasVariableBlocks = false; @@ -41364,6 +41740,7 @@ public CompleteAgentMovementPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 249; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); } @@ -41386,11 +41763,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public CompleteAgentMovementPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -41532,7 +41908,7 @@ public override void FromBytes(byte[] bytes, ref int i) int length; try { - length = (bytes[i++] + (bytes[i++] << 8)); + length = Utils.BytesToUInt16(bytes, i); i+=2; ChannelVersion = new byte[length]; Buffer.BlockCopy(bytes, i, ChannelVersion, 0, length); i += length; } @@ -41544,8 +41920,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = (byte)(ChannelVersion.Length % 256); - bytes[i++] = (byte)((ChannelVersion.Length >> 8) % 256); + Utils.UInt16ToBytes((ushort)ChannelVersion.Length, bytes, i); i += 2; Buffer.BlockCopy(ChannelVersion, 0, bytes, i, ChannelVersion.Length); i += ChannelVersion.Length; } @@ -41566,6 +41941,8 @@ public override int Length public DataBlock Data; public SimDataBlock SimData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public AgentMovementCompletePacket() { HasVariableBlocks = false; @@ -41574,6 +41951,7 @@ public AgentMovementCompletePacket() Header.Frequency = PacketFrequency.Low; Header.ID = 250; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); Data = new DataBlock(); SimData = new SimDataBlock(); @@ -41600,11 +41978,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public AgentMovementCompletePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -41690,6 +42067,8 @@ public override int Length } public AgentDataBlock AgentData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public LogoutRequestPacket() { HasVariableBlocks = false; @@ -41698,6 +42077,7 @@ public LogoutRequestPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 252; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); } @@ -41720,11 +42100,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public LogoutRequestPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -41845,6 +42224,8 @@ public override int Length public AgentDataBlock AgentData; public InventoryDataBlock[] InventoryData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public LogoutReplyPacket() { HasVariableBlocks = true; @@ -41853,6 +42234,7 @@ public LogoutReplyPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 253; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); InventoryData = null; @@ -41886,11 +42268,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public LogoutReplyPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -41916,7 +42297,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)InventoryData.Length; + Utils.ByteToBytes((byte)InventoryData.Length, bytes, ref i); for (int j = 0; j < InventoryData.Length; j++) { InventoryData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -42068,22 +42449,22 @@ public override void FromBytes(byte[] bytes, ref int i) int length; try { - FromGroup = (bytes[i++] != 0) ? (bool)true : (bool)false; + FromGroup = (Utils.BytesToByte(bytes, ref i) != 0); ToAgentID.FromBytes(bytes, i); i += 16; ParentEstateID = Utils.BytesToUIntSafepos(bytes, i); i += 4; RegionID.FromBytes(bytes, i); i += 16; Position.FromBytes(bytes, i); i += 12; - Offline = (byte)bytes[i++]; - Dialog = (byte)bytes[i++]; + Offline = Utils.BytesToByte(bytes, ref i); + Dialog = Utils.BytesToByte(bytes, ref i); ID.FromBytes(bytes, i); i += 16; Timestamp = Utils.BytesToUIntSafepos(bytes, i); i += 4; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); FromAgentName = new byte[length]; Buffer.BlockCopy(bytes, i, FromAgentName, 0, length); i += length; - length = (bytes[i++] + (bytes[i++] << 8)); + length = Utils.BytesToUInt16(bytes, i); i+=2; Message = new byte[length]; Buffer.BlockCopy(bytes, i, Message, 0, length); i += length; - length = (bytes[i++] + (bytes[i++] << 8)); + length = Utils.BytesToUInt16(bytes, i); i+=2; BinaryBucket = new byte[length]; Buffer.BlockCopy(bytes, i, BinaryBucket, 0, length); i += length; } @@ -42095,22 +42476,20 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = (byte)((FromGroup) ? 1 : 0); + Utils.ByteToBytes((byte)((FromGroup) ? 1 : 0), bytes, ref i); ToAgentID.ToBytes(bytes, i); i += 16; Utils.UIntToBytesSafepos(ParentEstateID, bytes, i); i += 4; RegionID.ToBytes(bytes, i); i += 16; Position.ToBytes(bytes, i); i += 12; - bytes[i++] = Offline; - bytes[i++] = Dialog; + Utils.ByteToBytes( Offline, bytes, ref i); + Utils.ByteToBytes( Dialog, bytes, ref i); ID.ToBytes(bytes, i); i += 16; Utils.UIntToBytesSafepos(Timestamp, bytes, i); i += 4; - bytes[i++] = (byte)FromAgentName.Length; + Utils.ByteToBytes((byte)FromAgentName.Length, bytes, ref i); Buffer.BlockCopy(FromAgentName, 0, bytes, i, FromAgentName.Length); i += FromAgentName.Length; - bytes[i++] = (byte)(Message.Length % 256); - bytes[i++] = (byte)((Message.Length >> 8) % 256); + Utils.UInt16ToBytes((ushort)Message.Length, bytes, i); i += 2; Buffer.BlockCopy(Message, 0, bytes, i, Message.Length); i += Message.Length; - bytes[i++] = (byte)(BinaryBucket.Length % 256); - bytes[i++] = (byte)((BinaryBucket.Length >> 8) % 256); + Utils.UInt16ToBytes((ushort)BinaryBucket.Length, bytes, i); i += 2; Buffer.BlockCopy(BinaryBucket, 0, bytes, i, BinaryBucket.Length); i += BinaryBucket.Length; } @@ -42129,6 +42508,8 @@ public override int Length public AgentDataBlock AgentData; public MessageBlockBlock MessageBlock; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ImprovedInstantMessagePacket() { HasVariableBlocks = false; @@ -42137,6 +42518,7 @@ public ImprovedInstantMessagePacket() Header.Frequency = PacketFrequency.Low; Header.ID = 254; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); MessageBlock = new MessageBlockBlock(); @@ -42162,11 +42544,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ImprovedInstantMessagePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -42249,6 +42630,8 @@ public override int Length } public AgentDataBlock AgentData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public RetrieveInstantMessagesPacket() { HasVariableBlocks = false; @@ -42257,6 +42640,7 @@ public RetrieveInstantMessagesPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 255; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); } @@ -42279,11 +42663,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public RetrieveInstantMessagesPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -42418,6 +42801,7 @@ public FindAgentPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 256; Header.Reliable = true; + NeedValidateIDs = false; AgentBlock = new AgentBlockBlock(); LocationBlock = null; } @@ -42450,11 +42834,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public FindAgentPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentBlock.FromBytes(bytes, ref i); @@ -42480,7 +42863,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentBlock.ToBytes(bytes, ref i); - bytes[i++] = (byte)LocationBlock.Length; + Utils.ByteToBytes((byte)LocationBlock.Length, bytes, ref i); for (int j = 0; j < LocationBlock.Length; j++) { LocationBlock[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -42617,7 +43000,7 @@ public override void FromBytes(byte[] bytes, ref int i) { try { - Godlike = (bytes[i++] != 0) ? (bool)true : (bool)false; + Godlike = (Utils.BytesToByte(bytes, ref i) != 0); Token.FromBytes(bytes, i); i += 16; } catch (Exception) @@ -42628,7 +43011,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = (byte)((Godlike) ? 1 : 0); + Utils.ByteToBytes((byte)((Godlike) ? 1 : 0), bytes, ref i); Token.ToBytes(bytes, i); i += 16; } @@ -42647,6 +43030,8 @@ public override int Length public AgentDataBlock AgentData; public RequestBlockBlock RequestBlock; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public RequestGodlikePowersPacket() { HasVariableBlocks = false; @@ -42655,6 +43040,7 @@ public RequestGodlikePowersPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 257; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); RequestBlock = new RequestBlockBlock(); } @@ -42679,11 +43065,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public RequestGodlikePowersPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -42779,7 +43164,7 @@ public override void FromBytes(byte[] bytes, ref int i) { try { - GodLevel = (byte)bytes[i++]; + GodLevel = Utils.BytesToByte(bytes, ref i); Token.FromBytes(bytes, i); i += 16; } catch (Exception) @@ -42790,7 +43175,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = GodLevel; + Utils.ByteToBytes( GodLevel, bytes, ref i); Token.ToBytes(bytes, i); i += 16; } @@ -42809,6 +43194,8 @@ public override int Length public AgentDataBlock AgentData; public GrantDataBlock GrantData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public GrantGodlikePowersPacket() { HasVariableBlocks = false; @@ -42817,6 +43204,7 @@ public GrantGodlikePowersPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 258; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); GrantData = new GrantDataBlock(); } @@ -42841,11 +43229,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public GrantGodlikePowersPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -42947,7 +43334,7 @@ public override void FromBytes(byte[] bytes, ref int i) int length; try { - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Method = new byte[length]; Buffer.BlockCopy(bytes, i, Method, 0, length); i += length; Invoice.FromBytes(bytes, i); i += 16; @@ -42960,7 +43347,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = (byte)Method.Length; + Utils.ByteToBytes((byte)Method.Length, bytes, ref i); Buffer.BlockCopy(Method, 0, bytes, i, Method.Length); i += Method.Length; Invoice.ToBytes(bytes, i); i += 16; } @@ -42993,7 +43380,7 @@ public override void FromBytes(byte[] bytes, ref int i) int length; try { - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Parameter = new byte[length]; Buffer.BlockCopy(bytes, i, Parameter, 0, length); i += length; } @@ -43005,7 +43392,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = (byte)Parameter.Length; + Utils.ByteToBytes((byte)Parameter.Length, bytes, ref i); Buffer.BlockCopy(Parameter, 0, bytes, i, Parameter.Length); i += Parameter.Length; } @@ -43027,6 +43414,8 @@ public override int Length public MethodDataBlock MethodData; public ParamListBlock[] ParamList; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public GodlikeMessagePacket() { HasVariableBlocks = true; @@ -43035,6 +43424,7 @@ public GodlikeMessagePacket() Header.Frequency = PacketFrequency.Low; Header.ID = 259; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); MethodData = new MethodDataBlock(); @@ -43070,11 +43460,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public GodlikeMessagePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -43103,7 +43492,7 @@ public override byte[] ToBytes() Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); MethodData.ToBytes(bytes, ref i); - bytes[i++] = (byte)ParamList.Length; + Utils.ByteToBytes((byte)ParamList.Length, bytes, ref i); for (int j = 0; j < ParamList.Length; j++) { ParamList[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -43248,7 +43637,7 @@ public override void FromBytes(byte[] bytes, ref int i) int length; try { - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Method = new byte[length]; Buffer.BlockCopy(bytes, i, Method, 0, length); i += length; Invoice.FromBytes(bytes, i); i += 16; @@ -43261,7 +43650,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = (byte)Method.Length; + Utils.ByteToBytes((byte)Method.Length, bytes, ref i); Buffer.BlockCopy(Method, 0, bytes, i, Method.Length); i += Method.Length; Invoice.ToBytes(bytes, i); i += 16; } @@ -43294,7 +43683,7 @@ public override void FromBytes(byte[] bytes, ref int i) int length; try { - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Parameter = new byte[length]; Buffer.BlockCopy(bytes, i, Parameter, 0, length); i += length; } @@ -43306,7 +43695,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = (byte)Parameter.Length; + Utils.ByteToBytes((byte)Parameter.Length, bytes, ref i); Buffer.BlockCopy(Parameter, 0, bytes, i, Parameter.Length); i += Parameter.Length; } @@ -43328,6 +43717,8 @@ public override int Length public MethodDataBlock MethodData; public ParamListBlock[] ParamList; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public EstateOwnerMessagePacket() { HasVariableBlocks = true; @@ -43336,6 +43727,7 @@ public EstateOwnerMessagePacket() Header.Frequency = PacketFrequency.Low; Header.ID = 260; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); MethodData = new MethodDataBlock(); @@ -43371,11 +43763,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public EstateOwnerMessagePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -43404,7 +43795,7 @@ public override byte[] ToBytes() Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); MethodData.ToBytes(bytes, ref i); - bytes[i++] = (byte)ParamList.Length; + Utils.ByteToBytes((byte)ParamList.Length, bytes, ref i); for (int j = 0; j < ParamList.Length; j++) { ParamList[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -43549,7 +43940,7 @@ public override void FromBytes(byte[] bytes, ref int i) int length; try { - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Method = new byte[length]; Buffer.BlockCopy(bytes, i, Method, 0, length); i += length; Invoice.FromBytes(bytes, i); i += 16; @@ -43562,7 +43953,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = (byte)Method.Length; + Utils.ByteToBytes((byte)Method.Length, bytes, ref i); Buffer.BlockCopy(Method, 0, bytes, i, Method.Length); i += Method.Length; Invoice.ToBytes(bytes, i); i += 16; } @@ -43595,7 +43986,7 @@ public override void FromBytes(byte[] bytes, ref int i) int length; try { - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Parameter = new byte[length]; Buffer.BlockCopy(bytes, i, Parameter, 0, length); i += length; } @@ -43607,7 +43998,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = (byte)Parameter.Length; + Utils.ByteToBytes((byte)Parameter.Length, bytes, ref i); Buffer.BlockCopy(Parameter, 0, bytes, i, Parameter.Length); i += Parameter.Length; } @@ -43629,6 +44020,8 @@ public override int Length public MethodDataBlock MethodData; public ParamListBlock[] ParamList; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public GenericMessagePacket() { HasVariableBlocks = true; @@ -43637,6 +44030,7 @@ public GenericMessagePacket() Header.Frequency = PacketFrequency.Low; Header.ID = 261; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); MethodData = new MethodDataBlock(); @@ -43672,11 +44066,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public GenericMessagePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -43705,7 +44098,7 @@ public override byte[] ToBytes() Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); MethodData.ToBytes(bytes, ref i); - bytes[i++] = (byte)ParamList.Length; + Utils.ByteToBytes((byte)ParamList.Length, bytes, ref i); for (int j = 0; j < ParamList.Length; j++) { ParamList[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -43871,6 +44264,8 @@ public override int Length public AgentDataBlock AgentData; public MuteDataBlock MuteData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public MuteListRequestPacket() { HasVariableBlocks = false; @@ -43879,6 +44274,7 @@ public MuteListRequestPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 262; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); MuteData = new MuteDataBlock(); } @@ -43903,11 +44299,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public MuteListRequestPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -44009,7 +44404,7 @@ public override void FromBytes(byte[] bytes, ref int i) try { MuteID.FromBytes(bytes, i); i += 16; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); MuteName = new byte[length]; Buffer.BlockCopy(bytes, i, MuteName, 0, length); i += length; MuteType = Utils.BytesToIntSafepos(bytes, i); i += 4; @@ -44024,7 +44419,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { MuteID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)MuteName.Length; + Utils.ByteToBytes((byte)MuteName.Length, bytes, ref i); Buffer.BlockCopy(MuteName, 0, bytes, i, MuteName.Length); i += MuteName.Length; Utils.IntToBytesSafepos(MuteType, bytes, i); i += 4; Utils.UIntToBytesSafepos(MuteFlags, bytes, i); i += 4; @@ -44045,6 +44440,8 @@ public override int Length public AgentDataBlock AgentData; public MuteDataBlock MuteData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public UpdateMuteListEntryPacket() { HasVariableBlocks = false; @@ -44053,6 +44450,7 @@ public UpdateMuteListEntryPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 263; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); MuteData = new MuteDataBlock(); } @@ -44077,11 +44475,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public UpdateMuteListEntryPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -44181,7 +44578,7 @@ public override void FromBytes(byte[] bytes, ref int i) try { MuteID.FromBytes(bytes, i); i += 16; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); MuteName = new byte[length]; Buffer.BlockCopy(bytes, i, MuteName, 0, length); i += length; } @@ -44194,7 +44591,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { MuteID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)MuteName.Length; + Utils.ByteToBytes((byte)MuteName.Length, bytes, ref i); Buffer.BlockCopy(MuteName, 0, bytes, i, MuteName.Length); i += MuteName.Length; } @@ -44213,6 +44610,8 @@ public override int Length public AgentDataBlock AgentData; public MuteDataBlock MuteData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public RemoveMuteListEntryPacket() { HasVariableBlocks = false; @@ -44221,6 +44620,7 @@ public RemoveMuteListEntryPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 264; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); MuteData = new MuteDataBlock(); } @@ -44245,11 +44645,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public RemoveMuteListEntryPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -44419,6 +44818,8 @@ public override int Length public NotecardDataBlock NotecardData; public InventoryDataBlock[] InventoryData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public CopyInventoryFromNotecardPacket() { HasVariableBlocks = true; @@ -44427,6 +44828,7 @@ public CopyInventoryFromNotecardPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 265; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); NotecardData = new NotecardDataBlock(); @@ -44462,11 +44864,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public CopyInventoryFromNotecardPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -44495,7 +44896,7 @@ public override byte[] ToBytes() Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); NotecardData.ToBytes(bytes, ref i); - bytes[i++] = (byte)InventoryData.Length; + Utils.ByteToBytes((byte)InventoryData.Length, bytes, ref i); for (int j = 0; j < InventoryData.Length; j++) { InventoryData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -44672,17 +45073,17 @@ public override void FromBytes(byte[] bytes, ref int i) GroupMask = Utils.BytesToUIntSafepos(bytes, i); i += 4; EveryoneMask = Utils.BytesToUIntSafepos(bytes, i); i += 4; NextOwnerMask = Utils.BytesToUIntSafepos(bytes, i); i += 4; - GroupOwned = (bytes[i++] != 0) ? (bool)true : (bool)false; + GroupOwned = (Utils.BytesToByte(bytes, ref i) != 0); TransactionID.FromBytes(bytes, i); i += 16; - Type = (sbyte)bytes[i++]; - InvType = (sbyte)bytes[i++]; + Type = (sbyte)Utils.BytesToByte(bytes, ref i); + InvType = (sbyte)Utils.BytesToByte(bytes, ref i); Flags = Utils.BytesToUIntSafepos(bytes, i); i += 4; - SaleType = (byte)bytes[i++]; + SaleType = Utils.BytesToByte(bytes, ref i); SalePrice = Utils.BytesToIntSafepos(bytes, i); i += 4; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Name = new byte[length]; Buffer.BlockCopy(bytes, i, Name, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Description = new byte[length]; Buffer.BlockCopy(bytes, i, Description, 0, length); i += length; CreationDate = Utils.BytesToIntSafepos(bytes, i); i += 4; @@ -44707,16 +45108,16 @@ public override void ToBytes(byte[] bytes, ref int i) Utils.UIntToBytesSafepos(GroupMask, bytes, i); i += 4; Utils.UIntToBytesSafepos(EveryoneMask, bytes, i); i += 4; Utils.UIntToBytesSafepos(NextOwnerMask, bytes, i); i += 4; - bytes[i++] = (byte)((GroupOwned) ? 1 : 0); + Utils.ByteToBytes((byte)((GroupOwned) ? 1 : 0), bytes, ref i); TransactionID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)Type; - bytes[i++] = (byte)InvType; + Utils.ByteToBytes( (byte)Type, bytes, ref i); + Utils.ByteToBytes( (byte)InvType, bytes, ref i); Utils.UIntToBytesSafepos(Flags, bytes, i); i += 4; - bytes[i++] = SaleType; + Utils.ByteToBytes( SaleType, bytes, ref i); Utils.IntToBytesSafepos(SalePrice, bytes, i); i += 4; - bytes[i++] = (byte)Name.Length; + Utils.ByteToBytes((byte)Name.Length, bytes, ref i); Buffer.BlockCopy(Name, 0, bytes, i, Name.Length); i += Name.Length; - bytes[i++] = (byte)Description.Length; + Utils.ByteToBytes((byte)Description.Length, bytes, ref i); Buffer.BlockCopy(Description, 0, bytes, i, Description.Length); i += Description.Length; Utils.IntToBytesSafepos(CreationDate, bytes, i); i += 4; Utils.UIntToBytesSafepos(CRC, bytes, i); i += 4; @@ -44738,6 +45139,8 @@ public override int Length public AgentDataBlock AgentData; public InventoryDataBlock[] InventoryData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public UpdateInventoryItemPacket() { HasVariableBlocks = true; @@ -44746,6 +45149,7 @@ public UpdateInventoryItemPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 266; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); InventoryData = null; @@ -44779,11 +45183,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public UpdateInventoryItemPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -44809,7 +45212,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)InventoryData.Length; + Utils.ByteToBytes((byte)InventoryData.Length, bytes, ref i); for (int j = 0; j < InventoryData.Length; j++) { InventoryData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -44907,7 +45310,7 @@ public override void FromBytes(byte[] bytes, ref int i) try { AgentID.FromBytes(bytes, i); i += 16; - SimApproved = (bytes[i++] != 0) ? (bool)true : (bool)false; + SimApproved = (Utils.BytesToByte(bytes, ref i) != 0); TransactionID.FromBytes(bytes, i); i += 16; } catch (Exception) @@ -44919,7 +45322,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { AgentID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)((SimApproved) ? 1 : 0); + Utils.ByteToBytes((byte)((SimApproved) ? 1 : 0), bytes, ref i); TransactionID.ToBytes(bytes, i); i += 16; } @@ -44984,17 +45387,17 @@ public override void FromBytes(byte[] bytes, ref int i) GroupMask = Utils.BytesToUIntSafepos(bytes, i); i += 4; EveryoneMask = Utils.BytesToUIntSafepos(bytes, i); i += 4; NextOwnerMask = Utils.BytesToUIntSafepos(bytes, i); i += 4; - GroupOwned = (bytes[i++] != 0) ? (bool)true : (bool)false; + GroupOwned = (Utils.BytesToByte(bytes, ref i) != 0); AssetID.FromBytes(bytes, i); i += 16; - Type = (sbyte)bytes[i++]; - InvType = (sbyte)bytes[i++]; + Type = (sbyte)Utils.BytesToByte(bytes, ref i); + InvType = (sbyte)Utils.BytesToByte(bytes, ref i); Flags = Utils.BytesToUIntSafepos(bytes, i); i += 4; - SaleType = (byte)bytes[i++]; + SaleType = Utils.BytesToByte(bytes, ref i); SalePrice = Utils.BytesToIntSafepos(bytes, i); i += 4; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Name = new byte[length]; Buffer.BlockCopy(bytes, i, Name, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Description = new byte[length]; Buffer.BlockCopy(bytes, i, Description, 0, length); i += length; CreationDate = Utils.BytesToIntSafepos(bytes, i); i += 4; @@ -45019,16 +45422,16 @@ public override void ToBytes(byte[] bytes, ref int i) Utils.UIntToBytesSafepos(GroupMask, bytes, i); i += 4; Utils.UIntToBytesSafepos(EveryoneMask, bytes, i); i += 4; Utils.UIntToBytesSafepos(NextOwnerMask, bytes, i); i += 4; - bytes[i++] = (byte)((GroupOwned) ? 1 : 0); + Utils.ByteToBytes((byte)((GroupOwned) ? 1 : 0), bytes, ref i); AssetID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)Type; - bytes[i++] = (byte)InvType; + Utils.ByteToBytes( (byte)Type, bytes, ref i); + Utils.ByteToBytes( (byte)InvType, bytes, ref i); Utils.UIntToBytesSafepos(Flags, bytes, i); i += 4; - bytes[i++] = SaleType; + Utils.ByteToBytes( SaleType, bytes, ref i); Utils.IntToBytesSafepos(SalePrice, bytes, i); i += 4; - bytes[i++] = (byte)Name.Length; + Utils.ByteToBytes((byte)Name.Length, bytes, ref i); Buffer.BlockCopy(Name, 0, bytes, i, Name.Length); i += Name.Length; - bytes[i++] = (byte)Description.Length; + Utils.ByteToBytes((byte)Description.Length, bytes, ref i); Buffer.BlockCopy(Description, 0, bytes, i, Description.Length); i += Description.Length; Utils.IntToBytesSafepos(CreationDate, bytes, i); i += 4; Utils.UIntToBytesSafepos(CRC, bytes, i); i += 4; @@ -45058,6 +45461,7 @@ public UpdateCreateInventoryItemPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 267; Header.Reliable = true; + NeedValidateIDs = false; Header.Zerocoded = true; AgentData = new AgentDataBlock(); InventoryData = null; @@ -45091,11 +45495,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public UpdateCreateInventoryItemPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -45121,7 +45524,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)InventoryData.Length; + Utils.ByteToBytes((byte)InventoryData.Length, bytes, ref i); for (int j = 0; j < InventoryData.Length; j++) { InventoryData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -45220,7 +45623,7 @@ public override void FromBytes(byte[] bytes, ref int i) { AgentID.FromBytes(bytes, i); i += 16; SessionID.FromBytes(bytes, i); i += 16; - Stamp = (bytes[i++] != 0) ? (bool)true : (bool)false; + Stamp = (Utils.BytesToByte(bytes, ref i) != 0); } catch (Exception) { @@ -45232,7 +45635,7 @@ public override void ToBytes(byte[] bytes, ref int i) { AgentID.ToBytes(bytes, i); i += 16; SessionID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)((Stamp) ? 1 : 0); + Utils.ByteToBytes((byte)((Stamp) ? 1 : 0), bytes, ref i); } } @@ -45267,7 +45670,7 @@ public override void FromBytes(byte[] bytes, ref int i) { ItemID.FromBytes(bytes, i); i += 16; FolderID.FromBytes(bytes, i); i += 16; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); NewName = new byte[length]; Buffer.BlockCopy(bytes, i, NewName, 0, length); i += length; } @@ -45281,7 +45684,7 @@ public override void ToBytes(byte[] bytes, ref int i) { ItemID.ToBytes(bytes, i); i += 16; FolderID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)NewName.Length; + Utils.ByteToBytes((byte)NewName.Length, bytes, ref i); Buffer.BlockCopy(NewName, 0, bytes, i, NewName.Length); i += NewName.Length; } @@ -45301,6 +45704,8 @@ public override int Length public AgentDataBlock AgentData; public InventoryDataBlock[] InventoryData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public MoveInventoryItemPacket() { HasVariableBlocks = true; @@ -45309,6 +45714,7 @@ public MoveInventoryItemPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 268; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); InventoryData = null; @@ -45342,11 +45748,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public MoveInventoryItemPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -45372,7 +45777,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)InventoryData.Length; + Utils.ByteToBytes((byte)InventoryData.Length, bytes, ref i); for (int j = 0; j < InventoryData.Length; j++) { InventoryData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -45519,7 +45924,7 @@ public override void FromBytes(byte[] bytes, ref int i) OldAgentID.FromBytes(bytes, i); i += 16; OldItemID.FromBytes(bytes, i); i += 16; NewFolderID.FromBytes(bytes, i); i += 16; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); NewName = new byte[length]; Buffer.BlockCopy(bytes, i, NewName, 0, length); i += length; } @@ -45535,7 +45940,7 @@ public override void ToBytes(byte[] bytes, ref int i) OldAgentID.ToBytes(bytes, i); i += 16; OldItemID.ToBytes(bytes, i); i += 16; NewFolderID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)NewName.Length; + Utils.ByteToBytes((byte)NewName.Length, bytes, ref i); Buffer.BlockCopy(NewName, 0, bytes, i, NewName.Length); i += NewName.Length; } @@ -45555,6 +45960,8 @@ public override int Length public AgentDataBlock AgentData; public InventoryDataBlock[] InventoryData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public CopyInventoryItemPacket() { HasVariableBlocks = true; @@ -45563,6 +45970,7 @@ public CopyInventoryItemPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 269; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); InventoryData = null; @@ -45596,11 +46004,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public CopyInventoryItemPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -45626,7 +46033,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)InventoryData.Length; + Utils.ByteToBytes((byte)InventoryData.Length, bytes, ref i); for (int j = 0; j < InventoryData.Length; j++) { InventoryData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -45791,6 +46198,8 @@ public override int Length public AgentDataBlock AgentData; public InventoryDataBlock[] InventoryData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public RemoveInventoryItemPacket() { HasVariableBlocks = true; @@ -45799,6 +46208,7 @@ public RemoveInventoryItemPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 270; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); InventoryData = null; } @@ -45831,11 +46241,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public RemoveInventoryItemPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -45861,7 +46270,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)InventoryData.Length; + Utils.ByteToBytes((byte)InventoryData.Length, bytes, ref i); for (int j = 0; j < InventoryData.Length; j++) { InventoryData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -46029,6 +46438,8 @@ public override int Length public AgentDataBlock AgentData; public InventoryDataBlock[] InventoryData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ChangeInventoryItemFlagsPacket() { HasVariableBlocks = true; @@ -46037,6 +46448,7 @@ public ChangeInventoryItemFlagsPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 271; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); InventoryData = null; } @@ -46069,11 +46481,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ChangeInventoryItemFlagsPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -46099,7 +46510,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)InventoryData.Length; + Utils.ByteToBytes((byte)InventoryData.Length, bytes, ref i); for (int j = 0; j < InventoryData.Length; j++) { InventoryData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -46271,6 +46682,7 @@ public SaveAssetIntoInventoryPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 272; Header.Reliable = true; + NeedValidateIDs = false; AgentData = new AgentDataBlock(); InventoryData = new InventoryDataBlock(); } @@ -46295,11 +46707,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public SaveAssetIntoInventoryPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -46402,8 +46813,8 @@ public override void FromBytes(byte[] bytes, ref int i) { FolderID.FromBytes(bytes, i); i += 16; ParentID.FromBytes(bytes, i); i += 16; - Type = (sbyte)bytes[i++]; - length = bytes[i++]; + Type = (sbyte)Utils.BytesToByte(bytes, ref i); + length = Utils.BytesToByte(bytes, ref i); Name = new byte[length]; Buffer.BlockCopy(bytes, i, Name, 0, length); i += length; } @@ -46417,8 +46828,8 @@ public override void ToBytes(byte[] bytes, ref int i) { FolderID.ToBytes(bytes, i); i += 16; ParentID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)Type; - bytes[i++] = (byte)Name.Length; + Utils.ByteToBytes( (byte)Type, bytes, ref i); + Utils.ByteToBytes((byte)Name.Length, bytes, ref i); Buffer.BlockCopy(Name, 0, bytes, i, Name.Length); i += Name.Length; } @@ -46437,6 +46848,8 @@ public override int Length public AgentDataBlock AgentData; public FolderDataBlock FolderData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public CreateInventoryFolderPacket() { HasVariableBlocks = false; @@ -46445,6 +46858,7 @@ public CreateInventoryFolderPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 273; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); FolderData = new FolderDataBlock(); } @@ -46469,11 +46883,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public CreateInventoryFolderPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -46576,8 +46989,8 @@ public override void FromBytes(byte[] bytes, ref int i) { FolderID.FromBytes(bytes, i); i += 16; ParentID.FromBytes(bytes, i); i += 16; - Type = (sbyte)bytes[i++]; - length = bytes[i++]; + Type = (sbyte)Utils.BytesToByte(bytes, ref i); + length = Utils.BytesToByte(bytes, ref i); Name = new byte[length]; Buffer.BlockCopy(bytes, i, Name, 0, length); i += length; } @@ -46591,8 +47004,8 @@ public override void ToBytes(byte[] bytes, ref int i) { FolderID.ToBytes(bytes, i); i += 16; ParentID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)Type; - bytes[i++] = (byte)Name.Length; + Utils.ByteToBytes( (byte)Type, bytes, ref i); + Utils.ByteToBytes((byte)Name.Length, bytes, ref i); Buffer.BlockCopy(Name, 0, bytes, i, Name.Length); i += Name.Length; } @@ -46612,6 +47025,8 @@ public override int Length public AgentDataBlock AgentData; public FolderDataBlock[] FolderData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public UpdateInventoryFolderPacket() { HasVariableBlocks = true; @@ -46620,6 +47035,7 @@ public UpdateInventoryFolderPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 274; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); FolderData = null; } @@ -46652,11 +47068,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public UpdateInventoryFolderPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -46682,7 +47097,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)FolderData.Length; + Utils.ByteToBytes((byte)FolderData.Length, bytes, ref i); for (int j = 0; j < FolderData.Length; j++) { FolderData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -46781,7 +47196,7 @@ public override void FromBytes(byte[] bytes, ref int i) { AgentID.FromBytes(bytes, i); i += 16; SessionID.FromBytes(bytes, i); i += 16; - Stamp = (bytes[i++] != 0) ? (bool)true : (bool)false; + Stamp = (Utils.BytesToByte(bytes, ref i) != 0); } catch (Exception) { @@ -46793,7 +47208,7 @@ public override void ToBytes(byte[] bytes, ref int i) { AgentID.ToBytes(bytes, i); i += 16; SessionID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)((Stamp) ? 1 : 0); + Utils.ByteToBytes((byte)((Stamp) ? 1 : 0), bytes, ref i); } } @@ -46853,6 +47268,8 @@ public override int Length public AgentDataBlock AgentData; public InventoryDataBlock[] InventoryData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public MoveInventoryFolderPacket() { HasVariableBlocks = true; @@ -46861,6 +47278,7 @@ public MoveInventoryFolderPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 275; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); InventoryData = null; @@ -46894,11 +47312,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public MoveInventoryFolderPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -46924,7 +47341,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)InventoryData.Length; + Utils.ByteToBytes((byte)InventoryData.Length, bytes, ref i); for (int j = 0; j < InventoryData.Length; j++) { InventoryData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -47089,6 +47506,8 @@ public override int Length public AgentDataBlock AgentData; public FolderDataBlock[] FolderData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public RemoveInventoryFolderPacket() { HasVariableBlocks = true; @@ -47097,6 +47516,7 @@ public RemoveInventoryFolderPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 276; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); FolderData = null; } @@ -47129,11 +47549,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public RemoveInventoryFolderPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -47159,7 +47578,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)FolderData.Length; + Utils.ByteToBytes((byte)FolderData.Length, bytes, ref i); for (int j = 0; j < FolderData.Length; j++) { FolderData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -47302,8 +47721,8 @@ public override void FromBytes(byte[] bytes, ref int i) FolderID.FromBytes(bytes, i); i += 16; OwnerID.FromBytes(bytes, i); i += 16; SortOrder = Utils.BytesToIntSafepos(bytes, i); i += 4; - FetchFolders = (bytes[i++] != 0) ? (bool)true : (bool)false; - FetchItems = (bytes[i++] != 0) ? (bool)true : (bool)false; + FetchFolders = (Utils.BytesToByte(bytes, ref i) != 0); + FetchItems = (Utils.BytesToByte(bytes, ref i) != 0); } catch (Exception) { @@ -47316,8 +47735,8 @@ public override void ToBytes(byte[] bytes, ref int i) FolderID.ToBytes(bytes, i); i += 16; OwnerID.ToBytes(bytes, i); i += 16; Utils.IntToBytesSafepos(SortOrder, bytes, i); i += 4; - bytes[i++] = (byte)((FetchFolders) ? 1 : 0); - bytes[i++] = (byte)((FetchItems) ? 1 : 0); + Utils.ByteToBytes((byte)((FetchFolders) ? 1 : 0), bytes, ref i); + Utils.ByteToBytes((byte)((FetchItems) ? 1 : 0), bytes, ref i); } } @@ -47335,6 +47754,8 @@ public override int Length public AgentDataBlock AgentData; public InventoryDataBlock InventoryData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public FetchInventoryDescendentsPacket() { HasVariableBlocks = false; @@ -47343,6 +47764,7 @@ public FetchInventoryDescendentsPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 277; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); InventoryData = new InventoryDataBlock(); @@ -47368,11 +47790,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public FetchInventoryDescendentsPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -47484,8 +47905,8 @@ public override void FromBytes(byte[] bytes, ref int i) { FolderID.FromBytes(bytes, i); i += 16; ParentID.FromBytes(bytes, i); i += 16; - Type = (sbyte)bytes[i++]; - length = bytes[i++]; + Type = (sbyte)Utils.BytesToByte(bytes, ref i); + length = Utils.BytesToByte(bytes, ref i); Name = new byte[length]; Buffer.BlockCopy(bytes, i, Name, 0, length); i += length; } @@ -47499,8 +47920,8 @@ public override void ToBytes(byte[] bytes, ref int i) { FolderID.ToBytes(bytes, i); i += 16; ParentID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)Type; - bytes[i++] = (byte)Name.Length; + Utils.ByteToBytes( (byte)Type, bytes, ref i); + Utils.ByteToBytes((byte)Name.Length, bytes, ref i); Buffer.BlockCopy(Name, 0, bytes, i, Name.Length); i += Name.Length; } @@ -47563,17 +47984,17 @@ public override void FromBytes(byte[] bytes, ref int i) GroupMask = Utils.BytesToUIntSafepos(bytes, i); i += 4; EveryoneMask = Utils.BytesToUIntSafepos(bytes, i); i += 4; NextOwnerMask = Utils.BytesToUIntSafepos(bytes, i); i += 4; - GroupOwned = (bytes[i++] != 0) ? (bool)true : (bool)false; + GroupOwned = (Utils.BytesToByte(bytes, ref i) != 0); AssetID.FromBytes(bytes, i); i += 16; - Type = (sbyte)bytes[i++]; - InvType = (sbyte)bytes[i++]; + Type = (sbyte)Utils.BytesToByte(bytes, ref i); + InvType = (sbyte)Utils.BytesToByte(bytes, ref i); Flags = Utils.BytesToUIntSafepos(bytes, i); i += 4; - SaleType = (byte)bytes[i++]; + SaleType = Utils.BytesToByte(bytes, ref i); SalePrice = Utils.BytesToIntSafepos(bytes, i); i += 4; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Name = new byte[length]; Buffer.BlockCopy(bytes, i, Name, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Description = new byte[length]; Buffer.BlockCopy(bytes, i, Description, 0, length); i += length; CreationDate = Utils.BytesToIntSafepos(bytes, i); i += 4; @@ -47597,16 +48018,16 @@ public override void ToBytes(byte[] bytes, ref int i) Utils.UIntToBytesSafepos(GroupMask, bytes, i); i += 4; Utils.UIntToBytesSafepos(EveryoneMask, bytes, i); i += 4; Utils.UIntToBytesSafepos(NextOwnerMask, bytes, i); i += 4; - bytes[i++] = (byte)((GroupOwned) ? 1 : 0); + Utils.ByteToBytes((byte)((GroupOwned) ? 1 : 0), bytes, ref i); AssetID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)Type; - bytes[i++] = (byte)InvType; + Utils.ByteToBytes( (byte)Type, bytes, ref i); + Utils.ByteToBytes( (byte)InvType, bytes, ref i); Utils.UIntToBytesSafepos(Flags, bytes, i); i += 4; - bytes[i++] = SaleType; + Utils.ByteToBytes( SaleType, bytes, ref i); Utils.IntToBytesSafepos(SalePrice, bytes, i); i += 4; - bytes[i++] = (byte)Name.Length; + Utils.ByteToBytes((byte)Name.Length, bytes, ref i); Buffer.BlockCopy(Name, 0, bytes, i, Name.Length); i += Name.Length; - bytes[i++] = (byte)Description.Length; + Utils.ByteToBytes((byte)Description.Length, bytes, ref i); Buffer.BlockCopy(Description, 0, bytes, i, Description.Length); i += Description.Length; Utils.IntToBytesSafepos(CreationDate, bytes, i); i += 4; Utils.UIntToBytesSafepos(CRC, bytes, i); i += 4; @@ -47639,6 +48060,7 @@ public InventoryDescendentsPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 278; Header.Reliable = true; + NeedValidateIDs = false; Header.Zerocoded = true; AgentData = new AgentDataBlock(); FolderData = null; @@ -47682,11 +48104,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public InventoryDescendentsPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -47723,9 +48144,9 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)FolderData.Length; + Utils.ByteToBytes((byte)FolderData.Length, bytes, ref i); for (int j = 0; j < FolderData.Length; j++) { FolderData[j].ToBytes(bytes, ref i); } - bytes[i++] = (byte)ItemData.Length; + Utils.ByteToBytes((byte)ItemData.Length, bytes, ref i); for (int j = 0; j < ItemData.Length; j++) { ItemData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -47913,6 +48334,8 @@ public override int Length public AgentDataBlock AgentData; public InventoryDataBlock[] InventoryData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public FetchInventoryPacket() { HasVariableBlocks = true; @@ -47921,6 +48344,7 @@ public FetchInventoryPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 279; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); InventoryData = null; @@ -47954,11 +48378,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public FetchInventoryPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -47984,7 +48407,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)InventoryData.Length; + Utils.ByteToBytes((byte)InventoryData.Length, bytes, ref i); for (int j = 0; j < InventoryData.Length; j++) { InventoryData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -48151,17 +48574,17 @@ public override void FromBytes(byte[] bytes, ref int i) GroupMask = Utils.BytesToUIntSafepos(bytes, i); i += 4; EveryoneMask = Utils.BytesToUIntSafepos(bytes, i); i += 4; NextOwnerMask = Utils.BytesToUIntSafepos(bytes, i); i += 4; - GroupOwned = (bytes[i++] != 0) ? (bool)true : (bool)false; + GroupOwned = (Utils.BytesToByte(bytes, ref i) != 0); AssetID.FromBytes(bytes, i); i += 16; - Type = (sbyte)bytes[i++]; - InvType = (sbyte)bytes[i++]; + Type = (sbyte)Utils.BytesToByte(bytes, ref i); + InvType = (sbyte)Utils.BytesToByte(bytes, ref i); Flags = Utils.BytesToUIntSafepos(bytes, i); i += 4; - SaleType = (byte)bytes[i++]; + SaleType = Utils.BytesToByte(bytes, ref i); SalePrice = Utils.BytesToIntSafepos(bytes, i); i += 4; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Name = new byte[length]; Buffer.BlockCopy(bytes, i, Name, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Description = new byte[length]; Buffer.BlockCopy(bytes, i, Description, 0, length); i += length; CreationDate = Utils.BytesToIntSafepos(bytes, i); i += 4; @@ -48185,16 +48608,16 @@ public override void ToBytes(byte[] bytes, ref int i) Utils.UIntToBytesSafepos(GroupMask, bytes, i); i += 4; Utils.UIntToBytesSafepos(EveryoneMask, bytes, i); i += 4; Utils.UIntToBytesSafepos(NextOwnerMask, bytes, i); i += 4; - bytes[i++] = (byte)((GroupOwned) ? 1 : 0); + Utils.ByteToBytes((byte)((GroupOwned) ? 1 : 0), bytes, ref i); AssetID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)Type; - bytes[i++] = (byte)InvType; + Utils.ByteToBytes( (byte)Type, bytes, ref i); + Utils.ByteToBytes( (byte)InvType, bytes, ref i); Utils.UIntToBytesSafepos(Flags, bytes, i); i += 4; - bytes[i++] = SaleType; + Utils.ByteToBytes( SaleType, bytes, ref i); Utils.IntToBytesSafepos(SalePrice, bytes, i); i += 4; - bytes[i++] = (byte)Name.Length; + Utils.ByteToBytes((byte)Name.Length, bytes, ref i); Buffer.BlockCopy(Name, 0, bytes, i, Name.Length); i += Name.Length; - bytes[i++] = (byte)Description.Length; + Utils.ByteToBytes((byte)Description.Length, bytes, ref i); Buffer.BlockCopy(Description, 0, bytes, i, Description.Length); i += Description.Length; Utils.IntToBytesSafepos(CreationDate, bytes, i); i += 4; Utils.UIntToBytesSafepos(CRC, bytes, i); i += 4; @@ -48224,6 +48647,7 @@ public FetchInventoryReplyPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 280; Header.Reliable = true; + NeedValidateIDs = false; Header.Zerocoded = true; AgentData = new AgentDataBlock(); InventoryData = null; @@ -48257,11 +48681,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public FetchInventoryReplyPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -48287,7 +48710,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)InventoryData.Length; + Utils.ByteToBytes((byte)InventoryData.Length, bytes, ref i); for (int j = 0; j < InventoryData.Length; j++) { InventoryData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -48431,8 +48854,8 @@ public override void FromBytes(byte[] bytes, ref int i) { FolderID.FromBytes(bytes, i); i += 16; ParentID.FromBytes(bytes, i); i += 16; - Type = (sbyte)bytes[i++]; - length = bytes[i++]; + Type = (sbyte)Utils.BytesToByte(bytes, ref i); + length = Utils.BytesToByte(bytes, ref i); Name = new byte[length]; Buffer.BlockCopy(bytes, i, Name, 0, length); i += length; } @@ -48446,8 +48869,8 @@ public override void ToBytes(byte[] bytes, ref int i) { FolderID.ToBytes(bytes, i); i += 16; ParentID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)Type; - bytes[i++] = (byte)Name.Length; + Utils.ByteToBytes( (byte)Type, bytes, ref i); + Utils.ByteToBytes((byte)Name.Length, bytes, ref i); Buffer.BlockCopy(Name, 0, bytes, i, Name.Length); i += Name.Length; } @@ -48512,17 +48935,17 @@ public override void FromBytes(byte[] bytes, ref int i) GroupMask = Utils.BytesToUIntSafepos(bytes, i); i += 4; EveryoneMask = Utils.BytesToUIntSafepos(bytes, i); i += 4; NextOwnerMask = Utils.BytesToUIntSafepos(bytes, i); i += 4; - GroupOwned = (bytes[i++] != 0) ? (bool)true : (bool)false; + GroupOwned = (Utils.BytesToByte(bytes, ref i) != 0); AssetID.FromBytes(bytes, i); i += 16; - Type = (sbyte)bytes[i++]; - InvType = (sbyte)bytes[i++]; + Type = (sbyte)Utils.BytesToByte(bytes, ref i); + InvType = (sbyte)Utils.BytesToByte(bytes, ref i); Flags = Utils.BytesToUIntSafepos(bytes, i); i += 4; - SaleType = (byte)bytes[i++]; + SaleType = Utils.BytesToByte(bytes, ref i); SalePrice = Utils.BytesToIntSafepos(bytes, i); i += 4; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Name = new byte[length]; Buffer.BlockCopy(bytes, i, Name, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Description = new byte[length]; Buffer.BlockCopy(bytes, i, Description, 0, length); i += length; CreationDate = Utils.BytesToIntSafepos(bytes, i); i += 4; @@ -48547,16 +48970,16 @@ public override void ToBytes(byte[] bytes, ref int i) Utils.UIntToBytesSafepos(GroupMask, bytes, i); i += 4; Utils.UIntToBytesSafepos(EveryoneMask, bytes, i); i += 4; Utils.UIntToBytesSafepos(NextOwnerMask, bytes, i); i += 4; - bytes[i++] = (byte)((GroupOwned) ? 1 : 0); + Utils.ByteToBytes((byte)((GroupOwned) ? 1 : 0), bytes, ref i); AssetID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)Type; - bytes[i++] = (byte)InvType; + Utils.ByteToBytes( (byte)Type, bytes, ref i); + Utils.ByteToBytes( (byte)InvType, bytes, ref i); Utils.UIntToBytesSafepos(Flags, bytes, i); i += 4; - bytes[i++] = SaleType; + Utils.ByteToBytes( SaleType, bytes, ref i); Utils.IntToBytesSafepos(SalePrice, bytes, i); i += 4; - bytes[i++] = (byte)Name.Length; + Utils.ByteToBytes((byte)Name.Length, bytes, ref i); Buffer.BlockCopy(Name, 0, bytes, i, Name.Length); i += Name.Length; - bytes[i++] = (byte)Description.Length; + Utils.ByteToBytes((byte)Description.Length, bytes, ref i); Buffer.BlockCopy(Description, 0, bytes, i, Description.Length); i += Description.Length; Utils.IntToBytesSafepos(CreationDate, bytes, i); i += 4; Utils.UIntToBytesSafepos(CRC, bytes, i); i += 4; @@ -48589,6 +49012,7 @@ public BulkUpdateInventoryPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 281; Header.Reliable = true; + NeedValidateIDs = false; Header.Zerocoded = true; AgentData = new AgentDataBlock(); FolderData = null; @@ -48632,11 +49056,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public BulkUpdateInventoryPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -48673,9 +49096,9 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)FolderData.Length; + Utils.ByteToBytes((byte)FolderData.Length, bytes, ref i); for (int j = 0; j < FolderData.Length; j++) { FolderData[j].ToBytes(bytes, ref i); } - bytes[i++] = (byte)ItemData.Length; + Utils.ByteToBytes((byte)ItemData.Length, bytes, ref i); for (int j = 0; j < ItemData.Length; j++) { ItemData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -48901,6 +49324,8 @@ public override int Length public FolderDataBlock[] FolderData; public ItemDataBlock[] ItemData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public RemoveInventoryObjectsPacket() { HasVariableBlocks = true; @@ -48909,6 +49334,7 @@ public RemoveInventoryObjectsPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 284; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); FolderData = null; ItemData = null; @@ -48951,11 +49377,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public RemoveInventoryObjectsPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -48992,9 +49417,9 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)FolderData.Length; + Utils.ByteToBytes((byte)FolderData.Length, bytes, ref i); for (int j = 0; j < FolderData.Length; j++) { FolderData[j].ToBytes(bytes, ref i); } - bytes[i++] = (byte)ItemData.Length; + Utils.ByteToBytes((byte)ItemData.Length, bytes, ref i); for (int j = 0; j < ItemData.Length; j++) { ItemData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -49178,6 +49603,8 @@ public override int Length public AgentDataBlock AgentData; public InventoryDataBlock InventoryData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public PurgeInventoryDescendentsPacket() { HasVariableBlocks = false; @@ -49186,6 +49613,7 @@ public PurgeInventoryDescendentsPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 285; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); InventoryData = new InventoryDataBlock(); @@ -49211,11 +49639,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public PurgeInventoryDescendentsPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -49312,7 +49739,7 @@ public override void FromBytes(byte[] bytes, ref int i) try { LocalID = Utils.BytesToUIntSafepos(bytes, i); i += 4; - Key = (byte)bytes[i++]; + Key = Utils.BytesToByte(bytes, ref i); } catch (Exception) { @@ -49323,7 +49750,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { Utils.UIntToBytesSafepos(LocalID, bytes, i); i += 4; - bytes[i++] = Key; + Utils.ByteToBytes( Key, bytes, ref i); } } @@ -49385,17 +49812,17 @@ public override void FromBytes(byte[] bytes, ref int i) GroupMask = Utils.BytesToUIntSafepos(bytes, i); i += 4; EveryoneMask = Utils.BytesToUIntSafepos(bytes, i); i += 4; NextOwnerMask = Utils.BytesToUIntSafepos(bytes, i); i += 4; - GroupOwned = (bytes[i++] != 0) ? (bool)true : (bool)false; + GroupOwned = (Utils.BytesToByte(bytes, ref i) != 0); TransactionID.FromBytes(bytes, i); i += 16; - Type = (sbyte)bytes[i++]; - InvType = (sbyte)bytes[i++]; + Type = (sbyte)Utils.BytesToByte(bytes, ref i); + InvType = (sbyte)Utils.BytesToByte(bytes, ref i); Flags = Utils.BytesToUIntSafepos(bytes, i); i += 4; - SaleType = (byte)bytes[i++]; + SaleType = Utils.BytesToByte(bytes, ref i); SalePrice = Utils.BytesToIntSafepos(bytes, i); i += 4; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Name = new byte[length]; Buffer.BlockCopy(bytes, i, Name, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Description = new byte[length]; Buffer.BlockCopy(bytes, i, Description, 0, length); i += length; CreationDate = Utils.BytesToIntSafepos(bytes, i); i += 4; @@ -49419,16 +49846,16 @@ public override void ToBytes(byte[] bytes, ref int i) Utils.UIntToBytesSafepos(GroupMask, bytes, i); i += 4; Utils.UIntToBytesSafepos(EveryoneMask, bytes, i); i += 4; Utils.UIntToBytesSafepos(NextOwnerMask, bytes, i); i += 4; - bytes[i++] = (byte)((GroupOwned) ? 1 : 0); + Utils.ByteToBytes((byte)((GroupOwned) ? 1 : 0), bytes, ref i); TransactionID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)Type; - bytes[i++] = (byte)InvType; + Utils.ByteToBytes( (byte)Type, bytes, ref i); + Utils.ByteToBytes( (byte)InvType, bytes, ref i); Utils.UIntToBytesSafepos(Flags, bytes, i); i += 4; - bytes[i++] = SaleType; + Utils.ByteToBytes( SaleType, bytes, ref i); Utils.IntToBytesSafepos(SalePrice, bytes, i); i += 4; - bytes[i++] = (byte)Name.Length; + Utils.ByteToBytes((byte)Name.Length, bytes, ref i); Buffer.BlockCopy(Name, 0, bytes, i, Name.Length); i += Name.Length; - bytes[i++] = (byte)Description.Length; + Utils.ByteToBytes((byte)Description.Length, bytes, ref i); Buffer.BlockCopy(Description, 0, bytes, i, Description.Length); i += Description.Length; Utils.IntToBytesSafepos(CreationDate, bytes, i); i += 4; Utils.UIntToBytesSafepos(CRC, bytes, i); i += 4; @@ -49451,6 +49878,8 @@ public override int Length public UpdateDataBlock UpdateData; public InventoryDataBlock InventoryData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public UpdateTaskInventoryPacket() { HasVariableBlocks = false; @@ -49459,6 +49888,7 @@ public UpdateTaskInventoryPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 286; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); UpdateData = new UpdateDataBlock(); @@ -49486,11 +49916,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public UpdateTaskInventoryPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -49619,6 +50048,8 @@ public override int Length public AgentDataBlock AgentData; public InventoryDataBlock InventoryData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public RemoveTaskInventoryPacket() { HasVariableBlocks = false; @@ -49627,6 +50058,7 @@ public RemoveTaskInventoryPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 287; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); InventoryData = new InventoryDataBlock(); @@ -49652,11 +50084,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public RemoveTaskInventoryPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -49785,6 +50216,8 @@ public override int Length public AgentDataBlock AgentData; public InventoryDataBlock InventoryData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public MoveTaskInventoryPacket() { HasVariableBlocks = false; @@ -49793,6 +50226,7 @@ public MoveTaskInventoryPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 288; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); InventoryData = new InventoryDataBlock(); } @@ -49817,11 +50251,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public MoveTaskInventoryPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -49944,6 +50377,8 @@ public override int Length public AgentDataBlock AgentData; public InventoryDataBlock InventoryData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public RequestTaskInventoryPacket() { HasVariableBlocks = false; @@ -49952,6 +50387,7 @@ public RequestTaskInventoryPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 289; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); InventoryData = new InventoryDataBlock(); } @@ -49976,11 +50412,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public RequestTaskInventoryPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -50041,7 +50476,7 @@ public override void FromBytes(byte[] bytes, ref int i) { TaskID.FromBytes(bytes, i); i += 16; Serial = Utils.BytesToInt16(bytes, i); i += 2; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Filename = new byte[length]; Buffer.BlockCopy(bytes, i, Filename, 0, length); i += length; } @@ -50055,7 +50490,7 @@ public override void ToBytes(byte[] bytes, ref int i) { TaskID.ToBytes(bytes, i); i += 16; Utils.Int16ToBytes(Serial, bytes, i); i += 2; - bytes[i++] = (byte)Filename.Length; + Utils.ByteToBytes((byte)Filename.Length, bytes, ref i); Buffer.BlockCopy(Filename, 0, bytes, i, Filename.Length); i += Filename.Length; } @@ -50080,6 +50515,7 @@ public ReplyTaskInventoryPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 290; Header.Reliable = true; + NeedValidateIDs = false; Header.Zerocoded = true; InventoryData = new InventoryDataBlock(); } @@ -50103,11 +50539,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ReplyTaskInventoryPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; InventoryData.FromBytes(bytes, ref i); @@ -50205,11 +50640,11 @@ public override void FromBytes(byte[] bytes, ref int i) try { GroupID.FromBytes(bytes, i); i += 16; - Destination = (byte)bytes[i++]; + Destination = Utils.BytesToByte(bytes, ref i); DestinationID.FromBytes(bytes, i); i += 16; TransactionID.FromBytes(bytes, i); i += 16; - PacketCount = (byte)bytes[i++]; - PacketNumber = (byte)bytes[i++]; + PacketCount = Utils.BytesToByte(bytes, ref i); + PacketNumber = Utils.BytesToByte(bytes, ref i); } catch (Exception) { @@ -50220,11 +50655,11 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { GroupID.ToBytes(bytes, i); i += 16; - bytes[i++] = Destination; + Utils.ByteToBytes( Destination, bytes, ref i); DestinationID.ToBytes(bytes, i); i += 16; TransactionID.ToBytes(bytes, i); i += 16; - bytes[i++] = PacketCount; - bytes[i++] = PacketNumber; + Utils.ByteToBytes( PacketCount, bytes, ref i); + Utils.ByteToBytes( PacketNumber, bytes, ref i); } } @@ -50283,6 +50718,8 @@ public override int Length public AgentBlockBlock AgentBlock; public ObjectDataBlock[] ObjectData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public DeRezObjectPacket() { HasVariableBlocks = true; @@ -50291,6 +50728,7 @@ public DeRezObjectPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 291; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); AgentBlock = new AgentBlockBlock(); @@ -50326,11 +50764,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public DeRezObjectPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -50359,7 +50796,7 @@ public override byte[] ToBytes() Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); AgentBlock.ToBytes(bytes, ref i); - bytes[i++] = (byte)ObjectData.Length; + Utils.ByteToBytes((byte)ObjectData.Length, bytes, ref i); for (int j = 0; j < ObjectData.Length; j++) { ObjectData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -50458,7 +50895,7 @@ public override void FromBytes(byte[] bytes, ref int i) try { TransactionID.FromBytes(bytes, i); i += 16; - Success = (bytes[i++] != 0) ? (bool)true : (bool)false; + Success = (Utils.BytesToByte(bytes, ref i) != 0); } catch (Exception) { @@ -50469,7 +50906,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { TransactionID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)((Success) ? 1 : 0); + Utils.ByteToBytes((byte)((Success) ? 1 : 0), bytes, ref i); } } @@ -50493,6 +50930,7 @@ public DeRezAckPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 292; Header.Reliable = true; + NeedValidateIDs = false; TransactionData = new TransactionDataBlock(); } @@ -50515,11 +50953,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public DeRezAckPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; TransactionData.FromBytes(bytes, ref i); @@ -50626,13 +51063,13 @@ public override void FromBytes(byte[] bytes, ref int i) try { FromTaskID.FromBytes(bytes, i); i += 16; - BypassRaycast = (byte)bytes[i++]; + BypassRaycast = Utils.BytesToByte(bytes, ref i); RayStart.FromBytes(bytes, i); i += 12; RayEnd.FromBytes(bytes, i); i += 12; RayTargetID.FromBytes(bytes, i); i += 16; - RayEndIsIntersection = (bytes[i++] != 0) ? (bool)true : (bool)false; - RezSelected = (bytes[i++] != 0) ? (bool)true : (bool)false; - RemoveItem = (bytes[i++] != 0) ? (bool)true : (bool)false; + RayEndIsIntersection = (Utils.BytesToByte(bytes, ref i) != 0); + RezSelected = (Utils.BytesToByte(bytes, ref i) != 0); + RemoveItem = (Utils.BytesToByte(bytes, ref i) != 0); ItemFlags = Utils.BytesToUIntSafepos(bytes, i); i += 4; GroupMask = Utils.BytesToUIntSafepos(bytes, i); i += 4; EveryoneMask = Utils.BytesToUIntSafepos(bytes, i); i += 4; @@ -50647,13 +51084,13 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { FromTaskID.ToBytes(bytes, i); i += 16; - bytes[i++] = BypassRaycast; + Utils.ByteToBytes( BypassRaycast, bytes, ref i); RayStart.ToBytes(bytes, i); i += 12; RayEnd.ToBytes(bytes, i); i += 12; RayTargetID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)((RayEndIsIntersection) ? 1 : 0); - bytes[i++] = (byte)((RezSelected) ? 1 : 0); - bytes[i++] = (byte)((RemoveItem) ? 1 : 0); + Utils.ByteToBytes((byte)((RayEndIsIntersection) ? 1 : 0), bytes, ref i); + Utils.ByteToBytes((byte)((RezSelected) ? 1 : 0), bytes, ref i); + Utils.ByteToBytes((byte)((RemoveItem) ? 1 : 0), bytes, ref i); Utils.UIntToBytesSafepos(ItemFlags, bytes, i); i += 4; Utils.UIntToBytesSafepos(GroupMask, bytes, i); i += 4; Utils.UIntToBytesSafepos(EveryoneMask, bytes, i); i += 4; @@ -50719,17 +51156,17 @@ public override void FromBytes(byte[] bytes, ref int i) GroupMask = Utils.BytesToUIntSafepos(bytes, i); i += 4; EveryoneMask = Utils.BytesToUIntSafepos(bytes, i); i += 4; NextOwnerMask = Utils.BytesToUIntSafepos(bytes, i); i += 4; - GroupOwned = (bytes[i++] != 0) ? (bool)true : (bool)false; + GroupOwned = (Utils.BytesToByte(bytes, ref i) != 0); TransactionID.FromBytes(bytes, i); i += 16; - Type = (sbyte)bytes[i++]; - InvType = (sbyte)bytes[i++]; + Type = (sbyte)Utils.BytesToByte(bytes, ref i); + InvType = (sbyte)Utils.BytesToByte(bytes, ref i); Flags = Utils.BytesToUIntSafepos(bytes, i); i += 4; - SaleType = (byte)bytes[i++]; + SaleType = Utils.BytesToByte(bytes, ref i); SalePrice = Utils.BytesToIntSafepos(bytes, i); i += 4; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Name = new byte[length]; Buffer.BlockCopy(bytes, i, Name, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Description = new byte[length]; Buffer.BlockCopy(bytes, i, Description, 0, length); i += length; CreationDate = Utils.BytesToIntSafepos(bytes, i); i += 4; @@ -50753,16 +51190,16 @@ public override void ToBytes(byte[] bytes, ref int i) Utils.UIntToBytesSafepos(GroupMask, bytes, i); i += 4; Utils.UIntToBytesSafepos(EveryoneMask, bytes, i); i += 4; Utils.UIntToBytesSafepos(NextOwnerMask, bytes, i); i += 4; - bytes[i++] = (byte)((GroupOwned) ? 1 : 0); + Utils.ByteToBytes((byte)((GroupOwned) ? 1 : 0), bytes, ref i); TransactionID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)Type; - bytes[i++] = (byte)InvType; + Utils.ByteToBytes( (byte)Type, bytes, ref i); + Utils.ByteToBytes( (byte)InvType, bytes, ref i); Utils.UIntToBytesSafepos(Flags, bytes, i); i += 4; - bytes[i++] = SaleType; + Utils.ByteToBytes( SaleType, bytes, ref i); Utils.IntToBytesSafepos(SalePrice, bytes, i); i += 4; - bytes[i++] = (byte)Name.Length; + Utils.ByteToBytes((byte)Name.Length, bytes, ref i); Buffer.BlockCopy(Name, 0, bytes, i, Name.Length); i += Name.Length; - bytes[i++] = (byte)Description.Length; + Utils.ByteToBytes((byte)Description.Length, bytes, ref i); Buffer.BlockCopy(Description, 0, bytes, i, Description.Length); i += Description.Length; Utils.IntToBytesSafepos(CreationDate, bytes, i); i += 4; Utils.UIntToBytesSafepos(CRC, bytes, i); i += 4; @@ -50785,6 +51222,8 @@ public override int Length public RezDataBlock RezData; public InventoryDataBlock InventoryData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public RezObjectPacket() { HasVariableBlocks = false; @@ -50793,6 +51232,7 @@ public RezObjectPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 293; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); RezData = new RezDataBlock(); @@ -50820,11 +51260,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public RezObjectPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -50937,13 +51376,13 @@ public override void FromBytes(byte[] bytes, ref int i) try { FromTaskID.FromBytes(bytes, i); i += 16; - BypassRaycast = (byte)bytes[i++]; + BypassRaycast = Utils.BytesToByte(bytes, ref i); RayStart.FromBytes(bytes, i); i += 12; RayEnd.FromBytes(bytes, i); i += 12; RayTargetID.FromBytes(bytes, i); i += 16; - RayEndIsIntersection = (bytes[i++] != 0) ? (bool)true : (bool)false; - RezSelected = (bytes[i++] != 0) ? (bool)true : (bool)false; - RemoveItem = (bytes[i++] != 0) ? (bool)true : (bool)false; + RayEndIsIntersection = (Utils.BytesToByte(bytes, ref i) != 0); + RezSelected = (Utils.BytesToByte(bytes, ref i) != 0); + RemoveItem = (Utils.BytesToByte(bytes, ref i) != 0); ItemFlags = Utils.BytesToUIntSafepos(bytes, i); i += 4; GroupMask = Utils.BytesToUIntSafepos(bytes, i); i += 4; EveryoneMask = Utils.BytesToUIntSafepos(bytes, i); i += 4; @@ -50958,13 +51397,13 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { FromTaskID.ToBytes(bytes, i); i += 16; - bytes[i++] = BypassRaycast; + Utils.ByteToBytes( BypassRaycast, bytes, ref i); RayStart.ToBytes(bytes, i); i += 12; RayEnd.ToBytes(bytes, i); i += 12; RayTargetID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)((RayEndIsIntersection) ? 1 : 0); - bytes[i++] = (byte)((RezSelected) ? 1 : 0); - bytes[i++] = (byte)((RemoveItem) ? 1 : 0); + Utils.ByteToBytes((byte)((RayEndIsIntersection) ? 1 : 0), bytes, ref i); + Utils.ByteToBytes((byte)((RezSelected) ? 1 : 0), bytes, ref i); + Utils.ByteToBytes((byte)((RemoveItem) ? 1 : 0), bytes, ref i); Utils.UIntToBytesSafepos(ItemFlags, bytes, i); i += 4; Utils.UIntToBytesSafepos(GroupMask, bytes, i); i += 4; Utils.UIntToBytesSafepos(EveryoneMask, bytes, i); i += 4; @@ -51070,6 +51509,8 @@ public override int Length public NotecardDataBlock NotecardData; public InventoryDataBlock[] InventoryData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public RezObjectFromNotecardPacket() { HasVariableBlocks = true; @@ -51078,6 +51519,7 @@ public RezObjectFromNotecardPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 294; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); RezData = new RezDataBlock(); @@ -51115,11 +51557,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public RezObjectFromNotecardPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -51151,7 +51592,7 @@ public override byte[] ToBytes() AgentData.ToBytes(bytes, ref i); RezData.ToBytes(bytes, ref i); NotecardData.ToBytes(bytes, ref i); - bytes[i++] = (byte)InventoryData.Length; + Utils.ByteToBytes((byte)InventoryData.Length, bytes, ref i); for (int j = 0; j < InventoryData.Length; j++) { InventoryData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -51360,6 +51801,8 @@ public override int Length public TransactionBlockBlock TransactionBlock; public FolderDataBlock[] FolderData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public AcceptFriendshipPacket() { HasVariableBlocks = true; @@ -51368,6 +51811,7 @@ public AcceptFriendshipPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 297; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); TransactionBlock = new TransactionBlockBlock(); FolderData = null; @@ -51402,11 +51846,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public AcceptFriendshipPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -51435,7 +51878,7 @@ public override byte[] ToBytes() Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); TransactionBlock.ToBytes(bytes, ref i); - bytes[i++] = (byte)FolderData.Length; + Utils.ByteToBytes((byte)FolderData.Length, bytes, ref i); for (int j = 0; j < FolderData.Length; j++) { FolderData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -51601,6 +52044,8 @@ public override int Length public AgentDataBlock AgentData; public TransactionBlockBlock TransactionBlock; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public DeclineFriendshipPacket() { HasVariableBlocks = false; @@ -51609,6 +52054,7 @@ public DeclineFriendshipPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 298; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); TransactionBlock = new TransactionBlockBlock(); } @@ -51633,11 +52079,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public DeclineFriendshipPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -51760,6 +52205,8 @@ public override int Length public AgentDataBlock AgentData; public ExBlockBlock ExBlock; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public TerminateFriendshipPacket() { HasVariableBlocks = false; @@ -51768,6 +52215,7 @@ public TerminateFriendshipPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 300; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); ExBlock = new ExBlockBlock(); } @@ -51792,11 +52240,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public TerminateFriendshipPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -51922,6 +52369,8 @@ public override int Length public AgentDataBlock AgentData; public AgentBlockBlock AgentBlock; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public OfferCallingCardPacket() { HasVariableBlocks = false; @@ -51930,6 +52379,7 @@ public OfferCallingCardPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 301; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); AgentBlock = new AgentBlockBlock(); } @@ -51954,11 +52404,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public OfferCallingCardPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -52122,6 +52571,8 @@ public override int Length public TransactionBlockBlock TransactionBlock; public FolderDataBlock[] FolderData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public AcceptCallingCardPacket() { HasVariableBlocks = true; @@ -52130,6 +52581,7 @@ public AcceptCallingCardPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 302; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); TransactionBlock = new TransactionBlockBlock(); FolderData = null; @@ -52164,11 +52616,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public AcceptCallingCardPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -52197,7 +52648,7 @@ public override byte[] ToBytes() Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); TransactionBlock.ToBytes(bytes, ref i); - bytes[i++] = (byte)FolderData.Length; + Utils.ByteToBytes((byte)FolderData.Length, bytes, ref i); for (int j = 0; j < FolderData.Length; j++) { FolderData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -52363,6 +52814,8 @@ public override int Length public AgentDataBlock AgentData; public TransactionBlockBlock TransactionBlock; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public DeclineCallingCardPacket() { HasVariableBlocks = false; @@ -52371,6 +52824,7 @@ public DeclineCallingCardPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 303; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); TransactionBlock = new TransactionBlockBlock(); } @@ -52395,11 +52849,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public DeclineCallingCardPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -52499,7 +52952,7 @@ public override void FromBytes(byte[] bytes, ref int i) try { ObjectLocalID = Utils.BytesToUIntSafepos(bytes, i); i += 4; - Enabled = (bytes[i++] != 0) ? (bool)true : (bool)false; + Enabled = (Utils.BytesToByte(bytes, ref i) != 0); } catch (Exception) { @@ -52510,7 +52963,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { Utils.UIntToBytesSafepos(ObjectLocalID, bytes, i); i += 4; - bytes[i++] = (byte)((Enabled) ? 1 : 0); + Utils.ByteToBytes((byte)((Enabled) ? 1 : 0), bytes, ref i); } } @@ -52572,17 +53025,17 @@ public override void FromBytes(byte[] bytes, ref int i) GroupMask = Utils.BytesToUIntSafepos(bytes, i); i += 4; EveryoneMask = Utils.BytesToUIntSafepos(bytes, i); i += 4; NextOwnerMask = Utils.BytesToUIntSafepos(bytes, i); i += 4; - GroupOwned = (bytes[i++] != 0) ? (bool)true : (bool)false; + GroupOwned = (Utils.BytesToByte(bytes, ref i) != 0); TransactionID.FromBytes(bytes, i); i += 16; - Type = (sbyte)bytes[i++]; - InvType = (sbyte)bytes[i++]; + Type = (sbyte)Utils.BytesToByte(bytes, ref i); + InvType = (sbyte)Utils.BytesToByte(bytes, ref i); Flags = Utils.BytesToUIntSafepos(bytes, i); i += 4; - SaleType = (byte)bytes[i++]; + SaleType = Utils.BytesToByte(bytes, ref i); SalePrice = Utils.BytesToIntSafepos(bytes, i); i += 4; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Name = new byte[length]; Buffer.BlockCopy(bytes, i, Name, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Description = new byte[length]; Buffer.BlockCopy(bytes, i, Description, 0, length); i += length; CreationDate = Utils.BytesToIntSafepos(bytes, i); i += 4; @@ -52606,16 +53059,16 @@ public override void ToBytes(byte[] bytes, ref int i) Utils.UIntToBytesSafepos(GroupMask, bytes, i); i += 4; Utils.UIntToBytesSafepos(EveryoneMask, bytes, i); i += 4; Utils.UIntToBytesSafepos(NextOwnerMask, bytes, i); i += 4; - bytes[i++] = (byte)((GroupOwned) ? 1 : 0); + Utils.ByteToBytes((byte)((GroupOwned) ? 1 : 0), bytes, ref i); TransactionID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)Type; - bytes[i++] = (byte)InvType; + Utils.ByteToBytes( (byte)Type, bytes, ref i); + Utils.ByteToBytes( (byte)InvType, bytes, ref i); Utils.UIntToBytesSafepos(Flags, bytes, i); i += 4; - bytes[i++] = SaleType; + Utils.ByteToBytes( SaleType, bytes, ref i); Utils.IntToBytesSafepos(SalePrice, bytes, i); i += 4; - bytes[i++] = (byte)Name.Length; + Utils.ByteToBytes((byte)Name.Length, bytes, ref i); Buffer.BlockCopy(Name, 0, bytes, i, Name.Length); i += Name.Length; - bytes[i++] = (byte)Description.Length; + Utils.ByteToBytes((byte)Description.Length, bytes, ref i); Buffer.BlockCopy(Description, 0, bytes, i, Description.Length); i += Description.Length; Utils.IntToBytesSafepos(CreationDate, bytes, i); i += 4; Utils.UIntToBytesSafepos(CRC, bytes, i); i += 4; @@ -52638,6 +53091,8 @@ public override int Length public UpdateBlockBlock UpdateBlock; public InventoryBlockBlock InventoryBlock; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public RezScriptPacket() { HasVariableBlocks = false; @@ -52646,6 +53101,7 @@ public RezScriptPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 304; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); UpdateBlock = new UpdateBlockBlock(); @@ -52673,11 +53129,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public RezScriptPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -52791,13 +53246,13 @@ public override void FromBytes(byte[] bytes, ref int i) FolderID.FromBytes(bytes, i); i += 16; TransactionID.FromBytes(bytes, i); i += 16; NextOwnerMask = Utils.BytesToUIntSafepos(bytes, i); i += 4; - Type = (sbyte)bytes[i++]; - InvType = (sbyte)bytes[i++]; - WearableType = (byte)bytes[i++]; - length = bytes[i++]; + Type = (sbyte)Utils.BytesToByte(bytes, ref i); + InvType = (sbyte)Utils.BytesToByte(bytes, ref i); + WearableType = Utils.BytesToByte(bytes, ref i); + length = Utils.BytesToByte(bytes, ref i); Name = new byte[length]; Buffer.BlockCopy(bytes, i, Name, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Description = new byte[length]; Buffer.BlockCopy(bytes, i, Description, 0, length); i += length; } @@ -52813,12 +53268,12 @@ public override void ToBytes(byte[] bytes, ref int i) FolderID.ToBytes(bytes, i); i += 16; TransactionID.ToBytes(bytes, i); i += 16; Utils.UIntToBytesSafepos(NextOwnerMask, bytes, i); i += 4; - bytes[i++] = (byte)Type; - bytes[i++] = (byte)InvType; - bytes[i++] = WearableType; - bytes[i++] = (byte)Name.Length; + Utils.ByteToBytes( (byte)Type, bytes, ref i); + Utils.ByteToBytes( (byte)InvType, bytes, ref i); + Utils.ByteToBytes( WearableType, bytes, ref i); + Utils.ByteToBytes((byte)Name.Length, bytes, ref i); Buffer.BlockCopy(Name, 0, bytes, i, Name.Length); i += Name.Length; - bytes[i++] = (byte)Description.Length; + Utils.ByteToBytes((byte)Description.Length, bytes, ref i); Buffer.BlockCopy(Description, 0, bytes, i, Description.Length); i += Description.Length; } @@ -52837,6 +53292,8 @@ public override int Length public AgentDataBlock AgentData; public InventoryBlockBlock InventoryBlock; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public CreateInventoryItemPacket() { HasVariableBlocks = false; @@ -52845,6 +53302,7 @@ public CreateInventoryItemPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 305; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); InventoryBlock = new InventoryBlockBlock(); @@ -52870,11 +53328,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public CreateInventoryItemPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -53012,7 +53469,7 @@ public override void FromBytes(byte[] bytes, ref int i) try { FolderID.FromBytes(bytes, i); i += 16; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Name = new byte[length]; Buffer.BlockCopy(bytes, i, Name, 0, length); i += length; } @@ -53025,7 +53482,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { FolderID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)Name.Length; + Utils.ByteToBytes((byte)Name.Length, bytes, ref i); Buffer.BlockCopy(Name, 0, bytes, i, Name.Length); i += Name.Length; } @@ -53046,6 +53503,8 @@ public override int Length public EventDataBlock EventData; public InventoryBlockBlock InventoryBlock; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public CreateLandmarkForEventPacket() { HasVariableBlocks = false; @@ -53054,6 +53513,7 @@ public CreateLandmarkForEventPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 306; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); EventData = new EventDataBlock(); @@ -53081,11 +53541,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public CreateLandmarkForEventPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -53176,6 +53635,7 @@ public RegionHandleRequestPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 309; Header.Reliable = true; + NeedValidateIDs = false; RequestBlock = new RequestBlockBlock(); } @@ -53198,11 +53658,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public RegionHandleRequestPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; RequestBlock.FromBytes(bytes, ref i); @@ -53290,6 +53749,7 @@ public RegionIDAndHandleReplyPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 310; Header.Reliable = true; + NeedValidateIDs = false; ReplyBlock = new ReplyBlockBlock(); } @@ -53312,11 +53772,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public RegionIDAndHandleReplyPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; ReplyBlock.FromBytes(bytes, ref i); @@ -53420,12 +53879,12 @@ public override void FromBytes(byte[] bytes, ref int i) { SourceID.FromBytes(bytes, i); i += 16; DestID.FromBytes(bytes, i); i += 16; - Flags = (byte)bytes[i++]; + Flags = Utils.BytesToByte(bytes, ref i); Amount = Utils.BytesToIntSafepos(bytes, i); i += 4; - AggregatePermNextOwner = (byte)bytes[i++]; - AggregatePermInventory = (byte)bytes[i++]; + AggregatePermNextOwner = Utils.BytesToByte(bytes, ref i); + AggregatePermInventory = Utils.BytesToByte(bytes, ref i); TransactionType = Utils.BytesToIntSafepos(bytes, i); i += 4; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Description = new byte[length]; Buffer.BlockCopy(bytes, i, Description, 0, length); i += length; } @@ -53439,12 +53898,12 @@ public override void ToBytes(byte[] bytes, ref int i) { SourceID.ToBytes(bytes, i); i += 16; DestID.ToBytes(bytes, i); i += 16; - bytes[i++] = Flags; + Utils.ByteToBytes( Flags, bytes, ref i); Utils.IntToBytesSafepos(Amount, bytes, i); i += 4; - bytes[i++] = AggregatePermNextOwner; - bytes[i++] = AggregatePermInventory; + Utils.ByteToBytes( AggregatePermNextOwner, bytes, ref i); + Utils.ByteToBytes( AggregatePermInventory, bytes, ref i); Utils.IntToBytesSafepos(TransactionType, bytes, i); i += 4; - bytes[i++] = (byte)Description.Length; + Utils.ByteToBytes((byte)Description.Length, bytes, ref i); Buffer.BlockCopy(Description, 0, bytes, i, Description.Length); i += Description.Length; } @@ -53463,6 +53922,8 @@ public override int Length public AgentDataBlock AgentData; public MoneyDataBlock MoneyData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public MoneyTransferRequestPacket() { HasVariableBlocks = false; @@ -53471,6 +53932,7 @@ public MoneyTransferRequestPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 311; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); MoneyData = new MoneyDataBlock(); @@ -53496,11 +53958,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public MoneyTransferRequestPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -53623,6 +54084,8 @@ public override int Length public AgentDataBlock AgentData; public MoneyDataBlock MoneyData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public MoneyBalanceRequestPacket() { HasVariableBlocks = false; @@ -53631,6 +54094,7 @@ public MoneyBalanceRequestPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 313; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); MoneyData = new MoneyDataBlock(); @@ -53656,11 +54120,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public MoneyBalanceRequestPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -53725,11 +54188,11 @@ public override void FromBytes(byte[] bytes, ref int i) { AgentID.FromBytes(bytes, i); i += 16; TransactionID.FromBytes(bytes, i); i += 16; - TransactionSuccess = (bytes[i++] != 0) ? (bool)true : (bool)false; + TransactionSuccess = (Utils.BytesToByte(bytes, ref i) != 0); MoneyBalance = Utils.BytesToIntSafepos(bytes, i); i += 4; SquareMetersCredit = Utils.BytesToIntSafepos(bytes, i); i += 4; SquareMetersCommitted = Utils.BytesToIntSafepos(bytes, i); i += 4; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Description = new byte[length]; Buffer.BlockCopy(bytes, i, Description, 0, length); i += length; } @@ -53743,11 +54206,11 @@ public override void ToBytes(byte[] bytes, ref int i) { AgentID.ToBytes(bytes, i); i += 16; TransactionID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)((TransactionSuccess) ? 1 : 0); + Utils.ByteToBytes((byte)((TransactionSuccess) ? 1 : 0), bytes, ref i); Utils.IntToBytesSafepos(MoneyBalance, bytes, i); i += 4; Utils.IntToBytesSafepos(SquareMetersCredit, bytes, i); i += 4; Utils.IntToBytesSafepos(SquareMetersCommitted, bytes, i); i += 4; - bytes[i++] = (byte)Description.Length; + Utils.ByteToBytes((byte)Description.Length, bytes, ref i); Buffer.BlockCopy(Description, 0, bytes, i, Description.Length); i += Description.Length; } @@ -53787,11 +54250,11 @@ public override void FromBytes(byte[] bytes, ref int i) { TransactionType = Utils.BytesToIntSafepos(bytes, i); i += 4; SourceID.FromBytes(bytes, i); i += 16; - IsSourceGroup = (bytes[i++] != 0) ? (bool)true : (bool)false; + IsSourceGroup = (Utils.BytesToByte(bytes, ref i) != 0); DestID.FromBytes(bytes, i); i += 16; - IsDestGroup = (bytes[i++] != 0) ? (bool)true : (bool)false; + IsDestGroup = (Utils.BytesToByte(bytes, ref i) != 0); Amount = Utils.BytesToIntSafepos(bytes, i); i += 4; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); ItemDescription = new byte[length]; Buffer.BlockCopy(bytes, i, ItemDescription, 0, length); i += length; } @@ -53805,11 +54268,11 @@ public override void ToBytes(byte[] bytes, ref int i) { Utils.IntToBytesSafepos(TransactionType, bytes, i); i += 4; SourceID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)((IsSourceGroup) ? 1 : 0); + Utils.ByteToBytes((byte)((IsSourceGroup) ? 1 : 0), bytes, ref i); DestID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)((IsDestGroup) ? 1 : 0); + Utils.ByteToBytes((byte)((IsDestGroup) ? 1 : 0), bytes, ref i); Utils.IntToBytesSafepos(Amount, bytes, i); i += 4; - bytes[i++] = (byte)ItemDescription.Length; + Utils.ByteToBytes((byte)ItemDescription.Length, bytes, ref i); Buffer.BlockCopy(ItemDescription, 0, bytes, i, ItemDescription.Length); i += ItemDescription.Length; } @@ -53836,6 +54299,7 @@ public MoneyBalanceReplyPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 314; Header.Reliable = true; + NeedValidateIDs = false; Header.Zerocoded = true; MoneyData = new MoneyDataBlock(); TransactionInfo = new TransactionInfoBlock(); @@ -53861,11 +54325,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public MoneyBalanceReplyPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; MoneyData.FromBytes(bytes, ref i); @@ -53932,8 +54395,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { Utils.UIntToBytesSafepos(TargetIP, bytes, i); i += 4; - bytes[i++] = (byte)((TargetPort >> 8) % 256); - bytes[i++] = (byte)(TargetPort % 256); + Utils.UInt16ToBytesBig(TargetPort, bytes, i); i += 2; } } @@ -53972,11 +54434,11 @@ public override void FromBytes(byte[] bytes, ref int i) { AgentID.FromBytes(bytes, i); i += 16; TransactionID.FromBytes(bytes, i); i += 16; - TransactionSuccess = (bytes[i++] != 0) ? (bool)true : (bool)false; + TransactionSuccess = (Utils.BytesToByte(bytes, ref i) != 0); MoneyBalance = Utils.BytesToIntSafepos(bytes, i); i += 4; SquareMetersCredit = Utils.BytesToIntSafepos(bytes, i); i += 4; SquareMetersCommitted = Utils.BytesToIntSafepos(bytes, i); i += 4; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Description = new byte[length]; Buffer.BlockCopy(bytes, i, Description, 0, length); i += length; } @@ -53990,11 +54452,11 @@ public override void ToBytes(byte[] bytes, ref int i) { AgentID.ToBytes(bytes, i); i += 16; TransactionID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)((TransactionSuccess) ? 1 : 0); + Utils.ByteToBytes((byte)((TransactionSuccess) ? 1 : 0), bytes, ref i); Utils.IntToBytesSafepos(MoneyBalance, bytes, i); i += 4; Utils.IntToBytesSafepos(SquareMetersCredit, bytes, i); i += 4; Utils.IntToBytesSafepos(SquareMetersCommitted, bytes, i); i += 4; - bytes[i++] = (byte)Description.Length; + Utils.ByteToBytes((byte)Description.Length, bytes, ref i); Buffer.BlockCopy(Description, 0, bytes, i, Description.Length); i += Description.Length; } @@ -54034,11 +54496,11 @@ public override void FromBytes(byte[] bytes, ref int i) { TransactionType = Utils.BytesToIntSafepos(bytes, i); i += 4; SourceID.FromBytes(bytes, i); i += 16; - IsSourceGroup = (bytes[i++] != 0) ? (bool)true : (bool)false; + IsSourceGroup = (Utils.BytesToByte(bytes, ref i) != 0); DestID.FromBytes(bytes, i); i += 16; - IsDestGroup = (bytes[i++] != 0) ? (bool)true : (bool)false; + IsDestGroup = (Utils.BytesToByte(bytes, ref i) != 0); Amount = Utils.BytesToIntSafepos(bytes, i); i += 4; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); ItemDescription = new byte[length]; Buffer.BlockCopy(bytes, i, ItemDescription, 0, length); i += length; } @@ -54052,11 +54514,11 @@ public override void ToBytes(byte[] bytes, ref int i) { Utils.IntToBytesSafepos(TransactionType, bytes, i); i += 4; SourceID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)((IsSourceGroup) ? 1 : 0); + Utils.ByteToBytes((byte)((IsSourceGroup) ? 1 : 0), bytes, ref i); DestID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)((IsDestGroup) ? 1 : 0); + Utils.ByteToBytes((byte)((IsDestGroup) ? 1 : 0), bytes, ref i); Utils.IntToBytesSafepos(Amount, bytes, i); i += 4; - bytes[i++] = (byte)ItemDescription.Length; + Utils.ByteToBytes((byte)ItemDescription.Length, bytes, ref i); Buffer.BlockCopy(ItemDescription, 0, bytes, i, ItemDescription.Length); i += ItemDescription.Length; } @@ -54085,6 +54547,7 @@ public RoutedMoneyBalanceReplyPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 315; Header.Reliable = true; + NeedValidateIDs = false; Header.Zerocoded = true; TargetBlock = new TargetBlockBlock(); MoneyData = new MoneyDataBlock(); @@ -54112,11 +54575,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public RoutedMoneyBalanceReplyPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; TargetBlock.FromBytes(bytes, ref i); @@ -54252,6 +54714,8 @@ public override int Length public AgentDataBlock AgentData; public DataBlock[] Data; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ActivateGesturesPacket() { HasVariableBlocks = true; @@ -54260,6 +54724,7 @@ public ActivateGesturesPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 316; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); Data = null; } @@ -54292,11 +54757,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ActivateGesturesPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -54322,7 +54786,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)Data.Length; + Utils.ByteToBytes((byte)Data.Length, bytes, ref i); for (int j = 0; j < Data.Length; j++) { Data[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -54493,6 +54957,8 @@ public override int Length public AgentDataBlock AgentData; public DataBlock[] Data; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public DeactivateGesturesPacket() { HasVariableBlocks = true; @@ -54501,6 +54967,7 @@ public DeactivateGesturesPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 317; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); Data = null; } @@ -54533,11 +55000,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public DeactivateGesturesPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -54563,7 +55029,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)Data.Length; + Utils.ByteToBytes((byte)Data.Length, bytes, ref i); for (int j = 0; j < Data.Length; j++) { Data[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -54663,7 +55129,7 @@ public override void FromBytes(byte[] bytes, ref int i) try { AgentID.FromBytes(bytes, i); i += 16; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Filename = new byte[length]; Buffer.BlockCopy(bytes, i, Filename, 0, length); i += length; } @@ -54676,7 +55142,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { AgentID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)Filename.Length; + Utils.ByteToBytes((byte)Filename.Length, bytes, ref i); Buffer.BlockCopy(Filename, 0, bytes, i, Filename.Length); i += Filename.Length; } @@ -54701,6 +55167,7 @@ public MuteListUpdatePacket() Header.Frequency = PacketFrequency.Low; Header.ID = 318; Header.Reliable = true; + NeedValidateIDs = false; MuteData = new MuteDataBlock(); } @@ -54723,11 +55190,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public MuteListUpdatePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; MuteData.FromBytes(bytes, ref i); @@ -54812,6 +55278,7 @@ public UseCachedMuteListPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 319; Header.Reliable = true; + NeedValidateIDs = false; AgentData = new AgentDataBlock(); } @@ -54834,11 +55301,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public UseCachedMuteListPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -54962,6 +55428,8 @@ public override int Length public AgentDataBlock AgentData; public RightsBlock[] Rights; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public GrantUserRightsPacket() { HasVariableBlocks = true; @@ -54970,6 +55438,7 @@ public GrantUserRightsPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 320; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); Rights = null; } @@ -55002,11 +55471,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public GrantUserRightsPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -55032,7 +55500,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)Rights.Length; + Utils.ByteToBytes((byte)Rights.Length, bytes, ref i); for (int j = 0; j < Rights.Length; j++) { Rights[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -55205,6 +55673,7 @@ public ChangeUserRightsPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 321; Header.Reliable = true; + NeedValidateIDs = false; AgentData = new AgentDataBlock(); Rights = null; } @@ -55237,11 +55706,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ChangeUserRightsPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -55267,7 +55735,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)Rights.Length; + Utils.ByteToBytes((byte)Rights.Length, bytes, ref i); for (int j = 0; j < Rights.Length; j++) { Rights[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -55397,6 +55865,7 @@ public OnlineNotificationPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 322; Header.Reliable = true; + NeedValidateIDs = false; AgentBlock = null; } @@ -55427,11 +55896,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public OnlineNotificationPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; int count = (int)bytes[i++]; @@ -55454,7 +55922,7 @@ public override byte[] ToBytes() byte[] bytes = new byte[length]; int i = 0; Header.ToBytes(bytes, ref i); - bytes[i++] = (byte)AgentBlock.Length; + Utils.ByteToBytes((byte)AgentBlock.Length, bytes, ref i); for (int j = 0; j < AgentBlock.Length; j++) { AgentBlock[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -55582,6 +56050,7 @@ public OfflineNotificationPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 323; Header.Reliable = true; + NeedValidateIDs = false; AgentBlock = null; } @@ -55612,11 +56081,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public OfflineNotificationPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; int count = (int)bytes[i++]; @@ -55639,7 +56107,7 @@ public override byte[] ToBytes() byte[] bytes = new byte[length]; int i = 0; Header.ToBytes(bytes, ref i); - bytes[i++] = (byte)AgentBlock.Length; + Utils.ByteToBytes((byte)AgentBlock.Length, bytes, ref i); for (int j = 0; j < AgentBlock.Length; j++) { AgentBlock[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -55779,7 +56247,7 @@ public override void FromBytes(byte[] bytes, ref int i) int length; try { - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); SimName = new byte[length]; Buffer.BlockCopy(bytes, i, SimName, 0, length); i += length; LocationID = Utils.BytesToUIntSafepos(bytes, i); i += 4; @@ -55794,7 +56262,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = (byte)SimName.Length; + Utils.ByteToBytes((byte)SimName.Length, bytes, ref i); Buffer.BlockCopy(SimName, 0, bytes, i, SimName.Length); i += SimName.Length; Utils.UIntToBytesSafepos(LocationID, bytes, i); i += 4; LocationPos.ToBytes(bytes, i); i += 12; @@ -55816,6 +56284,8 @@ public override int Length public AgentDataBlock AgentData; public StartLocationDataBlock StartLocationData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public SetStartLocationRequestPacket() { HasVariableBlocks = false; @@ -55824,6 +56294,7 @@ public SetStartLocationRequestPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 324; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); StartLocationData = new StartLocationDataBlock(); @@ -55849,11 +56320,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public SetStartLocationRequestPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -55915,10 +56385,10 @@ public override void FromBytes(byte[] bytes, ref int i) try { TransactionID.FromBytes(bytes, i); i += 16; - Type = (sbyte)bytes[i++]; - Tempfile = (bytes[i++] != 0) ? (bool)true : (bool)false; - StoreLocal = (bytes[i++] != 0) ? (bool)true : (bool)false; - length = (bytes[i++] + (bytes[i++] << 8)); + Type = (sbyte)Utils.BytesToByte(bytes, ref i); + Tempfile = (Utils.BytesToByte(bytes, ref i) != 0); + StoreLocal = (Utils.BytesToByte(bytes, ref i) != 0); + length = Utils.BytesToUInt16(bytes, i); i+=2; AssetData = new byte[length]; Buffer.BlockCopy(bytes, i, AssetData, 0, length); i += length; } @@ -55931,11 +56401,10 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { TransactionID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)Type; - bytes[i++] = (byte)((Tempfile) ? 1 : 0); - bytes[i++] = (byte)((StoreLocal) ? 1 : 0); - bytes[i++] = (byte)(AssetData.Length % 256); - bytes[i++] = (byte)((AssetData.Length >> 8) % 256); + Utils.ByteToBytes( (byte)Type, bytes, ref i); + Utils.ByteToBytes((byte)((Tempfile) ? 1 : 0), bytes, ref i); + Utils.ByteToBytes((byte)((StoreLocal) ? 1 : 0), bytes, ref i); + Utils.UInt16ToBytes((ushort)AssetData.Length, bytes, i); i += 2; Buffer.BlockCopy(AssetData, 0, bytes, i, AssetData.Length); i += AssetData.Length; } @@ -55960,6 +56429,7 @@ public AssetUploadRequestPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 333; Header.Reliable = true; + NeedValidateIDs = false; AssetBlock = new AssetBlockBlock(); } @@ -55982,11 +56452,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public AssetUploadRequestPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AssetBlock.FromBytes(bytes, ref i); @@ -56040,8 +56509,8 @@ public override void FromBytes(byte[] bytes, ref int i) try { UUID.FromBytes(bytes, i); i += 16; - Type = (sbyte)bytes[i++]; - Success = (bytes[i++] != 0) ? (bool)true : (bool)false; + Type = (sbyte)Utils.BytesToByte(bytes, ref i); + Success = (Utils.BytesToByte(bytes, ref i) != 0); } catch (Exception) { @@ -56052,8 +56521,8 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { UUID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)Type; - bytes[i++] = (byte)((Success) ? 1 : 0); + Utils.ByteToBytes( (byte)Type, bytes, ref i); + Utils.ByteToBytes((byte)((Success) ? 1 : 0), bytes, ref i); } } @@ -56077,6 +56546,7 @@ public AssetUploadCompletePacket() Header.Frequency = PacketFrequency.Low; Header.ID = 334; Header.Reliable = true; + NeedValidateIDs = false; AssetBlock = new AssetBlockBlock(); } @@ -56099,11 +56569,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public AssetUploadCompletePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AssetBlock.FromBytes(bytes, ref i); @@ -56206,18 +56675,18 @@ public override void FromBytes(byte[] bytes, ref int i) int length; try { - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Name = new byte[length]; Buffer.BlockCopy(bytes, i, Name, 0, length); i += length; - length = (bytes[i++] + (bytes[i++] << 8)); + length = Utils.BytesToUInt16(bytes, i); i+=2; Charter = new byte[length]; Buffer.BlockCopy(bytes, i, Charter, 0, length); i += length; - ShowInList = (bytes[i++] != 0) ? (bool)true : (bool)false; + ShowInList = (Utils.BytesToByte(bytes, ref i) != 0); InsigniaID.FromBytes(bytes, i); i += 16; MembershipFee = Utils.BytesToIntSafepos(bytes, i); i += 4; - OpenEnrollment = (bytes[i++] != 0) ? (bool)true : (bool)false; - AllowPublish = (bytes[i++] != 0) ? (bool)true : (bool)false; - MaturePublish = (bytes[i++] != 0) ? (bool)true : (bool)false; + OpenEnrollment = (Utils.BytesToByte(bytes, ref i) != 0); + AllowPublish = (Utils.BytesToByte(bytes, ref i) != 0); + MaturePublish = (Utils.BytesToByte(bytes, ref i) != 0); } catch (Exception) { @@ -56227,17 +56696,16 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = (byte)Name.Length; + Utils.ByteToBytes((byte)Name.Length, bytes, ref i); Buffer.BlockCopy(Name, 0, bytes, i, Name.Length); i += Name.Length; - bytes[i++] = (byte)(Charter.Length % 256); - bytes[i++] = (byte)((Charter.Length >> 8) % 256); + Utils.UInt16ToBytes((ushort)Charter.Length, bytes, i); i += 2; Buffer.BlockCopy(Charter, 0, bytes, i, Charter.Length); i += Charter.Length; - bytes[i++] = (byte)((ShowInList) ? 1 : 0); + Utils.ByteToBytes((byte)((ShowInList) ? 1 : 0), bytes, ref i); InsigniaID.ToBytes(bytes, i); i += 16; Utils.IntToBytesSafepos(MembershipFee, bytes, i); i += 4; - bytes[i++] = (byte)((OpenEnrollment) ? 1 : 0); - bytes[i++] = (byte)((AllowPublish) ? 1 : 0); - bytes[i++] = (byte)((MaturePublish) ? 1 : 0); + Utils.ByteToBytes((byte)((OpenEnrollment) ? 1 : 0), bytes, ref i); + Utils.ByteToBytes((byte)((AllowPublish) ? 1 : 0), bytes, ref i); + Utils.ByteToBytes((byte)((MaturePublish) ? 1 : 0), bytes, ref i); } } @@ -56255,6 +56723,8 @@ public override int Length public AgentDataBlock AgentData; public GroupDataBlock GroupData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public CreateGroupRequestPacket() { HasVariableBlocks = false; @@ -56263,6 +56733,7 @@ public CreateGroupRequestPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 339; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); GroupData = new GroupDataBlock(); @@ -56288,11 +56759,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public CreateGroupRequestPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -56390,8 +56860,8 @@ public override void FromBytes(byte[] bytes, ref int i) try { GroupID.FromBytes(bytes, i); i += 16; - Success = (bytes[i++] != 0) ? (bool)true : (bool)false; - length = bytes[i++]; + Success = (Utils.BytesToByte(bytes, ref i) != 0); + length = Utils.BytesToByte(bytes, ref i); Message = new byte[length]; Buffer.BlockCopy(bytes, i, Message, 0, length); i += length; } @@ -56404,8 +56874,8 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { GroupID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)((Success) ? 1 : 0); - bytes[i++] = (byte)Message.Length; + Utils.ByteToBytes((byte)((Success) ? 1 : 0), bytes, ref i); + Utils.ByteToBytes((byte)Message.Length, bytes, ref i); Buffer.BlockCopy(Message, 0, bytes, i, Message.Length); i += Message.Length; } @@ -56432,6 +56902,7 @@ public CreateGroupReplyPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 340; Header.Reliable = true; + NeedValidateIDs = false; AgentData = new AgentDataBlock(); ReplyData = new ReplyDataBlock(); } @@ -56456,11 +56927,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public CreateGroupReplyPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -56566,15 +57036,15 @@ public override void FromBytes(byte[] bytes, ref int i) try { GroupID.FromBytes(bytes, i); i += 16; - length = (bytes[i++] + (bytes[i++] << 8)); + length = Utils.BytesToUInt16(bytes, i); i+=2; Charter = new byte[length]; Buffer.BlockCopy(bytes, i, Charter, 0, length); i += length; - ShowInList = (bytes[i++] != 0) ? (bool)true : (bool)false; + ShowInList = (Utils.BytesToByte(bytes, ref i) != 0); InsigniaID.FromBytes(bytes, i); i += 16; MembershipFee = Utils.BytesToIntSafepos(bytes, i); i += 4; - OpenEnrollment = (bytes[i++] != 0) ? (bool)true : (bool)false; - AllowPublish = (bytes[i++] != 0) ? (bool)true : (bool)false; - MaturePublish = (bytes[i++] != 0) ? (bool)true : (bool)false; + OpenEnrollment = (Utils.BytesToByte(bytes, ref i) != 0); + AllowPublish = (Utils.BytesToByte(bytes, ref i) != 0); + MaturePublish = (Utils.BytesToByte(bytes, ref i) != 0); } catch (Exception) { @@ -56585,15 +57055,14 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { GroupID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)(Charter.Length % 256); - bytes[i++] = (byte)((Charter.Length >> 8) % 256); + Utils.UInt16ToBytes((ushort)Charter.Length, bytes, i); i += 2; Buffer.BlockCopy(Charter, 0, bytes, i, Charter.Length); i += Charter.Length; - bytes[i++] = (byte)((ShowInList) ? 1 : 0); + Utils.ByteToBytes((byte)((ShowInList) ? 1 : 0), bytes, ref i); InsigniaID.ToBytes(bytes, i); i += 16; Utils.IntToBytesSafepos(MembershipFee, bytes, i); i += 4; - bytes[i++] = (byte)((OpenEnrollment) ? 1 : 0); - bytes[i++] = (byte)((AllowPublish) ? 1 : 0); - bytes[i++] = (byte)((MaturePublish) ? 1 : 0); + Utils.ByteToBytes((byte)((OpenEnrollment) ? 1 : 0), bytes, ref i); + Utils.ByteToBytes((byte)((AllowPublish) ? 1 : 0), bytes, ref i); + Utils.ByteToBytes((byte)((MaturePublish) ? 1 : 0), bytes, ref i); } } @@ -56611,6 +57080,8 @@ public override int Length public AgentDataBlock AgentData; public GroupDataBlock GroupData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public UpdateGroupInfoPacket() { HasVariableBlocks = false; @@ -56619,6 +57090,7 @@ public UpdateGroupInfoPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 341; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); GroupData = new GroupDataBlock(); @@ -56644,11 +57116,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public UpdateGroupInfoPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -56781,6 +57252,8 @@ public override int Length public AgentDataBlock AgentData; public RoleChangeBlock[] RoleChange; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public GroupRoleChangesPacket() { HasVariableBlocks = true; @@ -56789,6 +57262,7 @@ public GroupRoleChangesPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 342; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); RoleChange = null; } @@ -56821,11 +57295,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public GroupRoleChangesPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -56851,7 +57324,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)RoleChange.Length; + Utils.ByteToBytes((byte)RoleChange.Length, bytes, ref i); for (int j = 0; j < RoleChange.Length; j++) { RoleChange[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -57015,6 +57488,8 @@ public override int Length public AgentDataBlock AgentData; public GroupDataBlock GroupData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public JoinGroupRequestPacket() { HasVariableBlocks = false; @@ -57023,6 +57498,7 @@ public JoinGroupRequestPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 343; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); GroupData = new GroupDataBlock(); @@ -57048,11 +57524,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public JoinGroupRequestPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -57146,7 +57621,7 @@ public override void FromBytes(byte[] bytes, ref int i) try { GroupID.FromBytes(bytes, i); i += 16; - Success = (bytes[i++] != 0) ? (bool)true : (bool)false; + Success = (Utils.BytesToByte(bytes, ref i) != 0); } catch (Exception) { @@ -57157,7 +57632,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { GroupID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)((Success) ? 1 : 0); + Utils.ByteToBytes((byte)((Success) ? 1 : 0), bytes, ref i); } } @@ -57183,6 +57658,7 @@ public JoinGroupReplyPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 344; Header.Reliable = true; + NeedValidateIDs = false; AgentData = new AgentDataBlock(); GroupData = new GroupDataBlock(); } @@ -57207,11 +57683,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public JoinGroupReplyPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -57375,6 +57850,8 @@ public override int Length public GroupDataBlock GroupData; public EjectDataBlock[] EjectData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public EjectGroupMemberRequestPacket() { HasVariableBlocks = true; @@ -57383,6 +57860,7 @@ public EjectGroupMemberRequestPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 345; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); GroupData = new GroupDataBlock(); EjectData = null; @@ -57417,11 +57895,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public EjectGroupMemberRequestPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -57450,7 +57927,7 @@ public override byte[] ToBytes() Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); GroupData.ToBytes(bytes, ref i); - bytes[i++] = (byte)EjectData.Length; + Utils.ByteToBytes((byte)EjectData.Length, bytes, ref i); for (int j = 0; j < EjectData.Length; j++) { EjectData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -57623,7 +58100,7 @@ public override void FromBytes(byte[] bytes, ref int i) { try { - Success = (bytes[i++] != 0) ? (bool)true : (bool)false; + Success = (Utils.BytesToByte(bytes, ref i) != 0); } catch (Exception) { @@ -57633,7 +58110,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = (byte)((Success) ? 1 : 0); + Utils.ByteToBytes((byte)((Success) ? 1 : 0), bytes, ref i); } } @@ -57661,6 +58138,7 @@ public EjectGroupMemberReplyPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 346; Header.Reliable = true; + NeedValidateIDs = false; AgentData = new AgentDataBlock(); GroupData = new GroupDataBlock(); EjectData = new EjectDataBlock(); @@ -57687,11 +58165,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public EjectGroupMemberReplyPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -57817,6 +58294,8 @@ public override int Length public AgentDataBlock AgentData; public GroupDataBlock GroupData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public LeaveGroupRequestPacket() { HasVariableBlocks = false; @@ -57825,6 +58304,7 @@ public LeaveGroupRequestPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 347; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); GroupData = new GroupDataBlock(); } @@ -57849,11 +58329,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public LeaveGroupRequestPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -57947,7 +58426,7 @@ public override void FromBytes(byte[] bytes, ref int i) try { GroupID.FromBytes(bytes, i); i += 16; - Success = (bytes[i++] != 0) ? (bool)true : (bool)false; + Success = (Utils.BytesToByte(bytes, ref i) != 0); } catch (Exception) { @@ -57958,7 +58437,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { GroupID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)((Success) ? 1 : 0); + Utils.ByteToBytes((byte)((Success) ? 1 : 0), bytes, ref i); } } @@ -57984,6 +58463,7 @@ public LeaveGroupReplyPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 348; Header.Reliable = true; + NeedValidateIDs = false; AgentData = new AgentDataBlock(); GroupData = new GroupDataBlock(); } @@ -58008,11 +58488,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public LeaveGroupReplyPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -58179,6 +58658,8 @@ public override int Length public GroupDataBlock GroupData; public InviteDataBlock[] InviteData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public InviteGroupRequestPacket() { HasVariableBlocks = true; @@ -58187,6 +58668,7 @@ public InviteGroupRequestPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 349; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); GroupData = new GroupDataBlock(); InviteData = null; @@ -58221,11 +58703,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public InviteGroupRequestPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -58254,7 +58735,7 @@ public override byte[] ToBytes() Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); GroupData.ToBytes(bytes, ref i); - bytes[i++] = (byte)InviteData.Length; + Utils.ByteToBytes((byte)InviteData.Length, bytes, ref i); for (int j = 0; j < InviteData.Length; j++) { InviteData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -58420,6 +58901,8 @@ public override int Length public AgentDataBlock AgentData; public GroupDataBlock GroupData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public GroupProfileRequestPacket() { HasVariableBlocks = false; @@ -58428,6 +58911,7 @@ public GroupProfileRequestPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 351; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); GroupData = new GroupDataBlock(); } @@ -58452,11 +58936,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public GroupProfileRequestPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -58569,26 +59052,26 @@ public override void FromBytes(byte[] bytes, ref int i) try { GroupID.FromBytes(bytes, i); i += 16; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Name = new byte[length]; Buffer.BlockCopy(bytes, i, Name, 0, length); i += length; - length = (bytes[i++] + (bytes[i++] << 8)); + length = Utils.BytesToUInt16(bytes, i); i+=2; Charter = new byte[length]; Buffer.BlockCopy(bytes, i, Charter, 0, length); i += length; - ShowInList = (bytes[i++] != 0) ? (bool)true : (bool)false; - length = bytes[i++]; + ShowInList = (Utils.BytesToByte(bytes, ref i) != 0); + length = Utils.BytesToByte(bytes, ref i); MemberTitle = new byte[length]; Buffer.BlockCopy(bytes, i, MemberTitle, 0, length); i += length; PowersMask = Utils.BytesToUInt64Safepos(bytes, i); i += 8; InsigniaID.FromBytes(bytes, i); i += 16; FounderID.FromBytes(bytes, i); i += 16; MembershipFee = Utils.BytesToIntSafepos(bytes, i); i += 4; - OpenEnrollment = (bytes[i++] != 0) ? (bool)true : (bool)false; + OpenEnrollment = (Utils.BytesToByte(bytes, ref i) != 0); Money = Utils.BytesToIntSafepos(bytes, i); i += 4; GroupMembershipCount = Utils.BytesToIntSafepos(bytes, i); i += 4; GroupRolesCount = Utils.BytesToIntSafepos(bytes, i); i += 4; - AllowPublish = (bytes[i++] != 0) ? (bool)true : (bool)false; - MaturePublish = (bytes[i++] != 0) ? (bool)true : (bool)false; + AllowPublish = (Utils.BytesToByte(bytes, ref i) != 0); + MaturePublish = (Utils.BytesToByte(bytes, ref i) != 0); OwnerRole.FromBytes(bytes, i); i += 16; } catch (Exception) @@ -58600,24 +59083,23 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { GroupID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)Name.Length; + Utils.ByteToBytes((byte)Name.Length, bytes, ref i); Buffer.BlockCopy(Name, 0, bytes, i, Name.Length); i += Name.Length; - bytes[i++] = (byte)(Charter.Length % 256); - bytes[i++] = (byte)((Charter.Length >> 8) % 256); + Utils.UInt16ToBytes((ushort)Charter.Length, bytes, i); i += 2; Buffer.BlockCopy(Charter, 0, bytes, i, Charter.Length); i += Charter.Length; - bytes[i++] = (byte)((ShowInList) ? 1 : 0); - bytes[i++] = (byte)MemberTitle.Length; + Utils.ByteToBytes((byte)((ShowInList) ? 1 : 0), bytes, ref i); + Utils.ByteToBytes((byte)MemberTitle.Length, bytes, ref i); Buffer.BlockCopy(MemberTitle, 0, bytes, i, MemberTitle.Length); i += MemberTitle.Length; Utils.UInt64ToBytesSafepos(PowersMask, bytes, i); i += 8; InsigniaID.ToBytes(bytes, i); i += 16; FounderID.ToBytes(bytes, i); i += 16; Utils.IntToBytesSafepos(MembershipFee, bytes, i); i += 4; - bytes[i++] = (byte)((OpenEnrollment) ? 1 : 0); + Utils.ByteToBytes((byte)((OpenEnrollment) ? 1 : 0), bytes, ref i); Utils.IntToBytesSafepos(Money, bytes, i); i += 4; Utils.IntToBytesSafepos(GroupMembershipCount, bytes, i); i += 4; Utils.IntToBytesSafepos(GroupRolesCount, bytes, i); i += 4; - bytes[i++] = (byte)((AllowPublish) ? 1 : 0); - bytes[i++] = (byte)((MaturePublish) ? 1 : 0); + Utils.ByteToBytes((byte)((AllowPublish) ? 1 : 0), bytes, ref i); + Utils.ByteToBytes((byte)((MaturePublish) ? 1 : 0), bytes, ref i); OwnerRole.ToBytes(bytes, i); i += 16; } @@ -58644,6 +59126,7 @@ public GroupProfileReplyPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 352; Header.Reliable = true; + NeedValidateIDs = false; Header.Zerocoded = true; AgentData = new AgentDataBlock(); GroupData = new GroupDataBlock(); @@ -58669,11 +59152,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public GroupProfileReplyPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -58805,6 +59287,8 @@ public override int Length public AgentDataBlock AgentData; public MoneyDataBlock MoneyData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public GroupAccountSummaryRequestPacket() { HasVariableBlocks = false; @@ -58813,6 +59297,7 @@ public GroupAccountSummaryRequestPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 353; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); MoneyData = new MoneyDataBlock(); @@ -58838,11 +59323,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public GroupAccountSummaryRequestPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -58964,7 +59448,7 @@ public override void FromBytes(byte[] bytes, ref int i) RequestID.FromBytes(bytes, i); i += 16; IntervalDays = Utils.BytesToIntSafepos(bytes, i); i += 4; CurrentInterval = Utils.BytesToIntSafepos(bytes, i); i += 4; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); StartDate = new byte[length]; Buffer.BlockCopy(bytes, i, StartDate, 0, length); i += length; Balance = Utils.BytesToIntSafepos(bytes, i); i += 4; @@ -58981,10 +59465,10 @@ public override void FromBytes(byte[] bytes, ref int i) GroupTaxEstimate = Utils.BytesToIntSafepos(bytes, i); i += 4; ParcelDirFeeEstimate = Utils.BytesToIntSafepos(bytes, i); i += 4; NonExemptMembers = Utils.BytesToIntSafepos(bytes, i); i += 4; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); LastTaxDate = new byte[length]; Buffer.BlockCopy(bytes, i, LastTaxDate, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); TaxDate = new byte[length]; Buffer.BlockCopy(bytes, i, TaxDate, 0, length); i += length; } @@ -58999,7 +59483,7 @@ public override void ToBytes(byte[] bytes, ref int i) RequestID.ToBytes(bytes, i); i += 16; Utils.IntToBytesSafepos(IntervalDays, bytes, i); i += 4; Utils.IntToBytesSafepos(CurrentInterval, bytes, i); i += 4; - bytes[i++] = (byte)StartDate.Length; + Utils.ByteToBytes((byte)StartDate.Length, bytes, ref i); Buffer.BlockCopy(StartDate, 0, bytes, i, StartDate.Length); i += StartDate.Length; Utils.IntToBytesSafepos(Balance, bytes, i); i += 4; Utils.IntToBytesSafepos(TotalCredits, bytes, i); i += 4; @@ -59015,9 +59499,9 @@ public override void ToBytes(byte[] bytes, ref int i) Utils.IntToBytesSafepos(GroupTaxEstimate, bytes, i); i += 4; Utils.IntToBytesSafepos(ParcelDirFeeEstimate, bytes, i); i += 4; Utils.IntToBytesSafepos(NonExemptMembers, bytes, i); i += 4; - bytes[i++] = (byte)LastTaxDate.Length; + Utils.ByteToBytes((byte)LastTaxDate.Length, bytes, ref i); Buffer.BlockCopy(LastTaxDate, 0, bytes, i, LastTaxDate.Length); i += LastTaxDate.Length; - bytes[i++] = (byte)TaxDate.Length; + Utils.ByteToBytes((byte)TaxDate.Length, bytes, ref i); Buffer.BlockCopy(TaxDate, 0, bytes, i, TaxDate.Length); i += TaxDate.Length; } @@ -59044,6 +59528,7 @@ public GroupAccountSummaryReplyPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 354; Header.Reliable = true; + NeedValidateIDs = false; Header.Zerocoded = true; AgentData = new AgentDataBlock(); MoneyData = new MoneyDataBlock(); @@ -59069,11 +59554,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public GroupAccountSummaryReplyPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -59205,6 +59689,8 @@ public override int Length public AgentDataBlock AgentData; public MoneyDataBlock MoneyData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public GroupAccountDetailsRequestPacket() { HasVariableBlocks = false; @@ -59213,6 +59699,7 @@ public GroupAccountDetailsRequestPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 355; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); MoneyData = new MoneyDataBlock(); @@ -59238,11 +59725,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public GroupAccountDetailsRequestPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -59346,7 +59832,7 @@ public override void FromBytes(byte[] bytes, ref int i) RequestID.FromBytes(bytes, i); i += 16; IntervalDays = Utils.BytesToIntSafepos(bytes, i); i += 4; CurrentInterval = Utils.BytesToIntSafepos(bytes, i); i += 4; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); StartDate = new byte[length]; Buffer.BlockCopy(bytes, i, StartDate, 0, length); i += length; } @@ -59361,7 +59847,7 @@ public override void ToBytes(byte[] bytes, ref int i) RequestID.ToBytes(bytes, i); i += 16; Utils.IntToBytesSafepos(IntervalDays, bytes, i); i += 4; Utils.IntToBytesSafepos(CurrentInterval, bytes, i); i += 4; - bytes[i++] = (byte)StartDate.Length; + Utils.ByteToBytes((byte)StartDate.Length, bytes, ref i); Buffer.BlockCopy(StartDate, 0, bytes, i, StartDate.Length); i += StartDate.Length; } @@ -59394,7 +59880,7 @@ public override void FromBytes(byte[] bytes, ref int i) int length; try { - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Description = new byte[length]; Buffer.BlockCopy(bytes, i, Description, 0, length); i += length; Amount = Utils.BytesToIntSafepos(bytes, i); i += 4; @@ -59407,7 +59893,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = (byte)Description.Length; + Utils.ByteToBytes((byte)Description.Length, bytes, ref i); Buffer.BlockCopy(Description, 0, bytes, i, Description.Length); i += Description.Length; Utils.IntToBytesSafepos(Amount, bytes, i); i += 4; } @@ -59438,6 +59924,7 @@ public GroupAccountDetailsReplyPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 356; Header.Reliable = true; + NeedValidateIDs = false; Header.Zerocoded = true; AgentData = new AgentDataBlock(); MoneyData = new MoneyDataBlock(); @@ -59473,11 +59960,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public GroupAccountDetailsReplyPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -59506,7 +59992,7 @@ public override byte[] ToBytes() Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); MoneyData.ToBytes(bytes, ref i); - bytes[i++] = (byte)HistoryData.Length; + Utils.ByteToBytes((byte)HistoryData.Length, bytes, ref i); for (int j = 0; j < HistoryData.Length; j++) { HistoryData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -59681,6 +60167,8 @@ public override int Length public AgentDataBlock AgentData; public MoneyDataBlock MoneyData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public GroupAccountTransactionsRequestPacket() { HasVariableBlocks = false; @@ -59689,6 +60177,7 @@ public GroupAccountTransactionsRequestPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 357; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); MoneyData = new MoneyDataBlock(); @@ -59714,11 +60203,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public GroupAccountTransactionsRequestPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -59822,7 +60310,7 @@ public override void FromBytes(byte[] bytes, ref int i) RequestID.FromBytes(bytes, i); i += 16; IntervalDays = Utils.BytesToIntSafepos(bytes, i); i += 4; CurrentInterval = Utils.BytesToIntSafepos(bytes, i); i += 4; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); StartDate = new byte[length]; Buffer.BlockCopy(bytes, i, StartDate, 0, length); i += length; } @@ -59837,7 +60325,7 @@ public override void ToBytes(byte[] bytes, ref int i) RequestID.ToBytes(bytes, i); i += 16; Utils.IntToBytesSafepos(IntervalDays, bytes, i); i += 4; Utils.IntToBytesSafepos(CurrentInterval, bytes, i); i += 4; - bytes[i++] = (byte)StartDate.Length; + Utils.ByteToBytes((byte)StartDate.Length, bytes, ref i); Buffer.BlockCopy(StartDate, 0, bytes, i, StartDate.Length); i += StartDate.Length; } @@ -59875,14 +60363,14 @@ public override void FromBytes(byte[] bytes, ref int i) int length; try { - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Time = new byte[length]; Buffer.BlockCopy(bytes, i, Time, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); User = new byte[length]; Buffer.BlockCopy(bytes, i, User, 0, length); i += length; Type = Utils.BytesToIntSafepos(bytes, i); i += 4; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Item = new byte[length]; Buffer.BlockCopy(bytes, i, Item, 0, length); i += length; Amount = Utils.BytesToIntSafepos(bytes, i); i += 4; @@ -59895,12 +60383,12 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = (byte)Time.Length; + Utils.ByteToBytes((byte)Time.Length, bytes, ref i); Buffer.BlockCopy(Time, 0, bytes, i, Time.Length); i += Time.Length; - bytes[i++] = (byte)User.Length; + Utils.ByteToBytes((byte)User.Length, bytes, ref i); Buffer.BlockCopy(User, 0, bytes, i, User.Length); i += User.Length; Utils.IntToBytesSafepos(Type, bytes, i); i += 4; - bytes[i++] = (byte)Item.Length; + Utils.ByteToBytes((byte)Item.Length, bytes, ref i); Buffer.BlockCopy(Item, 0, bytes, i, Item.Length); i += Item.Length; Utils.IntToBytesSafepos(Amount, bytes, i); i += 4; } @@ -59931,6 +60419,7 @@ public GroupAccountTransactionsReplyPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 358; Header.Reliable = true; + NeedValidateIDs = false; Header.Zerocoded = true; AgentData = new AgentDataBlock(); MoneyData = new MoneyDataBlock(); @@ -59966,11 +60455,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public GroupAccountTransactionsReplyPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -59999,7 +60487,7 @@ public override byte[] ToBytes() Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); MoneyData.ToBytes(bytes, ref i); - bytes[i++] = (byte)HistoryData.Length; + Utils.ByteToBytes((byte)HistoryData.Length, bytes, ref i); for (int j = 0; j < HistoryData.Length; j++) { HistoryData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -60205,6 +60693,8 @@ public override int Length public GroupDataBlock GroupData; public TransactionDataBlock TransactionData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public GroupActiveProposalsRequestPacket() { HasVariableBlocks = false; @@ -60213,6 +60703,7 @@ public GroupActiveProposalsRequestPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 359; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); GroupData = new GroupDataBlock(); TransactionData = new TransactionDataBlock(); @@ -60239,11 +60730,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public GroupActiveProposalsRequestPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -60400,22 +60890,22 @@ public override void FromBytes(byte[] bytes, ref int i) { VoteID.FromBytes(bytes, i); i += 16; VoteInitiator.FromBytes(bytes, i); i += 16; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); TerseDateID = new byte[length]; Buffer.BlockCopy(bytes, i, TerseDateID, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); StartDateTime = new byte[length]; Buffer.BlockCopy(bytes, i, StartDateTime, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); EndDateTime = new byte[length]; Buffer.BlockCopy(bytes, i, EndDateTime, 0, length); i += length; - AlreadyVoted = (bytes[i++] != 0) ? (bool)true : (bool)false; - length = bytes[i++]; + AlreadyVoted = (Utils.BytesToByte(bytes, ref i) != 0); + length = Utils.BytesToByte(bytes, ref i); VoteCast = new byte[length]; Buffer.BlockCopy(bytes, i, VoteCast, 0, length); i += length; Majority = Utils.BytesToFloatSafepos(bytes, i); i += 4; Quorum = Utils.BytesToIntSafepos(bytes, i); i += 4; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); ProposalText = new byte[length]; Buffer.BlockCopy(bytes, i, ProposalText, 0, length); i += length; } @@ -60429,18 +60919,18 @@ public override void ToBytes(byte[] bytes, ref int i) { VoteID.ToBytes(bytes, i); i += 16; VoteInitiator.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)TerseDateID.Length; + Utils.ByteToBytes((byte)TerseDateID.Length, bytes, ref i); Buffer.BlockCopy(TerseDateID, 0, bytes, i, TerseDateID.Length); i += TerseDateID.Length; - bytes[i++] = (byte)StartDateTime.Length; + Utils.ByteToBytes((byte)StartDateTime.Length, bytes, ref i); Buffer.BlockCopy(StartDateTime, 0, bytes, i, StartDateTime.Length); i += StartDateTime.Length; - bytes[i++] = (byte)EndDateTime.Length; + Utils.ByteToBytes((byte)EndDateTime.Length, bytes, ref i); Buffer.BlockCopy(EndDateTime, 0, bytes, i, EndDateTime.Length); i += EndDateTime.Length; - bytes[i++] = (byte)((AlreadyVoted) ? 1 : 0); - bytes[i++] = (byte)VoteCast.Length; + Utils.ByteToBytes((byte)((AlreadyVoted) ? 1 : 0), bytes, ref i); + Utils.ByteToBytes((byte)VoteCast.Length, bytes, ref i); Buffer.BlockCopy(VoteCast, 0, bytes, i, VoteCast.Length); i += VoteCast.Length; Utils.FloatToBytesSafepos(Majority, bytes, i); i += 4; Utils.IntToBytesSafepos(Quorum, bytes, i); i += 4; - bytes[i++] = (byte)ProposalText.Length; + Utils.ByteToBytes((byte)ProposalText.Length, bytes, ref i); Buffer.BlockCopy(ProposalText, 0, bytes, i, ProposalText.Length); i += ProposalText.Length; } @@ -60470,6 +60960,7 @@ public GroupActiveProposalItemReplyPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 360; Header.Reliable = true; + NeedValidateIDs = false; Header.Zerocoded = true; AgentData = new AgentDataBlock(); TransactionData = new TransactionDataBlock(); @@ -60505,11 +60996,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public GroupActiveProposalItemReplyPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -60538,7 +61028,7 @@ public override byte[] ToBytes() Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); TransactionData.ToBytes(bytes, ref i); - bytes[i++] = (byte)ProposalData.Length; + Utils.ByteToBytes((byte)ProposalData.Length, bytes, ref i); for (int j = 0; j < ProposalData.Length; j++) { ProposalData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -60744,6 +61234,8 @@ public override int Length public GroupDataBlock GroupData; public TransactionDataBlock TransactionData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public GroupVoteHistoryRequestPacket() { HasVariableBlocks = false; @@ -60752,6 +61244,7 @@ public GroupVoteHistoryRequestPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 361; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); GroupData = new GroupDataBlock(); TransactionData = new TransactionDataBlock(); @@ -60778,11 +61271,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public GroupVoteHistoryRequestPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -60939,25 +61431,25 @@ public override void FromBytes(byte[] bytes, ref int i) try { VoteID.FromBytes(bytes, i); i += 16; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); TerseDateID = new byte[length]; Buffer.BlockCopy(bytes, i, TerseDateID, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); StartDateTime = new byte[length]; Buffer.BlockCopy(bytes, i, StartDateTime, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); EndDateTime = new byte[length]; Buffer.BlockCopy(bytes, i, EndDateTime, 0, length); i += length; VoteInitiator.FromBytes(bytes, i); i += 16; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); VoteType = new byte[length]; Buffer.BlockCopy(bytes, i, VoteType, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); VoteResult = new byte[length]; Buffer.BlockCopy(bytes, i, VoteResult, 0, length); i += length; Majority = Utils.BytesToFloatSafepos(bytes, i); i += 4; Quorum = Utils.BytesToIntSafepos(bytes, i); i += 4; - length = (bytes[i++] + (bytes[i++] << 8)); + length = Utils.BytesToUInt16(bytes, i); i+=2; ProposalText = new byte[length]; Buffer.BlockCopy(bytes, i, ProposalText, 0, length); i += length; } @@ -60970,21 +61462,20 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { VoteID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)TerseDateID.Length; + Utils.ByteToBytes((byte)TerseDateID.Length, bytes, ref i); Buffer.BlockCopy(TerseDateID, 0, bytes, i, TerseDateID.Length); i += TerseDateID.Length; - bytes[i++] = (byte)StartDateTime.Length; + Utils.ByteToBytes((byte)StartDateTime.Length, bytes, ref i); Buffer.BlockCopy(StartDateTime, 0, bytes, i, StartDateTime.Length); i += StartDateTime.Length; - bytes[i++] = (byte)EndDateTime.Length; + Utils.ByteToBytes((byte)EndDateTime.Length, bytes, ref i); Buffer.BlockCopy(EndDateTime, 0, bytes, i, EndDateTime.Length); i += EndDateTime.Length; VoteInitiator.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)VoteType.Length; + Utils.ByteToBytes((byte)VoteType.Length, bytes, ref i); Buffer.BlockCopy(VoteType, 0, bytes, i, VoteType.Length); i += VoteType.Length; - bytes[i++] = (byte)VoteResult.Length; + Utils.ByteToBytes((byte)VoteResult.Length, bytes, ref i); Buffer.BlockCopy(VoteResult, 0, bytes, i, VoteResult.Length); i += VoteResult.Length; Utils.FloatToBytesSafepos(Majority, bytes, i); i += 4; Utils.IntToBytesSafepos(Quorum, bytes, i); i += 4; - bytes[i++] = (byte)(ProposalText.Length % 256); - bytes[i++] = (byte)((ProposalText.Length >> 8) % 256); + Utils.UInt16ToBytes((ushort)ProposalText.Length, bytes, i); i += 2; Buffer.BlockCopy(ProposalText, 0, bytes, i, ProposalText.Length); i += ProposalText.Length; } @@ -61019,7 +61510,7 @@ public override void FromBytes(byte[] bytes, ref int i) try { CandidateID.FromBytes(bytes, i); i += 16; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); VoteCast = new byte[length]; Buffer.BlockCopy(bytes, i, VoteCast, 0, length); i += length; NumVotes = Utils.BytesToIntSafepos(bytes, i); i += 4; @@ -61033,7 +61524,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { CandidateID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)VoteCast.Length; + Utils.ByteToBytes((byte)VoteCast.Length, bytes, ref i); Buffer.BlockCopy(VoteCast, 0, bytes, i, VoteCast.Length); i += VoteCast.Length; Utils.IntToBytesSafepos(NumVotes, bytes, i); i += 4; } @@ -61066,6 +61557,7 @@ public GroupVoteHistoryItemReplyPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 362; Header.Reliable = true; + NeedValidateIDs = false; Header.Zerocoded = true; AgentData = new AgentDataBlock(); TransactionData = new TransactionDataBlock(); @@ -61103,11 +61595,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public GroupVoteHistoryItemReplyPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -61139,7 +61630,7 @@ public override byte[] ToBytes() AgentData.ToBytes(bytes, ref i); TransactionData.ToBytes(bytes, ref i); HistoryItemData.ToBytes(bytes, ref i); - bytes[i++] = (byte)VoteItem.Length; + Utils.ByteToBytes((byte)VoteItem.Length, bytes, ref i); for (int j = 0; j < VoteItem.Length; j++) { VoteItem[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -61290,7 +61781,7 @@ public override void FromBytes(byte[] bytes, ref int i) Quorum = Utils.BytesToIntSafepos(bytes, i); i += 4; Majority = Utils.BytesToFloatSafepos(bytes, i); i += 4; Duration = Utils.BytesToIntSafepos(bytes, i); i += 4; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); ProposalText = new byte[length]; Buffer.BlockCopy(bytes, i, ProposalText, 0, length); i += length; } @@ -61306,7 +61797,7 @@ public override void ToBytes(byte[] bytes, ref int i) Utils.IntToBytesSafepos(Quorum, bytes, i); i += 4; Utils.FloatToBytesSafepos(Majority, bytes, i); i += 4; Utils.IntToBytesSafepos(Duration, bytes, i); i += 4; - bytes[i++] = (byte)ProposalText.Length; + Utils.ByteToBytes((byte)ProposalText.Length, bytes, ref i); Buffer.BlockCopy(ProposalText, 0, bytes, i, ProposalText.Length); i += ProposalText.Length; } @@ -61325,6 +61816,8 @@ public override int Length public AgentDataBlock AgentData; public ProposalDataBlock ProposalData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public StartGroupProposalPacket() { HasVariableBlocks = false; @@ -61333,6 +61826,7 @@ public StartGroupProposalPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 363; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); ProposalData = new ProposalDataBlock(); @@ -61358,11 +61852,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public StartGroupProposalPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -61464,7 +61957,7 @@ public override void FromBytes(byte[] bytes, ref int i) { ProposalID.FromBytes(bytes, i); i += 16; GroupID.FromBytes(bytes, i); i += 16; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); VoteCast = new byte[length]; Buffer.BlockCopy(bytes, i, VoteCast, 0, length); i += length; } @@ -61478,7 +61971,7 @@ public override void ToBytes(byte[] bytes, ref int i) { ProposalID.ToBytes(bytes, i); i += 16; GroupID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)VoteCast.Length; + Utils.ByteToBytes((byte)VoteCast.Length, bytes, ref i); Buffer.BlockCopy(VoteCast, 0, bytes, i, VoteCast.Length); i += VoteCast.Length; } @@ -61497,6 +61990,8 @@ public override int Length public AgentDataBlock AgentData; public ProposalDataBlock ProposalData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public GroupProposalBallotPacket() { HasVariableBlocks = false; @@ -61505,6 +62000,7 @@ public GroupProposalBallotPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 364; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); ProposalData = new ProposalDataBlock(); } @@ -61529,11 +62025,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public GroupProposalBallotPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -61659,6 +62154,8 @@ public override int Length public AgentDataBlock AgentData; public GroupDataBlock GroupData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public GroupMembersRequestPacket() { HasVariableBlocks = false; @@ -61667,6 +62164,7 @@ public GroupMembersRequestPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 366; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); GroupData = new GroupDataBlock(); } @@ -61691,11 +62189,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public GroupMembersRequestPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -61842,14 +62339,14 @@ public override void FromBytes(byte[] bytes, ref int i) { AgentID.FromBytes(bytes, i); i += 16; Contribution = Utils.BytesToIntSafepos(bytes, i); i += 4; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); OnlineStatus = new byte[length]; Buffer.BlockCopy(bytes, i, OnlineStatus, 0, length); i += length; AgentPowers = Utils.BytesToUInt64Safepos(bytes, i); i += 8; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Title = new byte[length]; Buffer.BlockCopy(bytes, i, Title, 0, length); i += length; - IsOwner = (bytes[i++] != 0) ? (bool)true : (bool)false; + IsOwner = (Utils.BytesToByte(bytes, ref i) != 0); } catch (Exception) { @@ -61861,12 +62358,12 @@ public override void ToBytes(byte[] bytes, ref int i) { AgentID.ToBytes(bytes, i); i += 16; Utils.IntToBytesSafepos(Contribution, bytes, i); i += 4; - bytes[i++] = (byte)OnlineStatus.Length; + Utils.ByteToBytes((byte)OnlineStatus.Length, bytes, ref i); Buffer.BlockCopy(OnlineStatus, 0, bytes, i, OnlineStatus.Length); i += OnlineStatus.Length; Utils.UInt64ToBytesSafepos(AgentPowers, bytes, i); i += 8; - bytes[i++] = (byte)Title.Length; + Utils.ByteToBytes((byte)Title.Length, bytes, ref i); Buffer.BlockCopy(Title, 0, bytes, i, Title.Length); i += Title.Length; - bytes[i++] = (byte)((IsOwner) ? 1 : 0); + Utils.ByteToBytes((byte)((IsOwner) ? 1 : 0), bytes, ref i); } } @@ -61895,6 +62392,7 @@ public GroupMembersReplyPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 367; Header.Reliable = true; + NeedValidateIDs = false; Header.Zerocoded = true; AgentData = new AgentDataBlock(); GroupData = new GroupDataBlock(); @@ -61930,11 +62428,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public GroupMembersReplyPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -61963,7 +62460,7 @@ public override byte[] ToBytes() Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); GroupData.ToBytes(bytes, ref i); - bytes[i++] = (byte)MemberData.Length; + Utils.ByteToBytes((byte)MemberData.Length, bytes, ref i); for (int j = 0; j < MemberData.Length; j++) { MemberData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -62092,6 +62589,8 @@ public override int Length } public AgentDataBlock AgentData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ActivateGroupPacket() { HasVariableBlocks = false; @@ -62100,6 +62599,7 @@ public ActivateGroupPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 368; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); } @@ -62123,11 +62623,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ActivateGroupPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -62250,6 +62749,8 @@ public override int Length public AgentDataBlock AgentData; public DataBlock Data; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public SetGroupContributionPacket() { HasVariableBlocks = false; @@ -62258,6 +62759,7 @@ public SetGroupContributionPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 369; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); Data = new DataBlock(); } @@ -62282,11 +62784,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public SetGroupContributionPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -62383,7 +62884,7 @@ public override void FromBytes(byte[] bytes, ref int i) try { GroupID.FromBytes(bytes, i); i += 16; - AcceptNotices = (bytes[i++] != 0) ? (bool)true : (bool)false; + AcceptNotices = (Utils.BytesToByte(bytes, ref i) != 0); } catch (Exception) { @@ -62394,7 +62895,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { GroupID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)((AcceptNotices) ? 1 : 0); + Utils.ByteToBytes((byte)((AcceptNotices) ? 1 : 0), bytes, ref i); } } @@ -62422,7 +62923,7 @@ public override void FromBytes(byte[] bytes, ref int i) { try { - ListInProfile = (bytes[i++] != 0) ? (bool)true : (bool)false; + ListInProfile = (Utils.BytesToByte(bytes, ref i) != 0); } catch (Exception) { @@ -62432,7 +62933,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = (byte)((ListInProfile) ? 1 : 0); + Utils.ByteToBytes((byte)((ListInProfile) ? 1 : 0), bytes, ref i); } } @@ -62452,6 +62953,8 @@ public override int Length public DataBlock Data; public NewDataBlock NewData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public SetGroupAcceptNoticesPacket() { HasVariableBlocks = false; @@ -62460,6 +62963,7 @@ public SetGroupAcceptNoticesPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 370; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); Data = new DataBlock(); NewData = new NewDataBlock(); @@ -62486,11 +62990,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public SetGroupAcceptNoticesPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -62619,6 +63122,8 @@ public override int Length public AgentDataBlock AgentData; public GroupDataBlock GroupData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public GroupRoleDataRequestPacket() { HasVariableBlocks = false; @@ -62627,6 +63132,7 @@ public GroupRoleDataRequestPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 371; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); GroupData = new GroupDataBlock(); } @@ -62651,11 +63157,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public GroupRoleDataRequestPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -62802,13 +63307,13 @@ public override void FromBytes(byte[] bytes, ref int i) try { RoleID.FromBytes(bytes, i); i += 16; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Name = new byte[length]; Buffer.BlockCopy(bytes, i, Name, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Title = new byte[length]; Buffer.BlockCopy(bytes, i, Title, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Description = new byte[length]; Buffer.BlockCopy(bytes, i, Description, 0, length); i += length; Powers = Utils.BytesToUInt64Safepos(bytes, i); i += 8; @@ -62823,11 +63328,11 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { RoleID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)Name.Length; + Utils.ByteToBytes((byte)Name.Length, bytes, ref i); Buffer.BlockCopy(Name, 0, bytes, i, Name.Length); i += Name.Length; - bytes[i++] = (byte)Title.Length; + Utils.ByteToBytes((byte)Title.Length, bytes, ref i); Buffer.BlockCopy(Title, 0, bytes, i, Title.Length); i += Title.Length; - bytes[i++] = (byte)Description.Length; + Utils.ByteToBytes((byte)Description.Length, bytes, ref i); Buffer.BlockCopy(Description, 0, bytes, i, Description.Length); i += Description.Length; Utils.UInt64ToBytesSafepos(Powers, bytes, i); i += 8; Utils.UIntToBytesSafepos(Members, bytes, i); i += 4; @@ -62859,6 +63364,7 @@ public GroupRoleDataReplyPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 372; Header.Reliable = true; + NeedValidateIDs = false; AgentData = new AgentDataBlock(); GroupData = new GroupDataBlock(); RoleData = null; @@ -62893,11 +63399,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public GroupRoleDataReplyPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -62926,7 +63431,7 @@ public override byte[] ToBytes() Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); GroupData.ToBytes(bytes, ref i); - bytes[i++] = (byte)RoleData.Length; + Utils.ByteToBytes((byte)RoleData.Length, bytes, ref i); for (int j = 0; j < RoleData.Length; j++) { RoleData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -63095,6 +63600,8 @@ public override int Length public AgentDataBlock AgentData; public GroupDataBlock GroupData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public GroupRoleMembersRequestPacket() { HasVariableBlocks = false; @@ -63103,6 +63610,7 @@ public GroupRoleMembersRequestPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 373; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); GroupData = new GroupDataBlock(); } @@ -63127,11 +63635,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public GroupRoleMembersRequestPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -63272,6 +63779,7 @@ public GroupRoleMembersReplyPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 374; Header.Reliable = true; + NeedValidateIDs = false; AgentData = new AgentDataBlock(); MemberData = null; } @@ -63304,11 +63812,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public GroupRoleMembersReplyPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -63334,7 +63841,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)MemberData.Length; + Utils.ByteToBytes((byte)MemberData.Length, bytes, ref i); for (int j = 0; j < MemberData.Length; j++) { MemberData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -63464,6 +63971,8 @@ public override int Length } public AgentDataBlock AgentData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public GroupTitlesRequestPacket() { HasVariableBlocks = false; @@ -63472,6 +63981,7 @@ public GroupTitlesRequestPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 375; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); } @@ -63494,11 +64004,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public GroupTitlesRequestPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -63598,11 +64107,11 @@ public override void FromBytes(byte[] bytes, ref int i) int length; try { - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Title = new byte[length]; Buffer.BlockCopy(bytes, i, Title, 0, length); i += length; RoleID.FromBytes(bytes, i); i += 16; - Selected = (bytes[i++] != 0) ? (bool)true : (bool)false; + Selected = (Utils.BytesToByte(bytes, ref i) != 0); } catch (Exception) { @@ -63612,10 +64121,10 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = (byte)Title.Length; + Utils.ByteToBytes((byte)Title.Length, bytes, ref i); Buffer.BlockCopy(Title, 0, bytes, i, Title.Length); i += Title.Length; RoleID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)((Selected) ? 1 : 0); + Utils.ByteToBytes((byte)((Selected) ? 1 : 0), bytes, ref i); } } @@ -63642,6 +64151,7 @@ public GroupTitlesReplyPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 376; Header.Reliable = true; + NeedValidateIDs = false; Header.Zerocoded = true; AgentData = new AgentDataBlock(); GroupData = null; @@ -63675,11 +64185,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public GroupTitlesReplyPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -63705,7 +64214,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)GroupData.Length; + Utils.ByteToBytes((byte)GroupData.Length, bytes, ref i); for (int j = 0; j < GroupData.Length; j++) { GroupData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -63835,6 +64344,8 @@ public override int Length } public AgentDataBlock AgentData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public GroupTitleUpdatePacket() { HasVariableBlocks = false; @@ -63843,6 +64354,7 @@ public GroupTitleUpdatePacket() Header.Frequency = PacketFrequency.Low; Header.ID = 377; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); } @@ -63865,11 +64377,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public GroupTitleUpdatePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -63975,17 +64486,17 @@ public override void FromBytes(byte[] bytes, ref int i) try { RoleID.FromBytes(bytes, i); i += 16; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Name = new byte[length]; Buffer.BlockCopy(bytes, i, Name, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Description = new byte[length]; Buffer.BlockCopy(bytes, i, Description, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Title = new byte[length]; Buffer.BlockCopy(bytes, i, Title, 0, length); i += length; Powers = Utils.BytesToUInt64Safepos(bytes, i); i += 8; - UpdateType = (byte)bytes[i++]; + UpdateType = Utils.BytesToByte(bytes, ref i); } catch (Exception) { @@ -63996,14 +64507,14 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { RoleID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)Name.Length; + Utils.ByteToBytes((byte)Name.Length, bytes, ref i); Buffer.BlockCopy(Name, 0, bytes, i, Name.Length); i += Name.Length; - bytes[i++] = (byte)Description.Length; + Utils.ByteToBytes((byte)Description.Length, bytes, ref i); Buffer.BlockCopy(Description, 0, bytes, i, Description.Length); i += Description.Length; - bytes[i++] = (byte)Title.Length; + Utils.ByteToBytes((byte)Title.Length, bytes, ref i); Buffer.BlockCopy(Title, 0, bytes, i, Title.Length); i += Title.Length; Utils.UInt64ToBytesSafepos(Powers, bytes, i); i += 8; - bytes[i++] = UpdateType; + Utils.ByteToBytes( UpdateType, bytes, ref i); } } @@ -64022,6 +64533,8 @@ public override int Length public AgentDataBlock AgentData; public RoleDataBlock[] RoleData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public GroupRoleUpdatePacket() { HasVariableBlocks = true; @@ -64030,6 +64543,7 @@ public GroupRoleUpdatePacket() Header.Frequency = PacketFrequency.Low; Header.ID = 378; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); RoleData = null; } @@ -64062,11 +64576,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public GroupRoleUpdatePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -64092,7 +64605,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)RoleData.Length; + Utils.ByteToBytes((byte)RoleData.Length, bytes, ref i); for (int j = 0; j < RoleData.Length; j++) { RoleData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -64224,6 +64737,7 @@ public LiveHelpGroupRequestPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 379; Header.Reliable = true; + NeedValidateIDs = false; RequestData = new RequestDataBlock(); } @@ -64246,11 +64760,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public LiveHelpGroupRequestPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; RequestData.FromBytes(bytes, ref i); @@ -64308,7 +64821,7 @@ public override void FromBytes(byte[] bytes, ref int i) { RequestID.FromBytes(bytes, i); i += 16; GroupID.FromBytes(bytes, i); i += 16; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Selection = new byte[length]; Buffer.BlockCopy(bytes, i, Selection, 0, length); i += length; } @@ -64322,7 +64835,7 @@ public override void ToBytes(byte[] bytes, ref int i) { RequestID.ToBytes(bytes, i); i += 16; GroupID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)Selection.Length; + Utils.ByteToBytes((byte)Selection.Length, bytes, ref i); Buffer.BlockCopy(Selection, 0, bytes, i, Selection.Length); i += Selection.Length; } @@ -64347,6 +64860,7 @@ public LiveHelpGroupReplyPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 380; Header.Reliable = true; + NeedValidateIDs = false; ReplyData = new ReplyDataBlock(); } @@ -64369,11 +64883,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public LiveHelpGroupReplyPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; ReplyData.FromBytes(bytes, ref i); @@ -64453,6 +64966,8 @@ public override int Length } public AgentDataBlock AgentData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public AgentWearablesRequestPacket() { HasVariableBlocks = false; @@ -64461,6 +64976,7 @@ public AgentWearablesRequestPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 381; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); } @@ -64483,11 +64999,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public AgentWearablesRequestPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -64586,7 +65101,7 @@ public override void FromBytes(byte[] bytes, ref int i) { ItemID.FromBytes(bytes, i); i += 16; AssetID.FromBytes(bytes, i); i += 16; - WearableType = (byte)bytes[i++]; + WearableType = Utils.BytesToByte(bytes, ref i); } catch (Exception) { @@ -64598,7 +65113,7 @@ public override void ToBytes(byte[] bytes, ref int i) { ItemID.ToBytes(bytes, i); i += 16; AssetID.ToBytes(bytes, i); i += 16; - bytes[i++] = WearableType; + Utils.ByteToBytes( WearableType, bytes, ref i); } } @@ -64617,6 +65132,8 @@ public override int Length public AgentDataBlock AgentData; public WearableDataBlock[] WearableData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public AgentWearablesUpdatePacket() { HasVariableBlocks = true; @@ -64625,6 +65142,7 @@ public AgentWearablesUpdatePacket() Header.Frequency = PacketFrequency.Low; Header.ID = 382; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); WearableData = null; @@ -64658,11 +65176,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public AgentWearablesUpdatePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -64688,7 +65205,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)WearableData.Length; + Utils.ByteToBytes((byte)WearableData.Length, bytes, ref i); for (int j = 0; j < WearableData.Length; j++) { WearableData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -64826,7 +65343,7 @@ public override void FromBytes(byte[] bytes, ref int i) try { ItemID.FromBytes(bytes, i); i += 16; - WearableType = (byte)bytes[i++]; + WearableType = Utils.BytesToByte(bytes, ref i); } catch (Exception) { @@ -64837,7 +65354,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { ItemID.ToBytes(bytes, i); i += 16; - bytes[i++] = WearableType; + Utils.ByteToBytes( WearableType, bytes, ref i); } } @@ -64856,6 +65373,8 @@ public override int Length public AgentDataBlock AgentData; public WearableDataBlock[] WearableData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public AgentIsNowWearingPacket() { HasVariableBlocks = true; @@ -64864,6 +65383,7 @@ public AgentIsNowWearingPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 383; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); WearableData = null; @@ -64897,11 +65417,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public AgentIsNowWearingPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -64927,7 +65446,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)WearableData.Length; + Utils.ByteToBytes((byte)WearableData.Length, bytes, ref i); for (int j = 0; j < WearableData.Length; j++) { WearableData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -65068,7 +65587,7 @@ public override void FromBytes(byte[] bytes, ref int i) try { ID.FromBytes(bytes, i); i += 16; - TextureIndex = (byte)bytes[i++]; + TextureIndex = Utils.BytesToByte(bytes, ref i); } catch (Exception) { @@ -65079,7 +65598,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { ID.ToBytes(bytes, i); i += 16; - bytes[i++] = TextureIndex; + Utils.ByteToBytes( TextureIndex, bytes, ref i); } } @@ -65098,6 +65617,8 @@ public override int Length public AgentDataBlock AgentData; public WearableDataBlock[] WearableData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public AgentCachedTexturePacket() { HasVariableBlocks = true; @@ -65106,6 +65627,7 @@ public AgentCachedTexturePacket() Header.Frequency = PacketFrequency.Low; Header.ID = 384; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); WearableData = null; } @@ -65138,11 +65660,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public AgentCachedTexturePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -65168,7 +65689,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)WearableData.Length; + Utils.ByteToBytes((byte)WearableData.Length, bytes, ref i); for (int j = 0; j < WearableData.Length; j++) { WearableData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -65313,8 +65834,8 @@ public override void FromBytes(byte[] bytes, ref int i) try { TextureID.FromBytes(bytes, i); i += 16; - TextureIndex = (byte)bytes[i++]; - length = bytes[i++]; + TextureIndex = Utils.BytesToByte(bytes, ref i); + length = Utils.BytesToByte(bytes, ref i); HostName = new byte[length]; Buffer.BlockCopy(bytes, i, HostName, 0, length); i += length; } @@ -65327,8 +65848,8 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { TextureID.ToBytes(bytes, i); i += 16; - bytes[i++] = TextureIndex; - bytes[i++] = (byte)HostName.Length; + Utils.ByteToBytes( TextureIndex, bytes, ref i); + Utils.ByteToBytes((byte)HostName.Length, bytes, ref i); Buffer.BlockCopy(HostName, 0, bytes, i, HostName.Length); i += HostName.Length; } @@ -65348,6 +65869,8 @@ public override int Length public AgentDataBlock AgentData; public WearableDataBlock[] WearableData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public AgentCachedTextureResponsePacket() { HasVariableBlocks = true; @@ -65356,6 +65879,7 @@ public AgentCachedTextureResponsePacket() Header.Frequency = PacketFrequency.Low; Header.ID = 385; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); WearableData = null; } @@ -65388,11 +65912,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public AgentCachedTextureResponsePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -65418,7 +65941,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)WearableData.Length; + Utils.ByteToBytes((byte)WearableData.Length, bytes, ref i); for (int j = 0; j < WearableData.Length; j++) { WearableData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -65542,6 +66065,8 @@ public override int Length } public AgentDataBlock AgentData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public AgentDataUpdateRequestPacket() { HasVariableBlocks = false; @@ -65550,6 +66075,7 @@ public AgentDataUpdateRequestPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 386; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); } @@ -65572,11 +66098,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public AgentDataUpdateRequestPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -65640,18 +66165,18 @@ public override void FromBytes(byte[] bytes, ref int i) try { AgentID.FromBytes(bytes, i); i += 16; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); FirstName = new byte[length]; Buffer.BlockCopy(bytes, i, FirstName, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); LastName = new byte[length]; Buffer.BlockCopy(bytes, i, LastName, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); GroupTitle = new byte[length]; Buffer.BlockCopy(bytes, i, GroupTitle, 0, length); i += length; ActiveGroupID.FromBytes(bytes, i); i += 16; GroupPowers = Utils.BytesToUInt64Safepos(bytes, i); i += 8; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); GroupName = new byte[length]; Buffer.BlockCopy(bytes, i, GroupName, 0, length); i += length; } @@ -65664,15 +66189,15 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { AgentID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)FirstName.Length; + Utils.ByteToBytes((byte)FirstName.Length, bytes, ref i); Buffer.BlockCopy(FirstName, 0, bytes, i, FirstName.Length); i += FirstName.Length; - bytes[i++] = (byte)LastName.Length; + Utils.ByteToBytes((byte)LastName.Length, bytes, ref i); Buffer.BlockCopy(LastName, 0, bytes, i, LastName.Length); i += LastName.Length; - bytes[i++] = (byte)GroupTitle.Length; + Utils.ByteToBytes((byte)GroupTitle.Length, bytes, ref i); Buffer.BlockCopy(GroupTitle, 0, bytes, i, GroupTitle.Length); i += GroupTitle.Length; ActiveGroupID.ToBytes(bytes, i); i += 16; Utils.UInt64ToBytesSafepos(GroupPowers, bytes, i); i += 8; - bytes[i++] = (byte)GroupName.Length; + Utils.ByteToBytes((byte)GroupName.Length, bytes, ref i); Buffer.BlockCopy(GroupName, 0, bytes, i, GroupName.Length); i += GroupName.Length; } @@ -65697,6 +66222,7 @@ public AgentDataUpdatePacket() Header.Frequency = PacketFrequency.Low; Header.ID = 387; Header.Reliable = true; + NeedValidateIDs = false; Header.Zerocoded = true; AgentData = new AgentDataBlock(); } @@ -65720,11 +66246,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public AgentDataUpdatePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -65784,7 +66309,7 @@ public override void FromBytes(byte[] bytes, ref int i) AgentID.FromBytes(bytes, i); i += 16; GroupID.FromBytes(bytes, i); i += 16; AgentPowers = Utils.BytesToUInt64Safepos(bytes, i); i += 8; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); GroupTitle = new byte[length]; Buffer.BlockCopy(bytes, i, GroupTitle, 0, length); i += length; } @@ -65799,7 +66324,7 @@ public override void ToBytes(byte[] bytes, ref int i) AgentID.ToBytes(bytes, i); i += 16; GroupID.ToBytes(bytes, i); i += 16; Utils.UInt64ToBytesSafepos(AgentPowers, bytes, i); i += 8; - bytes[i++] = (byte)GroupTitle.Length; + Utils.ByteToBytes((byte)GroupTitle.Length, bytes, ref i); Buffer.BlockCopy(GroupTitle, 0, bytes, i, GroupTitle.Length); i += GroupTitle.Length; } @@ -65825,6 +66350,7 @@ public GroupDataUpdatePacket() Header.Frequency = PacketFrequency.Low; Header.ID = 388; Header.Reliable = true; + NeedValidateIDs = false; Header.Zerocoded = true; AgentGroupData = null; } @@ -65856,11 +66382,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public GroupDataUpdatePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; int count = (int)bytes[i++]; @@ -65883,7 +66408,7 @@ public override byte[] ToBytes() byte[] bytes = new byte[length]; int i = 0; Header.ToBytes(bytes, ref i); - bytes[i++] = (byte)AgentGroupData.Length; + Utils.ByteToBytes((byte)AgentGroupData.Length, bytes, ref i); for (int j = 0; j < AgentGroupData.Length; j++) { AgentGroupData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -66024,10 +66549,10 @@ public override void FromBytes(byte[] bytes, ref int i) { GroupID.FromBytes(bytes, i); i += 16; GroupPowers = Utils.BytesToUInt64Safepos(bytes, i); i += 8; - AcceptNotices = (bytes[i++] != 0) ? (bool)true : (bool)false; + AcceptNotices = (Utils.BytesToByte(bytes, ref i) != 0); GroupInsigniaID.FromBytes(bytes, i); i += 16; Contribution = Utils.BytesToIntSafepos(bytes, i); i += 4; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); GroupName = new byte[length]; Buffer.BlockCopy(bytes, i, GroupName, 0, length); i += length; } @@ -66041,10 +66566,10 @@ public override void ToBytes(byte[] bytes, ref int i) { GroupID.ToBytes(bytes, i); i += 16; Utils.UInt64ToBytesSafepos(GroupPowers, bytes, i); i += 8; - bytes[i++] = (byte)((AcceptNotices) ? 1 : 0); + Utils.ByteToBytes((byte)((AcceptNotices) ? 1 : 0), bytes, ref i); GroupInsigniaID.ToBytes(bytes, i); i += 16; Utils.IntToBytesSafepos(Contribution, bytes, i); i += 4; - bytes[i++] = (byte)GroupName.Length; + Utils.ByteToBytes((byte)GroupName.Length, bytes, ref i); Buffer.BlockCopy(GroupName, 0, bytes, i, GroupName.Length); i += GroupName.Length; } @@ -66072,6 +66597,7 @@ public AgentGroupDataUpdatePacket() Header.Frequency = PacketFrequency.Low; Header.ID = 389; Header.Reliable = true; + NeedValidateIDs = false; Header.Zerocoded = true; AgentData = new AgentDataBlock(); GroupData = null; @@ -66105,11 +66631,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public AgentGroupDataUpdatePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -66135,7 +66660,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)GroupData.Length; + Utils.ByteToBytes((byte)GroupData.Length, bytes, ref i); for (int j = 0; j < GroupData.Length; j++) { GroupData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -66267,6 +66792,7 @@ public AgentDropGroupPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 390; Header.Reliable = true; + NeedValidateIDs = false; Header.Zerocoded = true; AgentData = new AgentDataBlock(); } @@ -66290,11 +66816,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public AgentDropGroupPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -66400,15 +66925,15 @@ public override void FromBytes(byte[] bytes, ref int i) { ItemID.FromBytes(bytes, i); i += 16; OwnerID.FromBytes(bytes, i); i += 16; - AttachmentPt = (byte)bytes[i++]; + AttachmentPt = Utils.BytesToByte(bytes, ref i); ItemFlags = Utils.BytesToUIntSafepos(bytes, i); i += 4; GroupMask = Utils.BytesToUIntSafepos(bytes, i); i += 4; EveryoneMask = Utils.BytesToUIntSafepos(bytes, i); i += 4; NextOwnerMask = Utils.BytesToUIntSafepos(bytes, i); i += 4; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Name = new byte[length]; Buffer.BlockCopy(bytes, i, Name, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Description = new byte[length]; Buffer.BlockCopy(bytes, i, Description, 0, length); i += length; } @@ -66422,14 +66947,14 @@ public override void ToBytes(byte[] bytes, ref int i) { ItemID.ToBytes(bytes, i); i += 16; OwnerID.ToBytes(bytes, i); i += 16; - bytes[i++] = AttachmentPt; + Utils.ByteToBytes( AttachmentPt, bytes, ref i); Utils.UIntToBytesSafepos(ItemFlags, bytes, i); i += 4; Utils.UIntToBytesSafepos(GroupMask, bytes, i); i += 4; Utils.UIntToBytesSafepos(EveryoneMask, bytes, i); i += 4; Utils.UIntToBytesSafepos(NextOwnerMask, bytes, i); i += 4; - bytes[i++] = (byte)Name.Length; + Utils.ByteToBytes((byte)Name.Length, bytes, ref i); Buffer.BlockCopy(Name, 0, bytes, i, Name.Length); i += Name.Length; - bytes[i++] = (byte)Description.Length; + Utils.ByteToBytes((byte)Description.Length, bytes, ref i); Buffer.BlockCopy(Description, 0, bytes, i, Description.Length); i += Description.Length; } @@ -66448,6 +66973,8 @@ public override int Length public AgentDataBlock AgentData; public ObjectDataBlock ObjectData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public RezSingleAttachmentFromInvPacket() { HasVariableBlocks = false; @@ -66456,6 +66983,7 @@ public RezSingleAttachmentFromInvPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 395; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); ObjectData = new ObjectDataBlock(); @@ -66481,11 +67009,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public RezSingleAttachmentFromInvPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -66583,8 +67110,8 @@ public override void FromBytes(byte[] bytes, ref int i) try { CompoundMsgID.FromBytes(bytes, i); i += 16; - TotalObjects = (byte)bytes[i++]; - FirstDetachAll = (bytes[i++] != 0) ? (bool)true : (bool)false; + TotalObjects = Utils.BytesToByte(bytes, ref i); + FirstDetachAll = (Utils.BytesToByte(bytes, ref i) != 0); } catch (Exception) { @@ -66595,8 +67122,8 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { CompoundMsgID.ToBytes(bytes, i); i += 16; - bytes[i++] = TotalObjects; - bytes[i++] = (byte)((FirstDetachAll) ? 1 : 0); + Utils.ByteToBytes( TotalObjects, bytes, ref i); + Utils.ByteToBytes((byte)((FirstDetachAll) ? 1 : 0), bytes, ref i); } } @@ -66638,15 +67165,15 @@ public override void FromBytes(byte[] bytes, ref int i) { ItemID.FromBytes(bytes, i); i += 16; OwnerID.FromBytes(bytes, i); i += 16; - AttachmentPt = (byte)bytes[i++]; + AttachmentPt = Utils.BytesToByte(bytes, ref i); ItemFlags = Utils.BytesToUIntSafepos(bytes, i); i += 4; GroupMask = Utils.BytesToUIntSafepos(bytes, i); i += 4; EveryoneMask = Utils.BytesToUIntSafepos(bytes, i); i += 4; NextOwnerMask = Utils.BytesToUIntSafepos(bytes, i); i += 4; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Name = new byte[length]; Buffer.BlockCopy(bytes, i, Name, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Description = new byte[length]; Buffer.BlockCopy(bytes, i, Description, 0, length); i += length; } @@ -66660,14 +67187,14 @@ public override void ToBytes(byte[] bytes, ref int i) { ItemID.ToBytes(bytes, i); i += 16; OwnerID.ToBytes(bytes, i); i += 16; - bytes[i++] = AttachmentPt; + Utils.ByteToBytes( AttachmentPt, bytes, ref i); Utils.UIntToBytesSafepos(ItemFlags, bytes, i); i += 4; Utils.UIntToBytesSafepos(GroupMask, bytes, i); i += 4; Utils.UIntToBytesSafepos(EveryoneMask, bytes, i); i += 4; Utils.UIntToBytesSafepos(NextOwnerMask, bytes, i); i += 4; - bytes[i++] = (byte)Name.Length; + Utils.ByteToBytes((byte)Name.Length, bytes, ref i); Buffer.BlockCopy(Name, 0, bytes, i, Name.Length); i += Name.Length; - bytes[i++] = (byte)Description.Length; + Utils.ByteToBytes((byte)Description.Length, bytes, ref i); Buffer.BlockCopy(Description, 0, bytes, i, Description.Length); i += Description.Length; } @@ -66689,6 +67216,8 @@ public override int Length public HeaderDataBlock HeaderData; public ObjectDataBlock[] ObjectData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public RezMultipleAttachmentsFromInvPacket() { HasVariableBlocks = true; @@ -66697,6 +67226,7 @@ public RezMultipleAttachmentsFromInvPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 396; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); HeaderData = new HeaderDataBlock(); @@ -66732,11 +67262,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public RezMultipleAttachmentsFromInvPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -66765,7 +67294,7 @@ public override byte[] ToBytes() Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); HeaderData.ToBytes(bytes, ref i); - bytes[i++] = (byte)ObjectData.Length; + Utils.ByteToBytes((byte)ObjectData.Length, bytes, ref i); for (int j = 0; j < ObjectData.Length; j++) { ObjectData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -66899,6 +67428,7 @@ public DetachAttachmentIntoInvPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 397; Header.Reliable = true; + NeedValidateIDs = false; ObjectData = new ObjectDataBlock(); } @@ -66921,11 +67451,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public DetachAttachmentIntoInvPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; ObjectData.FromBytes(bytes, ref i); @@ -67089,6 +67618,8 @@ public override int Length public HeaderDataBlock HeaderData; public ObjectDataBlock[] ObjectData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public CreateNewOutfitAttachmentsPacket() { HasVariableBlocks = true; @@ -67097,6 +67628,7 @@ public CreateNewOutfitAttachmentsPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 398; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); HeaderData = new HeaderDataBlock(); ObjectData = null; @@ -67131,11 +67663,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public CreateNewOutfitAttachmentsPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -67164,7 +67695,7 @@ public override byte[] ToBytes() Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); HeaderData.ToBytes(bytes, ref i); - bytes[i++] = (byte)ObjectData.Length; + Utils.ByteToBytes((byte)ObjectData.Length, bytes, ref i); for (int j = 0; j < ObjectData.Length; j++) { ObjectData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -67290,6 +67821,8 @@ public override int Length } public AgentDataBlock AgentData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public UserInfoRequestPacket() { HasVariableBlocks = false; @@ -67298,6 +67831,7 @@ public UserInfoRequestPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 399; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); } @@ -67320,11 +67854,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public UserInfoRequestPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -67419,11 +67952,11 @@ public override void FromBytes(byte[] bytes, ref int i) int length; try { - IMViaEMail = (bytes[i++] != 0) ? (bool)true : (bool)false; - length = bytes[i++]; + IMViaEMail = (Utils.BytesToByte(bytes, ref i) != 0); + length = Utils.BytesToByte(bytes, ref i); DirectoryVisibility = new byte[length]; Buffer.BlockCopy(bytes, i, DirectoryVisibility, 0, length); i += length; - length = (bytes[i++] + (bytes[i++] << 8)); + length = Utils.BytesToUInt16(bytes, i); i+=2; EMail = new byte[length]; Buffer.BlockCopy(bytes, i, EMail, 0, length); i += length; } @@ -67435,11 +67968,10 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = (byte)((IMViaEMail) ? 1 : 0); - bytes[i++] = (byte)DirectoryVisibility.Length; + Utils.ByteToBytes((byte)((IMViaEMail) ? 1 : 0), bytes, ref i); + Utils.ByteToBytes((byte)DirectoryVisibility.Length, bytes, ref i); Buffer.BlockCopy(DirectoryVisibility, 0, bytes, i, DirectoryVisibility.Length); i += DirectoryVisibility.Length; - bytes[i++] = (byte)(EMail.Length % 256); - bytes[i++] = (byte)((EMail.Length >> 8) % 256); + Utils.UInt16ToBytes((ushort)EMail.Length, bytes, i); i += 2; Buffer.BlockCopy(EMail, 0, bytes, i, EMail.Length); i += EMail.Length; } @@ -67466,6 +67998,7 @@ public UserInfoReplyPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 400; Header.Reliable = true; + NeedValidateIDs = false; AgentData = new AgentDataBlock(); UserData = new UserDataBlock(); } @@ -67490,11 +68023,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public UserInfoReplyPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -67593,8 +68125,8 @@ public override void FromBytes(byte[] bytes, ref int i) int length; try { - IMViaEMail = (bytes[i++] != 0) ? (bool)true : (bool)false; - length = bytes[i++]; + IMViaEMail = (Utils.BytesToByte(bytes, ref i) != 0); + length = Utils.BytesToByte(bytes, ref i); DirectoryVisibility = new byte[length]; Buffer.BlockCopy(bytes, i, DirectoryVisibility, 0, length); i += length; } @@ -67606,8 +68138,8 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = (byte)((IMViaEMail) ? 1 : 0); - bytes[i++] = (byte)DirectoryVisibility.Length; + Utils.ByteToBytes((byte)((IMViaEMail) ? 1 : 0), bytes, ref i); + Utils.ByteToBytes((byte)DirectoryVisibility.Length, bytes, ref i); Buffer.BlockCopy(DirectoryVisibility, 0, bytes, i, DirectoryVisibility.Length); i += DirectoryVisibility.Length; } @@ -67626,6 +68158,8 @@ public override int Length public AgentDataBlock AgentData; public UserDataBlock UserData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public UpdateUserInfoPacket() { HasVariableBlocks = false; @@ -67634,6 +68168,7 @@ public UpdateUserInfoPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 401; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); UserData = new UserDataBlock(); } @@ -67658,11 +68193,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public UpdateUserInfoPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -67759,10 +68293,10 @@ public override void FromBytes(byte[] bytes, ref int i) int length; try { - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); SimFilename = new byte[length]; Buffer.BlockCopy(bytes, i, SimFilename, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); ViewerFilename = new byte[length]; Buffer.BlockCopy(bytes, i, ViewerFilename, 0, length); i += length; } @@ -67774,9 +68308,9 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = (byte)SimFilename.Length; + Utils.ByteToBytes((byte)SimFilename.Length, bytes, ref i); Buffer.BlockCopy(SimFilename, 0, bytes, i, SimFilename.Length); i += SimFilename.Length; - bytes[i++] = (byte)ViewerFilename.Length; + Utils.ByteToBytes((byte)ViewerFilename.Length, bytes, ref i); Buffer.BlockCopy(ViewerFilename, 0, bytes, i, ViewerFilename.Length); i += ViewerFilename.Length; } @@ -67803,6 +68337,7 @@ public InitiateDownloadPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 403; Header.Reliable = true; + NeedValidateIDs = false; AgentData = new AgentDataBlock(); FileData = new FileDataBlock(); } @@ -67827,11 +68362,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public InitiateDownloadPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -67893,7 +68427,7 @@ public override void FromBytes(byte[] bytes, ref int i) SessionID.FromBytes(bytes, i); i += 16; Flags = Utils.BytesToUIntSafepos(bytes, i); i += 4; EstateID = Utils.BytesToUIntSafepos(bytes, i); i += 4; - Godlike = (bytes[i++] != 0) ? (bool)true : (bool)false; + Godlike = (Utils.BytesToByte(bytes, ref i) != 0); } catch (Exception) { @@ -67907,7 +68441,7 @@ public override void ToBytes(byte[] bytes, ref int i) SessionID.ToBytes(bytes, i); i += 16; Utils.UIntToBytesSafepos(Flags, bytes, i); i += 4; Utils.UIntToBytesSafepos(EstateID, bytes, i); i += 4; - bytes[i++] = (byte)((Godlike) ? 1 : 0); + Utils.ByteToBytes((byte)((Godlike) ? 1 : 0), bytes, ref i); } } @@ -67923,6 +68457,8 @@ public override int Length } public AgentDataBlock AgentData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public MapLayerRequestPacket() { HasVariableBlocks = false; @@ -67931,6 +68467,7 @@ public MapLayerRequestPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 405; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); } @@ -67953,11 +68490,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public MapLayerRequestPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -68098,6 +68634,7 @@ public MapLayerReplyPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 406; Header.Reliable = true; + NeedValidateIDs = false; AgentData = new AgentDataBlock(); LayerData = null; } @@ -68130,11 +68667,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public MapLayerReplyPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -68160,7 +68696,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)LayerData.Length; + Utils.ByteToBytes((byte)LayerData.Length, bytes, ref i); for (int j = 0; j < LayerData.Length; j++) { LayerData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -68263,7 +68799,7 @@ public override void FromBytes(byte[] bytes, ref int i) SessionID.FromBytes(bytes, i); i += 16; Flags = Utils.BytesToUIntSafepos(bytes, i); i += 4; EstateID = Utils.BytesToUIntSafepos(bytes, i); i += 4; - Godlike = (bytes[i++] != 0) ? (bool)true : (bool)false; + Godlike = (Utils.BytesToByte(bytes, ref i) != 0); } catch (Exception) { @@ -68277,7 +68813,7 @@ public override void ToBytes(byte[] bytes, ref int i) SessionID.ToBytes(bytes, i); i += 16; Utils.UIntToBytesSafepos(Flags, bytes, i); i += 4; Utils.UIntToBytesSafepos(EstateID, bytes, i); i += 4; - bytes[i++] = (byte)((Godlike) ? 1 : 0); + Utils.ByteToBytes((byte)((Godlike) ? 1 : 0), bytes, ref i); } } @@ -68342,6 +68878,8 @@ public override int Length public AgentDataBlock AgentData; public PositionDataBlock PositionData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public MapBlockRequestPacket() { HasVariableBlocks = false; @@ -68350,6 +68888,7 @@ public MapBlockRequestPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 407; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); PositionData = new PositionDataBlock(); } @@ -68374,11 +68913,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public MapBlockRequestPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -68440,7 +68978,7 @@ public override void FromBytes(byte[] bytes, ref int i) SessionID.FromBytes(bytes, i); i += 16; Flags = Utils.BytesToUIntSafepos(bytes, i); i += 4; EstateID = Utils.BytesToUIntSafepos(bytes, i); i += 4; - Godlike = (bytes[i++] != 0) ? (bool)true : (bool)false; + Godlike = (Utils.BytesToByte(bytes, ref i) != 0); } catch (Exception) { @@ -68454,7 +68992,7 @@ public override void ToBytes(byte[] bytes, ref int i) SessionID.ToBytes(bytes, i); i += 16; Utils.UIntToBytesSafepos(Flags, bytes, i); i += 4; Utils.UIntToBytesSafepos(EstateID, bytes, i); i += 4; - bytes[i++] = (byte)((Godlike) ? 1 : 0); + Utils.ByteToBytes((byte)((Godlike) ? 1 : 0), bytes, ref i); } } @@ -68485,7 +69023,7 @@ public override void FromBytes(byte[] bytes, ref int i) int length; try { - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Name = new byte[length]; Buffer.BlockCopy(bytes, i, Name, 0, length); i += length; } @@ -68497,7 +69035,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = (byte)Name.Length; + Utils.ByteToBytes((byte)Name.Length, bytes, ref i); Buffer.BlockCopy(Name, 0, bytes, i, Name.Length); i += Name.Length; } @@ -68516,6 +69054,8 @@ public override int Length public AgentDataBlock AgentData; public NameDataBlock NameData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public MapNameRequestPacket() { HasVariableBlocks = false; @@ -68524,6 +69064,7 @@ public MapNameRequestPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 408; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); NameData = new NameDataBlock(); } @@ -68548,11 +69089,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public MapNameRequestPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -68659,13 +69199,13 @@ public override void FromBytes(byte[] bytes, ref int i) { X = Utils.BytesToUInt16(bytes, i); i += 2; Y = Utils.BytesToUInt16(bytes, i); i += 2; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Name = new byte[length]; Buffer.BlockCopy(bytes, i, Name, 0, length); i += length; - Access = (byte)bytes[i++]; + Access = Utils.BytesToByte(bytes, ref i); RegionFlags = Utils.BytesToUIntSafepos(bytes, i); i += 4; - WaterHeight = (byte)bytes[i++]; - Agents = (byte)bytes[i++]; + WaterHeight = Utils.BytesToByte(bytes, ref i); + Agents = Utils.BytesToByte(bytes, ref i); MapImageID.FromBytes(bytes, i); i += 16; } catch (Exception) @@ -68678,12 +69218,12 @@ public override void ToBytes(byte[] bytes, ref int i) { Utils.UInt16ToBytes(X, bytes, i); i += 2; Utils.UInt16ToBytes(Y, bytes, i); i += 2; - bytes[i++] = (byte)Name.Length; + Utils.ByteToBytes((byte)Name.Length, bytes, ref i); Buffer.BlockCopy(Name, 0, bytes, i, Name.Length); i += Name.Length; - bytes[i++] = Access; + Utils.ByteToBytes( Access, bytes, ref i); Utils.UIntToBytesSafepos(RegionFlags, bytes, i); i += 4; - bytes[i++] = WaterHeight; - bytes[i++] = Agents; + Utils.ByteToBytes( WaterHeight, bytes, ref i); + Utils.ByteToBytes( Agents, bytes, ref i); MapImageID.ToBytes(bytes, i); i += 16; } @@ -68755,6 +69295,7 @@ public MapBlockReplyPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 409; Header.Reliable = true; + NeedValidateIDs = false; AgentData = new AgentDataBlock(); Data = null; Size = null; @@ -68797,11 +69338,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public MapBlockReplyPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -68838,9 +69378,9 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)Data.Length; + Utils.ByteToBytes((byte)Data.Length, bytes, ref i); for (int j = 0; j < Data.Length; j++) { Data[j].ToBytes(bytes, ref i); } - bytes[i++] = (byte)Size.Length; + Utils.ByteToBytes((byte)Size.Length, bytes, ref i); for (int j = 0; j < Size.Length; j++) { Size[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -68963,7 +69503,7 @@ public override void FromBytes(byte[] bytes, ref int i) SessionID.FromBytes(bytes, i); i += 16; Flags = Utils.BytesToUIntSafepos(bytes, i); i += 4; EstateID = Utils.BytesToUIntSafepos(bytes, i); i += 4; - Godlike = (bytes[i++] != 0) ? (bool)true : (bool)false; + Godlike = (Utils.BytesToByte(bytes, ref i) != 0); } catch (Exception) { @@ -68977,7 +69517,7 @@ public override void ToBytes(byte[] bytes, ref int i) SessionID.ToBytes(bytes, i); i += 16; Utils.UIntToBytesSafepos(Flags, bytes, i); i += 4; Utils.UIntToBytesSafepos(EstateID, bytes, i); i += 4; - bytes[i++] = (byte)((Godlike) ? 1 : 0); + Utils.ByteToBytes((byte)((Godlike) ? 1 : 0), bytes, ref i); } } @@ -69036,6 +69576,8 @@ public override int Length public AgentDataBlock AgentData; public RequestDataBlock RequestData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public MapItemRequestPacket() { HasVariableBlocks = false; @@ -69044,6 +69586,7 @@ public MapItemRequestPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 410; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); RequestData = new RequestDataBlock(); } @@ -69068,11 +69611,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public MapItemRequestPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -69218,7 +69760,7 @@ public override void FromBytes(byte[] bytes, ref int i) ID.FromBytes(bytes, i); i += 16; Extra = Utils.BytesToIntSafepos(bytes, i); i += 4; Extra2 = Utils.BytesToIntSafepos(bytes, i); i += 4; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Name = new byte[length]; Buffer.BlockCopy(bytes, i, Name, 0, length); i += length; } @@ -69235,7 +69777,7 @@ public override void ToBytes(byte[] bytes, ref int i) ID.ToBytes(bytes, i); i += 16; Utils.IntToBytesSafepos(Extra, bytes, i); i += 4; Utils.IntToBytesSafepos(Extra2, bytes, i); i += 4; - bytes[i++] = (byte)Name.Length; + Utils.ByteToBytes((byte)Name.Length, bytes, ref i); Buffer.BlockCopy(Name, 0, bytes, i, Name.Length); i += Name.Length; } @@ -69265,6 +69807,7 @@ public MapItemReplyPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 411; Header.Reliable = true; + NeedValidateIDs = false; AgentData = new AgentDataBlock(); RequestData = new RequestDataBlock(); Data = null; @@ -69299,11 +69842,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public MapItemReplyPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -69332,7 +69874,7 @@ public override byte[] ToBytes() Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); RequestData.ToBytes(bytes, ref i); - bytes[i++] = (byte)Data.Length; + Utils.ByteToBytes((byte)Data.Length, bytes, ref i); for (int j = 0; j < Data.Length; j++) { Data[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -69450,23 +69992,23 @@ public override void FromBytes(byte[] bytes, ref int i) SessionID.FromBytes(bytes, i); i += 16; AssetID.FromBytes(bytes, i); i += 16; PosGlobal.FromBytes(bytes, i); i += 24; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); To = new byte[length]; Buffer.BlockCopy(bytes, i, To, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); From = new byte[length]; Buffer.BlockCopy(bytes, i, From, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Name = new byte[length]; Buffer.BlockCopy(bytes, i, Name, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Subject = new byte[length]; Buffer.BlockCopy(bytes, i, Subject, 0, length); i += length; - length = (bytes[i++] + (bytes[i++] << 8)); + length = Utils.BytesToUInt16(bytes, i); i+=2; Msg = new byte[length]; Buffer.BlockCopy(bytes, i, Msg, 0, length); i += length; - AllowPublish = (bytes[i++] != 0) ? (bool)true : (bool)false; - MaturePublish = (bytes[i++] != 0) ? (bool)true : (bool)false; + AllowPublish = (Utils.BytesToByte(bytes, ref i) != 0); + MaturePublish = (Utils.BytesToByte(bytes, ref i) != 0); } catch (Exception) { @@ -69480,19 +70022,18 @@ public override void ToBytes(byte[] bytes, ref int i) SessionID.ToBytes(bytes, i); i += 16; AssetID.ToBytes(bytes, i); i += 16; PosGlobal.ToBytes(bytes, i); i += 24; - bytes[i++] = (byte)To.Length; + Utils.ByteToBytes((byte)To.Length, bytes, ref i); Buffer.BlockCopy(To, 0, bytes, i, To.Length); i += To.Length; - bytes[i++] = (byte)From.Length; + Utils.ByteToBytes((byte)From.Length, bytes, ref i); Buffer.BlockCopy(From, 0, bytes, i, From.Length); i += From.Length; - bytes[i++] = (byte)Name.Length; + Utils.ByteToBytes((byte)Name.Length, bytes, ref i); Buffer.BlockCopy(Name, 0, bytes, i, Name.Length); i += Name.Length; - bytes[i++] = (byte)Subject.Length; + Utils.ByteToBytes((byte)Subject.Length, bytes, ref i); Buffer.BlockCopy(Subject, 0, bytes, i, Subject.Length); i += Subject.Length; - bytes[i++] = (byte)(Msg.Length % 256); - bytes[i++] = (byte)((Msg.Length >> 8) % 256); + Utils.UInt16ToBytes((ushort)Msg.Length, bytes, i); i += 2; Buffer.BlockCopy(Msg, 0, bytes, i, Msg.Length); i += Msg.Length; - bytes[i++] = (byte)((AllowPublish) ? 1 : 0); - bytes[i++] = (byte)((MaturePublish) ? 1 : 0); + Utils.ByteToBytes((byte)((AllowPublish) ? 1 : 0), bytes, ref i); + Utils.ByteToBytes((byte)((MaturePublish) ? 1 : 0), bytes, ref i); } } @@ -69508,6 +70049,8 @@ public override int Length } public AgentDataBlock AgentData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public SendPostcardPacket() { HasVariableBlocks = false; @@ -69516,6 +70059,7 @@ public SendPostcardPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 412; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); } @@ -69538,11 +70082,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public SendPostcardPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -69633,6 +70176,7 @@ public ParcelMediaCommandMessagePacket() Header.Frequency = PacketFrequency.Low; Header.ID = 419; Header.Reliable = true; + NeedValidateIDs = false; CommandBlock = new CommandBlockBlock(); } @@ -69655,11 +70199,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ParcelMediaCommandMessagePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; CommandBlock.FromBytes(bytes, ref i); @@ -69715,11 +70258,11 @@ public override void FromBytes(byte[] bytes, ref int i) int length; try { - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); MediaURL = new byte[length]; Buffer.BlockCopy(bytes, i, MediaURL, 0, length); i += length; MediaID.FromBytes(bytes, i); i += 16; - MediaAutoScale = (byte)bytes[i++]; + MediaAutoScale = Utils.BytesToByte(bytes, ref i); } catch (Exception) { @@ -69729,10 +70272,10 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = (byte)MediaURL.Length; + Utils.ByteToBytes((byte)MediaURL.Length, bytes, ref i); Buffer.BlockCopy(MediaURL, 0, bytes, i, MediaURL.Length); i += MediaURL.Length; MediaID.ToBytes(bytes, i); i += 16; - bytes[i++] = MediaAutoScale; + Utils.ByteToBytes( MediaAutoScale, bytes, ref i); } } @@ -69768,15 +70311,15 @@ public override void FromBytes(byte[] bytes, ref int i) int length; try { - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); MediaType = new byte[length]; Buffer.BlockCopy(bytes, i, MediaType, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); MediaDesc = new byte[length]; Buffer.BlockCopy(bytes, i, MediaDesc, 0, length); i += length; MediaWidth = Utils.BytesToIntSafepos(bytes, i); i += 4; MediaHeight = Utils.BytesToIntSafepos(bytes, i); i += 4; - MediaLoop = (byte)bytes[i++]; + MediaLoop = Utils.BytesToByte(bytes, ref i); } catch (Exception) { @@ -69786,13 +70329,13 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = (byte)MediaType.Length; + Utils.ByteToBytes((byte)MediaType.Length, bytes, ref i); Buffer.BlockCopy(MediaType, 0, bytes, i, MediaType.Length); i += MediaType.Length; - bytes[i++] = (byte)MediaDesc.Length; + Utils.ByteToBytes((byte)MediaDesc.Length, bytes, ref i); Buffer.BlockCopy(MediaDesc, 0, bytes, i, MediaDesc.Length); i += MediaDesc.Length; Utils.IntToBytesSafepos(MediaWidth, bytes, i); i += 4; Utils.IntToBytesSafepos(MediaHeight, bytes, i); i += 4; - bytes[i++] = MediaLoop; + Utils.ByteToBytes( MediaLoop, bytes, ref i); } } @@ -69818,6 +70361,7 @@ public ParcelMediaUpdatePacket() Header.Frequency = PacketFrequency.Low; Header.ID = 420; Header.Reliable = true; + NeedValidateIDs = false; DataBlock = new DataBlockBlock(); DataBlockExtended = new DataBlockExtendedBlock(); } @@ -69842,11 +70386,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ParcelMediaUpdatePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; DataBlock.FromBytes(bytes, ref i); @@ -69949,7 +70492,7 @@ public override void FromBytes(byte[] bytes, ref int i) { ReportType = Utils.BytesToUIntSafepos(bytes, i); i += 4; RequestFlags = Utils.BytesToUIntSafepos(bytes, i); i += 4; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Filter = new byte[length]; Buffer.BlockCopy(bytes, i, Filter, 0, length); i += length; ParcelLocalID = Utils.BytesToIntSafepos(bytes, i); i += 4; @@ -69964,7 +70507,7 @@ public override void ToBytes(byte[] bytes, ref int i) { Utils.UIntToBytesSafepos(ReportType, bytes, i); i += 4; Utils.UIntToBytesSafepos(RequestFlags, bytes, i); i += 4; - bytes[i++] = (byte)Filter.Length; + Utils.ByteToBytes((byte)Filter.Length, bytes, ref i); Buffer.BlockCopy(Filter, 0, bytes, i, Filter.Length); i += Filter.Length; Utils.IntToBytesSafepos(ParcelLocalID, bytes, i); i += 4; } @@ -69984,6 +70527,8 @@ public override int Length public AgentDataBlock AgentData; public RequestDataBlock RequestData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public LandStatRequestPacket() { HasVariableBlocks = false; @@ -69992,6 +70537,7 @@ public LandStatRequestPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 421; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); RequestData = new RequestDataBlock(); } @@ -70016,11 +70562,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public LandStatRequestPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -70135,10 +70680,10 @@ public override void FromBytes(byte[] bytes, ref int i) LocationY = Utils.BytesToFloatSafepos(bytes, i); i += 4; LocationZ = Utils.BytesToFloatSafepos(bytes, i); i += 4; Score = Utils.BytesToFloatSafepos(bytes, i); i += 4; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); TaskName = new byte[length]; Buffer.BlockCopy(bytes, i, TaskName, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); OwnerName = new byte[length]; Buffer.BlockCopy(bytes, i, OwnerName, 0, length); i += length; } @@ -70156,9 +70701,9 @@ public override void ToBytes(byte[] bytes, ref int i) Utils.FloatToBytesSafepos(LocationY, bytes, i); i += 4; Utils.FloatToBytesSafepos(LocationZ, bytes, i); i += 4; Utils.FloatToBytesSafepos(Score, bytes, i); i += 4; - bytes[i++] = (byte)TaskName.Length; + Utils.ByteToBytes((byte)TaskName.Length, bytes, ref i); Buffer.BlockCopy(TaskName, 0, bytes, i, TaskName.Length); i += TaskName.Length; - bytes[i++] = (byte)OwnerName.Length; + Utils.ByteToBytes((byte)OwnerName.Length, bytes, ref i); Buffer.BlockCopy(OwnerName, 0, bytes, i, OwnerName.Length); i += OwnerName.Length; } @@ -70186,6 +70731,7 @@ public LandStatReplyPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 422; Header.Reliable = true; + NeedValidateIDs = false; RequestData = new RequestDataBlock(); ReportData = null; } @@ -70218,11 +70764,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public LandStatReplyPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; RequestData.FromBytes(bytes, ref i); @@ -70248,7 +70793,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); RequestData.ToBytes(bytes, ref i); - bytes[i++] = (byte)ReportData.Length; + Utils.ByteToBytes((byte)ReportData.Length, bytes, ref i); for (int j = 0; j < ReportData.Length; j++) { ReportData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -70393,17 +70938,17 @@ public override void FromBytes(byte[] bytes, ref int i) try { Code = Utils.BytesToIntSafepos(bytes, i); i += 4; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Token = new byte[length]; Buffer.BlockCopy(bytes, i, Token, 0, length); i += length; ID.FromBytes(bytes, i); i += 16; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); System = new byte[length]; Buffer.BlockCopy(bytes, i, System, 0, length); i += length; - length = (bytes[i++] + (bytes[i++] << 8)); + length = Utils.BytesToUInt16(bytes, i); i+=2; Message = new byte[length]; Buffer.BlockCopy(bytes, i, Message, 0, length); i += length; - length = (bytes[i++] + (bytes[i++] << 8)); + length = Utils.BytesToUInt16(bytes, i); i+=2; Data = new byte[length]; Buffer.BlockCopy(bytes, i, Data, 0, length); i += length; } @@ -70416,16 +70961,14 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { Utils.IntToBytesSafepos(Code, bytes, i); i += 4; - bytes[i++] = (byte)Token.Length; + Utils.ByteToBytes((byte)Token.Length, bytes, ref i); Buffer.BlockCopy(Token, 0, bytes, i, Token.Length); i += Token.Length; ID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)System.Length; + Utils.ByteToBytes((byte)System.Length, bytes, ref i); Buffer.BlockCopy(System, 0, bytes, i, System.Length); i += System.Length; - bytes[i++] = (byte)(Message.Length % 256); - bytes[i++] = (byte)((Message.Length >> 8) % 256); + Utils.UInt16ToBytes((ushort)Message.Length, bytes, i); i += 2; Buffer.BlockCopy(Message, 0, bytes, i, Message.Length); i += Message.Length; - bytes[i++] = (byte)(Data.Length % 256); - bytes[i++] = (byte)((Data.Length >> 8) % 256); + Utils.UInt16ToBytes((ushort)Data.Length, bytes, i); i += 2; Buffer.BlockCopy(Data, 0, bytes, i, Data.Length); i += Data.Length; } @@ -70452,6 +70995,7 @@ public ErrorPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 423; Header.Reliable = true; + NeedValidateIDs = false; Header.Zerocoded = true; AgentData = new AgentDataBlock(); Data = new DataBlock(); @@ -70477,11 +71021,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ErrorPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -70578,7 +71121,7 @@ public override void FromBytes(byte[] bytes, ref int i) try { ObjectLocalID = Utils.BytesToUIntSafepos(bytes, i); i += 4; - IncludeInSearch = (bytes[i++] != 0) ? (bool)true : (bool)false; + IncludeInSearch = (Utils.BytesToByte(bytes, ref i) != 0); } catch (Exception) { @@ -70589,7 +71132,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { Utils.UIntToBytesSafepos(ObjectLocalID, bytes, i); i += 4; - bytes[i++] = (byte)((IncludeInSearch) ? 1 : 0); + Utils.ByteToBytes((byte)((IncludeInSearch) ? 1 : 0), bytes, ref i); } } @@ -70608,6 +71151,8 @@ public override int Length public AgentDataBlock AgentData; public ObjectDataBlock[] ObjectData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ObjectIncludeInSearchPacket() { HasVariableBlocks = true; @@ -70616,6 +71161,7 @@ public ObjectIncludeInSearchPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 424; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); ObjectData = null; } @@ -70648,11 +71194,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ObjectIncludeInSearchPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -70678,7 +71223,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)ObjectData.Length; + Utils.ByteToBytes((byte)ObjectData.Length, bytes, ref i); for (int j = 0; j < ObjectData.Length; j++) { ObjectData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -70848,17 +71393,17 @@ public override void FromBytes(byte[] bytes, ref int i) GroupMask = Utils.BytesToUIntSafepos(bytes, i); i += 4; EveryoneMask = Utils.BytesToUIntSafepos(bytes, i); i += 4; NextOwnerMask = Utils.BytesToUIntSafepos(bytes, i); i += 4; - GroupOwned = (bytes[i++] != 0) ? (bool)true : (bool)false; + GroupOwned = (Utils.BytesToByte(bytes, ref i) != 0); TransactionID.FromBytes(bytes, i); i += 16; - Type = (sbyte)bytes[i++]; - InvType = (sbyte)bytes[i++]; + Type = (sbyte)Utils.BytesToByte(bytes, ref i); + InvType = (sbyte)Utils.BytesToByte(bytes, ref i); Flags = Utils.BytesToUIntSafepos(bytes, i); i += 4; - SaleType = (byte)bytes[i++]; + SaleType = Utils.BytesToByte(bytes, ref i); SalePrice = Utils.BytesToIntSafepos(bytes, i); i += 4; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Name = new byte[length]; Buffer.BlockCopy(bytes, i, Name, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Description = new byte[length]; Buffer.BlockCopy(bytes, i, Description, 0, length); i += length; CreationDate = Utils.BytesToIntSafepos(bytes, i); i += 4; @@ -70882,16 +71427,16 @@ public override void ToBytes(byte[] bytes, ref int i) Utils.UIntToBytesSafepos(GroupMask, bytes, i); i += 4; Utils.UIntToBytesSafepos(EveryoneMask, bytes, i); i += 4; Utils.UIntToBytesSafepos(NextOwnerMask, bytes, i); i += 4; - bytes[i++] = (byte)((GroupOwned) ? 1 : 0); + Utils.ByteToBytes((byte)((GroupOwned) ? 1 : 0), bytes, ref i); TransactionID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)Type; - bytes[i++] = (byte)InvType; + Utils.ByteToBytes( (byte)Type, bytes, ref i); + Utils.ByteToBytes( (byte)InvType, bytes, ref i); Utils.UIntToBytesSafepos(Flags, bytes, i); i += 4; - bytes[i++] = SaleType; + Utils.ByteToBytes( SaleType, bytes, ref i); Utils.IntToBytesSafepos(SalePrice, bytes, i); i += 4; - bytes[i++] = (byte)Name.Length; + Utils.ByteToBytes((byte)Name.Length, bytes, ref i); Buffer.BlockCopy(Name, 0, bytes, i, Name.Length); i += Name.Length; - bytes[i++] = (byte)Description.Length; + Utils.ByteToBytes((byte)Description.Length, bytes, ref i); Buffer.BlockCopy(Description, 0, bytes, i, Description.Length); i += Description.Length; Utils.IntToBytesSafepos(CreationDate, bytes, i); i += 4; Utils.UIntToBytesSafepos(CRC, bytes, i); i += 4; @@ -70912,6 +71457,8 @@ public override int Length public AgentDataBlock AgentData; public InventoryDataBlock InventoryData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public RezRestoreToWorldPacket() { HasVariableBlocks = false; @@ -70920,6 +71467,7 @@ public RezRestoreToWorldPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 425; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); InventoryData = new InventoryDataBlock(); } @@ -70944,11 +71492,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public RezRestoreToWorldPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -71058,12 +71605,12 @@ public override void FromBytes(byte[] bytes, ref int i) FolderID.FromBytes(bytes, i); i += 16; TransactionID.FromBytes(bytes, i); i += 16; OldItemID.FromBytes(bytes, i); i += 16; - Type = (sbyte)bytes[i++]; - InvType = (sbyte)bytes[i++]; - length = bytes[i++]; + Type = (sbyte)Utils.BytesToByte(bytes, ref i); + InvType = (sbyte)Utils.BytesToByte(bytes, ref i); + length = Utils.BytesToByte(bytes, ref i); Name = new byte[length]; Buffer.BlockCopy(bytes, i, Name, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Description = new byte[length]; Buffer.BlockCopy(bytes, i, Description, 0, length); i += length; } @@ -71079,11 +71626,11 @@ public override void ToBytes(byte[] bytes, ref int i) FolderID.ToBytes(bytes, i); i += 16; TransactionID.ToBytes(bytes, i); i += 16; OldItemID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)Type; - bytes[i++] = (byte)InvType; - bytes[i++] = (byte)Name.Length; + Utils.ByteToBytes( (byte)Type, bytes, ref i); + Utils.ByteToBytes( (byte)InvType, bytes, ref i); + Utils.ByteToBytes((byte)Name.Length, bytes, ref i); Buffer.BlockCopy(Name, 0, bytes, i, Name.Length); i += Name.Length; - bytes[i++] = (byte)Description.Length; + Utils.ByteToBytes((byte)Description.Length, bytes, ref i); Buffer.BlockCopy(Description, 0, bytes, i, Description.Length); i += Description.Length; } @@ -71102,6 +71649,8 @@ public override int Length public AgentDataBlock AgentData; public InventoryBlockBlock InventoryBlock; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public LinkInventoryItemPacket() { HasVariableBlocks = false; @@ -71110,6 +71659,7 @@ public LinkInventoryItemPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 426; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); InventoryBlock = new InventoryBlockBlock(); @@ -71135,11 +71685,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public LinkInventoryItemPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -71241,7 +71790,7 @@ public override void FromBytes(byte[] bytes, ref int i) int length; try { - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Method = new byte[length]; Buffer.BlockCopy(bytes, i, Method, 0, length); i += length; Invoice.FromBytes(bytes, i); i += 16; @@ -71254,7 +71803,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = (byte)Method.Length; + Utils.ByteToBytes((byte)Method.Length, bytes, ref i); Buffer.BlockCopy(Method, 0, bytes, i, Method.Length); i += Method.Length; Invoice.ToBytes(bytes, i); i += 16; } @@ -71287,7 +71836,7 @@ public override void FromBytes(byte[] bytes, ref int i) int length; try { - length = (bytes[i++] + (bytes[i++] << 8)); + length = Utils.BytesToUInt16(bytes, i); i+=2; Parameter = new byte[length]; Buffer.BlockCopy(bytes, i, Parameter, 0, length); i += length; } @@ -71299,8 +71848,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = (byte)(Parameter.Length % 256); - bytes[i++] = (byte)((Parameter.Length >> 8) % 256); + Utils.UInt16ToBytes((ushort)Parameter.Length, bytes, i); i += 2; Buffer.BlockCopy(Parameter, 0, bytes, i, Parameter.Length); i += Parameter.Length; } @@ -71322,6 +71870,8 @@ public override int Length public MethodDataBlock MethodData; public ParamListBlock[] ParamList; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public LargeGenericMessagePacket() { HasVariableBlocks = true; @@ -71330,6 +71880,7 @@ public LargeGenericMessagePacket() Header.Frequency = PacketFrequency.Low; Header.ID = 430; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); MethodData = new MethodDataBlock(); ParamList = null; @@ -71363,11 +71914,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public LargeGenericMessagePacket(Header head, byte[] bytes, ref int i): this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -71395,7 +71945,7 @@ public override byte[] ToBytes() Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); MethodData.ToBytes(bytes, ref i); - bytes[i++] = (byte)ParamList.Length; + Utils.ByteToBytes((byte)ParamList.Length, bytes, ref i); for (int j = 0; j < ParamList.Length; j++) { ParamList[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -71531,6 +72081,7 @@ public PacketAckPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 65531; Header.Reliable = true; + NeedValidateIDs = false; Packets = null; } @@ -71561,11 +72112,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public PacketAckPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; int count = (int)bytes[i++]; @@ -71588,7 +72138,7 @@ public override byte[] ToBytes() byte[] bytes = new byte[length]; int i = 0; Header.ToBytes(bytes, ref i); - bytes[i++] = (byte)Packets.Length; + Utils.ByteToBytes((byte)Packets.Length, bytes, ref i); for (int j = 0; j < Packets.Length; j++) { Packets[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -71777,8 +72327,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { Utils.UIntToBytesSafepos(IP, bytes, i); i += 4; - bytes[i++] = (byte)((Port >> 8) % 256); - bytes[i++] = (byte)(Port % 256); + Utils.UInt16ToBytesBig(Port, bytes, i); i += 2; } } @@ -71802,6 +72351,7 @@ public OpenCircuitPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 65532; Header.Reliable = true; + NeedValidateIDs = false; CircuitInfo = new CircuitInfoBlock(); } @@ -71824,11 +72374,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public OpenCircuitPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; CircuitInfo.FromBytes(bytes, ref i); @@ -71873,6 +72422,7 @@ public CloseCircuitPacket() Header.Frequency = PacketFrequency.Low; Header.ID = 65533; Header.Reliable = true; + NeedValidateIDs = false; } public CloseCircuitPacket(byte[] bytes, ref int i) : this() @@ -71893,11 +72443,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public CloseCircuitPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; } @@ -72017,35 +72566,35 @@ public override void FromBytes(byte[] bytes, ref int i) { try { - PCode = (byte)bytes[i++]; - Material = (byte)bytes[i++]; + PCode = Utils.BytesToByte(bytes, ref i); + Material = Utils.BytesToByte(bytes, ref i); AddFlags = Utils.BytesToUIntSafepos(bytes, i); i += 4; - PathCurve = (byte)bytes[i++]; - ProfileCurve = (byte)bytes[i++]; + PathCurve = Utils.BytesToByte(bytes, ref i); + ProfileCurve = Utils.BytesToByte(bytes, ref i); PathBegin = Utils.BytesToUInt16(bytes, i); i += 2; PathEnd = Utils.BytesToUInt16(bytes, i); i += 2; - PathScaleX = (byte)bytes[i++]; - PathScaleY = (byte)bytes[i++]; - PathShearX = (byte)bytes[i++]; - PathShearY = (byte)bytes[i++]; - PathTwist = (sbyte)bytes[i++]; - PathTwistBegin = (sbyte)bytes[i++]; - PathRadiusOffset = (sbyte)bytes[i++]; - PathTaperX = (sbyte)bytes[i++]; - PathTaperY = (sbyte)bytes[i++]; - PathRevolutions = (byte)bytes[i++]; - PathSkew = (sbyte)bytes[i++]; + PathScaleX = Utils.BytesToByte(bytes, ref i); + PathScaleY = Utils.BytesToByte(bytes, ref i); + PathShearX = Utils.BytesToByte(bytes, ref i); + PathShearY = Utils.BytesToByte(bytes, ref i); + PathTwist = (sbyte)Utils.BytesToByte(bytes, ref i); + PathTwistBegin = (sbyte)Utils.BytesToByte(bytes, ref i); + PathRadiusOffset = (sbyte)Utils.BytesToByte(bytes, ref i); + PathTaperX = (sbyte)Utils.BytesToByte(bytes, ref i); + PathTaperY = (sbyte)Utils.BytesToByte(bytes, ref i); + PathRevolutions = Utils.BytesToByte(bytes, ref i); + PathSkew = (sbyte)Utils.BytesToByte(bytes, ref i); ProfileBegin = Utils.BytesToUInt16(bytes, i); i += 2; ProfileEnd = Utils.BytesToUInt16(bytes, i); i += 2; ProfileHollow = Utils.BytesToUInt16(bytes, i); i += 2; - BypassRaycast = (byte)bytes[i++]; + BypassRaycast = Utils.BytesToByte(bytes, ref i); RayStart.FromBytes(bytes, i); i += 12; RayEnd.FromBytes(bytes, i); i += 12; RayTargetID.FromBytes(bytes, i); i += 16; - RayEndIsIntersection = (byte)bytes[i++]; + RayEndIsIntersection = Utils.BytesToByte(bytes, ref i); Scale.FromBytes(bytes, i); i += 12; Rotation.FromBytes(bytes, i, true); i += 12; - State = (byte)bytes[i++]; + State = Utils.BytesToByte(bytes, ref i); } catch (Exception) { @@ -72055,35 +72604,35 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = PCode; - bytes[i++] = Material; + Utils.ByteToBytes( PCode, bytes, ref i); + Utils.ByteToBytes( Material, bytes, ref i); Utils.UIntToBytesSafepos(AddFlags, bytes, i); i += 4; - bytes[i++] = PathCurve; - bytes[i++] = ProfileCurve; + Utils.ByteToBytes( PathCurve, bytes, ref i); + Utils.ByteToBytes( ProfileCurve, bytes, ref i); Utils.UInt16ToBytes(PathBegin, bytes, i); i += 2; Utils.UInt16ToBytes(PathEnd, bytes, i); i += 2; - bytes[i++] = PathScaleX; - bytes[i++] = PathScaleY; - bytes[i++] = PathShearX; - bytes[i++] = PathShearY; - bytes[i++] = (byte)PathTwist; - bytes[i++] = (byte)PathTwistBegin; - bytes[i++] = (byte)PathRadiusOffset; - bytes[i++] = (byte)PathTaperX; - bytes[i++] = (byte)PathTaperY; - bytes[i++] = PathRevolutions; - bytes[i++] = (byte)PathSkew; + Utils.ByteToBytes( PathScaleX, bytes, ref i); + Utils.ByteToBytes( PathScaleY, bytes, ref i); + Utils.ByteToBytes( PathShearX, bytes, ref i); + Utils.ByteToBytes( PathShearY, bytes, ref i); + Utils.ByteToBytes( (byte)PathTwist, bytes, ref i); + Utils.ByteToBytes( (byte)PathTwistBegin, bytes, ref i); + Utils.ByteToBytes( (byte)PathRadiusOffset, bytes, ref i); + Utils.ByteToBytes( (byte)PathTaperX, bytes, ref i); + Utils.ByteToBytes( (byte)PathTaperY, bytes, ref i); + Utils.ByteToBytes( PathRevolutions, bytes, ref i); + Utils.ByteToBytes( (byte)PathSkew, bytes, ref i); Utils.UInt16ToBytes(ProfileBegin, bytes, i); i += 2; Utils.UInt16ToBytes(ProfileEnd, bytes, i); i += 2; Utils.UInt16ToBytes(ProfileHollow, bytes, i); i += 2; - bytes[i++] = BypassRaycast; + Utils.ByteToBytes( BypassRaycast, bytes, ref i); RayStart.ToBytes(bytes, i); i += 12; RayEnd.ToBytes(bytes, i); i += 12; RayTargetID.ToBytes(bytes, i); i += 16; - bytes[i++] = RayEndIsIntersection; + Utils.ByteToBytes( RayEndIsIntersection, bytes, ref i); Scale.ToBytes(bytes, i); i += 12; Rotation.ToBytes(bytes, i); i += 12; - bytes[i++] = State; + Utils.ByteToBytes( State, bytes, ref i); } } @@ -72101,6 +72650,8 @@ public override int Length public AgentDataBlock AgentData; public ObjectDataBlock ObjectData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ObjectAddPacket() { HasVariableBlocks = false; @@ -72109,6 +72660,7 @@ public ObjectAddPacket() Header.Frequency = PacketFrequency.Medium; Header.ID = 1; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); ObjectData = new ObjectDataBlock(); @@ -72134,11 +72686,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ObjectAddPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -72239,8 +72790,8 @@ public override void FromBytes(byte[] bytes, ref int i) try { ObjectLocalID = Utils.BytesToUIntSafepos(bytes, i); i += 4; - Type = (byte)bytes[i++]; - length = bytes[i++]; + Type = Utils.BytesToByte(bytes, ref i); + length = Utils.BytesToByte(bytes, ref i); Data = new byte[length]; Buffer.BlockCopy(bytes, i, Data, 0, length); i += length; } @@ -72253,8 +72804,8 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { Utils.UIntToBytesSafepos(ObjectLocalID, bytes, i); i += 4; - bytes[i++] = Type; - bytes[i++] = (byte)Data.Length; + Utils.ByteToBytes( Type, bytes, ref i); + Utils.ByteToBytes((byte)Data.Length, bytes, ref i); Buffer.BlockCopy(Data, 0, bytes, i, Data.Length); i += Data.Length; } @@ -72274,6 +72825,8 @@ public override int Length public AgentDataBlock AgentData; public ObjectDataBlock[] ObjectData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public MultipleObjectUpdatePacket() { HasVariableBlocks = true; @@ -72282,6 +72835,7 @@ public MultipleObjectUpdatePacket() Header.Frequency = PacketFrequency.Medium; Header.ID = 2; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); ObjectData = null; @@ -72315,11 +72869,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public MultipleObjectUpdatePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -72345,7 +72898,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)ObjectData.Length; + Utils.ByteToBytes((byte)ObjectData.Length, bytes, ref i); for (int j = 0; j < ObjectData.Length; j++) { ObjectData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -72482,7 +73035,7 @@ public override void FromBytes(byte[] bytes, ref int i) { try { - CacheMissType = (byte)bytes[i++]; + CacheMissType = Utils.BytesToByte(bytes, ref i); ID = Utils.BytesToUIntSafepos(bytes, i); i += 4; } catch (Exception) @@ -72493,7 +73046,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = CacheMissType; + Utils.ByteToBytes( CacheMissType, bytes, ref i); Utils.UIntToBytesSafepos(ID, bytes, i); i += 4; } @@ -72513,6 +73066,8 @@ public override int Length public AgentDataBlock AgentData; public ObjectDataBlock[] ObjectData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public RequestMultipleObjectsPacket() { HasVariableBlocks = true; @@ -72521,6 +73076,7 @@ public RequestMultipleObjectsPacket() Header.Frequency = PacketFrequency.Medium; Header.ID = 3; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); ObjectData = null; @@ -72554,11 +73110,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public RequestMultipleObjectsPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -72584,7 +73139,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)ObjectData.Length; + Utils.ByteToBytes((byte)ObjectData.Length, bytes, ref i); for (int j = 0; j < ObjectData.Length; j++) { ObjectData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -72752,6 +73307,8 @@ public override int Length public AgentDataBlock AgentData; public ObjectDataBlock[] ObjectData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ObjectPositionPacket() { HasVariableBlocks = true; @@ -72760,6 +73317,7 @@ public ObjectPositionPacket() Header.Frequency = PacketFrequency.Medium; Header.ID = 4; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); ObjectData = null; @@ -72793,11 +73351,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ObjectPositionPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -72823,7 +73380,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)ObjectData.Length; + Utils.ByteToBytes((byte)ObjectData.Length, bytes, ref i); for (int j = 0; j < ObjectData.Length; j++) { ObjectData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -72990,6 +73547,8 @@ public override int Length public AgentDataBlock AgentData; public ObjectDataBlock ObjectData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public RequestObjectPropertiesFamilyPacket() { HasVariableBlocks = false; @@ -72998,6 +73557,7 @@ public RequestObjectPropertiesFamilyPacket() Header.Frequency = PacketFrequency.Medium; Header.ID = 5; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); ObjectData = new ObjectDataBlock(); @@ -73023,11 +73583,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public RequestObjectPropertiesFamilyPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -73083,9 +73642,9 @@ public override void FromBytes(byte[] bytes, ref int i) { try { - X = (byte)bytes[i++]; - Y = (byte)bytes[i++]; - Z = (byte)bytes[i++]; + X = Utils.BytesToByte(bytes, ref i); + Y = Utils.BytesToByte(bytes, ref i); + Z = Utils.BytesToByte(bytes, ref i); } catch (Exception) { @@ -73095,9 +73654,9 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = X; - bytes[i++] = Y; - bytes[i++] = Z; + Utils.ByteToBytes( X, bytes, ref i); + Utils.ByteToBytes( Y, bytes, ref i); + Utils.ByteToBytes( Z, bytes, ref i); } } @@ -73206,6 +73765,7 @@ public CoarseLocationUpdatePacket() Header.Frequency = PacketFrequency.Medium; Header.ID = 6; Header.Reliable = true; + NeedValidateIDs = false; Location = null; Index = new IndexBlock(); AgentData = null; @@ -73248,11 +73808,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public CoarseLocationUpdatePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; int count = (int)bytes[i++]; @@ -73288,10 +73847,10 @@ public override byte[] ToBytes() byte[] bytes = new byte[length]; int i = 0; Header.ToBytes(bytes, ref i); - bytes[i++] = (byte)Location.Length; + Utils.ByteToBytes((byte)Location.Length, bytes, ref i); for (int j = 0; j < Location.Length; j++) { Location[j].ToBytes(bytes, ref i); } Index.ToBytes(bytes, ref i); - bytes[i++] = (byte)AgentData.Length; + Utils.ByteToBytes((byte)AgentData.Length, bytes, ref i); for (int j = 0; j < AgentData.Length; j++) { AgentData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -73379,7 +73938,7 @@ public override void FromBytes(byte[] bytes, ref int i) SimIP = Utils.BytesToUIntSafepos(bytes, i); i += 4; SimPort = (ushort)((bytes[i++] << 8) + bytes[i++]); RegionHandle = Utils.BytesToUInt64Safepos(bytes, i); i += 8; - length = (bytes[i++] + (bytes[i++] << 8)); + length = Utils.BytesToUInt16(bytes, i); i+=2; SeedCapability = new byte[length]; Buffer.BlockCopy(bytes, i, SeedCapability, 0, length); i += length; } @@ -73392,11 +73951,9 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { Utils.UIntToBytesSafepos(SimIP, bytes, i); i += 4; - bytes[i++] = (byte)((SimPort >> 8) % 256); - bytes[i++] = (byte)(SimPort % 256); + Utils.UInt16ToBytesBig(SimPort, bytes, i); i += 2; Utils.UInt64ToBytesSafepos(RegionHandle, bytes, i); i += 8; - bytes[i++] = (byte)(SeedCapability.Length % 256); - bytes[i++] = (byte)((SeedCapability.Length >> 8) % 256); + Utils.UInt16ToBytes((ushort)SeedCapability.Length, bytes, i); i += 2; Buffer.BlockCopy(SeedCapability, 0, bytes, i, SeedCapability.Length); i += SeedCapability.Length; } @@ -73458,6 +74015,8 @@ public override int Length public RegionDataBlock RegionData; public InfoBlock Info; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public CrossedRegionPacket() { HasVariableBlocks = false; @@ -73466,6 +74025,7 @@ public CrossedRegionPacket() Header.Frequency = PacketFrequency.Medium; Header.ID = 7; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); RegionData = new RegionDataBlock(); Info = new InfoBlock(); @@ -73492,11 +74052,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public CrossedRegionPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -73582,6 +74141,8 @@ public override int Length } public AgentDataBlock AgentData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ConfirmEnableSimulatorPacket() { HasVariableBlocks = false; @@ -73590,6 +74151,7 @@ public ConfirmEnableSimulatorPacket() Header.Frequency = PacketFrequency.Medium; Header.ID = 8; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); } @@ -73612,11 +74174,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ConfirmEnableSimulatorPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -73711,30 +74272,30 @@ public override void FromBytes(byte[] bytes, ref int i) EveryoneMask = Utils.BytesToUIntSafepos(bytes, i); i += 4; NextOwnerMask = Utils.BytesToUIntSafepos(bytes, i); i += 4; OwnershipCost = Utils.BytesToIntSafepos(bytes, i); i += 4; - SaleType = (byte)bytes[i++]; + SaleType = Utils.BytesToByte(bytes, ref i); SalePrice = Utils.BytesToIntSafepos(bytes, i); i += 4; - AggregatePerms = (byte)bytes[i++]; - AggregatePermTextures = (byte)bytes[i++]; - AggregatePermTexturesOwner = (byte)bytes[i++]; + AggregatePerms = Utils.BytesToByte(bytes, ref i); + AggregatePermTextures = Utils.BytesToByte(bytes, ref i); + AggregatePermTexturesOwner = Utils.BytesToByte(bytes, ref i); Category = Utils.BytesToUIntSafepos(bytes, i); i += 4; InventorySerial = Utils.BytesToInt16(bytes, i); i += 2; ItemID.FromBytes(bytes, i); i += 16; FolderID.FromBytes(bytes, i); i += 16; FromTaskID.FromBytes(bytes, i); i += 16; LastOwnerID.FromBytes(bytes, i); i += 16; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Name = new byte[length]; Buffer.BlockCopy(bytes, i, Name, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Description = new byte[length]; Buffer.BlockCopy(bytes, i, Description, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); TouchName = new byte[length]; Buffer.BlockCopy(bytes, i, TouchName, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); SitName = new byte[length]; Buffer.BlockCopy(bytes, i, SitName, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); TextureID = new byte[length]; Buffer.BlockCopy(bytes, i, TextureID, 0, length); i += length; } @@ -73757,26 +74318,26 @@ public override void ToBytes(byte[] bytes, ref int i) Utils.UIntToBytesSafepos(EveryoneMask, bytes, i); i += 4; Utils.UIntToBytesSafepos(NextOwnerMask, bytes, i); i += 4; Utils.IntToBytesSafepos(OwnershipCost, bytes, i); i += 4; - bytes[i++] = SaleType; + Utils.ByteToBytes( SaleType, bytes, ref i); Utils.IntToBytesSafepos(SalePrice, bytes, i); i += 4; - bytes[i++] = AggregatePerms; - bytes[i++] = AggregatePermTextures; - bytes[i++] = AggregatePermTexturesOwner; + Utils.ByteToBytes( AggregatePerms, bytes, ref i); + Utils.ByteToBytes( AggregatePermTextures, bytes, ref i); + Utils.ByteToBytes( AggregatePermTexturesOwner, bytes, ref i); Utils.UIntToBytesSafepos(Category, bytes, i); i += 4; Utils.Int16ToBytes(InventorySerial, bytes, i); i += 2; ItemID.ToBytes(bytes, i); i += 16; FolderID.ToBytes(bytes, i); i += 16; FromTaskID.ToBytes(bytes, i); i += 16; LastOwnerID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)Name.Length; + Utils.ByteToBytes((byte)Name.Length, bytes, ref i); Buffer.BlockCopy(Name, 0, bytes, i, Name.Length); i += Name.Length; - bytes[i++] = (byte)Description.Length; + Utils.ByteToBytes((byte)Description.Length, bytes, ref i); Buffer.BlockCopy(Description, 0, bytes, i, Description.Length); i += Description.Length; - bytes[i++] = (byte)TouchName.Length; + Utils.ByteToBytes((byte)TouchName.Length, bytes, ref i); Buffer.BlockCopy(TouchName, 0, bytes, i, TouchName.Length); i += TouchName.Length; - bytes[i++] = (byte)SitName.Length; + Utils.ByteToBytes((byte)SitName.Length, bytes, ref i); Buffer.BlockCopy(SitName, 0, bytes, i, SitName.Length); i += SitName.Length; - bytes[i++] = (byte)TextureID.Length; + Utils.ByteToBytes((byte)TextureID.Length, bytes, ref i); Buffer.BlockCopy(TextureID, 0, bytes, i, TextureID.Length); i += TextureID.Length; } @@ -73802,6 +74363,7 @@ public ObjectPropertiesPacket() Header.Frequency = PacketFrequency.Medium; Header.ID = 9; Header.Reliable = true; + NeedValidateIDs = false; Header.Zerocoded = true; ObjectData = null; } @@ -73833,11 +74395,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ObjectPropertiesPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; int count = (int)bytes[i++]; @@ -73860,7 +74421,7 @@ public override byte[] ToBytes() byte[] bytes = new byte[length]; int i = 0; Header.ToBytes(bytes, ref i); - bytes[i++] = (byte)ObjectData.Length; + Utils.ByteToBytes((byte)ObjectData.Length, bytes, ref i); for (int j = 0; j < ObjectData.Length; j++) { ObjectData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -73982,14 +74543,14 @@ public override void FromBytes(byte[] bytes, ref int i) EveryoneMask = Utils.BytesToUIntSafepos(bytes, i); i += 4; NextOwnerMask = Utils.BytesToUIntSafepos(bytes, i); i += 4; OwnershipCost = Utils.BytesToIntSafepos(bytes, i); i += 4; - SaleType = (byte)bytes[i++]; + SaleType = Utils.BytesToByte(bytes, ref i); SalePrice = Utils.BytesToIntSafepos(bytes, i); i += 4; Category = Utils.BytesToUIntSafepos(bytes, i); i += 4; LastOwnerID.FromBytes(bytes, i); i += 16; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Name = new byte[length]; Buffer.BlockCopy(bytes, i, Name, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Description = new byte[length]; Buffer.BlockCopy(bytes, i, Description, 0, length); i += length; } @@ -74011,13 +74572,13 @@ public override void ToBytes(byte[] bytes, ref int i) Utils.UIntToBytesSafepos(EveryoneMask, bytes, i); i += 4; Utils.UIntToBytesSafepos(NextOwnerMask, bytes, i); i += 4; Utils.IntToBytesSafepos(OwnershipCost, bytes, i); i += 4; - bytes[i++] = SaleType; + Utils.ByteToBytes( SaleType, bytes, ref i); Utils.IntToBytesSafepos(SalePrice, bytes, i); i += 4; Utils.UIntToBytesSafepos(Category, bytes, i); i += 4; LastOwnerID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)Name.Length; + Utils.ByteToBytes((byte)Name.Length, bytes, ref i); Buffer.BlockCopy(Name, 0, bytes, i, Name.Length); i += Name.Length; - bytes[i++] = (byte)Description.Length; + Utils.ByteToBytes((byte)Description.Length, bytes, ref i); Buffer.BlockCopy(Description, 0, bytes, i, Description.Length); i += Description.Length; } @@ -74042,6 +74603,7 @@ public ObjectPropertiesFamilyPacket() Header.Frequency = PacketFrequency.Medium; Header.ID = 10; Header.Reliable = true; + NeedValidateIDs = false; Header.Zerocoded = true; ObjectData = new ObjectDataBlock(); } @@ -74065,11 +74627,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ObjectPropertiesFamilyPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; ObjectData.FromBytes(bytes, ref i); @@ -74171,7 +74732,7 @@ public override void FromBytes(byte[] bytes, ref int i) South = Utils.BytesToFloatSafepos(bytes, i); i += 4; East = Utils.BytesToFloatSafepos(bytes, i); i += 4; North = Utils.BytesToFloatSafepos(bytes, i); i += 4; - SnapSelection = (bytes[i++] != 0) ? (bool)true : (bool)false; + SnapSelection = (Utils.BytesToByte(bytes, ref i) != 0); } catch (Exception) { @@ -74186,7 +74747,7 @@ public override void ToBytes(byte[] bytes, ref int i) Utils.FloatToBytesSafepos(South, bytes, i); i += 4; Utils.FloatToBytesSafepos(East, bytes, i); i += 4; Utils.FloatToBytesSafepos(North, bytes, i); i += 4; - bytes[i++] = (byte)((SnapSelection) ? 1 : 0); + Utils.ByteToBytes((byte)((SnapSelection) ? 1 : 0), bytes, ref i); } } @@ -74204,6 +74765,8 @@ public override int Length public AgentDataBlock AgentData; public ParcelDataBlock ParcelData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ParcelPropertiesRequestPacket() { HasVariableBlocks = false; @@ -74212,6 +74775,7 @@ public ParcelPropertiesRequestPacket() Header.Frequency = PacketFrequency.Medium; Header.ID = 11; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); ParcelData = new ParcelDataBlock(); @@ -74237,11 +74801,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ParcelPropertiesRequestPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -74303,7 +74866,7 @@ public override void FromBytes(byte[] bytes, ref int i) ObjectID.FromBytes(bytes, i); i += 16; OwnerID.FromBytes(bytes, i); i += 16; Gain = Utils.BytesToFloatSafepos(bytes, i); i += 4; - Flags = (byte)bytes[i++]; + Flags = Utils.BytesToByte(bytes, ref i); } catch (Exception) { @@ -74317,7 +74880,7 @@ public override void ToBytes(byte[] bytes, ref int i) ObjectID.ToBytes(bytes, i); i += 16; OwnerID.ToBytes(bytes, i); i += 16; Utils.FloatToBytesSafepos(Gain, bytes, i); i += 4; - bytes[i++] = Flags; + Utils.ByteToBytes( Flags, bytes, ref i); } } @@ -74341,6 +74904,7 @@ public AttachedSoundPacket() Header.Frequency = PacketFrequency.Medium; Header.ID = 13; Header.Reliable = true; + NeedValidateIDs = false; DataBlock = new DataBlockBlock(); } @@ -74363,11 +74927,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public AttachedSoundPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; DataBlock.FromBytes(bytes, ref i); @@ -74455,6 +75018,7 @@ public AttachedSoundGainChangePacket() Header.Frequency = PacketFrequency.Medium; Header.ID = 14; Header.Reliable = true; + NeedValidateIDs = false; DataBlock = new DataBlockBlock(); } @@ -74477,11 +75041,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public AttachedSoundGainChangePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; DataBlock.FromBytes(bytes, ref i); @@ -74573,6 +75136,7 @@ public PreloadSoundPacket() Header.Frequency = PacketFrequency.Medium; Header.ID = 15; Header.Reliable = true; + NeedValidateIDs = false; DataBlock = null; } @@ -74603,11 +75167,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public PreloadSoundPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; int count = (int)bytes[i++]; @@ -74630,7 +75193,7 @@ public override byte[] ToBytes() byte[] bytes = new byte[length]; int i = 0; Header.ToBytes(bytes, ref i); - bytes[i++] = (byte)DataBlock.Length; + Utils.ByteToBytes((byte)DataBlock.Length, bytes, ref i); for (int j = 0; j < DataBlock.Length; j++) { DataBlock[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -74774,11 +75337,11 @@ public override void FromBytes(byte[] bytes, ref int i) { ID.FromBytes(bytes, i); i += 16; AgentID.FromBytes(bytes, i); i += 16; - Type = (byte)bytes[i++]; + Type = Utils.BytesToByte(bytes, ref i); Duration = Utils.BytesToFloatSafepos(bytes, i); i += 4; Color = new byte[4]; Buffer.BlockCopy(bytes, i, Color, 0, 4); i += 4; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); TypeData = new byte[length]; Buffer.BlockCopy(bytes, i, TypeData, 0, length); i += length; } @@ -74792,10 +75355,10 @@ public override void ToBytes(byte[] bytes, ref int i) { ID.ToBytes(bytes, i); i += 16; AgentID.ToBytes(bytes, i); i += 16; - bytes[i++] = Type; + Utils.ByteToBytes( Type, bytes, ref i); Utils.FloatToBytesSafepos(Duration, bytes, i); i += 4; Buffer.BlockCopy(Color, 0, bytes, i, 4); i += 4; - bytes[i++] = (byte)TypeData.Length; + Utils.ByteToBytes((byte)TypeData.Length, bytes, ref i); Buffer.BlockCopy(TypeData, 0, bytes, i, TypeData.Length); i += TypeData.Length; } @@ -74815,6 +75378,8 @@ public override int Length public AgentDataBlock AgentData; public EffectBlock[] Effect; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ViewerEffectPacket() { HasVariableBlocks = true; @@ -74823,6 +75388,7 @@ public ViewerEffectPacket() Header.Frequency = PacketFrequency.Medium; Header.ID = 17; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); Effect = null; @@ -74856,11 +75422,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ViewerEffectPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -74886,7 +75451,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)Effect.Length; + Utils.ByteToBytes((byte)Effect.Length, bytes, ref i); for (int j = 0; j < Effect.Length; j++) { Effect[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -74990,7 +75555,7 @@ public override void FromBytes(byte[] bytes, ref int i) { try { - PingID = (byte)bytes[i++]; + PingID = Utils.BytesToByte(bytes, ref i); OldestUnacked = Utils.BytesToUIntSafepos(bytes, i); i += 4; } catch (Exception) @@ -75001,7 +75566,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = PingID; + Utils.ByteToBytes( PingID, bytes, ref i); Utils.UIntToBytesSafepos(OldestUnacked, bytes, i); i += 4; } @@ -75026,6 +75591,7 @@ public StartPingCheckPacket() Header.Frequency = PacketFrequency.High; Header.ID = 1; Header.Reliable = true; + NeedValidateIDs = false; PingID = new PingIDBlock(); } @@ -75048,11 +75614,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public StartPingCheckPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; PingID.FromBytes(bytes, ref i); @@ -75132,7 +75697,7 @@ public override void FromBytes(byte[] bytes, ref int i) { try { - PingID = (byte)bytes[i++]; + PingID = Utils.BytesToByte(bytes, ref i); } catch (Exception) { @@ -75142,7 +75707,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = PingID; + Utils.ByteToBytes( PingID, bytes, ref i); } } @@ -75166,6 +75731,7 @@ public CompletePingCheckPacket() Header.Frequency = PacketFrequency.High; Header.ID = 2; Header.Reliable = true; + NeedValidateIDs = false; PingID = new PingIDBlock(); } @@ -75188,11 +75754,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public CompletePingCheckPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; PingID.FromBytes(bytes, ref i); @@ -75287,14 +75852,14 @@ public override void FromBytes(byte[] bytes, ref int i) SessionID.FromBytes(bytes, i); i += 16; BodyRotation.FromBytes(bytes, i, true); i += 12; HeadRotation.FromBytes(bytes, i, true); i += 12; - State = (byte)bytes[i++]; + State = Utils.BytesToByte(bytes, ref i); CameraCenter.FromBytes(bytes, i); i += 12; CameraAtAxis.FromBytes(bytes, i); i += 12; CameraLeftAxis.FromBytes(bytes, i); i += 12; CameraUpAxis.FromBytes(bytes, i); i += 12; Far = Utils.BytesToFloatSafepos(bytes, i); i += 4; ControlFlags = Utils.BytesToUIntSafepos(bytes, i); i += 4; - Flags = (byte)bytes[i++]; + Flags = Utils.BytesToByte(bytes, ref i); } catch (Exception) { @@ -75308,14 +75873,14 @@ public override void ToBytes(byte[] bytes, ref int i) SessionID.ToBytes(bytes, i); i += 16; BodyRotation.ToBytes(bytes, i); i += 12; HeadRotation.ToBytes(bytes, i); i += 12; - bytes[i++] = State; + Utils.ByteToBytes( State, bytes, ref i); CameraCenter.ToBytes(bytes, i); i += 12; CameraAtAxis.ToBytes(bytes, i); i += 12; CameraLeftAxis.ToBytes(bytes, i); i += 12; CameraUpAxis.ToBytes(bytes, i); i += 12; Utils.FloatToBytesSafepos(Far, bytes, i); i += 4; Utils.UIntToBytesSafepos(ControlFlags, bytes, i); i += 4; - bytes[i++] = Flags; + Utils.ByteToBytes( Flags, bytes, ref i); } } @@ -75331,6 +75896,8 @@ public override int Length } public AgentDataBlock AgentData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public AgentUpdatePacket() { HasVariableBlocks = false; @@ -75339,6 +75906,7 @@ public AgentUpdatePacket() Header.Frequency = PacketFrequency.High; Header.ID = 4; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); } @@ -75362,11 +75930,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public AgentUpdatePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -75489,7 +76056,7 @@ public override void FromBytes(byte[] bytes, ref int i) try { AnimID.FromBytes(bytes, i); i += 16; - StartAnim = (bytes[i++] != 0) ? (bool)true : (bool)false; + StartAnim = (Utils.BytesToByte(bytes, ref i) != 0); } catch (Exception) { @@ -75500,7 +76067,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { AnimID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)((StartAnim) ? 1 : 0); + Utils.ByteToBytes((byte)((StartAnim) ? 1 : 0), bytes, ref i); } } @@ -75531,7 +76098,7 @@ public override void FromBytes(byte[] bytes, ref int i) int length; try { - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); TypeData = new byte[length]; Buffer.BlockCopy(bytes, i, TypeData, 0, length); i += length; } @@ -75543,7 +76110,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = (byte)TypeData.Length; + Utils.ByteToBytes((byte)TypeData.Length, bytes, ref i); Buffer.BlockCopy(TypeData, 0, bytes, i, TypeData.Length); i += TypeData.Length; } @@ -75566,6 +76133,8 @@ public override int Length public AnimationListBlock[] AnimationList; public PhysicalAvatarEventListBlock[] PhysicalAvatarEventList; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public AgentAnimationPacket() { HasVariableBlocks = true; @@ -75574,6 +76143,7 @@ public AgentAnimationPacket() Header.Frequency = PacketFrequency.High; Header.ID = 5; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); AnimationList = null; PhysicalAvatarEventList = null; @@ -75616,11 +76186,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public AgentAnimationPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -75657,9 +76226,9 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)AnimationList.Length; + Utils.ByteToBytes((byte)AnimationList.Length, bytes, ref i); for (int j = 0; j < AnimationList.Length; j++) { AnimationList[j].ToBytes(bytes, ref i); } - bytes[i++] = (byte)PhysicalAvatarEventList.Length; + Utils.ByteToBytes((byte)PhysicalAvatarEventList.Length, bytes, ref i); for (int j = 0; j < PhysicalAvatarEventList.Length; j++) { PhysicalAvatarEventList[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -75964,6 +76533,8 @@ public override int Length public AgentDataBlock AgentData; public TargetObjectBlock TargetObject; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public AgentRequestSitPacket() { HasVariableBlocks = false; @@ -75972,6 +76543,7 @@ public AgentRequestSitPacket() Header.Frequency = PacketFrequency.High; Header.ID = 6; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); TargetObject = new TargetObjectBlock(); @@ -75997,11 +76569,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public AgentRequestSitPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -76115,6 +76686,8 @@ public override int Length } public AgentDataBlock AgentData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public AgentSitPacket() { HasVariableBlocks = false; @@ -76123,6 +76696,7 @@ public AgentSitPacket() Header.Frequency = PacketFrequency.High; Header.ID = 7; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); } @@ -76145,11 +76719,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public AgentSitPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -76275,10 +76848,10 @@ public override void FromBytes(byte[] bytes, ref int i) try { Image.FromBytes(bytes, i); i += 16; - DiscardLevel = (sbyte)bytes[i++]; + DiscardLevel = (sbyte)Utils.BytesToByte(bytes, ref i); DownloadPriority = Utils.BytesToFloatSafepos(bytes, i); i += 4; Packet = Utils.BytesToUIntSafepos(bytes, i); i += 4; - Type = (byte)bytes[i++]; + Type = Utils.BytesToByte(bytes, ref i); } catch (Exception) { @@ -76289,10 +76862,10 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { Image.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)DiscardLevel; + Utils.ByteToBytes( (byte)DiscardLevel, bytes, ref i); Utils.FloatToBytesSafepos(DownloadPriority, bytes, i); i += 4; Utils.UIntToBytesSafepos(Packet, bytes, i); i += 4; - bytes[i++] = Type; + Utils.ByteToBytes( Type, bytes, ref i); } } @@ -76311,6 +76884,8 @@ public override int Length public AgentDataBlock AgentData; public RequestImageBlock[] RequestImage; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public RequestImagePacket() { HasVariableBlocks = true; @@ -76319,6 +76894,7 @@ public RequestImagePacket() Header.Frequency = PacketFrequency.High; Header.ID = 8; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); RequestImage = null; } @@ -76351,11 +76927,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public RequestImagePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -76381,7 +76956,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)RequestImage.Length; + Utils.ByteToBytes((byte)RequestImage.Length, bytes, ref i); for (int j = 0; j < RequestImage.Length; j++) { RequestImage[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -76574,7 +77149,7 @@ public override void FromBytes(byte[] bytes, ref int i) try { ID.FromBytes(bytes, i); i += 16; - Codec = (byte)bytes[i++]; + Codec = Utils.BytesToByte(bytes, ref i); Size = Utils.BytesToUIntSafepos(bytes, i); i += 4; Packets = Utils.BytesToUInt16(bytes, i); i += 2; } @@ -76587,7 +77162,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { ID.ToBytes(bytes, i); i += 16; - bytes[i++] = Codec; + Utils.ByteToBytes( Codec, bytes, ref i); Utils.UIntToBytesSafepos(Size, bytes, i); i += 4; Utils.UInt16ToBytes(Packets, bytes, i); i += 2; } @@ -76620,7 +77195,7 @@ public override void FromBytes(byte[] bytes, ref int i) int length; try { - length = (bytes[i++] + (bytes[i++] << 8)); + length = Utils.BytesToUInt16(bytes, i); i+=2; Data = new byte[length]; Buffer.BlockCopy(bytes, i, Data, 0, length); i += length; } @@ -76632,8 +77207,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = (byte)(Data.Length % 256); - bytes[i++] = (byte)((Data.Length >> 8) % 256); + Utils.UInt16ToBytes((ushort)Data.Length, bytes, i); i += 2; Buffer.BlockCopy(Data, 0, bytes, i, Data.Length); i += Data.Length; } @@ -76660,6 +77234,7 @@ public ImageDataPacket() Header.Frequency = PacketFrequency.High; Header.ID = 9; Header.Reliable = true; + NeedValidateIDs = false; ImageID = new ImageIDBlock(); ImageData = new ImageDataBlock(); } @@ -76684,11 +77259,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ImageDataPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; ImageID.FromBytes(bytes, ref i); @@ -76818,7 +77392,7 @@ public override void FromBytes(byte[] bytes, ref int i) int length; try { - length = (bytes[i++] + (bytes[i++] << 8)); + length = Utils.BytesToUInt16(bytes, i); i+=2; Data = new byte[length]; Buffer.BlockCopy(bytes, i, Data, 0, length); i += length; } @@ -76830,8 +77404,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = (byte)(Data.Length % 256); - bytes[i++] = (byte)((Data.Length >> 8) % 256); + Utils.UInt16ToBytes((ushort)Data.Length, bytes, i); i += 2; Buffer.BlockCopy(Data, 0, bytes, i, Data.Length); i += Data.Length; } @@ -76858,6 +77431,7 @@ public ImagePacketPacket() Header.Frequency = PacketFrequency.High; Header.ID = 10; Header.Reliable = true; + NeedValidateIDs = false; ImageID = new ImageIDBlock(); ImageData = new ImageDataBlock(); } @@ -76882,11 +77456,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ImagePacketPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; ImageID.FromBytes(bytes, ref i); @@ -76971,7 +77544,7 @@ public override void FromBytes(byte[] bytes, ref int i) { try { - Type = (byte)bytes[i++]; + Type = Utils.BytesToByte(bytes, ref i); } catch (Exception) { @@ -76981,7 +77554,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = Type; + Utils.ByteToBytes( Type, bytes, ref i); } } @@ -77012,7 +77585,7 @@ public override void FromBytes(byte[] bytes, ref int i) int length; try { - length = (bytes[i++] + (bytes[i++] << 8)); + length = Utils.BytesToUInt16(bytes, i); i+=2; Data = new byte[length]; Buffer.BlockCopy(bytes, i, Data, 0, length); i += length; } @@ -77024,8 +77597,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = (byte)(Data.Length % 256); - bytes[i++] = (byte)((Data.Length >> 8) % 256); + Utils.UInt16ToBytes((ushort)Data.Length, bytes, i); i += 2; Buffer.BlockCopy(Data, 0, bytes, i, Data.Length); i += Data.Length; } @@ -77052,6 +77624,7 @@ public LayerDataPacket() Header.Frequency = PacketFrequency.High; Header.ID = 11; Header.Reliable = true; + NeedValidateIDs = false; LayerID = new LayerIDBlock(); LayerData = new LayerDataBlock(); } @@ -77076,11 +77649,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public LayerDataPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; LayerID.FromBytes(bytes, ref i); @@ -77263,68 +77835,68 @@ public override void FromBytes(byte[] bytes, ref int i) try { ID = Utils.BytesToUIntSafepos(bytes, i); i += 4; - State = (byte)bytes[i++]; + State = Utils.BytesToByte(bytes, ref i); FullID.FromBytes(bytes, i); i += 16; CRC = Utils.BytesToUIntSafepos(bytes, i); i += 4; - PCode = (byte)bytes[i++]; - Material = (byte)bytes[i++]; - ClickAction = (byte)bytes[i++]; + PCode = Utils.BytesToByte(bytes, ref i); + Material = Utils.BytesToByte(bytes, ref i); + ClickAction = Utils.BytesToByte(bytes, ref i); Scale.FromBytes(bytes, i); i += 12; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); ObjectData = new byte[length]; Buffer.BlockCopy(bytes, i, ObjectData, 0, length); i += length; ParentID = Utils.BytesToUIntSafepos(bytes, i); i += 4; UpdateFlags = Utils.BytesToUIntSafepos(bytes, i); i += 4; - PathCurve = (byte)bytes[i++]; - ProfileCurve = (byte)bytes[i++]; + PathCurve = Utils.BytesToByte(bytes, ref i); + ProfileCurve = Utils.BytesToByte(bytes, ref i); PathBegin = Utils.BytesToUInt16(bytes, i); i += 2; PathEnd = Utils.BytesToUInt16(bytes, i); i += 2; - PathScaleX = (byte)bytes[i++]; - PathScaleY = (byte)bytes[i++]; - PathShearX = (byte)bytes[i++]; - PathShearY = (byte)bytes[i++]; - PathTwist = (sbyte)bytes[i++]; - PathTwistBegin = (sbyte)bytes[i++]; - PathRadiusOffset = (sbyte)bytes[i++]; - PathTaperX = (sbyte)bytes[i++]; - PathTaperY = (sbyte)bytes[i++]; - PathRevolutions = (byte)bytes[i++]; - PathSkew = (sbyte)bytes[i++]; + PathScaleX = Utils.BytesToByte(bytes, ref i); + PathScaleY = Utils.BytesToByte(bytes, ref i); + PathShearX = Utils.BytesToByte(bytes, ref i); + PathShearY = Utils.BytesToByte(bytes, ref i); + PathTwist = (sbyte)Utils.BytesToByte(bytes, ref i); + PathTwistBegin = (sbyte)Utils.BytesToByte(bytes, ref i); + PathRadiusOffset = (sbyte)Utils.BytesToByte(bytes, ref i); + PathTaperX = (sbyte)Utils.BytesToByte(bytes, ref i); + PathTaperY = (sbyte)Utils.BytesToByte(bytes, ref i); + PathRevolutions = Utils.BytesToByte(bytes, ref i); + PathSkew = (sbyte)Utils.BytesToByte(bytes, ref i); ProfileBegin = Utils.BytesToUInt16(bytes, i); i += 2; ProfileEnd = Utils.BytesToUInt16(bytes, i); i += 2; ProfileHollow = Utils.BytesToUInt16(bytes, i); i += 2; - length = (bytes[i++] + (bytes[i++] << 8)); + length = Utils.BytesToUInt16(bytes, i); i+=2; TextureEntry = new byte[length]; Buffer.BlockCopy(bytes, i, TextureEntry, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); TextureAnim = new byte[length]; Buffer.BlockCopy(bytes, i, TextureAnim, 0, length); i += length; - length = (bytes[i++] + (bytes[i++] << 8)); + length = Utils.BytesToUInt16(bytes, i); i+=2; NameValue = new byte[length]; Buffer.BlockCopy(bytes, i, NameValue, 0, length); i += length; - length = (bytes[i++] + (bytes[i++] << 8)); + length = Utils.BytesToUInt16(bytes, i); i+=2; Data = new byte[length]; Buffer.BlockCopy(bytes, i, Data, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Text = new byte[length]; Buffer.BlockCopy(bytes, i, Text, 0, length); i += length; TextColor = new byte[4]; Buffer.BlockCopy(bytes, i, TextColor, 0, 4); i += 4; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); MediaURL = new byte[length]; Buffer.BlockCopy(bytes, i, MediaURL, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); PSBlock = new byte[length]; Buffer.BlockCopy(bytes, i, PSBlock, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); ExtraParams = new byte[length]; Buffer.BlockCopy(bytes, i, ExtraParams, 0, length); i += length; Sound.FromBytes(bytes, i); i += 16; OwnerID.FromBytes(bytes, i); i += 16; Gain = Utils.BytesToFloatSafepos(bytes, i); i += 4; - Flags = (byte)bytes[i++]; + Flags = Utils.BytesToByte(bytes, ref i); Radius = Utils.BytesToFloatSafepos(bytes, i); i += 4; - JointType = (byte)bytes[i++]; + JointType = Utils.BytesToByte(bytes, ref i); JointPivot.FromBytes(bytes, i); i += 12; JointAxisOrAnchor.FromBytes(bytes, i); i += 12; } @@ -77337,61 +77909,58 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { Utils.UIntToBytesSafepos(ID, bytes, i); i += 4; - bytes[i++] = State; + Utils.ByteToBytes( State, bytes, ref i); FullID.ToBytes(bytes, i); i += 16; Utils.UIntToBytesSafepos(CRC, bytes, i); i += 4; - bytes[i++] = PCode; - bytes[i++] = Material; - bytes[i++] = ClickAction; + Utils.ByteToBytes( PCode, bytes, ref i); + Utils.ByteToBytes( Material, bytes, ref i); + Utils.ByteToBytes( ClickAction, bytes, ref i); Scale.ToBytes(bytes, i); i += 12; - bytes[i++] = (byte)ObjectData.Length; + Utils.ByteToBytes((byte)ObjectData.Length, bytes, ref i); Buffer.BlockCopy(ObjectData, 0, bytes, i, ObjectData.Length); i += ObjectData.Length; Utils.UIntToBytesSafepos(ParentID, bytes, i); i += 4; Utils.UIntToBytesSafepos(UpdateFlags, bytes, i); i += 4; - bytes[i++] = PathCurve; - bytes[i++] = ProfileCurve; + Utils.ByteToBytes( PathCurve, bytes, ref i); + Utils.ByteToBytes( ProfileCurve, bytes, ref i); Utils.UInt16ToBytes(PathBegin, bytes, i); i += 2; Utils.UInt16ToBytes(PathEnd, bytes, i); i += 2; - bytes[i++] = PathScaleX; - bytes[i++] = PathScaleY; - bytes[i++] = PathShearX; - bytes[i++] = PathShearY; - bytes[i++] = (byte)PathTwist; - bytes[i++] = (byte)PathTwistBegin; - bytes[i++] = (byte)PathRadiusOffset; - bytes[i++] = (byte)PathTaperX; - bytes[i++] = (byte)PathTaperY; - bytes[i++] = PathRevolutions; - bytes[i++] = (byte)PathSkew; + Utils.ByteToBytes( PathScaleX, bytes, ref i); + Utils.ByteToBytes( PathScaleY, bytes, ref i); + Utils.ByteToBytes( PathShearX, bytes, ref i); + Utils.ByteToBytes( PathShearY, bytes, ref i); + Utils.ByteToBytes( (byte)PathTwist, bytes, ref i); + Utils.ByteToBytes( (byte)PathTwistBegin, bytes, ref i); + Utils.ByteToBytes( (byte)PathRadiusOffset, bytes, ref i); + Utils.ByteToBytes( (byte)PathTaperX, bytes, ref i); + Utils.ByteToBytes( (byte)PathTaperY, bytes, ref i); + Utils.ByteToBytes( PathRevolutions, bytes, ref i); + Utils.ByteToBytes( (byte)PathSkew, bytes, ref i); Utils.UInt16ToBytes(ProfileBegin, bytes, i); i += 2; Utils.UInt16ToBytes(ProfileEnd, bytes, i); i += 2; Utils.UInt16ToBytes(ProfileHollow, bytes, i); i += 2; - bytes[i++] = (byte)(TextureEntry.Length % 256); - bytes[i++] = (byte)((TextureEntry.Length >> 8) % 256); + Utils.UInt16ToBytes((ushort)TextureEntry.Length, bytes, i); i += 2; Buffer.BlockCopy(TextureEntry, 0, bytes, i, TextureEntry.Length); i += TextureEntry.Length; - bytes[i++] = (byte)TextureAnim.Length; + Utils.ByteToBytes((byte)TextureAnim.Length, bytes, ref i); Buffer.BlockCopy(TextureAnim, 0, bytes, i, TextureAnim.Length); i += TextureAnim.Length; - bytes[i++] = (byte)(NameValue.Length % 256); - bytes[i++] = (byte)((NameValue.Length >> 8) % 256); + Utils.UInt16ToBytes((ushort)NameValue.Length, bytes, i); i += 2; Buffer.BlockCopy(NameValue, 0, bytes, i, NameValue.Length); i += NameValue.Length; - bytes[i++] = (byte)(Data.Length % 256); - bytes[i++] = (byte)((Data.Length >> 8) % 256); + Utils.UInt16ToBytes((ushort)Data.Length, bytes, i); i += 2; Buffer.BlockCopy(Data, 0, bytes, i, Data.Length); i += Data.Length; - bytes[i++] = (byte)Text.Length; + Utils.ByteToBytes((byte)Text.Length, bytes, ref i); Buffer.BlockCopy(Text, 0, bytes, i, Text.Length); i += Text.Length; Buffer.BlockCopy(TextColor, 0, bytes, i, 4); i += 4; - bytes[i++] = (byte)MediaURL.Length; + Utils.ByteToBytes((byte)MediaURL.Length, bytes, ref i); Buffer.BlockCopy(MediaURL, 0, bytes, i, MediaURL.Length); i += MediaURL.Length; - bytes[i++] = (byte)PSBlock.Length; + Utils.ByteToBytes((byte)PSBlock.Length, bytes, ref i); Buffer.BlockCopy(PSBlock, 0, bytes, i, PSBlock.Length); i += PSBlock.Length; - bytes[i++] = (byte)ExtraParams.Length; + Utils.ByteToBytes((byte)ExtraParams.Length, bytes, ref i); Buffer.BlockCopy(ExtraParams, 0, bytes, i, ExtraParams.Length); i += ExtraParams.Length; Sound.ToBytes(bytes, i); i += 16; OwnerID.ToBytes(bytes, i); i += 16; Utils.FloatToBytesSafepos(Gain, bytes, i); i += 4; - bytes[i++] = Flags; + Utils.ByteToBytes( Flags, bytes, ref i); Utils.FloatToBytesSafepos(Radius, bytes, i); i += 4; - bytes[i++] = JointType; + Utils.ByteToBytes( JointType, bytes, ref i); JointPivot.ToBytes(bytes, i); i += 12; JointAxisOrAnchor.ToBytes(bytes, i); i += 12; } @@ -77420,6 +77989,7 @@ public ObjectUpdatePacket() Header.Frequency = PacketFrequency.High; Header.ID = 12; Header.Reliable = true; + NeedValidateIDs = false; Header.Zerocoded = true; RegionData = new RegionDataBlock(); ObjectData = null; @@ -77453,11 +78023,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ObjectUpdatePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; RegionData.FromBytes(bytes, ref i); @@ -77483,7 +78052,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); RegionData.ToBytes(bytes, ref i); - bytes[i++] = (byte)ObjectData.Length; + Utils.ByteToBytes((byte)ObjectData.Length, bytes, ref i); for (int j = 0; j < ObjectData.Length; j++) { ObjectData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -77718,7 +78287,7 @@ public override void FromBytes(byte[] bytes, ref int i) try { UpdateFlags = Utils.BytesToUIntSafepos(bytes, i); i += 4; - length = (bytes[i++] + (bytes[i++] << 8)); + length = Utils.BytesToUInt16(bytes, i); i+=2; Data = new byte[length]; Buffer.BlockCopy(bytes, i, Data, 0, length); i += length; } @@ -77731,8 +78300,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { Utils.UIntToBytesSafepos(UpdateFlags, bytes, i); i += 4; - bytes[i++] = (byte)(Data.Length % 256); - bytes[i++] = (byte)((Data.Length >> 8) % 256); + Utils.UInt16ToBytes((ushort)Data.Length, bytes, i); i += 2; Buffer.BlockCopy(Data, 0, bytes, i, Data.Length); i += Data.Length; } @@ -77760,6 +78328,7 @@ public ObjectUpdateCompressedPacket() Header.Frequency = PacketFrequency.High; Header.ID = 13; Header.Reliable = true; + NeedValidateIDs = false; RegionData = new RegionDataBlock(); ObjectData = null; } @@ -77792,11 +78361,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ObjectUpdateCompressedPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; RegionData.FromBytes(bytes, ref i); @@ -77822,7 +78390,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); RegionData.ToBytes(bytes, ref i); - bytes[i++] = (byte)ObjectData.Length; + Utils.ByteToBytes((byte)ObjectData.Length, bytes, ref i); for (int j = 0; j < ObjectData.Length; j++) { ObjectData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -78095,6 +78663,7 @@ public ObjectUpdateCachedPacket() Header.Frequency = PacketFrequency.High; Header.ID = 14; Header.Reliable = true; + NeedValidateIDs = false; RegionData = new RegionDataBlock(); ObjectData = null; } @@ -78127,11 +78696,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ObjectUpdateCachedPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; RegionData.FromBytes(bytes, ref i); @@ -78157,7 +78725,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); RegionData.ToBytes(bytes, ref i); - bytes[i++] = (byte)ObjectData.Length; + Utils.ByteToBytes((byte)ObjectData.Length, bytes, ref i); for (int j = 0; j < ObjectData.Length; j++) { ObjectData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -78392,10 +78960,10 @@ public override void FromBytes(byte[] bytes, ref int i) int length; try { - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Data = new byte[length]; Buffer.BlockCopy(bytes, i, Data, 0, length); i += length; - length = (bytes[i++] + (bytes[i++] << 8)); + length = Utils.BytesToUInt16(bytes, i); i+=2; TextureEntry = new byte[length]; Buffer.BlockCopy(bytes, i, TextureEntry, 0, length); i += length; } @@ -78407,10 +78975,9 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = (byte)Data.Length; + Utils.ByteToBytes((byte)Data.Length, bytes, ref i); Buffer.BlockCopy(Data, 0, bytes, i, Data.Length); i += Data.Length; - bytes[i++] = (byte)(TextureEntry.Length % 256); - bytes[i++] = (byte)((TextureEntry.Length >> 8) % 256); + Utils.UInt16ToBytes((ushort)TextureEntry.Length, bytes, i); i += 2; Buffer.BlockCopy(TextureEntry, 0, bytes, i, TextureEntry.Length); i += TextureEntry.Length; } @@ -78438,6 +79005,7 @@ public ImprovedTerseObjectUpdatePacket() Header.Frequency = PacketFrequency.High; Header.ID = 15; Header.Reliable = true; + NeedValidateIDs = false; RegionData = new RegionDataBlock(); ObjectData = null; } @@ -78470,11 +79038,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ImprovedTerseObjectUpdatePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; RegionData.FromBytes(bytes, ref i); @@ -78500,7 +79067,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); RegionData.ToBytes(bytes, ref i); - bytes[i++] = (byte)ObjectData.Length; + Utils.ByteToBytes((byte)ObjectData.Length, bytes, ref i); for (int j = 0; j < ObjectData.Length; j++) { ObjectData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -78725,6 +79292,7 @@ public KillObjectPacket() Header.Frequency = PacketFrequency.High; Header.ID = 16; Header.Reliable = true; + NeedValidateIDs = false; ObjectData = null; } @@ -78755,11 +79323,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public KillObjectPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; int count = (int)bytes[i++]; @@ -78782,7 +79349,7 @@ public override byte[] ToBytes() byte[] bytes = new byte[length]; int i = 0; Header.ToBytes(bytes, ref i); - bytes[i++] = (byte)ObjectData.Length; + Utils.ByteToBytes((byte)ObjectData.Length, bytes, ref i); for (int j = 0; j < ObjectData.Length; j++) { ObjectData[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -78976,7 +79543,7 @@ public override void FromBytes(byte[] bytes, ref int i) ChannelType = Utils.BytesToIntSafepos(bytes, i); i += 4; Packet = Utils.BytesToIntSafepos(bytes, i); i += 4; Status = Utils.BytesToIntSafepos(bytes, i); i += 4; - length = (bytes[i++] + (bytes[i++] << 8)); + length = Utils.BytesToUInt16(bytes, i); i+=2; Data = new byte[length]; Buffer.BlockCopy(bytes, i, Data, 0, length); i += length; } @@ -78992,8 +79559,7 @@ public override void ToBytes(byte[] bytes, ref int i) Utils.IntToBytesSafepos(ChannelType, bytes, i); i += 4; Utils.IntToBytesSafepos(Packet, bytes, i); i += 4; Utils.IntToBytesSafepos(Status, bytes, i); i += 4; - bytes[i++] = (byte)(Data.Length % 256); - bytes[i++] = (byte)((Data.Length >> 8) % 256); + Utils.UInt16ToBytes((ushort)Data.Length, bytes, i); i += 2; Buffer.BlockCopy(Data, 0, bytes, i, Data.Length); i += Data.Length; } @@ -79018,6 +79584,7 @@ public TransferPacketPacket() Header.Frequency = PacketFrequency.High; Header.ID = 17; Header.Reliable = true; + NeedValidateIDs = false; TransferData = new TransferDataBlock(); } @@ -79040,11 +79607,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public TransferPacketPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; TransferData.FromBytes(bytes, ref i); @@ -79168,7 +79734,7 @@ public override void FromBytes(byte[] bytes, ref int i) int length; try { - length = (bytes[i++] + (bytes[i++] << 8)); + length = Utils.BytesToUInt16(bytes, i); i+=2; Data = new byte[length]; Buffer.BlockCopy(bytes, i, Data, 0, length); i += length; } @@ -79180,8 +79746,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = (byte)(Data.Length % 256); - bytes[i++] = (byte)((Data.Length >> 8) % 256); + Utils.UInt16ToBytes((ushort)Data.Length, bytes, i); i += 2; Buffer.BlockCopy(Data, 0, bytes, i, Data.Length); i += Data.Length; } @@ -79208,6 +79773,7 @@ public SendXferPacketPacket() Header.Frequency = PacketFrequency.High; Header.ID = 18; Header.Reliable = true; + NeedValidateIDs = false; XferID = new XferIDBlock(); DataPacket = new DataPacketBlock(); } @@ -79232,11 +79798,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public SendXferPacketPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; XferID.FromBytes(bytes, ref i); @@ -79358,6 +79923,7 @@ public ConfirmXferPacketPacket() Header.Frequency = PacketFrequency.High; Header.ID = 19; Header.Reliable = true; + NeedValidateIDs = false; XferID = new XferIDBlock(); } @@ -79380,11 +79946,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ConfirmXferPacketPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; XferID.FromBytes(bytes, ref i); @@ -79584,7 +80149,7 @@ public override void FromBytes(byte[] bytes, ref int i) int length; try { - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); TypeData = new byte[length]; Buffer.BlockCopy(bytes, i, TypeData, 0, length); i += length; } @@ -79596,7 +80161,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = (byte)TypeData.Length; + Utils.ByteToBytes((byte)TypeData.Length, bytes, ref i); Buffer.BlockCopy(TypeData, 0, bytes, i, TypeData.Length); i += TypeData.Length; } @@ -79630,6 +80195,7 @@ public AvatarAnimationPacket() Header.Frequency = PacketFrequency.High; Header.ID = 20; Header.Reliable = true; + NeedValidateIDs = false; Sender = new SenderBlock(); AnimationList = null; AnimationSourceList = null; @@ -79682,11 +80248,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public AvatarAnimationPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; Sender.FromBytes(bytes, ref i); @@ -79734,11 +80299,11 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); Sender.ToBytes(bytes, ref i); - bytes[i++] = (byte)AnimationList.Length; + Utils.ByteToBytes((byte)AnimationList.Length, bytes, ref i); for (int j = 0; j < AnimationList.Length; j++) { AnimationList[j].ToBytes(bytes, ref i); } - bytes[i++] = (byte)AnimationSourceList.Length; + Utils.ByteToBytes((byte)AnimationSourceList.Length, bytes, ref i); for (int j = 0; j < AnimationSourceList.Length; j++) { AnimationSourceList[j].ToBytes(bytes, ref i); } - bytes[i++] = (byte)PhysicalAvatarEventList.Length; + Utils.ByteToBytes((byte)PhysicalAvatarEventList.Length, bytes, ref i); for (int j = 0; j < PhysicalAvatarEventList.Length; j++) { PhysicalAvatarEventList[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -80058,12 +80623,12 @@ public override void FromBytes(byte[] bytes, ref int i) { try { - AutoPilot = (bytes[i++] != 0) ? (bool)true : (bool)false; + AutoPilot = (Utils.BytesToByte(bytes, ref i) != 0); SitPosition.FromBytes(bytes, i); i += 12; SitRotation.FromBytes(bytes, i, true); i += 12; CameraEyeOffset.FromBytes(bytes, i); i += 12; CameraAtOffset.FromBytes(bytes, i); i += 12; - ForceMouselook = (bytes[i++] != 0) ? (bool)true : (bool)false; + ForceMouselook = (Utils.BytesToByte(bytes, ref i) != 0); } catch (Exception) { @@ -80073,12 +80638,12 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = (byte)((AutoPilot) ? 1 : 0); + Utils.ByteToBytes((byte)((AutoPilot) ? 1 : 0), bytes, ref i); SitPosition.ToBytes(bytes, i); i += 12; SitRotation.ToBytes(bytes, i); i += 12; CameraEyeOffset.ToBytes(bytes, i); i += 12; CameraAtOffset.ToBytes(bytes, i); i += 12; - bytes[i++] = (byte)((ForceMouselook) ? 1 : 0); + Utils.ByteToBytes((byte)((ForceMouselook) ? 1 : 0), bytes, ref i); } } @@ -80104,6 +80669,7 @@ public AvatarSitResponsePacket() Header.Frequency = PacketFrequency.High; Header.ID = 21; Header.Reliable = true; + NeedValidateIDs = false; Header.Zerocoded = true; SitObject = new SitObjectBlock(); SitTransform = new SitTransformBlock(); @@ -80129,11 +80695,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public AvatarSitResponsePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; SitObject.FromBytes(bytes, ref i); @@ -80252,6 +80817,7 @@ public CameraConstraintPacket() Header.Frequency = PacketFrequency.High; Header.ID = 22; Header.Reliable = true; + NeedValidateIDs = false; Header.Zerocoded = true; CameraCollidePlane = new CameraCollidePlaneBlock(); } @@ -80275,11 +80841,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public CameraConstraintPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; CameraCollidePlane.FromBytes(bytes, ref i); @@ -80416,24 +80981,24 @@ public override void FromBytes(byte[] bytes, ref int i) { RequestResult = Utils.BytesToIntSafepos(bytes, i); i += 4; SequenceID = Utils.BytesToIntSafepos(bytes, i); i += 4; - SnapSelection = (bytes[i++] != 0) ? (bool)true : (bool)false; + SnapSelection = (Utils.BytesToByte(bytes, ref i) != 0); SelfCount = Utils.BytesToIntSafepos(bytes, i); i += 4; OtherCount = Utils.BytesToIntSafepos(bytes, i); i += 4; PublicCount = Utils.BytesToIntSafepos(bytes, i); i += 4; LocalID = Utils.BytesToIntSafepos(bytes, i); i += 4; OwnerID.FromBytes(bytes, i); i += 16; - IsGroupOwned = (bytes[i++] != 0) ? (bool)true : (bool)false; + IsGroupOwned = (Utils.BytesToByte(bytes, ref i) != 0); AuctionID = Utils.BytesToUIntSafepos(bytes, i); i += 4; ClaimDate = Utils.BytesToIntSafepos(bytes, i); i += 4; ClaimPrice = Utils.BytesToIntSafepos(bytes, i); i += 4; RentPrice = Utils.BytesToIntSafepos(bytes, i); i += 4; AABBMin.FromBytes(bytes, i); i += 12; AABBMax.FromBytes(bytes, i); i += 12; - length = (bytes[i++] + (bytes[i++] << 8)); + length = Utils.BytesToUInt16(bytes, i); i+=2; Bitmap = new byte[length]; Buffer.BlockCopy(bytes, i, Bitmap, 0, length); i += length; Area = Utils.BytesToIntSafepos(bytes, i); i += 4; - Status = (byte)bytes[i++]; + Status = Utils.BytesToByte(bytes, ref i); SimWideMaxPrims = Utils.BytesToIntSafepos(bytes, i); i += 4; SimWideTotalPrims = Utils.BytesToIntSafepos(bytes, i); i += 4; MaxPrims = Utils.BytesToIntSafepos(bytes, i); i += 4; @@ -80446,33 +81011,33 @@ public override void FromBytes(byte[] bytes, ref int i) OtherCleanTime = Utils.BytesToIntSafepos(bytes, i); i += 4; ParcelFlags = Utils.BytesToUIntSafepos(bytes, i); i += 4; SalePrice = Utils.BytesToIntSafepos(bytes, i); i += 4; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Name = new byte[length]; Buffer.BlockCopy(bytes, i, Name, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Desc = new byte[length]; Buffer.BlockCopy(bytes, i, Desc, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); MusicURL = new byte[length]; Buffer.BlockCopy(bytes, i, MusicURL, 0, length); i += length; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); MediaURL = new byte[length]; Buffer.BlockCopy(bytes, i, MediaURL, 0, length); i += length; MediaID.FromBytes(bytes, i); i += 16; - MediaAutoScale = (byte)bytes[i++]; + MediaAutoScale = Utils.BytesToByte(bytes, ref i); GroupID.FromBytes(bytes, i); i += 16; PassPrice = Utils.BytesToIntSafepos(bytes, i); i += 4; PassHours = Utils.BytesToFloatSafepos(bytes, i); i += 4; - Category = (byte)bytes[i++]; + Category = Utils.BytesToByte(bytes, ref i); AuthBuyerID.FromBytes(bytes, i); i += 16; SnapshotID.FromBytes(bytes, i); i += 16; UserLocation.FromBytes(bytes, i); i += 12; UserLookAt.FromBytes(bytes, i); i += 12; - LandingType = (byte)bytes[i++]; - RegionPushOverride = (bytes[i++] != 0) ? (bool)true : (bool)false; - RegionDenyAnonymous = (bytes[i++] != 0) ? (bool)true : (bool)false; - RegionDenyIdentified = (bytes[i++] != 0) ? (bool)true : (bool)false; - RegionDenyTransacted = (bytes[i++] != 0) ? (bool)true : (bool)false; + LandingType = Utils.BytesToByte(bytes, ref i); + RegionPushOverride = (Utils.BytesToByte(bytes, ref i) != 0); + RegionDenyAnonymous = (Utils.BytesToByte(bytes, ref i) != 0); + RegionDenyIdentified = (Utils.BytesToByte(bytes, ref i) != 0); + RegionDenyTransacted = (Utils.BytesToByte(bytes, ref i) != 0); } catch (Exception) { @@ -80484,24 +81049,23 @@ public override void ToBytes(byte[] bytes, ref int i) { Utils.IntToBytesSafepos(RequestResult, bytes, i); i += 4; Utils.IntToBytesSafepos(SequenceID, bytes, i); i += 4; - bytes[i++] = (byte)((SnapSelection) ? 1 : 0); + Utils.ByteToBytes((byte)((SnapSelection) ? 1 : 0), bytes, ref i); Utils.IntToBytesSafepos(SelfCount, bytes, i); i += 4; Utils.IntToBytesSafepos(OtherCount, bytes, i); i += 4; Utils.IntToBytesSafepos(PublicCount, bytes, i); i += 4; Utils.IntToBytesSafepos(LocalID, bytes, i); i += 4; OwnerID.ToBytes(bytes, i); i += 16; - bytes[i++] = (byte)((IsGroupOwned) ? 1 : 0); + Utils.ByteToBytes((byte)((IsGroupOwned) ? 1 : 0), bytes, ref i); Utils.UIntToBytesSafepos(AuctionID, bytes, i); i += 4; Utils.IntToBytesSafepos(ClaimDate, bytes, i); i += 4; Utils.IntToBytesSafepos(ClaimPrice, bytes, i); i += 4; Utils.IntToBytesSafepos(RentPrice, bytes, i); i += 4; AABBMin.ToBytes(bytes, i); i += 12; AABBMax.ToBytes(bytes, i); i += 12; - bytes[i++] = (byte)(Bitmap.Length % 256); - bytes[i++] = (byte)((Bitmap.Length >> 8) % 256); + Utils.UInt16ToBytes((ushort)Bitmap.Length, bytes, i); i += 2; Buffer.BlockCopy(Bitmap, 0, bytes, i, Bitmap.Length); i += Bitmap.Length; Utils.IntToBytesSafepos(Area, bytes, i); i += 4; - bytes[i++] = Status; + Utils.ByteToBytes( Status, bytes, ref i); Utils.IntToBytesSafepos(SimWideMaxPrims, bytes, i); i += 4; Utils.IntToBytesSafepos(SimWideTotalPrims, bytes, i); i += 4; Utils.IntToBytesSafepos(MaxPrims, bytes, i); i += 4; @@ -80514,29 +81078,29 @@ public override void ToBytes(byte[] bytes, ref int i) Utils.IntToBytesSafepos(OtherCleanTime, bytes, i); i += 4; Utils.UIntToBytesSafepos(ParcelFlags, bytes, i); i += 4; Utils.IntToBytesSafepos(SalePrice, bytes, i); i += 4; - bytes[i++] = (byte)Name.Length; + Utils.ByteToBytes((byte)Name.Length, bytes, ref i); Buffer.BlockCopy(Name, 0, bytes, i, Name.Length); i += Name.Length; - bytes[i++] = (byte)Desc.Length; + Utils.ByteToBytes((byte)Desc.Length, bytes, ref i); Buffer.BlockCopy(Desc, 0, bytes, i, Desc.Length); i += Desc.Length; - bytes[i++] = (byte)MusicURL.Length; + Utils.ByteToBytes((byte)MusicURL.Length, bytes, ref i); Buffer.BlockCopy(MusicURL, 0, bytes, i, MusicURL.Length); i += MusicURL.Length; - bytes[i++] = (byte)MediaURL.Length; + Utils.ByteToBytes((byte)MediaURL.Length, bytes, ref i); Buffer.BlockCopy(MediaURL, 0, bytes, i, MediaURL.Length); i += MediaURL.Length; MediaID.ToBytes(bytes, i); i += 16; - bytes[i++] = MediaAutoScale; + Utils.ByteToBytes( MediaAutoScale, bytes, ref i); GroupID.ToBytes(bytes, i); i += 16; Utils.IntToBytesSafepos(PassPrice, bytes, i); i += 4; Utils.FloatToBytesSafepos(PassHours, bytes, i); i += 4; - bytes[i++] = Category; + Utils.ByteToBytes( Category, bytes, ref i); AuthBuyerID.ToBytes(bytes, i); i += 16; SnapshotID.ToBytes(bytes, i); i += 16; UserLocation.ToBytes(bytes, i); i += 12; UserLookAt.ToBytes(bytes, i); i += 12; - bytes[i++] = LandingType; - bytes[i++] = (byte)((RegionPushOverride) ? 1 : 0); - bytes[i++] = (byte)((RegionDenyAnonymous) ? 1 : 0); - bytes[i++] = (byte)((RegionDenyIdentified) ? 1 : 0); - bytes[i++] = (byte)((RegionDenyTransacted) ? 1 : 0); + Utils.ByteToBytes( LandingType, bytes, ref i); + Utils.ByteToBytes((byte)((RegionPushOverride) ? 1 : 0), bytes, ref i); + Utils.ByteToBytes((byte)((RegionDenyAnonymous) ? 1 : 0), bytes, ref i); + Utils.ByteToBytes((byte)((RegionDenyIdentified) ? 1 : 0), bytes, ref i); + Utils.ByteToBytes((byte)((RegionDenyTransacted) ? 1 : 0), bytes, ref i); } } @@ -80564,7 +81128,7 @@ public override void FromBytes(byte[] bytes, ref int i) { try { - RegionDenyAgeUnverified = (bytes[i++] != 0) ? (bool)true : (bool)false; + RegionDenyAgeUnverified = (Utils.BytesToByte(bytes, ref i) != 0); } catch (Exception) { @@ -80574,7 +81138,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = (byte)((RegionDenyAgeUnverified) ? 1 : 0); + Utils.ByteToBytes((byte)((RegionDenyAgeUnverified) ? 1 : 0), bytes, ref i); } } @@ -80602,7 +81166,7 @@ public override void FromBytes(byte[] bytes, ref int i) { try { - RegionAllowAccessOverride = (bytes[i++] != 0) ? (bool)true : (bool)false; + RegionAllowAccessOverride = (Utils.BytesToByte(bytes, ref i) != 0); } catch (Exception) { @@ -80612,7 +81176,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = (byte)((RegionAllowAccessOverride) ? 1 : 0); + Utils.ByteToBytes((byte)((RegionAllowAccessOverride) ? 1 : 0), bytes, ref i); } } @@ -80642,7 +81206,7 @@ public override void FromBytes(byte[] bytes, ref int i) try { ParcelEnvironmentVersion = Utils.BytesToIntSafepos(bytes, i); i +=4; - RegionAllowEnvironmentOverride = (bytes[i++] != 0) ? (bool)true : (bool)false; + RegionAllowEnvironmentOverride = (Utils.BytesToByte(bytes, ref i) != 0); } catch (Exception) { @@ -80653,7 +81217,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { Utils.IntToBytesSafepos(ParcelEnvironmentVersion, bytes, i); i += 4; - bytes[i++] = (byte)((RegionAllowEnvironmentOverride) ? 1 : 0); + Utils.ByteToBytes((byte)((RegionAllowEnvironmentOverride) ? 1 : 0), bytes, ref i); } } @@ -80683,6 +81247,7 @@ public ParcelPropertiesPacket() Header.Frequency = PacketFrequency.High; Header.ID = 23; Header.Reliable = true; + NeedValidateIDs = false; Header.Zerocoded = true; ParcelData = new ParcelDataBlock(); AgeVerificationBlock = new AgeVerificationBlockBlock(); @@ -80712,11 +81277,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ParcelPropertiesPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; ParcelData.FromBytes(bytes, ref i); @@ -80847,10 +81411,10 @@ public override void FromBytes(byte[] bytes, ref int i) AtAxis.FromBytes(bytes, i); i += 12; LeftAxis.FromBytes(bytes, i); i += 12; UpAxis.FromBytes(bytes, i); i += 12; - ChangedGrid = (bytes[i++] != 0) ? (bool)true : (bool)false; + ChangedGrid = (Utils.BytesToByte(bytes, ref i) != 0); Far = Utils.BytesToFloatSafepos(bytes, i); i += 4; Aspect = Utils.BytesToFloatSafepos(bytes, i); i += 4; - length = bytes[i++]; + length = Utils.BytesToByte(bytes, ref i); Throttles = new byte[length]; Buffer.BlockCopy(bytes, i, Throttles, 0, length); i += length; LocomotionState = Utils.BytesToUIntSafepos(bytes, i); i += 4; @@ -80858,11 +81422,11 @@ public override void FromBytes(byte[] bytes, ref int i) BodyRotation.FromBytes(bytes, i, true); i += 12; ControlFlags = Utils.BytesToUIntSafepos(bytes, i); i += 4; EnergyLevel = Utils.BytesToFloatSafepos(bytes, i); i += 4; - GodLevel = (byte)bytes[i++]; - AlwaysRun = (bytes[i++] != 0) ? (bool)true : (bool)false; + GodLevel = Utils.BytesToByte(bytes, ref i); + AlwaysRun = (Utils.BytesToByte(bytes, ref i) != 0); PreyAgent.FromBytes(bytes, i); i += 16; - AgentAccess = (byte)bytes[i++]; - length = (bytes[i++] + (bytes[i++] << 8)); + AgentAccess = Utils.BytesToByte(bytes, ref i); + length = Utils.BytesToUInt16(bytes, i); i+=2; AgentTextures = new byte[length]; Buffer.BlockCopy(bytes, i, AgentTextures, 0, length); i += length; ActiveGroupID.FromBytes(bytes, i); i += 16; @@ -80886,22 +81450,21 @@ public override void ToBytes(byte[] bytes, ref int i) AtAxis.ToBytes(bytes, i); i += 12; LeftAxis.ToBytes(bytes, i); i += 12; UpAxis.ToBytes(bytes, i); i += 12; - bytes[i++] = (byte)((ChangedGrid) ? 1 : 0); + Utils.ByteToBytes((byte)((ChangedGrid) ? 1 : 0), bytes, ref i); Utils.FloatToBytesSafepos(Far, bytes, i); i += 4; Utils.FloatToBytesSafepos(Aspect, bytes, i); i += 4; - bytes[i++] = (byte)Throttles.Length; + Utils.ByteToBytes((byte)Throttles.Length, bytes, ref i); Buffer.BlockCopy(Throttles, 0, bytes, i, Throttles.Length); i += Throttles.Length; Utils.UIntToBytesSafepos(LocomotionState, bytes, i); i += 4; HeadRotation.ToBytes(bytes, i); i += 12; BodyRotation.ToBytes(bytes, i); i += 12; Utils.UIntToBytesSafepos(ControlFlags, bytes, i); i += 4; Utils.FloatToBytesSafepos(EnergyLevel, bytes, i); i += 4; - bytes[i++] = GodLevel; - bytes[i++] = (byte)((AlwaysRun) ? 1 : 0); + Utils.ByteToBytes( GodLevel, bytes, ref i); + Utils.ByteToBytes((byte)((AlwaysRun) ? 1 : 0), bytes, ref i); PreyAgent.ToBytes(bytes, i); i += 16; - bytes[i++] = AgentAccess; - bytes[i++] = (byte)(AgentTextures.Length % 256); - bytes[i++] = (byte)((AgentTextures.Length >> 8) % 256); + Utils.ByteToBytes( AgentAccess, bytes, ref i); + Utils.UInt16ToBytes((ushort)AgentTextures.Length, bytes, i); i += 2; Buffer.BlockCopy(AgentTextures, 0, bytes, i, AgentTextures.Length); i += AgentTextures.Length; ActiveGroupID.ToBytes(bytes, i); i += 16; } @@ -80935,7 +81498,7 @@ public override void FromBytes(byte[] bytes, ref int i) { GroupID.FromBytes(bytes, i); i += 16; GroupPowers = Utils.BytesToUInt64Safepos(bytes, i); i += 8; - AcceptNotices = (bytes[i++] != 0) ? (bool)true : (bool)false; + AcceptNotices = (Utils.BytesToByte(bytes, ref i) != 0); } catch (Exception) { @@ -80947,7 +81510,7 @@ public override void ToBytes(byte[] bytes, ref int i) { GroupID.ToBytes(bytes, i); i += 16; Utils.UInt64ToBytesSafepos(GroupPowers, bytes, i); i += 8; - bytes[i++] = (byte)((AcceptNotices) ? 1 : 0); + Utils.ByteToBytes((byte)((AcceptNotices) ? 1 : 0), bytes, ref i); } } @@ -81057,7 +81620,7 @@ public override void FromBytes(byte[] bytes, ref int i) int length; try { - length = (bytes[i++] + (bytes[i++] << 8)); + length = Utils.BytesToUInt16(bytes, i); i+=2; NVPairs = new byte[length]; Buffer.BlockCopy(bytes, i, NVPairs, 0, length); i += length; } @@ -81069,8 +81632,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = (byte)(NVPairs.Length % 256); - bytes[i++] = (byte)((NVPairs.Length >> 8) % 256); + Utils.UInt16ToBytes((ushort)NVPairs.Length, bytes, i); i += 2; Buffer.BlockCopy(NVPairs, 0, bytes, i, NVPairs.Length); i += NVPairs.Length; } @@ -81099,7 +81661,7 @@ public override void FromBytes(byte[] bytes, ref int i) { try { - ParamValue = (byte)bytes[i++]; + ParamValue = Utils.BytesToByte(bytes, ref i); } catch (Exception) { @@ -81109,7 +81671,7 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = ParamValue; + Utils.ByteToBytes( ParamValue, bytes, ref i); } } @@ -81138,8 +81700,8 @@ public override void FromBytes(byte[] bytes, ref int i) { try { - AgentLegacyAccess = (byte)bytes[i++]; - AgentMaxAccess = (byte)bytes[i++]; + AgentLegacyAccess = Utils.BytesToByte(bytes, ref i); + AgentMaxAccess = Utils.BytesToByte(bytes, ref i); } catch (Exception) { @@ -81149,8 +81711,8 @@ public override void FromBytes(byte[] bytes, ref int i) public override void ToBytes(byte[] bytes, ref int i) { - bytes[i++] = AgentLegacyAccess; - bytes[i++] = AgentMaxAccess; + Utils.ByteToBytes( AgentLegacyAccess, bytes, ref i); + Utils.ByteToBytes( AgentMaxAccess, bytes, ref i); } } @@ -81225,6 +81787,8 @@ public override int Length public AgentAccessBlock[] AgentAccess; public AgentInfoBlock[] AgentInfo; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ChildAgentUpdatePacket() { HasVariableBlocks = true; @@ -81233,6 +81797,7 @@ public ChildAgentUpdatePacket() Header.Frequency = PacketFrequency.High; Header.ID = 25; Header.Reliable = true; + NeedValidateIDs = true; Header.Zerocoded = true; AgentData = new AgentDataBlock(); GroupData = null; @@ -81326,11 +81891,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ChildAgentUpdatePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -81422,19 +81986,19 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); AgentData.ToBytes(bytes, ref i); - bytes[i++] = (byte)GroupData.Length; + Utils.ByteToBytes((byte)GroupData.Length, bytes, ref i); for (int j = 0; j < GroupData.Length; j++) { GroupData[j].ToBytes(bytes, ref i); } - bytes[i++] = (byte)AnimationData.Length; + Utils.ByteToBytes((byte)AnimationData.Length, bytes, ref i); for (int j = 0; j < AnimationData.Length; j++) { AnimationData[j].ToBytes(bytes, ref i); } - bytes[i++] = (byte)GranterBlock.Length; + Utils.ByteToBytes((byte)GranterBlock.Length, bytes, ref i); for (int j = 0; j < GranterBlock.Length; j++) { GranterBlock[j].ToBytes(bytes, ref i); } - bytes[i++] = (byte)NVPairData.Length; + Utils.ByteToBytes((byte)NVPairData.Length, bytes, ref i); for (int j = 0; j < NVPairData.Length; j++) { NVPairData[j].ToBytes(bytes, ref i); } - bytes[i++] = (byte)VisualParam.Length; + Utils.ByteToBytes((byte)VisualParam.Length, bytes, ref i); for (int j = 0; j < VisualParam.Length; j++) { VisualParam[j].ToBytes(bytes, ref i); } - bytes[i++] = (byte)AgentAccess.Length; + Utils.ByteToBytes((byte)AgentAccess.Length, bytes, ref i); for (int j = 0; j < AgentAccess.Length; j++) { AgentAccess[j].ToBytes(bytes, ref i); } - bytes[i++] = (byte)AgentInfo.Length; + Utils.ByteToBytes((byte)AgentInfo.Length, bytes, ref i); for (int j = 0; j < AgentInfo.Length; j++) { AgentInfo[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -81921,6 +82485,8 @@ public override int Length } public AgentDataBlock AgentData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ChildAgentAlivePacket() { HasVariableBlocks = false; @@ -81929,6 +82495,7 @@ public ChildAgentAlivePacket() Header.Frequency = PacketFrequency.High; Header.ID = 26; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); } @@ -81951,11 +82518,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ChildAgentAlivePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -82057,7 +82623,7 @@ public override void FromBytes(byte[] bytes, ref int i) AtAxis.FromBytes(bytes, i); i += 12; LeftAxis.FromBytes(bytes, i); i += 12; UpAxis.FromBytes(bytes, i); i += 12; - ChangedGrid = (bytes[i++] != 0) ? (bool)true : (bool)false; + ChangedGrid = (Utils.BytesToByte(bytes, ref i) != 0); } catch (Exception) { @@ -82078,7 +82644,7 @@ public override void ToBytes(byte[] bytes, ref int i) AtAxis.ToBytes(bytes, i); i += 12; LeftAxis.ToBytes(bytes, i); i += 12; UpAxis.ToBytes(bytes, i); i += 12; - bytes[i++] = (byte)((ChangedGrid) ? 1 : 0); + Utils.ByteToBytes((byte)((ChangedGrid) ? 1 : 0), bytes, ref i); } } @@ -82094,6 +82660,8 @@ public override int Length } public AgentDataBlock AgentData; + public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); } + public ChildAgentPositionUpdatePacket() { HasVariableBlocks = false; @@ -82102,6 +82670,7 @@ public ChildAgentPositionUpdatePacket() Header.Frequency = PacketFrequency.High; Header.ID = 27; Header.Reliable = true; + NeedValidateIDs = true; AgentData = new AgentDataBlock(); } @@ -82124,11 +82693,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ChildAgentPositionUpdatePacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; AgentData.FromBytes(bytes, ref i); @@ -82260,6 +82828,7 @@ public SoundTriggerPacket() Header.Frequency = PacketFrequency.High; Header.ID = 29; Header.Reliable = true; + NeedValidateIDs = false; SoundData = new SoundDataBlock(); } @@ -82282,11 +82851,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public SoundTriggerPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; SoundData.FromBytes(bytes, ref i); @@ -82436,6 +83004,7 @@ public ObjectAnimationPacket() Header.Frequency = PacketFrequency.High; Header.ID = 30; Header.Reliable = true; + NeedValidateIDs = false; Sender = new SenderBlock(); AnimationList = null; } @@ -82468,11 +83037,10 @@ override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[ public ObjectAnimationPacket(Header head, byte[] bytes, ref int i) : this() { - int packetEnd = bytes.Length - 1; - FromBytes(head, bytes, ref i, ref packetEnd); + FromBytes(head, bytes, ref i); } - override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd) + override public void FromBytes(Header header, byte[] bytes, ref int i) { Header = header; Sender.FromBytes(bytes, ref i); @@ -82498,7 +83066,7 @@ public override byte[] ToBytes() int i = 0; Header.ToBytes(bytes, ref i); Sender.ToBytes(bytes, ref i); - bytes[i++] = (byte)AnimationList.Length; + Utils.ByteToBytes((byte)AnimationList.Length, bytes, ref i); for (int j = 0; j < AnimationList.Length; j++) { AnimationList[j].ToBytes(bytes, ref i); } if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } return bytes; @@ -82567,4 +83135,166 @@ public override byte[][] ToBytesMultiple() } } + /// + public sealed class GenericStreamingMessagePacket : Packet + { + /// + public sealed class MethodDataBlock : PacketBlock + { + public ushort Method; + + public override int Length + { + get + { + return 2; + } + } + + public MethodDataBlock() { } + public MethodDataBlock(byte[] bytes, ref int i) + { + FromBytes(bytes, ref i); + } + + public override void FromBytes(byte[] bytes, ref int i) + { + try + { + Method = Utils.BytesToUInt16(bytes, i); i+=2; + } + catch (Exception) + { + throw new MalformedDataException(); + } + } + + public override void ToBytes(byte[] bytes, ref int i) + { + Utils.UInt16ToBytes(Method, bytes, i); i += 2; + } + + } + + /// + public sealed class DataBlockBlock : PacketBlock + { + public byte[] Data; + + public override int Length + { + get + { + int length = 2; + if (Data != null) { length += Data.Length; } + return length; + } + } + + public DataBlockBlock() { } + public DataBlockBlock(byte[] bytes, ref int i) + { + FromBytes(bytes, ref i); + } + + public override void FromBytes(byte[] bytes, ref int i) + { + int length; + try + { + length = Utils.BytesToUInt16(bytes, i); i+=2; + Data = new byte[length]; + Buffer.BlockCopy(bytes, i, Data, 0, length); i += length; + } + catch (Exception) + { + throw new MalformedDataException(); + } + } + + public override void ToBytes(byte[] bytes, ref int i) + { + Utils.UInt16ToBytes((ushort)Data.Length, bytes, i); i += 2; + Buffer.BlockCopy(Data, 0, bytes, i, Data.Length); i += Data.Length; + } + + } + + public override int Length + { + get + { + int length = 7; + length += MethodData.Length; + length += DataBlock.Length; + return length; + } + } + public MethodDataBlock MethodData; + public DataBlockBlock DataBlock; + + public GenericStreamingMessagePacket() + { + HasVariableBlocks = false; + Type = PacketType.GenericStreamingMessage; + Header = new Header(); + Header.Frequency = PacketFrequency.High; + Header.ID =31; + Header.Reliable = true; + NeedValidateIDs = false; + MethodData = new MethodDataBlock(); + DataBlock = new DataBlockBlock(); + } + + public GenericStreamingMessagePacket(byte[] bytes, ref int i) : this() + { + int packetEnd = bytes.Length - 1; + FromBytes(bytes, ref i, ref packetEnd, null); + } + + override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[] zeroBuffer) + { + Header.FromBytes(bytes, ref i, ref packetEnd); + if (Header.Zerocoded && zeroBuffer != null) + { + packetEnd = Helpers.ZeroDecode(bytes, packetEnd + 1, zeroBuffer) - 1; + bytes = zeroBuffer; + } + MethodData.FromBytes(bytes, ref i); + DataBlock.FromBytes(bytes, ref i); + } + + public GenericStreamingMessagePacket(Header head, byte[] bytes, ref int i): this() + { + FromBytes(head, bytes, ref i); + } + + override public void FromBytes(Header header, byte[] bytes, ref int i) + { + Header = header; + MethodData.FromBytes(bytes, ref i); + DataBlock.FromBytes(bytes, ref i); + } + + public override byte[] ToBytes() + { + int length = 7; + length += MethodData.Length; + length += DataBlock.Length; + if (Header.AckList != null && Header.AckList.Length > 0) { length += Header.AckList.Length * 4 + 1; } + byte[] bytes = new byte[length]; + int i = 0; + Header.ToBytes(bytes, ref i); + MethodData.ToBytes(bytes, ref i); + DataBlock.ToBytes(bytes, ref i); + if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); } + return bytes; + } + + public override byte[][] ToBytesMultiple() + { + return new byte[][] { ToBytes() }; + } + } + } diff --git a/PrimMesher/CONTRIBUTORS.txt b/PrimMesher/CONTRIBUTORS.txt new file mode 100644 index 00000000..cd638b4b --- /dev/null +++ b/PrimMesher/CONTRIBUTORS.txt @@ -0,0 +1,9 @@ +Original primary developer of PrimMesher is Dahlia Trimble. https://github.com/dahliaT/PrimMesher + +Additional contributors (in no particular order): +Morgaine Dinova +Latif Kalifa (lkalif) + +Some portions of PrimMesher are from the following projects: +* OpenSimulator (original extrusion concept) +* LibOpenMetaverse (quaternion multiplication routine) diff --git a/OpenMetaverse.PrimMesher/ObjMesh.cs b/PrimMesher/ObjMesh.cs similarity index 71% rename from OpenMetaverse.PrimMesher/ObjMesh.cs rename to PrimMesher/ObjMesh.cs index 2a7a414e..799bd238 100644 --- a/OpenMetaverse.PrimMesher/ObjMesh.cs +++ b/PrimMesher/ObjMesh.cs @@ -25,52 +25,52 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ +using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text.RegularExpressions; +using OpenMetaverse; -namespace OpenMetaverse.PrimMesher +namespace PrimMesher { public class ObjMesh { - private readonly List coords = new List(); - private List facePolygons = new List(); - - private List faceVertices = new List(); + List coords = []; + List normals = []; + List uvs = []; public string meshName = string.Empty; - private readonly List normals = new List(); + public List> viewerVertices = []; + public List> viewerPolygons = []; + + List faceVertices = []; + List facePolygons = []; public int numPrimFaces; - private readonly List uvs = new List(); - public List> viewerPolygons = new List>(); - private Dictionary viewerVertexLookup = new Dictionary(); - public List> viewerVertices = new List>(); + Dictionary viewerVertexLookup = new(); public ObjMesh(string path) { ProcessStream(new StreamReader(path)); } - public ObjMesh(StreamReader sr) { ProcessStream(sr); } - private void ProcessStream(StreamReader s) { numPrimFaces = 0; while (!s.EndOfStream) { - var line = s.ReadLine().Trim(); - var tokens = Regex.Split(line, @"\s+"); + string line = s.ReadLine().Trim(); + string[] tokens = Regex.Split(line, @"\s+"); // Skip blank lines and comments - if (tokens.Length > 0 && tokens[0] != string.Empty && !tokens[0].StartsWith("#")) + if (tokens.Length > 0 && tokens[0] != String.Empty && !tokens[0].StartsWith("#")) ProcessTokens(tokens); } MakePrimFace(); @@ -78,7 +78,7 @@ private void ProcessStream(StreamReader s) public VertexIndexer GetVertexIndexer() { - var vi = new VertexIndexer(); + VertexIndexer vi = new VertexIndexer(); vi.numPrimFaces = numPrimFaces; vi.viewerPolygons = viewerPolygons; vi.viewerVertices = viewerVertices; @@ -86,7 +86,6 @@ public VertexIndexer GetVertexIndexer() return vi; } - private void ProcessTokens(string[] tokens) { switch (tokens[0].ToLower()) @@ -100,10 +99,10 @@ private void ProcessTokens(string[] tokens) break; case "vt": - { - uvs.Add(ParseUVCoord(tokens)); - break; - } + { + uvs.Add(ParseUVCoord(tokens)); + break; + } case "vn": normals.Add(ParseCoord(tokens)); @@ -120,39 +119,42 @@ private void ProcessTokens(string[] tokens) case "f": - var vertIndices = new int[3]; + int[] vertIndices = new int[3]; - for (var vertexIndex = 1; vertexIndex <= 3; vertexIndex++) + for (int vertexIndex = 1; vertexIndex <= 3; vertexIndex++) { - var indices = tokens[vertexIndex].Split('/'); + string[] indices = tokens[vertexIndex].Split('/'); - var positionIndex = int.Parse(indices[0], - CultureInfo.InvariantCulture) - 1; + int positionIndex = int.Parse(indices[0], + CultureInfo.InvariantCulture) - 1; - var texCoordIndex = -1; - var normalIndex = -1; + int texCoordIndex = -1; + int normalIndex = -1; if (indices.Length > 1) - if (int.TryParse(indices[1], NumberStyles.Integer, CultureInfo.InvariantCulture, - out texCoordIndex)) + { + + if (int.TryParse(indices[1], System.Globalization.NumberStyles.Integer, CultureInfo.InvariantCulture, out texCoordIndex)) texCoordIndex--; else texCoordIndex = -1; + } + if (indices.Length > 2) - if (int.TryParse(indices[1], NumberStyles.Integer, CultureInfo.InvariantCulture, - out normalIndex)) + { + if (int.TryParse(indices[1], System.Globalization.NumberStyles.Integer, CultureInfo.InvariantCulture, out normalIndex)) normalIndex--; else normalIndex = -1; + } - var hash = hashInts(positionIndex, texCoordIndex, normalIndex); + int hash = hashInts(positionIndex, texCoordIndex, normalIndex); - if (viewerVertexLookup.ContainsKey(hash)) - { - vertIndices[vertexIndex - 1] = viewerVertexLookup[hash]; - } + if (viewerVertexLookup.TryGetValue(hash, out int hv)) + vertIndices[vertexIndex - 1] = hv; else { - var vv = new ViewerVertex {v = coords[positionIndex]}; + ViewerVertex vv = new(); + vv.v = coords[positionIndex]; if (normalIndex > -1) vv.n = normals[normalIndex]; if (texCoordIndex > -1) @@ -170,10 +172,12 @@ private void ProcessTokens(string[] tokens) case "usemtl": break; + + default: + break; } } - private void MakePrimFace() { if (faceVertices.Count > 0 && facePolygons.Count > 0) @@ -197,9 +201,9 @@ private UVCoord ParseUVCoord(string[] tokens) float.Parse(tokens[1], CultureInfo.InvariantCulture)); } - private Coord ParseCoord(string[] tokens) + private Vector3 ParseCoord(string[] tokens) { - return new Coord( + return new Vector3( float.Parse(tokens[1], CultureInfo.InvariantCulture), float.Parse(tokens[2], CultureInfo.InvariantCulture), float.Parse(tokens[3], CultureInfo.InvariantCulture)); @@ -207,7 +211,7 @@ private Coord ParseCoord(string[] tokens) private int hashInts(int i1, int i2, int i3) { - return (i1 + " " + i2 + " " + i3).GetHashCode(); + return HashCode.Combine(i1, i2, i3); } } -} \ No newline at end of file +} diff --git a/PrimMesher/PrimMesher.cs b/PrimMesher/PrimMesher.cs new file mode 100644 index 00000000..098eaf01 --- /dev/null +++ b/PrimMesher/PrimMesher.cs @@ -0,0 +1,2114 @@ +/* + * Copyright (c) Contributors + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSimulator Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``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 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. + */ + +using OpenMetaverse; +using System; +using System.Collections.Generic; +using System.IO; +using System.Runtime.CompilerServices; + +namespace PrimMesher +{ + public struct UVCoord(float u, float v) + { + public float U = u; + public float V = v; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public UVCoord Flip() + { + U = 1.0f - U; + V = 1.0f - V; + return this; + } + } + + public struct Face + { + // vertices + public int v1; + public int v2; + public int v3; + + //normals + public int n1; + public int n2; + public int n3; + + // uvs + public int uv1; + public int uv2; + public int uv3; + + public Face(int v1, int v2, int v3) + { + this.v1 = v1; + this.v2 = v2; + this.v3 = v3; + + n1 = 0; + n2 = 0; + n3 = 0; + + uv1 = 0; + uv2 = 0; + uv3 = 0; + } + + public Face(int v1, int v2, int v3, int n1, int n2, int n3) + { + this.v1 = v1; + this.v2 = v2; + this.v3 = v3; + + this.n1 = n1; + this.n2 = n2; + this.n3 = n3; + + uv1 = 0; + uv2 = 0; + uv3 = 0; + } + + public Vector3 SurfaceNormal(List coordList) + { + Vector3 c1 = coordList[v1]; + Vector3 c2 = coordList[v2]; + Vector3 c3 = coordList[v3]; + + Vector3 edge1 = c2 - c1; + Vector3 edge2 = c3 - c1; + c1 = Vector3.Cross(edge1, edge2); + c1.Normalize(); + return c1; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void AddVerticesIndexesOffset(int o) + { + v1 += o; + v2 += o; + v3 += o; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void AddNormalsIndexesOffset(int o) + { + n1 += o; + n2 += o; + n3 += o; + } + } + + public struct ViewerFace + { + public int primFaceNumber; + + public Vector3 v1; + public Vector3 v2; + public Vector3 v3; + + public int coordIndex1; + public int coordIndex2; + public int coordIndex3; + + public Vector3 n1; + public Vector3 n2; + public Vector3 n3; + + public UVCoord uv1; + public UVCoord uv2; + public UVCoord uv3; + + public ViewerFace(int primFaceNumber) + { + this.primFaceNumber = primFaceNumber; + + v1 = new(); + v2 = new(); + v3 = new(); + + coordIndex1 = coordIndex2 = coordIndex3 = -1; // -1 means not assigned yet + + n1 = new(); + n2 = new(); + n3 = new(); + + uv1 = new(); + uv2 = new(); + uv3 = new(); + } + + public void Scale(float x, float y, float z) + { + v1.X *= x; + v1.Y *= y; + v1.Z *= z; + + v2.X *= x; + v2.Y *= y; + v2.Z *= z; + + v3.X *= x; + v3.Y *= y; + v3.Z *= z; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Scale(Vector3 scale) + { + v1 *= scale; + v2 *= scale; + v3 *= scale; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void AddPos(float x, float y, float z) + { + v1.X += x; + v2.X += x; + v3.X += x; + + v1.Y += y; + v2.Y += y; + v3.Y += y; + + v1.Z += z; + v2.Z += z; + v3.Z += z; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void AddPos(Vector3 v) + { + v1 += v; + v2 += v; + v3 += v; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void AddRot(Quaternion q) + { + v1 *= q; + v2 *= q; + v3 *= q; + + n1 *= q; + n2 *= q; + n3 *= q; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void CalcSurfaceNormal() + { + Vector3 edge1 = v2 - v1; + Vector3 edge2 = v3 - v1; + n1= Vector3.Cross(edge1, edge2); + n1.Normalize(); + + n2 = n3 = n1; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly bool IsValid() + { + return + (MathF.Abs(n1.X) + MathF.Abs(n1.Y) + MathF.Abs(n1.Z) > 0.2f) && + (MathF.Abs(n2.X) + MathF.Abs(n2.Y) + MathF.Abs(n2.Z) > 0.2f) && + (MathF.Abs(n3.X) + MathF.Abs(n3.Y) + MathF.Abs(n3.Z) > 0.2f) + ; + } + } + + internal struct Angle + { + internal float angle; + internal float X; + internal float Y; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal Angle(float _angle, float x, float y) + { + angle = _angle; + X = x; + Y = y; + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal Angle(float _angle) + { + angle = _angle; + X = MathF.Cos(angle); // cos + Y = MathF.Sin(angle); // sin + } + } + + internal class AngleList + { + private float iX, iY; // intersection point + + private static readonly Angle[] angles3 = + { + new(0.0f, 1.0f, 0.0f), + new(0.33333333333333333f, -0.5f, 0.86602540378443871f), + new(0.66666666666666667f, -0.5f, -0.86602540378443837f), + new(1.0f, 1.0f, 0.0f) + }; + + private static Vector3[] normals3 = + { + Vector3.Normalize(0.25f, 0.4330127019f, 0.0f), + Vector3.Normalize(-0.5f, 0.0f, 0.0f), + Vector3.Normalize(0.25f, -0.4330127019f, 0.0f), + Vector3.Normalize(0.25f, 0.4330127019f, 0.0f) + }; + + private static Angle[] angles4 = + { + new(0.0f, 1.0f, 0.0f), + new(0.25f, 0.0f, 1.0f), + new(0.5f, -1.0f, 0.0f), + new(0.75f, 0.0f, -1.0f), + new(1.0f, 1.0f, 0.0f) + }; + + private static readonly Vector3[] normals4 = + { + Vector3.Normalize(0.5f, 0.5f, 0.0f), + Vector3.Normalize(-0.5f, 0.5f, 0.0f), + Vector3.Normalize(-0.5f, -0.5f, 0.0f), + Vector3.Normalize(0.5f, -0.5f, 0.0f), + Vector3.Normalize(0.5f, 0.5f, 0.0f) + }; + + private static readonly Angle[] angles6 = + { + new(0.0f, 1.0f, 0.0f), + new(0.16666666666666667f, 0.5f, 0.8660254037844386f), + new(0.33333333333333333f, -0.5f, 0.86602540378443871f), + new(0.5f, -1.0f, 0.0f), + new(0.66666666666666667f, -0.5f, -0.86602540378443837f), + new(0.83333333333333326f, 0.5f, -0.86602540378443904f), + new(1.0f, 1.0f, 0.0f) + }; + + private static readonly Angle[] angles12 = + { + new(0.0f, 1.0f, 0.0f), + new(0.083333333333333329f, 0.86602540378443871f, 0.5f), + new(0.16666666666666667f, 0.5f, 0.8660254037844386f), + new(0.25f, 0.0f, 1.0f), + new(0.33333333333333333f, -0.5f, 0.86602540378443871f), + new(0.41666666666666663f, -0.86602540378443849f, 0.5f), + new(0.5f, -1.0f, 0.0f), + new(0.58333333333333326f, -0.86602540378443882f, -0.5f), + new(0.66666666666666667f, -0.5f, -0.86602540378443837f), + new(0.75f, 0.0f, -1.0f), + new(0.83333333333333326f, 0.5f, -0.86602540378443904f), + new(0.91666666666666663f, 0.86602540378443837f, -0.5f), + new(1.0f, 1.0f, 0.0f) + }; + + private static readonly Angle[] angles24 = + { + new(0.0f, 1.0f, 0.0f), + new(0.041666666666666664f, 0.96592582628906831f, 0.25881904510252074f), + new(0.083333333333333329f, 0.86602540378443871f, 0.5f), + new(0.125f, 0.70710678118654757f, 0.70710678118654746f), + new(0.16666666666666667f, 0.5f, 0.8660254037844386f), + new(0.20833333333333331f, 0.25881904510252096f, 0.9659258262890682f), + new(0.25f, 0.0f, 1.0f), + new(0.29166666666666663f, -0.25881904510252063f, 0.96592582628906831f), + new(0.33333333333333333f, -0.5f, 0.86602540378443871f), + new(0.375f, -0.70710678118654746f, 0.70710678118654757f), + new(0.41666666666666663f, -0.86602540378443849f, 0.5f), + new(0.45833333333333331f, -0.9659258262890682f, 0.25881904510252102f), + new(0.5f, -1.0f, 0.0f), + new(0.54166666666666663f, -0.96592582628906842f, -0.25881904510252035f), + new(0.58333333333333326f, -0.86602540378443882f, -0.5f), + new(0.62499999999999989f, -0.70710678118654791f, -0.70710678118654713f), + new(0.66666666666666667f, -0.5f, -0.86602540378443837f), + new(0.70833333333333326f, -0.25881904510252152f, -0.96592582628906809f), + new(0.75f, 0.0f, -1.0f), + new(0.79166666666666663f, 0.2588190451025203f, -0.96592582628906842f), + new(0.83333333333333326f, 0.5f, -0.86602540378443904f), + new(0.875f, 0.70710678118654735f, -0.70710678118654768f), + new(0.91666666666666663f, 0.86602540378443837f, -0.5f), + new(0.95833333333333326f, 0.96592582628906809f, -0.25881904510252157f), + new(1.0f, 1.0f, 0.0f) + }; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private Angle interpolatePoints(float newPoint, Angle p1, Angle p2) + { + float m = (newPoint - p1.angle) / (p2.angle - p1.angle); + return new(newPoint, p1.X + m * (p2.X - p1.X), p1.Y + m * (p2.Y - p1.Y)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void intersection(float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4) + { // ref: https://paulbourke.net/geometry/pointlineplane/ + float denom = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1); + if (denom != 0.0f) + { + float uaNumerator = (x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3); + float ua = uaNumerator / denom; + iX = x1 + ua * (x2 - x1); + iY = y1 + ua * (y2 - y1); + } + } + + // if p3 is origin: + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void intersection(float x1, float y1, float x2, float y2, float x4, float y4) + { // https://paulbourke.net/geometry/pointlineplane/ + float denom = y4 * (x2 - x1) - x4 * (y2 - y1); + if (denom != 0.0f) + { + float uaNumerator = x4 * y1 - y4 * x1; + float ua = uaNumerator / denom; + iX = x1 + ua * (x2 - x1); + iY = y1 + ua * (y2 - y1); + } + } + + internal List angles; + internal List normals; + + internal void makeAngles(int sides, float startAngle, float stopAngle) + { + angles = new List(); + normals = new List(); + + const float twoPi = MathF.PI * 2.0f; + const float twoPiInv = 1.0f / (float)twoPi; + + if (sides < 1) + throw new Exception("number of sides not greater than zero"); + if (stopAngle <= startAngle) + throw new Exception("stopAngle not greater than startAngle"); + + Angle[] sourceAngles = sides switch + { + 3 => angles3, + 4 => angles4, + 6 => angles6, + 12 => angles12, + 24 => angles24, + _ => null + }; + + if (sourceAngles != null) + { + startAngle *= twoPiInv; + stopAngle *= twoPiInv; + + int startAngleIndex = (int)(startAngle * sides); + int endAngleIndex = sourceAngles.Length - 1; + if (stopAngle < 1.0f) + endAngleIndex = (int)(stopAngle * sides) + 1; + if (endAngleIndex == startAngleIndex) + endAngleIndex++; + + for (int angleIndex = startAngleIndex; angleIndex <= endAngleIndex; angleIndex++) + { + angles.Add(sourceAngles[angleIndex]); + if (sides == 3) + normals.Add(normals3[angleIndex]); + else if (sides == 4) + normals.Add(normals4[angleIndex]); + } + + if (startAngle > 0.0f) + angles[0] = interpolatePoints(startAngle, angles[0], angles[1]); + + if (stopAngle < 1.0f) + { + int lastAngleIndex = angles.Count - 1; + angles[lastAngleIndex] = interpolatePoints(stopAngle, angles[lastAngleIndex - 1], angles[lastAngleIndex]); + } + } + else + { + double stepSize = twoPi / sides; + + int startStep = (int)(startAngle / stepSize); + double angle = (float)(stepSize * startStep); + int step = startStep; + double stopAngleTest = stopAngle; + if (stopAngle < twoPi) + { + stopAngleTest = stepSize * ((int)(stopAngle / stepSize) + 1); + if (stopAngleTest < stopAngle) + stopAngleTest += stepSize; + if (stopAngleTest > twoPi) + stopAngleTest = twoPi; + } + + while (angle <= stopAngleTest) + { + Angle newAngle = new((float)angle); + angles.Add(newAngle); + step += 1; + angle = stepSize * step; + } + + if (startAngle > angles[0].angle) + { + intersection(angles[0].X, angles[0].Y, angles[1].X, angles[1].Y, MathF.Cos(startAngle), MathF.Sin(startAngle)); + angles[0] = new(startAngle, iX, iY); + } + + int index = angles.Count - 1; + if (stopAngle < angles[index].angle) + { + int indxMinus1 = index - 1; + intersection(angles[indxMinus1].X, angles[indxMinus1].Y, angles[index].X, angles[index].Y, MathF.Cos(stopAngle), MathF.Sin(stopAngle)); + angles[index] = new(stopAngle, iX, iY);; + } + } + } + } + + /// + /// generates a profile for extrusion + /// + public class Profile + { + private const float twoPi = 2.0f * MathF.PI; + + public string errorMessage = null; + + public List coords; + public List faces; + public List vertexNormals; + public List us; + public List faceUVs; + public List faceNumbers; + + // use these for making individual meshes for each prim face + public List outerCoordIndices = null; + public List hollowCoordIndices = null; + public List cut1CoordIndices = null; + public List cut2CoordIndices = null; + + public Vector3 faceNormal = Vector3.UnitZ; + public Vector3 cutNormal1 = new(); + public Vector3 cutNormal2 = new(); + + public int numOuterVerts = 0; + public int numHollowVerts = 0; + + public int outerFaceNumber = -1; + public int hollowFaceNumber = -1; + + public bool calcVertexNormals = false; + public int bottomFaceNumber = 0; + public int numPrimFaces = 0; + + public Profile() + { + coords = []; + faces = []; + vertexNormals = []; + us = []; + faceUVs = []; + faceNumbers = []; + } + + public Profile(int sides, float profileStart, float profileEnd, + float hollow, int hollowSides, bool createFaces, bool calcVertexNormals) + { + this.calcVertexNormals = calcVertexNormals; + coords = []; + faces = []; + vertexNormals = []; + us = []; + faceUVs = []; + faceNumbers = []; + + List hollowCoords = []; + List hollowNormals = []; + List hollowUs = new List(); + + if (calcVertexNormals) + { + outerCoordIndices = []; + hollowCoordIndices = []; + cut1CoordIndices = []; + cut2CoordIndices = []; + } + + bool hasHollow = hollow > 0.0f; + bool hasProfileCut = profileStart > 0.0f || profileEnd < 1.0f; + + AngleList angles = new(); + AngleList hollowAngles = new(); + + float xScale; + float yScale; + if (sides == 4) // corners of a square are sqrt(2) from center + { + xScale = 0.707107f; + yScale = 0.707107f; + } + else + { + xScale = 0.5f; + yScale = 0.5f; + } + + float startAngle = profileStart * twoPi; + float stopAngle = profileEnd * twoPi; + + try { angles.makeAngles(sides, startAngle, stopAngle); } + catch (Exception ex) + { + errorMessage = "makeAngles failed: Exception: " + ex.ToString() + + "\nsides: " + sides.ToString() + " startAngle: " + startAngle.ToString() + " stopAngle: " + stopAngle.ToString(); + + return; + } + + numOuterVerts = angles.angles.Count; + + // flag to create as few triangles as possible for 3 or 4 side profile + bool simpleFace = sides < 5 && !hasHollow && !hasProfileCut; + + if (hasHollow) + { + if (sides == hollowSides) + hollowAngles = angles; + else + { + try { hollowAngles.makeAngles(hollowSides, startAngle, stopAngle); } + catch (Exception ex) + { + errorMessage = "makeAngles failed: Exception: " + ex.ToString() + + "\nsides: " + sides.ToString() + " startAngle: " + startAngle.ToString() + " stopAngle: " + stopAngle.ToString(); + + return; + } + } + numHollowVerts = hollowAngles.angles.Count; + } + else if (!simpleFace) + { + coords.Add(Vector3.Zero); + if (calcVertexNormals) + vertexNormals.Add(Vector3.UnitZ); + us.Add(0.0f); + } + + Angle angle; + Vector3 newVert = new(); + + if (hasHollow && hollowSides != sides) + { + for (int i = 0; i < hollowAngles.angles.Count; i++) + { + angle = hollowAngles.angles[i]; + newVert.X = hollow * xScale * angle.X; + newVert.Y = hollow * yScale * angle.Y; + hollowCoords.Add(newVert); + + if (calcVertexNormals) + { + if (hollowSides < 5) + hollowNormals.Add(-hollowAngles.normals[i]); + else + hollowNormals.Add(new Vector3(-angle.X, -angle.Y, 0.0f)); + + if (hollowSides == 4) + hollowUs.Add(angle.angle * hollow * 0.707107f); + else + hollowUs.Add(angle.angle * hollow); + } + } + } + + int index = 0; + for (int i = 0; i < angles.angles.Count; i++) + { + angle = angles.angles[i]; + newVert.X = angle.X * xScale; + newVert.Y = angle.Y * yScale; + coords.Add(newVert); + + if (calcVertexNormals) + { + outerCoordIndices.Add(coords.Count - 1); + + if (sides < 5) + { + vertexNormals.Add(angles.normals[i]); + us.Add(angle.angle); + } + else + { + vertexNormals.Add(new(angle.X, angle.Y, 0.0f)); + us.Add(angle.angle); + } + } + + if (hasHollow) + { + if (hollowSides == sides) + { + newVert.X *= hollow; + newVert.Y *= hollow; + hollowCoords.Add(newVert); + if (calcVertexNormals) + { + if (sides < 5) + { + hollowNormals.Add(-angles.normals[i]); + } + + else + hollowNormals.Add(new Vector3(-angle.X, -angle.Y, 0.0f)); + + hollowUs.Add(angle.angle * hollow); + } + } + } + else if (!simpleFace && createFaces && angle.angle > 0.0001f) + { + faces.Add(new( 0, index, index + 1)); + } + index += 1; + } + + if (hasHollow) + { + hollowCoords.Reverse(); + if (calcVertexNormals) + { + hollowNormals.Reverse(); + hollowUs.Reverse(); + } + + if (createFaces) + { + int numTotalVerts = numOuterVerts + numHollowVerts; + + if (numOuterVerts == numHollowVerts) + { + for (int coordIndex = 0; coordIndex < numOuterVerts - 1; coordIndex++) + { + int fromTotal = numTotalVerts - coordIndex - 1; + faces.Add(new( coordIndex, coordIndex + 1, fromTotal )); + faces.Add(new( coordIndex + 1, fromTotal - 1, fromTotal )); + } + } + else + { + if (numOuterVerts < numHollowVerts) + { + int j = 0; // j is the index for outer vertices + int maxJ = numOuterVerts - 1; + for (int i = 0; i < numHollowVerts; i++) // i is the index for inner vertices + { + int fromTotal = numTotalVerts - i - 1; + if (j < maxJ) + { + if (angles.angles[j + 1].angle - hollowAngles.angles[i].angle < hollowAngles.angles[i].angle - angles.angles[j].angle + 0.000001f) + { + faces.Add(new( fromTotal, j, j + 1)); + j++; + } + } + + faces.Add(new( j, fromTotal - 1, fromTotal)); + } + } + else // numHollowVerts < numOuterVerts + { + int j = 0; // j is the index for inner vertices + int maxJ = numHollowVerts - 1; + for (int i = 0; i < numOuterVerts; i++) + { + int fromTotal = numTotalVerts - j - 1; + if (j < maxJ) + { + if (hollowAngles.angles[j + 1].angle - angles.angles[i].angle < angles.angles[i].angle - hollowAngles.angles[j].angle + 0.000001f) + { + faces.Add(new( i, fromTotal - 1, fromTotal )); + j++; + fromTotal--; + } + } + + faces.Add(new( fromTotal, i, i + 1 )); + } + } + } + } + + if (calcVertexNormals) + { + foreach (Vector3 hc in hollowCoords) + { + hollowCoordIndices.Add(coords.Count); + coords.Add(hc); + } + vertexNormals.AddRange(hollowNormals); + us.AddRange(hollowUs); + } + else + coords.AddRange(hollowCoords); + } + + if (simpleFace && createFaces) + { + if (sides == 3) + faces.Add(new(0, 1, 2)); + else if (sides == 4) + { + faces.Add(new(0, 1, 2)); + faces.Add(new(0, 2, 3)); + } + } + + if (calcVertexNormals && hasProfileCut) + { + int lastOuterVertIndex = numOuterVerts - 1; + + if (hasHollow) + { + cut1CoordIndices.Add(0); + cut1CoordIndices.Add(coords.Count - 1); + + int lastOuterVertIndexPlus1 = lastOuterVertIndex + 1; + cut2CoordIndices.Add(lastOuterVertIndexPlus1); + cut2CoordIndices.Add(lastOuterVertIndex); + + cutNormal1.X = coords[0].Y - coords[^1].Y; + cutNormal1.Y = -(coords[0].X - coords[^1].X); + + cutNormal2.X = coords[lastOuterVertIndexPlus1].Y - coords[lastOuterVertIndex].Y; + cutNormal2.Y = -(coords[lastOuterVertIndexPlus1].X - coords[lastOuterVertIndex].X); + } + + else + { + cut1CoordIndices.Add(0); + cut1CoordIndices.Add(1); + + cut2CoordIndices.Add(lastOuterVertIndex); + cut2CoordIndices.Add(0); + + cutNormal1.X = vertexNormals[1].Y; + cutNormal1.Y = -vertexNormals[1].X; + + cutNormal2.X = -vertexNormals[^2].Y; + cutNormal2.Y = vertexNormals[^2].X; + } + cutNormal1.Normalize(); + cutNormal2.Normalize(); + } + + MakeFaceUVs(); + + if (calcVertexNormals) + { // calculate prim face numbers + + // face number order is top, outer, hollow, bottom, start cut, end cut + // I know it's ugly but so is the whole concept of prim face numbers + + int faceNum = 1; // start with outer faces + outerFaceNumber = faceNum; + + if (hasProfileCut && !hasHollow) + faceNumbers.Add(-1); + + if(sides < 5) + { + for (int i = 0; i < numOuterVerts - 1; i++) + faceNumbers.Add(i <= sides ? faceNum++ : faceNum); + } + else + { + for (int i = 0; i < numOuterVerts - 1; i++) + faceNumbers.Add(faceNum); + } + + faceNumbers.Add(hasProfileCut ? -1 : faceNum++); + + if(hasHollow || hasProfileCut) + { + if (sides > 4) + faceNum++; + + if (sides < 5 && numOuterVerts < sides) + faceNum++; + } + + if (hasHollow) + { + for (int i = 0; i < numHollowVerts; i++) + faceNumbers.Add(faceNum); + + hollowFaceNumber = faceNum++; + } + + bottomFaceNumber = faceNum++; + + if (hasHollow && hasProfileCut) + faceNumbers.Add(faceNum++); + + for (int i = 0; i < faceNumbers.Count; i++) + if (faceNumbers[i] == -1) + faceNumbers[i] = faceNum++; + + numPrimFaces = faceNum; + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void MakeFaceUVs() + { + faceUVs = new(coords.Count); + foreach (Vector3 c in coords) + faceUVs.Add(new UVCoord(0.5f - c.X, 0.5f + c.Y)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Profile Copy() + { + return Copy(true); + } + + public Profile Copy(bool needFaces) + { + Profile copy = new(); + + copy.coords.AddRange(coords); + copy.faceUVs.AddRange(faceUVs); + + copy.calcVertexNormals = calcVertexNormals; + + if (needFaces) + copy.faces.AddRange(faces); + + if (calcVertexNormals) + { + copy.vertexNormals.AddRange(vertexNormals); + copy.faceNormal = faceNormal; + copy.cutNormal1 = cutNormal1; + copy.cutNormal2 = cutNormal2; + copy.us.AddRange(us); + copy.faceNumbers.AddRange(faceNumbers); + + copy.cut1CoordIndices = new(cut1CoordIndices); + copy.cut2CoordIndices = new(cut2CoordIndices); + copy.hollowCoordIndices = new(hollowCoordIndices); + copy.outerCoordIndices = new(outerCoordIndices); + } + copy.numOuterVerts = numOuterVerts; + copy.numHollowVerts = numHollowVerts; + + return copy; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void AddPos(Vector3 v) + { + for (int i = 0; i < coords.Count; i++) + coords[i] += v; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void AddPos(float x, float y, float z) + { + Vector3 v = new(x, y, z); + AddPos(v); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void AddRot(Quaternion q) + { + if(q.IsIdentity()) return; + + for (int i = 0; i < coords.Count; i++) + coords[i] *= q; + + if (calcVertexNormals) + { + for (int i = 0; i < vertexNormals.Count; i++) + vertexNormals[i] *= q; + + faceNormal *= q; + cutNormal1 *= q; + cutNormal2 *= q; + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Scale(float x, float y) + { + Vector3 vert; + for (int i = 0; i < coords.Count; i++) + { + vert = coords[i]; + vert.X *= x; + vert.Y *= y; + coords[i] = vert; + } + } + + /// + /// Changes order of the vertex indices and negates the center vertex normal. Does not alter vertex normals of radial vertices + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void FlipNormals() + { + Face tmpFace; + int tmp; + + for (int i = 0; i < faces.Count; i++) + { + tmpFace = faces[i]; + tmp = tmpFace.v3; + tmpFace.v3 = tmpFace.v1; + tmpFace.v1 = tmp; + faces[i] = tmpFace; + } + + if (calcVertexNormals) + { + if (vertexNormals.Count > 0) + { + Vector3 n = vertexNormals[^1]; + n.Z = -n.Z; + vertexNormals[^1] = n; + } + } + + faceNormal = -faceNormal; + + for (int i = 0; i < faceUVs.Count; i++) + { + UVCoord uv = faceUVs[i]; + uv.V = 1.0f - uv.V; + faceUVs[i] = uv; + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void AddValue2FaceVertexIndices(int num) + { + for (int i = 0; i < faces.Count; i++) + { + Face face = faces[i]; + face.AddVerticesIndexesOffset(num); + faces[i] = face; + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void AddValue2FaceNormalIndices(int num) + { + for (int i = 0; i < faces.Count; i++) + { + Face face = faces[i]; + faces[i].AddNormalsIndexesOffset(num); + faces[i] = face; + } + } + + public void DumpRaw(string path, string name, string title) + { + if (path == null) + return; + string fileName = name + "_" + title + ".raw"; + string completePath = System.IO.Path.Combine(path, fileName); + StreamWriter sw = new(completePath); + + for (int i = 0; i < faces.Count; i++) + sw.WriteLine($"{coords[faces[i].v1]} {coords[faces[i].v2]} {coords[faces[i].v3]}"); + + sw.Close(); + } + } + + public struct PathNode + { + public Vector3 position; + public Quaternion rotation; + public float xScale; + public float yScale; + public float percentOfPath; + } + + public enum PathType { Linear = 0, Circular = 1, Flexible = 2 } + + public class Path + { + public List pathNodes = []; + + public float twistBegin = 0.0f; + public float twistEnd = 0.0f; + public float topShearX = 0.0f; + public float topShearY = 0.0f; + public float pathCutBegin = 0.0f; + public float pathCutEnd = 1.0f; + public float dimpleBegin = 0.0f; + public float dimpleEnd = 1.0f; + public float skew = 0.0f; + public float holeSizeX = 1.0f; // called pathScaleX in pbs + public float holeSizeY = 0.25f; + public float taperX = 0.0f; + public float taperY = 0.0f; + public float radius = 0.0f; + public float revolutions = 1.0f; + public int stepsPerRevolution = 24; + + private const float twoPi = 2.0f * MathF.PI; + + public void Create(PathType pathType, int steps) + { + if(taperX < -0.999f) + taperX = -0.999f; + else if(taperX > 0.999f) + taperX = 0.999f; + + if(taperY < -0.999f) + taperY = -0.999f; + else if(taperY > 0.999f) + taperY = 0.999f; + + if (pathType == PathType.Linear || pathType == PathType.Flexible) + { + int step = 0; + + float length = pathCutEnd - pathCutBegin; + float twistTotal = twistEnd - twistBegin; + float twistTotalAbs = MathF.Abs(twistTotal); + if (twistTotalAbs > 0.01f) + steps += (int)(twistTotalAbs * 3.66f); // dahlia's magic number + + float start = -0.5f; + float stepSize = length / (float)steps; + float percentOfPathMultiplier = stepSize * 0.999999f; + float xOffset = topShearX * pathCutBegin; + float yOffset = topShearY * pathCutBegin; + float zOffset = start; + float xOffsetStepIncrement = topShearX * length / steps; + float yOffsetStepIncrement = topShearY * length / steps; + + float percentOfPath = pathCutBegin; + zOffset += percentOfPath; + + // sanity checks + + while (true) + { + PathNode newNode = new(); + + if (taperX == 0.0f) + newNode.xScale = 1.0f; + else if (taperX > 0.0f) + newNode.xScale = 1.0f - percentOfPath * taperX; + else + newNode.xScale = 1.0f + (1.0f - percentOfPath) * taperX; + + if (taperY == 0.0f) + newNode.yScale = 1.0f; + else if (taperY > 0.0f) + newNode.yScale = 1.0f - percentOfPath * taperY; + else + newNode.yScale = 1.0f + (1.0f - percentOfPath) * taperY; + + float twist = twistBegin + twistTotal * percentOfPath; + + newNode.rotation = twist == 0f ? Quaternion.Identity : + new Quaternion(Quaternion.MainAxis.Z, twist); + newNode.position = new Vector3(xOffset, yOffset, zOffset); + newNode.percentOfPath = percentOfPath; + + pathNodes.Add(newNode); + + if (step >= steps) + break; + + percentOfPath += percentOfPathMultiplier; + if (percentOfPath > pathCutEnd) + break; + + step++; + xOffset += xOffsetStepIncrement; + yOffset += yOffsetStepIncrement; + zOffset += stepSize; + } + } // end of linear path code + + else // pathType == Circular + { + float twistTotal = twistEnd - twistBegin; + + // if the profile has a lot of twist, add more layers otherwise the layers may overlap + // and the resulting mesh may be quite inaccurate. This method is arbitrary and doesn't + // accurately match the viewer + /* + float twistTotalAbs = MathF.Abs(twistTotal); + if (twistTotalAbs > 0.01f) + { + if (twistTotalAbs > MathF.PI * 1.5f) + steps *= 2; + if (twistTotalAbs > MathF.PI * 3.0f) + steps *= 2; + } + */ + + float yPathScale = holeSizeY * 0.5f; + float pathLength = pathCutEnd - pathCutBegin; + float totalSkew = skew * 2.0f * pathLength; + float skewStart = pathCutBegin * 2.0f * skew - skew; + float xOffsetTopShearXFactor = topShearX * (0.25f + 0.5f * (0.5f - holeSizeY)); + float yShearCompensation = 1.0f + MathF.Abs(topShearY) * 0.25f; + + // It's not quite clear what pushY (Y top shear) does, but subtracting it from the start and end + // angles appears to approximate it's effects on path cut. Likewise, adding it to the angle used + // to calculate the sine for generating the path radius appears to approximate it's effects there + // too, but there are some subtle differences in the radius which are noticeable as the prim size + // increases and it may affect megaprims quite a bit. The effect of the Y top shear parameter on + // the meshes generated with this technique appear nearly identical in shape to the same prims when + // displayed by the viewer. + + float startAngle = (twoPi * pathCutBegin * revolutions) - topShearY * 0.9f; + float endAngle = (twoPi * pathCutEnd * revolutions) - topShearY * 0.9f; + float stepSize = twoPi / stepsPerRevolution; + + float angle = startAngle; + + while (true) // loop through the length of the path and add the layers + { + PathNode newNode = new(); + + float xProfileScale = (1.0f - MathF.Abs(skew)) * holeSizeX; + float yProfileScale = holeSizeY; + + float percentOfPath = angle / (twoPi * revolutions); + float percentOfAngles = (angle - startAngle) / (endAngle - startAngle); + + if (taperX > 0.01f) + xProfileScale *= 1.0f - percentOfPath * taperX; + else if (taperX < -0.01f) + xProfileScale *= 1.0f + (1.0f - percentOfPath) * taperX; + + if (taperY > 0.01f) + yProfileScale *= 1.0f - percentOfPath * taperY; + else if (taperY < -0.01f) + yProfileScale *= 1.0f + (1.0f - percentOfPath) * taperY; + + newNode.xScale = xProfileScale; + newNode.yScale = yProfileScale; + + float radiusScale; + if (radius > 0.001f) + radiusScale = 1.0f - radius * percentOfPath; + else if (radius < 0.001f) + radiusScale = 1.0f + radius * (1.0f - percentOfPath); + else + radiusScale = 1.0f; + + float twist = twistBegin + twistTotal * percentOfPath; + + float xOffset = 0.5f * (skewStart + totalSkew * percentOfAngles); + xOffset += MathF.Sin(angle) * xOffsetTopShearXFactor; + + float yOffset = yShearCompensation * MathF.Cos(angle) * (0.5f - yPathScale) * radiusScale; + + float zOffset = MathF.Sin(angle + topShearY) * (0.5f - yPathScale) * radiusScale; + + newNode.position = new(xOffset, yOffset, zOffset); + + // now orient the rotation of the profile layer relative to it's position on the path + // adding taperY to the angle used to generate the quat appears to approximate the viewer + + newNode.rotation = angle + topShearY == 0f ? Quaternion.Identity : + new Quaternion(Quaternion.MainAxis.X, angle + topShearY); + + // next apply twist rotation to the profile layer + if (twistTotal != 0.0f || twistBegin != 0.0f) + newNode.rotation *= new Quaternion(Quaternion.MainAxis.Z, twist); + + newNode.percentOfPath = percentOfPath; + + pathNodes.Add(newNode); + + // calculate terms for next iteration + // calculate the angle for the next iteration of the loop + + if (angle >= endAngle - 0.01) + break; + + angle += stepSize; + if (angle > endAngle) + angle = endAngle; + } + } + } + } + + public class PrimMesh + { + public string errorMessage = ""; + private const float twoPi = 2.0f * MathF.PI; + private const float DegToRad = twoPi / 360f; + + public List coords; + public List normals; + public List faces; + + public List viewerFaces; + + private readonly int sides = 4; + private readonly int hollowSides = 4; + private readonly float profileStart = 0.0f; + private readonly float profileEnd = 1.0f; + private readonly float hollow = 0.0f; + public int twistBegin = 0; + public int twistEnd = 0; + public float topShearX = 0.0f; + public float topShearY = 0.0f; + public float pathCutBegin = 0.0f; + public float pathCutEnd = 1.0f; + public float dimpleBegin = 0.0f; + public float dimpleEnd = 1.0f; + public float skew = 0.0f; + public float holeSizeX = 1.0f; // called pathScaleX in pbs + public float holeSizeY = 0.25f; + public float taperX = 0.0f; + public float taperY = 0.0f; + public float radius = 0.0f; + public float revolutions = 1.0f; + public int stepsPerRevolution = 24; + + private int profileOuterFaceNumber = -1; + private int profileHollowFaceNumber = -1; + + private bool hasProfileCut = false; + private bool hasHollow = false; + public bool calcVertexNormals = false; + private bool normalsProcessed = false; + public bool viewerMode = false; + public bool sphereMode = false; + + public int numPrimFaces = 0; + + /// + /// Human readable string representation of the parameters used to create a mesh. + /// + /// + public string ParamsToDisplayString() + { + string s = ""; + s += "sides..................: " + sides.ToString(); + s += "\nhollowSides..........: " + hollowSides.ToString(); + s += "\nprofileStart.........: " + profileStart.ToString(); + s += "\nprofileEnd...........: " + profileEnd.ToString(); + s += "\nhollow...............: " + hollow.ToString(); + s += "\ntwistBegin...........: " + twistBegin.ToString(); + s += "\ntwistEnd.............: " + twistEnd.ToString(); + s += "\ntopShearX............: " + topShearX.ToString(); + s += "\ntopShearY............: " + topShearY.ToString(); + s += "\npathCutBegin.........: " + pathCutBegin.ToString(); + s += "\npathCutEnd...........: " + pathCutEnd.ToString(); + s += "\ndimpleBegin..........: " + dimpleBegin.ToString(); + s += "\ndimpleEnd............: " + dimpleEnd.ToString(); + s += "\nskew.................: " + skew.ToString(); + s += "\nholeSizeX............: " + holeSizeX.ToString(); + s += "\nholeSizeY............: " + holeSizeY.ToString(); + s += "\ntaperX...............: " + taperX.ToString(); + s += "\ntaperY...............: " + taperY.ToString(); + s += "\nradius...............: " + radius.ToString(); + s += "\nrevolutions..........: " + revolutions.ToString(); + s += "\nstepsPerRevolution...: " + stepsPerRevolution.ToString(); + s += "\nsphereMode...........: " + sphereMode.ToString(); + s += "\nhasProfileCut........: " + hasProfileCut.ToString(); + s += "\nhasHollow............: " + hasHollow.ToString(); + s += "\nviewerMode...........: " + viewerMode.ToString(); + + return s; + } + + public int ProfileOuterFaceNumber + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get { return profileOuterFaceNumber; } + } + + public int ProfileHollowFaceNumber + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get { return profileHollowFaceNumber; } + } + + public bool HasProfileCut + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get { return hasProfileCut; } + } + + public bool HasHollow + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get { return hasHollow; } + } + + + /// + /// Constructs a PrimMesh object and creates the profile for extrusion. + /// + /// + /// + /// + /// + /// + public PrimMesh(int _sides, float _profileStart, float _profileEnd, float _hollow, int _hollowSides) + { + coords = []; + faces = []; + + sides = _sides < 3 ? 3 : _sides; + hollowSides = _hollowSides < 3 ? 3 : _hollowSides; + profileStart = _profileStart; + profileEnd = _profileEnd; + hollow = _hollow; + + if(hollow < 0f) + hollow = 0f; + else if(hollow > 0.99f) + hollow = 0.99f; + + if(profileEnd < 0.02f) + profileEnd = 0.02f; + else if( profileEnd > 1f) + profileEnd = 1f; + + if (profileStart < 0.0f) + profileStart = 0.0f; + else if (profileStart >= profileEnd) + profileStart = profileEnd - 0.02f; + } + + /// + /// Extrudes a profile along a path. + /// + public void Extrude(PathType pathType) + { + + coords = []; + faces = []; + + if (viewerMode) + { + viewerFaces = []; + calcVertexNormals = true; + } + + if (calcVertexNormals) + normals = []; + + normalsProcessed = false; + + int steps = 1; + float length = pathCutEnd - pathCutBegin; + + if (viewerMode && sides == 3) + { + // prisms don't taper well so add some vertical resolution + // other prims may benefit from this but just do prisms for now + if (MathF.Abs(taperX) > 0.01f || MathF.Abs(taperY) > 0.01f) + steps = (int)(steps * 4.5f * length); + } + + if (sphereMode) + hasProfileCut = profileEnd - profileStart < 0.4999f; + else + hasProfileCut = profileEnd - profileStart < 0.9999f; + + float hollow = this.hollow; + hasHollow = hollow > 0.001f; + + float twistBegin = this.twistBegin * DegToRad; + float twistEnd = this.twistEnd * DegToRad; + float twistTotal = twistEnd - twistBegin; + float twistTotalAbs = MathF.Abs(twistTotal); + if (twistTotalAbs > 0.01f) + steps += (int)(twistTotalAbs * 3.66f); // dahlia's magic number + + bool needEndFaces = + pathType != PathType.Circular || + pathCutBegin > float.Epsilon || pathCutEnd < 1.0f - float.Epsilon || + taperX > 0.01f || taperY > 0.01f || + MathF.Abs(skew) > 0.01f || + MathF.Abs(twistTotal) > 0.001f || + MathF.Abs(radius) > 0.0005f; + + // sanity checks + float initialProfileRot = 0.0f; + + if (pathType == PathType.Circular) + { + if (sides == 3) + { + initialProfileRot = MathF.PI; + if (hollowSides == 4) + { + if (hollow > 0.7f) + hollow = 0.7f; + hollow *= 0.707f; + } + else hollow *= 0.5f; + } + else if (sides == 4) + { + initialProfileRot = 0.25f * MathF.PI; + if (hollowSides != 4) + hollow *= 0.707f; + } + else if (sides > 4) + { + initialProfileRot = MathF.PI; + if (hollowSides == 4) + { + if (hollow > 0.7f) + hollow = 0.7f; + hollow /= 0.7f; + } + } + } + else + { + if (sides == 3) + { + if (hollowSides == 4) + { + if (hollow > 0.7f) + hollow = 0.7f; + hollow *= 0.707f; + } + else hollow *= 0.5f; + } + else if (sides == 4) + { + initialProfileRot = 1.25f * MathF.PI; + if (hollowSides != 4) + hollow *= 0.707f; + } + else if (sides > 4 && hollowSides == 4) + hollow *= 1.414f; + } + + Profile profile = new(sides, profileStart, profileEnd, hollow, hollowSides, true, calcVertexNormals); + errorMessage = profile.errorMessage; + + numPrimFaces = profile.numPrimFaces; + + int cut1FaceNumber; + if(needEndFaces) + { + cut1FaceNumber = profile.bottomFaceNumber + 1; + profileOuterFaceNumber = profile.outerFaceNumber; + } + else + { + cut1FaceNumber = profile.bottomFaceNumber - 1; + profileOuterFaceNumber = profile.outerFaceNumber - 1; + } + int cut2FaceNumber = cut1FaceNumber + 1; + + if (hasHollow) + { + profileHollowFaceNumber = needEndFaces ? profile.hollowFaceNumber : profile.hollowFaceNumber - 1; + } + + int cut1Vert; + int cut2Vert; + if (hasProfileCut) + { + cut1Vert = hasHollow ? profile.coords.Count - 1 : 0; + cut2Vert = hasHollow ? profile.numOuterVerts - 1 : profile.numOuterVerts; + } + else + { + cut1Vert = -1; + cut2Vert = -1; + } + + if (initialProfileRot != 0.0f) + { + profile.AddRot(new Quaternion(Quaternion.MainAxis.Z, initialProfileRot)); + if (viewerMode) + profile.MakeFaceUVs(); + } + + Vector3 lastCutNormal1 = new(); + Vector3 lastCutNormal2 = new(); + float lastV = 0.0f; + float thisV; + + Path path = new() + { + twistBegin = twistBegin, + twistEnd = twistEnd, + topShearX = topShearX, + topShearY = topShearY, + pathCutBegin = pathCutBegin, + pathCutEnd = pathCutEnd, + dimpleBegin = dimpleBegin, + dimpleEnd = dimpleEnd, + skew = skew, + holeSizeX = holeSizeX, + holeSizeY = holeSizeY, + taperX = taperX, + taperY = taperY, + radius = radius, + revolutions = revolutions, + stepsPerRevolution = stepsPerRevolution + }; + + path.Create(pathType, steps); + + for (int nodeIndex = 0; nodeIndex < path.pathNodes.Count; nodeIndex++) + { + PathNode node = path.pathNodes[nodeIndex]; + Profile newLayer = profile.Copy(); + newLayer.Scale(node.xScale, node.yScale); + + newLayer.AddRot(node.rotation); + newLayer.AddPos(node.position); + + if (needEndFaces && nodeIndex == 0) + { + newLayer.FlipNormals(); + + // add the bottom faces to the viewerFaces list + if (viewerMode) + { + Vector3 faceNormal = newLayer.faceNormal; + ViewerFace newViewerFace = new(profile.bottomFaceNumber); + List faces = newLayer.faces; + + for (int i = 0; i < faces.Count; i++) + { + Face face = faces[i]; + newViewerFace.v1 = newLayer.coords[face.v1]; + newViewerFace.v2 = newLayer.coords[face.v2]; + newViewerFace.v3 = newLayer.coords[face.v3]; + + newViewerFace.coordIndex1 = face.v1; + newViewerFace.coordIndex2 = face.v2; + newViewerFace.coordIndex3 = face.v3; + + newViewerFace.n1 = faceNormal; + newViewerFace.n2 = faceNormal; + newViewerFace.n3 = faceNormal; + + newViewerFace.uv1 = newLayer.faceUVs[face.v1]; + newViewerFace.uv2 = newLayer.faceUVs[face.v2]; + newViewerFace.uv3 = newLayer.faceUVs[face.v3]; + + if (pathType == PathType.Linear) + { + newViewerFace.uv1.Flip(); + newViewerFace.uv2.Flip(); + newViewerFace.uv3.Flip(); + } + + viewerFaces.Add(newViewerFace); + } + } + } // if (nodeIndex == 0) + + // append this layer + int coordsLen = coords.Count; + if(coordsLen > 0) + newLayer.AddValue2FaceVertexIndices(coordsLen); + coords.AddRange(newLayer.coords); + + if (calcVertexNormals) + { + if(normals.Count > 0) + newLayer.AddValue2FaceNormalIndices(normals.Count); + normals.AddRange(newLayer.vertexNormals); + } + + if (needEndFaces) + { + if (nodeIndex == 0 || nodeIndex == path.pathNodes.Count - 1) + faces.AddRange(newLayer.faces); + } + + if(nodeIndex == 0) + { + lastCutNormal1 = newLayer.cutNormal1; + lastCutNormal2 = newLayer.cutNormal2; + lastV = 1.0f - node.percentOfPath; + continue; + } + // fill faces between layers + + int numVerts = newLayer.coords.Count; + Face newFace1 = new(); + Face newFace2 = new(); + + thisV = 1.0f - node.percentOfPath; + + int startVert = coordsLen + 1; + int endVert = coords.Count; + + if (sides < 5 || hasProfileCut || hasHollow) + startVert--; + + for (int i = startVert; i < endVert; i++) + { + int iNext = i == endVert - 1 ? startVert : i + 1; + + newFace1.v1 = i; + newFace1.v2 = i - numVerts; + newFace1.v3 = iNext; + + newFace1.n1 = newFace1.v1; + newFace1.n2 = newFace1.v2; + newFace1.n3 = newFace1.v3; + faces.Add(newFace1); + + newFace2.v1 = iNext; + newFace2.v2 = i - numVerts; + newFace2.v3 = iNext - numVerts; + + newFace2.n1 = newFace2.v1; + newFace2.n2 = newFace2.v2; + newFace2.n3 = newFace2.v3; + faces.Add(newFace2); + + if (viewerMode) + { + // add the side faces to the list of viewerFaces here + int whichVert = i - startVert; + + int primFaceNum = profile.faceNumbers[whichVert]; + if (!needEndFaces) + primFaceNum -= 1; + + ViewerFace newViewerFace1 = new(primFaceNum); + ViewerFace newViewerFace2 = new(primFaceNum); + + int uIndex = whichVert; + if (!hasHollow && sides > 4 && uIndex < newLayer.us.Count - 1) + { + uIndex++; + } + + float u1 = newLayer.us[uIndex]; + float u2 = 1.0f; + if (uIndex < newLayer.us.Count - 1) + u2 = newLayer.us[uIndex + 1]; + + if (whichVert == cut1Vert || whichVert == cut2Vert) + { + u1 = 0.0f; + u2 = 1.0f; + } + else if (sides < 5) + { + if (whichVert < profile.numOuterVerts) + { // boxes and prisms have one texture face per side of the prim, so the U values have to be scaled + // to reflect the entire texture width + u1 *= sides; + u2 *= sides; + u2 -= (int)u1; + u1 -= (int)u1; + if (u2 < 0.1f) + u2 = 1.0f; + } + } + + if (sphereMode) + { + if (whichVert != cut1Vert && whichVert != cut2Vert) + { + u1 = u1 * 2.0f - 1.0f; + u2 = u2 * 2.0f - 1.0f; + + if (whichVert >= newLayer.numOuterVerts) + { + u1 -= hollow; + u2 -= hollow; + } + } + } + + newViewerFace1.uv1.U = u1; + newViewerFace1.uv2.U = u1; + newViewerFace1.uv3.U = u2; + + newViewerFace1.uv1.V = thisV; + newViewerFace1.uv2.V = lastV; + newViewerFace1.uv3.V = thisV; + + newViewerFace2.uv1.U = u2; + newViewerFace2.uv2.U = u1; + newViewerFace2.uv3.U = u2; + + newViewerFace2.uv1.V = thisV; + newViewerFace2.uv2.V = lastV; + newViewerFace2.uv3.V = lastV; + + newViewerFace1.v1 = coords[newFace1.v1]; + newViewerFace1.v2 = coords[newFace1.v2]; + newViewerFace1.v3 = coords[newFace1.v3]; + + newViewerFace2.v1 = coords[newFace2.v1]; + newViewerFace2.v2 = coords[newFace2.v2]; + newViewerFace2.v3 = coords[newFace2.v3]; + + newViewerFace1.coordIndex1 = newFace1.v1; + newViewerFace1.coordIndex2 = newFace1.v2; + newViewerFace1.coordIndex3 = newFace1.v3; + + newViewerFace2.coordIndex1 = newFace2.v1; + newViewerFace2.coordIndex2 = newFace2.v2; + newViewerFace2.coordIndex3 = newFace2.v3; + + // profile cut faces + if (whichVert == cut1Vert) + { + newViewerFace1.primFaceNumber = cut1FaceNumber; + newViewerFace2.primFaceNumber = cut1FaceNumber; + newViewerFace1.n1 = newLayer.cutNormal1; + newViewerFace1.n2 = lastCutNormal1; + newViewerFace1.n3 = lastCutNormal1; + + newViewerFace2.n1 = newLayer.cutNormal1; + newViewerFace2.n3 = newLayer.cutNormal1; + newViewerFace2.n2 = lastCutNormal1; + } + else if (whichVert == cut2Vert) + { + newViewerFace1.primFaceNumber = cut2FaceNumber; + newViewerFace2.primFaceNumber = cut2FaceNumber; + newViewerFace1.n1 = newLayer.cutNormal2; + newViewerFace1.n2 = lastCutNormal2; + newViewerFace1.n3 = lastCutNormal2; + + newViewerFace2.n1 = newLayer.cutNormal2; + newViewerFace2.n3 = newLayer.cutNormal2; + newViewerFace2.n2 = lastCutNormal2; + } + + else // outer and hollow faces + { + if ((sides < 5 && whichVert < newLayer.numOuterVerts) || (hollowSides < 5 && whichVert >= newLayer.numOuterVerts)) + { // looks terrible when path is twisted... need vertex normals here + newViewerFace1.CalcSurfaceNormal(); + newViewerFace2.CalcSurfaceNormal(); + } + else + { + newViewerFace1.n1 = normals[newFace1.n1]; + newViewerFace1.n2 = normals[newFace1.n2]; + newViewerFace1.n3 = normals[newFace1.n3]; + + newViewerFace2.n1 = normals[newFace2.n1]; + newViewerFace2.n2 = normals[newFace2.n2]; + newViewerFace2.n3 = normals[newFace2.n3]; + } + } + + viewerFaces.Add(newViewerFace1); + viewerFaces.Add(newViewerFace2); + } + } + + lastCutNormal1 = newLayer.cutNormal1; + lastCutNormal2 = newLayer.cutNormal2; + lastV = thisV; + + if (needEndFaces && nodeIndex == path.pathNodes.Count - 1 && viewerMode) + { + // add the top faces to the viewerFaces list here + Vector3 faceNormal = newLayer.faceNormal; + ViewerFace newViewerFace = new(0); + List faces = newLayer.faces; + + for (int i = 0; i < faces.Count; i++) + { + Face face = faces[i]; + newViewerFace.v1 = newLayer.coords[face.v1 - coordsLen]; + newViewerFace.v2 = newLayer.coords[face.v2 - coordsLen]; + newViewerFace.v3 = newLayer.coords[face.v3 - coordsLen]; + + newViewerFace.coordIndex1 = face.v1 - coordsLen; + newViewerFace.coordIndex2 = face.v2 - coordsLen; + newViewerFace.coordIndex3 = face.v3 - coordsLen; + + newViewerFace.n1 = faceNormal; + newViewerFace.n2 = faceNormal; + newViewerFace.n3 = faceNormal; + + newViewerFace.uv1 = newLayer.faceUVs[face.v1 - coordsLen]; + newViewerFace.uv2 = newLayer.faceUVs[face.v2 - coordsLen]; + newViewerFace.uv3 = newLayer.faceUVs[face.v3 - coordsLen]; + + if (pathType == PathType.Linear) + { + newViewerFace.uv1.Flip(); + newViewerFace.uv2.Flip(); + newViewerFace.uv3.Flip(); + } + + viewerFaces.Add(newViewerFace); + } + } + } // for (int nodeIndex = 0; nodeIndex < path.pathNodes.Count; nodeIndex++) + + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void ExtrudeLinear() + { + Extrude(PathType.Linear); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void ExtrudeCircular() + { + Extrude(PathType.Circular); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static Vector3 SurfaceNormal(Vector3 c1, Vector3 c2, Vector3 c3) + { + Vector3 edge1 = c2 - c1; + Vector3 edge2 = c3 - c1; + + Vector3 normal = Vector3.Cross(edge1, edge2); + normal.Normalize(); + + return normal; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private Vector3 SurfaceNormal(Face face) + { + return SurfaceNormal(coords[face.v1], coords[face.v2], coords[face.v3]); + } + + /// + /// Calculate the surface normal for a face in the list of faces + /// + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Vector3 SurfaceNormal(int faceIndex) + { + if (faceIndex < 0 || faceIndex >= faces.Count) + throw new Exception("faceIndex out of range"); + + return SurfaceNormal(faces[faceIndex]); + } + + /// + /// Duplicates a PrimMesh object. All object properties are copied by value, including lists. + /// + /// + public PrimMesh Copy() + { + PrimMesh copy = new(sides, profileStart, profileEnd, hollow, hollowSides) + { + twistBegin = twistBegin, + twistEnd = twistEnd, + topShearX = topShearX, + topShearY = topShearY, + pathCutBegin = pathCutBegin, + pathCutEnd = pathCutEnd, + dimpleBegin = dimpleBegin, + dimpleEnd = dimpleEnd, + skew = skew, + holeSizeX = holeSizeX, + holeSizeY = holeSizeY, + taperX = taperX, + taperY = taperY, + radius = radius, + revolutions = revolutions, + stepsPerRevolution = stepsPerRevolution, + calcVertexNormals = calcVertexNormals, + normalsProcessed = normalsProcessed, + viewerMode = viewerMode, + numPrimFaces = numPrimFaces, + errorMessage = errorMessage, + + coords = new List(coords), + faces = new List(faces), + viewerFaces = new List(viewerFaces), + normals = new List(normals) + }; + + return copy; + } + + /// + /// Calculate surface normals for all of the faces in the list of faces in this mesh + /// + public void CalcNormals() + { + if (normalsProcessed) + return; + + normalsProcessed = true; + + if (!calcVertexNormals) + normals = []; + + for (int i = 0; i < faces.Count; i++) + { + int normIndex = normals.Count; + + Face face = faces[i]; + Vector3 n = SurfaceNormal(face); + n.Normalize(); + normals.Add(n); + + face.n1 = normIndex; + face.n2 = normIndex; + face.n3 = normIndex; + + faces[i] = face; + } + } + + /// + /// Adds a value to each XYZ vertex coordinate in the mesh + /// + /// + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void AddPos(float x, float y, float z) + { + Vector3 vert = new(x, y, z); + + for (int i = 0; i < coords.Count; i++) + coords[i] += vert; + + if (viewerFaces != null) + { + for (int i = 0; i < viewerFaces.Count; i++) + { + ViewerFace face = viewerFaces[i]; + face.AddPos(vert); + viewerFaces[i] = face; + } + } + } + + /// + /// Rotates the mesh + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void AddRot(Quaternion q) + { + if(q.IsIdentity()) + return; + + for (int i = 0; i < coords.Count; i++) + coords[i] *= q; + + if (normals != null) + { + for (int i = 0; i < normals.Count; i++) + normals[i] *= q; + } + + if (viewerFaces != null) + { + for (int i = 0; i < viewerFaces.Count; i++) + { + ViewerFace face = viewerFaces[i]; + face.AddRot(q); + viewerFaces[i] = face; + } + } + } + + public VertexIndexer GetVertexIndexer() + { + return (viewerMode && viewerFaces.Count > 0) ? new VertexIndexer(this) : null; + } + + /// + /// Scales the mesh + /// + /// + /// + /// + public void Scale(float x, float y, float z) + { + Vector3 scale = new(x, y, z); + for (int i = 0; i < coords.Count; i++) + coords[i] *= scale; + + if (viewerFaces != null) + { + for (int i = 0; i < viewerFaces.Count; i++) + { + ViewerFace face = viewerFaces[i]; + face.Scale(scale); + viewerFaces[i] = face; + } + } + } + + /// + /// Dumps the mesh to a Blender compatible "Raw" format file + /// + /// + /// + /// + public void DumpRaw(string path, string name, string title) + { + if (path == null) + return; + string fileName = name + "_" + title + ".raw"; + string completePath = System.IO.Path.Combine(path, fileName); + + using StreamWriter sw = new(completePath); + + for (int i = 0; i < faces.Count; i++) + { + Face face = faces[i]; + string s = $"{coords[face.v1]} {coords[face.v2]} {coords[face.v3]}"; + sw.WriteLine(s); + } + } + } +} diff --git a/PrimMesher/Properties/AssemblyInfo.cs b/PrimMesher/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..1dec5445 --- /dev/null +++ b/PrimMesher/Properties/AssemblyInfo.cs @@ -0,0 +1,13 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("ef69232f-7e8c-4efa-9ce6-d4e9743aac66")] diff --git a/OpenMetaverse.PrimMesher/SculptMap.cs b/PrimMesher/SculptMap.cs similarity index 58% rename from OpenMetaverse.PrimMesher/SculptMap.cs rename to PrimMesher/SculptMap.cs index 8cb2ebc5..ebfa2fa0 100644 --- a/OpenMetaverse.PrimMesher/SculptMap.cs +++ b/PrimMesher/SculptMap.cs @@ -27,36 +27,36 @@ using System; using System.Collections.Generic; -using System.Drawing; -using System.Drawing.Drawing2D; +using OpenMetaverse; +using SkiaSharp; -namespace OpenMetaverse.PrimMesher +namespace PrimMesher { public class SculptMap { - public byte[] blueBytes; - public byte[] greenBytes; + public int width; public int height; public byte[] redBytes; - public int width; + public byte[] greenBytes; + public byte[] blueBytes; public SculptMap() { } - public SculptMap(Bitmap bm, int lod) + public SculptMap(SKBitmap bm, int lod) { - var bmW = bm.Width; - var bmH = bm.Height; + int bmW = bm.Width; + int bmH = bm.Height; if (bmW == 0 || bmH == 0) throw new Exception("SculptMap: bitmap has no data"); - var numLodPixels = lod * 2 * lod * 2; // (32 * 2)^2 = 64^2 pixels for default sculpt map image + int numLodPixels = lod * 2 * lod * 2; // (32 * 2)^2 = 64^2 pixels for default sculpt map image - var needsScaling = false; + bool needsScaling = false; - var smallMap = bmW * bmH <= lod * lod; + bool smallMap = bmW * bmH <= lod * lod; width = bmW; height = bmH; @@ -67,17 +67,16 @@ public SculptMap(Bitmap bm, int lod) needsScaling = true; } - try { if (needsScaling) bm = ScaleImage(bm, width, height, - InterpolationMode.NearestNeighbor); + SKFilterMode.Nearest); } catch (Exception e) { - throw new Exception("Exception in ScaleImage(): e: " + e); + throw new Exception("Exception in ScaleImage(): e: " + e.ToString()); } if (width * height > lod * lod) @@ -86,44 +85,48 @@ public SculptMap(Bitmap bm, int lod) height >>= 1; } - var numBytes = smallMap ? width * height : (width + 1) * (height + 1); + int numBytes = smallMap ? width * height : (width + 1) * (height + 1); redBytes = new byte[numBytes]; greenBytes = new byte[numBytes]; blueBytes = new byte[numBytes]; - var byteNdx = 0; + int byteNdx = 0; try { if (smallMap) - for (var y = 0; y < height; y++) - for (var x = 0; x < width; x++) + for (int y = 0; y < height; y++) { - var c = bm.GetPixel(x, y); + for (int x = 0; x < width; x++) + { + SKColor c = bm.GetPixel(x, y); - redBytes[byteNdx] = c.R; - greenBytes[byteNdx] = c.G; - blueBytes[byteNdx] = c.B; + redBytes[byteNdx] = c.Red; + greenBytes[byteNdx] = c.Green; + blueBytes[byteNdx] = c.Blue; - ++byteNdx; + ++byteNdx; + } } else - for (var y = 0; y <= height; y++) - for (var x = 0; x <= width; x++) + for (int y = 0; y <= height; y++) { - var c = bm.GetPixel(x < width ? x * 2 : x * 2 - 1, - y < height ? y * 2 : y * 2 - 1); + for (int x = 0; x <= width; x++) + { + SKColor c = bm.GetPixel(x < width ? x * 2 : x * 2 - 1, + y < height ? y * 2 : y * 2 - 1); - redBytes[byteNdx] = c.R; - greenBytes[byteNdx] = c.G; - blueBytes[byteNdx] = c.B; + redBytes[byteNdx] = c.Red; + greenBytes[byteNdx] = c.Green; + blueBytes[byteNdx] = c.Blue; - ++byteNdx; + ++byteNdx; + } } } catch (Exception e) { - throw new Exception("Caught exception processing byte arrays in SculptMap(): e: " + e); + throw new Exception("Caught exception processing byte arrays in SculptMap(): e: " + e.ToString()); } if (!smallMap) @@ -133,29 +136,27 @@ public SculptMap(Bitmap bm, int lod) } } - public List> ToRows(bool mirror) + public List> ToRows(bool mirror) { - var numRows = height; - var numCols = width; + int numRows = height; + int numCols = width; - var rows = new List>(numRows); + List> rows = new List>(numRows); - var pixScale = 1.0f / 255; + const float pixScale = 1.0f / 255.0f; int rowNdx, colNdx; - var smNdx = 0; + int smNdx = 0; for (rowNdx = 0; rowNdx < numRows; rowNdx++) { - var row = new List(numCols); + List row = new List(numCols); for (colNdx = 0; colNdx < numCols; colNdx++) { if (mirror) - row.Add(new Coord(-(redBytes[smNdx] * pixScale - 0.5f), greenBytes[smNdx] * pixScale - 0.5f, - blueBytes[smNdx] * pixScale - 0.5f)); + row.Add(new Vector3(-(redBytes[smNdx] * pixScale - 0.5f), (greenBytes[smNdx] * pixScale - 0.5f), blueBytes[smNdx] * pixScale - 0.5f)); else - row.Add(new Coord(redBytes[smNdx] * pixScale - 0.5f, greenBytes[smNdx] * pixScale - 0.5f, - blueBytes[smNdx] * pixScale - 0.5f)); + row.Add(new Vector3(redBytes[smNdx] * pixScale - 0.5f, greenBytes[smNdx] * pixScale - 0.5f, blueBytes[smNdx] * pixScale - 0.5f)); ++smNdx; } @@ -164,22 +165,15 @@ public List> ToRows(bool mirror) return rows; } - private Bitmap ScaleImage(Bitmap srcImage, int destWidth, int destHeight, - InterpolationMode interpMode) + private SKBitmap ScaleImage(SKBitmap srcImage, int destWidth, int destHeight, + SKFilterMode filterMode) { - var scaledImage = new Bitmap(srcImage, destWidth, destHeight); - scaledImage.SetResolution(96.0f, 96.0f); - - var grPhoto = Graphics.FromImage(scaledImage); - grPhoto.InterpolationMode = interpMode; - - grPhoto.DrawImage(srcImage, - new Rectangle(0, 0, destWidth, destHeight), - new Rectangle(0, 0, srcImage.Width, srcImage.Height), - GraphicsUnit.Pixel); - - grPhoto.Dispose(); + SKBitmap scaledImage = new SKBitmap(destWidth, destHeight, srcImage.ColorType, srcImage.AlphaType, + srcImage.ColorSpace); + SKSamplingOptions sampling = new SKSamplingOptions(filterMode, SKMipmapMode.None); + srcImage.ScalePixels(scaledImage, sampling); return scaledImage; } } -} \ No newline at end of file +} + diff --git a/OpenMetaverse.PrimMesher/SculptMesh.cs b/PrimMesher/SculptMesh.cs similarity index 50% rename from OpenMetaverse.PrimMesher/SculptMesh.cs rename to PrimMesher/SculptMesh.cs index fa277770..6580d3b4 100644 --- a/OpenMetaverse.PrimMesher/SculptMesh.cs +++ b/PrimMesher/SculptMesh.cs @@ -25,41 +25,45 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ +// SkiaSharp bitmap/pixel APIs are used for sculpt image loading and sampling. + using System; using System.Collections.Generic; -using System.Drawing; using System.IO; -namespace OpenMetaverse.PrimMesher +using OpenMetaverse; +using SkiaSharp; + +namespace PrimMesher { public class SculptMesh { - public enum SculptType - { - sphere = 1, - torus = 2, - plane = 3, - cylinder = 4 - } - - public List coords; + public List coords; public List faces; - public List normals; - public List uvs; public List viewerFaces; + public List normals; + public List uvs; + + public enum SculptType { sphere = 1, torus = 2, plane = 3, cylinder = 4 }; + + public SculptMesh SculptMeshFromFile(string fileName, SculptType sculptType, int lod, bool viewerMode) + { + using SKBitmap bitmap = SKBitmap.Decode(fileName) ?? throw new Exception("Failed to decode sculpt image"); + SculptMesh sculptMesh = new SculptMesh(bitmap, sculptType, lod, viewerMode); + return sculptMesh; + } public SculptMesh(string fileName, int sculptType, int lod, int viewerMode, int mirror, int invert) { - var bitmap = (Bitmap) Image.FromFile(fileName); - _SculptMesh(bitmap, (SculptType) sculptType, lod, viewerMode != 0, mirror != 0, invert != 0); - bitmap.Dispose(); + using SKBitmap bitmap = SKBitmap.Decode(fileName) ?? throw new Exception("Failed to decode sculpt image"); + _SculptMesh(bitmap, (SculptType)sculptType, lod, viewerMode != 0, mirror != 0, invert != 0); } /// - /// ** Experimental ** May disappear from future versions ** not recommeneded for use in applications - /// Construct a sculpt mesh from a 2D array of floats + /// ** Experimental ** May disappear from future versions ** not recommeneded for use in applications + /// Construct a sculpt mesh from a 2D array of floats /// /// /// @@ -72,13 +76,13 @@ public SculptMesh(float[,] zMap, float xBegin, float xEnd, float yBegin, float y float xStep, yStep; float uStep, vStep; - var numYElements = zMap.GetLength(0); - var numXElements = zMap.GetLength(1); + int numYElements = zMap.GetLength(0); + int numXElements = zMap.GetLength(1); try { - xStep = (xEnd - xBegin) / (numXElements - 1); - yStep = (yEnd - yBegin) / (numYElements - 1); + xStep = (xEnd - xBegin) / (float)(numXElements - 1); + yStep = (yEnd - yBegin) / (float)(numYElements - 1); uStep = 1.0f / (numXElements - 1); vStep = 1.0f / (numYElements - 1); @@ -88,12 +92,12 @@ public SculptMesh(float[,] zMap, float xBegin, float xEnd, float yBegin, float y return; } - coords = new List(); - faces = new List(); - normals = new List(); - uvs = new List(); + coords = []; + faces = []; + normals = []; + uvs = []; - viewerFaces = new List(); + viewerFaces = []; int p1, p2, p3, p4; @@ -102,7 +106,7 @@ public SculptMesh(float[,] zMap, float xBegin, float xEnd, float yBegin, float y for (y = yStart; y < numYElements; y++) { - var rowOffset = y * numXElements; + int rowOffset = y * numXElements; for (x = xStart; x < numXElements; x++) { @@ -120,11 +124,11 @@ public SculptMesh(float[,] zMap, float xBegin, float xEnd, float yBegin, float y p2 = p4 - numXElements; p1 = p3 - numXElements; - var c = new Coord(xBegin + x * xStep, yBegin + y * yStep, zMap[y, x]); - coords.Add(c); + Vector3 c = new(xBegin + x * xStep, yBegin + y * yStep, zMap[y, x]); + this.coords.Add(c); if (viewerMode) { - normals.Add(new Coord()); + normals.Add(Vector3.Zero); uvs.Add(new UVCoord(uStep * x, 1.0f - vStep * y)); } @@ -134,19 +138,15 @@ public SculptMesh(float[,] zMap, float xBegin, float xEnd, float yBegin, float y if (viewerMode) { - f1 = new Face(p1, p4, p3, p1, p4, p3) - { - uv1 = p1, - uv2 = p4, - uv3 = p3 - }; - - f2 = new Face(p1, p2, p4, p1, p2, p4) - { - uv1 = p1, - uv2 = p2, - uv3 = p4 - }; + f1 = new Face(p1, p4, p3, p1, p4, p3); + f1.uv1 = p1; + f1.uv2 = p4; + f1.uv3 = p3; + + f2 = new Face(p1, p2, p4, p1, p2, p4); + f2.uv1 = p1; + f2.uv2 = p2; + f2.uv3 = p4; } else { @@ -164,56 +164,38 @@ public SculptMesh(float[,] zMap, float xBegin, float xEnd, float yBegin, float y calcVertexNormals(SculptType.plane, numXElements, numYElements); } - public SculptMesh(Bitmap sculptBitmap, SculptType sculptType, int lod, bool viewerMode) + public SculptMesh(SKBitmap sculptBitmap, SculptType sculptType, int lod, bool viewerMode) { _SculptMesh(sculptBitmap, sculptType, lod, viewerMode, false, false); } - public SculptMesh(Bitmap sculptBitmap, SculptType sculptType, int lod, bool viewerMode, bool mirror, - bool invert) + public SculptMesh(SKBitmap sculptBitmap, SculptType sculptType, int lod, bool viewerMode, bool mirror, bool invert) { _SculptMesh(sculptBitmap, sculptType, lod, viewerMode, mirror, invert); } - public SculptMesh(List> rows, SculptType sculptType, bool viewerMode, bool mirror, bool invert) + public SculptMesh(List> rows, SculptType sculptType, bool viewerMode, bool mirror, bool invert) { _SculptMesh(rows, sculptType, viewerMode, mirror, invert); } - public SculptMesh(SculptMesh sm) - { - coords = new List(sm.coords); - faces = new List(sm.faces); - viewerFaces = new List(sm.viewerFaces); - normals = new List(sm.normals); - uvs = new List(sm.uvs); - } - - public SculptMesh SculptMeshFromFile(string fileName, SculptType sculptType, int lod, bool viewerMode) - { - var bitmap = (Bitmap) Image.FromFile(fileName); - var sculptMesh = new SculptMesh(bitmap, sculptType, lod, viewerMode); - bitmap.Dispose(); - return sculptMesh; - } - /// - /// converts a bitmap to a list of lists of coords, while scaling the image. - /// the scaling is done in floating point so as to allow for reduced vertex position - /// quantization as the position will be averaged between pixel values. this routine will - /// likely fail if the bitmap width and height are not powers of 2. + /// converts a bitmap to a list of lists of coords, while scaling the image. + /// the scaling is done in floating point so as to allow for reduced vertex position + /// quantization as the position will be averaged between pixel values. this routine will + /// likely fail if the bitmap width and height are not powers of 2. /// /// /// /// /// - private List> bitmap2Coords(Bitmap bitmap, int scale, bool mirror) + private List> bitmap2Coords(SKBitmap bitmap, int scale, bool mirror) { - var numRows = bitmap.Height / scale; - var numCols = bitmap.Width / scale; - var rows = new List>(numRows); + int numRows = bitmap.Height / scale; + int numCols = bitmap.Width / scale; + List> rows = new List>(numRows); - var pixScale = 1.0f / (scale * scale); + float pixScale = 1.0f / (scale * scale); pixScale /= 255; int imageX, imageY = 0; @@ -222,45 +204,49 @@ private List> bitmap2Coords(Bitmap bitmap, int scale, bool mirror) for (rowNdx = 0; rowNdx < numRows; rowNdx++) { - var row = new List(numCols); + List row = new List(numCols); for (colNdx = 0; colNdx < numCols; colNdx++) { imageX = colNdx * scale; - var imageYStart = rowNdx * scale; - var imageYEnd = imageYStart + scale; - var imageXEnd = imageX + scale; - var rSum = 0.0f; - var gSum = 0.0f; - var bSum = 0.0f; + int imageYStart = rowNdx * scale; + int imageYEnd = imageYStart + scale; + int imageXEnd = imageX + scale; + float rSum = 0.0f; + float gSum = 0.0f; + float bSum = 0.0f; for (; imageX < imageXEnd; imageX++) - for (imageY = imageYStart; imageY < imageYEnd; imageY++) { - var c = bitmap.GetPixel(imageX, imageY); - if (c.A != 255) + for (imageY = imageYStart; imageY < imageYEnd; imageY++) { - bitmap.SetPixel(imageX, imageY, Color.FromArgb(255, c.R, c.G, c.B)); - c = bitmap.GetPixel(imageX, imageY); + SKColor c = bitmap.GetPixel(imageX, imageY); + if (c.Alpha != 255) + { + bitmap.SetPixel(imageX, imageY, new SKColor(c.Red, c.Green, c.Blue, 255)); + c = bitmap.GetPixel(imageX, imageY); + } + rSum += c.Red; + gSum += c.Green; + bSum += c.Blue; } - rSum += c.R; - gSum += c.G; - bSum += c.B; } - row.Add(mirror - ? new Coord(-(rSum * pixScale - 0.5f), gSum * pixScale - 0.5f, bSum * pixScale - 0.5f) - : new Coord(rSum * pixScale - 0.5f, gSum * pixScale - 0.5f, bSum * pixScale - 0.5f)); + if (mirror) + row.Add(new(-(rSum * pixScale - 0.5f), gSum * pixScale - 0.5f, bSum * pixScale - 0.5f)); + else + row.Add(new(rSum * pixScale - 0.5f, gSum * pixScale - 0.5f, bSum * pixScale - 0.5f)); + } rows.Add(row); } return rows; } - private List> bitmap2CoordsSampled(Bitmap bitmap, int scale, bool mirror) + private List> bitmap2CoordsSampled(SKBitmap bitmap, int scale, bool mirror) { - var numRows = bitmap.Height / scale; - var numCols = bitmap.Width / scale; - var rows = new List>(numRows); + int numRows = bitmap.Height / scale; + int numCols = bitmap.Width / scale; + List> rows = new List>(numRows); - var pixScale = 1.0f / 256.0f; + float pixScale = 1.0f / 256.0f; int imageX, imageY = 0; @@ -268,7 +254,7 @@ private List> bitmap2CoordsSampled(Bitmap bitmap, int scale, bool mi for (rowNdx = 0; rowNdx <= numRows; rowNdx++) { - var row = new List(numCols); + List row = new List(numCols); imageY = rowNdx * scale; if (rowNdx == numRows) imageY--; for (colNdx = 0; colNdx <= numCols; colNdx++) @@ -276,75 +262,77 @@ private List> bitmap2CoordsSampled(Bitmap bitmap, int scale, bool mi imageX = colNdx * scale; if (colNdx == numCols) imageX--; - var c = bitmap.GetPixel(imageX, imageY); - if (c.A != 255) + SKColor c = bitmap.GetPixel(imageX, imageY); + if (c.Alpha != 255) { - bitmap.SetPixel(imageX, imageY, Color.FromArgb(255, c.R, c.G, c.B)); + bitmap.SetPixel(imageX, imageY, new SKColor(c.Red, c.Green, c.Blue, 255)); c = bitmap.GetPixel(imageX, imageY); } - row.Add(mirror - ? new Coord(-(c.R * pixScale - 0.5f), c.G * pixScale - 0.5f, c.B * pixScale - 0.5f) - : new Coord(c.R * pixScale - 0.5f, c.G * pixScale - 0.5f, c.B * pixScale - 0.5f)); + if (mirror) + row.Add(new(-(c.Red * pixScale - 0.5f), c.Green * pixScale - 0.5f, c.Blue * pixScale - 0.5f)); + else + row.Add(new(c.Red * pixScale - 0.5f, c.Green * pixScale - 0.5f, c.Blue * pixScale - 0.5f)); + } rows.Add(row); } return rows; } - - private void _SculptMesh(Bitmap sculptBitmap, SculptType sculptType, int lod, bool viewerMode, bool mirror, - bool invert) + void _SculptMesh(SKBitmap sculptBitmap, SculptType sculptType, int lod, bool viewerMode, bool mirror, bool invert) { _SculptMesh(new SculptMap(sculptBitmap, lod).ToRows(mirror), sculptType, viewerMode, mirror, invert); } - private void _SculptMesh(List> rows, SculptType sculptType, bool viewerMode, bool mirror, - bool invert) + void _SculptMesh(List> rows, SculptType sculptType, bool viewerMode, bool mirror, bool invert) { - coords = new List(); - faces = new List(); - normals = new List(); - uvs = new List(); + coords = []; + faces = []; + normals = []; + uvs = []; - sculptType = (SculptType) ((int) sculptType & 0x07); + sculptType = (SculptType)(((int)sculptType) & 0x07); if (mirror) invert = !invert; viewerFaces = new List(); - var width = rows[0].Count; + int width = rows[0].Count; int p1, p2, p3, p4; int imageX, imageY; if (sculptType != SculptType.plane) + { if (rows.Count % 2 == 0) { - foreach (List row in rows) - row.Add(row[0]); + for (int rowNdx = 0; rowNdx < rows.Count; rowNdx++) + rows[rowNdx].Add(rows[rowNdx][0]); } else { - var lastIndex = rows[0].Count - 1; + int lastIndex = rows[0].Count - 1; - foreach (List row in rows) - row[0] = row[lastIndex]; + for (int i = 0; i < rows.Count; i++) + rows[i][0] = rows[i][lastIndex]; } + } - var topPole = rows[0][width / 2]; - var bottomPole = rows[rows.Count - 1][width / 2]; + Vector3 topPole = rows[0][width / 2]; + Vector3 bottomPole = rows[rows.Count - 1][width / 2]; if (sculptType == SculptType.sphere) + { if (rows.Count % 2 == 0) { - var count = rows[0].Count; - var topPoleRow = new List(count); - var bottomPoleRow = new List(count); + int count = rows[0].Count; + List topPoleRow = []; + List bottomPoleRow = []; - for (var i = 0; i < count; i++) + for (int i = 0; i < count; i++) { topPoleRow.Add(topPole); bottomPoleRow.Add(bottomPole); @@ -354,31 +342,32 @@ private void _SculptMesh(List> rows, SculptType sculptType, bool vie } else { - var count = rows[0].Count; + int count = rows[0].Count; - var topPoleRow = rows[0]; - var bottomPoleRow = rows[rows.Count - 1]; + List topPoleRow = rows[0]; + List bottomPoleRow = rows[rows.Count - 1]; - for (var i = 0; i < count; i++) + for (int i = 0; i < count; i++) { topPoleRow[i] = topPole; bottomPoleRow[i] = bottomPole; } } + } if (sculptType == SculptType.torus) rows.Add(rows[0]); - var coordsDown = rows.Count; - var coordsAcross = rows[0].Count; - var lastColumn = coordsAcross - 1; + int coordsDown = rows.Count; + int coordsAcross = rows[0].Count; + int lastColumn = coordsAcross - 1; - var widthUnit = 1.0f / (coordsAcross - 1); - var heightUnit = 1.0f / (coordsDown - 1); + float widthUnit = 1.0f / (coordsAcross - 1); + float heightUnit = 1.0f / (coordsDown - 1); for (imageY = 0; imageY < coordsDown; imageY++) { - var rowOffset = imageY * coordsAcross; + int rowOffset = imageY * coordsAcross; for (imageX = 0; imageX < coordsAcross; imageX++) { @@ -399,8 +388,8 @@ private void _SculptMesh(List> rows, SculptType sculptType, bool vie coords.Add(rows[imageY][imageX]); if (viewerMode) { - normals.Add(new Coord()); - uvs.Add(new UVCoord(widthUnit * imageX, heightUnit * imageY)); + normals.Add(Vector3.Zero); + uvs.Add(new(widthUnit * imageX, heightUnit * imageY)); } if (imageY > 0 && imageX > 0) @@ -411,35 +400,27 @@ private void _SculptMesh(List> rows, SculptType sculptType, bool vie { if (invert) { - f1 = new Face(p1, p4, p3, p1, p4, p3) - { - uv1 = p1, - uv2 = p4, - uv3 = p3 - }; - - f2 = new Face(p1, p2, p4, p1, p2, p4) - { - uv1 = p1, - uv2 = p2, - uv3 = p4 - }; + f1 = new Face(p1, p4, p3, p1, p4, p3); + f1.uv1 = p1; + f1.uv2 = p4; + f1.uv3 = p3; + + f2 = new Face(p1, p2, p4, p1, p2, p4); + f2.uv1 = p1; + f2.uv2 = p2; + f2.uv3 = p4; } else { - f1 = new Face(p1, p3, p4, p1, p3, p4) - { - uv1 = p1, - uv2 = p3, - uv3 = p4 - }; - - f2 = new Face(p1, p4, p2, p1, p4, p2) - { - uv1 = p1, - uv2 = p4, - uv3 = p2 - }; + f1 = new Face(p1, p3, p4, p1, p3, p4); + f1.uv1 = p1; + f1.uv2 = p3; + f1.uv3 = p4; + + f2 = new Face(p1, p4, p2, p1, p4, p2); + f2.uv1 = p1; + f2.uv2 = p4; + f2.uv3 = p2; } } else @@ -456,8 +437,8 @@ private void _SculptMesh(List> rows, SculptType sculptType, bool vie } } - faces.Add(f1); - faces.Add(f2); + this.faces.Add(f1); + this.faces.Add(f2); } } } @@ -467,7 +448,7 @@ private void _SculptMesh(List> rows, SculptType sculptType, bool vie } /// - /// Duplicates a SculptMesh object. All object properties are copied by value, including lists. + /// Duplicates a SculptMesh object. All object properties are copied by value, including lists. /// /// public SculptMesh Copy() @@ -475,167 +456,150 @@ public SculptMesh Copy() return new SculptMesh(this); } - private void calcVertexNormals(SculptType sculptType, int xSize, int ySize) + public SculptMesh(SculptMesh sm) { - // compute vertex normals by summing all the surface normals of all the triangles sharing + coords = new List(sm.coords); + faces = new List(sm.faces); + viewerFaces = new List(sm.viewerFaces); + normals = new List(sm.normals); + uvs = new List(sm.uvs); + } + + private void calcVertexNormals(SculptType sculptType, int xSize, int ySize) + { // compute vertex normals by summing all the surface normals of all the triangles sharing // each vertex and then normalizing - var numFaces = faces.Count; - for (var i = 0; i < numFaces; i++) + for (int i = 0; i < faces.Count; i++) { - var face = faces[i]; - var surfaceNormal = face.SurfaceNormal(coords); + Face face = faces[i]; + Vector3 surfaceNormal = face.SurfaceNormal(coords); normals[face.n1] += surfaceNormal; normals[face.n2] += surfaceNormal; normals[face.n3] += surfaceNormal; } - var numNormals = normals.Count; - for (var i = 0; i < numNormals; i++) - normals[i] = normals[i].Normalize(); + for (int i = 0; i < normals.Count; i++) + { + Vector3 n = normals[i]; + n.Normalize(); + normals[i] = n; + } if (sculptType != SculptType.plane) - for (var y = 0; y < ySize; y++) + { // blend the vertex normals at the cylinder seam + for (int rowOffsetA = 0; rowOffsetA < xSize * ySize; rowOffsetA += xSize) { - var rowOffset = y * xSize; - - normals[rowOffset] = normals[rowOffset + xSize - 1] = - (normals[rowOffset] + normals[rowOffset + xSize - 1]).Normalize(); + int rowOffsetB = rowOffsetA + xSize - 1; + Vector3 v = normals[rowOffsetA] + normals[rowOffsetB]; + v.Normalize(); + normals[rowOffsetA] = normals[rowOffsetB] = v; } + } - foreach (var face in faces) + foreach (Face face in faces) { - var vf = new ViewerFace(0); - vf.v1 = coords[face.v1]; - vf.v2 = coords[face.v2]; - vf.v3 = coords[face.v3]; + ViewerFace vf = new(0) + { + v1 = coords[face.v1], + v2 = coords[face.v2], + v3 = coords[face.v3], - vf.coordIndex1 = face.v1; - vf.coordIndex2 = face.v2; - vf.coordIndex3 = face.v3; + coordIndex1 = face.v1, + coordIndex2 = face.v2, + coordIndex3 = face.v3, - vf.n1 = normals[face.n1]; - vf.n2 = normals[face.n2]; - vf.n3 = normals[face.n3]; + n1 = normals[face.n1], + n2 = normals[face.n2], + n3 = normals[face.n3], - vf.uv1 = uvs[face.uv1]; - vf.uv2 = uvs[face.uv2]; - vf.uv3 = uvs[face.uv3]; + uv1 = uvs[face.uv1], + uv2 = uvs[face.uv2], + uv3 = uvs[face.uv3] + }; viewerFaces.Add(vf); } } /// - /// Adds a value to each XYZ vertex coordinate in the mesh + /// Adds a value to each XYZ vertex coordinate in the mesh /// /// /// /// public void AddPos(float x, float y, float z) { - int i; - var numVerts = coords.Count; - Coord vert; - - for (i = 0; i < numVerts; i++) - { - vert = coords[i]; - vert.X += x; - vert.Y += y; - vert.Z += z; - coords[i] = vert; - } + Vector3 v = new(x, y, z); + for (int i = 0; i < coords.Count; i++) + coords[i] += v; if (viewerFaces != null) { - var numViewerFaces = viewerFaces.Count; - - for (i = 0; i < numViewerFaces; i++) + for (int i = 0; i < viewerFaces.Count; i++) { - var v = viewerFaces[i]; - v.AddPos(x, y, z); - viewerFaces[i] = v; + ViewerFace vf = viewerFaces[i]; + vf.AddPos(v); + viewerFaces[i] = vf; } } } /// - /// Rotates the mesh + /// Rotates the mesh /// /// - public void AddRot(Quat q) + public void AddRot(Quaternion q) { - int i; - var numVerts = coords.Count; - - for (i = 0; i < numVerts; i++) + if(q.IsIdentity()) + return; + for (int i = 0; i < coords.Count; i++) coords[i] *= q; - var numNormals = normals.Count; - for (i = 0; i < numNormals; i++) + for (int i = 0; i < normals.Count; i++) normals[i] *= q; if (viewerFaces != null) { - var numViewerFaces = viewerFaces.Count; - - for (i = 0; i < numViewerFaces; i++) + for (int i = 0; i < viewerFaces.Count; i++) { - var v = viewerFaces[i]; - v.v1 *= q; - v.v2 *= q; - v.v3 *= q; - - v.n1 *= q; - v.n2 *= q; - v.n3 *= q; - - viewerFaces[i] = v; + ViewerFace vf = viewerFaces[i]; + vf.AddRot(q); + viewerFaces[i] = vf; } } } public void Scale(float x, float y, float z) { - int i; - var numVerts = coords.Count; - - var m = new Coord(x, y, z); - for (i = 0; i < numVerts; i++) + Vector3 m = new(x, y, z); + for (int i = 0; i < coords.Count; i++) coords[i] *= m; if (viewerFaces != null) { - var numViewerFaces = viewerFaces.Count; - for (i = 0; i < numViewerFaces; i++) + for (int i = 0; i < viewerFaces.Count; i++) { - var v = viewerFaces[i]; - v.v1 *= m; - v.v2 *= m; - v.v3 *= m; - viewerFaces[i] = v; + ViewerFace vf = viewerFaces[i]; + vf.Scale(m); + viewerFaces[i] = vf; } } } - public void DumpRaw(string path, string name, string title) { if (path == null) return; - var fileName = name + "_" + title + ".raw"; - var completePath = System.IO.Path.Combine(path, fileName); - var sw = new StreamWriter(completePath); + string fileName = name + "_" + title + ".raw"; + string completePath = System.IO.Path.Combine(path, fileName); + StreamWriter sw = new StreamWriter(completePath); - for (var i = 0; i < faces.Count; i++) + for (int i = 0; i < faces.Count; i++) { - var s = coords[faces[i].v1].ToString(); - s += " " + coords[faces[i].v2]; - s += " " + coords[faces[i].v3]; - + Face face = faces[i]; + string s = $"{coords[face.v1]} {coords[face.v2]} {coords[face.v3]}"; sw.WriteLine(s); } sw.Close(); } } -} \ No newline at end of file +} diff --git a/OpenMetaverse.PrimMesher/VertexIndexer.cs b/PrimMesher/VertexIndexer.cs similarity index 59% rename from OpenMetaverse.PrimMesher/VertexIndexer.cs rename to PrimMesher/VertexIndexer.cs index 8631c590..01bc2050 100644 --- a/OpenMetaverse.PrimMesher/VertexIndexer.cs +++ b/PrimMesher/VertexIndexer.cs @@ -25,20 +25,23 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ + +using System; using System.Collections.Generic; +using OpenMetaverse; -namespace OpenMetaverse.PrimMesher +namespace PrimMesher { public struct ViewerVertex { - public Coord v; - public Coord n; + public Vector3 v; + public Vector3 n; public UVCoord uv; - public ViewerVertex(Coord coord, Coord normal, UVCoord uv) + public ViewerVertex(Vector3 coord, Vector3 normal, UVCoord uv) { - v = coord; - n = normal; + this.v = coord; + this.n = normal; this.uv = uv; } } @@ -59,62 +62,94 @@ public ViewerPolygon(int v1, int v2, int v3) public class VertexIndexer { - public int numPrimFaces; - public List> viewerPolygons; public List> viewerVertices; - private readonly int[][] viewerVertIndices; + public List> viewerPolygons; + public int numPrimFaces; + private int[][] viewerVertIndices; public VertexIndexer() { } + bool IsValidFace(ViewerFace vf) + { + if (Math.Abs(vf.n1.X) + Math.Abs(vf.n1.Y) + Math.Abs(vf.n1.Z) < 0.2f) + return false; + if (Math.Abs(vf.n2.X) + Math.Abs(vf.n2.Y) + Math.Abs(vf.n2.Z) < 0.2f) + return false; + if (Math.Abs(vf.n3.X) + Math.Abs(vf.n3.Y) + Math.Abs(vf.n3.Z) < 0.2f) + return false; + + return true; + } public VertexIndexer(PrimMesh primMesh) { - var maxPrimFaceNumber = 0; + int maxPrimFaceNumber = 0; + + int[] validFaces = new int[9], invalidFaces = new int[9]; + for (int i = 0; i < 9; i++) + { + validFaces[i] = -1; + invalidFaces[i] = 0; + } + int numValidFaces = 0; - foreach (var vf in primMesh.viewerFaces) + foreach (ViewerFace vf in primMesh.viewerFaces) + { if (maxPrimFaceNumber < vf.primFaceNumber) maxPrimFaceNumber = vf.primFaceNumber; - numPrimFaces = maxPrimFaceNumber + 1; + if (!IsValidFace(vf)) + invalidFaces[vf.primFaceNumber]++; + } + + this.numPrimFaces = maxPrimFaceNumber + 1; + for (int i = 0; i < this.numPrimFaces; i++) + if (invalidFaces[i] == 0) + validFaces[i] = numValidFaces++; - var numViewerVerts = new int[numPrimFaces]; - var numVertsPerPrimFace = new int[numPrimFaces]; + int[] numViewerVerts = new int[numPrimFaces]; + int[] numVertsPerPrimFace = new int[numPrimFaces]; - for (var i = 0; i < numPrimFaces; i++) + for (int i = 0; i < numPrimFaces; i++) { numViewerVerts[i] = 0; numVertsPerPrimFace[i] = 0; } - foreach (var vf in primMesh.viewerFaces) + foreach (ViewerFace vf in primMesh.viewerFaces) numVertsPerPrimFace[vf.primFaceNumber] += 3; - viewerVertices = new List>(numPrimFaces); - viewerPolygons = new List>(numPrimFaces); - viewerVertIndices = new int[numPrimFaces][]; + this.viewerVertices = new List>(numPrimFaces); + this.viewerPolygons = new List>(numPrimFaces); + this.viewerVertIndices = new int[numPrimFaces][]; // create index lists - for (var primFaceNumber = 0; primFaceNumber < numPrimFaces; primFaceNumber++) + for (int primFaceNumber = 0; primFaceNumber < numPrimFaces; primFaceNumber++) { //set all indices to -1 to indicate an invalid index - var vertIndices = new int[primMesh.coords.Count]; - for (var i = 0; i < primMesh.coords.Count; i++) + int[] vertIndices = new int[primMesh.coords.Count]; + for (int i = 0; i < primMesh.coords.Count; i++) vertIndices[i] = -1; viewerVertIndices[primFaceNumber] = vertIndices; - + viewerVertices.Add(new List(numVertsPerPrimFace[primFaceNumber])); viewerPolygons.Add(new List()); } + this.numPrimFaces = numValidFaces; + // populate the index lists - foreach (var vf in primMesh.viewerFaces) + foreach (ViewerFace vf in primMesh.viewerFaces) { - int v1, v2, v3; + if (invalidFaces[vf.primFaceNumber] != 0) + continue; - var vertIndices = viewerVertIndices[vf.primFaceNumber]; - var viewerVerts = viewerVertices[vf.primFaceNumber]; + int v1, v2, v3; + + int[] vertIndices = viewerVertIndices[validFaces[vf.primFaceNumber]]; + List viewerVerts = viewerVertices[validFaces[vf.primFaceNumber]]; // add the vertices if (vertIndices[vf.coordIndex1] < 0) @@ -123,10 +158,7 @@ public VertexIndexer(PrimMesh primMesh) v1 = viewerVerts.Count - 1; vertIndices[vf.coordIndex1] = v1; } - else - { - v1 = vertIndices[vf.coordIndex1]; - } + else v1 = vertIndices[vf.coordIndex1]; if (vertIndices[vf.coordIndex2] < 0) { @@ -134,10 +166,7 @@ public VertexIndexer(PrimMesh primMesh) v2 = viewerVerts.Count - 1; vertIndices[vf.coordIndex2] = v2; } - else - { - v2 = vertIndices[vf.coordIndex2]; - } + else v2 = vertIndices[vf.coordIndex2]; if (vertIndices[vf.coordIndex3] < 0) { @@ -145,13 +174,12 @@ public VertexIndexer(PrimMesh primMesh) v3 = viewerVerts.Count - 1; vertIndices[vf.coordIndex3] = v3; } - else - { - v3 = vertIndices[vf.coordIndex3]; - } + else v3 = vertIndices[vf.coordIndex3]; - viewerPolygons[vf.primFaceNumber].Add(new ViewerPolygon(v1, v2, v3)); + if (v1 != v2 && v1 != v3 && v2 != v3) + viewerPolygons[validFaces[vf.primFaceNumber]].Add(new ViewerPolygon(v1, v2, v3)); } + } } -} \ No newline at end of file +} diff --git a/Programs/AvatarPreview/AvatarPreview.csproj b/Programs/AvatarPreview/AvatarPreview.csproj index ca2e3d6e..acf1501f 100644 --- a/Programs/AvatarPreview/AvatarPreview.csproj +++ b/Programs/AvatarPreview/AvatarPreview.csproj @@ -1,7 +1,6 @@  Local - net48 WinExe avatarpreview Millions Of Us diff --git a/Programs/Baker/Baker.csproj b/Programs/Baker/Baker.csproj index e836cf5a..9d29b2ff 100644 --- a/Programs/Baker/Baker.csproj +++ b/Programs/Baker/Baker.csproj @@ -1,7 +1,6 @@  Local - net48 WinExe True 1591,1574,0419,0618 diff --git a/Programs/GridImageUpload/GridImageUpload.csproj b/Programs/GridImageUpload/GridImageUpload.csproj index 6fc517f5..d2c51f30 100644 --- a/Programs/GridImageUpload/GridImageUpload.csproj +++ b/Programs/GridImageUpload/GridImageUpload.csproj @@ -1,7 +1,6 @@  Local - net48 WinExe GridImageUpload Open Metaverse Foundation diff --git a/Programs/GridImageUpload/Properties/Resources.Designer.cs b/Programs/GridImageUpload/Properties/Resources.Designer.cs index f5a366c1..890a2aa5 100644 --- a/Programs/GridImageUpload/Properties/Resources.Designer.cs +++ b/Programs/GridImageUpload/Properties/Resources.Designer.cs @@ -1,71 +1,63 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:2.0.50727.42 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace GridImageUpload.Properties -{ - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the StronglyTypedResourceBuilder - // class via a tool like ResGen or Visual Studio. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "2.0.0.0")] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class Resources - { - - private static global::System.Resources.ResourceManager resourceMan; - - private static global::System.Globalization.CultureInfo resourceCulture; - - [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal Resources() - { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager - { - get - { - if ((resourceMan == null)) - { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("GridImageUpload.Properties.Resources", typeof(Resources).Assembly); - resourceMan = temp; - } - return resourceMan; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture - { - get - { - return resourceCulture; - } - set - { - resourceCulture = value; - } - } - } -} +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace GridImageUpload.Properties { + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("GridImageUpload.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + } +} diff --git a/Programs/GridImageUpload/Properties/Settings.Designer.cs b/Programs/GridImageUpload/Properties/Settings.Designer.cs index 3c5c10ac..495ea1ae 100644 --- a/Programs/GridImageUpload/Properties/Settings.Designer.cs +++ b/Programs/GridImageUpload/Properties/Settings.Designer.cs @@ -1,30 +1,26 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:2.0.50727.42 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace SLImageUpload.Properties -{ - - - [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "8.0.0.0")] - internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase - { - - private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); - - public static Settings Default - { - get - { - return defaultInstance; - } - } - } -} +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace GridImageUpload.Properties { + + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "15.5.0.0")] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { + + private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); + + public static Settings Default { + get { + return defaultInstance; + } + } + } +} diff --git a/Programs/GridProxy/GridProxy.cs b/Programs/GridProxy/GridProxy.cs index 6fd7b531..31d522f0 100644 --- a/Programs/GridProxy/GridProxy.cs +++ b/Programs/GridProxy/GridProxy.cs @@ -30,23 +30,19 @@ * POSSIBILITY OF SUCH DAMAGE. */ -using System; using System.Collections; -using System.Collections.Generic; -using System.IO; using System.Net; using System.Net.Sockets; using System.Text; using System.Text.RegularExpressions; -using System.Threading; using System.Xml; -using Nwc.XmlRpc; - using OpenMetaverse; using OpenMetaverse.Http; using OpenMetaverse.Packets; using OpenMetaverse.StructuredData; +using System.Net.Security; +using System.Security.Cryptography.X509Certificates; namespace GridProxy { @@ -199,6 +195,23 @@ public class Proxy /* * Proxy Management */ + public static bool ValidateServerCertificate( + object sender, + X509Certificate certificate, + X509Chain chain, + SslPolicyErrors sslPolicyErrors) + { + //if (m_NoVerifyCertChain) + sslPolicyErrors &= ~SslPolicyErrors.RemoteCertificateChainErrors; + + //if (m_NoVerifyCertHostname) + sslPolicyErrors &= ~SslPolicyErrors.RemoteCertificateNameMismatch; + + if (sslPolicyErrors == SslPolicyErrors.None) + return true; + + return false; + } // Proxy: construct a proxy server with the given configuration public Proxy(ProxyConfig proxyConfig) @@ -207,7 +220,7 @@ public Proxy(ProxyConfig proxyConfig) ServicePointManager.Expect100Continue = false; ServicePointManager.DefaultConnectionLimit = 128; - ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true; + ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertificate; InitializeLoginProxy(); InitializeSimProxy(); @@ -583,9 +596,9 @@ private void ProxyHTTP(Socket client) if (uri == "/") { headers["method"] = meth; - if (contentType == "application/xml+llsd" || contentType == "application/xml") + if (contentType == "application/llsd+xml" || contentType == "application/xml+llsd" || contentType == "application/xml") { - ProxyLoginSD(netStream, content); + ProxyLoginSD(netStream, content, headers); } else { @@ -620,9 +633,11 @@ private void ProxyHTTP(Socket client) public ObservableDictionary KnownCaps = new ObservableDictionary(); //private Dictionary SubHack = new Dictionary(); + private static Regex CapMainRegex = new Regex(@"^(https?)://([^:/]+)(:\d+)?(/.*)$", RegexOptions.Compiled | RegexOptions.CultureInvariant); + private static Regex CapUriRegex = new Regex(@"/?\?.*$", RegexOptions.Compiled | RegexOptions.CultureInvariant); private void ProxyCaps(NetworkStream netStream, string meth, string uri, Dictionary headers, byte[] content, int reqNo) { - Match match = new Regex(@"^(https?)://([^:/]+)(:\d+)?(/.*)$").Match(uri); + Match match = CapMainRegex.Match(uri); if (!match.Success) { OpenMetaverse.Logger.Log("[" + reqNo + "] Malformed proxy URI: " + uri, Helpers.LogLevel.Error); @@ -638,8 +653,7 @@ private void ProxyCaps(NetworkStream netStream, string meth, string uri, Diction CapInfo cap = null; lock (this) { - string capuri = Regex.Replace(uri, @"/?\?.*$", string.Empty); - + string capuri = CapUriRegex.Replace(uri, string.Empty); // detect AIS url int indx = capuri.IndexOf("/item/"); if (indx < 0) @@ -647,9 +661,14 @@ private void ProxyCaps(NetworkStream netStream, string meth, string uri, Diction if(indx > 0) capuri = capuri.Substring(0,indx); - if (KnownCaps.ContainsKey(capuri)) + if (!KnownCaps.TryGetValue(capuri, out cap)) { - cap = KnownCaps[capuri]; + indx = capuri.IndexOf("cap/"); + if(indx > 0) + { + capuri = capuri.Substring(0,indx + 36 + 4); + _ = KnownCaps.TryGetValue(capuri, out cap); + } } } @@ -1028,10 +1047,8 @@ private bool KnownCapDelegate(CapsRequest capReq, CapsStage stage) if (stage == CapsStage.Response) { - if (capReq.Response != null && capReq.Response is OSDMap) + if (capReq.Response is OSDMap map) { - OSDMap map = (OSDMap)capReq.Response; - if (map.ContainsKey("uploader")) { string val = map["uploader"].AsString(); @@ -1063,15 +1080,10 @@ private bool FixupEventQueueGet(CapsRequest capReq, CapsStage stage) { if (stage != CapsStage.Response) return false; - OSDMap map = null; - if (capReq.Response is OSDMap) - map = (OSDMap)capReq.Response; - else return false; + if (capReq.Response is not OSDMap map) + return false; - OSDArray array = null; - if (map.ContainsKey("events") && map["events"] is OSDArray) - array = (OSDArray)map["events"]; - else + if(!map.TryGetValue("events", out OSD oarray) || oarray is not OSDArray array) return false; for (int i = 0; i < array.Count; i++) @@ -1237,12 +1249,13 @@ private void ProxyLogin(NetworkStream netStream, byte[] content, Dictionary headers) { lock (this) { AutoResetEvent remoteComplete = new AutoResetEvent(false); CapsClient loginRequest = new CapsClient(proxyConfig.remoteLoginUri); + OSD response = null; loginRequest.OnComplete += new CapsClient.CompleteCallback( delegate (CapsClient client, OSD result, Exception error) @@ -1257,6 +1270,7 @@ private void ProxyLoginSD(NetworkStream netStream, byte[] content) remoteComplete.Set(); } ); + loginRequest.BeginGetResponse(content, "application/llsd+xml", 1000 * 100); remoteComplete.WaitOne(1000 * 100, false); @@ -1383,7 +1397,7 @@ private void ReceiveFromSim(IAsyncResult ar) // interpret the packet according to the SL protocol Packet packet; - int end = length - 1; + int end = length; packet = Packet.BuildPacket(receiveBuffer, ref end, zeroBuffer); @@ -1721,7 +1735,7 @@ private void ReceiveFromClient(IAsyncResult ar) if (length != 0) { // interpret the packet according to the SL protocol - int end = length - 1; + int end = length; Packet packet = OpenMetaverse.Packets.Packet.BuildPacket(receiveBuffer, ref end, zeroBuffer); //OpenMetaverse.Logger.Log("-> " + packet.Type + " #" + packet.Header.Sequence, Helpers.LogLevel.Debug); @@ -2168,9 +2182,7 @@ public class CapInfo public CapInfo(string URI, IPEndPoint Sim, string CapType) - : - this(URI, Sim, CapType, CapsDataFormat.OSD, CapsDataFormat.OSD) - { } + : this(URI, Sim, CapType, CapsDataFormat.OSD, CapsDataFormat.OSD) { } public CapInfo(string URI, IPEndPoint Sim, string CapType, CapsDataFormat ReqFmt, CapsDataFormat RespFmt) { uri = URI; sim = Sim; type = CapType; reqFmt = ReqFmt; respFmt = RespFmt; @@ -2252,6 +2264,7 @@ public CapsRequest(CapInfo info) public string FullUri = string.Empty; public string Method = string.Empty; + public string ExtraInfo = string.Empty; } // XmlRpcRequestDelegate: specifies a delegate to be called for XML-RPC requests diff --git a/Programs/GridProxy/GridProxy.csproj b/Programs/GridProxy/GridProxy.csproj index 80c3589b..eed7cc7d 100644 --- a/Programs/GridProxy/GridProxy.csproj +++ b/Programs/GridProxy/GridProxy.csproj @@ -1,12 +1,12 @@  Local - net48 + Exe True 1591,1574,0419,0618 - + diff --git a/Programs/GridProxyApp/GridProxyApp.csproj b/Programs/GridProxyApp/GridProxyApp.csproj index d0b9e776..012c6617 100644 --- a/Programs/GridProxyApp/GridProxyApp.csproj +++ b/Programs/GridProxyApp/GridProxyApp.csproj @@ -1,7 +1,6 @@  Local - net48 Exe True 1591,1574,0419,0618 diff --git a/Programs/PrimWorkshop/PrimWorkshop.csproj b/Programs/PrimWorkshop/PrimWorkshop.csproj index 66e37f2d..1e773d8e 100644 --- a/Programs/PrimWorkshop/PrimWorkshop.csproj +++ b/Programs/PrimWorkshop/PrimWorkshop.csproj @@ -1,7 +1,6 @@  Local - net48 WinExe primpreview Metaverse Industries LLC diff --git a/Programs/PrimWorkshop/Properties/Resources.Designer.cs b/Programs/PrimWorkshop/Properties/Resources.Designer.cs index ab76bed3..cb5c05e7 100644 --- a/Programs/PrimWorkshop/Properties/Resources.Designer.cs +++ b/Programs/PrimWorkshop/Properties/Resources.Designer.cs @@ -1,71 +1,63 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:2.0.50727.42 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace PrimWorkshop.Properties -{ - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the StronglyTypedResourceBuilder - // class via a tool like ResGen or Visual Studio. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "2.0.0.0")] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class Resources - { - - private static global::System.Resources.ResourceManager resourceMan; - - private static global::System.Globalization.CultureInfo resourceCulture; - - [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal Resources() - { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager - { - get - { - if ((resourceMan == null)) - { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("primpreview.Properties.Resources", typeof(Resources).Assembly); - resourceMan = temp; - } - return resourceMan; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture - { - get - { - return resourceCulture; - } - set - { - resourceCulture = value; - } - } - } -} +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace PrimWorkshop.Properties { + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("PrimWorkshop.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + } +} diff --git a/Programs/PrimWorkshop/Properties/Settings.Designer.cs b/Programs/PrimWorkshop/Properties/Settings.Designer.cs index 2b903164..3e49e161 100644 --- a/Programs/PrimWorkshop/Properties/Settings.Designer.cs +++ b/Programs/PrimWorkshop/Properties/Settings.Designer.cs @@ -1,30 +1,26 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:2.0.50727.42 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace PrimWorkshop.Properties -{ - - - [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "8.0.0.0")] - internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase - { - - private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); - - public static Settings Default - { - get - { - return defaultInstance; - } - } - } -} +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace PrimWorkshop.Properties { + + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "15.5.0.0")] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { + + private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); + + public static Settings Default { + get { + return defaultInstance; + } + } + } +} diff --git a/Programs/PrimWorkshop/frmBrowser.cs b/Programs/PrimWorkshop/frmBrowser.cs index fb5cdf4b..60082cd8 100644 --- a/Programs/PrimWorkshop/frmBrowser.cs +++ b/Programs/PrimWorkshop/frmBrowser.cs @@ -20,8 +20,8 @@ public partial class frmBrowser : Form const float DEG_TO_RAD = 0.0174532925f; const uint TERRAIN_START = (uint)Int32.MaxValue + 1; - ContextMenu ExportPrimMenu; - ContextMenu ExportTerrainMenu; + ContextMenuStrip ExportPrimMenu; + ContextMenuStrip ExportTerrainMenu; GridClient Client; Camera Camera; @@ -82,14 +82,14 @@ public frmBrowser() cboServer.SelectedIndex = 0; // Context menus - ExportPrimMenu = new ContextMenu(); - ExportPrimMenu.MenuItems.Add("Download", new EventHandler(DownloadMenu_Clicked)); - ExportPrimMenu.MenuItems.Add("Download All Objects", new EventHandler(DownloadAllMenu_Clicked)); - ExportTerrainMenu = new ContextMenu(); - ExportTerrainMenu.MenuItems.Add("Teleport", new EventHandler(TeleportMenu_Clicked)); - ExportTerrainMenu.MenuItems.Add("Export Terrain", new EventHandler(ExportTerrainMenu_Clicked)); - ExportTerrainMenu.MenuItems.Add("Import Object", new EventHandler(ImportObjectMenu_Clicked)); - ExportTerrainMenu.MenuItems.Add("Import Sim", new EventHandler(ImportSimMenu_Clicked)); + ExportPrimMenu = new ContextMenuStrip(); + ExportPrimMenu.Items.Add("Download", null,new EventHandler(DownloadMenu_Clicked) ); + ExportPrimMenu.Items.Add("Download All Objects",null, new EventHandler(DownloadAllMenu_Clicked)); + ExportTerrainMenu = new ContextMenuStrip(); + ExportTerrainMenu.Items.Add("Teleport", null, new EventHandler(TeleportMenu_Clicked)); + ExportTerrainMenu.Items.Add("Export Terrain",null, new EventHandler(ExportTerrainMenu_Clicked)); + ExportTerrainMenu.Items.Add("Import Object",null, new EventHandler(ImportObjectMenu_Clicked)); + ExportTerrainMenu.Items.Add("Import Sim",null, new EventHandler(ImportSimMenu_Clicked)); // Setup a timer for updating the progress bar ProgressTimer = new System.Timers.Timer(250); @@ -556,14 +556,14 @@ private void DownloadMenu_Clicked(object sender, EventArgs e) { // This should have already been fixed in the picking processing code Console.WriteLine("Download menu clicked when a child prim is selected!"); - glControl.ContextMenu = null; + glControl.ContextMenuStrip = null; LastHit = 0; } } else { Console.WriteLine("Download menu clicked when there is no selected prim!"); - glControl.ContextMenu = null; + glControl.ContextMenuStrip = null; LastHit = 0; } } @@ -696,7 +696,7 @@ private void TeleportMenu_Clicked(object sender, EventArgs e) else { // This shouldn't have happened... - glControl.ContextMenu = null; + glControl.ContextMenuStrip = null; } } } @@ -867,7 +867,7 @@ private void StopPicking() else { LastHit = 0; - glControl.ContextMenu = null; + glControl.ContextMenuStrip = null; } } @@ -903,7 +903,7 @@ private void ProcessHits(int hits, uint[] selectBuffer) if (LastHit >= TERRAIN_START) { // Terrain was clicked on, turn off the context menu - glControl.ContextMenu = ExportTerrainMenu; + glControl.ContextMenuStrip = ExportTerrainMenu; } else { @@ -922,7 +922,7 @@ private void ProcessHits(int hits, uint[] selectBuffer) if (RenderPrimList.TryGetValue(render.Prim.ParentID, out renderParent)) { // Turn on the context menu - glControl.ContextMenu = ExportPrimMenu; + glControl.ContextMenuStrip = ExportPrimMenu; // Change the clicked on prim to the parent. Camera position stays on the // clicked child but the highlighting is applied to all the children @@ -1325,7 +1325,7 @@ private void RenderPrims() else { if (face.TextureFace.TextureID == Primitive.TextureEntry.WHITE_TEXTURE || - face.TextureFace.TextureID == UUID.Zero) + face.TextureFace.TextureID.IsZero()) { Gl.glPolygonMode(Gl.GL_FRONT, Gl.GL_FILL); } diff --git a/Programs/PrimWorkshop/frmPrimWorkshop.cs b/Programs/PrimWorkshop/frmPrimWorkshop.cs index 0569c97a..17c6df3f 100644 --- a/Programs/PrimWorkshop/frmPrimWorkshop.cs +++ b/Programs/PrimWorkshop/frmPrimWorkshop.cs @@ -275,7 +275,7 @@ private void XmlObjectLoadedHandler(OpenMetaverse.Assets.AssetPrim linkset, long { FacetedMesh mesh = null; - if (parent.Sculpt == null || parent.Sculpt.SculptTexture == UUID.Zero) + if (parent.Sculpt == null || parent.Sculpt.SculptTexture.IsZero()) mesh = Render.Plugin.GenerateFacetedMesh(parent, DetailLevel.Highest); if (mesh != null) LoadMesh(mesh, null); @@ -286,7 +286,7 @@ private void XmlObjectLoadedHandler(OpenMetaverse.Assets.AssetPrim linkset, long Primitive child = linkset.Children[i].ToPrimitive(); FacetedMesh mesh = null; - if (parent.Sculpt == null || child.Sculpt.SculptTexture == UUID.Zero) + if (parent.Sculpt == null || child.Sculpt.SculptTexture.IsZero()) mesh = Render.Plugin.GenerateFacetedMesh(child, DetailLevel.Highest); if (mesh != null) LoadMesh(mesh, null); diff --git a/Programs/VisualParamGenerator/VisualParamGenerator.csproj b/Programs/VisualParamGenerator/VisualParamGenerator.csproj index 6d4e1ad7..7a9cbd64 100644 --- a/Programs/VisualParamGenerator/VisualParamGenerator.csproj +++ b/Programs/VisualParamGenerator/VisualParamGenerator.csproj @@ -1,16 +1,11 @@  Local - net48 Exe True - 1591,1574,0419,0618 - - - \ No newline at end of file diff --git a/Programs/VoiceTest/VoiceTest.csproj b/Programs/VoiceTest/VoiceTest.csproj index 014fa068..579a6847 100644 --- a/Programs/VoiceTest/VoiceTest.csproj +++ b/Programs/VoiceTest/VoiceTest.csproj @@ -1,10 +1,8 @@  Local - net48 Exe True - 1591,1574,0419,0618 diff --git a/Programs/WinGridProxy/FormWinGridProxy.cs b/Programs/WinGridProxy/FormWinGridProxy.cs index 4193d3d7..f557f64b 100644 --- a/Programs/WinGridProxy/FormWinGridProxy.cs +++ b/Programs/WinGridProxy/FormWinGridProxy.cs @@ -138,7 +138,7 @@ void ProxyManager_OnEventMessageLog(CapsRequest req, CapsStage stage) { if (this.InvokeRequired) { - this.BeginInvoke(new MethodInvoker(() => ProxyManager_OnEventMessageLog(req, stage))); + this.BeginInvoke(new System.Windows.Forms.MethodInvoker(() => ProxyManager_OnEventMessageLog(req, stage))); } else { @@ -169,7 +169,7 @@ private void ProxyManager_OnCapabilityAdded(CapInfo cap) { if (this.InvokeRequired) { - this.BeginInvoke(new MethodInvoker(() => ProxyManager_OnCapabilityAdded(cap))); + this.BeginInvoke(new System.Windows.Forms.MethodInvoker(() => ProxyManager_OnCapabilityAdded(cap))); } else { @@ -194,7 +194,7 @@ private void ProxyManager_OnLoginResponse(object request, int rsize, Dictionary< { if (this.InvokeRequired) { - this.BeginInvoke(new MethodInvoker(() => ProxyManager_OnLoginResponse(request, rsize, headers, host, direction))); + this.BeginInvoke(new System.Windows.Forms.MethodInvoker(() => ProxyManager_OnLoginResponse(request, rsize, headers, host, direction))); } else { @@ -262,7 +262,7 @@ private void ProxyManager_OnMessageLog(CapsRequest req, CapsStage stage) { if (this.InvokeRequired) { - this.BeginInvoke(new MethodInvoker(() => ProxyManager_OnMessageLog(req, stage))); + this.BeginInvoke(new System.Windows.Forms.MethodInvoker(() => ProxyManager_OnMessageLog(req, stage))); } else { @@ -309,7 +309,7 @@ private void ProxyManager_OnMessageLog(CapsRequest req, CapsStage stage) } else { - capsSession = new SessionEvent(req.RawResponse, req.ResponseHeaders, req.Info.URI, req.Info.CapType, proto); + capsSession = new SessionEvent(req.RawResponse, req.ResponseHeaders, req.Info.URI, req.Info.CapType, proto, req.ExtraInfo); } string[] s = { PacketCounter.ToString(), capsSession.TimeStamp.ToString("HH:mm:ss.fff"), capsSession.Protocol, capsSession.Name, capsSession.Length.ToString(), capsSession.Host, capsSession.ContentType }; @@ -1040,7 +1040,7 @@ private void SearchSessions(FilterOptions opts) { if (this.InvokeRequired) { - this.BeginInvoke(new MethodInvoker(() => SearchSessions(opts))); + this.BeginInvoke(new System.Windows.Forms.MethodInvoker(() => SearchSessions(opts))); } else { @@ -1157,7 +1157,7 @@ private void timer1_Tick(object sender, EventArgs e) { if (this.InvokeRequired) { - this.BeginInvoke(new MethodInvoker(() => timer1_Tick(sender, e))); + this.BeginInvoke(new System.Windows.Forms.MethodInvoker(() => timer1_Tick(sender, e))); } else { @@ -1295,7 +1295,7 @@ void Instance_MessageLoggedEvent(object sender, MessageLoggedEventArgs e) if (InvokeRequired) { - BeginInvoke(new MethodInvoker(() => Instance_MessageLoggedEvent(sender, e))); + BeginInvoke(new System.Windows.Forms.MethodInvoker(() => Instance_MessageLoggedEvent(sender, e))); } else { diff --git a/Programs/WinGridProxy/ProxyManager.cs b/Programs/WinGridProxy/ProxyManager.cs index 4a2a7a21..ac75c4b3 100644 --- a/Programs/WinGridProxy/ProxyManager.cs +++ b/Programs/WinGridProxy/ProxyManager.cs @@ -170,30 +170,38 @@ private bool CapsHandler(CapsRequest req, CapsStage stage) /// private bool EventQueueGetHandler(CapsRequest req, CapsStage stage) { - if (stage == CapsStage.Response && req.Response is OSDMap) + if (stage == CapsStage.Response && req.Response is OSDMap map) { - OSDMap map = (OSDMap)req.Response; + if (OnEventMessageLog is null) + return false; - if (map.ContainsKey("events")) + if (map.TryGetValue("events", out OSD tmposd)) { - OSDArray eventsArray = (OSDArray)map["events"]; + OSDArray eventsArray = (OSDArray)tmposd; + int EventID = 0; + if(map.TryGetValue("id", out OSD idsd)) + EventID = idsd.AsInteger(); + + int events = eventsArray.Count; for (int i = 0; i < eventsArray.Count; i++) { OSDMap bodyMap = (OSDMap)eventsArray[i]; - if (OnEventMessageLog != null) - { - CapInfo capInfo = new CapInfo(req.Info.URI, req.Info.Sim, bodyMap["message"].AsString()); - CapsRequest capReq = new CapsRequest(capInfo); - capReq.RequestHeaders = req.RequestHeaders; - capReq.ResponseHeaders = req.ResponseHeaders; - capReq.Request = null;// req.Request; - capReq.RawRequest = null;// req.RawRequest; - capReq.RawResponse = OSDParser.SerializeLLSDXmlBytes(bodyMap); - capReq.Response = bodyMap; - - OnEventMessageLog(capReq, CapsStage.Response); - } + + CapInfo capInfo = new CapInfo(req.Info.URI, req.Info.Sim, bodyMap["message"].AsString()); + CapsRequest capReq = new CapsRequest(capInfo) + { + RequestHeaders = req.RequestHeaders, + ResponseHeaders = req.ResponseHeaders, + Request = null,// req.Request; + RawRequest = null,// req.RawRequest; + RawResponse = OSDParser.SerializeLLSDXmlBytes(bodyMap), + Response = bodyMap + }; + + capReq.ExtraInfo = $"Event iD {EventID} Message {i + 1}/{events}"; + + OnEventMessageLog?.Invoke(capReq, CapsStage.Response); } } } diff --git a/Programs/WinGridProxy/SessionTypes.cs b/Programs/WinGridProxy/SessionTypes.cs index 87f286bb..edabe8b4 100644 --- a/Programs/WinGridProxy/SessionTypes.cs +++ b/Programs/WinGridProxy/SessionTypes.cs @@ -76,7 +76,7 @@ public virtual string ToRawString(Direction direction) public virtual byte[] ToBytes(Direction direction) { - return OpenMetaverse.Utils.EmptyBytes; + return Array.Empty(); } public virtual string ToXml(Direction direction) @@ -176,7 +176,7 @@ public override Session Deserialize(byte[] bytes) byte[] packetData = map["PacketBytes"].AsBinary(); this.Length = packetData.Length; - int packetEnd = packetData.Length - 1; + int packetEnd = packetData.Length; this.Packet = Packet.BuildPacket(packetData, ref packetEnd, null); this.Name = this.Packet.Type.ToString(); return this; @@ -203,12 +203,12 @@ public SessionCaps(byte[] requestBytes, byte[] responseBytes, if (requestBytes != null) RequestBytes = requestBytes; else - RequestBytes = OpenMetaverse.Utils.EmptyBytes; + RequestBytes = Array.Empty(); if (responseBytes != null) ResponseBytes = responseBytes; else - ResponseBytes = OpenMetaverse.Utils.EmptyBytes; + ResponseBytes = Array.Empty(); RequestHeaders = requestHeaders; ResponseHeaders = responseHeaders; Protocol = proto; @@ -666,10 +666,11 @@ internal class SessionEvent : Session { private byte[] ResponseBytes; private WebHeaderCollection ResponseHeaders; + private string ExtraInfo; public SessionEvent() : base() { this.Protocol = "EventQ"; } public SessionEvent(byte[] responseBytes, WebHeaderCollection responseHeaders, - String uri, String capsKey, String proto) + String uri, String capsKey, String proto, string ExtraInfo) : base() { this.Protocol = proto; @@ -680,10 +681,8 @@ public SessionEvent(byte[] responseBytes, WebHeaderCollection responseHeaders, this.Name = capsKey; this.ContentType = responseHeaders.Get("Content-Type"); var ContentLength = responseHeaders.Get("Content-Length"); - if (ContentLength != null) - this.Length = Int32.Parse(ContentLength); - else - this.Length = 0; + this.Length = ContentLength is null ? 0 : Int32.Parse (ContentLength); + this.ExtraInfo = ExtraInfo; } public override string ToPrettyString(Direction direction) @@ -691,7 +690,15 @@ public override string ToPrettyString(Direction direction) if (direction == this.Direction) { IMessage message = null; - OSD osd = OSDParser.Deserialize(this.ResponseBytes); + OSD osd; + try + { + osd = OSDParser.Deserialize(this.ResponseBytes); + } + catch (Exception e) + { + return "Decode failed"; + } OSDMap data = (OSDMap)osd; if (data.ContainsKey("body")) message = MessageUtils.DecodeEvent(this.Name, (OSDMap)data["body"]); @@ -729,9 +736,16 @@ public override string ToRawString(Direction direction) StringBuilder result = new StringBuilder(); foreach (String key in ResponseHeaders.Keys) { - result.AppendFormat("{0} {1}" + Environment.NewLine, key, ResponseHeaders[key]); + //result.AppendFormat("{0} {1}" + Environment.NewLine, key, ResponseHeaders[key]); + result.AppendLine($"{key} {ResponseHeaders[key]}"); } result.AppendLine(); + if (!string.IsNullOrEmpty(this.ExtraInfo)) + { + result.Append(this.ExtraInfo); + result.AppendLine(); + result.AppendLine(); + } result.AppendLine(this.ToXml(direction)); return result.ToString(); } diff --git a/Programs/WinGridProxy/WinGridProxy.csproj b/Programs/WinGridProxy/WinGridProxy.csproj index 3a0ec4ae..35956453 100644 --- a/Programs/WinGridProxy/WinGridProxy.csproj +++ b/Programs/WinGridProxy/WinGridProxy.csproj @@ -1,7 +1,6 @@  Local - net48 WinExe WinGridProxy OpenMetaverse @@ -9,10 +8,11 @@ Proxy server and packet analyzer Copyright © 2015 OpenMetaverse Ninjas True - 1591,1574,0419,0618 + True - + + diff --git a/Programs/examples/Dashboard/Dashboard.csproj b/Programs/examples/Dashboard/Dashboard.csproj index cfe23f15..7ebee53d 100644 --- a/Programs/examples/Dashboard/Dashboard.csproj +++ b/Programs/examples/Dashboard/Dashboard.csproj @@ -1,7 +1,6 @@  Local - net48 WinExe True 1591,1574,0419,0618 diff --git a/Programs/examples/GridAccountant/GridAccountant.csproj b/Programs/examples/GridAccountant/GridAccountant.csproj index 86eb17c4..a1ab261b 100644 --- a/Programs/examples/GridAccountant/GridAccountant.csproj +++ b/Programs/examples/GridAccountant/GridAccountant.csproj @@ -1,11 +1,14 @@  Local - net48 WinExe 1591,1574,0419,0618 True + True + + + False diff --git a/Programs/examples/GridAccountant/frmGridAccountant.cs b/Programs/examples/GridAccountant/frmGridAccountant.cs index 4ed978b4..f7f3d39e 100644 --- a/Programs/examples/GridAccountant/frmGridAccountant.cs +++ b/Programs/examples/GridAccountant/frmGridAccountant.cs @@ -484,7 +484,7 @@ private void cmdFind_Click(object sender, System.EventArgs e) query.QueryData.QueryFlags = 1; query.QueryData.QueryID = UUID.Random(); query.QueryData.QueryStart = 0; - query.QueryData.QueryText = Utils.StringToBytes(txtFind.Text); + query.QueryData.QueryText = Utils.StringToBytes(ref txtFind.Text); query.Header.Reliable = true; Client.Network.SendPacket(query); diff --git a/Programs/examples/Heightmap/Heightmap.csproj b/Programs/examples/Heightmap/Heightmap.csproj index a54e86a1..4f7a274f 100644 --- a/Programs/examples/Heightmap/Heightmap.csproj +++ b/Programs/examples/Heightmap/Heightmap.csproj @@ -1,7 +1,6 @@  Local - net48 WinExe 1591,1574,0419,0618 True diff --git a/Programs/examples/IRCGateway/IRCGateway.csproj b/Programs/examples/IRCGateway/IRCGateway.csproj index 5dc17432..e99ef1ad 100644 --- a/Programs/examples/IRCGateway/IRCGateway.csproj +++ b/Programs/examples/IRCGateway/IRCGateway.csproj @@ -1,7 +1,6 @@  Local - net48 Exe True 1591,1574,0419,0618 diff --git a/Programs/examples/PacketDump/PacketDump.csproj b/Programs/examples/PacketDump/PacketDump.csproj index 5dc17432..2cd1263f 100644 --- a/Programs/examples/PacketDump/PacketDump.csproj +++ b/Programs/examples/PacketDump/PacketDump.csproj @@ -1,10 +1,8 @@  Local - net48 Exe True - 1591,1574,0419,0618 diff --git a/Programs/examples/TestClient/ClientManager.cs b/Programs/examples/TestClient/ClientManager.cs index ca367d42..4f893bb8 100644 --- a/Programs/examples/TestClient/ClientManager.cs +++ b/Programs/examples/TestClient/ClientManager.cs @@ -133,7 +133,7 @@ public TestClient Login(LoginDetails account) { Clients[client.Self.AgentID] = client; - if (client.MasterKey == UUID.Zero) + if (client.MasterKey.IsZero()) { UUID query = UUID.Zero; EventHandler peopleDirCallback = diff --git a/Programs/examples/TestClient/Commands/Appearance/WearCommand.cs b/Programs/examples/TestClient/Commands/Appearance/WearCommand.cs index 25ae7ff2..b49214e4 100644 --- a/Programs/examples/TestClient/Commands/Appearance/WearCommand.cs +++ b/Programs/examples/TestClient/Commands/Appearance/WearCommand.cs @@ -29,7 +29,7 @@ public override string Execute(string[] args, UUID fromAgentID) UUID folder = Client.Inventory.FindObjectByPath(Client.Inventory.Store.RootFolder.UUID, Client.Self.AgentID, target, 20 * 1000); - if (folder == UUID.Zero) + if (folder.IsZero()) { return "Outfit path " + target + " not found"; } diff --git a/Programs/examples/TestClient/Commands/Groups/JoinGroupCommand.cs b/Programs/examples/TestClient/Commands/Groups/JoinGroupCommand.cs index ada8dc39..e7fa3e41 100644 --- a/Programs/examples/TestClient/Commands/Groups/JoinGroupCommand.cs +++ b/Programs/examples/TestClient/Commands/Groups/JoinGroupCommand.cs @@ -53,7 +53,7 @@ public override string Execute(string[] args, UUID fromAgentID) GetGroupsSearchEvent.Reset(); } - if (resolvedGroupID == UUID.Zero) + if (resolvedGroupID.IsZero()) { if (string.IsNullOrEmpty(resolvedGroupName)) return "Unable to obtain UUID for group " + groupName; diff --git a/Programs/examples/TestClient/Commands/Inventory/GiveAllCommand.cs b/Programs/examples/TestClient/Commands/Inventory/GiveAllCommand.cs index dc6cff9b..7591bd5a 100644 --- a/Programs/examples/TestClient/Commands/Inventory/GiveAllCommand.cs +++ b/Programs/examples/TestClient/Commands/Inventory/GiveAllCommand.cs @@ -10,9 +10,9 @@ public GiveAllCommand(TestClient testClient) } public override string Execute(string[] args, UUID fromAgentID) - { - if (fromAgentID == UUID.Zero) - return "Unable to send money to console. This command only works when IMed."; + { + if (fromAgentID.IsZero()) + return "Unable to send money to console. This command only works when IMed."; int amount = Client.Self.Balance; Client.Self.GiveAvatarMoney(fromAgentID, Client.Self.Balance, "TestClient.GiveAll"); diff --git a/Programs/examples/TestClient/Commands/Movement/TurnToCommand.cs b/Programs/examples/TestClient/Commands/Movement/TurnToCommand.cs index 4b828a88..cd7ed14b 100644 --- a/Programs/examples/TestClient/Commands/Movement/TurnToCommand.cs +++ b/Programs/examples/TestClient/Commands/Movement/TurnToCommand.cs @@ -46,10 +46,7 @@ public override string Execute(string[] args, UUID fromAgentID) return "Usage: turnto x y z"; } - Vector3 newDirection; - newDirection.X = (float)x; - newDirection.Y = (float)y; - newDirection.Z = (float)z; + Vector3 newDirection = new Vector3((float)x, (float)y, (float)z); Client.Self.Movement.TurnToward(newDirection); Client.Self.Movement.SendUpdate(false); return "Turned to "; diff --git a/Programs/examples/TestClient/TestClient.csproj b/Programs/examples/TestClient/TestClient.csproj index 597fa047..5b9c169b 100644 --- a/Programs/examples/TestClient/TestClient.csproj +++ b/Programs/examples/TestClient/TestClient.csproj @@ -1,13 +1,11 @@  Local - net48 Exe TestClient TestClient Copyright © 2006 True - 1591,1574,0419,0618 diff --git a/Programs/examples/groupmanager/groupmanager.csproj b/Programs/examples/groupmanager/groupmanager.csproj index 359d27d6..28791e1f 100644 --- a/Programs/examples/groupmanager/groupmanager.csproj +++ b/Programs/examples/groupmanager/groupmanager.csproj @@ -1,7 +1,6 @@  Local - net48 WinExe 1591,1574,0419,0618 True diff --git a/Programs/importprimscript/importprimscript.cs b/Programs/importprimscript/importprimscript.cs index 39151115..aaf501ac 100644 --- a/Programs/importprimscript/importprimscript.cs +++ b/Programs/importprimscript/importprimscript.cs @@ -142,12 +142,12 @@ static void Main(string[] args) sculpties[i].TextureID = UploadImage(sculpties[i].TextureFile, false); // Check for failed uploads - if (sculpties[i].SculptID == UUID.Zero) + if (sculpties[i].SculptID.IsZero()) { Console.WriteLine("Sculpt map " + sculpties[i].SculptFile + " failed to upload, skipping " + sculpties[i].Name); continue; } - else if (sculpties[i].TextureID == UUID.Zero) + else if (sculpties[i].TextureID.IsZero()) { Console.WriteLine("Texture " + sculpties[i].TextureFile + " failed to upload, skipping " + sculpties[i].Name); continue; diff --git a/Programs/importprimscript/importprimscript.csproj b/Programs/importprimscript/importprimscript.csproj index 55fb072e..abdf682f 100644 --- a/Programs/importprimscript/importprimscript.csproj +++ b/Programs/importprimscript/importprimscript.csproj @@ -1,7 +1,6 @@  Local - net48 Exe 1591,1574,0419,0618 True diff --git a/Programs/mapgenerator/ProtocolManager.cs b/Programs/mapgenerator/ProtocolManager.cs index 659822a0..d986f940 100644 --- a/Programs/mapgenerator/ProtocolManager.cs +++ b/Programs/mapgenerator/ProtocolManager.cs @@ -310,17 +310,13 @@ public MapPacket Command(byte[] data) /// public MapPacket Command(ushort command, PacketFrequency frequency) { - switch (frequency) + return frequency switch { - case PacketFrequency.High: - return HighMaps[command]; - case PacketFrequency.Medium: - return MediumMaps[command]; - case PacketFrequency.Low: - return LowMaps[command]; - } - - throw new Exception("Cannot find map for command \"" + command + "\" with frequency \"" + frequency + "\""); + PacketFrequency.High => HighMaps[command], + PacketFrequency.Medium => MediumMaps[command], + PacketFrequency.Low => LowMaps[command], + _ => throw new Exception("Cannot find map for command \"" + command + "\" with frequency \"" + frequency + "\""), + }; } /// @@ -656,9 +652,9 @@ private void LoadMapFile(string mapFile) r.Close(); map.Close(); } - catch (Exception e) + catch (Exception) { - throw e; + throw; } } diff --git a/Programs/mapgenerator/mapgenerator.cs b/Programs/mapgenerator/mapgenerator.cs index 8ed2cdc5..d53c38e0 100644 --- a/Programs/mapgenerator/mapgenerator.cs +++ b/Programs/mapgenerator/mapgenerator.cs @@ -1,10 +1,11 @@ using System; using System.Collections.Generic; using System.IO; +using System.Text; namespace mapgenerator { - class mapgenerator + class MapGenerator { static void WriteFieldMember(TextWriter writer, MapField field) { @@ -94,7 +95,7 @@ static void WriteFieldFromBytes(TextWriter writer, MapField field) switch (field.Type) { case FieldType.BOOL: - writer.WriteLine(" " + field.Name + " = (bytes[i++] != 0) ? (bool)true : (bool)false;"); + writer.WriteLine(" " + field.Name + " = (Utils.BytesToByte(bytes, ref i) != 0);"); break; case FieldType.F32: writer.WriteLine(" " + field.Name + " = Utils.BytesToFloatSafepos(bytes, i); i += 4;"); @@ -113,7 +114,7 @@ static void WriteFieldFromBytes(TextWriter writer, MapField field) break; case FieldType.IPPORT: // IPPORT is big endian while U16/S16 are little endian. Go figure - writer.WriteLine(" " + field.Name + + writer.WriteLine(" " + field.Name + " = (ushort)((bytes[i++] << 8) + bytes[i++]);"); break; case FieldType.U16: @@ -141,22 +142,22 @@ static void WriteFieldFromBytes(TextWriter writer, MapField field) writer.WriteLine(" " + field.Name + " = Utils.BytesToIntSafepos(bytes, i); i +=4;"); break; case FieldType.S8: - writer.WriteLine(" " + field.Name + " = (sbyte)bytes[i++];"); + writer.WriteLine(" " + field.Name + " = (sbyte)Utils.BytesToByte(bytes, ref i);"); break; case FieldType.U64: writer.WriteLine(" " + field.Name + " = Utils.BytesToUInt64Safepos(bytes, i); i += 8;"); break; case FieldType.U8: - writer.WriteLine(" " + field.Name + " = (byte)bytes[i++];"); + writer.WriteLine(" " + field.Name + " = Utils.BytesToByte(bytes, ref i);"); break; case FieldType.Variable: if (field.Count == 1) { - writer.WriteLine(" length = bytes[i++];"); + writer.WriteLine(" length = Utils.BytesToByte(bytes, ref i);"); } else { - writer.WriteLine(" length = (bytes[i++] + (bytes[i++] << 8));"); + writer.WriteLine(" length = Utils.BytesToUInt16(bytes, i); i+=2;"); } writer.WriteLine(" " + field.Name + " = new byte[length];"); writer.WriteLine(" Buffer.BlockCopy(bytes, i, " + field.Name + ", 0, length); i += length;"); @@ -174,7 +175,7 @@ static void WriteFieldToBytes(TextWriter writer, MapField field) switch (field.Type) { case FieldType.BOOL: - writer.WriteLine("bytes[i++] = (byte)((" + field.Name + ") ? 1 : 0);"); + writer.WriteLine("Utils.ByteToBytes((byte)((" + field.Name + ") ? 1 : 0), bytes, ref i);"); break; case FieldType.F32: writer.WriteLine("Utils.FloatToBytesSafepos(" + field.Name + ", bytes, i); i += 4;"); @@ -188,8 +189,7 @@ static void WriteFieldToBytes(TextWriter writer, MapField field) break; case FieldType.IPPORT: // IPPORT is big endian while U16/S16 is little endian. Go figure - writer.WriteLine("bytes[i++] = (byte)((" + field.Name + " >> 8) % 256);"); - writer.WriteLine(" bytes[i++] = (byte)(" + field.Name + " % 256);"); + writer.WriteLine("Utils.UInt16ToBytesBig(" + field.Name + ", bytes, i); i += 2;"); break; case FieldType.U16: writer.WriteLine("Utils.UInt16ToBytes(" + field.Name + ", bytes, i); i += 2;"); @@ -209,10 +209,10 @@ static void WriteFieldToBytes(TextWriter writer, MapField field) writer.WriteLine(field.Name + ".ToBytes(bytes, i); i += 24;"); break; case FieldType.U8: - writer.WriteLine("bytes[i++] = " + field.Name + ";"); + writer.WriteLine("Utils.ByteToBytes( " + field.Name + ", bytes, ref i);"); break; case FieldType.S8: - writer.WriteLine("bytes[i++] = (byte)" + field.Name + ";"); + writer.WriteLine("Utils.ByteToBytes( (byte)" + field.Name + ", bytes, ref i);"); break; case FieldType.IPADDR: case FieldType.U32: @@ -229,13 +229,11 @@ static void WriteFieldToBytes(TextWriter writer, MapField field) //writer.Write(" "); if (field.Count == 1) { - writer.WriteLine("bytes[i++] = (byte)" + field.Name + ".Length;"); + writer.WriteLine("Utils.ByteToBytes((byte)" + field.Name + ".Length, bytes, ref i);"); } else { - writer.WriteLine("bytes[i++] = (byte)(" + field.Name + ".Length % 256);"); - writer.WriteLine(" bytes[i++] = (byte)((" + - field.Name + ".Length >> 8) % 256);"); + writer.WriteLine("Utils.UInt16ToBytes((ushort)" + field.Name + ".Length, bytes, i); i += 2;"); } writer.WriteLine(" Buffer.BlockCopy(" + field.Name + ", 0, bytes, i, " + field.Name + ".Length); " + "i += " + field.Name + ".Length;"); @@ -386,6 +384,9 @@ static void WritePacketClass(TextWriter writer, MapPacket packet) bool hasVariableBlocks = false; string sanitizedName; + bool hasSessionID = false; + bool hasAgentID = false; + //writer.WriteLine(" /// " + packet.Name + " packet"); writer.WriteLine(" /// "); writer.WriteLine(" public sealed class " + packet.Name + "Packet : Packet" + Environment.NewLine + " {"); @@ -401,7 +402,7 @@ static void WritePacketClass(TextWriter writer, MapPacket packet) " {" + Environment.NewLine + " get" + Environment.NewLine + " {"); - int length = 0; + int length; if (packet.Frequency == PacketFrequency.Low) { length = 10; } else if (packet.Frequency == PacketFrequency.Medium) { length = 8; } else { length = 7; } @@ -452,19 +453,37 @@ static void WritePacketClass(TextWriter writer, MapPacket packet) //writer.WriteLine(" /// " + block.Name + " block"); writer.WriteLine(" public " + block.Name + "Block" + ((block.Count != 1) ? "[]" : "") + " " + sanitizedName + ";"); + if(block.Name.Equals("AgentData")) + { + foreach (MapField field in block.Fields) + { + if(field.Name == "SessionID") + hasSessionID = true; + else if(field.Name == "AgentID") + hasAgentID = true; + } + } } writer.WriteLine(""); + if (hasSessionID && hasAgentID) + { + writer.WriteLine(" public override bool ValidIDs(UUID session, UUID agent) { return session.Equals(AgentData.SessionID) && agent.Equals(AgentData.AgentID); }"); + writer.WriteLine(); + } + // Default constructor //writer.WriteLine(" /// Default constructor"); writer.WriteLine(" public " + packet.Name + "Packet()" + Environment.NewLine + " {"); - writer.WriteLine(" HasVariableBlocks = " + hasVariableBlocks.ToString().ToLowerInvariant() + ";"); - writer.WriteLine(" Type = PacketType." + packet.Name + ";"); + writer.WriteLine($" HasVariableBlocks = {hasVariableBlocks.ToString().ToLowerInvariant()};"); + writer.WriteLine($" Type = PacketType.{packet.Name};"); writer.WriteLine(" Header = new Header();"); - writer.WriteLine(" Header.Frequency = PacketFrequency." + packet.Frequency + ";"); - writer.WriteLine(" Header.ID = " + packet.ID + ";"); + writer.WriteLine($" Header.Frequency = PacketFrequency.{packet.Frequency};"); + writer.WriteLine($" Header.ID ={packet.ID};"); writer.WriteLine(" Header.Reliable = true;"); // Turn the reliable flag on by default + writer.WriteLine($" NeedValidateIDs = {(hasSessionID && hasAgentID).ToString().ToLowerInvariant()};"); + if (packet.Encoded) { writer.WriteLine(" Header.Zerocoded = true;"); } foreach (MapBlock block in packet.Blocks) { @@ -556,11 +575,10 @@ static void WritePacketClass(TextWriter writer, MapPacket packet) //writer.WriteLine(" /// Constructor that takes a byte array and a prebuilt header"); writer.WriteLine(" public " + packet.Name + "Packet(Header head, byte[] bytes, ref int i): this()" + Environment.NewLine + " {" + Environment.NewLine + - " int packetEnd = bytes.Length - 1;" + Environment.NewLine + - " FromBytes(head, bytes, ref i, ref packetEnd);" + Environment.NewLine + + " FromBytes(head, bytes, ref i);" + Environment.NewLine + " }" + Environment.NewLine); - writer.WriteLine(" override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd)" + Environment.NewLine + + writer.WriteLine(" override public void FromBytes(Header header, byte[] bytes, ref int i)" + Environment.NewLine + " {"); writer.WriteLine(" Header = header;"); foreach (MapBlock block in packet.Blocks) @@ -659,7 +677,7 @@ static void WritePacketClass(TextWriter writer, MapPacket packet) if (block.Count == -1) { // Variable count block - writer.WriteLine(" bytes[i++] = (byte)" + sanitizedName + ".Length;"); + writer.WriteLine(" Utils.ByteToBytes((byte)" + sanitizedName + ".Length, bytes, ref i);"); writer.WriteLine(" for (int j = 0; j < " + sanitizedName + ".Length; j++) { " + sanitizedName + "[j].ToBytes(bytes, ref i); }"); } @@ -878,7 +896,7 @@ static void WriteToBytesMultiple(TextWriter writer, MapPacket packet) writer.WriteLine(); writer.WriteLine(" packets.Add(packet);"); - + writer.WriteLine(" } while ("); bool first = true; foreach (MapBlock block in packet.Blocks) @@ -911,7 +929,7 @@ static void WriteToBytesMultiple(TextWriter writer, MapPacket packet) static int Main(string[] args) { ProtocolManager protocol; - List unused = new List(); + HashSet unused = new(); TextWriter writer; try @@ -926,7 +944,7 @@ static int Main(string[] args) protocol = new ProtocolManager(args[0]); // Build a list of unused packets - using (StreamReader unusedReader = new StreamReader(args[2])) + using (StreamReader unusedReader = new(args[2])) { while (unusedReader.Peek() >= 0) { @@ -995,10 +1013,12 @@ static int Main(string[] args) " public PacketType Type;" + Environment.NewLine + " public abstract int Length { get; }" + Environment.NewLine + " public abstract void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[] zeroBuffer);" + Environment.NewLine + - " public abstract void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd);" + Environment.NewLine + + " public abstract void FromBytes(Header header, byte[] bytes, ref int i);" + Environment.NewLine + " public abstract byte[] ToBytes();" + Environment.NewLine + - " public abstract byte[][] ToBytesMultiple();" - ); + " public abstract byte[][] ToBytesMultiple();" + Environment.NewLine + + " public bool NeedValidateIDs;" + Environment.NewLine + + " public virtual bool ValidIDs(UUID session, UUID agent) { return true; }" + ); ; writer.WriteLine(); // Write the Packet.GetType() function @@ -1032,37 +1052,41 @@ static int Main(string[] args) " return PacketType.Default;" + Environment.NewLine + " }" + Environment.NewLine); // Write the Packet.BuildPacket(PacketType) function - writer.WriteLine(" public static Packet BuildPacket(PacketType type)"); - writer.WriteLine(" {"); + writer.WriteLine(" public static Packet BuildPacket(PacketType type)"); + writer.WriteLine(" {"); + writer.WriteLine(" switch(type)"); + writer.WriteLine(" {"); foreach (MapPacket packet in protocol.HighMaps) if (packet != null) - writer.WriteLine(" if(type == PacketType." + packet.Name + ") return new " + packet.Name + "Packet();"); + writer.WriteLine(" case PacketType." + packet.Name + ": return new " + packet.Name + "Packet();"); + foreach (MapPacket packet in protocol.MediumMaps) if (packet != null) - writer.WriteLine(" if(type == PacketType." + packet.Name + ") return new " + packet.Name + "Packet();"); + writer.WriteLine(" case PacketType." + packet.Name + ": return new " + packet.Name + "Packet();"); foreach (MapPacket packet in protocol.LowMaps) if (packet != null) - writer.WriteLine(" if(type == PacketType." + packet.Name + ") return new " + packet.Name + "Packet();"); - writer.WriteLine(" return null;" + Environment.NewLine); - writer.WriteLine(" }"); + writer.WriteLine(" case PacketType." + packet.Name + ": return new " + packet.Name + "Packet();"); + writer.WriteLine(" }"); + writer.WriteLine(" return null;"); + writer.WriteLine(" }"); // Write the Packet.BuildPacket() function writer.WriteLine(@" - public static Packet BuildPacket(byte[] packetBuffer, ref int packetEnd, byte[] zeroBuffer) + public static Packet BuildPacket(byte[] packetBuffer, ref int packetLength, byte[] zeroBuffer) { byte[] bytes; int i = 0; - Header header = Header.BuildHeader(packetBuffer, ref i, ref packetEnd); + Header header = Header.BuildHeader(packetBuffer, ref i, ref packetLength); if (header.Zerocoded) { - packetEnd = Helpers.ZeroDecode(packetBuffer, packetEnd + 1, zeroBuffer) - 1; + packetLength = Helpers.ZeroDecode(packetBuffer, packetLength, zeroBuffer); bytes = zeroBuffer; } else { bytes = packetBuffer; } - Array.Clear(bytes, packetEnd + 1, bytes.Length - packetEnd - 1); + //Array.Clear(bytes, packetEnd + 1, bytes.Length - packetEnd - 1); switch (header.Frequency) { diff --git a/Programs/mapgenerator/mapgenerator.csproj b/Programs/mapgenerator/mapgenerator.csproj index 10acbb0f..24507427 100644 --- a/Programs/mapgenerator/mapgenerator.csproj +++ b/Programs/mapgenerator/mapgenerator.csproj @@ -1,7 +1,6 @@  Local - net48 Exe True 1591,1574,0419,0618 diff --git a/Programs/mapgenerator/template.cs b/Programs/mapgenerator/template.cs index fb7f3649..0445510f 100644 --- a/Programs/mapgenerator/template.cs +++ b/Programs/mapgenerator/template.cs @@ -151,7 +151,7 @@ public void AcksToBytes(byte[] bytes, ref int i) /// /// /// - public static Header BuildHeader(byte[] bytes, ref int pos, ref int packetEnd) + public static Header BuildHeader(byte[] bytes, ref int pos, ref int packetLength) { Header header; byte flags = bytes[pos]; @@ -160,8 +160,9 @@ public static Header BuildHeader(byte[] bytes, ref int pos, ref int packetEnd) header.Reliable = (flags & Helpers.MSG_RELIABLE) != 0; header.Resent = (flags & Helpers.MSG_RESENT) != 0; header.Zerocoded = (flags & Helpers.MSG_ZEROCODED) != 0; - header.Sequence = (uint)((bytes[pos + 1] << 24) + (bytes[pos + 2] << 16) + (bytes[pos + 3] << 8) + bytes[pos + 4]); + header.Sequence = (uint)Utils.BytesToIntBig(bytes, 1); + pos += bytes[pos + 5]; // Set the frequency and packet ID number if (bytes[pos + 6] == 0xFF) { @@ -191,36 +192,78 @@ public static Header BuildHeader(byte[] bytes, ref int pos, ref int packetEnd) pos += 7; } - header.AckList = null; - CreateAckList(ref header, bytes, ref packetEnd); - - return header; - } - - /// - /// - /// - /// - /// - /// - static void CreateAckList(ref Header header, byte[] bytes, ref int packetEnd) - { if (header.AppendedAcks) { - int count = bytes[packetEnd--]; + --packetLength; + int count = bytes[packetLength]; header.AckList = new uint[count]; - for (int i = 0; i < count; i++) { - header.AckList[i] = (uint)( - (bytes[(packetEnd - i * 4) - 3] << 24) | - (bytes[(packetEnd - i * 4) - 2] << 16) | - (bytes[(packetEnd - i * 4) - 1] << 8) | - (bytes[(packetEnd - i * 4) ])); + packetLength -= 4; + header.AckList[i] = (uint)Utils.BytesToIntBig(bytes, packetLength); } + } + else + header.AckList = null; + + return header; + } + + public static bool TryParseHeader(byte[] bytes, int packetLen, out Header header, out int messageBody, out int messageEnd) + { + messageBody = 0; + messageEnd = packetLen; + header = new Header(); + + try + { + byte flags = bytes[0]; + + header.AppendedAcks = (flags & Helpers.MSG_APPENDED_ACKS) != 0; + header.Reliable = (flags & Helpers.MSG_RELIABLE) != 0; + header.Resent = (flags & Helpers.MSG_RESENT) != 0; + header.Zerocoded = (flags & Helpers.MSG_ZEROCODED) != 0; + + header.Sequence = (uint)Utils.BytesToIntBig(bytes, 1); + + messageBody += bytes[5]; + + header.ID = bytes[messageBody + 6]; + // Set the frequency and packet ID number + if (header.ID == 0xFF) + { + header.ID = bytes[messageBody + 7]; + if (header.ID == 0xFF) + { + header.Frequency = PacketFrequency.Low; + if (header.Zerocoded && bytes[messageBody + 8] == 0) + header.ID = bytes[messageBody + 10]; + else + header.ID = (ushort)((bytes[messageBody + 8] << 8) + bytes[messageBody + 9]); - packetEnd -= (count * 4); + messageBody += 10; + } + else + { + header.Frequency = PacketFrequency.Medium; + messageBody += 8; + } + } + else + { + header.Frequency = PacketFrequency.High; + messageBody += 7; + } + if (header.AppendedAcks) + { + --messageEnd; + int count = bytes[messageEnd]; + messageEnd -= 4 * count; + } + return messageEnd >= messageBody; } + catch { } + return false; } } diff --git a/README.md b/README.md new file mode 100644 index 00000000..cc148e7e --- /dev/null +++ b/README.md @@ -0,0 +1,77 @@ +A fork of libOpenMetaverse for OpenSimulator (versions >= 0.9.3.0) use + +For OpenSimulator versions 0.9.1.x and 0.9.2.x use branch Mono-Net4x + +For OpenSimulator older versions use the original Library + + `https://github.com/openmetaversefoundation/libopenmetaverse` + + +# git clone + +get or update source from git + + `git clone https://bitbucket.org/opensimulator/libopenmetaverse.git` + +or + + `git clone https://github.com/opensim/libopenmetaverse.git` + +or + + `git clone https://github.com/UbitUmarov/libopenmetaverse.git` + + +# Building on Windows + +## Requirements + To building under Windows, the following is required: + + * [dotnet 8.0 SDK](https://dotnet.microsoft.com/en-us/download/dotnet/8.0) + +optionally also + + * [Visual Studio](https://visualstudio.microsoft.com/vs/features/net-development/), version 2022 or later + + +### Building + To create the project files, run + + `runprebuild.bat` + +run + + `compile.bat` + +Or load the generated OpenMetaverse.sln into Visual Studio and build the solution. + + + +# Building on Linux / Mac + +## Requirements + + * [dotnet 8.0 SDK](https://dotnet.microsoft.com/en-us/download/dotnet/8.0) + * libgdiplus + + if you have mono 6.x complete, you already have libgdiplus, otherwise you need to install it + using a package manager for your operating system, like apt, brew, macports, etc + for example on debian: + + `apt-get update && apt-get install -y apt-utils libgdiplus libc6-dev` + +### Building + To create the project files, run: + + `./runprebuild.sh` + + then run + + `compile.bat` + + +### Current building problems +several projects will only compile and run on windows +many of those project also need fixes on their project files to set the framework to netxxx-windows and allow windows forms + +For now, runprebuild.(bat/sh) will only create projects for the dlls needed for OpenSimulator. diff --git a/README.txt b/README.txt deleted file mode 100644 index de4135af..00000000 --- a/README.txt +++ /dev/null @@ -1,55 +0,0 @@ -libOpenMetaverse Library Fork for OpenSimulator (version >= 0.9.1.0) - - -Finding Help ------------- - -If you need any help we have a couple of resources, the primary one being -the #opensim-dev IRC channel on Freenode. - - -Getting started on Windows -==================================================================================== - - -Prerequisites (all Freely Available) --------------------------------------- - -Microsoft .NET Framework 4.6 -Visual Visual Studio (community) 2017 - -Compiling ---------- -1. Open Explorer and browse to the directory you extracted the source distribution to -2. Double click the runprebuild.bat file, this will create the necessary solution and project files -3. open the solution OpenMetaverse.sln from within Visual Studio -4. From the Build Menu choose Build Solution (or press the F6 Key) - -The library, example applications and tools will be in the bin directory - - -Getting started on Linux -==================================================================================== - -Prerequisites Needed --------------------- - -mono 5.x - https://www.mono-project.com/download/stable/#download-lin -(install mono.complete) - -Compiling ---------- -1. Change to the directory you extracted the source distribution to -2. run the prebuild file: % sh runprebuild.sh - This will generate the solution files for xbuild - -using xbuild -3. Compile the solution with the command: % xbuild OpenMetaverse.sln -using msbuild -3. Compile the solution with the command: % msbuild OpenMetaverse.sln - -The library, example applications and tools will be in the bin directory - - -Happy fiddling, --- OpenMetaverse Ninjas - diff --git a/bin/ICSharpCode.SharpZipLib.dll b/bin/ICSharpCode.SharpZipLib.dll deleted file mode 100755 index 536337c2..00000000 Binary files a/bin/ICSharpCode.SharpZipLib.dll and /dev/null differ diff --git a/bin/OpenMetaverse.dll.config b/bin/OpenMetaverse.dll.config deleted file mode 100755 index 6b7b9993..00000000 --- a/bin/OpenMetaverse.dll.config +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/bin/XMLRPC.dll b/bin/XMLRPC.dll deleted file mode 100755 index 2189d090..00000000 Binary files a/bin/XMLRPC.dll and /dev/null differ diff --git a/bin/libopenjpeg-dotnet-2-1.5.0-dotnet-1-i686.so b/bin/libopenjpeg-dotnet-2-1.5.0-dotnet-1-i686.so deleted file mode 100755 index 193eca4b..00000000 Binary files a/bin/libopenjpeg-dotnet-2-1.5.0-dotnet-1-i686.so and /dev/null differ diff --git a/bin/libopenjpeg-dotnet-2-1.5.0-dotnet-1-x86_64.so b/bin/libopenjpeg-dotnet-2-1.5.0-dotnet-1-x86_64.so deleted file mode 100755 index 7a9bdfcd..00000000 Binary files a/bin/libopenjpeg-dotnet-2-1.5.0-dotnet-1-x86_64.so and /dev/null differ diff --git a/bin/libopenjpeg-dotnet-2-1.5.0-dotnet-1.dylib b/bin/libopenjpeg-dotnet-2-1.5.0-dotnet-1.dylib deleted file mode 100755 index 91f7264f..00000000 Binary files a/bin/libopenjpeg-dotnet-2-1.5.0-dotnet-1.dylib and /dev/null differ diff --git a/bin/log4net.dll b/bin/log4net.dll deleted file mode 100755 index ffc57e11..00000000 Binary files a/bin/log4net.dll and /dev/null differ diff --git a/bin/nunit.framework.dll b/bin/nunit.framework.dll deleted file mode 100755 index d68d9f20..00000000 Binary files a/bin/nunit.framework.dll and /dev/null differ diff --git a/bin/openjpeg-dotnet-x86_64.dll b/bin/openjpeg-dotnet-x86_64.dll deleted file mode 100755 index 9e8cd215..00000000 Binary files a/bin/openjpeg-dotnet-x86_64.dll and /dev/null differ diff --git a/bin/openjpeg-dotnet.dll b/bin/openjpeg-dotnet.dll deleted file mode 100755 index 6377b8d9..00000000 Binary files a/bin/openjpeg-dotnet.dll and /dev/null differ diff --git a/bin/openmetaverse_data/avatar_skeleton.xml b/bin/openmetaverse_data/avatar_skeleton.xml deleted file mode 100644 index 6b07bbc1..00000000 --- a/bin/openmetaverse_data/avatar_skeleton.xml +++ /dev/null @@ -1,81 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/bin/zlib.net.dll b/bin/zlib.net.dll deleted file mode 100755 index 9d156547..00000000 Binary files a/bin/zlib.net.dll and /dev/null differ diff --git a/build-debug.sh b/build-debug.sh deleted file mode 100644 index dde746a5..00000000 --- a/build-debug.sh +++ /dev/null @@ -1 +0,0 @@ -msbuild /t:Build /p:Configuration=Debug diff --git a/build-release.sh b/build-release.sh deleted file mode 100644 index 8ea14c13..00000000 --- a/build-release.sh +++ /dev/null @@ -1 +0,0 @@ -msbuild /t:Build /p:Configuration=Release diff --git a/data/message_template.msg b/data/message_template.msg index 07a08658..8235623e 100755 --- a/data/message_template.msg +++ b/data/message_template.msg @@ -4353,6 +4353,9 @@ version 2.0 } // ScriptTeleportRequest +// Interestingly, this message does not actually "Request a Teleport" +// on the viewer. Instead it opens the world map and places a beacon +// at the indicated location. // reliable { ScriptTeleportRequest Low 195 Trusted Unencoded @@ -4363,6 +4366,10 @@ version 2.0 { SimPosition LLVector3 } { LookAt LLVector3 } } + { + Options Variable + { Flags U32 } + } } @@ -5780,6 +5787,24 @@ version 2.0 } } +// GenericStreamingMessage +// Optimized generic message for streaming arbitrary data to viewer +// Avoid payloads over 7KB (8KB ceiling) +// Method -- magic number indicating method to use to decode payload: +// 0x4175 - GLTF material override data +// Payload -- data to be decoded +{ + GenericStreamingMessage High 31 Trusted Unencoded + { + MethodData Single + { Method U16 } + } + + { + DataBlock Single + { Data Variable 2 } + } +} // LargeGenericMessage // Similar to the above messages, but can handle larger payloads and serialized // LLSD. Uses HTTP transport diff --git a/mapgen.bat b/mapgen.bat index ab69895a..2cc00d62 100644 --- a/mapgen.bat +++ b/mapgen.bat @@ -1 +1,2 @@ -"bin/mapgenerator.exe" data/message_template.msg Programs/mapgenerator/template.cs Programs/mapgenerator/unusedpackets.txt OpenMetaverse/_Packets_.cs \ No newline at end of file +rem "bin/mapgenerator.exe" data/message_template.msg Programs/mapgenerator/template.cs Programs/mapgenerator/unusedpackets.txt OpenMetaverse/_Packets_.cs +"bin/mapgenerator.exe" data/message_template.msg Programs/mapgenerator/template.cs Programs/mapgenerator/unusedpackets.txt _Packets_.cs \ No newline at end of file diff --git a/nuget.config b/nuget.config new file mode 100644 index 00000000..ec65b0db --- /dev/null +++ b/nuget.config @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + diff --git a/openjpeg-dotnet/DllOpenJPEG.sln b/openjpeg-dotnet/DllOpenJPEG.sln deleted file mode 100644 index b6c741d4..00000000 --- a/openjpeg-dotnet/DllOpenJPEG.sln +++ /dev/null @@ -1,26 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 10.00 -# Visual Studio 2008 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "DllOpenJPEG", "DllOpenJPEG.vcproj", "{89AC992C-5E2C-4E6B-A453-61C1DF446216}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Win32 = Debug|Win32 - Debug|Win64 = Debug|Win64 - Release|Win32 = Release|Win32 - Release|Win64 = Release|Win64 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {89AC992C-5E2C-4E6B-A453-61C1DF446216}.Debug|Win32.ActiveCfg = Debug|Win32 - {89AC992C-5E2C-4E6B-A453-61C1DF446216}.Debug|Win32.Build.0 = Debug|Win32 - {89AC992C-5E2C-4E6B-A453-61C1DF446216}.Debug|Win64.ActiveCfg = Debug|x64 - {89AC992C-5E2C-4E6B-A453-61C1DF446216}.Debug|Win64.Build.0 = Debug|x64 - {89AC992C-5E2C-4E6B-A453-61C1DF446216}.Release|Win32.ActiveCfg = Release|Win32 - {89AC992C-5E2C-4E6B-A453-61C1DF446216}.Release|Win32.Build.0 = Release|Win32 - {89AC992C-5E2C-4E6B-A453-61C1DF446216}.Release|Win64.ActiveCfg = Release|x64 - {89AC992C-5E2C-4E6B-A453-61C1DF446216}.Release|Win64.Build.0 = Release|x64 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/openjpeg-dotnet/DllOpenJPEG.vcproj b/openjpeg-dotnet/DllOpenJPEG.vcproj deleted file mode 100644 index 15ca4f3b..00000000 --- a/openjpeg-dotnet/DllOpenJPEG.vcproj +++ /dev/null @@ -1,1227 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/openjpeg-dotnet/Makefile b/openjpeg-dotnet/Makefile deleted file mode 100644 index 2e9383f9..00000000 --- a/openjpeg-dotnet/Makefile +++ /dev/null @@ -1,95 +0,0 @@ -# Linux makefile for OpenJPEG - -VER_MAJOR = 2 -VER_MINOR = 1.5.0-dotnet-1 - -SRCS = ./libopenjpeg/bio.c ./libopenjpeg/cio.c ./libopenjpeg/dwt.c ./libopenjpeg/event.c ./libopenjpeg/image.c ./libopenjpeg/j2k.c ./libopenjpeg/j2k_lib.c ./libopenjpeg/jp2.c ./libopenjpeg/jpt.c ./libopenjpeg/mct.c ./libopenjpeg/mqc.c ./libopenjpeg/openjpeg.c ./libopenjpeg/pi.c ./libopenjpeg/raw.c ./libopenjpeg/t1.c ./libopenjpeg/t2.c ./libopenjpeg/tcd.c ./libopenjpeg/tgt.c -CPPSRCS = ./dotnet/dotnet.cpp -INCLS = ./libopenjpeg/bio.h ./libopenjpeg/cio.h ./libopenjpeg/dwt.h ./libopenjpeg/event.h ./libopenjpeg/fix.h ./libopenjpeg/image.h ./libopenjpeg/int.h ./libopenjpeg/j2k.h ./libopenjpeg/j2k_lib.h ./libopenjpeg/jp2.h ./libopenjpeg/jpt.h ./libopenjpeg/mct.h ./libopenjpeg/mqc.h ./libopenjpeg/openjpeg.h ./libopenjpeg/pi.h ./libopenjpeg/raw.h ./libopenjpeg/t1.h ./libopenjpeg/t2.h ./libopenjpeg/tcd.h ./libopenjpeg/tgt.h ./libopenjpeg/opj_malloc.h ./libopenjpeg/opj_includes.h ./dotnet/dotnet.h -INCLUDE = -Ilibopenjpeg - -# General configuration variables: -CC = gcc -AR = ar - -OSNAME = $(shell uname -s) - -ifeq ($(OSNAME), Linux) - ARCH = $(shell uname -m) - ARCHSET = 0 - ifeq ($(ARCH), x86_64) - ARCH=-x86_64 - ARCHFLAGS=-m64 - ARCHSET=1 - endif - ifeq ($(ARCH), s390x) - ARCH=-s390x - ARCHFLAGS=-m64 - ARCHSET=1 - endif - ifeq ($(ARCH), ppc64) - ARCH=-ppc64 - ARCHFLAGS=-m64 - ARCHSET=1 - endif - ifeq ($(ARCHSET), 0) - ARCH=-i686 - ARCHFLAGS=-m32 - endif -endif - - -# Converts cr/lf to just lf -DOS2UNIX = dos2unix - -COMPILERFLAGS = -O3 -fPIC $(ARCHFLAGS) -LIBRARIES = -lstdc++ - -MODULES = $(SRCS:.c=.o) -CPPMODULES = $(CPPSRCS:.cpp=.o) -CFLAGS = $(COMPILERFLAGS) $(INCLUDE) - -TARGET = openjpeg-dotnet -SHAREDLIB = lib$(TARGET)-$(VER_MAJOR)-$(VER_MINOR)$(ARCH).so -LIBNAME = lib$(TARGET).so.$(VER_MAJOR) - -default: all - -# Force 32 bit binary on 64 bit platform -32bit: OpenJPEG - -all: OpenJPEG - -dist: OpenJPEG - install -d ../bin - cp $(SHAREDLIB) ../bin/ - -dos2unix: - @$(DOS2UNIX) $(SRCS) $(INCLS) - -OpenJPEG: $(SHAREDLIB) - -$(MODULES): %.o: %.c - $(CC) $(CFLAGS) -c $< -o $@ - -$(CPPMODULES): %.o: %.cpp - $(CC) $(CFLAGS) -c $< -o $@ - -$(SHAREDLIB): $(MODULES) $(CPPMODULES) - $(CC) $(ARCHFLAGS) -s -shared -Wl,-soname,$(LIBNAME) -o $@ $(MODULES) $(CPPMODULES) $(LIBRARIES) - -install: OpenJPEG - install -d ../bin - cp $(SHAREDLIB) ../bin/ - -clean: - rm -rf core dist/ u2dtmp* $(MODULES) $(CPPMODULES) $(SHAREDLIB) $(LIBNAME) - -osx: - make -f Makefile.osx - -osxinstall: - make -f Makefile.osx install - -osxclean: - make -f Makefile.osx clean diff --git a/openjpeg-dotnet/Makefile.osx b/openjpeg-dotnet/Makefile.osx deleted file mode 100644 index cfa6e8a2..00000000 --- a/openjpeg-dotnet/Makefile.osx +++ /dev/null @@ -1,65 +0,0 @@ -# MacOSX makefile for OpenJPEG - -VER_MAJOR = 2 -VER_MINOR = 1.5.0-dotnet-1 - -SRCS = ./libopenjpeg/bio.c ./libopenjpeg/cio.c ./libopenjpeg/dwt.c ./libopenjpeg/event.c ./libopenjpeg/image.c ./libopenjpeg/j2k.c ./libopenjpeg/j2k_lib.c ./libopenjpeg/jp2.c ./libopenjpeg/jpt.c ./libopenjpeg/mct.c ./libopenjpeg/mqc.c ./libopenjpeg/openjpeg.c ./libopenjpeg/pi.c ./libopenjpeg/raw.c ./libopenjpeg/t1.c ./libopenjpeg/t2.c ./libopenjpeg/tcd.c ./libopenjpeg/tgt.c ./libopenjpeg/cidx_manager.c ./libopenjpeg/phix_manager.c ./libopenjpeg/ppix_manager.c ./libopenjpeg/thix_manager.c ./libopenjpeg/tpix_manager.c -CPPSRCS = ./dotnet/dotnet.cpp -INCLS = ./libopenjpeg/bio.h ./libopenjpeg/cio.h ./libopenjpeg/dwt.h ./libopenjpeg/event.h ./libopenjpeg/fix.h ./libopenjpeg/image.h ./libopenjpeg/int.h ./libopenjpeg/j2k.h ./libopenjpeg/j2k_lib.h ./libopenjpeg/jp2.h ./libopenjpeg/jpt.h ./libopenjpeg/mct.h ./libopenjpeg/mqc.h ./libopenjpeg/openjpeg.h ./libopenjpeg/pi.h ./libopenjpeg/raw.h ./libopenjpeg/t1.h ./libopenjpeg/t2.h ./libopenjpeg/tcd.h ./libopenjpeg/tgt.h ./libopenjpeg/opj_includes.h ./dotnet/dotnet.h ./libopenjpeg/cidx_manager.h ./libopenjpeg/indexbox_manager.h -INCLUDE = -Ilibopenjpeg - -# General configuration variables: -CC = gcc -LIBTOOLSTAT = libtool -LIBTOOLDYN = g++ - - -COMPILERFLAGS = -O3 -fPIC -m32 - -MODULES = $(SRCS:.c=.o) -CPPMODULES = $(CPPSRCS:.cpp=.o) -CFLAGS = $(COMPILERFLAGS) $(INCLUDE) - -TARGET = openjpeg-dotnet -SHAREDLIB = lib$(TARGET)-$(VER_MAJOR)-$(VER_MINOR).dylib -LIBNAME = lib$(TARGET).dylib - - - - -default: all - -all: OpenJPEG - -dos2unix: - @$(DOS2UNIX) $(SRCS) $(INCLS) - -dist: OpenJPEG - install -d ../bin - cp $(SHAREDLIB) ../bin/ - -OpenJPEG: $(STATICLIB) $(SHAREDLIB) - -.c.o: - $(CC) $(CFLAGS) -c $< -o $@ - -$(STATICLIB): $(MODULES) - $(LIBTOOLSTAT) -o $@ $(MODULES) - - -.cpp.o: - $(CC) $(CFLAGS) -c $< -o $@ - -$(SHAREDLIB): $(MODULES) $(CPPMODULES) - $(LIBTOOLDYN) -m32 -dynamiclib -o $@ $(MODULES) $(CPPMODULES) $(LIBRARIES) - - - -install: - install -d ../bin - cp $(SHAREDLIB) ../bin/ - - -clean: - rm -rf core dist/ u2dtmp* $(MODULES) $(STATICLIB) $(SHAREDLIB) $(LIBNAME) - diff --git a/openjpeg-dotnet/OpenJPEG.rc b/openjpeg-dotnet/OpenJPEG.rc deleted file mode 100644 index aa893eb2..00000000 --- a/openjpeg-dotnet/OpenJPEG.rc +++ /dev/null @@ -1,110 +0,0 @@ -//Microsoft Developer Studio generated resource script. -// -#include "resource.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -//#include "afxres.h" -#include "windows.h" - -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// French (France) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_FRA) -#ifdef _WIN32 -LANGUAGE LANG_FRENCH, SUBLANG_FRENCH -#pragma code_page(1252) -#endif //_WIN32 - -#ifndef _MAC -///////////////////////////////////////////////////////////////////////////// -// -// Version -// - -VS_VERSION_INFO VERSIONINFO - FILEVERSION 1,1,0,0 - PRODUCTVERSION 1,1,0,0 - FILEFLAGSMASK 0x3fL -#ifdef _DEBUG - FILEFLAGS 0x1L -#else - FILEFLAGS 0x0L -#endif - FILEOS 0x40004L - FILETYPE 0x2L - FILESUBTYPE 0x0L -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "000004b0" - BEGIN - VALUE "Comments", "The OpenJPEG library is an open-source JPEG 2000 codec. \0" - VALUE "CompanyName", "OpenJPEG\0" - VALUE "FileDescription", "OpenJPEG\0" - VALUE "FileVersion", "1, 1, 0, 0\0" - VALUE "InternalName", "OpenJPEG\0" - VALUE "LegalCopyright", "Copyright © 2002-2007, Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium\0" - VALUE "LegalTrademarks", "See http://www.openjpeg.org for details\0" - VALUE "OriginalFilename", "OpenJPEG.dll\0" - VALUE "PrivateBuild", "\0" - VALUE "ProductName", "OpenJPEG\0" - VALUE "ProductVersion", "1, 1, 0, 0\0" - VALUE "SpecialBuild", "\0" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x0, 1200 - END -END - -#endif // !_MAC - - -#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 - "\r\n" - "\0" -END - -#endif // APSTUDIO_INVOKED - -#endif // French (France) resources -///////////////////////////////////////////////////////////////////////////// - - - -#ifndef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 3 resource. -// - - -///////////////////////////////////////////////////////////////////////////// -#endif // not APSTUDIO_INVOKED - diff --git a/openjpeg-dotnet/Resource.h b/openjpeg-dotnet/Resource.h deleted file mode 100644 index 285c3c07..00000000 --- a/openjpeg-dotnet/Resource.h +++ /dev/null @@ -1,17 +0,0 @@ -//{{NO_DEPENDENCIES}} -// Microsoft Visual C++ generated include file. -// Used by foob.rc -// - -#define IDS_APP_TITLE 103 - -// Next default values for new objects -// -#ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 101 -#define _APS_NEXT_COMMAND_VALUE 40001 -#define _APS_NEXT_CONTROL_VALUE 1000 -#define _APS_NEXT_SYMED_VALUE 101 -#endif -#endif diff --git a/openjpeg-dotnet/dotnet/dotnet.cpp b/openjpeg-dotnet/dotnet/dotnet.cpp deleted file mode 100644 index c892fdc0..00000000 --- a/openjpeg-dotnet/dotnet/dotnet.cpp +++ /dev/null @@ -1,243 +0,0 @@ -// This is the main DLL file. - -#include "dotnet.h" -extern "C" { -#include "../libopenjpeg/openjpeg.h" -} -#include - -bool DotNetAllocEncoded64(MarshalledImage* image) -{ - return DotNetAllocEncoded(image); -} - -bool DotNetAllocEncoded(MarshalledImage* image) -{ - DotNetFree(image); - - try - { - image->encoded = new unsigned char[image->length]; - image->decoded = 0; - } - catch (...) - { - return false; - } - - return true; -} -bool DotNetAllocDecoded64(MarshalledImage* image) -{ - return DotNetAllocDecoded(image); -} - -bool DotNetAllocDecoded(MarshalledImage* image) -{ - DotNetFree(image); - - try - { - image->decoded = new unsigned char[image->width * image->height * image->components]; - image->encoded = 0; - } - catch (...) - { - return false; - } - - return true; -} -void DotNetFree64(MarshalledImage* image) -{ - DotNetFree(image); -} - -void DotNetFree(MarshalledImage* image) -{ - if (image->encoded != 0) delete[] image->encoded; - if (image->decoded != 0) delete[] image->decoded; -} - -bool DotNetEncode64(MarshalledImage* image, bool lossless) -{ - return DotNetEncode(image, lossless); -} - -bool DotNetEncode(MarshalledImage* image, bool lossless) -{ - try - { - opj_cparameters cparameters; - opj_set_default_encoder_parameters(&cparameters); - cparameters.cp_disto_alloc = 1; - - if (lossless) - { - cparameters.tcp_numlayers = 1; - cparameters.tcp_rates[0] = 0; - } - else - { - cparameters.tcp_numlayers = 5; - cparameters.tcp_rates[0] = 1920; - cparameters.tcp_rates[1] = 480; - cparameters.tcp_rates[2] = 120; - cparameters.tcp_rates[3] = 30; - cparameters.tcp_rates[4] = 10; - cparameters.irreversible = 1; - if (image->components >= 3) - { - cparameters.tcp_mct = 1; - } - } - - cparameters.cp_comment = (char*)""; - - opj_image_comptparm comptparm[5]; - - for (int i = 0; i < image->components; i++) - { - comptparm[i].bpp = 8; - comptparm[i].prec = 8; - comptparm[i].sgnd = 0; - comptparm[i].dx = 1; - comptparm[i].dy = 1; - comptparm[i].x0 = 0; - comptparm[i].y0 = 0; - comptparm[i].w = image->width; - comptparm[i].h = image->height; - } - - opj_image_t* jp2_image = opj_image_create(image->components, comptparm, CLRSPC_SRGB); - if (jp2_image == NULL) - throw "opj_image_create failed"; - - jp2_image->x0 = 0; - jp2_image->y0 = 0; - jp2_image->x1 = image->width; - jp2_image->y1 = image->height; - int n = image->width * image->height; - - for (int i = 0; i < image->components; i++) - std::copy(image->decoded + i * n, image->decoded + (i + 1) * n, jp2_image->comps[i].data); - - opj_cinfo* cinfo = opj_create_compress(CODEC_J2K); - opj_setup_encoder(cinfo, &cparameters, jp2_image); - opj_cio* cio = opj_cio_open((opj_common_ptr)cinfo, NULL, 0); - if (cio == NULL) - throw "opj_cio_open failed"; - - if (!opj_encode(cinfo, cio, jp2_image, cparameters.index)) - return false; - - image->length = cio_tell(cio); - image->encoded = new unsigned char[image->length]; - std::copy(cio->buffer, cio->buffer + image->length, image->encoded); - - opj_image_destroy(jp2_image); - opj_destroy_compress(cinfo); - opj_cio_close(cio); - - return true; - } - - catch (...) - { - return false; - } -} - -bool DotNetDecode64(MarshalledImage* image) -{ - return DotNetDecode(image); -} - -bool DotNetDecode(MarshalledImage* image) -{ - opj_dparameters dparameters; - - try - { - opj_set_default_decoder_parameters(&dparameters); - opj_dinfo_t* dinfo = opj_create_decompress(CODEC_J2K); - opj_setup_decoder(dinfo, &dparameters); - opj_cio* cio = opj_cio_open((opj_common_ptr)dinfo, image->encoded, image->length); - - opj_image* jp2_image = opj_decode(dinfo, cio); // decode happens here - if (jp2_image == NULL) - throw "opj_decode failed"; - - image->width = jp2_image->x1 - jp2_image->x0; - image->height = jp2_image->y1 - jp2_image->y0; - image->components = jp2_image->numcomps; - int n = image->width * image->height; - image->decoded = new unsigned char[n * image->components]; - - for (int i = 0; i < image->components; i++) - std::copy(jp2_image->comps[i].data, jp2_image->comps[i].data + n, image->decoded + i * n); - - opj_image_destroy(jp2_image); - opj_destroy_decompress(dinfo); - opj_cio_close(cio); - - return true; - } - catch (...) - { - return false; - } -} -bool DotNetDecodeWithInfo64(MarshalledImage* image) -{ - return DotNetDecodeWithInfo(image); -} - -bool DotNetDecodeWithInfo(MarshalledImage* image) -{ - opj_dparameters dparameters; - opj_codestream_info_t info; - - try - { - opj_set_default_decoder_parameters(&dparameters); - opj_dinfo_t* dinfo = opj_create_decompress(CODEC_J2K); - opj_setup_decoder(dinfo, &dparameters); - opj_cio* cio = opj_cio_open((opj_common_ptr)dinfo, image->encoded, image->length); - - opj_image* jp2_image = opj_decode_with_info(dinfo, cio, &info); // decode happens here - if (jp2_image == NULL) - throw "opj_decode failed"; - - // maximum number of decompositions - int max_numdecompos = 0; - for (int compno = 0; compno < info.numcomps; compno++) - { - if (max_numdecompos < info.numdecompos[compno]) - max_numdecompos = info.numdecompos[compno]; - } - - image->width = jp2_image->x1 - jp2_image->x0; - image->height = jp2_image->y1 - jp2_image->y0; - image->layers = info.numlayers; - image->resolutions = max_numdecompos + 1; - image->components = info.numcomps; - image->packet_count = info.packno; - image->packets = info.tile->packet; - int n = image->width * image->height; - image->decoded = new unsigned char[n * image->components]; - - for (int i = 0; i < image->components; i++) - std::copy(jp2_image->comps[i].data, jp2_image->comps[i].data + n, image->decoded + i * n); - - opj_image_destroy(jp2_image); - opj_destroy_decompress(dinfo); - opj_cio_close(cio); - - return true; - } - catch (...) - { - return false; - } -} diff --git a/openjpeg-dotnet/dotnet/dotnet.h b/openjpeg-dotnet/dotnet/dotnet.h deleted file mode 100644 index c0f9e8f5..00000000 --- a/openjpeg-dotnet/dotnet/dotnet.h +++ /dev/null @@ -1,44 +0,0 @@ - -#ifndef LIBSL_H -#define LIBSL_H - -#include "../libopenjpeg/openjpeg.h" - -struct MarshalledImage -{ - unsigned char* encoded; - int length; - int dummy; // padding for 64-bit alignment - - unsigned char* decoded; - int width; - int height; - int layers; - int resolutions; - int components; - int packet_count; - opj_packet_info_t* packets; -}; - -#ifdef WIN32 -#define DLLEXPORT extern "C" __declspec(dllexport) -#else -#define DLLEXPORT extern "C" -#endif - -// uncompresed images are raw RGBA 8bit/channel -DLLEXPORT bool DotNetEncode(MarshalledImage* image, bool lossless); -DLLEXPORT bool DotNetDecode(MarshalledImage* image); -DLLEXPORT bool DotNetDecodeWithInfo(MarshalledImage* image); -DLLEXPORT bool DotNetAllocEncoded(MarshalledImage* image); -DLLEXPORT bool DotNetAllocDecoded(MarshalledImage* image); -DLLEXPORT void DotNetFree(MarshalledImage* image); - -DLLEXPORT bool DotNetEncode64(MarshalledImage* image, bool lossless); -DLLEXPORT bool DotNetDecode64(MarshalledImage* image); -DLLEXPORT bool DotNetDecodeWithInfo64(MarshalledImage* image); -DLLEXPORT bool DotNetAllocEncoded64(MarshalledImage* image); -DLLEXPORT bool DotNetAllocDecoded64(MarshalledImage* image); -DLLEXPORT void DotNetFree64(MarshalledImage* image); - -#endif diff --git a/openjpeg-dotnet/libopenjpeg/bio.c b/openjpeg-dotnet/libopenjpeg/bio.c deleted file mode 100644 index 4c02f464..00000000 --- a/openjpeg-dotnet/libopenjpeg/bio.c +++ /dev/null @@ -1,187 +0,0 @@ -/* - * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium - * Copyright (c) 2002-2007, Professor Benoit Macq - * Copyright (c) 2001-2003, David Janssens - * Copyright (c) 2002-2003, Yannick Verschueren - * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe - * Copyright (c) 2005, Herve Drolon, FreeImage Team - * 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 "opj_includes.h" - -/** @defgroup BIO BIO - Individual bit input-output stream */ -/*@{*/ - -/** @name Local static functions */ -/*@{*/ - -/** -Write a bit -@param bio BIO handle -@param b Bit to write (0 or 1) -*/ -static void bio_putbit(opj_bio_t *bio, int b); -/** -Read a bit -@param bio BIO handle -@return Returns the read bit -*/ -static int bio_getbit(opj_bio_t *bio); -/** -Write a byte -@param bio BIO handle -@return Returns 0 if successful, returns 1 otherwise -*/ -static int bio_byteout(opj_bio_t *bio); -/** -Read a byte -@param bio BIO handle -@return Returns 0 if successful, returns 1 otherwise -*/ -static int bio_bytein(opj_bio_t *bio); - -/*@}*/ - -/*@}*/ - -/* -========================================================== - local functions -========================================================== -*/ - -static int bio_byteout(opj_bio_t *bio) { - bio->buf = (bio->buf << 8) & 0xffff; - bio->ct = bio->buf == 0xff00 ? 7 : 8; - if (bio->bp >= bio->end) { - return 1; - } - *bio->bp++ = bio->buf >> 8; - return 0; -} - -static int bio_bytein(opj_bio_t *bio) { - bio->buf = (bio->buf << 8) & 0xffff; - bio->ct = bio->buf == 0xff00 ? 7 : 8; - if (bio->bp >= bio->end) { - return 1; - } - bio->buf |= *bio->bp++; - return 0; -} - -static void bio_putbit(opj_bio_t *bio, int b) { - if (bio->ct == 0) { - bio_byteout(bio); - } - bio->ct--; - bio->buf |= b << bio->ct; -} - -static int bio_getbit(opj_bio_t *bio) { - if (bio->ct == 0) { - bio_bytein(bio); - } - bio->ct--; - return (bio->buf >> bio->ct) & 1; -} - -/* -========================================================== - Bit Input/Output interface -========================================================== -*/ - -opj_bio_t* bio_create(void) { - opj_bio_t *bio = (opj_bio_t*)opj_malloc(sizeof(opj_bio_t)); - return bio; -} - -void bio_destroy(opj_bio_t *bio) { - if(bio) { - opj_free(bio); - } -} - -int bio_numbytes(opj_bio_t *bio) { - return (bio->bp - bio->start); -} - -void bio_init_enc(opj_bio_t *bio, unsigned char *bp, int len) { - bio->start = bp; - bio->end = bp + len; - bio->bp = bp; - bio->buf = 0; - bio->ct = 8; -} - -void bio_init_dec(opj_bio_t *bio, unsigned char *bp, int len) { - bio->start = bp; - bio->end = bp + len; - bio->bp = bp; - bio->buf = 0; - bio->ct = 0; -} - -void bio_write(opj_bio_t *bio, int v, int n) { - int i; - for (i = n - 1; i >= 0; i--) { - bio_putbit(bio, (v >> i) & 1); - } -} - -int bio_read(opj_bio_t *bio, int n) { - int i, v; - v = 0; - for (i = n - 1; i >= 0; i--) { - v += bio_getbit(bio) << i; - } - return v; -} - -int bio_flush(opj_bio_t *bio) { - bio->ct = 0; - if (bio_byteout(bio)) { - return 1; - } - if (bio->ct == 7) { - bio->ct = 0; - if (bio_byteout(bio)) { - return 1; - } - } - return 0; -} - -int bio_inalign(opj_bio_t *bio) { - bio->ct = 0; - if ((bio->buf & 0xff) == 0xff) { - if (bio_bytein(bio)) { - return 1; - } - bio->ct = 0; - } - return 0; -} diff --git a/openjpeg-dotnet/libopenjpeg/bio.h b/openjpeg-dotnet/libopenjpeg/bio.h deleted file mode 100644 index 764d7cb2..00000000 --- a/openjpeg-dotnet/libopenjpeg/bio.h +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium - * Copyright (c) 2002-2007, Professor Benoit Macq - * Copyright (c) 2001-2003, David Janssens - * Copyright (c) 2002-2003, Yannick Verschueren - * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe - * Copyright (c) 2005, Herve Drolon, FreeImage Team - * 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 -/** -@file bio.h -@brief Implementation of an individual bit input-output (BIO) - -The functions in BIO.C have for goal to realize an individual bit input - output. -*/ - -/** @defgroup BIO BIO - Individual bit input-output stream */ -/*@{*/ - -/** -Individual bit input-output stream (BIO) -*/ -typedef struct opj_bio { - /** pointer to the start of the buffer */ - unsigned char *start; - /** pointer to the end of the buffer */ - unsigned char *end; - /** pointer to the present position in the buffer */ - unsigned char *bp; - /** temporary place where each byte is read or written */ - unsigned int buf; - /** coder : number of bits free to write. decoder : number of bits read */ - int ct; -} opj_bio_t; - -/** @name Exported functions */ -/*@{*/ -/* ----------------------------------------------------------------------- */ -/** -Create a new BIO handle -@return Returns a new BIO handle if successful, returns NULL otherwise -*/ -opj_bio_t* bio_create(void); -/** -Destroy a previously created BIO handle -@param bio BIO handle to destroy -*/ -void bio_destroy(opj_bio_t *bio); -/** -Number of bytes written. -@param bio BIO handle -@return Returns the number of bytes written -*/ -int bio_numbytes(opj_bio_t *bio); -/** -Init encoder -@param bio BIO handle -@param bp Output buffer -@param len Output buffer length -*/ -void bio_init_enc(opj_bio_t *bio, unsigned char *bp, int len); -/** -Init decoder -@param bio BIO handle -@param bp Input buffer -@param len Input buffer length -*/ -void bio_init_dec(opj_bio_t *bio, unsigned char *bp, int len); -/** -Write bits -@param bio BIO handle -@param v Value of bits -@param n Number of bits to write -*/ -void bio_write(opj_bio_t *bio, int v, int n); -/** -Read bits -@param bio BIO handle -@param n Number of bits to read -@return Returns the corresponding read number -*/ -int bio_read(opj_bio_t *bio, int n); -/** -Flush bits -@param bio BIO handle -@return Returns 1 if successful, returns 0 otherwise -*/ -int bio_flush(opj_bio_t *bio); -/** -Passes the ending bits (coming from flushing) -@param bio BIO handle -@return Returns 1 if successful, returns 0 otherwise -*/ -int bio_inalign(opj_bio_t *bio); -/* ----------------------------------------------------------------------- */ -/*@}*/ - -/*@}*/ - -#endif /* __BIO_H */ - diff --git a/openjpeg-dotnet/libopenjpeg/cidx_manager.c b/openjpeg-dotnet/libopenjpeg/cidx_manager.c deleted file mode 100644 index 6131b938..00000000 --- a/openjpeg-dotnet/libopenjpeg/cidx_manager.c +++ /dev/null @@ -1,213 +0,0 @@ -/* - * $Id: cidx_manager.c 897 2011-08-28 21:43:57Z Kaori.Hagihara@gmail.com $ - * - * Copyright (c) 2002-2011, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium - * Copyright (c) 2002-2011, Professor Benoit Macq - * Copyright (c) 2003-2004, Yannick Verschueren - * Copyright (c) 2010-2011, Kaori Hagihara - * 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 "opj_includes.h" - - -/* - * Write CPTR Codestream finder box - * - * @param[in] coff offset of j2k codestream - * @param[in] clen length of j2k codestream - * @param[in] cio file output handle - */ -void write_cptr(int coff, int clen, opj_cio_t *cio); - - -/* - * Write main header index table (box) - * - * @param[in] coff offset of j2k codestream - * @param[in] cstr_info codestream information - * @param[in] cio file output handle - * @return length of mainmhix box - */ -int write_mainmhix( int coff, opj_codestream_info_t cstr_info, opj_cio_t *cio); - - -/* - * Check if EPH option is used - * - * @param[in] coff offset of j2k codestream - * @param[in] markers marker information - * @param[in] marknum number of markers - * @param[in] cio file output handle - * @return true if EPH is used - */ -opj_bool check_EPHuse( int coff, opj_marker_info_t *markers, int marknum, opj_cio_t *cio); - - -int write_cidx( int offset, opj_cio_t *cio, opj_image_t *image, opj_codestream_info_t cstr_info, int j2klen) -{ - int len, i, lenp; - opj_jp2_box_t *box; - int num_box = 0; - opj_bool EPHused; - (void)image; /* unused ? */ - - lenp = -1; - box = (opj_jp2_box_t *)opj_calloc( 32, sizeof(opj_jp2_box_t)); - - for (i=0;i<2;i++){ - - if(i) - cio_seek( cio, lenp); - - lenp = cio_tell( cio); - - cio_skip( cio, 4); /* L [at the end] */ - cio_write( cio, JPIP_CIDX, 4); /* CIDX */ - write_cptr( offset, cstr_info.codestream_size, cio); - - write_manf( i, num_box, box, cio); - - num_box = 0; - box[num_box].length = write_mainmhix( offset, cstr_info, cio); - box[num_box].type = JPIP_MHIX; - num_box++; - - box[num_box].length = write_tpix( offset, cstr_info, j2klen, cio); - box[num_box].type = JPIP_TPIX; - num_box++; - - box[num_box].length = write_thix( offset, cstr_info, cio); - box[num_box].type = JPIP_THIX; - num_box++; - - EPHused = check_EPHuse( offset, cstr_info.marker, cstr_info.marknum, cio); - - box[num_box].length = write_ppix( offset, cstr_info, EPHused, j2klen, cio); - box[num_box].type = JPIP_PPIX; - num_box++; - - box[num_box].length = write_phix( offset, cstr_info, EPHused, j2klen, cio); - box[num_box].type = JPIP_PHIX; - num_box++; - - len = cio_tell( cio)-lenp; - cio_seek( cio, lenp); - cio_write( cio, len, 4); /* L */ - cio_seek( cio, lenp+len); - } - - opj_free( box); - - return len; -} - -void write_cptr(int coff, int clen, opj_cio_t *cio) -{ - int len, lenp; - - lenp = cio_tell( cio); - cio_skip( cio, 4); /* L [at the end] */ - cio_write( cio, JPIP_CPTR, 4); /* T */ - cio_write( cio, 0, 2); /* DR A PRECISER !! */ - cio_write( cio, 0, 2); /* CONT */ - cio_write( cio, coff, 8); /* COFF A PRECISER !! */ - cio_write( cio, clen, 8); /* CLEN */ - len = cio_tell( cio) - lenp; - cio_seek( cio, lenp); - cio_write( cio, len, 4); /* L */ - cio_seek( cio, lenp+len); -} - -void write_manf(int second, int v, opj_jp2_box_t *box, opj_cio_t *cio) -{ - int len, lenp, i; - - lenp = cio_tell( cio); - cio_skip( cio, 4); /* L [at the end] */ - cio_write( cio, JPIP_MANF,4); /* T */ - - if (second){ /* Write only during the second pass */ - for( i=0; i> 2) & 1)) - EPHused = OPJ_TRUE; - cio_seek( cio, org_pos); - - break; - } - } - return EPHused; -} diff --git a/openjpeg-dotnet/libopenjpeg/cidx_manager.h b/openjpeg-dotnet/libopenjpeg/cidx_manager.h deleted file mode 100644 index 23eebd52..00000000 --- a/openjpeg-dotnet/libopenjpeg/cidx_manager.h +++ /dev/null @@ -1,56 +0,0 @@ -/* - * $Id: cidx_manager.h 897 2011-08-28 21:43:57Z Kaori.Hagihara@gmail.com $ - * - * Copyright (c) 2002-2011, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium - * Copyright (c) 2002-2011, Professor Benoit Macq - * Copyright (c) 2003-2004, Yannick Verschueren - * Copyright (c) 2010-2011, Kaori Hagihara - * 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. - */ - -/*! \file - * \brief Modification of jpip.h from 2KAN indexer - */ - - -#ifndef CIDX_MANAGER_H_ -# define CIDX_MANAGER_H_ - -#include "openjpeg.h" - - -/* - * Write Codestream index box (superbox) - * - * @param[in] offset offset of j2k codestream - * @param[in] cio file output handle - * @param[in] image image data - * @param[in] cstr_info codestream information - * @param[in] j2klen length of j2k codestream - * @return length of cidx box - */ -int write_cidx( int offset, opj_cio_t *cio, opj_image_t *image, opj_codestream_info_t cstr_info, int j2klen); - - -#endif /* !CIDX_MANAGER_H_ */ diff --git a/openjpeg-dotnet/libopenjpeg/cio.c b/openjpeg-dotnet/libopenjpeg/cio.c deleted file mode 100644 index b8a7ecf8..00000000 --- a/openjpeg-dotnet/libopenjpeg/cio.c +++ /dev/null @@ -1,191 +0,0 @@ -/* - * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium - * Copyright (c) 2002-2007, Professor Benoit Macq - * Copyright (c) 2001-2003, David Janssens - * Copyright (c) 2002-2003, Yannick Verschueren - * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe - * Copyright (c) 2005, Herve Drolon, FreeImage Team - * 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 "opj_includes.h" - -/* ----------------------------------------------------------------------- */ - -opj_cio_t* OPJ_CALLCONV opj_cio_open(opj_common_ptr cinfo, unsigned char *buffer, int length) { - opj_cp_t *cp = NULL; - opj_cio_t *cio = (opj_cio_t*)opj_malloc(sizeof(opj_cio_t)); - if(!cio) return NULL; - cio->cinfo = cinfo; - if(buffer && length) { - /* wrap a user buffer containing the encoded image */ - cio->openmode = OPJ_STREAM_READ; - cio->buffer = buffer; - cio->length = length; - } - else if(!buffer && !length && cinfo) { - /* allocate a buffer for the encoded image */ - cio->openmode = OPJ_STREAM_WRITE; - switch(cinfo->codec_format) { - case CODEC_J2K: - cp = ((opj_j2k_t*)cinfo->j2k_handle)->cp; - break; - case CODEC_JP2: - cp = ((opj_jp2_t*)cinfo->jp2_handle)->j2k->cp; - break; - default: - opj_free(cio); - return NULL; - } - cio->length = (unsigned int) (0.1625 * cp->img_size + 2000); /* 0.1625 = 1.3/8 and 2000 bytes as a minimum for headers */ - cio->buffer = (unsigned char *)opj_malloc(cio->length); - if(!cio->buffer) { - opj_event_msg(cio->cinfo, EVT_ERROR, "Error allocating memory for compressed bitstream\n"); - opj_free(cio); - return NULL; - } - } - else { - opj_free(cio); - return NULL; - } - - /* Initialize byte IO */ - cio->start = cio->buffer; - cio->end = cio->buffer + cio->length; - cio->bp = cio->buffer; - - return cio; -} - -void OPJ_CALLCONV opj_cio_close(opj_cio_t *cio) { - if(cio) { - if(cio->openmode == OPJ_STREAM_WRITE) { - /* destroy the allocated buffer */ - opj_free(cio->buffer); - } - /* destroy the cio */ - opj_free(cio); - } -} - - -/* ----------------------------------------------------------------------- */ - -/* - * Get position in byte stream. - */ -int OPJ_CALLCONV cio_tell(opj_cio_t *cio) { - return cio->bp - cio->start; -} - -/* - * Set position in byte stream. - * - * pos : position, in number of bytes, from the beginning of the stream - */ -void OPJ_CALLCONV cio_seek(opj_cio_t *cio, int pos) { - cio->bp = cio->start + pos; -} - -/* - * Number of bytes left before the end of the stream. - */ -int cio_numbytesleft(opj_cio_t *cio) { - return cio->end - cio->bp; -} - -/* - * Get pointer to the current position in the stream. - */ -unsigned char *cio_getbp(opj_cio_t *cio) { - return cio->bp; -} - -/* - * Write a byte. - */ -opj_bool cio_byteout(opj_cio_t *cio, unsigned char v) { - if (cio->bp >= cio->end) { - opj_event_msg(cio->cinfo, EVT_ERROR, "write error\n"); - return OPJ_FALSE; - } - *cio->bp++ = v; - return OPJ_TRUE; -} - -/* - * Read a byte. - */ -unsigned char cio_bytein(opj_cio_t *cio) { - if (cio->bp >= cio->end) { - opj_event_msg(cio->cinfo, EVT_ERROR, "read error: passed the end of the codestream (start = %d, current = %d, end = %d\n", cio->start, cio->bp, cio->end); - return 0; - } - return *cio->bp++; -} - -/* - * Write some bytes. - * - * v : value to write - * n : number of bytes to write - */ -unsigned int cio_write(opj_cio_t *cio, unsigned long long int v, int n) { - int i; - for (i = n - 1; i >= 0; i--) { - if( !cio_byteout(cio, (unsigned char) ((v >> (i << 3)) & 0xff)) ) - return 0; - } - return n; -} - -/* - * Read some bytes. - * - * n : number of bytes to read - * - * return : value of the n bytes read - */ -unsigned int cio_read(opj_cio_t *cio, int n) { - int i; - unsigned int v; - v = 0; - for (i = n - 1; i >= 0; i--) { - v += cio_bytein(cio) << (i << 3); - } - return v; -} - -/* - * Skip some bytes. - * - * n : number of bytes to skip - */ -void cio_skip(opj_cio_t *cio, int n) { - cio->bp += n; -} - - - diff --git a/openjpeg-dotnet/libopenjpeg/cio.h b/openjpeg-dotnet/libopenjpeg/cio.h deleted file mode 100644 index ce1a13ec..00000000 --- a/openjpeg-dotnet/libopenjpeg/cio.h +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium - * Copyright (c) 2002-2007, Professor Benoit Macq - * Copyright (c) 2001-2003, David Janssens - * Copyright (c) 2002-2003, Yannick Verschueren - * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe - * Copyright (c) 2005, Herve Drolon, FreeImage Team - * 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 -/** -@file cio.h -@brief Implementation of a byte input-output process (CIO) - -The functions in CIO.C have for goal to realize a byte input / output process. -*/ - -/** @defgroup CIO CIO - byte input-output stream */ -/*@{*/ - -/** @name Exported functions (see also openjpeg.h) */ -/*@{*/ -/* ----------------------------------------------------------------------- */ -/** -Number of bytes left before the end of the stream -@param cio CIO handle -@return Returns the number of bytes before the end of the stream -*/ -int cio_numbytesleft(opj_cio_t *cio); -/** -Get pointer to the current position in the stream -@param cio CIO handle -@return Returns a pointer to the current position -*/ -unsigned char *cio_getbp(opj_cio_t *cio); -/** -Write some bytes -@param cio CIO handle -@param v Value to write -@param n Number of bytes to write -@return Returns the number of bytes written or 0 if an error occured -*/ -unsigned int cio_write(opj_cio_t *cio, unsigned long long int v, int n); -/** -Read some bytes -@param cio CIO handle -@param n Number of bytes to read -@return Returns the value of the n bytes read -*/ -unsigned int cio_read(opj_cio_t *cio, int n); -/** -Skip some bytes -@param cio CIO handle -@param n Number of bytes to skip -*/ -void cio_skip(opj_cio_t *cio, int n); -/* ----------------------------------------------------------------------- */ -/*@}*/ - -/*@}*/ - -#endif /* __CIO_H */ - diff --git a/openjpeg-dotnet/libopenjpeg/dwt.c b/openjpeg-dotnet/libopenjpeg/dwt.c deleted file mode 100644 index 0fbfc203..00000000 --- a/openjpeg-dotnet/libopenjpeg/dwt.c +++ /dev/null @@ -1,858 +0,0 @@ -/* - * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium - * Copyright (c) 2002-2007, Professor Benoit Macq - * Copyright (c) 2001-2003, David Janssens - * Copyright (c) 2002-2003, Yannick Verschueren - * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe - * Copyright (c) 2005, Herve Drolon, FreeImage Team - * Copyright (c) 2007, Jonathan Ballard - * Copyright (c) 2007, Callum Lerwick - * 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. - */ - -#ifdef __SSE__ -#include -#endif - -#include "opj_includes.h" - -/** @defgroup DWT DWT - Implementation of a discrete wavelet transform */ -/*@{*/ - -#define WS(i) v->mem[(i)*2] -#define WD(i) v->mem[(1+(i)*2)] - -/** @name Local data structures */ -/*@{*/ - -typedef struct dwt_local { - int* mem; - int dn; - int sn; - int cas; -} dwt_t; - -typedef union { - float f[4]; -} v4; - -typedef struct v4dwt_local { - v4* wavelet ; - int dn ; - int sn ; - int cas ; -} v4dwt_t ; - -static const float dwt_alpha = 1.586134342f; /* 12994 */ -static const float dwt_beta = 0.052980118f; /* 434 */ -static const float dwt_gamma = -0.882911075f; /* -7233 */ -static const float dwt_delta = -0.443506852f; /* -3633 */ - -static const float K = 1.230174105f; /* 10078 */ -/* FIXME: What is this constant? */ -static const float c13318 = 1.625732422f; - -/*@}*/ - -/** -Virtual function type for wavelet transform in 1-D -*/ -typedef void (*DWT1DFN)(dwt_t* v); - -/** @name Local static functions */ -/*@{*/ - -/** -Forward lazy transform (horizontal) -*/ -static void dwt_deinterleave_h(int *a, int *b, int dn, int sn, int cas); -/** -Forward lazy transform (vertical) -*/ -static void dwt_deinterleave_v(int *a, int *b, int dn, int sn, int x, int cas); -/** -Inverse lazy transform (horizontal) -*/ -static void dwt_interleave_h(dwt_t* h, int *a); -/** -Inverse lazy transform (vertical) -*/ -static void dwt_interleave_v(dwt_t* v, int *a, int x); -/** -Forward 5-3 wavelet transform in 1-D -*/ -static void dwt_encode_1(int *a, int dn, int sn, int cas); -/** -Inverse 5-3 wavelet transform in 1-D -*/ -static void dwt_decode_1(dwt_t *v); -/** -Forward 9-7 wavelet transform in 1-D -*/ -static void dwt_encode_1_real(int *a, int dn, int sn, int cas); -/** -Explicit calculation of the Quantization Stepsizes -*/ -static void dwt_encode_stepsize(int stepsize, int numbps, opj_stepsize_t *bandno_stepsize); -/** -Inverse wavelet transform in 2-D. -*/ -static void dwt_decode_tile(opj_tcd_tilecomp_t* tilec, int i, DWT1DFN fn); - -/*@}*/ - -/*@}*/ - -#define S(i) a[(i)*2] -#define D(i) a[(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))) -/* new */ -#define SS_(i) ((i)<0?S(0):((i)>=dn?S(dn-1):S(i))) -#define DD_(i) ((i)<0?D(0):((i)>=sn?D(sn-1):D(i))) - -/* */ -/* This table contains the norms of the 5-3 wavelets for different bands. */ -/* */ -static const 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. */ -/* */ -static const 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} -}; - -/* -========================================================== - local functions -========================================================== -*/ - -/* */ -/* Forward lazy transform (horizontal). */ -/* */ -static void dwt_deinterleave_h(int *a, int *b, int dn, int sn, int cas) { - int i; - for (i=0; i */ -/* Forward lazy transform (vertical). */ -/* */ -static void dwt_deinterleave_v(int *a, int *b, int dn, int sn, int x, int cas) { - int i; - for (i=0; i */ -/* Inverse lazy transform (horizontal). */ -/* */ -static void dwt_interleave_h(dwt_t* h, int *a) { - int *ai = a; - int *bi = h->mem + h->cas; - int i = h->sn; - while( i-- ) { - *bi = *(ai++); - bi += 2; - } - ai = a + h->sn; - bi = h->mem + 1 - h->cas; - i = h->dn ; - while( i-- ) { - *bi = *(ai++); - bi += 2; - } -} - -/* */ -/* Inverse lazy transform (vertical). */ -/* */ -static void dwt_interleave_v(dwt_t* v, int *a, int x) { - int *ai = a; - int *bi = v->mem + v->cas; - int i = v->sn; - while( i-- ) { - *bi = *ai; - bi += 2; - ai += x; - } - ai = a + (v->sn * x); - bi = v->mem + 1 - v->cas; - i = v->dn ; - while( i-- ) { - *bi = *ai; - bi += 2; - ai += x; - } -} - - -/* */ -/* Forward 5-3 wavelet transform in 1-D. */ -/* */ -static void dwt_encode_1(int *a, int dn, int sn, int cas) { - int i; - - if (!cas) { - if ((dn > 0) || (sn > 1)) { /* NEW : CASE ONE ELEMENT */ - for (i = 0; i < dn; i++) D(i) -= (S_(i) + S_(i + 1)) >> 1; - for (i = 0; i < sn; i++) S(i) += (D_(i - 1) + D_(i) + 2) >> 2; - } - } else { - if (!sn && dn == 1) /* NEW : CASE ONE ELEMENT */ - S(0) *= 2; - else { - for (i = 0; i < dn; i++) S(i) -= (DD_(i) + DD_(i - 1)) >> 1; - for (i = 0; i < sn; i++) D(i) += (SS_(i) + SS_(i + 1) + 2) >> 2; - } - } -} - -/* */ -/* Inverse 5-3 wavelet transform in 1-D. */ -/* */ -static void dwt_decode_1_(int *a, int dn, int sn, int cas) { - int i; - - if (!cas) { - if ((dn > 0) || (sn > 1)) { /* NEW : CASE ONE ELEMENT */ - for (i = 0; i < sn; i++) S(i) -= (D_(i - 1) + D_(i) + 2) >> 2; - for (i = 0; i < dn; i++) D(i) += (S_(i) + S_(i + 1)) >> 1; - } - } else { - if (!sn && dn == 1) /* NEW : CASE ONE ELEMENT */ - S(0) /= 2; - else { - for (i = 0; i < sn; i++) D(i) -= (SS_(i) + SS_(i + 1) + 2) >> 2; - for (i = 0; i < dn; i++) S(i) += (DD_(i) + DD_(i - 1)) >> 1; - } - } -} - -/* */ -/* Inverse 5-3 wavelet transform in 1-D. */ -/* */ -static void dwt_decode_1(dwt_t *v) { - dwt_decode_1_(v->mem, v->dn, v->sn, v->cas); -} - -/* */ -/* Forward 9-7 wavelet transform in 1-D. */ -/* */ -static void dwt_encode_1_real(int *a, int dn, int sn, int cas) { - int i; - if (!cas) { - if ((dn > 0) || (sn > 1)) { /* NEW : CASE ONE ELEMENT */ - for (i = 0; i < dn; i++) - D(i) -= fix_mul(S_(i) + S_(i + 1), 12993); - for (i = 0; i < sn; i++) - S(i) -= fix_mul(D_(i - 1) + D_(i), 434); - for (i = 0; i < dn; i++) - D(i) += fix_mul(S_(i) + S_(i + 1), 7233); - for (i = 0; i < sn; i++) - S(i) += fix_mul(D_(i - 1) + D_(i), 3633); - for (i = 0; i < dn; i++) - D(i) = fix_mul(D(i), 5038); /*5038 */ - for (i = 0; i < sn; i++) - S(i) = fix_mul(S(i), 6659); /*6660 */ - } - } else { - if ((sn > 0) || (dn > 1)) { /* NEW : CASE ONE ELEMENT */ - for (i = 0; i < dn; i++) - S(i) -= fix_mul(DD_(i) + DD_(i - 1), 12993); - for (i = 0; i < sn; i++) - D(i) -= fix_mul(SS_(i) + SS_(i + 1), 434); - for (i = 0; i < dn; i++) - S(i) += fix_mul(DD_(i) + DD_(i - 1), 7233); - for (i = 0; i < sn; i++) - D(i) += fix_mul(SS_(i) + SS_(i + 1), 3633); - for (i = 0; i < dn; i++) - S(i) = fix_mul(S(i), 5038); /*5038 */ - for (i = 0; i < sn; i++) - D(i) = fix_mul(D(i), 6659); /*6660 */ - } - } -} - -static void dwt_encode_stepsize(int stepsize, int numbps, opj_stepsize_t *bandno_stepsize) { - int p, n; - p = int_floorlog2(stepsize) - 13; - n = 11 - int_floorlog2(stepsize); - bandno_stepsize->mant = (n < 0 ? stepsize >> -n : stepsize << n) & 0x7ff; - bandno_stepsize->expn = numbps - p; -} - -/* -========================================================== - DWT interface -========================================================== -*/ - -/* */ -/* Forward 5-3 wavelet transform in 2-D. */ -/* */ -void dwt_encode(opj_tcd_tilecomp_t * tilec) { - int i, j, k; - int *a = NULL; - int *aj = NULL; - int *bj = NULL; - int w, l; - - w = tilec->x1-tilec->x0; - l = tilec->numresolutions-1; - a = tilec->data; - - for (i = 0; i < l; i++) { - int rw; /* width of the resolution level computed */ - int rh; /* height of the resolution level computed */ - int rw1; /* width of the resolution level once lower than computed one */ - int rh1; /* height of the resolution level once lower than computed one */ - int cas_col; /* 0 = non inversion on horizontal filtering 1 = inversion between low-pass and high-pass filtering */ - int cas_row; /* 0 = non inversion on vertical filtering 1 = inversion between low-pass and high-pass filtering */ - int dn, sn; - - rw = tilec->resolutions[l - i].x1 - tilec->resolutions[l - i].x0; - rh = tilec->resolutions[l - i].y1 - tilec->resolutions[l - i].y0; - rw1= tilec->resolutions[l - i - 1].x1 - tilec->resolutions[l - i - 1].x0; - rh1= tilec->resolutions[l - i - 1].y1 - tilec->resolutions[l - i - 1].y0; - - cas_row = tilec->resolutions[l - i].x0 % 2; - cas_col = tilec->resolutions[l - i].y0 % 2; - - sn = rh1; - dn = rh - rh1; - bj = (int*)opj_malloc(rh * sizeof(int)); - for (j = 0; j < rw; j++) { - aj = a + j; - for (k = 0; k < rh; k++) bj[k] = aj[k*w]; - dwt_encode_1(bj, dn, sn, cas_col); - dwt_deinterleave_v(bj, aj, dn, sn, w, cas_col); - } - opj_free(bj); - - sn = rw1; - dn = rw - rw1; - bj = (int*)opj_malloc(rw * sizeof(int)); - for (j = 0; j < rh; j++) { - aj = a + j * w; - for (k = 0; k < rw; k++) bj[k] = aj[k]; - dwt_encode_1(bj, dn, sn, cas_row); - dwt_deinterleave_h(bj, aj, dn, sn, cas_row); - } - opj_free(bj); - } -} - - -/* */ -/* Inverse 5-3 wavelet transform in 2-D. */ -/* */ -void dwt_decode(opj_tcd_tilecomp_t* tilec, int numres) { - dwt_decode_tile(tilec, numres, &dwt_decode_1); -} - - -/* */ -/* 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 2-D. */ -/* */ - -void dwt_encode_real(opj_tcd_tilecomp_t * tilec) { - int i, j, k; - int *a = NULL; - int *aj = NULL; - int *bj = NULL; - int w, l; - - w = tilec->x1-tilec->x0; - l = tilec->numresolutions-1; - a = tilec->data; - - for (i = 0; i < l; i++) { - int rw; /* width of the resolution level computed */ - int rh; /* height of the resolution level computed */ - int rw1; /* width of the resolution level once lower than computed one */ - int rh1; /* height of the resolution level once lower than computed one */ - int cas_col; /* 0 = non inversion on horizontal filtering 1 = inversion between low-pass and high-pass filtering */ - int cas_row; /* 0 = non inversion on vertical filtering 1 = inversion between low-pass and high-pass filtering */ - int dn, sn; - - rw = tilec->resolutions[l - i].x1 - tilec->resolutions[l - i].x0; - rh = tilec->resolutions[l - i].y1 - tilec->resolutions[l - i].y0; - rw1= tilec->resolutions[l - i - 1].x1 - tilec->resolutions[l - i - 1].x0; - rh1= tilec->resolutions[l - i - 1].y1 - tilec->resolutions[l - i - 1].y0; - - cas_row = tilec->resolutions[l - i].x0 % 2; - cas_col = tilec->resolutions[l - i].y0 % 2; - - sn = rh1; - dn = rh - rh1; - bj = (int*)opj_malloc(rh * sizeof(int)); - for (j = 0; j < rw; j++) { - aj = a + j; - for (k = 0; k < rh; k++) bj[k] = aj[k*w]; - dwt_encode_1_real(bj, dn, sn, cas_col); - dwt_deinterleave_v(bj, aj, dn, sn, w, cas_col); - } - opj_free(bj); - - sn = rw1; - dn = rw - rw1; - bj = (int*)opj_malloc(rw * sizeof(int)); - for (j = 0; j < rh; j++) { - aj = a + j * w; - for (k = 0; k < rw; k++) bj[k] = aj[k]; - dwt_encode_1_real(bj, dn, sn, cas_row); - dwt_deinterleave_h(bj, aj, dn, sn, cas_row); - } - opj_free(bj); - } -} - - -/* */ -/* Get gain of 9-7 wavelet transform. */ -/* */ -int dwt_getgain_real(int orient) { - (void)orient; - return 0; -} - -/* */ -/* Get norm of 9-7 wavelet. */ -/* */ -double dwt_getnorm_real(int level, int orient) { - return dwt_norms_real[orient][level]; -} - -void dwt_calc_explicit_stepsizes(opj_tccp_t * tccp, int prec) { - int numbands, bandno; - numbands = 3 * tccp->numresolutions - 2; - for (bandno = 0; bandno < numbands; bandno++) { - double stepsize; - int resno, level, orient, gain; - - resno = (bandno == 0) ? 0 : ((bandno - 1) / 3 + 1); - orient = (bandno == 0) ? 0 : ((bandno - 1) % 3 + 1); - level = tccp->numresolutions - 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_real[orient][level]; - stepsize = (1 << (gain)) / norm; - } - dwt_encode_stepsize((int) floor(stepsize * 8192.0), prec + gain, &tccp->stepsizes[bandno]); - } -} - - -/* */ -/* Determine maximum computed resolution level for inverse wavelet transform */ -/* */ -static int dwt_decode_max_resolution(opj_tcd_resolution_t* restrict r, int i) { - int mr = 1; - int w; - while( --i ) { - r++; - if( mr < ( w = r->x1 - r->x0 ) ) - mr = w ; - if( mr < ( w = r->y1 - r->y0 ) ) - mr = w ; - } - return mr ; -} - - -/* */ -/* Inverse wavelet transform in 2-D. */ -/* */ -static void dwt_decode_tile(opj_tcd_tilecomp_t* tilec, int numres, DWT1DFN dwt_1D) { - dwt_t h; - dwt_t v; - - opj_tcd_resolution_t* tr = tilec->resolutions; - - int rw = tr->x1 - tr->x0; /* width of the resolution level computed */ - int rh = tr->y1 - tr->y0; /* height of the resolution level computed */ - - int w = tilec->x1 - tilec->x0; - - h.mem = (int*)opj_aligned_malloc(dwt_decode_max_resolution(tr, numres) * sizeof(int)); - v.mem = h.mem; - - while( --numres) { - int * restrict tiledp = tilec->data; - int j; - - ++tr; - h.sn = rw; - v.sn = rh; - - rw = tr->x1 - tr->x0; - rh = tr->y1 - tr->y0; - - h.dn = rw - h.sn; - h.cas = tr->x0 % 2; - - for(j = 0; j < rh; ++j) { - dwt_interleave_h(&h, &tiledp[j*w]); - (dwt_1D)(&h); - memcpy(&tiledp[j*w], h.mem, rw * sizeof(int)); - } - - v.dn = rh - v.sn; - v.cas = tr->y0 % 2; - - for(j = 0; j < rw; ++j){ - int k; - dwt_interleave_v(&v, &tiledp[j], w); - (dwt_1D)(&v); - for(k = 0; k < rh; ++k) { - tiledp[k * w + j] = v.mem[k]; - } - } - } - opj_aligned_free(h.mem); -} - -static void v4dwt_interleave_h(v4dwt_t* restrict w, float* restrict a, int x, int size){ - float* restrict bi = (float*) (w->wavelet + w->cas); - int count = w->sn; - int i, k; - for(k = 0; k < 2; ++k){ - if (count + 3 * x < size && ((size_t) a & 0x0f) == 0 && ((size_t) bi & 0x0f) == 0 && (x & 0x0f) == 0) { - /* Fast code path */ - for(i = 0; i < count; ++i){ - int j = i; - bi[i*8 ] = a[j]; - j += x; - bi[i*8 + 1] = a[j]; - j += x; - bi[i*8 + 2] = a[j]; - j += x; - bi[i*8 + 3] = a[j]; - } - } else { - /* Slow code path */ - for(i = 0; i < count; ++i){ - int j = i; - bi[i*8 ] = a[j]; - j += x; - if(j > size) continue; - bi[i*8 + 1] = a[j]; - j += x; - if(j > size) continue; - bi[i*8 + 2] = a[j]; - j += x; - if(j > size) continue; - bi[i*8 + 3] = a[j]; - } - } - bi = (float*) (w->wavelet + 1 - w->cas); - a += w->sn; - size -= w->sn; - count = w->dn; - } -} - -static void v4dwt_interleave_v(v4dwt_t* restrict v , float* restrict a , int x){ - v4* restrict bi = v->wavelet + v->cas; - int i; - for(i = 0; i < v->sn; ++i){ - memcpy(&bi[i*2], &a[i*x], 4 * sizeof(float)); - } - a += v->sn * x; - bi = v->wavelet + 1 - v->cas; - for(i = 0; i < v->dn; ++i){ - memcpy(&bi[i*2], &a[i*x], 4 * sizeof(float)); - } -} - -#ifdef __SSE__ - -static void v4dwt_decode_step1_sse(v4* w, int count, const __m128 c){ - __m128* restrict vw = (__m128*) w; - int i; - /* 4x unrolled loop */ - for(i = 0; i < count >> 2; ++i){ - *vw = _mm_mul_ps(*vw, c); - vw += 2; - *vw = _mm_mul_ps(*vw, c); - vw += 2; - *vw = _mm_mul_ps(*vw, c); - vw += 2; - *vw = _mm_mul_ps(*vw, c); - vw += 2; - } - count &= 3; - for(i = 0; i < count; ++i){ - *vw = _mm_mul_ps(*vw, c); - vw += 2; - } -} - -static void v4dwt_decode_step2_sse(v4* l, v4* w, int k, int m, __m128 c){ - __m128* restrict vl = (__m128*) l; - __m128* restrict vw = (__m128*) w; - int i; - __m128 tmp1, tmp2, tmp3; - tmp1 = vl[0]; - for(i = 0; i < m; ++i){ - tmp2 = vw[-1]; - tmp3 = vw[ 0]; - vw[-1] = _mm_add_ps(tmp2, _mm_mul_ps(_mm_add_ps(tmp1, tmp3), c)); - tmp1 = tmp3; - vw += 2; - } - vl = vw - 2; - if(m >= k){ - return; - } - c = _mm_add_ps(c, c); - c = _mm_mul_ps(c, vl[0]); - for(; m < k; ++m){ - __m128 tmp = vw[-1]; - vw[-1] = _mm_add_ps(tmp, c); - vw += 2; - } -} - -#else - -static void v4dwt_decode_step1(v4* w, int count, const float c){ - float* restrict fw = (float*) w; - int i; - for(i = 0; i < count; ++i){ - float tmp1 = fw[i*8 ]; - float tmp2 = fw[i*8 + 1]; - float tmp3 = fw[i*8 + 2]; - float tmp4 = fw[i*8 + 3]; - fw[i*8 ] = tmp1 * c; - fw[i*8 + 1] = tmp2 * c; - fw[i*8 + 2] = tmp3 * c; - fw[i*8 + 3] = tmp4 * c; - } -} - -static void v4dwt_decode_step2(v4* l, v4* w, int k, int m, float c){ - float* restrict fl = (float*) l; - float* restrict fw = (float*) w; - int i; - for(i = 0; i < m; ++i){ - float tmp1_1 = fl[0]; - float tmp1_2 = fl[1]; - float tmp1_3 = fl[2]; - float tmp1_4 = fl[3]; - float tmp2_1 = fw[-4]; - float tmp2_2 = fw[-3]; - float tmp2_3 = fw[-2]; - float tmp2_4 = fw[-1]; - float tmp3_1 = fw[0]; - float tmp3_2 = fw[1]; - float tmp3_3 = fw[2]; - float tmp3_4 = fw[3]; - fw[-4] = tmp2_1 + ((tmp1_1 + tmp3_1) * c); - fw[-3] = tmp2_2 + ((tmp1_2 + tmp3_2) * c); - fw[-2] = tmp2_3 + ((tmp1_3 + tmp3_3) * c); - fw[-1] = tmp2_4 + ((tmp1_4 + tmp3_4) * c); - fl = fw; - fw += 8; - } - if(m < k){ - float c1; - float c2; - float c3; - float c4; - c += c; - c1 = fl[0] * c; - c2 = fl[1] * c; - c3 = fl[2] * c; - c4 = fl[3] * c; - for(; m < k; ++m){ - float tmp1 = fw[-4]; - float tmp2 = fw[-3]; - float tmp3 = fw[-2]; - float tmp4 = fw[-1]; - fw[-4] = tmp1 + c1; - fw[-3] = tmp2 + c2; - fw[-2] = tmp3 + c3; - fw[-1] = tmp4 + c4; - fw += 8; - } - } -} - -#endif - -/* */ -/* Inverse 9-7 wavelet transform in 1-D. */ -/* */ -static void v4dwt_decode(v4dwt_t* restrict dwt){ - int a, b; - if(dwt->cas == 0) { - if(!((dwt->dn > 0) || (dwt->sn > 1))){ - return; - } - a = 0; - b = 1; - }else{ - if(!((dwt->sn > 0) || (dwt->dn > 1))) { - return; - } - a = 1; - b = 0; - } -#ifdef __SSE__ - v4dwt_decode_step1_sse(dwt->wavelet+a, dwt->sn, _mm_set1_ps(K)); - v4dwt_decode_step1_sse(dwt->wavelet+b, dwt->dn, _mm_set1_ps(c13318)); - v4dwt_decode_step2_sse(dwt->wavelet+b, dwt->wavelet+a+1, dwt->sn, int_min(dwt->sn, dwt->dn-a), _mm_set1_ps(dwt_delta)); - v4dwt_decode_step2_sse(dwt->wavelet+a, dwt->wavelet+b+1, dwt->dn, int_min(dwt->dn, dwt->sn-b), _mm_set1_ps(dwt_gamma)); - v4dwt_decode_step2_sse(dwt->wavelet+b, dwt->wavelet+a+1, dwt->sn, int_min(dwt->sn, dwt->dn-a), _mm_set1_ps(dwt_beta)); - v4dwt_decode_step2_sse(dwt->wavelet+a, dwt->wavelet+b+1, dwt->dn, int_min(dwt->dn, dwt->sn-b), _mm_set1_ps(dwt_alpha)); -#else - v4dwt_decode_step1(dwt->wavelet+a, dwt->sn, K); - v4dwt_decode_step1(dwt->wavelet+b, dwt->dn, c13318); - v4dwt_decode_step2(dwt->wavelet+b, dwt->wavelet+a+1, dwt->sn, int_min(dwt->sn, dwt->dn-a), dwt_delta); - v4dwt_decode_step2(dwt->wavelet+a, dwt->wavelet+b+1, dwt->dn, int_min(dwt->dn, dwt->sn-b), dwt_gamma); - v4dwt_decode_step2(dwt->wavelet+b, dwt->wavelet+a+1, dwt->sn, int_min(dwt->sn, dwt->dn-a), dwt_beta); - v4dwt_decode_step2(dwt->wavelet+a, dwt->wavelet+b+1, dwt->dn, int_min(dwt->dn, dwt->sn-b), dwt_alpha); -#endif -} - -/* */ -/* Inverse 9-7 wavelet transform in 2-D. */ -/* */ -void dwt_decode_real(opj_tcd_tilecomp_t* restrict tilec, int numres){ - v4dwt_t h; - v4dwt_t v; - - opj_tcd_resolution_t* res = tilec->resolutions; - - int rw = res->x1 - res->x0; /* width of the resolution level computed */ - int rh = res->y1 - res->y0; /* height of the resolution level computed */ - - int w = tilec->x1 - tilec->x0; - - h.wavelet = (v4*) opj_aligned_malloc((dwt_decode_max_resolution(res, numres)+5) * sizeof(v4)); - v.wavelet = h.wavelet; - - while( --numres) { - float * restrict aj = (float*) tilec->data; - int bufsize = (tilec->x1 - tilec->x0) * (tilec->y1 - tilec->y0); - int j; - - h.sn = rw; - v.sn = rh; - - ++res; - - rw = res->x1 - res->x0; /* width of the resolution level computed */ - rh = res->y1 - res->y0; /* height of the resolution level computed */ - - h.dn = rw - h.sn; - h.cas = res->x0 % 2; - - for(j = rh; j > 3; j -= 4){ - int k; - v4dwt_interleave_h(&h, aj, w, bufsize); - v4dwt_decode(&h); - for(k = rw; --k >= 0;){ - aj[k ] = h.wavelet[k].f[0]; - aj[k+w ] = h.wavelet[k].f[1]; - aj[k+w*2] = h.wavelet[k].f[2]; - aj[k+w*3] = h.wavelet[k].f[3]; - } - aj += w*4; - bufsize -= w*4; - } - if (rh & 0x03) { - int k; - j = rh & 0x03; - v4dwt_interleave_h(&h, aj, w, bufsize); - v4dwt_decode(&h); - for(k = rw; --k >= 0;){ - switch(j) { - case 3: aj[k+w*2] = h.wavelet[k].f[2]; - case 2: aj[k+w ] = h.wavelet[k].f[1]; - case 1: aj[k ] = h.wavelet[k].f[0]; - } - } - } - - v.dn = rh - v.sn; - v.cas = res->y0 % 2; - - aj = (float*) tilec->data; - for(j = rw; j > 3; j -= 4){ - int k; - v4dwt_interleave_v(&v, aj, w); - v4dwt_decode(&v); - for(k = 0; k < rh; ++k){ - memcpy(&aj[k*w], &v.wavelet[k], 4 * sizeof(float)); - } - aj += 4; - } - if (rw & 0x03){ - int k; - j = rw & 0x03; - v4dwt_interleave_v(&v, aj, w); - v4dwt_decode(&v); - for(k = 0; k < rh; ++k){ - memcpy(&aj[k*w], &v.wavelet[k], j * sizeof(float)); - } - } - } - - opj_aligned_free(h.wavelet); -} - diff --git a/openjpeg-dotnet/libopenjpeg/dwt.h b/openjpeg-dotnet/libopenjpeg/dwt.h deleted file mode 100644 index adf73e54..00000000 --- a/openjpeg-dotnet/libopenjpeg/dwt.h +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium - * Copyright (c) 2002-2007, Professor Benoit Macq - * Copyright (c) 2001-2003, David Janssens - * Copyright (c) 2002-2003, Yannick Verschueren - * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe - * Copyright (c) 2005, Herve Drolon, FreeImage Team - * 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 -/** -@file dwt.h -@brief Implementation of a discrete wavelet transform (DWT) - -The functions in DWT.C have for goal to realize forward and inverse discret wavelet -transform with filter 5-3 (reversible) and filter 9-7 (irreversible). The functions in -DWT.C are used by some function in TCD.C. -*/ - -/** @defgroup DWT DWT - Implementation of a discrete wavelet transform */ -/*@{*/ - - -/** @name Exported functions */ -/*@{*/ -/* ----------------------------------------------------------------------- */ -/** -Forward 5-3 wavelet tranform in 2-D. -Apply a reversible DWT transform to a component of an image. -@param tilec Tile component information (current tile) -*/ -void dwt_encode(opj_tcd_tilecomp_t * tilec); -/** -Inverse 5-3 wavelet tranform in 2-D. -Apply a reversible inverse DWT transform to a component of an image. -@param tilec Tile component information (current tile) -@param numres Number of resolution levels to decode -*/ -void dwt_decode(opj_tcd_tilecomp_t* tilec, int numres); -/** -Get the gain of a subband for the reversible 5-3 DWT. -@param orient Number that identifies the subband (0->LL, 1->HL, 2->LH, 3->HH) -@return Returns 0 if orient = 0, returns 1 if orient = 1 or 2, returns 2 otherwise -*/ -int dwt_getgain(int orient); -/** -Get the norm of a wavelet function of a subband at a specified level for the reversible 5-3 DWT. -@param level Level of the wavelet function -@param orient Band of the wavelet function -@return Returns the norm of the wavelet function -*/ -double dwt_getnorm(int level, int orient); -/** -Forward 9-7 wavelet transform in 2-D. -Apply an irreversible DWT transform to a component of an image. -@param tilec Tile component information (current tile) -*/ -void dwt_encode_real(opj_tcd_tilecomp_t * tilec); -/** -Inverse 9-7 wavelet transform in 2-D. -Apply an irreversible inverse DWT transform to a component of an image. -@param tilec Tile component information (current tile) -@param numres Number of resolution levels to decode -*/ -void dwt_decode_real(opj_tcd_tilecomp_t* tilec, int numres); -/** -Get the gain of a subband for the irreversible 9-7 DWT. -@param orient Number that identifies the subband (0->LL, 1->HL, 2->LH, 3->HH) -@return Returns the gain of the 9-7 wavelet transform -*/ -int dwt_getgain_real(int orient); -/** -Get the norm of a wavelet function of a subband at a specified level for the irreversible 9-7 DWT -@param level Level of the wavelet function -@param orient Band of the wavelet function -@return Returns the norm of the 9-7 wavelet -*/ -double dwt_getnorm_real(int level, int orient); -/** -Explicit calculation of the Quantization Stepsizes -@param tccp Tile-component coding parameters -@param prec Precint analyzed -*/ -void dwt_calc_explicit_stepsizes(opj_tccp_t * tccp, int prec); -/* ----------------------------------------------------------------------- */ -/*@}*/ - -/*@}*/ - -#endif /* __DWT_H */ diff --git a/openjpeg-dotnet/libopenjpeg/event.c b/openjpeg-dotnet/libopenjpeg/event.c deleted file mode 100644 index 0dc22f12..00000000 --- a/openjpeg-dotnet/libopenjpeg/event.c +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Copyright (c) 2005, Herve Drolon, FreeImage Team - * 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 "opj_includes.h" - -/* ========================================================== - Utility functions - ==========================================================*/ - -#ifdef OPJ_CODE_NOT_USED -#ifndef _WIN32 -static char* -i2a(unsigned i, char *a, unsigned r) { - if (i/r > 0) a = i2a(i/r,a,r); - *a = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"[i%r]; - return a+1; -} - -/** - Transforms integer i into an ascii string and stores the result in a; - string is encoded in the base indicated by r. - @param i Number to be converted - @param a String result - @param r Base of value; must be in the range 2 - 36 - @return Returns a -*/ -static char * -_itoa(int i, char *a, int r) { - r = ((r < 2) || (r > 36)) ? 10 : r; - if(i < 0) { - *a = '-'; - *i2a(-i, a+1, r) = 0; - } - else *i2a(i, a, r) = 0; - return a; -} - -#endif /* !_WIN32 */ -#endif -/* ----------------------------------------------------------------------- */ - -opj_event_mgr_t* OPJ_CALLCONV opj_set_event_mgr(opj_common_ptr cinfo, opj_event_mgr_t *event_mgr, void *context) { - if(cinfo) { - opj_event_mgr_t *previous = cinfo->event_mgr; - cinfo->event_mgr = event_mgr; - cinfo->client_data = context; - return previous; - } - - return NULL; -} - -opj_bool opj_event_msg(opj_common_ptr cinfo, int event_type, const char *fmt, ...) { -#define MSG_SIZE 512 /* 512 bytes should be more than enough for a short message */ - opj_msg_callback msg_handler = NULL; - - opj_event_mgr_t *event_mgr = cinfo->event_mgr; - if(event_mgr != NULL) { - switch(event_type) { - case EVT_ERROR: - msg_handler = event_mgr->error_handler; - break; - case EVT_WARNING: - msg_handler = event_mgr->warning_handler; - break; - case EVT_INFO: - msg_handler = event_mgr->info_handler; - break; - default: - break; - } - if(msg_handler == NULL) { - return OPJ_FALSE; - } - } else { - return OPJ_FALSE; - } - - if ((fmt != NULL) && (event_mgr != NULL)) { - va_list arg; - int str_length/*, i, j*/; /* UniPG */ - char message[MSG_SIZE]; - memset(message, 0, MSG_SIZE); - /* initialize the optional parameter list */ - va_start(arg, fmt); - /* check the length of the format string */ - str_length = (strlen(fmt) > MSG_SIZE) ? MSG_SIZE : strlen(fmt); - /* parse the format string and put the result in 'message' */ - vsprintf(message, fmt, arg); /* UniPG */ - /* deinitialize the optional parameter list */ - va_end(arg); - - /* output the message to the user program */ - msg_handler(message, cinfo->client_data); - } - - return OPJ_TRUE; -} - diff --git a/openjpeg-dotnet/libopenjpeg/event.h b/openjpeg-dotnet/libopenjpeg/event.h deleted file mode 100644 index 9c59787c..00000000 --- a/openjpeg-dotnet/libopenjpeg/event.h +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (c) 2005, Herve Drolon, FreeImage Team - * 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 __EVENT_H -#define __EVENT_H -/** -@file event.h -@brief Implementation of a event callback system - -The functions in EVENT.C have for goal to send output messages (errors, warnings, debug) to the user. -*/ - -#define EVT_ERROR 1 /**< Error event type */ -#define EVT_WARNING 2 /**< Warning event type */ -#define EVT_INFO 4 /**< Debug event type */ - -/** @defgroup EVENT EVENT - Implementation of a event callback system */ -/*@{*/ - -/** @name Exported functions (see also openjpeg.h) */ -/*@{*/ -/* ----------------------------------------------------------------------- */ -/** -Write formatted data to a string and send the string to a user callback. -@param cinfo Codec context info -@param event_type Event type or callback to use to send the message -@param fmt Format-control string (plus optionnal arguments) -@return Returns true if successful, returns false otherwise -*/ -opj_bool opj_event_msg(opj_common_ptr cinfo, int event_type, const char *fmt, ...); -/* ----------------------------------------------------------------------- */ -/*@}*/ - -/*@}*/ - -#endif /* __EVENT_H */ diff --git a/openjpeg-dotnet/libopenjpeg/fix.h b/openjpeg-dotnet/libopenjpeg/fix.h deleted file mode 100644 index bcb2acb5..00000000 --- a/openjpeg-dotnet/libopenjpeg/fix.h +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium - * Copyright (c) 2002-2007, Professor Benoit Macq - * Copyright (c) 2001-2003, David Janssens - * Copyright (c) 2002-2003, Yannick Verschueren - * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe - * Copyright (c) 2005, Herve Drolon, FreeImage Team - * 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 - -#if defined(_MSC_VER) || defined(__BORLANDC__) -#define int64 __int64 -#else -#define int64 long long -#endif - -/** -@file fix.h -@brief Implementation of operations of specific multiplication (FIX) - -The functions in FIX.H have for goal to realize specific multiplication. -*/ - -/** @defgroup FIX FIX - Implementation of operations of specific multiplication */ -/*@{*/ - -/** -Multiply two fixed-precision rational numbers. -@param a -@param b -@return Returns a * b -*/ -static INLINE int fix_mul(int a, int b) { - int64 temp = (int64) a * (int64) b ; - temp += temp & 4096; - return (int) (temp >> 13) ; -} - -/*@}*/ - -#endif /* __FIX_H */ diff --git a/openjpeg-dotnet/libopenjpeg/image.c b/openjpeg-dotnet/libopenjpeg/image.c deleted file mode 100644 index a4d2c010..00000000 --- a/openjpeg-dotnet/libopenjpeg/image.c +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright (c) 2005, Herve Drolon, FreeImage Team - * 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 "opj_includes.h" - -opj_image_t* opj_image_create0(void) { - opj_image_t *image = (opj_image_t*)opj_calloc(1, sizeof(opj_image_t)); - return image; -} - -opj_image_t* OPJ_CALLCONV opj_image_create(int numcmpts, opj_image_cmptparm_t *cmptparms, OPJ_COLOR_SPACE clrspc) { - int compno; - opj_image_t *image = NULL; - - image = (opj_image_t*) opj_calloc(1, sizeof(opj_image_t)); - if(image) { - image->color_space = clrspc; - image->numcomps = numcmpts; - /* allocate memory for the per-component information */ - image->comps = (opj_image_comp_t*)opj_malloc(image->numcomps * sizeof(opj_image_comp_t)); - if(!image->comps) { - fprintf(stderr,"Unable to allocate memory for image.\n"); - opj_image_destroy(image); - return NULL; - } - /* create the individual image components */ - for(compno = 0; compno < numcmpts; compno++) { - opj_image_comp_t *comp = &image->comps[compno]; - comp->dx = cmptparms[compno].dx; - comp->dy = cmptparms[compno].dy; - comp->w = cmptparms[compno].w; - comp->h = cmptparms[compno].h; - comp->x0 = cmptparms[compno].x0; - comp->y0 = cmptparms[compno].y0; - comp->prec = cmptparms[compno].prec; - comp->bpp = cmptparms[compno].bpp; - comp->sgnd = cmptparms[compno].sgnd; - comp->data = (int*) opj_calloc(comp->w * comp->h, sizeof(int)); - if(!comp->data) { - fprintf(stderr,"Unable to allocate memory for image.\n"); - opj_image_destroy(image); - return NULL; - } - } - } - - return image; -} - -void OPJ_CALLCONV opj_image_destroy(opj_image_t *image) { - int i; - if(image) { - if(image->comps) { - /* image components */ - for(i = 0; i < image->numcomps; i++) { - opj_image_comp_t *image_comp = &image->comps[i]; - if(image_comp->data) { - opj_free(image_comp->data); - } - } - opj_free(image->comps); - } - opj_free(image); - } -} - diff --git a/openjpeg-dotnet/libopenjpeg/image.h b/openjpeg-dotnet/libopenjpeg/image.h deleted file mode 100644 index f828b5b7..00000000 --- a/openjpeg-dotnet/libopenjpeg/image.h +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2005, Herve Drolon, FreeImage Team - * 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 __IMAGE_H -#define __IMAGE_H -/** -@file image.h -@brief Implementation of operations on images (IMAGE) - -The functions in IMAGE.C have for goal to realize operations on images. -*/ - -/** @defgroup IMAGE IMAGE - Implementation of operations on images */ -/*@{*/ - -/** -Create an empty image -@todo this function should be removed -@return returns an empty image if successful, returns NULL otherwise -*/ -opj_image_t* opj_image_create0(void); - -/*@}*/ - -#endif /* __IMAGE_H */ - diff --git a/openjpeg-dotnet/libopenjpeg/indexbox_manager.h b/openjpeg-dotnet/libopenjpeg/indexbox_manager.h deleted file mode 100644 index 7364df62..00000000 --- a/openjpeg-dotnet/libopenjpeg/indexbox_manager.h +++ /dev/null @@ -1,118 +0,0 @@ -/* - * $Id: indexbox_manager.h 897 2011-08-28 21:43:57Z Kaori.Hagihara@gmail.com $ - * - * Copyright (c) 2002-2011, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium - * Copyright (c) 2002-2011, Professor Benoit Macq - * Copyright (c) 2003-2004, Yannick Verschueren - * Copyright (c) 2010-2011, Kaori Hagihara - * 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. - */ - -/*! \file - * \brief Modification of jpip.c from 2KAN indexer - */ - -#ifndef INDEXBOX_MANAGER_H_ -# define INDEXBOX_MANAGER_H_ - -#include "openjpeg.h" -#include "j2k.h" /* needed to use jp2.h */ -#include "jp2.h" - -#define JPIP_CIDX 0x63696478 /* Codestream index */ -#define JPIP_CPTR 0x63707472 /* Codestream Finder Box */ -#define JPIP_MANF 0x6d616e66 /* Manifest Box */ -#define JPIP_FAIX 0x66616978 /* Fragment array Index box */ -#define JPIP_MHIX 0x6d686978 /* Main Header Index Table */ -#define JPIP_TPIX 0x74706978 /* Tile-part Index Table box */ -#define JPIP_THIX 0x74686978 /* Tile header Index Table box */ -#define JPIP_PPIX 0x70706978 /* Precinct Packet Index Table box */ -#define JPIP_PHIX 0x70686978 /* Packet Header index Table */ -#define JPIP_FIDX 0x66696478 /* File Index */ -#define JPIP_FPTR 0x66707472 /* File Finder */ -#define JPIP_PRXY 0x70727879 /* Proxy boxes */ -#define JPIP_IPTR 0x69707472 /* Index finder box */ -#define JPIP_PHLD 0x70686c64 /* Place holder */ - - -/* - * Write tile-part Index table box (superbox) - * - * @param[in] coff offset of j2k codestream - * @param[in] cstr_info codestream information - * @param[in] j2klen length of j2k codestream - * @param[in] cio file output handle - * @return length of tpix box - */ -int write_tpix( int coff, opj_codestream_info_t cstr_info, int j2klen, opj_cio_t *cio); - - -/* - * Write tile header index table box (superbox) - * - * @param[in] coff offset of j2k codestream - * @param[in] cstr_info codestream information pointer - * @param[in] cio file output handle - * @return length of thix box - */ -int write_thix( int coff, opj_codestream_info_t cstr_info, opj_cio_t *cio); - - -/* - * Write precinct packet index table box (superbox) - * - * @param[in] coff offset of j2k codestream - * @param[in] cstr_info codestream information - * @param[in] EPHused true if EPH option used - * @param[in] j2klen length of j2k codestream - * @param[in] cio file output handle - * @return length of ppix box - */ -int write_ppix( int coff, opj_codestream_info_t cstr_info, opj_bool EPHused, int j2klen, opj_cio_t *cio); - - -/* - * Write packet header index table box (superbox) - * - * @param[in] coff offset of j2k codestream - * @param[in] cstr_info codestream information - * @param[in] EPHused true if EPH option used - * @param[in] j2klen length of j2k codestream - * @param[in] cio file output handle - * @return length of ppix box - */ -int write_phix( int coff, opj_codestream_info_t cstr_info, opj_bool EPHused, int j2klen, opj_cio_t *cio); - -/* - * Wriet manifest box (box) - * - * @param[in] second number to be visited - * @param[in] v number of boxes - * @param[in] box box to be manifested - * @param[in] cio file output handle - */ -void write_manf(int second, int v, opj_jp2_box_t *box, opj_cio_t *cio); - - -#endif /* !INDEXBOX_MANAGER_H_ */ diff --git a/openjpeg-dotnet/libopenjpeg/int.h b/openjpeg-dotnet/libopenjpeg/int.h deleted file mode 100644 index 4e5fe08e..00000000 --- a/openjpeg-dotnet/libopenjpeg/int.h +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium - * Copyright (c) 2002-2007, Professor Benoit Macq - * Copyright (c) 2001-2003, David Janssens - * Copyright (c) 2002-2003, Yannick Verschueren - * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe - * Copyright (c) 2005, Herve Drolon, FreeImage Team - * 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 -/** -@file int.h -@brief Implementation of operations on integers (INT) - -The functions in INT.H have for goal to realize operations on integers. -*/ - -/** @defgroup INT INT - Implementation of operations on integers */ -/*@{*/ - -/** @name Exported functions (see also openjpeg.h) */ -/*@{*/ -/* ----------------------------------------------------------------------- */ -/** -Get the minimum of two integers -@return Returns a if a < b else b -*/ -static INLINE int int_min(int a, int b) { - return a < b ? a : b; -} -/** -Get the maximum of two integers -@return Returns a if a > b else b -*/ -static INLINE int int_max(int a, int b) { - return (a > b) ? a : b; -} -/** -Clamp an integer inside an interval -@return -
      -
    • Returns a if (min < a < max) -
    • Returns max if (a > max) -
    • Returns min if (a < min) -
    -*/ -static INLINE int int_clamp(int a, int min, int max) { - if (a < min) - return min; - if (a > max) - return max; - return a; -} -/** -@return Get absolute value of integer -*/ -static INLINE int int_abs(int a) { - return a < 0 ? -a : a; -} -/** -Divide an integer and round upwards -@return Returns a divided by b -*/ -static INLINE int int_ceildiv(int a, int b) { - return (a + b - 1) / b; -} -/** -Divide an integer by a power of 2 and round upwards -@return Returns a divided by 2^b -*/ -static INLINE int int_ceildivpow2(int a, int b) { - return (a + (1 << b) - 1) >> b; -} -/** -Divide an integer by a power of 2 and round downwards -@return Returns a divided by 2^b -*/ -static INLINE int int_floordivpow2(int a, int b) { - return a >> b; -} -/** -Get logarithm of an integer and round downwards -@return Returns log2(a) -*/ -static INLINE int int_floorlog2(int a) { - int l; - for (l = 0; a > 1; l++) { - a >>= 1; - } - return l; -} -/* ----------------------------------------------------------------------- */ -/*@}*/ - -/*@}*/ - -#endif diff --git a/openjpeg-dotnet/libopenjpeg/j2k.c b/openjpeg-dotnet/libopenjpeg/j2k.c deleted file mode 100644 index d34c75fa..00000000 --- a/openjpeg-dotnet/libopenjpeg/j2k.c +++ /dev/null @@ -1,2534 +0,0 @@ -/* - * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium - * Copyright (c) 2002-2007, Professor Benoit Macq - * Copyright (c) 2001-2003, David Janssens - * Copyright (c) 2002-2003, Yannick Verschueren - * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe - * Copyright (c) 2005, Herve Drolon, FreeImage Team - * Copyright (c) 2006-2007, Parvatha Elangovan - * Copyright (c) 2010-2011, Kaori Hagihara - * 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 "opj_includes.h" - -/** @defgroup J2K J2K - JPEG-2000 codestream reader/writer */ -/*@{*/ - -/** @name Local static functions */ -/*@{*/ - -/** -Write the SOC marker (Start Of Codestream) -@param j2k J2K handle -*/ -static void j2k_write_soc(opj_j2k_t *j2k); -/** -Read the SOC marker (Start of Codestream) -@param j2k J2K handle -*/ -static void j2k_read_soc(opj_j2k_t *j2k); -/** -Write the SIZ marker (image and tile size) -@param j2k J2K handle -*/ -static void j2k_write_siz(opj_j2k_t *j2k); -/** -Read the SIZ marker (image and tile size) -@param j2k J2K handle -*/ -static void j2k_read_siz(opj_j2k_t *j2k); -/** -Write the COM marker (comment) -@param j2k J2K handle -*/ -static void j2k_write_com(opj_j2k_t *j2k); -/** -Read the COM marker (comment) -@param j2k J2K handle -*/ -static void j2k_read_com(opj_j2k_t *j2k); -/** -Write the value concerning the specified component in the marker COD and COC -@param j2k J2K handle -@param compno Number of the component concerned by the information written -*/ -static void j2k_write_cox(opj_j2k_t *j2k, int compno); -/** -Read the value concerning the specified component in the marker COD and COC -@param j2k J2K handle -@param compno Number of the component concerned by the information read -*/ -static void j2k_read_cox(opj_j2k_t *j2k, int compno); -/** -Write the COD marker (coding style default) -@param j2k J2K handle -*/ -static void j2k_write_cod(opj_j2k_t *j2k); -/** -Read the COD marker (coding style default) -@param j2k J2K handle -*/ -static void j2k_read_cod(opj_j2k_t *j2k); -/** -Write the COC marker (coding style component) -@param j2k J2K handle -@param compno Number of the component concerned by the information written -*/ -static void j2k_write_coc(opj_j2k_t *j2k, int compno); -/** -Read the COC marker (coding style component) -@param j2k J2K handle -*/ -static void j2k_read_coc(opj_j2k_t *j2k); -/** -Write the value concerning the specified component in the marker QCD and QCC -@param j2k J2K handle -@param compno Number of the component concerned by the information written -*/ -static void j2k_write_qcx(opj_j2k_t *j2k, int compno); -/** -Read the value concerning the specified component in the marker QCD and QCC -@param j2k J2K handle -@param compno Number of the component concern by the information read -@param len Length of the information in the QCX part of the marker QCD/QCC -*/ -static void j2k_read_qcx(opj_j2k_t *j2k, int compno, int len); -/** -Write the QCD marker (quantization default) -@param j2k J2K handle -*/ -static void j2k_write_qcd(opj_j2k_t *j2k); -/** -Read the QCD marker (quantization default) -@param j2k J2K handle -*/ -static void j2k_read_qcd(opj_j2k_t *j2k); -/** -Write the QCC marker (quantization component) -@param j2k J2K handle -@param compno Number of the component concerned by the information written -*/ -static void j2k_write_qcc(opj_j2k_t *j2k, int compno); -/** -Read the QCC marker (quantization component) -@param j2k J2K handle -*/ -static void j2k_read_qcc(opj_j2k_t *j2k); -/** -Write the POC marker (progression order change) -@param j2k J2K handle -*/ -static void j2k_write_poc(opj_j2k_t *j2k); -/** -Read the POC marker (progression order change) -@param j2k J2K handle -*/ -static void j2k_read_poc(opj_j2k_t *j2k); -/** -Read the CRG marker (component registration) -@param j2k J2K handle -*/ -static void j2k_read_crg(opj_j2k_t *j2k); -/** -Read the TLM marker (tile-part lengths) -@param j2k J2K handle -*/ -static void j2k_read_tlm(opj_j2k_t *j2k); -/** -Read the PLM marker (packet length, main header) -@param j2k J2K handle -*/ -static void j2k_read_plm(opj_j2k_t *j2k); -/** -Read the PLT marker (packet length, tile-part header) -@param j2k J2K handle -*/ -static void j2k_read_plt(opj_j2k_t *j2k); -/** -Read the PPM marker (packet packet headers, main header) -@param j2k J2K handle -*/ -static void j2k_read_ppm(opj_j2k_t *j2k); -/** -Read the PPT marker (packet packet headers, tile-part header) -@param j2k J2K handle -*/ -static void j2k_read_ppt(opj_j2k_t *j2k); -/** -Write the TLM marker (Mainheader) -@param j2k J2K handle -*/ -static void j2k_write_tlm(opj_j2k_t *j2k); -/** -Write the SOT marker (start of tile-part) -@param j2k J2K handle -*/ -static void j2k_write_sot(opj_j2k_t *j2k); -/** -Read the SOT marker (start of tile-part) -@param j2k J2K handle -*/ -static void j2k_read_sot(opj_j2k_t *j2k); -/** -Write the SOD marker (start of data) -@param j2k J2K handle -@param tile_coder Pointer to a TCD handle -*/ -static void j2k_write_sod(opj_j2k_t *j2k, void *tile_coder); -/** -Read the SOD marker (start of data) -@param j2k J2K handle -*/ -static void j2k_read_sod(opj_j2k_t *j2k); -/** -Write the RGN marker (region-of-interest) -@param j2k J2K handle -@param compno Number of the component concerned by the information written -@param tileno Number of the tile concerned by the information written -*/ -static void j2k_write_rgn(opj_j2k_t *j2k, int compno, int tileno); -/** -Read the RGN marker (region-of-interest) -@param j2k J2K handle -*/ -static void j2k_read_rgn(opj_j2k_t *j2k); -/** -Write the EOC marker (end of codestream) -@param j2k J2K handle -*/ -static void j2k_write_eoc(opj_j2k_t *j2k); -/** -Read the EOC marker (end of codestream) -@param j2k J2K handle -*/ -static void j2k_read_eoc(opj_j2k_t *j2k); -/** -Read an unknown marker -@param j2k J2K handle -*/ -static void j2k_read_unk(opj_j2k_t *j2k); -/** -Add main header marker information -@param cstr_info Codestream information structure -@param type marker type -@param pos byte offset of marker segment -@param len length of marker segment - */ -static void j2k_add_mhmarker(opj_codestream_info_t *cstr_info, unsigned short int type, int pos, int len); -/** -Add tile header marker information -@param tileno tile index number -@param cstr_info Codestream information structure -@param type marker type -@param pos byte offset of marker segment -@param len length of marker segment - */ -static void j2k_add_tlmarker( int tileno, opj_codestream_info_t *cstr_info, unsigned short int type, int pos, int len); - -/*@}*/ - -/*@}*/ - -/* ----------------------------------------------------------------------- */ -typedef struct j2k_prog_order{ - OPJ_PROG_ORDER enum_prog; - char str_prog[5]; -}j2k_prog_order_t; - -j2k_prog_order_t j2k_prog_order_list[] = { - {CPRL, "CPRL"}, - {LRCP, "LRCP"}, - {PCRL, "PCRL"}, - {RLCP, "RLCP"}, - {RPCL, "RPCL"}, - {(OPJ_PROG_ORDER)-1, ""} -}; - -char *j2k_convert_progression_order(OPJ_PROG_ORDER prg_order){ - j2k_prog_order_t *po; - for(po = j2k_prog_order_list; po->enum_prog != -1; po++ ){ - if(po->enum_prog == prg_order){ - break; - } - } - return po->str_prog; -} - -/* ----------------------------------------------------------------------- */ -static int j2k_get_num_tp(opj_cp_t *cp,int pino,int tileno){ - char *prog; - int i; - int tpnum=1,tpend=0; - opj_tcp_t *tcp = &cp->tcps[tileno]; - prog = j2k_convert_progression_order(tcp->prg); - - if(cp->tp_on == 1){ - for(i=0;i<4;i++){ - if(tpend!=1){ - if( cp->tp_flag == prog[i] ){ - tpend=1;cp->tp_pos=i; - } - switch(prog[i]){ - case 'C': - tpnum= tpnum * tcp->pocs[pino].compE; - break; - case 'R': - tpnum= tpnum * tcp->pocs[pino].resE; - break; - case 'P': - tpnum= tpnum * tcp->pocs[pino].prcE; - break; - case 'L': - tpnum= tpnum * tcp->pocs[pino].layE; - break; - } - } - } - }else{ - tpnum=1; - } - return tpnum; -} - -/** mem allocation for TLM marker*/ -int j2k_calculate_tp(opj_cp_t *cp,int img_numcomp,opj_image_t *image,opj_j2k_t *j2k ){ - int pino,tileno,totnum_tp=0; - - OPJ_ARG_NOT_USED(img_numcomp); - - j2k->cur_totnum_tp = (int *) opj_malloc(cp->tw * cp->th * sizeof(int)); - for (tileno = 0; tileno < cp->tw * cp->th; tileno++) { - int cur_totnum_tp = 0; - opj_tcp_t *tcp = &cp->tcps[tileno]; - for(pino = 0; pino <= tcp->numpocs; pino++) { - int tp_num=0; - opj_pi_iterator_t *pi = pi_initialise_encode(image, cp, tileno,FINAL_PASS); - if(!pi) { return -1;} - tp_num = j2k_get_num_tp(cp,pino,tileno); - totnum_tp = totnum_tp + tp_num; - cur_totnum_tp = cur_totnum_tp + tp_num; - pi_destroy(pi, cp, tileno); - } - j2k->cur_totnum_tp[tileno] = cur_totnum_tp; - /* INDEX >> */ - if (j2k->cstr_info) { - j2k->cstr_info->tile[tileno].num_tps = cur_totnum_tp; - j2k->cstr_info->tile[tileno].tp = (opj_tp_info_t *) opj_malloc(cur_totnum_tp * sizeof(opj_tp_info_t)); - } - /* << INDEX */ - } - return totnum_tp; -} - -static void j2k_write_soc(opj_j2k_t *j2k) { - opj_cio_t *cio = j2k->cio; - cio_write(cio, J2K_MS_SOC, 2); - - if(j2k->cstr_info) - j2k_add_mhmarker(j2k->cstr_info, J2K_MS_SOC, cio_tell(cio), 0); - -/* UniPG>> */ -#ifdef USE_JPWL - - /* update markers struct */ - j2k_add_marker(j2k->cstr_info, J2K_MS_SOC, cio_tell(cio) - 2, 2); -#endif /* USE_JPWL */ -/* <state = J2K_STATE_MHSIZ; - /* Index */ - if (j2k->cstr_info) { - j2k->cstr_info->main_head_start = cio_tell(j2k->cio) - 2; - j2k->cstr_info->codestream_size = cio_numbytesleft(j2k->cio) + 2 - j2k->cstr_info->main_head_start; - } -} - -static void j2k_write_siz(opj_j2k_t *j2k) { - int i; - int lenp, len; - - opj_cio_t *cio = j2k->cio; - opj_image_t *image = j2k->image; - opj_cp_t *cp = j2k->cp; - - cio_write(cio, J2K_MS_SIZ, 2); /* SIZ */ - lenp = cio_tell(cio); - cio_skip(cio, 2); - cio_write(cio, cp->rsiz, 2); /* Rsiz (capabilities) */ - cio_write(cio, image->x1, 4); /* Xsiz */ - cio_write(cio, image->y1, 4); /* Ysiz */ - cio_write(cio, image->x0, 4); /* X0siz */ - cio_write(cio, image->y0, 4); /* Y0siz */ - cio_write(cio, cp->tdx, 4); /* XTsiz */ - cio_write(cio, cp->tdy, 4); /* YTsiz */ - cio_write(cio, cp->tx0, 4); /* XT0siz */ - cio_write(cio, cp->ty0, 4); /* YT0siz */ - cio_write(cio, image->numcomps, 2); /* Csiz */ - for (i = 0; i < image->numcomps; i++) { - cio_write(cio, image->comps[i].prec - 1 + (image->comps[i].sgnd << 7), 1); /* Ssiz_i */ - cio_write(cio, image->comps[i].dx, 1); /* XRsiz_i */ - cio_write(cio, image->comps[i].dy, 1); /* YRsiz_i */ - } - len = cio_tell(cio) - lenp; - cio_seek(cio, lenp); - cio_write(cio, len, 2); /* Lsiz */ - cio_seek(cio, lenp + len); - - if(j2k->cstr_info) - j2k_add_mhmarker(j2k->cstr_info, J2K_MS_SIZ, lenp, len); -} - -static void j2k_read_siz(opj_j2k_t *j2k) { - int len, i; - - opj_cio_t *cio = j2k->cio; - opj_image_t *image = j2k->image; - opj_cp_t *cp = j2k->cp; - - len = cio_read(cio, 2); /* Lsiz */ - cio_read(cio, 2); /* Rsiz (capabilities) */ - image->x1 = cio_read(cio, 4); /* Xsiz */ - image->y1 = cio_read(cio, 4); /* Ysiz */ - image->x0 = cio_read(cio, 4); /* X0siz */ - image->y0 = cio_read(cio, 4); /* Y0siz */ - cp->tdx = cio_read(cio, 4); /* XTsiz */ - cp->tdy = cio_read(cio, 4); /* YTsiz */ - cp->tx0 = cio_read(cio, 4); /* XT0siz */ - cp->ty0 = cio_read(cio, 4); /* YT0siz */ - - if ((image->x0<0)||(image->x1<0)||(image->y0<0)||(image->y1<0)) { - opj_event_msg(j2k->cinfo, EVT_ERROR, - "%s: invalid image size (x0:%d, x1:%d, y0:%d, y1:%d)\n", - image->x0,image->x1,image->y0,image->y1); - return; - } - - image->numcomps = cio_read(cio, 2); /* Csiz */ - -#ifdef USE_JPWL - if (j2k->cp->correct) { - /* if JPWL is on, we check whether TX errors have damaged - too much the SIZ parameters */ - if (!(image->x1 * image->y1)) { - opj_event_msg(j2k->cinfo, EVT_ERROR, - "JPWL: bad image size (%d x %d)\n", - image->x1, image->y1); - if (!JPWL_ASSUME || JPWL_ASSUME) { - opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n"); - return; - } - } - if (image->numcomps != ((len - 38) / 3)) { - opj_event_msg(j2k->cinfo, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR, - "JPWL: Csiz is %d => space in SIZ only for %d comps.!!!\n", - image->numcomps, ((len - 38) / 3)); - if (!JPWL_ASSUME) { - opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n"); - return; - } - /* we try to correct */ - opj_event_msg(j2k->cinfo, EVT_WARNING, "- trying to adjust this\n"); - if (image->numcomps < ((len - 38) / 3)) { - len = 38 + 3 * image->numcomps; - opj_event_msg(j2k->cinfo, EVT_WARNING, "- setting Lsiz to %d => HYPOTHESIS!!!\n", - len); - } else { - image->numcomps = ((len - 38) / 3); - opj_event_msg(j2k->cinfo, EVT_WARNING, "- setting Csiz to %d => HYPOTHESIS!!!\n", - image->numcomps); - } - } - - /* update components number in the jpwl_exp_comps filed */ - cp->exp_comps = image->numcomps; - } -#endif /* USE_JPWL */ - - image->comps = (opj_image_comp_t*) opj_calloc(image->numcomps, sizeof(opj_image_comp_t)); - for (i = 0; i < image->numcomps; i++) { - int tmp, w, h; - tmp = cio_read(cio, 1); /* Ssiz_i */ - image->comps[i].prec = (tmp & 0x7f) + 1; - image->comps[i].sgnd = tmp >> 7; - image->comps[i].dx = cio_read(cio, 1); /* XRsiz_i */ - image->comps[i].dy = cio_read(cio, 1); /* YRsiz_i */ - -#ifdef USE_JPWL - if (j2k->cp->correct) { - /* if JPWL is on, we check whether TX errors have damaged - too much the SIZ parameters, again */ - if (!(image->comps[i].dx * image->comps[i].dy)) { - opj_event_msg(j2k->cinfo, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR, - "JPWL: bad XRsiz_%d/YRsiz_%d (%d x %d)\n", - i, i, image->comps[i].dx, image->comps[i].dy); - if (!JPWL_ASSUME) { - opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n"); - return; - } - /* we try to correct */ - opj_event_msg(j2k->cinfo, EVT_WARNING, "- trying to adjust them\n"); - if (!image->comps[i].dx) { - image->comps[i].dx = 1; - opj_event_msg(j2k->cinfo, EVT_WARNING, "- setting XRsiz_%d to %d => HYPOTHESIS!!!\n", - i, image->comps[i].dx); - } - if (!image->comps[i].dy) { - image->comps[i].dy = 1; - opj_event_msg(j2k->cinfo, EVT_WARNING, "- setting YRsiz_%d to %d => HYPOTHESIS!!!\n", - i, image->comps[i].dy); - } - } - - } -#endif /* USE_JPWL */ - - /* TODO: unused ? */ - w = int_ceildiv(image->x1 - image->x0, image->comps[i].dx); - h = int_ceildiv(image->y1 - image->y0, image->comps[i].dy); - - image->comps[i].resno_decoded = 0; /* number of resolution decoded */ - image->comps[i].factor = cp->reduce; /* reducing factor per component */ - } - - cp->tw = int_ceildiv(image->x1 - cp->tx0, cp->tdx); - cp->th = int_ceildiv(image->y1 - cp->ty0, cp->tdy); - -#ifdef USE_JPWL - if (j2k->cp->correct) { - /* if JPWL is on, we check whether TX errors have damaged - too much the SIZ parameters */ - if ((cp->tw < 1) || (cp->th < 1) || (cp->tw > cp->max_tiles) || (cp->th > cp->max_tiles)) { - opj_event_msg(j2k->cinfo, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR, - "JPWL: bad number of tiles (%d x %d)\n", - cp->tw, cp->th); - if (!JPWL_ASSUME) { - opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n"); - return; - } - /* we try to correct */ - opj_event_msg(j2k->cinfo, EVT_WARNING, "- trying to adjust them\n"); - if (cp->tw < 1) { - cp->tw= 1; - opj_event_msg(j2k->cinfo, EVT_WARNING, "- setting %d tiles in x => HYPOTHESIS!!!\n", - cp->tw); - } - if (cp->tw > cp->max_tiles) { - cp->tw= 1; - opj_event_msg(j2k->cinfo, EVT_WARNING, "- too large x, increase expectance of %d\n" - "- setting %d tiles in x => HYPOTHESIS!!!\n", - cp->max_tiles, cp->tw); - } - if (cp->th < 1) { - cp->th= 1; - opj_event_msg(j2k->cinfo, EVT_WARNING, "- setting %d tiles in y => HYPOTHESIS!!!\n", - cp->th); - } - if (cp->th > cp->max_tiles) { - cp->th= 1; - opj_event_msg(j2k->cinfo, EVT_WARNING, "- too large y, increase expectance of %d to continue\n", - "- setting %d tiles in y => HYPOTHESIS!!!\n", - cp->max_tiles, cp->th); - } - } - } -#endif /* USE_JPWL */ - - cp->tcps = (opj_tcp_t*) opj_calloc(cp->tw * cp->th, sizeof(opj_tcp_t)); - cp->tileno = (int*) opj_malloc(cp->tw * cp->th * sizeof(int)); - cp->tileno_size = 0; - -#ifdef USE_JPWL - if (j2k->cp->correct) { - if (!cp->tcps) { - opj_event_msg(j2k->cinfo, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR, - "JPWL: could not alloc tcps field of cp\n"); - if (!JPWL_ASSUME || JPWL_ASSUME) { - opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n"); - return; - } - } - } -#endif /* USE_JPWL */ - - for (i = 0; i < cp->tw * cp->th; i++) { - cp->tcps[i].POC = 0; - cp->tcps[i].numpocs = 0; - cp->tcps[i].first = 1; - } - - /* Initialization for PPM marker */ - cp->ppm = 0; - cp->ppm_data = NULL; - cp->ppm_data_first = NULL; - cp->ppm_previous = 0; - cp->ppm_store = 0; - - j2k->default_tcp->tccps = (opj_tccp_t*) opj_calloc(image->numcomps, sizeof(opj_tccp_t)); - for (i = 0; i < cp->tw * cp->th; i++) { - cp->tcps[i].tccps = (opj_tccp_t*) opj_malloc(image->numcomps * sizeof(opj_tccp_t)); - } - j2k->tile_data = (unsigned char**) opj_calloc(cp->tw * cp->th, sizeof(unsigned char*)); - j2k->tile_len = (int*) opj_calloc(cp->tw * cp->th, sizeof(int)); - j2k->state = J2K_STATE_MH; - - /* Index */ - if (j2k->cstr_info) { - opj_codestream_info_t *cstr_info = j2k->cstr_info; - cstr_info->image_w = image->x1 - image->x0; - cstr_info->image_h = image->y1 - image->y0; - cstr_info->numcomps = image->numcomps; - cstr_info->tw = cp->tw; - cstr_info->th = cp->th; - cstr_info->tile_x = cp->tdx; - cstr_info->tile_y = cp->tdy; - cstr_info->tile_Ox = cp->tx0; - cstr_info->tile_Oy = cp->ty0; - cstr_info->tile = (opj_tile_info_t*) opj_calloc(cp->tw * cp->th, sizeof(opj_tile_info_t)); - } -} - -static void j2k_write_com(opj_j2k_t *j2k) { - unsigned int i; - int lenp, len; - - if(j2k->cp->comment) { - opj_cio_t *cio = j2k->cio; - char *comment = j2k->cp->comment; - - cio_write(cio, J2K_MS_COM, 2); - lenp = cio_tell(cio); - cio_skip(cio, 2); - cio_write(cio, 1, 2); /* General use (IS 8859-15:1999 (Latin) values) */ - for (i = 0; i < strlen(comment); i++) { - cio_write(cio, comment[i], 1); - } - len = cio_tell(cio) - lenp; - cio_seek(cio, lenp); - cio_write(cio, len, 2); - cio_seek(cio, lenp + len); - - - if(j2k->cstr_info) - j2k_add_mhmarker(j2k->cstr_info, J2K_MS_COM, lenp, len); - - } -} - -static void j2k_read_com(opj_j2k_t *j2k) { - int len; - - opj_cio_t *cio = j2k->cio; - - len = cio_read(cio, 2); - cio_skip(cio, len - 2); -} - -static void j2k_write_cox(opj_j2k_t *j2k, int compno) { - int i; - - opj_cp_t *cp = j2k->cp; - opj_tcp_t *tcp = &cp->tcps[j2k->curtileno]; - opj_tccp_t *tccp = &tcp->tccps[compno]; - opj_cio_t *cio = j2k->cio; - - cio_write(cio, tccp->numresolutions - 1, 1); /* SPcox (D) */ - cio_write(cio, tccp->cblkw - 2, 1); /* SPcox (E) */ - cio_write(cio, tccp->cblkh - 2, 1); /* SPcox (F) */ - cio_write(cio, tccp->cblksty, 1); /* SPcox (G) */ - cio_write(cio, tccp->qmfbid, 1); /* SPcox (H) */ - - if (tccp->csty & J2K_CCP_CSTY_PRT) { - for (i = 0; i < tccp->numresolutions; i++) { - cio_write(cio, tccp->prcw[i] + (tccp->prch[i] << 4), 1); /* SPcox (I_i) */ - } - } -} - -static void j2k_read_cox(opj_j2k_t *j2k, int compno) { - int i; - - opj_cp_t *cp = j2k->cp; - opj_tcp_t *tcp = j2k->state == J2K_STATE_TPH ? &cp->tcps[j2k->curtileno] : j2k->default_tcp; - opj_tccp_t *tccp = &tcp->tccps[compno]; - opj_cio_t *cio = j2k->cio; - - tccp->numresolutions = cio_read(cio, 1) + 1; /* SPcox (D) */ - - /* If user wants to remove more resolutions than the codestream contains, return error*/ - if (cp->reduce >= tccp->numresolutions) { - opj_event_msg(j2k->cinfo, EVT_ERROR, "Error decoding component %d.\nThe number of resolutions to remove is higher than the number " - "of resolutions of this component\nModify the cp_reduce parameter.\n\n", compno); - j2k->state |= J2K_STATE_ERR; - } - - tccp->cblkw = cio_read(cio, 1) + 2; /* SPcox (E) */ - tccp->cblkh = cio_read(cio, 1) + 2; /* SPcox (F) */ - tccp->cblksty = cio_read(cio, 1); /* SPcox (G) */ - tccp->qmfbid = cio_read(cio, 1); /* SPcox (H) */ - if (tccp->csty & J2K_CP_CSTY_PRT) { - for (i = 0; i < tccp->numresolutions; i++) { - int tmp = cio_read(cio, 1); /* SPcox (I_i) */ - tccp->prcw[i] = tmp & 0xf; - tccp->prch[i] = tmp >> 4; - } - } - - /* INDEX >> */ - if(j2k->cstr_info && compno == 0) { - for (i = 0; i < tccp->numresolutions; i++) { - if (tccp->csty & J2K_CP_CSTY_PRT) { - j2k->cstr_info->tile[j2k->curtileno].pdx[i] = tccp->prcw[i]; - j2k->cstr_info->tile[j2k->curtileno].pdy[i] = tccp->prch[i]; - } - else { - j2k->cstr_info->tile[j2k->curtileno].pdx[i] = 15; - j2k->cstr_info->tile[j2k->curtileno].pdx[i] = 15; - } - } - } - /* << INDEX */ -} - -static void j2k_write_cod(opj_j2k_t *j2k) { - opj_cp_t *cp = NULL; - opj_tcp_t *tcp = NULL; - int lenp, len; - - opj_cio_t *cio = j2k->cio; - - cio_write(cio, J2K_MS_COD, 2); /* COD */ - - lenp = cio_tell(cio); - cio_skip(cio, 2); - - cp = j2k->cp; - tcp = &cp->tcps[j2k->curtileno]; - - cio_write(cio, tcp->csty, 1); /* Scod */ - cio_write(cio, tcp->prg, 1); /* SGcod (A) */ - cio_write(cio, tcp->numlayers, 2); /* SGcod (B) */ - cio_write(cio, tcp->mct, 1); /* SGcod (C) */ - - j2k_write_cox(j2k, 0); - len = cio_tell(cio) - lenp; - cio_seek(cio, lenp); - cio_write(cio, len, 2); /* Lcod */ - cio_seek(cio, lenp + len); - - if(j2k->cstr_info) - j2k_add_mhmarker(j2k->cstr_info, J2K_MS_COD, lenp, len); - -} - -static void j2k_read_cod(opj_j2k_t *j2k) { - int len, i, pos; - - opj_cio_t *cio = j2k->cio; - opj_cp_t *cp = j2k->cp; - opj_tcp_t *tcp = j2k->state == J2K_STATE_TPH ? &cp->tcps[j2k->curtileno] : j2k->default_tcp; - opj_image_t *image = j2k->image; - - len = cio_read(cio, 2); /* Lcod */ - tcp->csty = cio_read(cio, 1); /* Scod */ - tcp->prg = (OPJ_PROG_ORDER)cio_read(cio, 1); /* SGcod (A) */ - tcp->numlayers = cio_read(cio, 2); /* SGcod (B) */ - tcp->mct = cio_read(cio, 1); /* SGcod (C) */ - - pos = cio_tell(cio); - for (i = 0; i < image->numcomps; i++) { - tcp->tccps[i].csty = tcp->csty & J2K_CP_CSTY_PRT; - cio_seek(cio, pos); - j2k_read_cox(j2k, i); - } - - /* Index */ - if (j2k->cstr_info) { - opj_codestream_info_t *cstr_info = j2k->cstr_info; - cstr_info->prog = tcp->prg; - cstr_info->numlayers = tcp->numlayers; - cstr_info->numdecompos = (int*) opj_malloc(image->numcomps * sizeof(int)); - for (i = 0; i < image->numcomps; i++) { - cstr_info->numdecompos[i] = tcp->tccps[i].numresolutions - 1; - } - } -} - -static void j2k_write_coc(opj_j2k_t *j2k, int compno) { - int lenp, len; - - opj_cp_t *cp = j2k->cp; - opj_tcp_t *tcp = &cp->tcps[j2k->curtileno]; - opj_image_t *image = j2k->image; - opj_cio_t *cio = j2k->cio; - - cio_write(cio, J2K_MS_COC, 2); /* COC */ - lenp = cio_tell(cio); - cio_skip(cio, 2); - cio_write(cio, compno, image->numcomps <= 256 ? 1 : 2); /* Ccoc */ - cio_write(cio, tcp->tccps[compno].csty, 1); /* Scoc */ - j2k_write_cox(j2k, compno); - len = cio_tell(cio) - lenp; - cio_seek(cio, lenp); - cio_write(cio, len, 2); /* Lcoc */ - cio_seek(cio, lenp + len); -} - -static void j2k_read_coc(opj_j2k_t *j2k) { - int len, compno; - - opj_cp_t *cp = j2k->cp; - opj_tcp_t *tcp = j2k->state == J2K_STATE_TPH ? &cp->tcps[j2k->curtileno] : j2k->default_tcp; - opj_image_t *image = j2k->image; - opj_cio_t *cio = j2k->cio; - - len = cio_read(cio, 2); /* Lcoc */ - compno = cio_read(cio, image->numcomps <= 256 ? 1 : 2); /* Ccoc */ - tcp->tccps[compno].csty = cio_read(cio, 1); /* Scoc */ - j2k_read_cox(j2k, compno); -} - -static void j2k_write_qcx(opj_j2k_t *j2k, int compno) { - int bandno, numbands; - int expn, mant; - - opj_cp_t *cp = j2k->cp; - opj_tcp_t *tcp = &cp->tcps[j2k->curtileno]; - opj_tccp_t *tccp = &tcp->tccps[compno]; - opj_cio_t *cio = j2k->cio; - - cio_write(cio, tccp->qntsty + (tccp->numgbits << 5), 1); /* Sqcx */ - numbands = tccp->qntsty == J2K_CCP_QNTSTY_SIQNT ? 1 : tccp->numresolutions * 3 - 2; - - for (bandno = 0; bandno < numbands; bandno++) { - expn = tccp->stepsizes[bandno].expn; - mant = tccp->stepsizes[bandno].mant; - - if (tccp->qntsty == J2K_CCP_QNTSTY_NOQNT) { - cio_write(cio, expn << 3, 1); /* SPqcx_i */ - } else { - cio_write(cio, (expn << 11) + mant, 2); /* SPqcx_i */ - } - } -} - -static void j2k_read_qcx(opj_j2k_t *j2k, int compno, int len) { - int tmp; - int bandno, numbands; - - opj_cp_t *cp = j2k->cp; - opj_tcp_t *tcp = j2k->state == J2K_STATE_TPH ? &cp->tcps[j2k->curtileno] : j2k->default_tcp; - opj_tccp_t *tccp = &tcp->tccps[compno]; - opj_cio_t *cio = j2k->cio; - - tmp = cio_read(cio, 1); /* Sqcx */ - 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); - -#ifdef USE_JPWL - if (j2k->cp->correct) { - - /* if JPWL is on, we check whether there are too many subbands */ - if ((numbands < 0) || (numbands >= J2K_MAXBANDS)) { - opj_event_msg(j2k->cinfo, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR, - "JPWL: bad number of subbands in Sqcx (%d)\n", - numbands); - if (!JPWL_ASSUME) { - opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n"); - return; - } - /* we try to correct */ - numbands = 1; - opj_event_msg(j2k->cinfo, EVT_WARNING, "- trying to adjust them\n" - "- setting number of bands to %d => HYPOTHESIS!!!\n", - numbands); - }; - - }; - -#else - /* We check whether there are too many subbands */ - if ((numbands < 0) || (numbands >= J2K_MAXBANDS)) { - opj_event_msg(j2k->cinfo, EVT_WARNING , - "bad number of subbands in Sqcx (%d) regarding to J2K_MAXBANDS (%d) \n" - "- limiting number of bands to J2K_MAXBANDS and try to move to the next markers\n", numbands, J2K_MAXBANDS); - } - -#endif /* USE_JPWL */ - - for (bandno = 0; bandno < numbands; bandno++) { - int expn, mant; - if (tccp->qntsty == J2K_CCP_QNTSTY_NOQNT) { - expn = cio_read(cio, 1) >> 3; /* SPqcx_i */ - mant = 0; - } else { - tmp = cio_read(cio, 2); /* SPqcx_i */ - expn = tmp >> 11; - mant = tmp & 0x7ff; - } - if (bandno < J2K_MAXBANDS){ - tccp->stepsizes[bandno].expn = expn; - tccp->stepsizes[bandno].mant = mant; - } - } - - /* Add Antonin : if scalar_derived -> compute other stepsizes */ - if (tccp->qntsty == J2K_CCP_QNTSTY_SIQNT) { - for (bandno = 1; bandno < J2K_MAXBANDS; bandno++) { - tccp->stepsizes[bandno].expn = - ((tccp->stepsizes[0].expn) - ((bandno - 1) / 3) > 0) ? - (tccp->stepsizes[0].expn) - ((bandno - 1) / 3) : 0; - tccp->stepsizes[bandno].mant = tccp->stepsizes[0].mant; - } - } - /* ddA */ -} - -static void j2k_write_qcd(opj_j2k_t *j2k) { - int lenp, len; - - opj_cio_t *cio = j2k->cio; - - cio_write(cio, J2K_MS_QCD, 2); /* QCD */ - lenp = cio_tell(cio); - cio_skip(cio, 2); - j2k_write_qcx(j2k, 0); - len = cio_tell(cio) - lenp; - cio_seek(cio, lenp); - cio_write(cio, len, 2); /* Lqcd */ - cio_seek(cio, lenp + len); - - if(j2k->cstr_info) - j2k_add_mhmarker(j2k->cstr_info, J2K_MS_QCD, lenp, len); -} - -static void j2k_read_qcd(opj_j2k_t *j2k) { - int len, i, pos; - - opj_cio_t *cio = j2k->cio; - opj_image_t *image = j2k->image; - - len = cio_read(cio, 2); /* Lqcd */ - pos = cio_tell(cio); - for (i = 0; i < image->numcomps; i++) { - cio_seek(cio, pos); - j2k_read_qcx(j2k, i, len - 2); - } -} - -static void j2k_write_qcc(opj_j2k_t *j2k, int compno) { - int lenp, len; - - opj_cio_t *cio = j2k->cio; - - cio_write(cio, J2K_MS_QCC, 2); /* QCC */ - lenp = cio_tell(cio); - cio_skip(cio, 2); - cio_write(cio, compno, j2k->image->numcomps <= 256 ? 1 : 2); /* Cqcc */ - j2k_write_qcx(j2k, compno); - len = cio_tell(cio) - lenp; - cio_seek(cio, lenp); - cio_write(cio, len, 2); /* Lqcc */ - cio_seek(cio, lenp + len); -} - -static void j2k_read_qcc(opj_j2k_t *j2k) { - int len, compno; - int numcomp = j2k->image->numcomps; - opj_cio_t *cio = j2k->cio; - - len = cio_read(cio, 2); /* Lqcc */ - compno = cio_read(cio, numcomp <= 256 ? 1 : 2); /* Cqcc */ - -#ifdef USE_JPWL - if (j2k->cp->correct) { - - static int backup_compno = 0; - - /* compno is negative or larger than the number of components!!! */ - if ((compno < 0) || (compno >= numcomp)) { - opj_event_msg(j2k->cinfo, EVT_ERROR, - "JPWL: bad component number in QCC (%d out of a maximum of %d)\n", - compno, numcomp); - if (!JPWL_ASSUME) { - opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n"); - return; - } - /* we try to correct */ - compno = backup_compno % numcomp; - opj_event_msg(j2k->cinfo, EVT_WARNING, "- trying to adjust this\n" - "- setting component number to %d\n", - compno); - } - - /* keep your private count of tiles */ - backup_compno++; - }; -#endif /* USE_JPWL */ - - j2k_read_qcx(j2k, compno, len - 2 - (numcomp <= 256 ? 1 : 2)); -} - -static void j2k_write_poc(opj_j2k_t *j2k) { - int len, numpchgs, i; - - int numcomps = j2k->image->numcomps; - - opj_cp_t *cp = j2k->cp; - opj_tcp_t *tcp = &cp->tcps[j2k->curtileno]; - opj_tccp_t *tccp = &tcp->tccps[0]; - opj_cio_t *cio = j2k->cio; - - numpchgs = 1 + tcp->numpocs; - cio_write(cio, J2K_MS_POC, 2); /* POC */ - len = 2 + (5 + 2 * (numcomps <= 256 ? 1 : 2)) * numpchgs; - cio_write(cio, len, 2); /* Lpoc */ - for (i = 0; i < numpchgs; i++) { - opj_poc_t *poc = &tcp->pocs[i]; - cio_write(cio, poc->resno0, 1); /* RSpoc_i */ - cio_write(cio, poc->compno0, (numcomps <= 256 ? 1 : 2)); /* CSpoc_i */ - cio_write(cio, poc->layno1, 2); /* LYEpoc_i */ - poc->layno1 = int_min(poc->layno1, tcp->numlayers); - cio_write(cio, poc->resno1, 1); /* REpoc_i */ - poc->resno1 = int_min(poc->resno1, tccp->numresolutions); - cio_write(cio, poc->compno1, (numcomps <= 256 ? 1 : 2)); /* CEpoc_i */ - poc->compno1 = int_min(poc->compno1, numcomps); - cio_write(cio, poc->prg, 1); /* Ppoc_i */ - } -} - -static void j2k_read_poc(opj_j2k_t *j2k) { - int len, numpchgs, i, old_poc; - - int numcomps = j2k->image->numcomps; - - opj_cp_t *cp = j2k->cp; - opj_tcp_t *tcp = j2k->state == J2K_STATE_TPH ? &cp->tcps[j2k->curtileno] : j2k->default_tcp; - opj_cio_t *cio = j2k->cio; - - old_poc = tcp->POC ? tcp->numpocs + 1 : 0; - tcp->POC = 1; - len = cio_read(cio, 2); /* Lpoc */ - numpchgs = (len - 2) / (5 + 2 * (numcomps <= 256 ? 1 : 2)); - - for (i = old_poc; i < numpchgs + old_poc; i++) { - opj_poc_t *poc; - poc = &tcp->pocs[i]; - poc->resno0 = cio_read(cio, 1); /* RSpoc_i */ - poc->compno0 = cio_read(cio, numcomps <= 256 ? 1 : 2); /* CSpoc_i */ - poc->layno1 = cio_read(cio, 2); /* LYEpoc_i */ - poc->resno1 = cio_read(cio, 1); /* REpoc_i */ - poc->compno1 = int_min( - cio_read(cio, numcomps <= 256 ? 1 : 2), (unsigned int) numcomps); /* CEpoc_i */ - poc->prg = (OPJ_PROG_ORDER)cio_read(cio, 1); /* Ppoc_i */ - } - - tcp->numpocs = numpchgs + old_poc - 1; -} - -static void j2k_read_crg(opj_j2k_t *j2k) { - int len, i, Xcrg_i, Ycrg_i; - - opj_cio_t *cio = j2k->cio; - int numcomps = j2k->image->numcomps; - - len = cio_read(cio, 2); /* Lcrg */ - for (i = 0; i < numcomps; i++) { - Xcrg_i = cio_read(cio, 2); /* Xcrg_i */ - Ycrg_i = cio_read(cio, 2); /* Ycrg_i */ - } -} - -static void j2k_read_tlm(opj_j2k_t *j2k) { - int len, Ztlm, Stlm, ST, SP, tile_tlm, i; - long int Ttlm_i, Ptlm_i; - - opj_cio_t *cio = j2k->cio; - - len = cio_read(cio, 2); /* Ltlm */ - Ztlm = cio_read(cio, 1); /* Ztlm */ - Stlm = cio_read(cio, 1); /* Stlm */ - ST = ((Stlm >> 4) & 0x01) + ((Stlm >> 4) & 0x02); - SP = (Stlm >> 6) & 0x01; - tile_tlm = (len - 4) / ((SP + 1) * 2 + ST); - for (i = 0; i < tile_tlm; i++) { - Ttlm_i = cio_read(cio, ST); /* Ttlm_i */ - Ptlm_i = cio_read(cio, SP ? 4 : 2); /* Ptlm_i */ - } -} - -static void j2k_read_plm(opj_j2k_t *j2k) { - int len, i, Zplm, Nplm, add, packet_len = 0; - - opj_cio_t *cio = j2k->cio; - - len = cio_read(cio, 2); /* Lplm */ - Zplm = cio_read(cio, 1); /* Zplm */ - len -= 3; - while (len > 0) { - Nplm = cio_read(cio, 4); /* Nplm */ - len -= 4; - for (i = Nplm; i > 0; i--) { - add = cio_read(cio, 1); - len--; - packet_len = (packet_len << 7) + add; /* Iplm_ij */ - if ((add & 0x80) == 0) { - /* New packet */ - packet_len = 0; - } - if (len <= 0) - break; - } - } -} - -static void j2k_read_plt(opj_j2k_t *j2k) { - int len, i, Zplt, packet_len = 0, add; - - opj_cio_t *cio = j2k->cio; - - len = cio_read(cio, 2); /* Lplt */ - Zplt = cio_read(cio, 1); /* Zplt */ - for (i = len - 3; i > 0; i--) { - add = cio_read(cio, 1); - packet_len = (packet_len << 7) + add; /* Iplt_i */ - if ((add & 0x80) == 0) { - /* New packet */ - packet_len = 0; - } - } -} - -static void j2k_read_ppm(opj_j2k_t *j2k) { - int len, Z_ppm, i, j; - int N_ppm; - - opj_cp_t *cp = j2k->cp; - opj_cio_t *cio = j2k->cio; - - len = cio_read(cio, 2); - cp->ppm = 1; - - Z_ppm = cio_read(cio, 1); /* Z_ppm */ - len -= 3; - while (len > 0) { - if (cp->ppm_previous == 0) { - N_ppm = cio_read(cio, 4); /* N_ppm */ - len -= 4; - } else { - N_ppm = cp->ppm_previous; - } - j = cp->ppm_store; - if (Z_ppm == 0) { /* First PPM marker */ - cp->ppm_data = (unsigned char *) opj_malloc(N_ppm * sizeof(unsigned char)); - cp->ppm_data_first = cp->ppm_data; - cp->ppm_len = N_ppm; - } else { /* NON-first PPM marker */ - cp->ppm_data = (unsigned char *) opj_realloc(cp->ppm_data, (N_ppm + cp->ppm_store) * sizeof(unsigned char)); - -#ifdef USE_JPWL - /* this memory allocation check could be done even in non-JPWL cases */ - if (cp->correct) { - if (!cp->ppm_data) { - opj_event_msg(j2k->cinfo, EVT_ERROR, - "JPWL: failed memory allocation during PPM marker parsing (pos. %x)\n", - cio_tell(cio)); - if (!JPWL_ASSUME || JPWL_ASSUME) { - opj_free(cp->ppm_data); - opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n"); - return; - } - } - } -#endif - - cp->ppm_data_first = cp->ppm_data; - cp->ppm_len = N_ppm + cp->ppm_store; - } - for (i = N_ppm; i > 0; i--) { /* Read packet header */ - cp->ppm_data[j] = cio_read(cio, 1); - j++; - len--; - if (len == 0) - break; /* Case of non-finished packet header in present marker but finished in next one */ - } - cp->ppm_previous = i - 1; - cp->ppm_store = j; - } -} - -static void j2k_read_ppt(opj_j2k_t *j2k) { - int len, Z_ppt, i, j = 0; - - opj_cp_t *cp = j2k->cp; - opj_tcp_t *tcp = cp->tcps + j2k->curtileno; - opj_cio_t *cio = j2k->cio; - - len = cio_read(cio, 2); - Z_ppt = cio_read(cio, 1); - tcp->ppt = 1; - if (Z_ppt == 0) { /* First PPT marker */ - tcp->ppt_data = (unsigned char *) opj_malloc((len - 3) * sizeof(unsigned char)); - tcp->ppt_data_first = tcp->ppt_data; - tcp->ppt_store = 0; - tcp->ppt_len = len - 3; - } else { /* NON-first PPT marker */ - tcp->ppt_data = (unsigned char *) opj_realloc(tcp->ppt_data, (len - 3 + tcp->ppt_store) * sizeof(unsigned char)); - tcp->ppt_data_first = tcp->ppt_data; - tcp->ppt_len = len - 3 + tcp->ppt_store; - } - j = tcp->ppt_store; - for (i = len - 3; i > 0; i--) { - tcp->ppt_data[j] = cio_read(cio, 1); - j++; - } - tcp->ppt_store = j; -} - -static void j2k_write_tlm(opj_j2k_t *j2k){ - int lenp; - opj_cio_t *cio = j2k->cio; - j2k->tlm_start = cio_tell(cio); - cio_write(cio, J2K_MS_TLM, 2);/* TLM */ - lenp = 4 + (5*j2k->totnum_tp); - cio_write(cio,lenp,2); /* Ltlm */ - cio_write(cio, 0,1); /* Ztlm=0*/ - cio_write(cio,80,1); /* Stlm ST=1(8bits-255 tiles max),SP=1(Ptlm=32bits) */ - cio_skip(cio,5*j2k->totnum_tp); -} - -static void j2k_write_sot(opj_j2k_t *j2k) { - int lenp, len; - - opj_cio_t *cio = j2k->cio; - - j2k->sot_start = cio_tell(cio); - cio_write(cio, J2K_MS_SOT, 2); /* SOT */ - lenp = cio_tell(cio); - cio_skip(cio, 2); /* Lsot (further) */ - cio_write(cio, j2k->curtileno, 2); /* Isot */ - cio_skip(cio, 4); /* Psot (further in j2k_write_sod) */ - cio_write(cio, j2k->cur_tp_num , 1); /* TPsot */ - cio_write(cio, j2k->cur_totnum_tp[j2k->curtileno], 1); /* TNsot */ - len = cio_tell(cio) - lenp; - cio_seek(cio, lenp); - cio_write(cio, len, 2); /* Lsot */ - cio_seek(cio, lenp + len); - - /* UniPG>> */ -#ifdef USE_JPWL - /* update markers struct */ - j2k_add_marker(j2k->cstr_info, J2K_MS_SOT, j2k->sot_start, len + 2); -#endif /* USE_JPWL */ - /* <cstr_info && j2k->cur_tp_num==0){ - j2k_add_tlmarker( j2k->curtileno, j2k->cstr_info, J2K_MS_SOT, lenp, len); - } -} - -static void j2k_read_sot(opj_j2k_t *j2k) { - int len, tileno, totlen, partno, numparts, i; - opj_tcp_t *tcp = NULL; - char status = 0; - - opj_cp_t *cp = j2k->cp; - opj_cio_t *cio = j2k->cio; - - len = cio_read(cio, 2); - tileno = cio_read(cio, 2); - -#ifdef USE_JPWL - if (j2k->cp->correct) { - - static int backup_tileno = 0; - - /* tileno is negative or larger than the number of tiles!!! */ - if ((tileno < 0) || (tileno > (cp->tw * cp->th))) { - opj_event_msg(j2k->cinfo, EVT_ERROR, - "JPWL: bad tile number (%d out of a maximum of %d)\n", - tileno, (cp->tw * cp->th)); - if (!JPWL_ASSUME) { - opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n"); - return; - } - /* we try to correct */ - tileno = backup_tileno; - opj_event_msg(j2k->cinfo, EVT_WARNING, "- trying to adjust this\n" - "- setting tile number to %d\n", - tileno); - } - - /* keep your private count of tiles */ - backup_tileno++; - }; -#endif /* USE_JPWL */ - - if (cp->tileno_size == 0) { - cp->tileno[cp->tileno_size] = tileno; - cp->tileno_size++; - } else { - i = 0; - while (i < cp->tileno_size && status == 0) { - status = cp->tileno[i] == tileno ? 1 : 0; - i++; - } - if (status == 0) { - cp->tileno[cp->tileno_size] = tileno; - cp->tileno_size++; - } - } - - totlen = cio_read(cio, 4); - -#ifdef USE_JPWL - if (j2k->cp->correct) { - - /* totlen is negative or larger than the bytes left!!! */ - if ((totlen < 0) || (totlen > (cio_numbytesleft(cio) + 8))) { - opj_event_msg(j2k->cinfo, EVT_ERROR, - "JPWL: bad tile byte size (%d bytes against %d bytes left)\n", - totlen, cio_numbytesleft(cio) + 8); - if (!JPWL_ASSUME) { - opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n"); - return; - } - /* we try to correct */ - totlen = 0; - opj_event_msg(j2k->cinfo, EVT_WARNING, "- trying to adjust this\n" - "- setting Psot to %d => assuming it is the last tile\n", - totlen); - } - - }; -#endif /* USE_JPWL */ - - if (!totlen) - totlen = cio_numbytesleft(cio) + 8; - - partno = cio_read(cio, 1); - numparts = cio_read(cio, 1); - - if (partno >= numparts) { - opj_event_msg(j2k->cinfo, EVT_WARNING, "SOT marker inconsistency in tile %d: tile-part index greater (%d) than number of tile-parts (%d)\n", tileno, partno, numparts); - numparts = partno+1; - } - - j2k->curtileno = tileno; - j2k->cur_tp_num = partno; - j2k->eot = cio_getbp(cio) - 12 + totlen; - j2k->state = J2K_STATE_TPH; - tcp = &cp->tcps[j2k->curtileno]; - - /* Index */ - if (j2k->cstr_info) { - if (tcp->first) { - if (tileno == 0) - j2k->cstr_info->main_head_end = cio_tell(cio) - 13; - j2k->cstr_info->tile[tileno].tileno = tileno; - j2k->cstr_info->tile[tileno].start_pos = cio_tell(cio) - 12; - j2k->cstr_info->tile[tileno].end_pos = j2k->cstr_info->tile[tileno].start_pos + totlen - 1; - } else { - j2k->cstr_info->tile[tileno].end_pos += totlen; - } - j2k->cstr_info->tile[tileno].num_tps = numparts; - if (numparts) - j2k->cstr_info->tile[tileno].tp = (opj_tp_info_t *) opj_realloc(j2k->cstr_info->tile[tileno].tp, numparts * sizeof(opj_tp_info_t)); - else - j2k->cstr_info->tile[tileno].tp = (opj_tp_info_t *) opj_realloc(j2k->cstr_info->tile[tileno].tp, 10 * sizeof(opj_tp_info_t)); /* Fixme (10)*/ - j2k->cstr_info->tile[tileno].tp[partno].tp_start_pos = cio_tell(cio) - 12; - j2k->cstr_info->tile[tileno].tp[partno].tp_end_pos = - j2k->cstr_info->tile[tileno].tp[partno].tp_start_pos + totlen - 1; - } - - if (tcp->first == 1) { - /* Initialization PPT */ - opj_tccp_t *tmp = tcp->tccps; - memcpy(tcp, j2k->default_tcp, sizeof(opj_tcp_t)); - tcp->ppt = 0; - tcp->ppt_data = NULL; - tcp->ppt_data_first = NULL; - tcp->tccps = tmp; - - for (i = 0; i < j2k->image->numcomps; i++) { - tcp->tccps[i] = j2k->default_tcp->tccps[i]; - } - cp->tcps[j2k->curtileno].first = 0; - } -} - -static void j2k_write_sod(opj_j2k_t *j2k, void *tile_coder) { - int l, layno; - int totlen; - opj_tcp_t *tcp = NULL; - opj_codestream_info_t *cstr_info = NULL; - - opj_tcd_t *tcd = (opj_tcd_t*)tile_coder; /* cast is needed because of conflicts in header inclusions */ - opj_cp_t *cp = j2k->cp; - opj_cio_t *cio = j2k->cio; - - tcd->tp_num = j2k->tp_num ; - tcd->cur_tp_num = j2k->cur_tp_num; - - cio_write(cio, J2K_MS_SOD, 2); - - if( j2k->cstr_info && j2k->cur_tp_num==0){ - j2k_add_tlmarker( j2k->curtileno, j2k->cstr_info, J2K_MS_SOD, cio_tell(cio), 0); - } - - if (j2k->curtileno == 0) { - j2k->sod_start = cio_tell(cio) + j2k->pos_correction; - } - - /* INDEX >> */ - cstr_info = j2k->cstr_info; - if (cstr_info) { - if (!j2k->cur_tp_num ) { - cstr_info->tile[j2k->curtileno].end_header = cio_tell(cio) + j2k->pos_correction - 1; - j2k->cstr_info->tile[j2k->curtileno].tileno = j2k->curtileno; - } - else{ - if(cstr_info->tile[j2k->curtileno].packet[cstr_info->packno - 1].end_pos < cio_tell(cio)) - cstr_info->tile[j2k->curtileno].packet[cstr_info->packno].start_pos = cio_tell(cio); - } - /* UniPG>> */ -#ifdef USE_JPWL - /* update markers struct */ - j2k_add_marker(j2k->cstr_info, J2K_MS_SOD, j2k->sod_start, 2); -#endif /* USE_JPWL */ - /* <tcps[j2k->curtileno]; - for (layno = 0; layno < tcp->numlayers; layno++) { - if (tcp->rates[layno]>(j2k->sod_start / (cp->th * cp->tw))) { - tcp->rates[layno]-=(j2k->sod_start / (cp->th * cp->tw)); - } else if (tcp->rates[layno]) { - tcp->rates[layno]=1; - } - } - if(j2k->cur_tp_num == 0){ - tcd->tcd_image->tiles->packno = 0; - if(cstr_info) - cstr_info->packno = 0; - } - - l = tcd_encode_tile(tcd, j2k->curtileno, cio_getbp(cio), cio_numbytesleft(cio) - 2, cstr_info); - - /* Writing Psot in SOT marker */ - totlen = cio_tell(cio) + l - j2k->sot_start; - cio_seek(cio, j2k->sot_start + 6); - cio_write(cio, totlen, 4); - cio_seek(cio, j2k->sot_start + totlen); - /* Writing Ttlm and Ptlm in TLM marker */ - if(cp->cinema){ - cio_seek(cio, j2k->tlm_start + 6 + (5*j2k->cur_tp_num)); - cio_write(cio, j2k->curtileno, 1); - cio_write(cio, totlen, 4); - } - cio_seek(cio, j2k->sot_start + totlen); -} - -static void j2k_read_sod(opj_j2k_t *j2k) { - int len, truncate = 0, i; - unsigned char *data = NULL, *data_ptr = NULL; - - opj_cio_t *cio = j2k->cio; - int curtileno = j2k->curtileno; - - /* Index */ - if (j2k->cstr_info) { - j2k->cstr_info->tile[j2k->curtileno].tp[j2k->cur_tp_num].tp_end_header = - cio_tell(cio) + j2k->pos_correction - 1; - if (j2k->cur_tp_num == 0) - j2k->cstr_info->tile[j2k->curtileno].end_header = cio_tell(cio) + j2k->pos_correction - 1; - j2k->cstr_info->packno = 0; - } - - len = int_min(j2k->eot - cio_getbp(cio), cio_numbytesleft(cio) + 1); - - if (len == cio_numbytesleft(cio) + 1) { - truncate = 1; /* Case of a truncate codestream */ - } - - data = j2k->tile_data[curtileno]; - data = (unsigned char*) opj_realloc(data, (j2k->tile_len[curtileno] + len) * sizeof(unsigned char)); - - data_ptr = data + j2k->tile_len[curtileno]; - for (i = 0; i < len; i++) { - data_ptr[i] = cio_read(cio, 1); - } - - j2k->tile_len[curtileno] += len; - j2k->tile_data[curtileno] = data; - - if (!truncate) { - j2k->state = J2K_STATE_TPHSOT; - } else { - j2k->state = J2K_STATE_NEOC; /* RAJOUTE !! */ - } - j2k->cur_tp_num++; -} - -static void j2k_write_rgn(opj_j2k_t *j2k, int compno, int tileno) { - opj_cp_t *cp = j2k->cp; - opj_tcp_t *tcp = &cp->tcps[tileno]; - opj_cio_t *cio = j2k->cio; - int numcomps = j2k->image->numcomps; - - cio_write(cio, J2K_MS_RGN, 2); /* RGN */ - cio_write(cio, numcomps <= 256 ? 5 : 6, 2); /* Lrgn */ - cio_write(cio, compno, numcomps <= 256 ? 1 : 2); /* Crgn */ - cio_write(cio, 0, 1); /* Srgn */ - cio_write(cio, tcp->tccps[compno].roishift, 1); /* SPrgn */ -} - -static void j2k_read_rgn(opj_j2k_t *j2k) { - int len, compno, roisty; - - opj_cp_t *cp = j2k->cp; - opj_tcp_t *tcp = j2k->state == J2K_STATE_TPH ? &cp->tcps[j2k->curtileno] : j2k->default_tcp; - opj_cio_t *cio = j2k->cio; - int numcomps = j2k->image->numcomps; - - len = cio_read(cio, 2); /* Lrgn */ - compno = cio_read(cio, numcomps <= 256 ? 1 : 2); /* Crgn */ - roisty = cio_read(cio, 1); /* Srgn */ - -#ifdef USE_JPWL - if (j2k->cp->correct) { - /* totlen is negative or larger than the bytes left!!! */ - if (compno >= numcomps) { - opj_event_msg(j2k->cinfo, EVT_ERROR, - "JPWL: bad component number in RGN (%d when there are only %d)\n", - compno, numcomps); - if (!JPWL_ASSUME || JPWL_ASSUME) { - opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n"); - return; - } - } - }; -#endif /* USE_JPWL */ - - tcp->tccps[compno].roishift = cio_read(cio, 1); /* SPrgn */ -} - -static void j2k_write_eoc(opj_j2k_t *j2k) { - opj_cio_t *cio = j2k->cio; - /* opj_event_msg(j2k->cinfo, "%.8x: EOC\n", cio_tell(cio) + j2k->pos_correction); */ - cio_write(cio, J2K_MS_EOC, 2); - -/* UniPG>> */ -#ifdef USE_JPWL - /* update markers struct */ - j2k_add_marker(j2k->cstr_info, J2K_MS_EOC, cio_tell(cio) - 2, 2); -#endif /* USE_JPWL */ -/* <cp->limit_decoding != DECODE_ALL_BUT_PACKETS) { - opj_tcd_t *tcd = tcd_create(j2k->cinfo); - tcd_malloc_decode(tcd, j2k->image, j2k->cp); - for (i = 0; i < j2k->cp->tileno_size; i++) { - tcd_malloc_decode_tile(tcd, j2k->image, j2k->cp, i, j2k->cstr_info); - tileno = j2k->cp->tileno[i]; - success = tcd_decode_tile(tcd, j2k->tile_data[tileno], j2k->tile_len[tileno], tileno, j2k->cstr_info); - opj_free(j2k->tile_data[tileno]); - j2k->tile_data[tileno] = NULL; - tcd_free_decode_tile(tcd, i); - if (success == OPJ_FALSE) { - j2k->state |= J2K_STATE_ERR; - break; - } - } - tcd_free_decode(tcd); - tcd_destroy(tcd); - } - /* if packets should not be decoded */ - else { - for (i = 0; i < j2k->cp->tileno_size; i++) { - tileno = j2k->cp->tileno[i]; - opj_free(j2k->tile_data[tileno]); - j2k->tile_data[tileno] = NULL; - } - } - if (j2k->state & J2K_STATE_ERR) - j2k->state = J2K_STATE_MT + J2K_STATE_ERR; - else - j2k->state = J2K_STATE_MT; -} - -typedef struct opj_dec_mstabent { - /** marker value */ - int id; - /** value of the state when the marker can appear */ - int states; - /** action linked to the marker */ - void (*handler) (opj_j2k_t *j2k); -} opj_dec_mstabent_t; - -opj_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}, - -#ifdef USE_JPWL - {J2K_MS_EPC, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_epc}, - {J2K_MS_EPB, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_epb}, - {J2K_MS_ESD, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_esd}, - {J2K_MS_RED, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_red}, -#endif /* USE_JPWL */ -#ifdef USE_JPSEC - {J2K_MS_SEC, J2K_STATE_MH, j2k_read_sec}, - {J2K_MS_INSEC, 0, j2k_read_insec}, -#endif /* USE_JPSEC */ - - {0, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_unk} -}; - -static void j2k_read_unk(opj_j2k_t *j2k) { - opj_event_msg(j2k->cinfo, EVT_WARNING, "Unknown marker\n"); - -#ifdef USE_JPWL - if (j2k->cp->correct) { - int m = 0, id, i; - int min_id = 0, min_dist = 17, cur_dist = 0, tmp_id; - cio_seek(j2k->cio, cio_tell(j2k->cio) - 2); - id = cio_read(j2k->cio, 2); - opj_event_msg(j2k->cinfo, EVT_ERROR, - "JPWL: really don't know this marker %x\n", - id); - if (!JPWL_ASSUME) { - opj_event_msg(j2k->cinfo, EVT_ERROR, - "- possible synch loss due to uncorrectable codestream errors => giving up\n"); - return; - } - /* OK, activate this at your own risk!!! */ - /* we look for the marker at the minimum hamming distance from this */ - while (j2k_dec_mstab[m].id) { - - /* 1's where they differ */ - tmp_id = j2k_dec_mstab[m].id ^ id; - - /* compute the hamming distance between our id and the current */ - cur_dist = 0; - for (i = 0; i < 16; i++) { - if ((tmp_id >> i) & 0x0001) { - cur_dist++; - } - } - - /* if current distance is smaller, set the minimum */ - if (cur_dist < min_dist) { - min_dist = cur_dist; - min_id = j2k_dec_mstab[m].id; - } - - /* jump to the next marker */ - m++; - } - - /* do we substitute the marker? */ - if (min_dist < JPWL_MAXIMUM_HAMMING) { - opj_event_msg(j2k->cinfo, EVT_ERROR, - "- marker %x is at distance %d from the read %x\n", - min_id, min_dist, id); - opj_event_msg(j2k->cinfo, EVT_ERROR, - "- trying to substitute in place and crossing fingers!\n"); - cio_seek(j2k->cio, cio_tell(j2k->cio) - 2); - cio_write(j2k->cio, min_id, 2); - - /* rewind */ - cio_seek(j2k->cio, cio_tell(j2k->cio) - 2); - - } - - }; -#endif /* USE_JPWL */ - -} - -/** -Read the lookup table containing all the marker, status and action -@param id Marker value -*/ -static opj_dec_mstabent_t *j2k_dec_mstab_lookup(int id) { - opj_dec_mstabent_t *e; - for (e = j2k_dec_mstab; e->id != 0; e++) { - if (e->id == id) { - break; - } - } - return e; -} - -/* ----------------------------------------------------------------------- */ -/* J2K / JPT decoder interface */ -/* ----------------------------------------------------------------------- */ - -opj_j2k_t* j2k_create_decompress(opj_common_ptr cinfo) { - opj_j2k_t *j2k = (opj_j2k_t*) opj_calloc(1, sizeof(opj_j2k_t)); - if(!j2k) - return NULL; - - j2k->default_tcp = (opj_tcp_t*) opj_calloc(1, sizeof(opj_tcp_t)); - if(!j2k->default_tcp) { - opj_free(j2k); - return NULL; - } - - j2k->cinfo = cinfo; - j2k->tile_data = NULL; - - return j2k; -} - -void j2k_destroy_decompress(opj_j2k_t *j2k) { - int i = 0; - - if(j2k->tile_len != NULL) { - opj_free(j2k->tile_len); - } - if(j2k->tile_data != NULL) { - opj_free(j2k->tile_data); - } - if(j2k->default_tcp != NULL) { - opj_tcp_t *default_tcp = j2k->default_tcp; - if(default_tcp->ppt_data_first != NULL) { - opj_free(default_tcp->ppt_data_first); - } - if(j2k->default_tcp->tccps != NULL) { - opj_free(j2k->default_tcp->tccps); - } - opj_free(j2k->default_tcp); - } - if(j2k->cp != NULL) { - opj_cp_t *cp = j2k->cp; - if(cp->tcps != NULL) { - for(i = 0; i < cp->tw * cp->th; i++) { - if(cp->tcps[i].ppt_data_first != NULL) { - opj_free(cp->tcps[i].ppt_data_first); - } - if(cp->tcps[i].tccps != NULL) { - opj_free(cp->tcps[i].tccps); - } - } - opj_free(cp->tcps); - } - if(cp->ppm_data_first != NULL) { - opj_free(cp->ppm_data_first); - } - if(cp->tileno != NULL) { - opj_free(cp->tileno); - } - if(cp->comment != NULL) { - opj_free(cp->comment); - } - - opj_free(cp); - } - opj_free(j2k); -} - -void j2k_setup_decoder(opj_j2k_t *j2k, opj_dparameters_t *parameters) { - if(j2k && parameters) { - /* create and initialize the coding parameters structure */ - opj_cp_t *cp = (opj_cp_t*) opj_calloc(1, sizeof(opj_cp_t)); - cp->reduce = parameters->cp_reduce; - cp->layer = parameters->cp_layer; - cp->limit_decoding = parameters->cp_limit_decoding; - -#ifdef USE_JPWL - cp->correct = parameters->jpwl_correct; - cp->exp_comps = parameters->jpwl_exp_comps; - cp->max_tiles = parameters->jpwl_max_tiles; -#endif /* USE_JPWL */ - - - /* keep a link to cp so that we can destroy it later in j2k_destroy_decompress */ - j2k->cp = cp; - } -} - -opj_image_t* j2k_decode(opj_j2k_t *j2k, opj_cio_t *cio, opj_codestream_info_t *cstr_info) { - opj_image_t *image = NULL; - - opj_common_ptr cinfo = j2k->cinfo; - - j2k->cio = cio; - j2k->cstr_info = cstr_info; - if (cstr_info) - memset(cstr_info, 0, sizeof(opj_codestream_info_t)); - - /* create an empty image */ - image = opj_image_create0(); - j2k->image = image; - - j2k->state = J2K_STATE_MHSOC; - - for (;;) { - opj_dec_mstabent_t *e; - int id = cio_read(cio, 2); - -#ifdef USE_JPWL - /* we try to honor JPWL correction power */ - if (j2k->cp->correct) { - - int orig_pos = cio_tell(cio); - opj_bool status; - - /* call the corrector */ - status = jpwl_correct(j2k); - - /* go back to where you were */ - cio_seek(cio, orig_pos - 2); - - /* re-read the marker */ - id = cio_read(cio, 2); - - /* check whether it begins with ff */ - if (id >> 8 != 0xff) { - opj_event_msg(cinfo, EVT_ERROR, - "JPWL: possible bad marker %x at %d\n", - id, cio_tell(cio) - 2); - if (!JPWL_ASSUME) { - opj_image_destroy(image); - opj_event_msg(cinfo, EVT_ERROR, "JPWL: giving up\n"); - return 0; - } - /* we try to correct */ - id = id | 0xff00; - cio_seek(cio, cio_tell(cio) - 2); - cio_write(cio, id, 2); - opj_event_msg(cinfo, EVT_WARNING, "- trying to adjust this\n" - "- setting marker to %x\n", - id); - } - - } -#endif /* USE_JPWL */ - - if (id >> 8 != 0xff) { - opj_image_destroy(image); - opj_event_msg(cinfo, EVT_ERROR, "%.8x: expected a marker instead of %x\n", cio_tell(cio) - 2, id); - return 0; - } - e = j2k_dec_mstab_lookup(id); - /* Check if the marker is known*/ - if (!(j2k->state & e->states)) { - opj_image_destroy(image); - opj_event_msg(cinfo, EVT_ERROR, "%.8x: unexpected marker %x\n", cio_tell(cio) - 2, id); - return 0; - } - /* Check if the decoding is limited to the main header*/ - if (e->id == J2K_MS_SOT && j2k->cp->limit_decoding == LIMIT_TO_MAIN_HEADER) { - opj_event_msg(cinfo, EVT_INFO, "Main Header decoded.\n"); - return image; - } - - if (e->handler) { - (*e->handler)(j2k); - } - if (j2k->state & J2K_STATE_ERR) - return NULL; - - if (j2k->state == J2K_STATE_MT) { - break; - } - if (j2k->state == J2K_STATE_NEOC) { - break; - } - } - if (j2k->state == J2K_STATE_NEOC) { - j2k_read_eoc(j2k); - } - - if (j2k->state != J2K_STATE_MT) { - opj_event_msg(cinfo, EVT_WARNING, "Incomplete bitstream\n"); - } - return image; -} - -/* -* Read a JPT-stream and decode file -* -*/ -opj_image_t* j2k_decode_jpt_stream(opj_j2k_t *j2k, opj_cio_t *cio, opj_codestream_info_t *cstr_info) { - opj_image_t *image = NULL; - opj_jpt_msg_header_t header; - int position; - opj_common_ptr cinfo = j2k->cinfo; - - OPJ_ARG_NOT_USED(cstr_info); - - j2k->cio = cio; - - /* create an empty image */ - image = opj_image_create0(); - j2k->image = image; - - j2k->state = J2K_STATE_MHSOC; - - /* Initialize the header */ - jpt_init_msg_header(&header); - /* Read the first header of the message */ - jpt_read_msg_header(cinfo, cio, &header); - - position = cio_tell(cio); - if (header.Class_Id != 6) { /* 6 : Main header data-bin message */ - opj_image_destroy(image); - opj_event_msg(cinfo, EVT_ERROR, "[JPT-stream] : Expecting Main header first [class_Id %d] !\n", header.Class_Id); - return 0; - } - - for (;;) { - opj_dec_mstabent_t *e = NULL; - int id; - - if (!cio_numbytesleft(cio)) { - j2k_read_eoc(j2k); - return image; - } - /* data-bin read -> need to read a new header */ - if ((unsigned int) (cio_tell(cio) - position) == header.Msg_length) { - jpt_read_msg_header(cinfo, cio, &header); - position = cio_tell(cio); - if (header.Class_Id != 4) { /* 4 : Tile data-bin message */ - opj_image_destroy(image); - opj_event_msg(cinfo, EVT_ERROR, "[JPT-stream] : Expecting Tile info !\n"); - return 0; - } - } - - id = cio_read(cio, 2); - if (id >> 8 != 0xff) { - opj_image_destroy(image); - opj_event_msg(cinfo, EVT_ERROR, "%.8x: expected a marker instead of %x\n", cio_tell(cio) - 2, id); - return 0; - } - e = j2k_dec_mstab_lookup(id); - if (!(j2k->state & e->states)) { - opj_image_destroy(image); - opj_event_msg(cinfo, EVT_ERROR, "%.8x: unexpected marker %x\n", cio_tell(cio) - 2, id); - return 0; - } - if (e->handler) { - (*e->handler)(j2k); - } - if (j2k->state == J2K_STATE_MT) { - break; - } - if (j2k->state == J2K_STATE_NEOC) { - break; - } - } - if (j2k->state == J2K_STATE_NEOC) { - j2k_read_eoc(j2k); - } - - if (j2k->state != J2K_STATE_MT) { - opj_event_msg(cinfo, EVT_WARNING, "Incomplete bitstream\n"); - } - - return image; -} - -/* ----------------------------------------------------------------------- */ -/* J2K encoder interface */ -/* ----------------------------------------------------------------------- */ - -opj_j2k_t* j2k_create_compress(opj_common_ptr cinfo) { - opj_j2k_t *j2k = (opj_j2k_t*) opj_calloc(1, sizeof(opj_j2k_t)); - if(j2k) { - j2k->cinfo = cinfo; - } - return j2k; -} - -void j2k_destroy_compress(opj_j2k_t *j2k) { - int tileno; - - if(!j2k) return; - if(j2k->cp != NULL) { - opj_cp_t *cp = j2k->cp; - - if(cp->comment) { - opj_free(cp->comment); - } - if(cp->matrice) { - opj_free(cp->matrice); - } - for (tileno = 0; tileno < cp->tw * cp->th; tileno++) { - opj_free(cp->tcps[tileno].tccps); - } - opj_free(cp->tcps); - opj_free(cp); - } - - opj_free(j2k); -} - -void j2k_setup_encoder(opj_j2k_t *j2k, opj_cparameters_t *parameters, opj_image_t *image) { - int i, j, tileno, numpocs_tile; - opj_cp_t *cp = NULL; - - if(!j2k || !parameters || ! image) { - return; - } - - /* create and initialize the coding parameters structure */ - cp = (opj_cp_t*) opj_calloc(1, sizeof(opj_cp_t)); - - /* keep a link to cp so that we can destroy it later in j2k_destroy_compress */ - j2k->cp = cp; - - /* set default values for cp */ - cp->tw = 1; - cp->th = 1; - - /* - copy user encoding parameters - */ - cp->cinema = parameters->cp_cinema; - cp->max_comp_size = parameters->max_comp_size; - cp->rsiz = parameters->cp_rsiz; - cp->disto_alloc = parameters->cp_disto_alloc; - cp->fixed_alloc = parameters->cp_fixed_alloc; - cp->fixed_quality = parameters->cp_fixed_quality; - - /* mod fixed_quality */ - if(parameters->cp_matrice) { - size_t array_size = parameters->tcp_numlayers * parameters->numresolution * 3 * sizeof(int); - cp->matrice = (int *) opj_malloc(array_size); - memcpy(cp->matrice, parameters->cp_matrice, array_size); - } - - /* tiles */ - cp->tdx = parameters->cp_tdx; - cp->tdy = parameters->cp_tdy; - - /* tile offset */ - cp->tx0 = parameters->cp_tx0; - cp->ty0 = parameters->cp_ty0; - - /* comment string */ - if(parameters->cp_comment) { - cp->comment = (char*)opj_malloc(strlen(parameters->cp_comment) + 1); - if(cp->comment) { - strcpy(cp->comment, parameters->cp_comment); - } - } - - /* - calculate other encoding parameters - */ - - if (parameters->tile_size_on) { - cp->tw = int_ceildiv(image->x1 - cp->tx0, cp->tdx); - cp->th = int_ceildiv(image->y1 - cp->ty0, cp->tdy); - } else { - cp->tdx = image->x1 - cp->tx0; - cp->tdy = image->y1 - cp->ty0; - } - - if(parameters->tp_on){ - cp->tp_flag = parameters->tp_flag; - cp->tp_on = 1; - } - - cp->img_size = 0; - for(i=0;inumcomps ;i++){ - cp->img_size += (image->comps[i].w *image->comps[i].h * image->comps[i].prec); - } - - -#ifdef USE_JPWL - /* - calculate JPWL encoding parameters - */ - - if (parameters->jpwl_epc_on) { - int i; - - /* set JPWL on */ - cp->epc_on = OPJ_TRUE; - cp->info_on = OPJ_FALSE; /* no informative technique */ - - /* set EPB on */ - if ((parameters->jpwl_hprot_MH > 0) || (parameters->jpwl_hprot_TPH[0] > 0)) { - cp->epb_on = OPJ_TRUE; - - cp->hprot_MH = parameters->jpwl_hprot_MH; - for (i = 0; i < JPWL_MAX_NO_TILESPECS; i++) { - cp->hprot_TPH_tileno[i] = parameters->jpwl_hprot_TPH_tileno[i]; - cp->hprot_TPH[i] = parameters->jpwl_hprot_TPH[i]; - } - /* if tile specs are not specified, copy MH specs */ - if (cp->hprot_TPH[0] == -1) { - cp->hprot_TPH_tileno[0] = 0; - cp->hprot_TPH[0] = parameters->jpwl_hprot_MH; - } - for (i = 0; i < JPWL_MAX_NO_PACKSPECS; i++) { - cp->pprot_tileno[i] = parameters->jpwl_pprot_tileno[i]; - cp->pprot_packno[i] = parameters->jpwl_pprot_packno[i]; - cp->pprot[i] = parameters->jpwl_pprot[i]; - } - } - - /* set ESD writing */ - if ((parameters->jpwl_sens_size == 1) || (parameters->jpwl_sens_size == 2)) { - cp->esd_on = OPJ_TRUE; - - cp->sens_size = parameters->jpwl_sens_size; - cp->sens_addr = parameters->jpwl_sens_addr; - cp->sens_range = parameters->jpwl_sens_range; - - cp->sens_MH = parameters->jpwl_sens_MH; - for (i = 0; i < JPWL_MAX_NO_TILESPECS; i++) { - cp->sens_TPH_tileno[i] = parameters->jpwl_sens_TPH_tileno[i]; - cp->sens_TPH[i] = parameters->jpwl_sens_TPH[i]; - } - } - - /* always set RED writing to false: we are at the encoder */ - cp->red_on = OPJ_FALSE; - - } else { - cp->epc_on = OPJ_FALSE; - } -#endif /* USE_JPWL */ - - - /* initialize the mutiple tiles */ - /* ---------------------------- */ - cp->tcps = (opj_tcp_t*) opj_calloc(cp->tw * cp->th, sizeof(opj_tcp_t)); - - for (tileno = 0; tileno < cp->tw * cp->th; tileno++) { - opj_tcp_t *tcp = &cp->tcps[tileno]; - tcp->numlayers = parameters->tcp_numlayers; - for (j = 0; j < tcp->numlayers; j++) { - if(cp->cinema){ - if (cp->fixed_quality) { - tcp->distoratio[j] = parameters->tcp_distoratio[j]; - } - tcp->rates[j] = parameters->tcp_rates[j]; - }else{ - if (cp->fixed_quality) { /* add fixed_quality */ - tcp->distoratio[j] = parameters->tcp_distoratio[j]; - } else { - tcp->rates[j] = parameters->tcp_rates[j]; - } - } - } - tcp->csty = parameters->csty; - tcp->prg = parameters->prog_order; - tcp->mct = parameters->tcp_mct; - - numpocs_tile = 0; - tcp->POC = 0; - if (parameters->numpocs) { - /* initialisation of POC */ - tcp->POC = 1; - for (i = 0; i < parameters->numpocs; i++) { - if((tileno == parameters->POC[i].tile - 1) || (parameters->POC[i].tile == -1)) { - opj_poc_t *tcp_poc = &tcp->pocs[numpocs_tile]; - tcp_poc->resno0 = parameters->POC[numpocs_tile].resno0; - tcp_poc->compno0 = parameters->POC[numpocs_tile].compno0; - tcp_poc->layno1 = parameters->POC[numpocs_tile].layno1; - tcp_poc->resno1 = parameters->POC[numpocs_tile].resno1; - tcp_poc->compno1 = parameters->POC[numpocs_tile].compno1; - tcp_poc->prg1 = parameters->POC[numpocs_tile].prg1; - tcp_poc->tile = parameters->POC[numpocs_tile].tile; - numpocs_tile++; - } - } - tcp->numpocs = numpocs_tile -1 ; - }else{ - tcp->numpocs = 0; - } - - tcp->tccps = (opj_tccp_t*) opj_calloc(image->numcomps, sizeof(opj_tccp_t)); - - for (i = 0; i < image->numcomps; i++) { - opj_tccp_t *tccp = &tcp->tccps[i]; - tccp->csty = parameters->csty & 0x01; /* 0 => one precinct || 1 => custom precinct */ - tccp->numresolutions = parameters->numresolution; - tccp->cblkw = int_floorlog2(parameters->cblockw_init); - tccp->cblkh = int_floorlog2(parameters->cblockh_init); - tccp->cblksty = parameters->mode; - tccp->qmfbid = parameters->irreversible ? 0 : 1; - tccp->qntsty = parameters->irreversible ? J2K_CCP_QNTSTY_SEQNT : J2K_CCP_QNTSTY_NOQNT; - tccp->numgbits = 2; - if (i == parameters->roi_compno) { - tccp->roishift = parameters->roi_shift; - } else { - tccp->roishift = 0; - } - - if(parameters->cp_cinema) - { - /*Precinct size for lowest frequency subband=128*/ - tccp->prcw[0] = 7; - tccp->prch[0] = 7; - /*Precinct size at all other resolutions = 256*/ - for (j = 1; j < tccp->numresolutions; j++) { - tccp->prcw[j] = 8; - tccp->prch[j] = 8; - } - }else{ - if (parameters->csty & J2K_CCP_CSTY_PRT) { - int p = 0; - for (j = tccp->numresolutions - 1; j >= 0; j--) { - if (p < parameters->res_spec) { - - if (parameters->prcw_init[p] < 1) { - tccp->prcw[j] = 1; - } else { - tccp->prcw[j] = int_floorlog2(parameters->prcw_init[p]); - } - - if (parameters->prch_init[p] < 1) { - tccp->prch[j] = 1; - }else { - tccp->prch[j] = int_floorlog2(parameters->prch_init[p]); - } - - } else { - int res_spec = parameters->res_spec; - int size_prcw = parameters->prcw_init[res_spec - 1] >> (p - (res_spec - 1)); - int size_prch = parameters->prch_init[res_spec - 1] >> (p - (res_spec - 1)); - - if (size_prcw < 1) { - tccp->prcw[j] = 1; - } else { - tccp->prcw[j] = int_floorlog2(size_prcw); - } - - if (size_prch < 1) { - tccp->prch[j] = 1; - } else { - tccp->prch[j] = int_floorlog2(size_prch); - } - } - p++; - /*printf("\nsize precinct for level %d : %d,%d\n", j,tccp->prcw[j], tccp->prch[j]); */ - } /*end for*/ - } else { - for (j = 0; j < tccp->numresolutions; j++) { - tccp->prcw[j] = 15; - tccp->prch[j] = 15; - } - } - } - - dwt_calc_explicit_stepsizes(tccp, image->comps[i].prec); - } - } -} - -opj_bool j2k_encode(opj_j2k_t *j2k, opj_cio_t *cio, opj_image_t *image, opj_codestream_info_t *cstr_info) { - int tileno, compno; - opj_cp_t *cp = NULL; - - opj_tcd_t *tcd = NULL; /* TCD component */ - - j2k->cio = cio; - j2k->image = image; - - cp = j2k->cp; - - /* INDEX >> */ - j2k->cstr_info = cstr_info; - if (cstr_info) { - int compno; - cstr_info->tile = (opj_tile_info_t *) opj_malloc(cp->tw * cp->th * sizeof(opj_tile_info_t)); - cstr_info->image_w = image->x1 - image->x0; - cstr_info->image_h = image->y1 - image->y0; - cstr_info->prog = (&cp->tcps[0])->prg; - cstr_info->tw = cp->tw; - cstr_info->th = cp->th; - cstr_info->tile_x = cp->tdx; /* new version parser */ - cstr_info->tile_y = cp->tdy; /* new version parser */ - cstr_info->tile_Ox = cp->tx0; /* new version parser */ - cstr_info->tile_Oy = cp->ty0; /* new version parser */ - cstr_info->numcomps = image->numcomps; - cstr_info->numlayers = (&cp->tcps[0])->numlayers; - cstr_info->numdecompos = (int*) opj_malloc(image->numcomps * sizeof(int)); - for (compno=0; compno < image->numcomps; compno++) { - cstr_info->numdecompos[compno] = (&cp->tcps[0])->tccps->numresolutions - 1; - } - cstr_info->D_max = 0.0; /* ADD Marcela */ - cstr_info->main_head_start = cio_tell(cio); /* position of SOC */ - cstr_info->maxmarknum = 100; - cstr_info->marker = (opj_marker_info_t *) opj_malloc(cstr_info->maxmarknum * sizeof(opj_marker_info_t)); - cstr_info->marknum = 0; - } - /* << INDEX */ - - j2k_write_soc(j2k); - j2k_write_siz(j2k); - j2k_write_cod(j2k); - j2k_write_qcd(j2k); - - if(cp->cinema){ - for (compno = 1; compno < image->numcomps; compno++) { - j2k_write_coc(j2k, compno); - j2k_write_qcc(j2k, compno); - } - } - - for (compno = 0; compno < image->numcomps; compno++) { - opj_tcp_t *tcp = &cp->tcps[0]; - if (tcp->tccps[compno].roishift) - j2k_write_rgn(j2k, compno, 0); - } - if (cp->comment != NULL) { - j2k_write_com(j2k); - } - - j2k->totnum_tp = j2k_calculate_tp(cp,image->numcomps,image,j2k); - /* TLM Marker*/ - if(cp->cinema){ - j2k_write_tlm(j2k); - if (cp->cinema == CINEMA4K_24) { - j2k_write_poc(j2k); - } - } - - /* uncomment only for testing JPSEC marker writing */ - /* j2k_write_sec(j2k); */ - - /* INDEX >> */ - if(cstr_info) { - cstr_info->main_head_end = cio_tell(cio) - 1; - } - /* << INDEX */ - /**** Main Header ENDS here ***/ - - /* create the tile encoder */ - tcd = tcd_create(j2k->cinfo); - - /* encode each tile */ - for (tileno = 0; tileno < cp->tw * cp->th; tileno++) { - int pino; - int tilepartno=0; - /* UniPG>> */ - int acc_pack_num = 0; - /* <tcps[tileno]; - opj_event_msg(j2k->cinfo, EVT_INFO, "tile number %d / %d\n", tileno + 1, cp->tw * cp->th); - - j2k->curtileno = tileno; - j2k->cur_tp_num = 0; - tcd->cur_totnum_tp = j2k->cur_totnum_tp[j2k->curtileno]; - /* initialisation before tile encoding */ - if (tileno == 0) { - tcd_malloc_encode(tcd, image, cp, j2k->curtileno); - } else { - tcd_init_encode(tcd, image, cp, j2k->curtileno); - } - - /* INDEX >> */ - if(cstr_info) { - cstr_info->tile[j2k->curtileno].start_pos = cio_tell(cio) + j2k->pos_correction; - cstr_info->tile[j2k->curtileno].maxmarknum = 10; - cstr_info->tile[j2k->curtileno].marker = (opj_marker_info_t *) opj_malloc(cstr_info->tile[j2k->curtileno].maxmarknum * sizeof(opj_marker_info_t)); - cstr_info->tile[j2k->curtileno].marknum = 0; - } - /* << INDEX */ - - for(pino = 0; pino <= tcp->numpocs; pino++) { - int tot_num_tp; - tcd->cur_pino=pino; - - /*Get number of tile parts*/ - tot_num_tp = j2k_get_num_tp(cp,pino,tileno); - tcd->tp_pos = cp->tp_pos; - - for(tilepartno = 0; tilepartno < tot_num_tp ; tilepartno++){ - j2k->tp_num = tilepartno; - /* INDEX >> */ - if(cstr_info) - cstr_info->tile[j2k->curtileno].tp[j2k->cur_tp_num].tp_start_pos = - cio_tell(cio) + j2k->pos_correction; - /* << INDEX */ - j2k_write_sot(j2k); - - if(j2k->cur_tp_num == 0 && cp->cinema == 0){ - for (compno = 1; compno < image->numcomps; compno++) { - j2k_write_coc(j2k, compno); - j2k_write_qcc(j2k, compno); - } - if (cp->tcps[tileno].numpocs) { - j2k_write_poc(j2k); - } - } - - /* INDEX >> */ - if(cstr_info) - cstr_info->tile[j2k->curtileno].tp[j2k->cur_tp_num].tp_end_header = - cio_tell(cio) + j2k->pos_correction + 1; - /* << INDEX */ - - j2k_write_sod(j2k, tcd); - - /* INDEX >> */ - if(cstr_info) { - cstr_info->tile[j2k->curtileno].tp[j2k->cur_tp_num].tp_end_pos = - cio_tell(cio) + j2k->pos_correction - 1; - cstr_info->tile[j2k->curtileno].tp[j2k->cur_tp_num].tp_start_pack = - acc_pack_num; - cstr_info->tile[j2k->curtileno].tp[j2k->cur_tp_num].tp_numpacks = - cstr_info->packno - acc_pack_num; - acc_pack_num = cstr_info->packno; - } - /* << INDEX */ - - j2k->cur_tp_num++; - } - } - if(cstr_info) { - cstr_info->tile[j2k->curtileno].end_pos = cio_tell(cio) + j2k->pos_correction - 1; - } - - - /* - if (tile->PPT) { // BAD PPT !!! - FILE *PPT_file; - int i; - PPT_file=fopen("PPT","rb"); - fprintf(stderr,"%c%c%c%c",255,97,tile->len_ppt/256,tile->len_ppt%256); - for (i=0;ilen_ppt;i++) { - unsigned char elmt; - fread(&elmt, 1, 1, PPT_file); - fwrite(&elmt,1,1,f); - } - fclose(PPT_file); - unlink("PPT"); - } - */ - - } - - /* destroy the tile encoder */ - tcd_free_encode(tcd); - tcd_destroy(tcd); - - opj_free(j2k->cur_totnum_tp); - - j2k_write_eoc(j2k); - - if(cstr_info) { - cstr_info->codestream_size = cio_tell(cio) + j2k->pos_correction; - /* UniPG>> */ - /* The following adjustment is done to adjust the codestream size */ - /* if SOD is not at 0 in the buffer. Useful in case of JP2, where */ - /* the first bunch of bytes is not in the codestream */ - cstr_info->codestream_size -= cstr_info->main_head_start; - /* <epc_on) { - - /* encode according to JPWL */ - jpwl_encode(j2k, cio, image); - - } -#endif /* USE_JPWL */ - - return OPJ_TRUE; -} - -static void j2k_add_mhmarker(opj_codestream_info_t *cstr_info, unsigned short int type, int pos, int len) { - - if (!cstr_info) - return; - - /* expand the list? */ - if ((cstr_info->marknum + 1) > cstr_info->maxmarknum) { - cstr_info->maxmarknum = 100 + (int) ((float) cstr_info->maxmarknum * 1.0F); - cstr_info->marker = (opj_marker_info_t*)opj_realloc(cstr_info->marker, cstr_info->maxmarknum); - } - - /* add the marker */ - cstr_info->marker[cstr_info->marknum].type = type; - cstr_info->marker[cstr_info->marknum].pos = pos; - cstr_info->marker[cstr_info->marknum].len = len; - cstr_info->marknum++; - -} - -static void j2k_add_tlmarker( int tileno, opj_codestream_info_t *cstr_info, unsigned short int type, int pos, int len) { - - opj_marker_info_t *marker; - - if (!cstr_info) - return; - - /* expand the list? */ - if ((cstr_info->tile[tileno].marknum + 1) > cstr_info->tile[tileno].maxmarknum) { - cstr_info->tile[tileno].maxmarknum = 100 + (int) ((float) cstr_info->tile[tileno].maxmarknum * 1.0F); - cstr_info->tile[tileno].marker = (opj_marker_info_t*)opj_realloc(cstr_info->tile[tileno].marker, cstr_info->maxmarknum); - } - - marker = &(cstr_info->tile[tileno].marker[cstr_info->tile[tileno].marknum]); - - /* add the marker */ - marker->type = type; - marker->pos = pos; - marker->len = len; - cstr_info->tile[tileno].marknum++; -} diff --git a/openjpeg-dotnet/libopenjpeg/j2k.h b/openjpeg-dotnet/libopenjpeg/j2k.h deleted file mode 100644 index 6338c290..00000000 --- a/openjpeg-dotnet/libopenjpeg/j2k.h +++ /dev/null @@ -1,446 +0,0 @@ -/* - * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium - * Copyright (c) 2002-2007, Professor Benoit Macq - * Copyright (c) 2001-2003, David Janssens - * Copyright (c) 2002-2003, Yannick Verschueren - * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe - * Copyright (c) 2005, Herve Drolon, FreeImage Team - * Copyright (c) 2006-2007, Parvatha Elangovan - * 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 __J2K_H -#define __J2K_H -/** -@file j2k.h -@brief The JPEG-2000 Codestream Reader/Writer (J2K) - -The functions in J2K.C have for goal to read/write the several parts of the codestream: markers and data. -*/ - -/** @defgroup J2K J2K - JPEG-2000 codestream reader/writer */ -/*@{*/ - -#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 /**< Selective arithmetic coding bypass */ -#define J2K_CCP_CBLKSTY_RESET 0x02 /**< Reset context probabilities on coding pass boundaries */ -#define J2K_CCP_CBLKSTY_TERMALL 0x04 /**< Termination on each coding pass */ -#define J2K_CCP_CBLKSTY_VSC 0x08 /**< Vertically stripe causal context */ -#define J2K_CCP_CBLKSTY_PTERM 0x10 /**< Predictable termination */ -#define J2K_CCP_CBLKSTY_SEGSYM 0x20 /**< Segmentation symbols are used */ -#define J2K_CCP_QNTSTY_NOQNT 0 -#define J2K_CCP_QNTSTY_SIQNT 1 -#define J2K_CCP_QNTSTY_SEQNT 2 - -/* ----------------------------------------------------------------------- */ - -#define J2K_MS_SOC 0xff4f /**< SOC marker value */ -#define J2K_MS_SOT 0xff90 /**< SOT marker value */ -#define J2K_MS_SOD 0xff93 /**< SOD marker value */ -#define J2K_MS_EOC 0xffd9 /**< EOC marker value */ -#define J2K_MS_SIZ 0xff51 /**< SIZ marker value */ -#define J2K_MS_COD 0xff52 /**< COD marker value */ -#define J2K_MS_COC 0xff53 /**< COC marker value */ -#define J2K_MS_RGN 0xff5e /**< RGN marker value */ -#define J2K_MS_QCD 0xff5c /**< QCD marker value */ -#define J2K_MS_QCC 0xff5d /**< QCC marker value */ -#define J2K_MS_POC 0xff5f /**< POC marker value */ -#define J2K_MS_TLM 0xff55 /**< TLM marker value */ -#define J2K_MS_PLM 0xff57 /**< PLM marker value */ -#define J2K_MS_PLT 0xff58 /**< PLT marker value */ -#define J2K_MS_PPM 0xff60 /**< PPM marker value */ -#define J2K_MS_PPT 0xff61 /**< PPT marker value */ -#define J2K_MS_SOP 0xff91 /**< SOP marker value */ -#define J2K_MS_EPH 0xff92 /**< EPH marker value */ -#define J2K_MS_CRG 0xff63 /**< CRG marker value */ -#define J2K_MS_COM 0xff64 /**< COM marker value */ -/* UniPG>> */ -#ifdef USE_JPWL -#define J2K_MS_EPC 0xff68 /**< EPC marker value (Part 11: JPEG 2000 for Wireless) */ -#define J2K_MS_EPB 0xff66 /**< EPB marker value (Part 11: JPEG 2000 for Wireless) */ -#define J2K_MS_ESD 0xff67 /**< ESD marker value (Part 11: JPEG 2000 for Wireless) */ -#define J2K_MS_RED 0xff69 /**< RED marker value (Part 11: JPEG 2000 for Wireless) */ -#endif /* USE_JPWL */ -#ifdef USE_JPSEC -#define J2K_MS_SEC 0xff65 /**< SEC marker value (Part 8: Secure JPEG 2000) */ -#define J2K_MS_INSEC 0xff94 /**< INSEC marker value (Part 8: Secure JPEG 2000) */ -#endif /* USE_JPSEC */ -/* < there was a PPT marker for the present tile */ - int ppt; - /** used in case of multiple marker PPT (number of info already stored) */ - int ppt_store; - /** ppmbug1 */ - int ppt_len; - /** add fixed_quality */ - float distoratio[100]; - /** tile-component coding parameters */ - opj_tccp_t *tccps; -} opj_tcp_t; - -/** -Coding parameters -*/ -typedef struct opj_cp { - /** Digital cinema profile*/ - OPJ_CINEMA_MODE cinema; - /** Maximum rate for each component. If == 0, component size limitation is not considered */ - int max_comp_size; - /** Size of the image in bits*/ - int img_size; - /** Rsiz*/ - OPJ_RSIZ_CAPABILITIES rsiz; - /** Enabling Tile part generation*/ - char tp_on; - /** Flag determining tile part generation*/ - char tp_flag; - /** Position of tile part flag in progression order*/ - int tp_pos; - /** allocation by rate/distortion */ - int disto_alloc; - /** allocation by fixed layer */ - int fixed_alloc; - /** add fixed_quality */ - int fixed_quality; - /** if != 0, then original dimension divided by 2^(reduce); if == 0 or not used, image is decoded to the full resolution */ - int reduce; - /** if != 0, then only the first "layer" layers are decoded; if == 0 or not used, all the quality layers are decoded */ - int layer; - /** if == NO_LIMITATION, decode entire codestream; if == LIMIT_TO_MAIN_HEADER then only decode the main header */ - OPJ_LIMIT_DECODING limit_decoding; - /** XTOsiz */ - int tx0; - /** YTOsiz */ - int ty0; - /** XTsiz */ - int tdx; - /** YTsiz */ - int tdy; - /** comment for coding */ - char *comment; - /** number of tiles in width */ - int tw; - /** number of tiles in heigth */ - int th; - /** ID number of the tiles present in the codestream */ - int *tileno; - /** size of the vector tileno */ - int tileno_size; - /** packet header store there for futur use in t2_decode_packet */ - unsigned char *ppm_data; - /** pointer remaining on the first byte of the first header if ppm is used */ - unsigned char *ppm_data_first; - /** if ppm == 1 --> there was a PPM marker for the present tile */ - int ppm; - /** use in case of multiple marker PPM (number of info already store) */ - int ppm_store; - /** use in case of multiple marker PPM (case on non-finished previous info) */ - int ppm_previous; - /** ppmbug1 */ - int ppm_len; - /** tile coding parameters */ - opj_tcp_t *tcps; - /** fixed layer */ - int *matrice; -/* UniPG>> */ -#ifdef USE_JPWL - /** enables writing of EPC in MH, thus activating JPWL */ - opj_bool epc_on; - /** enables writing of EPB, in case of activated JPWL */ - opj_bool epb_on; - /** enables writing of ESD, in case of activated JPWL */ - opj_bool esd_on; - /** enables writing of informative techniques of ESD, in case of activated JPWL */ - opj_bool info_on; - /** enables writing of RED, in case of activated JPWL */ - opj_bool red_on; - /** error protection method for MH (0,1,16,32,37-128) */ - int hprot_MH; - /** tile number of header protection specification (>=0) */ - int hprot_TPH_tileno[JPWL_MAX_NO_TILESPECS]; - /** error protection methods for TPHs (0,1,16,32,37-128) */ - int hprot_TPH[JPWL_MAX_NO_TILESPECS]; - /** tile number of packet protection specification (>=0) */ - int pprot_tileno[JPWL_MAX_NO_PACKSPECS]; - /** packet number of packet protection specification (>=0) */ - int pprot_packno[JPWL_MAX_NO_PACKSPECS]; - /** error protection methods for packets (0,1,16,32,37-128) */ - int pprot[JPWL_MAX_NO_PACKSPECS]; - /** enables writing of ESD, (0/2/4 bytes) */ - int sens_size; - /** sensitivity addressing size (0=auto/2/4 bytes) */ - int sens_addr; - /** sensitivity range (0-3) */ - int sens_range; - /** sensitivity method for MH (-1,0-7) */ - int sens_MH; - /** tile number of sensitivity specification (>=0) */ - int sens_TPH_tileno[JPWL_MAX_NO_TILESPECS]; - /** sensitivity methods for TPHs (-1,0-7) */ - int sens_TPH[JPWL_MAX_NO_TILESPECS]; - /** enables JPWL correction at the decoder */ - opj_bool correct; - /** expected number of components at the decoder */ - int exp_comps; - /** maximum number of tiles at the decoder */ - int max_tiles; -#endif /* USE_JPWL */ -/* <cp. -@param j2k J2K decompressor handle -@param parameters decompression parameters -*/ -void j2k_setup_decoder(opj_j2k_t *j2k, opj_dparameters_t *parameters); -/** -Decode an image from a JPEG-2000 codestream -@param j2k J2K decompressor handle -@param cio Input buffer stream -@param cstr_info Codestream information structure if required, NULL otherwise -@return Returns a decoded image if successful, returns NULL otherwise -*/ -opj_image_t* j2k_decode(opj_j2k_t *j2k, opj_cio_t *cio, opj_codestream_info_t *cstr_info); -/** -Decode an image form a JPT-stream (JPEG 2000, JPIP) -@param j2k J2K decompressor handle -@param cio Input buffer stream -@param cstr_info Codestream information structure if required, NULL otherwise -@return Returns a decoded image if successful, returns NULL otherwise -*/ -opj_image_t* j2k_decode_jpt_stream(opj_j2k_t *j2k, opj_cio_t *cio, opj_codestream_info_t *cstr_info); -/** -Creates a J2K compression structure -@param cinfo Codec context info -@return Returns a handle to a J2K compressor if successful, returns NULL otherwise -*/ -opj_j2k_t* j2k_create_compress(opj_common_ptr cinfo); -/** -Destroy a J2K compressor handle -@param j2k J2K compressor handle to destroy -*/ -void j2k_destroy_compress(opj_j2k_t *j2k); -/** -Setup the encoder parameters using the current image and using user parameters. -Coding parameters are returned in j2k->cp. -@param j2k J2K compressor handle -@param parameters compression parameters -@param image input filled image -*/ -void j2k_setup_encoder(opj_j2k_t *j2k, opj_cparameters_t *parameters, opj_image_t *image); -/** -Converts an enum type progression order to string type -*/ -char *j2k_convert_progression_order(OPJ_PROG_ORDER prg_order); -/** -Encode an image into a JPEG-2000 codestream -@param j2k J2K compressor handle -@param cio Output buffer stream -@param image Image to encode -@param cstr_info Codestream information structure if required, NULL otherwise -@return Returns true if successful, returns false otherwise -*/ -opj_bool j2k_encode(opj_j2k_t *j2k, opj_cio_t *cio, opj_image_t *image, opj_codestream_info_t *cstr_info); - -/* ----------------------------------------------------------------------- */ -/*@}*/ - -/*@}*/ - -#endif /* __J2K_H */ diff --git a/openjpeg-dotnet/libopenjpeg/j2k_lib.c b/openjpeg-dotnet/libopenjpeg/j2k_lib.c deleted file mode 100644 index a66e31e9..00000000 --- a/openjpeg-dotnet/libopenjpeg/j2k_lib.c +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (c) 2005, Herve Drolon, FreeImage Team - * 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. - */ - -#ifdef _WIN32 -#include -#else -#include -#include -#include -#endif /* _WIN32 */ -#include "opj_includes.h" - -double opj_clock(void) { -#ifdef _WIN32 - /* _WIN32: use QueryPerformance (very accurate) */ - LARGE_INTEGER freq , t ; - /* freq is the clock speed of the CPU */ - QueryPerformanceFrequency(&freq) ; - /* cout << "freq = " << ((double) freq.QuadPart) << endl; */ - /* t is the high resolution performance counter (see MSDN) */ - QueryPerformanceCounter ( & t ) ; - return ( t.QuadPart /(double) freq.QuadPart ) ; -#else - /* Unix or Linux: use resource usage */ - struct rusage t; - double procTime; - /* (1) Get the rusage data structure at this moment (man getrusage) */ - getrusage(0,&t); - /* (2) What is the elapsed time ? - CPU time = User time + System time */ - /* (2a) Get the seconds */ - procTime = t.ru_utime.tv_sec + t.ru_stime.tv_sec; - /* (2b) More precisely! Get the microseconds part ! */ - return ( procTime + (t.ru_utime.tv_usec + t.ru_stime.tv_usec) * 1e-6 ) ; -#endif -} - diff --git a/openjpeg-dotnet/libopenjpeg/j2k_lib.h b/openjpeg-dotnet/libopenjpeg/j2k_lib.h deleted file mode 100644 index 5f3406e5..00000000 --- a/openjpeg-dotnet/libopenjpeg/j2k_lib.h +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) 2005, Herve Drolon, FreeImage Team - * 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 __J2K_LIB_H -#define __J2K_LIB_H -/** -@file j2k_lib.h -@brief Internal functions - -The functions in J2K_LIB.C are internal utilities mainly used for timing. -*/ - -/** @defgroup MISC MISC - Miscellaneous internal functions */ -/*@{*/ - -/** @name Exported functions */ -/*@{*/ -/* ----------------------------------------------------------------------- */ - -/** -Difference in successive opj_clock() calls tells you the elapsed time -@return Returns time in seconds -*/ -double opj_clock(void); - -/* ----------------------------------------------------------------------- */ -/*@}*/ - -/*@}*/ - -#endif /* __J2K_LIB_H */ - diff --git a/openjpeg-dotnet/libopenjpeg/jp2.c b/openjpeg-dotnet/libopenjpeg/jp2.c deleted file mode 100644 index 5ae114c3..00000000 --- a/openjpeg-dotnet/libopenjpeg/jp2.c +++ /dev/null @@ -1,1210 +0,0 @@ -/* - * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium - * Copyright (c) 2002-2007, Professor Benoit Macq - * Copyright (c) 2001-2003, David Janssens - * Copyright (c) 2002-2003, Yannick Verschueren - * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe - * Copyright (c) 2005, Herve Drolon, FreeImage Team - * Copyright (c) 2010-2011, Kaori Hagihara - * 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 "opj_includes.h" - -/** @defgroup JP2 JP2 - JPEG-2000 file format reader/writer */ -/*@{*/ - -/** @name Local static functions */ -/*@{*/ - -/** -Read box headers -@param cinfo Codec context info -@param cio Input stream -@param box -@return Returns true if successful, returns false otherwise -*/ -static opj_bool jp2_read_boxhdr(opj_common_ptr cinfo, opj_cio_t *cio, opj_jp2_box_t *box); -/*static void jp2_write_url(opj_cio_t *cio, char *Idx_file);*/ -/** -Read the IHDR box - Image Header box -@param jp2 JP2 handle -@param cio Input buffer stream -@return Returns true if successful, returns false otherwise -*/ -static opj_bool jp2_read_ihdr(opj_jp2_t *jp2, opj_cio_t *cio); -static void jp2_write_ihdr(opj_jp2_t *jp2, opj_cio_t *cio); -static void jp2_write_bpcc(opj_jp2_t *jp2, opj_cio_t *cio); -static opj_bool jp2_read_bpcc(opj_jp2_t *jp2, opj_cio_t *cio); -static void jp2_write_colr(opj_jp2_t *jp2, opj_cio_t *cio); -/** -Write the FTYP box - File type box -@param jp2 JP2 handle -@param cio Output buffer stream -*/ -static void jp2_write_ftyp(opj_jp2_t *jp2, opj_cio_t *cio); -/** -Read the FTYP box - File type box -@param jp2 JP2 handle -@param cio Input buffer stream -@return Returns true if successful, returns false otherwise -*/ -static opj_bool jp2_read_ftyp(opj_jp2_t *jp2, opj_cio_t *cio); -static int jp2_write_jp2c(opj_jp2_t *jp2, opj_cio_t *cio, opj_image_t *image, opj_codestream_info_t *cstr_info); -static opj_bool jp2_read_jp2c(opj_jp2_t *jp2, opj_cio_t *cio, unsigned int *j2k_codestream_length, unsigned int *j2k_codestream_offset); -static void jp2_write_jp(opj_cio_t *cio); -/** -Read the JP box - JPEG 2000 signature -@param jp2 JP2 handle -@param cio Input buffer stream -@return Returns true if successful, returns false otherwise -*/ -static opj_bool jp2_read_jp(opj_jp2_t *jp2, opj_cio_t *cio); -/** -Decode the structure of a JP2 file -@param jp2 JP2 handle -@param cio Input buffer stream -@param color Collector for profile, cdef and pclr data -@return Returns true if successful, returns false otherwise -*/ -static opj_bool jp2_read_struct(opj_jp2_t *jp2, opj_cio_t *cio, - opj_jp2_color_t *color); -/** -Apply collected palette data -@param color Collector for profile, cdef and pclr data -@param image -*/ -static void jp2_apply_pclr(opj_jp2_color_t *color, opj_image_t *image, opj_common_ptr cinfo); -/** -Collect palette data -@param jp2 JP2 handle -@param cio Input buffer stream -@param box -@param color Collector for profile, cdef and pclr data -@return Returns true if successful, returns false otherwise -*/ -static opj_bool jp2_read_pclr(opj_jp2_t *jp2, opj_cio_t *cio, - opj_jp2_box_t *box, opj_jp2_color_t *color); -/** -Collect component mapping data -@param jp2 JP2 handle -@param cio Input buffer stream -@param box -@param color Collector for profile, cdef and pclr data -@return Returns true if successful, returns false otherwise -*/ -static opj_bool jp2_read_cmap(opj_jp2_t *jp2, opj_cio_t *cio, - opj_jp2_box_t *box, opj_jp2_color_t *color); -/** -Collect colour specification data -@param jp2 JP2 handle -@param cio Input buffer stream -@param box -@param color Collector for profile, cdef and pclr data -@return Returns true if successful, returns false otherwise -*/ -static opj_bool jp2_read_colr(opj_jp2_t *jp2, opj_cio_t *cio, - opj_jp2_box_t *box, opj_jp2_color_t *color); -/** -Write file Index (superbox) -@param[in] offset_jp2c offset of jp2c box -@param[in] length_jp2c length of jp2c box -@param[in] offset_idx offset of cidx box -@param[in] length_idx length of cidx box -@param[in] cio file output handle -@return length of fidx box -*/ -static int write_fidx( int offset_jp2c, int length_jp2c, int offset_idx, int length_idx, opj_cio_t *cio); -/** -Write index Finder box -@param[in] offset offset of fidx box -@param[in] length length of fidx box -@param[in] cio file output handle -*/ -static void write_iptr( int offset, int length, opj_cio_t *cio); -/** -Write proxy box -@param[in] offset_jp2c offset of jp2c box -@param[in] length_jp2c length of jp2c box -@param[in] offset_idx offset of cidx box -@param[in] length_idx length of cidx box -@param[in] cio file output handle -*/ -static void write_prxy( int offset_jp2c, int length_jp2c, int offset_idx, int length_idx, opj_cio_t *cio); -/*@}*/ - -/*@}*/ - -/* ----------------------------------------------------------------------- */ - -static opj_bool jp2_read_boxhdr(opj_common_ptr cinfo, opj_cio_t *cio, opj_jp2_box_t *box) { - box->init_pos = cio_tell(cio); - box->length = cio_read(cio, 4); - box->type = cio_read(cio, 4); - if (box->length == 1) { - if (cio_read(cio, 4) != 0) { - opj_event_msg(cinfo, EVT_ERROR, "Cannot handle box sizes higher than 2^32\n"); - return OPJ_FALSE; - } - box->length = cio_read(cio, 4); - if (box->length == 0) - box->length = cio_numbytesleft(cio) + 12; - } - else if (box->length == 0) { - box->length = cio_numbytesleft(cio) + 8; - } - - return OPJ_TRUE; -} - -#if 0 -static void jp2_write_url(opj_cio_t *cio, char *Idx_file) { - unsigned int i; - opj_jp2_box_t box; - - box.init_pos = cio_tell(cio); - cio_skip(cio, 4); - cio_write(cio, JP2_URL, 4); /* DBTL */ - cio_write(cio, 0, 1); /* VERS */ - cio_write(cio, 0, 3); /* FLAG */ - - if(Idx_file) { - for (i = 0; i < strlen(Idx_file); i++) { - cio_write(cio, Idx_file[i], 1); - } - } - - box.length = cio_tell(cio) - box.init_pos; - cio_seek(cio, box.init_pos); - cio_write(cio, box.length, 4); /* L */ - cio_seek(cio, box.init_pos + box.length); -} -#endif - -static opj_bool jp2_read_ihdr(opj_jp2_t *jp2, opj_cio_t *cio) { - opj_jp2_box_t box; - - opj_common_ptr cinfo = jp2->cinfo; - - jp2_read_boxhdr(cinfo, cio, &box); - if (JP2_IHDR != box.type) { - opj_event_msg(cinfo, EVT_ERROR, "Expected IHDR Marker\n"); - return OPJ_FALSE; - } - - jp2->h = cio_read(cio, 4); /* HEIGHT */ - jp2->w = cio_read(cio, 4); /* WIDTH */ - jp2->numcomps = cio_read(cio, 2); /* NC */ - jp2->comps = (opj_jp2_comps_t*) opj_malloc(jp2->numcomps * sizeof(opj_jp2_comps_t)); - - jp2->bpc = cio_read(cio, 1); /* BPC */ - - jp2->C = cio_read(cio, 1); /* C */ - jp2->UnkC = cio_read(cio, 1); /* UnkC */ - jp2->IPR = cio_read(cio, 1); /* IPR */ - - if (cio_tell(cio) - box.init_pos != box.length) { - opj_event_msg(cinfo, EVT_ERROR, "Error with IHDR Box\n"); - return OPJ_FALSE; - } - - return OPJ_TRUE; -} - -static void jp2_write_ihdr(opj_jp2_t *jp2, opj_cio_t *cio) { - opj_jp2_box_t box; - - box.init_pos = cio_tell(cio); - cio_skip(cio, 4); - cio_write(cio, JP2_IHDR, 4); /* IHDR */ - - cio_write(cio, jp2->h, 4); /* HEIGHT */ - cio_write(cio, jp2->w, 4); /* WIDTH */ - cio_write(cio, jp2->numcomps, 2); /* NC */ - - cio_write(cio, jp2->bpc, 1); /* BPC */ - - cio_write(cio, jp2->C, 1); /* C : Always 7 */ - cio_write(cio, jp2->UnkC, 1); /* UnkC, colorspace unknown */ - cio_write(cio, jp2->IPR, 1); /* IPR, no intellectual property */ - - box.length = cio_tell(cio) - box.init_pos; - cio_seek(cio, box.init_pos); - cio_write(cio, box.length, 4); /* L */ - cio_seek(cio, box.init_pos + box.length); -} - -static void jp2_write_bpcc(opj_jp2_t *jp2, opj_cio_t *cio) { - unsigned int i; - opj_jp2_box_t box; - - box.init_pos = cio_tell(cio); - cio_skip(cio, 4); - cio_write(cio, JP2_BPCC, 4); /* BPCC */ - - for (i = 0; i < jp2->numcomps; i++) { - cio_write(cio, jp2->comps[i].bpcc, 1); - } - - box.length = cio_tell(cio) - box.init_pos; - cio_seek(cio, box.init_pos); - cio_write(cio, box.length, 4); /* L */ - cio_seek(cio, box.init_pos + box.length); -} - - -static opj_bool jp2_read_bpcc(opj_jp2_t *jp2, opj_cio_t *cio) { - unsigned int i; - opj_jp2_box_t box; - - opj_common_ptr cinfo = jp2->cinfo; - - jp2_read_boxhdr(cinfo, cio, &box); - if (JP2_BPCC != box.type) { - opj_event_msg(cinfo, EVT_ERROR, "Expected BPCC Marker\n"); - return OPJ_FALSE; - } - - for (i = 0; i < jp2->numcomps; i++) { - jp2->comps[i].bpcc = cio_read(cio, 1); - } - - if (cio_tell(cio) - box.init_pos != box.length) { - opj_event_msg(cinfo, EVT_ERROR, "Error with BPCC Box\n"); - return OPJ_FALSE; - } - - return OPJ_TRUE; -} - -static void jp2_write_colr(opj_jp2_t *jp2, opj_cio_t *cio) { - opj_jp2_box_t box; - - box.init_pos = cio_tell(cio); - cio_skip(cio, 4); - cio_write(cio, JP2_COLR, 4); /* COLR */ - - cio_write(cio, jp2->meth, 1); /* METH */ - cio_write(cio, jp2->precedence, 1); /* PRECEDENCE */ - cio_write(cio, jp2->approx, 1); /* APPROX */ - - if(jp2->meth == 2) - jp2->enumcs = 0; - - cio_write(cio, jp2->enumcs, 4); /* EnumCS */ - - box.length = cio_tell(cio) - box.init_pos; - cio_seek(cio, box.init_pos); - cio_write(cio, box.length, 4); /* L */ - cio_seek(cio, box.init_pos + box.length); -} - -static void jp2_free_pclr(opj_jp2_color_t *color) -{ - opj_free(color->jp2_pclr->channel_sign); - opj_free(color->jp2_pclr->channel_size); - opj_free(color->jp2_pclr->entries); - - if(color->jp2_pclr->cmap) opj_free(color->jp2_pclr->cmap); - - opj_free(color->jp2_pclr); color->jp2_pclr = NULL; -} - -static void free_color_data(opj_jp2_color_t *color) -{ - if(color->jp2_pclr) - { - jp2_free_pclr(color); - } - if(color->jp2_cdef) - { - if(color->jp2_cdef->info) opj_free(color->jp2_cdef->info); - opj_free(color->jp2_cdef); - } - if(color->icc_profile_buf) opj_free(color->icc_profile_buf); -} - -static void jp2_apply_pclr(opj_jp2_color_t *color, opj_image_t *image, opj_common_ptr cinfo) -{ - opj_image_comp_t *old_comps, *new_comps; - unsigned char *channel_size, *channel_sign; - unsigned int *entries; - opj_jp2_cmap_comp_t *cmap; - int *src, *dst; - unsigned int j, max; - unsigned short i, nr_channels, cmp, pcol; - int k, top_k; - - channel_size = color->jp2_pclr->channel_size; - channel_sign = color->jp2_pclr->channel_sign; - entries = color->jp2_pclr->entries; - cmap = color->jp2_pclr->cmap; - nr_channels = color->jp2_pclr->nr_channels; - - old_comps = image->comps; - new_comps = (opj_image_comp_t*) - opj_malloc(nr_channels * sizeof(opj_image_comp_t)); - - for(i = 0; i < nr_channels; ++i) - { - pcol = cmap[i].pcol; cmp = cmap[i].cmp; - - if( pcol < nr_channels ) - new_comps[pcol] = old_comps[cmp]; - else - { - opj_event_msg(cinfo, EVT_ERROR, "Error with pcol value %d (max: %d). skipping\n", pcol, nr_channels); - continue; - } - - if(cmap[i].mtyp == 0) /* Direct use */ - { - old_comps[cmp].data = NULL; continue; - } -/* Palette mapping: */ - new_comps[pcol].data = (int*) - opj_malloc(old_comps[cmp].w * old_comps[cmp].h * sizeof(int)); - new_comps[pcol].prec = channel_size[i]; - new_comps[pcol].sgnd = channel_sign[i]; - } - top_k = color->jp2_pclr->nr_entries - 1; - - for(i = 0; i < nr_channels; ++i) - { -/* Direct use: */ - if(cmap[i].mtyp == 0) continue; - -/* Palette mapping: */ - cmp = cmap[i].cmp; pcol = cmap[i].pcol; - src = old_comps[cmp].data; - dst = new_comps[pcol].data; - max = new_comps[pcol].w * new_comps[pcol].h; - - for(j = 0; j < max; ++j) - { -/* The index */ - if((k = src[j]) < 0) k = 0; else if(k > top_k) k = top_k; -/* The colour */ - dst[j] = entries[k * nr_channels + pcol]; - } - } - max = image->numcomps; - for(i = 0; i < max; ++i) - { - if(old_comps[i].data) opj_free(old_comps[i].data); - } - opj_free(old_comps); - image->comps = new_comps; - image->numcomps = nr_channels; - - jp2_free_pclr(color); - -}/* apply_pclr() */ - -static opj_bool jp2_read_pclr(opj_jp2_t *jp2, opj_cio_t *cio, - opj_jp2_box_t *box, opj_jp2_color_t *color) -{ - opj_jp2_pclr_t *jp2_pclr; - unsigned char *channel_size, *channel_sign; - unsigned int *entries; - unsigned short nr_entries, nr_channels; - unsigned short i, j; - unsigned char uc; - - OPJ_ARG_NOT_USED(box); - OPJ_ARG_NOT_USED(jp2); - -/* Part 1, I.5.3.4: 'There shall be at most one Palette box inside - * a JP2 Header box' : -*/ - if(color->jp2_pclr) return OPJ_FALSE; - - nr_entries = (unsigned short)cio_read(cio, 2); /* NE */ - nr_channels = (unsigned short)cio_read(cio, 1);/* NPC */ - - entries = (unsigned int*) - opj_malloc(nr_channels * nr_entries * sizeof(unsigned int)); - channel_size = (unsigned char*)opj_malloc(nr_channels); - channel_sign = (unsigned char*)opj_malloc(nr_channels); - - jp2_pclr = (opj_jp2_pclr_t*)opj_malloc(sizeof(opj_jp2_pclr_t)); - jp2_pclr->channel_sign = channel_sign; - jp2_pclr->channel_size = channel_size; - jp2_pclr->entries = entries; - jp2_pclr->nr_entries = nr_entries; - jp2_pclr->nr_channels = nr_channels; - jp2_pclr->cmap = NULL; - - color->jp2_pclr = jp2_pclr; - - for(i = 0; i < nr_channels; ++i) - { - uc = cio_read(cio, 1); /* Bi */ - channel_size[i] = (uc & 0x7f) + 1; - channel_sign[i] = (uc & 0x80)?1:0; - } - - for(j = 0; j < nr_entries; ++j) - { - for(i = 0; i < nr_channels; ++i) - { -/* Cji */ - *entries++ = cio_read(cio, channel_size[i]>>3); - } - } - - return OPJ_TRUE; -}/* jp2_read_pclr() */ - -static opj_bool jp2_read_cmap(opj_jp2_t *jp2, opj_cio_t *cio, - opj_jp2_box_t *box, opj_jp2_color_t *color) -{ - opj_jp2_cmap_comp_t *cmap; - unsigned short i, nr_channels; - - OPJ_ARG_NOT_USED(box); - OPJ_ARG_NOT_USED(jp2); - -/* Need nr_channels: */ - if(color->jp2_pclr == NULL) return OPJ_FALSE; - -/* Part 1, I.5.3.5: 'There shall be at most one Component Mapping box - * inside a JP2 Header box' : -*/ - if(color->jp2_pclr->cmap) return OPJ_FALSE; - - nr_channels = color->jp2_pclr->nr_channels; - cmap = (opj_jp2_cmap_comp_t*) - opj_malloc(nr_channels * sizeof(opj_jp2_cmap_comp_t)); - - for(i = 0; i < nr_channels; ++i) - { - cmap[i].cmp = (unsigned short)cio_read(cio, 2); - cmap[i].mtyp = cio_read(cio, 1); - cmap[i].pcol = cio_read(cio, 1); - - } - color->jp2_pclr->cmap = cmap; - - return OPJ_TRUE; -}/* jp2_read_cmap() */ - -static void jp2_apply_cdef(opj_image_t *image, opj_jp2_color_t *color) -{ - opj_jp2_cdef_info_t *info; - int color_space; - unsigned short i, n, cn, typ, asoc, acn; - - color_space = image->color_space; - info = color->jp2_cdef->info; - n = color->jp2_cdef->n; - - for(i = 0; i < n; ++i) - { -/* WATCH: acn = asoc - 1 ! */ - if((asoc = info[i].asoc) == 0) continue; - - cn = info[i].cn; typ = info[i].typ; acn = asoc - 1; - - if(cn != acn) - { - opj_image_comp_t saved; - - memcpy(&saved, &image->comps[cn], sizeof(opj_image_comp_t)); - memcpy(&image->comps[cn], &image->comps[acn], sizeof(opj_image_comp_t)); - memcpy(&image->comps[acn], &saved, sizeof(opj_image_comp_t)); - - info[i].asoc = cn + 1; - info[acn].asoc = info[acn].cn + 1; - } - } - if(color->jp2_cdef->info) opj_free(color->jp2_cdef->info); - - opj_free(color->jp2_cdef); color->jp2_cdef = NULL; - -}/* jp2_apply_cdef() */ - -static opj_bool jp2_read_cdef(opj_jp2_t *jp2, opj_cio_t *cio, - opj_jp2_box_t *box, opj_jp2_color_t *color) -{ - opj_jp2_cdef_info_t *info; - unsigned short i, n; - - OPJ_ARG_NOT_USED(box); - OPJ_ARG_NOT_USED(jp2); - -/* Part 1, I.5.3.6: 'The shall be at most one Channel Definition box - * inside a JP2 Header box.' -*/ - if(color->jp2_cdef) return OPJ_FALSE; - - if((n = (unsigned short)cio_read(cio, 2)) == 0) return OPJ_FALSE; /* szukw000: FIXME */ - - info = (opj_jp2_cdef_info_t*) - opj_malloc(n * sizeof(opj_jp2_cdef_info_t)); - - color->jp2_cdef = (opj_jp2_cdef_t*)opj_malloc(sizeof(opj_jp2_cdef_t)); - color->jp2_cdef->info = info; - color->jp2_cdef->n = n; - - for(i = 0; i < n; ++i) - { - info[i].cn = (unsigned short)cio_read(cio, 2); - info[i].typ = (unsigned short)cio_read(cio, 2); - info[i].asoc = (unsigned short)cio_read(cio, 2); - - } - return OPJ_TRUE; -}/* jp2_read_cdef() */ - -static opj_bool jp2_read_colr(opj_jp2_t *jp2, opj_cio_t *cio, - opj_jp2_box_t *box, opj_jp2_color_t *color) -{ - int skip_len; - opj_common_ptr cinfo; - -/* Part 1, I.5.3.3 : 'A conforming JP2 reader shall ignore all Colour - * Specification boxes after the first.' -*/ - if(color->jp2_has_colr) return OPJ_FALSE; - - cinfo = jp2->cinfo; - - jp2->meth = cio_read(cio, 1); /* METH */ - jp2->precedence = cio_read(cio, 1); /* PRECEDENCE */ - jp2->approx = cio_read(cio, 1); /* APPROX */ - - if (jp2->meth == 1) - { - jp2->enumcs = cio_read(cio, 4); /* EnumCS */ - } - else - if (jp2->meth == 2) - { -/* skip PROFILE */ - skip_len = box->init_pos + box->length - cio_tell(cio); - if (skip_len < 0) - { - opj_event_msg(cinfo, EVT_ERROR, "Error with COLR box size\n"); - return OPJ_FALSE; - } - if(skip_len > 0) - { - unsigned char *start; - - start = cio_getbp(cio); - color->icc_profile_buf = (unsigned char*)opj_malloc(skip_len); - color->icc_profile_len = skip_len; - - cio_skip(cio, box->init_pos + box->length - cio_tell(cio)); - - memcpy(color->icc_profile_buf, start, skip_len); - } - } - - if (cio_tell(cio) - box->init_pos != box->length) - { - opj_event_msg(cinfo, EVT_ERROR, "Error with COLR Box\n"); - return OPJ_FALSE; - } - color->jp2_has_colr = 1; - - return OPJ_TRUE; -}/* jp2_read_colr() */ - -opj_bool jp2_read_jp2h(opj_jp2_t *jp2, opj_cio_t *cio, opj_jp2_color_t *color) -{ - opj_jp2_box_t box; - int jp2h_end; - - opj_common_ptr cinfo = jp2->cinfo; - - jp2_read_boxhdr(cinfo, cio, &box); - do - { - if (JP2_JP2H != box.type) - { - if (box.type == JP2_JP2C) - { - opj_event_msg(cinfo, EVT_ERROR, "Expected JP2H Marker\n"); - return OPJ_FALSE; - } - cio_skip(cio, box.length - 8); - - if(cio->bp >= cio->end) return OPJ_FALSE; - - jp2_read_boxhdr(cinfo, cio, &box); - } - } while(JP2_JP2H != box.type); - - if (!jp2_read_ihdr(jp2, cio)) - return OPJ_FALSE; - jp2h_end = box.init_pos + box.length; - - if (jp2->bpc == 255) - { - if (!jp2_read_bpcc(jp2, cio)) - return OPJ_FALSE; - } - jp2_read_boxhdr(cinfo, cio, &box); - - while(cio_tell(cio) < jp2h_end) - { - if(box.type == JP2_COLR) - { - if( !jp2_read_colr(jp2, cio, &box, color)) - { - cio_seek(cio, box.init_pos + 8); - cio_skip(cio, box.length - 8); - } - jp2_read_boxhdr(cinfo, cio, &box); - continue; - } - if(box.type == JP2_CDEF && !jp2->ignore_pclr_cmap_cdef) - { - if( !jp2_read_cdef(jp2, cio, &box, color)) - { - cio_seek(cio, box.init_pos + 8); - cio_skip(cio, box.length - 8); - } - jp2_read_boxhdr(cinfo, cio, &box); - continue; - } - if(box.type == JP2_PCLR && !jp2->ignore_pclr_cmap_cdef) - { - if( !jp2_read_pclr(jp2, cio, &box, color)) - { - cio_seek(cio, box.init_pos + 8); - cio_skip(cio, box.length - 8); - } - jp2_read_boxhdr(cinfo, cio, &box); - continue; - } - if(box.type == JP2_CMAP && !jp2->ignore_pclr_cmap_cdef) - { - if( !jp2_read_cmap(jp2, cio, &box, color)) - { - cio_seek(cio, box.init_pos + 8); - cio_skip(cio, box.length - 8); - } - jp2_read_boxhdr(cinfo, cio, &box); - continue; - } - cio_seek(cio, box.init_pos + 8); - cio_skip(cio, box.length - 8); - jp2_read_boxhdr(cinfo, cio, &box); - - }/* while(cio_tell(cio) < box_end) */ - - cio_seek(cio, jp2h_end); - -/* Part 1, I.5.3.3 : 'must contain at least one' */ - return (color->jp2_has_colr == 1); - -}/* jp2_read_jp2h() */ - -opj_image_t* opj_jp2_decode(opj_jp2_t *jp2, opj_cio_t *cio, - opj_codestream_info_t *cstr_info) -{ - opj_common_ptr cinfo; - opj_image_t *image = NULL; - opj_jp2_color_t color; - - if(!jp2 || !cio) - { - return NULL; - } - memset(&color, 0, sizeof(opj_jp2_color_t)); - cinfo = jp2->cinfo; - -/* JP2 decoding */ - if(!jp2_read_struct(jp2, cio, &color)) - { - free_color_data(&color); - opj_event_msg(cinfo, EVT_ERROR, "Failed to decode jp2 structure\n"); - return NULL; - } - -/* J2K decoding */ - image = j2k_decode(jp2->j2k, cio, cstr_info); - - if(!image) - { - free_color_data(&color); - opj_event_msg(cinfo, EVT_ERROR, "Failed to decode J2K image\n"); - return NULL; - } - - if (!jp2->ignore_pclr_cmap_cdef){ - - /* Set Image Color Space */ - if (jp2->enumcs == 16) - image->color_space = CLRSPC_SRGB; - else if (jp2->enumcs == 17) - image->color_space = CLRSPC_GRAY; - else if (jp2->enumcs == 18) - image->color_space = CLRSPC_SYCC; - else - image->color_space = CLRSPC_UNKNOWN; - - if(color.jp2_cdef) - { - jp2_apply_cdef(image, &color); - } - if(color.jp2_pclr) - { -/* Part 1, I.5.3.4: Either both or none : */ - if( !color.jp2_pclr->cmap) - jp2_free_pclr(&color); - else - jp2_apply_pclr(&color, image, cinfo); - } - if(color.icc_profile_buf) - { - image->icc_profile_buf = color.icc_profile_buf; - color.icc_profile_buf = NULL; - image->icc_profile_len = color.icc_profile_len; - } - } - - return image; - -}/* opj_jp2_decode() */ - - -void jp2_write_jp2h(opj_jp2_t *jp2, opj_cio_t *cio) { - opj_jp2_box_t box; - - box.init_pos = cio_tell(cio); - cio_skip(cio, 4); - cio_write(cio, JP2_JP2H, 4); /* JP2H */ - - jp2_write_ihdr(jp2, cio); - - if (jp2->bpc == 255) { - jp2_write_bpcc(jp2, cio); - } - jp2_write_colr(jp2, cio); - - box.length = cio_tell(cio) - box.init_pos; - cio_seek(cio, box.init_pos); - cio_write(cio, box.length, 4); /* L */ - cio_seek(cio, box.init_pos + box.length); -} - -static void jp2_write_ftyp(opj_jp2_t *jp2, opj_cio_t *cio) { - unsigned int i; - opj_jp2_box_t box; - - box.init_pos = cio_tell(cio); - cio_skip(cio, 4); - cio_write(cio, JP2_FTYP, 4); /* FTYP */ - - cio_write(cio, jp2->brand, 4); /* BR */ - cio_write(cio, jp2->minversion, 4); /* MinV */ - - for (i = 0; i < jp2->numcl; i++) { - cio_write(cio, jp2->cl[i], 4); /* CL */ - } - - box.length = cio_tell(cio) - box.init_pos; - cio_seek(cio, box.init_pos); - cio_write(cio, box.length, 4); /* L */ - cio_seek(cio, box.init_pos + box.length); -} - -static opj_bool jp2_read_ftyp(opj_jp2_t *jp2, opj_cio_t *cio) { - int i; - opj_jp2_box_t box; - - opj_common_ptr cinfo = jp2->cinfo; - - jp2_read_boxhdr(cinfo, cio, &box); - - if (JP2_FTYP != box.type) { - opj_event_msg(cinfo, EVT_ERROR, "Expected FTYP Marker\n"); - return OPJ_FALSE; - } - - jp2->brand = cio_read(cio, 4); /* BR */ - jp2->minversion = cio_read(cio, 4); /* MinV */ - jp2->numcl = (box.length - 16) / 4; - jp2->cl = (unsigned int *) opj_malloc(jp2->numcl * sizeof(unsigned int)); - - for (i = 0; i < (int)jp2->numcl; i++) { - jp2->cl[i] = cio_read(cio, 4); /* CLi */ - } - - if (cio_tell(cio) - box.init_pos != box.length) { - opj_event_msg(cinfo, EVT_ERROR, "Error with FTYP Box\n"); - return OPJ_FALSE; - } - - return OPJ_TRUE; -} - -static int jp2_write_jp2c(opj_jp2_t *jp2, opj_cio_t *cio, opj_image_t *image, opj_codestream_info_t *cstr_info) { - unsigned int j2k_codestream_offset, j2k_codestream_length; - opj_jp2_box_t box; - - opj_j2k_t *j2k = jp2->j2k; - - box.init_pos = cio_tell(cio); - cio_skip(cio, 4); - cio_write(cio, JP2_JP2C, 4); /* JP2C */ - - /* J2K encoding */ - j2k_codestream_offset = cio_tell(cio); - if(!j2k_encode(j2k, cio, image, cstr_info)) { - opj_event_msg(j2k->cinfo, EVT_ERROR, "Failed to encode image\n"); - return 0; - } - j2k_codestream_length = cio_tell(cio) - j2k_codestream_offset; - - jp2->j2k_codestream_offset = j2k_codestream_offset; - jp2->j2k_codestream_length = j2k_codestream_length; - - box.length = 8 + jp2->j2k_codestream_length; - cio_seek(cio, box.init_pos); - cio_write(cio, box.length, 4); /* L */ - cio_seek(cio, box.init_pos + box.length); - - return box.length; -} - -static opj_bool jp2_read_jp2c(opj_jp2_t *jp2, opj_cio_t *cio, unsigned int *j2k_codestream_length, unsigned int *j2k_codestream_offset) { - opj_jp2_box_t box; - - opj_common_ptr cinfo = jp2->cinfo; - - jp2_read_boxhdr(cinfo, cio, &box); - do { - if(JP2_JP2C != box.type) { - cio_skip(cio, box.length - 8); - jp2_read_boxhdr(cinfo, cio, &box); - } - } while(JP2_JP2C != box.type); - - *j2k_codestream_offset = cio_tell(cio); - *j2k_codestream_length = box.length - 8; - - return OPJ_TRUE; -} - -static void jp2_write_jp(opj_cio_t *cio) { - opj_jp2_box_t box; - - box.init_pos = cio_tell(cio); - cio_skip(cio, 4); - cio_write(cio, JP2_JP, 4); /* JP2 signature */ - cio_write(cio, 0x0d0a870a, 4); - - box.length = cio_tell(cio) - box.init_pos; - cio_seek(cio, box.init_pos); - cio_write(cio, box.length, 4); /* L */ - cio_seek(cio, box.init_pos + box.length); -} - -static opj_bool jp2_read_jp(opj_jp2_t *jp2, opj_cio_t *cio) { - opj_jp2_box_t box; - - opj_common_ptr cinfo = jp2->cinfo; - - jp2_read_boxhdr(cinfo, cio, &box); - if (JP2_JP != box.type) { - opj_event_msg(cinfo, EVT_ERROR, "Expected JP Marker\n"); - return OPJ_FALSE; - } - if (0x0d0a870a != cio_read(cio, 4)) { - opj_event_msg(cinfo, EVT_ERROR, "Error with JP Marker\n"); - return OPJ_FALSE; - } - if (cio_tell(cio) - box.init_pos != box.length) { - opj_event_msg(cinfo, EVT_ERROR, "Error with JP Box size\n"); - return OPJ_FALSE; - } - - return OPJ_TRUE; -} - - -static opj_bool jp2_read_struct(opj_jp2_t *jp2, opj_cio_t *cio, - opj_jp2_color_t *color) { - if (!jp2_read_jp(jp2, cio)) - return OPJ_FALSE; - if (!jp2_read_ftyp(jp2, cio)) - return OPJ_FALSE; - if (!jp2_read_jp2h(jp2, cio, color)) - return OPJ_FALSE; - if (!jp2_read_jp2c(jp2, cio, &jp2->j2k_codestream_length, &jp2->j2k_codestream_offset)) - return OPJ_FALSE; - - return OPJ_TRUE; -} - - -static int write_fidx( int offset_jp2c, int length_jp2c, int offset_idx, int length_idx, opj_cio_t *cio) -{ - int len, lenp; - - lenp = cio_tell( cio); - cio_skip( cio, 4); /* L [at the end] */ - cio_write( cio, JPIP_FIDX, 4); /* IPTR */ - - write_prxy( offset_jp2c, length_jp2c, offset_idx, length_idx, cio); - - len = cio_tell( cio)-lenp; - cio_seek( cio, lenp); - cio_write( cio, len, 4); /* L */ - cio_seek( cio, lenp+len); - - return len; -} - -static void write_prxy( int offset_jp2c, int length_jp2c, int offset_idx, int length_idx, opj_cio_t *cio) -{ - int len, lenp; - - lenp = cio_tell( cio); - cio_skip( cio, 4); /* L [at the end] */ - cio_write( cio, JPIP_PRXY, 4); /* IPTR */ - - cio_write( cio, offset_jp2c, 8); /* OOFF */ - cio_write( cio, length_jp2c, 4); /* OBH part 1 */ - cio_write( cio, JP2_JP2C, 4); /* OBH part 2 */ - - cio_write( cio, 1,1); /* NI */ - - cio_write( cio, offset_idx, 8); /* IOFF */ - cio_write( cio, length_idx, 4); /* IBH part 1 */ - cio_write( cio, JPIP_CIDX, 4); /* IBH part 2 */ - - len = cio_tell( cio)-lenp; - cio_seek( cio, lenp); - cio_write( cio, len, 4); /* L */ - cio_seek( cio, lenp+len); -} - -static void write_iptr( int offset, int length, opj_cio_t *cio) -{ - int len, lenp; - - lenp = cio_tell( cio); - cio_skip( cio, 4); /* L [at the end] */ - cio_write( cio, JPIP_IPTR, 4); /* IPTR */ - - cio_write( cio, offset, 8); - cio_write( cio, length, 8); - - len = cio_tell( cio)-lenp; - cio_seek( cio, lenp); - cio_write( cio, len, 4); /* L */ - cio_seek( cio, lenp+len); -} - - -/* ----------------------------------------------------------------------- */ -/* JP2 decoder interface */ -/* ----------------------------------------------------------------------- */ - -opj_jp2_t* jp2_create_decompress(opj_common_ptr cinfo) { - opj_jp2_t *jp2 = (opj_jp2_t*) opj_calloc(1, sizeof(opj_jp2_t)); - if(jp2) { - jp2->cinfo = cinfo; - /* create the J2K codec */ - jp2->j2k = j2k_create_decompress(cinfo); - if(jp2->j2k == NULL) { - jp2_destroy_decompress(jp2); - return NULL; - } - } - return jp2; -} - -void jp2_destroy_decompress(opj_jp2_t *jp2) { - if(jp2) { - /* destroy the J2K codec */ - j2k_destroy_decompress(jp2->j2k); - - if(jp2->comps) { - opj_free(jp2->comps); - } - if(jp2->cl) { - opj_free(jp2->cl); - } - opj_free(jp2); - } -} - -void jp2_setup_decoder(opj_jp2_t *jp2, opj_dparameters_t *parameters) { - /* setup the J2K codec */ - j2k_setup_decoder(jp2->j2k, parameters); - /* further JP2 initializations go here */ - jp2->ignore_pclr_cmap_cdef = parameters->flags & OPJ_DPARAMETERS_IGNORE_PCLR_CMAP_CDEF_FLAG; -} - -/* ----------------------------------------------------------------------- */ -/* JP2 encoder interface */ -/* ----------------------------------------------------------------------- */ - -opj_jp2_t* jp2_create_compress(opj_common_ptr cinfo) { - opj_jp2_t *jp2 = (opj_jp2_t*)opj_malloc(sizeof(opj_jp2_t)); - if(jp2) { - jp2->cinfo = cinfo; - /* create the J2K codec */ - jp2->j2k = j2k_create_compress(cinfo); - if(jp2->j2k == NULL) { - jp2_destroy_compress(jp2); - return NULL; - } - } - return jp2; -} - -void jp2_destroy_compress(opj_jp2_t *jp2) { - if(jp2) { - /* destroy the J2K codec */ - j2k_destroy_compress(jp2->j2k); - - if(jp2->comps) { - opj_free(jp2->comps); - } - if(jp2->cl) { - opj_free(jp2->cl); - } - opj_free(jp2); - } -} - -void jp2_setup_encoder(opj_jp2_t *jp2, opj_cparameters_t *parameters, opj_image_t *image) { - int i; - int depth_0, sign; - - if(!jp2 || !parameters || !image) - return; - - /* setup the J2K codec */ - /* ------------------- */ - - /* Check if number of components respects standard */ - if (image->numcomps < 1 || image->numcomps > 16384) { - opj_event_msg(jp2->cinfo, EVT_ERROR, "Invalid number of components specified while setting up JP2 encoder\n"); - return; - } - - j2k_setup_encoder(jp2->j2k, parameters, image); - - /* setup the JP2 codec */ - /* ------------------- */ - - /* Profile box */ - - jp2->brand = JP2_JP2; /* BR */ - jp2->minversion = 0; /* MinV */ - jp2->numcl = 1; - jp2->cl = (unsigned int*) opj_malloc(jp2->numcl * sizeof(unsigned int)); - jp2->cl[0] = JP2_JP2; /* CL0 : JP2 */ - - /* Image Header box */ - - jp2->numcomps = image->numcomps; /* NC */ - jp2->comps = (opj_jp2_comps_t*) opj_malloc(jp2->numcomps * sizeof(opj_jp2_comps_t)); - jp2->h = image->y1 - image->y0; /* HEIGHT */ - jp2->w = image->x1 - image->x0; /* WIDTH */ - /* BPC */ - depth_0 = image->comps[0].prec - 1; - sign = image->comps[0].sgnd; - jp2->bpc = depth_0 + (sign << 7); - for (i = 1; i < image->numcomps; i++) { - int depth = image->comps[i].prec - 1; - sign = image->comps[i].sgnd; - if (depth_0 != depth) - jp2->bpc = 255; - } - jp2->C = 7; /* C : Always 7 */ - jp2->UnkC = 0; /* UnkC, colorspace specified in colr box */ - jp2->IPR = 0; /* IPR, no intellectual property */ - - /* BitsPerComponent box */ - - for (i = 0; i < image->numcomps; i++) { - jp2->comps[i].bpcc = image->comps[i].prec - 1 + (image->comps[i].sgnd << 7); - } - jp2->meth = 1; - if (image->color_space == 1) - jp2->enumcs = 16; /* sRGB as defined by IEC 61966-2.1 */ - else if (image->color_space == 2) - jp2->enumcs = 17; /* greyscale */ - else if (image->color_space == 3) - jp2->enumcs = 18; /* YUV */ - jp2->precedence = 0; /* PRECEDENCE */ - jp2->approx = 0; /* APPROX */ - - jp2->jpip_on = parameters->jpip_on; -} - -opj_bool opj_jp2_encode(opj_jp2_t *jp2, opj_cio_t *cio, opj_image_t *image, opj_codestream_info_t *cstr_info) { - - int pos_iptr, pos_cidx, pos_jp2c, len_jp2c, len_cidx, end_pos, pos_fidx, len_fidx; - pos_jp2c = pos_iptr = -1; /* remove a warning */ - - /* JP2 encoding */ - - /* JPEG 2000 Signature box */ - jp2_write_jp(cio); - /* File Type box */ - jp2_write_ftyp(jp2, cio); - /* JP2 Header box */ - jp2_write_jp2h(jp2, cio); - - if( jp2->jpip_on){ - pos_iptr = cio_tell( cio); - cio_skip( cio, 24); /* IPTR further ! */ - - pos_jp2c = cio_tell( cio); - } - - /* J2K encoding */ - if(!(len_jp2c = jp2_write_jp2c( jp2, cio, image, cstr_info))){ - opj_event_msg(jp2->cinfo, EVT_ERROR, "Failed to encode image\n"); - return OPJ_FALSE; - } - - if( jp2->jpip_on){ - pos_cidx = cio_tell( cio); - - len_cidx = write_cidx( pos_jp2c+8, cio, image, *cstr_info, len_jp2c-8); - - pos_fidx = cio_tell( cio); - len_fidx = write_fidx( pos_jp2c, len_jp2c, pos_cidx, len_cidx, cio); - - end_pos = cio_tell( cio); - - cio_seek( cio, pos_iptr); - write_iptr( pos_fidx, len_fidx, cio); - - cio_seek( cio, end_pos); - } - - return OPJ_TRUE; -} diff --git a/openjpeg-dotnet/libopenjpeg/jp2.h b/openjpeg-dotnet/libopenjpeg/jp2.h deleted file mode 100644 index acb643ca..00000000 --- a/openjpeg-dotnet/libopenjpeg/jp2.h +++ /dev/null @@ -1,234 +0,0 @@ -/* - * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium - * Copyright (c) 2002-2007, Professor Benoit Macq - * Copyright (c) 2002-2003, Yannick Verschueren - * Copyright (c) 2005, Herve Drolon, FreeImage Team - * 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 __JP2_H -#define __JP2_H -/** -@file jp2.h -@brief The JPEG-2000 file format Reader/Writer (JP2) - -*/ - -/** @defgroup JP2 JP2 - JPEG-2000 file format reader/writer */ -/*@{*/ - -#define JPIP_JPIP 0x6a706970 - -#define JP2_JP 0x6a502020 /**< JPEG 2000 signature box */ -#define JP2_FTYP 0x66747970 /**< File type box */ -#define JP2_JP2H 0x6a703268 /**< JP2 header box */ -#define JP2_IHDR 0x69686472 /**< Image header box */ -#define JP2_COLR 0x636f6c72 /**< Colour specification box */ -#define JP2_JP2C 0x6a703263 /**< Contiguous codestream box */ -#define JP2_URL 0x75726c20 /**< URL box */ -#define JP2_DTBL 0x6474626c /**< Data Reference box */ -#define JP2_BPCC 0x62706363 /**< Bits per component box */ -#define JP2_JP2 0x6a703220 /**< File type fields */ -#define JP2_PCLR 0x70636c72 /**< Palette box */ -#define JP2_CMAP 0x636d6170 /**< Component Mapping box */ -#define JP2_CDEF 0x63646566 /**< Channel Definition box */ - -/* ----------------------------------------------------------------------- */ -/** -Channel description: channel index, type, assocation -*/ -typedef struct opj_jp2_cdef_info -{ - unsigned short cn, typ, asoc; -} opj_jp2_cdef_info_t; - -/** -Channel descriptions and number of descriptions -*/ -typedef struct opj_jp2_cdef -{ - opj_jp2_cdef_info_t *info; - unsigned short n; -} opj_jp2_cdef_t; - -/** -Component mappings: channel index, mapping type, palette index -*/ -typedef struct opj_jp2_cmap_comp -{ - unsigned short cmp; - unsigned char mtyp, pcol; -} opj_jp2_cmap_comp_t; - -/** -Palette data: table entries, palette columns -*/ -typedef struct opj_jp2_pclr -{ - unsigned int *entries; - unsigned char *channel_sign; - unsigned char *channel_size; - opj_jp2_cmap_comp_t *cmap; - unsigned short nr_entries, nr_channels; -} opj_jp2_pclr_t; - -/** -Collector for ICC profile, palette, component mapping, channel description -*/ -typedef struct opj_jp2_color -{ - unsigned char *icc_profile_buf; - int icc_profile_len; - - opj_jp2_cdef_t *jp2_cdef; - opj_jp2_pclr_t *jp2_pclr; - unsigned char jp2_has_colr; -} opj_jp2_color_t; - -/** -JP2 component -*/ -typedef struct opj_jp2_comps { - int depth; - int sgnd; - int bpcc; -} opj_jp2_comps_t; - -/** -JPEG-2000 file format reader/writer -*/ -typedef struct opj_jp2 { - /** codec context */ - opj_common_ptr cinfo; - /** handle to the J2K codec */ - opj_j2k_t *j2k; - unsigned int w; - unsigned int h; - unsigned int numcomps; - unsigned int bpc; - unsigned int C; - unsigned int UnkC; - unsigned int IPR; - unsigned int meth; - unsigned int approx; - unsigned int enumcs; - unsigned int precedence; - unsigned int brand; - unsigned int minversion; - unsigned int numcl; - unsigned int *cl; - opj_jp2_comps_t *comps; - unsigned int j2k_codestream_offset; - unsigned int j2k_codestream_length; - opj_bool jpip_on; - opj_bool ignore_pclr_cmap_cdef; -} opj_jp2_t; - -/** -JP2 Box -*/ -typedef struct opj_jp2_box { - int length; - int type; - int init_pos; -} opj_jp2_box_t; - -/** @name Exported functions */ -/*@{*/ -/* ----------------------------------------------------------------------- */ -/** -Write the JP2H box - JP2 Header box (used in MJ2) -@param jp2 JP2 handle -@param cio Output buffer stream -*/ -void jp2_write_jp2h(opj_jp2_t *jp2, opj_cio_t *cio); -/** -Read the JP2H box - JP2 Header box (used in MJ2) -@param jp2 JP2 handle -@param cio Input buffer stream -@param ext Collector for profile, cdef and pclr data -@return Returns true if successful, returns false otherwise -*/ -opj_bool jp2_read_jp2h(opj_jp2_t *jp2, opj_cio_t *cio, opj_jp2_color_t *color); -/** -Creates a JP2 decompression structure -@param cinfo Codec context info -@return Returns a handle to a JP2 decompressor if successful, returns NULL otherwise -*/ -opj_jp2_t* jp2_create_decompress(opj_common_ptr cinfo); -/** -Destroy a JP2 decompressor handle -@param jp2 JP2 decompressor handle to destroy -*/ -void jp2_destroy_decompress(opj_jp2_t *jp2); -/** -Setup the decoder decoding parameters using user parameters. -Decoding parameters are returned in jp2->j2k->cp. -@param jp2 JP2 decompressor handle -@param parameters decompression parameters -*/ -void jp2_setup_decoder(opj_jp2_t *jp2, opj_dparameters_t *parameters); -/** -Decode an image from a JPEG-2000 file stream -@param jp2 JP2 decompressor handle -@param cio Input buffer stream -@param cstr_info Codestream information structure if required, NULL otherwise -@return Returns a decoded image if successful, returns NULL otherwise -*/ -opj_image_t* opj_jp2_decode(opj_jp2_t *jp2, opj_cio_t *cio, opj_codestream_info_t *cstr_info); -/** -Creates a JP2 compression structure -@param cinfo Codec context info -@return Returns a handle to a JP2 compressor if successful, returns NULL otherwise -*/ -opj_jp2_t* jp2_create_compress(opj_common_ptr cinfo); -/** -Destroy a JP2 compressor handle -@param jp2 JP2 compressor handle to destroy -*/ -void jp2_destroy_compress(opj_jp2_t *jp2); -/** -Setup the encoder parameters using the current image and using user parameters. -Coding parameters are returned in jp2->j2k->cp. -@param jp2 JP2 compressor handle -@param parameters compression parameters -@param image input filled image -*/ -void jp2_setup_encoder(opj_jp2_t *jp2, opj_cparameters_t *parameters, opj_image_t *image); -/** -Encode an image into a JPEG-2000 file stream -@param jp2 JP2 compressor handle -@param cio Output buffer stream -@param image Image to encode -@param cstr_info Codestream information structure if required, NULL otherwise -@return Returns true if successful, returns false otherwise -*/ -opj_bool opj_jp2_encode(opj_jp2_t *jp2, opj_cio_t *cio, opj_image_t *image, opj_codestream_info_t *cstr_info); - -/* ----------------------------------------------------------------------- */ -/*@}*/ - -/*@}*/ - -#endif /* __JP2_H */ - diff --git a/openjpeg-dotnet/libopenjpeg/jpt.c b/openjpeg-dotnet/libopenjpeg/jpt.c deleted file mode 100644 index a2566ea8..00000000 --- a/openjpeg-dotnet/libopenjpeg/jpt.c +++ /dev/null @@ -1,155 +0,0 @@ -/* - * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium - * Copyright (c) 2002-2007, Professor Benoit Macq - * Copyright (c) 2002-2003, Yannick Verschueren - * Copyright (c) 2005, Herve Drolon, FreeImage Team - * 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 "opj_includes.h" - -/* - * Read the information contains in VBAS [JPP/JPT stream message header] - * Store information (7 bits) in value - * - */ -unsigned int jpt_read_VBAS_info(opj_cio_t *cio, unsigned int value) { - unsigned char elmt; - - elmt = cio_read(cio, 1); - while ((elmt >> 7) == 1) { - value = (value << 7); - value |= (elmt & 0x7f); - elmt = cio_read(cio, 1); - } - value = (value << 7); - value |= (elmt & 0x7f); - - return value; -} - -/* - * Initialize the value of the message header structure - * - */ -void jpt_init_msg_header(opj_jpt_msg_header_t * header) { - header->Id = 0; /* In-class Identifier */ - header->last_byte = 0; /* Last byte information */ - header->Class_Id = 0; /* Class Identifier */ - header->CSn_Id = 0; /* CSn : index identifier */ - header->Msg_offset = 0; /* Message offset */ - header->Msg_length = 0; /* Message length */ - header->Layer_nb = 0; /* Auxiliary for JPP case */ -} - -/* - * Re-initialize the value of the message header structure - * - * Only parameters always present in message header - * - */ -void jpt_reinit_msg_header(opj_jpt_msg_header_t * header) { - header->Id = 0; /* In-class Identifier */ - header->last_byte = 0; /* Last byte information */ - header->Msg_offset = 0; /* Message offset */ - header->Msg_length = 0; /* Message length */ -} - -/* - * Read the message header for a JPP/JPT - stream - * - */ -void jpt_read_msg_header(opj_common_ptr cinfo, opj_cio_t *cio, opj_jpt_msg_header_t *header) { - unsigned char elmt, Class = 0, CSn = 0; - jpt_reinit_msg_header(header); - - /* ------------- */ - /* VBAS : Bin-ID */ - /* ------------- */ - elmt = cio_read(cio, 1); - - /* See for Class and CSn */ - switch ((elmt >> 5) & 0x03) { - case 0: - opj_event_msg(cinfo, EVT_ERROR, "Forbidden value encounter in message header !!\n"); - break; - case 1: - Class = 0; - CSn = 0; - break; - case 2: - Class = 1; - CSn = 0; - break; - case 3: - Class = 1; - CSn = 1; - break; - default: - break; - } - - /* see information on bits 'c' [p 10 : A.2.1 general, ISO/IEC FCD 15444-9] */ - if (((elmt >> 4) & 0x01) == 1) - header->last_byte = 1; - - /* In-class identifier */ - header->Id |= (elmt & 0x0f); - if ((elmt >> 7) == 1) - header->Id = jpt_read_VBAS_info(cio, header->Id); - - /* ------------ */ - /* VBAS : Class */ - /* ------------ */ - if (Class == 1) { - header->Class_Id = 0; - header->Class_Id = jpt_read_VBAS_info(cio, header->Class_Id); - } - - /* ---------- */ - /* VBAS : CSn */ - /* ---------- */ - if (CSn == 1) { - header->CSn_Id = 0; - header->CSn_Id = jpt_read_VBAS_info(cio, header->CSn_Id); - } - - /* ----------------- */ - /* VBAS : Msg_offset */ - /* ----------------- */ - header->Msg_offset = jpt_read_VBAS_info(cio, header->Msg_offset); - - /* ----------------- */ - /* VBAS : Msg_length */ - /* ----------------- */ - header->Msg_length = jpt_read_VBAS_info(cio, header->Msg_length); - - /* ---------- */ - /* VBAS : Aux */ - /* ---------- */ - if ((header->Class_Id & 0x01) == 1) { - header->Layer_nb = 0; - header->Layer_nb = jpt_read_VBAS_info(cio, header->Layer_nb); - } -} diff --git a/openjpeg-dotnet/libopenjpeg/jpt.h b/openjpeg-dotnet/libopenjpeg/jpt.h deleted file mode 100644 index eb01f98e..00000000 --- a/openjpeg-dotnet/libopenjpeg/jpt.h +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium - * Copyright (c) 2002-2007, Professor Benoit Macq - * Copyright (c) 2002-2003, Yannick Verschueren - * Copyright (c) 2005, Herve Drolon, FreeImage Team - * 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 __JPT_H -#define __JPT_H -/** -@file jpt.h -@brief JPT-stream reader (JPEG 2000, JPIP) - -JPT-stream functions are implemented in J2K.C. -*/ - -/** -Message Header JPT stream structure -*/ -typedef struct opj_jpt_msg_header { - /** In-class Identifier */ - unsigned int Id; - /** Last byte information */ - unsigned int last_byte; - /** Class Identifier */ - unsigned int Class_Id; - /** CSn : index identifier */ - unsigned int CSn_Id; - /** Message offset */ - unsigned int Msg_offset; - /** Message length */ - unsigned int Msg_length; - /** Auxiliary for JPP case */ - unsigned int Layer_nb; -} opj_jpt_msg_header_t; - -/* ----------------------------------------------------------------------- */ - -/** -Initialize the value of the message header structure -@param header Message header structure -*/ -void jpt_init_msg_header(opj_jpt_msg_header_t * header); - -/** -Read the message header for a JPP/JPT - stream -@param cinfo Codec context info -@param cio CIO handle -@param header Message header structure -*/ -void jpt_read_msg_header(opj_common_ptr cinfo, opj_cio_t *cio, opj_jpt_msg_header_t *header); - -#endif diff --git a/openjpeg-dotnet/libopenjpeg/jpwl/CMakeLists.txt b/openjpeg-dotnet/libopenjpeg/jpwl/CMakeLists.txt deleted file mode 100644 index 6fcfc957..00000000 --- a/openjpeg-dotnet/libopenjpeg/jpwl/CMakeLists.txt +++ /dev/null @@ -1,32 +0,0 @@ -# Makefile for the main JPWL OpenJPEG codecs: JPWL_ j2k_to_image and JPWL_image_to_j2k - -ADD_DEFINITIONS(-DUSE_JPWL) - -SET(JPWL_SRCS crc.c jpwl.c jpwl_lib.c rs.c) -IF(APPLE) - SET_SOURCE_FILES_PROPERTIES( - rs.c - PROPERTIES - COMPILE_FLAGS -fno-common) -ENDIF(APPLE) - -INCLUDE_DIRECTORIES( - ${OPENJPEG_SOURCE_DIR}/libopenjpeg - ) - -# Build the library -IF(WIN32) - IF(BUILD_SHARED_LIBS) - ADD_DEFINITIONS(-DOPJ_EXPORTS) - ELSE(BUILD_SHARED_LIBS) - ADD_DEFINITIONS(-DOPJ_STATIC) - ENDIF(BUILD_SHARED_LIBS) -ENDIF(WIN32) -ADD_LIBRARY(${OPENJPEG_LIBRARY_NAME}_JPWL ${JPWL_SRCS} ${OPENJPEG_SRCS}) -SET_TARGET_PROPERTIES(${OPENJPEG_LIBRARY_NAME}_JPWL - PROPERTIES ${OPENJPEG_LIBRARY_PROPERTIES}) - -# Install library -INSTALL(TARGETS ${OPENJPEG_LIBRARY_NAME}_JPWL - DESTINATION ${OPENJPEG_INSTALL_LIB_DIR} COMPONENT Libraries -) diff --git a/openjpeg-dotnet/libopenjpeg/jpwl/Makefile b/openjpeg-dotnet/libopenjpeg/jpwl/Makefile deleted file mode 100644 index 5e391778..00000000 --- a/openjpeg-dotnet/libopenjpeg/jpwl/Makefile +++ /dev/null @@ -1,908 +0,0 @@ -# Makefile.in generated by automake 1.11.1 from Makefile.am. -# libopenjpeg/jpwl/Makefile. Generated from Makefile.in by configure. - -# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, -# 2003, 2004, 2005, 2006, 2007, 2008, 2009 Free Software Foundation, -# Inc. -# This Makefile.in is free software; the Free Software Foundation -# gives unlimited permission to copy and/or distribute it, -# with or without modifications, as long as this notice is preserved. - -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY, to the extent permitted by law; without -# even the implied warranty of MERCHANTABILITY or FITNESS FOR A -# PARTICULAR PURPOSE. - - - - -pkgdatadir = $(datadir)/openjpeg -pkgincludedir = $(includedir)/openjpeg -pkglibdir = $(libdir)/openjpeg -pkglibexecdir = $(libexecdir)/openjpeg -am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd -install_sh_DATA = $(install_sh) -c -m 644 -install_sh_PROGRAM = $(install_sh) -c -install_sh_SCRIPT = $(install_sh) -c -INSTALL_HEADER = $(INSTALL_DATA) -transform = $(program_transform_name) -NORMAL_INSTALL = : -PRE_INSTALL = : -POST_INSTALL = : -NORMAL_UNINSTALL = : -PRE_UNINSTALL = : -POST_UNINSTALL = : -build_triplet = x86_64-unknown-linux-gnu -host_triplet = x86_64-unknown-linux-gnu -target_triplet = x86_64-unknown-linux-gnu -subdir = libopenjpeg/jpwl -DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in -ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/libtool.m4 \ - $(top_srcdir)/m4/ltoptions.m4 $(top_srcdir)/m4/ltsugar.m4 \ - $(top_srcdir)/m4/ltversion.m4 $(top_srcdir)/m4/lt~obsolete.m4 \ - $(top_srcdir)/m4/opj_check_lib.m4 \ - $(top_srcdir)/m4/opj_compiler_flag.m4 \ - $(top_srcdir)/m4/opj_doxygen.m4 $(top_srcdir)/m4/pkg.m4 \ - $(top_srcdir)/configure.ac -am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ - $(ACLOCAL_M4) -mkinstalldirs = $(install_sh) -d -CONFIG_HEADER = $(top_builddir)/opj_config.h -CONFIG_CLEAN_FILES = -CONFIG_CLEAN_VPATH_FILES = -am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; -am__vpath_adj = case $$p in \ - $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ - *) f=$$p;; \ - esac; -am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; -am__install_max = 40 -am__nobase_strip_setup = \ - srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` -am__nobase_strip = \ - for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" -am__nobase_list = $(am__nobase_strip_setup); \ - for p in $$list; do echo "$$p $$p"; done | \ - sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ - $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ - if (++n[$$2] == $(am__install_max)) \ - { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ - END { for (dir in files) print dir, files[dir] }' -am__base_list = \ - sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ - sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' -am__installdirs = "$(DESTDIR)$(libdir)" -LTLIBRARIES = $(lib_LTLIBRARIES) -libopenjpeg_JPWL_la_DEPENDENCIES = -am__objects_1 = libopenjpeg_JPWL_la-bio.lo libopenjpeg_JPWL_la-cio.lo \ - libopenjpeg_JPWL_la-dwt.lo libopenjpeg_JPWL_la-event.lo \ - libopenjpeg_JPWL_la-image.lo libopenjpeg_JPWL_la-j2k.lo \ - libopenjpeg_JPWL_la-j2k_lib.lo libopenjpeg_JPWL_la-jp2.lo \ - libopenjpeg_JPWL_la-jpt.lo libopenjpeg_JPWL_la-mct.lo \ - libopenjpeg_JPWL_la-mqc.lo libopenjpeg_JPWL_la-openjpeg.lo \ - libopenjpeg_JPWL_la-pi.lo libopenjpeg_JPWL_la-raw.lo \ - libopenjpeg_JPWL_la-t1.lo \ - libopenjpeg_JPWL_la-t1_generate_luts.lo \ - libopenjpeg_JPWL_la-t2.lo libopenjpeg_JPWL_la-tcd.lo \ - libopenjpeg_JPWL_la-tgt.lo libopenjpeg_JPWL_la-cidx_manager.lo \ - libopenjpeg_JPWL_la-phix_manager.lo \ - libopenjpeg_JPWL_la-ppix_manager.lo \ - libopenjpeg_JPWL_la-thix_manager.lo \ - libopenjpeg_JPWL_la-tpix_manager.lo -am_libopenjpeg_JPWL_la_OBJECTS = $(am__objects_1) \ - libopenjpeg_JPWL_la-crc.lo libopenjpeg_JPWL_la-jpwl.lo \ - libopenjpeg_JPWL_la-jpwl_lib.lo libopenjpeg_JPWL_la-rs.lo -libopenjpeg_JPWL_la_OBJECTS = $(am_libopenjpeg_JPWL_la_OBJECTS) -AM_V_lt = $(am__v_lt_$(V)) -am__v_lt_ = $(am__v_lt_$(AM_DEFAULT_VERBOSITY)) -am__v_lt_0 = --silent -libopenjpeg_JPWL_la_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ - $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ - $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) \ - $(libopenjpeg_JPWL_la_LDFLAGS) $(LDFLAGS) -o $@ -DEFAULT_INCLUDES = -I. -I$(top_builddir) -depcomp = $(SHELL) $(top_srcdir)/depcomp -am__depfiles_maybe = depfiles -am__mv = mv -f -COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ - $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ - $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \ - $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ - $(AM_CFLAGS) $(CFLAGS) -AM_V_CC = $(am__v_CC_$(V)) -am__v_CC_ = $(am__v_CC_$(AM_DEFAULT_VERBOSITY)) -am__v_CC_0 = @echo " CC " $@; -AM_V_at = $(am__v_at_$(V)) -am__v_at_ = $(am__v_at_$(AM_DEFAULT_VERBOSITY)) -am__v_at_0 = @ -CCLD = $(CC) -LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ - $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ - $(AM_LDFLAGS) $(LDFLAGS) -o $@ -AM_V_CCLD = $(am__v_CCLD_$(V)) -am__v_CCLD_ = $(am__v_CCLD_$(AM_DEFAULT_VERBOSITY)) -am__v_CCLD_0 = @echo " CCLD " $@; -AM_V_GEN = $(am__v_GEN_$(V)) -am__v_GEN_ = $(am__v_GEN_$(AM_DEFAULT_VERBOSITY)) -am__v_GEN_0 = @echo " GEN " $@; -SOURCES = $(libopenjpeg_JPWL_la_SOURCES) -DIST_SOURCES = $(libopenjpeg_JPWL_la_SOURCES) -ETAGS = etags -CTAGS = ctags -DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) -ACLOCAL = ${SHELL} /home/justincc/jc/it/g/graphics/jpeg/jpeg2000/openjpeg/src/openjpeg-1.5.0/missing --run aclocal-1.11 -AMTAR = ${SHELL} /home/justincc/jc/it/g/graphics/jpeg/jpeg2000/openjpeg/src/openjpeg-1.5.0/missing --run tar -AM_DEFAULT_VERBOSITY = 0 -AR = ar -AS = as -AUTOCONF = ${SHELL} /home/justincc/jc/it/g/graphics/jpeg/jpeg2000/openjpeg/src/openjpeg-1.5.0/missing --run autoconf -AUTOHEADER = ${SHELL} /home/justincc/jc/it/g/graphics/jpeg/jpeg2000/openjpeg/src/openjpeg-1.5.0/missing --run autoheader -AUTOMAKE = ${SHELL} /home/justincc/jc/it/g/graphics/jpeg/jpeg2000/openjpeg/src/openjpeg-1.5.0/missing --run automake-1.11 -AWK = mawk -CC = gcc -CCDEPMODE = depmode=gcc3 -CFLAGS = -g -O2 -Wno-unused-result -O3 -CPP = gcc -E -CPPFLAGS = -CYGPATH_W = echo -DEFS = -DHAVE_CONFIG_H -DEPDIR = .deps -DLLTOOL = dlltool -DSYMUTIL = -DUMPBIN = -ECHO_C = -ECHO_N = -n -ECHO_T = -EGREP = /bin/grep -E -EXEEXT = -FCGI_CFLAGS = -FCGI_LIBS = -FGREP = /bin/grep -F -GREP = /bin/grep -INSTALL = /usr/bin/install -c -INSTALL_DATA = ${INSTALL} -m 644 -INSTALL_PROGRAM = ${INSTALL} -INSTALL_SCRIPT = ${INSTALL} -INSTALL_STRIP_PROGRAM = $(install_sh) -c -s -LCMS1_CFLAGS = -LCMS1_LIBS = -LCMS2_CFLAGS = -LCMS2_LIBS = -LD = /usr/bin/ld -m elf_x86_64 -LDFLAGS = -LIBCURL_CFLAGS = -LIBCURL_LIBS = -LIBOBJS = -LIBS = -LIBTOOL = $(SHELL) $(top_builddir)/libtool -LIPO = -LN_S = ln -s -LTLIBOBJS = -MAJOR_NR = 1 -MAKEINFO = ${SHELL} /home/justincc/jc/it/g/graphics/jpeg/jpeg2000/openjpeg/src/openjpeg-1.5.0/missing --run makeinfo -MICRO_NR = 0 -MINOR_NR = 5 -MKDIR_P = /bin/mkdir -p -NM = /usr/bin/nm -B -NMEDIT = -OBJDUMP = objdump -OBJEXT = o -OTOOL = -OTOOL64 = -PACKAGE = openjpeg -PACKAGE_BUGREPORT = openjpeg@googlegroups.com -PACKAGE_NAME = OpenJPEG -PACKAGE_STRING = OpenJPEG 1.5.0 -PACKAGE_TARNAME = openjpeg -PACKAGE_URL = http://www.openjpeg.org -PACKAGE_VERSION = 1.5.0 -PATH_SEPARATOR = : -PKG_CONFIG = /usr/bin/pkg-config -PKG_CONFIG_LIBDIR = -PKG_CONFIG_PATH = -PNG_CFLAGS = -I/usr/include/libpng12 -PNG_LIBS = -lpng12 -lz -RANLIB = ranlib -SED = /bin/sed -SET_MAKE = -SHELL = /bin/bash -STRIP = strip -THREAD_CFLAGS = -THREAD_LIBS = -TIFF_CFLAGS = -I/usr/include -TIFF_LIBS = -L/usr/lib -ltiff -VERSION = 1.5.0 -Z_CFLAGS = -Z_LIBS = -abs_builddir = /home/justincc/jc/it/g/graphics/jpeg/jpeg2000/openjpeg/src/openjpeg-1.5.0/libopenjpeg/jpwl -abs_srcdir = /home/justincc/jc/it/g/graphics/jpeg/jpeg2000/openjpeg/src/openjpeg-1.5.0/libopenjpeg/jpwl -abs_top_builddir = /home/justincc/jc/it/g/graphics/jpeg/jpeg2000/openjpeg/src/openjpeg-1.5.0 -abs_top_srcdir = /home/justincc/jc/it/g/graphics/jpeg/jpeg2000/openjpeg/src/openjpeg-1.5.0 -ac_ct_CC = gcc -ac_ct_DUMPBIN = -am__include = include -am__leading_dot = . -am__quote = -am__tar = ${AMTAR} chof - "$$tardir" -am__untar = ${AMTAR} xf - -bindir = ${exec_prefix}/bin -build = x86_64-unknown-linux-gnu -build_alias = -build_cpu = x86_64 -build_os = linux-gnu -build_vendor = unknown -builddir = . -datadir = ${datarootdir} -datarootdir = ${prefix}/share -docdir = ${datarootdir}/doc/${PACKAGE_TARNAME} -dvidir = ${docdir} -exec_prefix = ${prefix} -host = x86_64-unknown-linux-gnu -host_alias = -host_cpu = x86_64 -host_os = linux-gnu -host_vendor = unknown -htmldir = ${docdir} -includedir = ${prefix}/include -infodir = ${datarootdir}/info -install_sh = ${SHELL} /home/justincc/jc/it/g/graphics/jpeg/jpeg2000/openjpeg/src/openjpeg-1.5.0/install-sh -libdir = ${exec_prefix}/lib -libexecdir = ${exec_prefix}/libexec -localedir = ${datarootdir}/locale -localstatedir = ${prefix}/var -lt_ECHO = echo -lt_version = 6:0:5 -mandir = ${datarootdir}/man -mkdir_p = /bin/mkdir -p -oldincludedir = /usr/include -opj_doxygen = doxygen -opj_have_doxygen = no -pdfdir = ${docdir} -pkgconfig_requires_private = Requires.private -prefix = /usr/local -program_transform_name = s,x,x, -psdir = ${docdir} -requirements = -sbindir = ${exec_prefix}/sbin -sharedstatedir = ${prefix}/com -srcdir = . -sysconfdir = ${prefix}/etc -target = x86_64-unknown-linux-gnu -target_alias = -target_cpu = x86_64 -target_os = linux-gnu -target_vendor = unknown -top_build_prefix = ../../ -top_builddir = ../.. -top_srcdir = ../.. -MAINTAINERCLEANFILES = Makefile.in -lib_LTLIBRARIES = libopenjpeg_JPWL.la -OPJ_SRC = \ -../bio.c \ -../cio.c \ -../dwt.c \ -../event.c \ -../image.c \ -../j2k.c \ -../j2k_lib.c \ -../jp2.c \ -../jpt.c \ -../mct.c \ -../mqc.c \ -../openjpeg.c \ -../pi.c \ -../raw.c \ -../t1.c \ -../t1_generate_luts.c \ -../t2.c \ -../tcd.c \ -../tgt.c \ -../cidx_manager.c \ -../phix_manager.c \ -../ppix_manager.c \ -../thix_manager.c \ -../tpix_manager.c - -libopenjpeg_JPWL_la_CPPFLAGS = \ --I. \ --I$(top_srcdir)/libopenjpeg \ --I$(top_builddir)/libopenjpeg \ --I$(top_srcdir)/libopenjpeg/jpwl \ --I$(top_builddir)/libopenjpeg/jpwl \ --DUSE_JPWL - -libopenjpeg_JPWL_la_CFLAGS = -libopenjpeg_JPWL_la_LIBADD = -lm -libopenjpeg_JPWL_la_LDFLAGS = -no-undefined -version-info 6:0:5 -libopenjpeg_JPWL_la_SOURCES = \ -$(OPJ_SRC) \ -crc.c \ -jpwl.c \ -jpwl_lib.c \ -rs.c \ -crc.h \ -jpwl.h \ -rs.h - -solist = $(foreach f, $(dll) $(so), echo -e ' $(SO_PREFIX)\t$(base)/$(f)' ;) -get_tok = $(shell grep -E "^$(1)=" $(lib_LTLIBRARIES) | cut -d "'" -f 2) -base = $(call get_tok,libdir) -so = $(call get_tok,library_names) -a = $(call get_tok,old_library) -SO_PREFIX = (SO) -#SO_PREFIX = (DY) -#SO_PREFIX = (DLL) -dll = -#dll = -#dll = $(call get_tok,dlname) -all: all-am - -.SUFFIXES: -.SUFFIXES: .c .lo .o .obj -$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) - @for dep in $?; do \ - case '$(am__configure_deps)' in \ - *$$dep*) \ - ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ - && { if test -f $@; then exit 0; else break; fi; }; \ - exit 1;; \ - esac; \ - done; \ - echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign libopenjpeg/jpwl/Makefile'; \ - $(am__cd) $(top_srcdir) && \ - $(AUTOMAKE) --foreign libopenjpeg/jpwl/Makefile -.PRECIOUS: Makefile -Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status - @case '$?' in \ - *config.status*) \ - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ - *) \ - echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ - cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ - esac; - -$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh - -$(top_srcdir)/configure: $(am__configure_deps) - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh -$(ACLOCAL_M4): $(am__aclocal_m4_deps) - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh -$(am__aclocal_m4_deps): -install-libLTLIBRARIES: $(lib_LTLIBRARIES) - @$(NORMAL_INSTALL) - test -z "$(libdir)" || $(MKDIR_P) "$(DESTDIR)$(libdir)" - @list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \ - list2=; for p in $$list; do \ - if test -f $$p; then \ - list2="$$list2 $$p"; \ - else :; fi; \ - done; \ - test -z "$$list2" || { \ - echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(libdir)'"; \ - $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(libdir)"; \ - } - -uninstall-libLTLIBRARIES: - @$(NORMAL_UNINSTALL) - @list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \ - for p in $$list; do \ - $(am__strip_dir) \ - echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f '$(DESTDIR)$(libdir)/$$f'"; \ - $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f "$(DESTDIR)$(libdir)/$$f"; \ - done - -clean-libLTLIBRARIES: - -test -z "$(lib_LTLIBRARIES)" || rm -f $(lib_LTLIBRARIES) - @list='$(lib_LTLIBRARIES)'; for p in $$list; do \ - dir="`echo $$p | sed -e 's|/[^/]*$$||'`"; \ - test "$$dir" != "$$p" || dir=.; \ - echo "rm -f \"$${dir}/so_locations\""; \ - rm -f "$${dir}/so_locations"; \ - done -libopenjpeg_JPWL.la: $(libopenjpeg_JPWL_la_OBJECTS) $(libopenjpeg_JPWL_la_DEPENDENCIES) - $(AM_V_CCLD)$(libopenjpeg_JPWL_la_LINK) -rpath $(libdir) $(libopenjpeg_JPWL_la_OBJECTS) $(libopenjpeg_JPWL_la_LIBADD) $(LIBS) - -mostlyclean-compile: - -rm -f *.$(OBJEXT) - -distclean-compile: - -rm -f *.tab.c - -include ./$(DEPDIR)/libopenjpeg_JPWL_la-bio.Plo -include ./$(DEPDIR)/libopenjpeg_JPWL_la-cidx_manager.Plo -include ./$(DEPDIR)/libopenjpeg_JPWL_la-cio.Plo -include ./$(DEPDIR)/libopenjpeg_JPWL_la-crc.Plo -include ./$(DEPDIR)/libopenjpeg_JPWL_la-dwt.Plo -include ./$(DEPDIR)/libopenjpeg_JPWL_la-event.Plo -include ./$(DEPDIR)/libopenjpeg_JPWL_la-image.Plo -include ./$(DEPDIR)/libopenjpeg_JPWL_la-j2k.Plo -include ./$(DEPDIR)/libopenjpeg_JPWL_la-j2k_lib.Plo -include ./$(DEPDIR)/libopenjpeg_JPWL_la-jp2.Plo -include ./$(DEPDIR)/libopenjpeg_JPWL_la-jpt.Plo -include ./$(DEPDIR)/libopenjpeg_JPWL_la-jpwl.Plo -include ./$(DEPDIR)/libopenjpeg_JPWL_la-jpwl_lib.Plo -include ./$(DEPDIR)/libopenjpeg_JPWL_la-mct.Plo -include ./$(DEPDIR)/libopenjpeg_JPWL_la-mqc.Plo -include ./$(DEPDIR)/libopenjpeg_JPWL_la-openjpeg.Plo -include ./$(DEPDIR)/libopenjpeg_JPWL_la-phix_manager.Plo -include ./$(DEPDIR)/libopenjpeg_JPWL_la-pi.Plo -include ./$(DEPDIR)/libopenjpeg_JPWL_la-ppix_manager.Plo -include ./$(DEPDIR)/libopenjpeg_JPWL_la-raw.Plo -include ./$(DEPDIR)/libopenjpeg_JPWL_la-rs.Plo -include ./$(DEPDIR)/libopenjpeg_JPWL_la-t1.Plo -include ./$(DEPDIR)/libopenjpeg_JPWL_la-t1_generate_luts.Plo -include ./$(DEPDIR)/libopenjpeg_JPWL_la-t2.Plo -include ./$(DEPDIR)/libopenjpeg_JPWL_la-tcd.Plo -include ./$(DEPDIR)/libopenjpeg_JPWL_la-tgt.Plo -include ./$(DEPDIR)/libopenjpeg_JPWL_la-thix_manager.Plo -include ./$(DEPDIR)/libopenjpeg_JPWL_la-tpix_manager.Plo - -.c.o: - $(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< - $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po -# $(AM_V_CC) \ -# source='$<' object='$@' libtool=no \ -# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ -# $(COMPILE) -c $< - -.c.obj: - $(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` - $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po -# $(AM_V_CC) \ -# source='$<' object='$@' libtool=no \ -# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ -# $(COMPILE) -c `$(CYGPATH_W) '$<'` - -.c.lo: - $(AM_V_CC)$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< - $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo -# $(AM_V_CC) \ -# source='$<' object='$@' libtool=yes \ -# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ -# $(LTCOMPILE) -c -o $@ $< - -libopenjpeg_JPWL_la-bio.lo: ../bio.c - $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -MT libopenjpeg_JPWL_la-bio.lo -MD -MP -MF $(DEPDIR)/libopenjpeg_JPWL_la-bio.Tpo -c -o libopenjpeg_JPWL_la-bio.lo `test -f '../bio.c' || echo '$(srcdir)/'`../bio.c - $(AM_V_at)$(am__mv) $(DEPDIR)/libopenjpeg_JPWL_la-bio.Tpo $(DEPDIR)/libopenjpeg_JPWL_la-bio.Plo -# $(AM_V_CC) \ -# source='../bio.c' object='libopenjpeg_JPWL_la-bio.lo' libtool=yes \ -# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ -# $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -c -o libopenjpeg_JPWL_la-bio.lo `test -f '../bio.c' || echo '$(srcdir)/'`../bio.c - -libopenjpeg_JPWL_la-cio.lo: ../cio.c - $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -MT libopenjpeg_JPWL_la-cio.lo -MD -MP -MF $(DEPDIR)/libopenjpeg_JPWL_la-cio.Tpo -c -o libopenjpeg_JPWL_la-cio.lo `test -f '../cio.c' || echo '$(srcdir)/'`../cio.c - $(AM_V_at)$(am__mv) $(DEPDIR)/libopenjpeg_JPWL_la-cio.Tpo $(DEPDIR)/libopenjpeg_JPWL_la-cio.Plo -# $(AM_V_CC) \ -# source='../cio.c' object='libopenjpeg_JPWL_la-cio.lo' libtool=yes \ -# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ -# $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -c -o libopenjpeg_JPWL_la-cio.lo `test -f '../cio.c' || echo '$(srcdir)/'`../cio.c - -libopenjpeg_JPWL_la-dwt.lo: ../dwt.c - $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -MT libopenjpeg_JPWL_la-dwt.lo -MD -MP -MF $(DEPDIR)/libopenjpeg_JPWL_la-dwt.Tpo -c -o libopenjpeg_JPWL_la-dwt.lo `test -f '../dwt.c' || echo '$(srcdir)/'`../dwt.c - $(AM_V_at)$(am__mv) $(DEPDIR)/libopenjpeg_JPWL_la-dwt.Tpo $(DEPDIR)/libopenjpeg_JPWL_la-dwt.Plo -# $(AM_V_CC) \ -# source='../dwt.c' object='libopenjpeg_JPWL_la-dwt.lo' libtool=yes \ -# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ -# $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -c -o libopenjpeg_JPWL_la-dwt.lo `test -f '../dwt.c' || echo '$(srcdir)/'`../dwt.c - -libopenjpeg_JPWL_la-event.lo: ../event.c - $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -MT libopenjpeg_JPWL_la-event.lo -MD -MP -MF $(DEPDIR)/libopenjpeg_JPWL_la-event.Tpo -c -o libopenjpeg_JPWL_la-event.lo `test -f '../event.c' || echo '$(srcdir)/'`../event.c - $(AM_V_at)$(am__mv) $(DEPDIR)/libopenjpeg_JPWL_la-event.Tpo $(DEPDIR)/libopenjpeg_JPWL_la-event.Plo -# $(AM_V_CC) \ -# source='../event.c' object='libopenjpeg_JPWL_la-event.lo' libtool=yes \ -# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ -# $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -c -o libopenjpeg_JPWL_la-event.lo `test -f '../event.c' || echo '$(srcdir)/'`../event.c - -libopenjpeg_JPWL_la-image.lo: ../image.c - $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -MT libopenjpeg_JPWL_la-image.lo -MD -MP -MF $(DEPDIR)/libopenjpeg_JPWL_la-image.Tpo -c -o libopenjpeg_JPWL_la-image.lo `test -f '../image.c' || echo '$(srcdir)/'`../image.c - $(AM_V_at)$(am__mv) $(DEPDIR)/libopenjpeg_JPWL_la-image.Tpo $(DEPDIR)/libopenjpeg_JPWL_la-image.Plo -# $(AM_V_CC) \ -# source='../image.c' object='libopenjpeg_JPWL_la-image.lo' libtool=yes \ -# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ -# $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -c -o libopenjpeg_JPWL_la-image.lo `test -f '../image.c' || echo '$(srcdir)/'`../image.c - -libopenjpeg_JPWL_la-j2k.lo: ../j2k.c - $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -MT libopenjpeg_JPWL_la-j2k.lo -MD -MP -MF $(DEPDIR)/libopenjpeg_JPWL_la-j2k.Tpo -c -o libopenjpeg_JPWL_la-j2k.lo `test -f '../j2k.c' || echo '$(srcdir)/'`../j2k.c - $(AM_V_at)$(am__mv) $(DEPDIR)/libopenjpeg_JPWL_la-j2k.Tpo $(DEPDIR)/libopenjpeg_JPWL_la-j2k.Plo -# $(AM_V_CC) \ -# source='../j2k.c' object='libopenjpeg_JPWL_la-j2k.lo' libtool=yes \ -# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ -# $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -c -o libopenjpeg_JPWL_la-j2k.lo `test -f '../j2k.c' || echo '$(srcdir)/'`../j2k.c - -libopenjpeg_JPWL_la-j2k_lib.lo: ../j2k_lib.c - $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -MT libopenjpeg_JPWL_la-j2k_lib.lo -MD -MP -MF $(DEPDIR)/libopenjpeg_JPWL_la-j2k_lib.Tpo -c -o libopenjpeg_JPWL_la-j2k_lib.lo `test -f '../j2k_lib.c' || echo '$(srcdir)/'`../j2k_lib.c - $(AM_V_at)$(am__mv) $(DEPDIR)/libopenjpeg_JPWL_la-j2k_lib.Tpo $(DEPDIR)/libopenjpeg_JPWL_la-j2k_lib.Plo -# $(AM_V_CC) \ -# source='../j2k_lib.c' object='libopenjpeg_JPWL_la-j2k_lib.lo' libtool=yes \ -# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ -# $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -c -o libopenjpeg_JPWL_la-j2k_lib.lo `test -f '../j2k_lib.c' || echo '$(srcdir)/'`../j2k_lib.c - -libopenjpeg_JPWL_la-jp2.lo: ../jp2.c - $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -MT libopenjpeg_JPWL_la-jp2.lo -MD -MP -MF $(DEPDIR)/libopenjpeg_JPWL_la-jp2.Tpo -c -o libopenjpeg_JPWL_la-jp2.lo `test -f '../jp2.c' || echo '$(srcdir)/'`../jp2.c - $(AM_V_at)$(am__mv) $(DEPDIR)/libopenjpeg_JPWL_la-jp2.Tpo $(DEPDIR)/libopenjpeg_JPWL_la-jp2.Plo -# $(AM_V_CC) \ -# source='../jp2.c' object='libopenjpeg_JPWL_la-jp2.lo' libtool=yes \ -# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ -# $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -c -o libopenjpeg_JPWL_la-jp2.lo `test -f '../jp2.c' || echo '$(srcdir)/'`../jp2.c - -libopenjpeg_JPWL_la-jpt.lo: ../jpt.c - $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -MT libopenjpeg_JPWL_la-jpt.lo -MD -MP -MF $(DEPDIR)/libopenjpeg_JPWL_la-jpt.Tpo -c -o libopenjpeg_JPWL_la-jpt.lo `test -f '../jpt.c' || echo '$(srcdir)/'`../jpt.c - $(AM_V_at)$(am__mv) $(DEPDIR)/libopenjpeg_JPWL_la-jpt.Tpo $(DEPDIR)/libopenjpeg_JPWL_la-jpt.Plo -# $(AM_V_CC) \ -# source='../jpt.c' object='libopenjpeg_JPWL_la-jpt.lo' libtool=yes \ -# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ -# $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -c -o libopenjpeg_JPWL_la-jpt.lo `test -f '../jpt.c' || echo '$(srcdir)/'`../jpt.c - -libopenjpeg_JPWL_la-mct.lo: ../mct.c - $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -MT libopenjpeg_JPWL_la-mct.lo -MD -MP -MF $(DEPDIR)/libopenjpeg_JPWL_la-mct.Tpo -c -o libopenjpeg_JPWL_la-mct.lo `test -f '../mct.c' || echo '$(srcdir)/'`../mct.c - $(AM_V_at)$(am__mv) $(DEPDIR)/libopenjpeg_JPWL_la-mct.Tpo $(DEPDIR)/libopenjpeg_JPWL_la-mct.Plo -# $(AM_V_CC) \ -# source='../mct.c' object='libopenjpeg_JPWL_la-mct.lo' libtool=yes \ -# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ -# $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -c -o libopenjpeg_JPWL_la-mct.lo `test -f '../mct.c' || echo '$(srcdir)/'`../mct.c - -libopenjpeg_JPWL_la-mqc.lo: ../mqc.c - $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -MT libopenjpeg_JPWL_la-mqc.lo -MD -MP -MF $(DEPDIR)/libopenjpeg_JPWL_la-mqc.Tpo -c -o libopenjpeg_JPWL_la-mqc.lo `test -f '../mqc.c' || echo '$(srcdir)/'`../mqc.c - $(AM_V_at)$(am__mv) $(DEPDIR)/libopenjpeg_JPWL_la-mqc.Tpo $(DEPDIR)/libopenjpeg_JPWL_la-mqc.Plo -# $(AM_V_CC) \ -# source='../mqc.c' object='libopenjpeg_JPWL_la-mqc.lo' libtool=yes \ -# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ -# $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -c -o libopenjpeg_JPWL_la-mqc.lo `test -f '../mqc.c' || echo '$(srcdir)/'`../mqc.c - -libopenjpeg_JPWL_la-openjpeg.lo: ../openjpeg.c - $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -MT libopenjpeg_JPWL_la-openjpeg.lo -MD -MP -MF $(DEPDIR)/libopenjpeg_JPWL_la-openjpeg.Tpo -c -o libopenjpeg_JPWL_la-openjpeg.lo `test -f '../openjpeg.c' || echo '$(srcdir)/'`../openjpeg.c - $(AM_V_at)$(am__mv) $(DEPDIR)/libopenjpeg_JPWL_la-openjpeg.Tpo $(DEPDIR)/libopenjpeg_JPWL_la-openjpeg.Plo -# $(AM_V_CC) \ -# source='../openjpeg.c' object='libopenjpeg_JPWL_la-openjpeg.lo' libtool=yes \ -# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ -# $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -c -o libopenjpeg_JPWL_la-openjpeg.lo `test -f '../openjpeg.c' || echo '$(srcdir)/'`../openjpeg.c - -libopenjpeg_JPWL_la-pi.lo: ../pi.c - $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -MT libopenjpeg_JPWL_la-pi.lo -MD -MP -MF $(DEPDIR)/libopenjpeg_JPWL_la-pi.Tpo -c -o libopenjpeg_JPWL_la-pi.lo `test -f '../pi.c' || echo '$(srcdir)/'`../pi.c - $(AM_V_at)$(am__mv) $(DEPDIR)/libopenjpeg_JPWL_la-pi.Tpo $(DEPDIR)/libopenjpeg_JPWL_la-pi.Plo -# $(AM_V_CC) \ -# source='../pi.c' object='libopenjpeg_JPWL_la-pi.lo' libtool=yes \ -# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ -# $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -c -o libopenjpeg_JPWL_la-pi.lo `test -f '../pi.c' || echo '$(srcdir)/'`../pi.c - -libopenjpeg_JPWL_la-raw.lo: ../raw.c - $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -MT libopenjpeg_JPWL_la-raw.lo -MD -MP -MF $(DEPDIR)/libopenjpeg_JPWL_la-raw.Tpo -c -o libopenjpeg_JPWL_la-raw.lo `test -f '../raw.c' || echo '$(srcdir)/'`../raw.c - $(AM_V_at)$(am__mv) $(DEPDIR)/libopenjpeg_JPWL_la-raw.Tpo $(DEPDIR)/libopenjpeg_JPWL_la-raw.Plo -# $(AM_V_CC) \ -# source='../raw.c' object='libopenjpeg_JPWL_la-raw.lo' libtool=yes \ -# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ -# $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -c -o libopenjpeg_JPWL_la-raw.lo `test -f '../raw.c' || echo '$(srcdir)/'`../raw.c - -libopenjpeg_JPWL_la-t1.lo: ../t1.c - $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -MT libopenjpeg_JPWL_la-t1.lo -MD -MP -MF $(DEPDIR)/libopenjpeg_JPWL_la-t1.Tpo -c -o libopenjpeg_JPWL_la-t1.lo `test -f '../t1.c' || echo '$(srcdir)/'`../t1.c - $(AM_V_at)$(am__mv) $(DEPDIR)/libopenjpeg_JPWL_la-t1.Tpo $(DEPDIR)/libopenjpeg_JPWL_la-t1.Plo -# $(AM_V_CC) \ -# source='../t1.c' object='libopenjpeg_JPWL_la-t1.lo' libtool=yes \ -# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ -# $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -c -o libopenjpeg_JPWL_la-t1.lo `test -f '../t1.c' || echo '$(srcdir)/'`../t1.c - -libopenjpeg_JPWL_la-t1_generate_luts.lo: ../t1_generate_luts.c - $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -MT libopenjpeg_JPWL_la-t1_generate_luts.lo -MD -MP -MF $(DEPDIR)/libopenjpeg_JPWL_la-t1_generate_luts.Tpo -c -o libopenjpeg_JPWL_la-t1_generate_luts.lo `test -f '../t1_generate_luts.c' || echo '$(srcdir)/'`../t1_generate_luts.c - $(AM_V_at)$(am__mv) $(DEPDIR)/libopenjpeg_JPWL_la-t1_generate_luts.Tpo $(DEPDIR)/libopenjpeg_JPWL_la-t1_generate_luts.Plo -# $(AM_V_CC) \ -# source='../t1_generate_luts.c' object='libopenjpeg_JPWL_la-t1_generate_luts.lo' libtool=yes \ -# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ -# $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -c -o libopenjpeg_JPWL_la-t1_generate_luts.lo `test -f '../t1_generate_luts.c' || echo '$(srcdir)/'`../t1_generate_luts.c - -libopenjpeg_JPWL_la-t2.lo: ../t2.c - $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -MT libopenjpeg_JPWL_la-t2.lo -MD -MP -MF $(DEPDIR)/libopenjpeg_JPWL_la-t2.Tpo -c -o libopenjpeg_JPWL_la-t2.lo `test -f '../t2.c' || echo '$(srcdir)/'`../t2.c - $(AM_V_at)$(am__mv) $(DEPDIR)/libopenjpeg_JPWL_la-t2.Tpo $(DEPDIR)/libopenjpeg_JPWL_la-t2.Plo -# $(AM_V_CC) \ -# source='../t2.c' object='libopenjpeg_JPWL_la-t2.lo' libtool=yes \ -# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ -# $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -c -o libopenjpeg_JPWL_la-t2.lo `test -f '../t2.c' || echo '$(srcdir)/'`../t2.c - -libopenjpeg_JPWL_la-tcd.lo: ../tcd.c - $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -MT libopenjpeg_JPWL_la-tcd.lo -MD -MP -MF $(DEPDIR)/libopenjpeg_JPWL_la-tcd.Tpo -c -o libopenjpeg_JPWL_la-tcd.lo `test -f '../tcd.c' || echo '$(srcdir)/'`../tcd.c - $(AM_V_at)$(am__mv) $(DEPDIR)/libopenjpeg_JPWL_la-tcd.Tpo $(DEPDIR)/libopenjpeg_JPWL_la-tcd.Plo -# $(AM_V_CC) \ -# source='../tcd.c' object='libopenjpeg_JPWL_la-tcd.lo' libtool=yes \ -# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ -# $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -c -o libopenjpeg_JPWL_la-tcd.lo `test -f '../tcd.c' || echo '$(srcdir)/'`../tcd.c - -libopenjpeg_JPWL_la-tgt.lo: ../tgt.c - $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -MT libopenjpeg_JPWL_la-tgt.lo -MD -MP -MF $(DEPDIR)/libopenjpeg_JPWL_la-tgt.Tpo -c -o libopenjpeg_JPWL_la-tgt.lo `test -f '../tgt.c' || echo '$(srcdir)/'`../tgt.c - $(AM_V_at)$(am__mv) $(DEPDIR)/libopenjpeg_JPWL_la-tgt.Tpo $(DEPDIR)/libopenjpeg_JPWL_la-tgt.Plo -# $(AM_V_CC) \ -# source='../tgt.c' object='libopenjpeg_JPWL_la-tgt.lo' libtool=yes \ -# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ -# $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -c -o libopenjpeg_JPWL_la-tgt.lo `test -f '../tgt.c' || echo '$(srcdir)/'`../tgt.c - -libopenjpeg_JPWL_la-cidx_manager.lo: ../cidx_manager.c - $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -MT libopenjpeg_JPWL_la-cidx_manager.lo -MD -MP -MF $(DEPDIR)/libopenjpeg_JPWL_la-cidx_manager.Tpo -c -o libopenjpeg_JPWL_la-cidx_manager.lo `test -f '../cidx_manager.c' || echo '$(srcdir)/'`../cidx_manager.c - $(AM_V_at)$(am__mv) $(DEPDIR)/libopenjpeg_JPWL_la-cidx_manager.Tpo $(DEPDIR)/libopenjpeg_JPWL_la-cidx_manager.Plo -# $(AM_V_CC) \ -# source='../cidx_manager.c' object='libopenjpeg_JPWL_la-cidx_manager.lo' libtool=yes \ -# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ -# $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -c -o libopenjpeg_JPWL_la-cidx_manager.lo `test -f '../cidx_manager.c' || echo '$(srcdir)/'`../cidx_manager.c - -libopenjpeg_JPWL_la-phix_manager.lo: ../phix_manager.c - $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -MT libopenjpeg_JPWL_la-phix_manager.lo -MD -MP -MF $(DEPDIR)/libopenjpeg_JPWL_la-phix_manager.Tpo -c -o libopenjpeg_JPWL_la-phix_manager.lo `test -f '../phix_manager.c' || echo '$(srcdir)/'`../phix_manager.c - $(AM_V_at)$(am__mv) $(DEPDIR)/libopenjpeg_JPWL_la-phix_manager.Tpo $(DEPDIR)/libopenjpeg_JPWL_la-phix_manager.Plo -# $(AM_V_CC) \ -# source='../phix_manager.c' object='libopenjpeg_JPWL_la-phix_manager.lo' libtool=yes \ -# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ -# $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -c -o libopenjpeg_JPWL_la-phix_manager.lo `test -f '../phix_manager.c' || echo '$(srcdir)/'`../phix_manager.c - -libopenjpeg_JPWL_la-ppix_manager.lo: ../ppix_manager.c - $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -MT libopenjpeg_JPWL_la-ppix_manager.lo -MD -MP -MF $(DEPDIR)/libopenjpeg_JPWL_la-ppix_manager.Tpo -c -o libopenjpeg_JPWL_la-ppix_manager.lo `test -f '../ppix_manager.c' || echo '$(srcdir)/'`../ppix_manager.c - $(AM_V_at)$(am__mv) $(DEPDIR)/libopenjpeg_JPWL_la-ppix_manager.Tpo $(DEPDIR)/libopenjpeg_JPWL_la-ppix_manager.Plo -# $(AM_V_CC) \ -# source='../ppix_manager.c' object='libopenjpeg_JPWL_la-ppix_manager.lo' libtool=yes \ -# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ -# $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -c -o libopenjpeg_JPWL_la-ppix_manager.lo `test -f '../ppix_manager.c' || echo '$(srcdir)/'`../ppix_manager.c - -libopenjpeg_JPWL_la-thix_manager.lo: ../thix_manager.c - $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -MT libopenjpeg_JPWL_la-thix_manager.lo -MD -MP -MF $(DEPDIR)/libopenjpeg_JPWL_la-thix_manager.Tpo -c -o libopenjpeg_JPWL_la-thix_manager.lo `test -f '../thix_manager.c' || echo '$(srcdir)/'`../thix_manager.c - $(AM_V_at)$(am__mv) $(DEPDIR)/libopenjpeg_JPWL_la-thix_manager.Tpo $(DEPDIR)/libopenjpeg_JPWL_la-thix_manager.Plo -# $(AM_V_CC) \ -# source='../thix_manager.c' object='libopenjpeg_JPWL_la-thix_manager.lo' libtool=yes \ -# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ -# $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -c -o libopenjpeg_JPWL_la-thix_manager.lo `test -f '../thix_manager.c' || echo '$(srcdir)/'`../thix_manager.c - -libopenjpeg_JPWL_la-tpix_manager.lo: ../tpix_manager.c - $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -MT libopenjpeg_JPWL_la-tpix_manager.lo -MD -MP -MF $(DEPDIR)/libopenjpeg_JPWL_la-tpix_manager.Tpo -c -o libopenjpeg_JPWL_la-tpix_manager.lo `test -f '../tpix_manager.c' || echo '$(srcdir)/'`../tpix_manager.c - $(AM_V_at)$(am__mv) $(DEPDIR)/libopenjpeg_JPWL_la-tpix_manager.Tpo $(DEPDIR)/libopenjpeg_JPWL_la-tpix_manager.Plo -# $(AM_V_CC) \ -# source='../tpix_manager.c' object='libopenjpeg_JPWL_la-tpix_manager.lo' libtool=yes \ -# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ -# $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -c -o libopenjpeg_JPWL_la-tpix_manager.lo `test -f '../tpix_manager.c' || echo '$(srcdir)/'`../tpix_manager.c - -libopenjpeg_JPWL_la-crc.lo: crc.c - $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -MT libopenjpeg_JPWL_la-crc.lo -MD -MP -MF $(DEPDIR)/libopenjpeg_JPWL_la-crc.Tpo -c -o libopenjpeg_JPWL_la-crc.lo `test -f 'crc.c' || echo '$(srcdir)/'`crc.c - $(AM_V_at)$(am__mv) $(DEPDIR)/libopenjpeg_JPWL_la-crc.Tpo $(DEPDIR)/libopenjpeg_JPWL_la-crc.Plo -# $(AM_V_CC) \ -# source='crc.c' object='libopenjpeg_JPWL_la-crc.lo' libtool=yes \ -# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ -# $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -c -o libopenjpeg_JPWL_la-crc.lo `test -f 'crc.c' || echo '$(srcdir)/'`crc.c - -libopenjpeg_JPWL_la-jpwl.lo: jpwl.c - $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -MT libopenjpeg_JPWL_la-jpwl.lo -MD -MP -MF $(DEPDIR)/libopenjpeg_JPWL_la-jpwl.Tpo -c -o libopenjpeg_JPWL_la-jpwl.lo `test -f 'jpwl.c' || echo '$(srcdir)/'`jpwl.c - $(AM_V_at)$(am__mv) $(DEPDIR)/libopenjpeg_JPWL_la-jpwl.Tpo $(DEPDIR)/libopenjpeg_JPWL_la-jpwl.Plo -# $(AM_V_CC) \ -# source='jpwl.c' object='libopenjpeg_JPWL_la-jpwl.lo' libtool=yes \ -# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ -# $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -c -o libopenjpeg_JPWL_la-jpwl.lo `test -f 'jpwl.c' || echo '$(srcdir)/'`jpwl.c - -libopenjpeg_JPWL_la-jpwl_lib.lo: jpwl_lib.c - $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -MT libopenjpeg_JPWL_la-jpwl_lib.lo -MD -MP -MF $(DEPDIR)/libopenjpeg_JPWL_la-jpwl_lib.Tpo -c -o libopenjpeg_JPWL_la-jpwl_lib.lo `test -f 'jpwl_lib.c' || echo '$(srcdir)/'`jpwl_lib.c - $(AM_V_at)$(am__mv) $(DEPDIR)/libopenjpeg_JPWL_la-jpwl_lib.Tpo $(DEPDIR)/libopenjpeg_JPWL_la-jpwl_lib.Plo -# $(AM_V_CC) \ -# source='jpwl_lib.c' object='libopenjpeg_JPWL_la-jpwl_lib.lo' libtool=yes \ -# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ -# $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -c -o libopenjpeg_JPWL_la-jpwl_lib.lo `test -f 'jpwl_lib.c' || echo '$(srcdir)/'`jpwl_lib.c - -libopenjpeg_JPWL_la-rs.lo: rs.c - $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -MT libopenjpeg_JPWL_la-rs.lo -MD -MP -MF $(DEPDIR)/libopenjpeg_JPWL_la-rs.Tpo -c -o libopenjpeg_JPWL_la-rs.lo `test -f 'rs.c' || echo '$(srcdir)/'`rs.c - $(AM_V_at)$(am__mv) $(DEPDIR)/libopenjpeg_JPWL_la-rs.Tpo $(DEPDIR)/libopenjpeg_JPWL_la-rs.Plo -# $(AM_V_CC) \ -# source='rs.c' object='libopenjpeg_JPWL_la-rs.lo' libtool=yes \ -# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ -# $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -c -o libopenjpeg_JPWL_la-rs.lo `test -f 'rs.c' || echo '$(srcdir)/'`rs.c - -mostlyclean-libtool: - -rm -f *.lo - -clean-libtool: - -rm -rf .libs _libs - -ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ - END { if (nonempty) { for (i in files) print i; }; }'`; \ - mkid -fID $$unique -tags: TAGS - -TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - set x; \ - here=`pwd`; \ - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ - END { if (nonempty) { for (i in files) print i; }; }'`; \ - shift; \ - if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ - test -n "$$unique" || unique=$$empty_fix; \ - if test $$# -gt 0; then \ - $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ - "$$@" $$unique; \ - else \ - $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ - $$unique; \ - fi; \ - fi -ctags: CTAGS -CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ - END { if (nonempty) { for (i in files) print i; }; }'`; \ - test -z "$(CTAGS_ARGS)$$unique" \ - || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ - $$unique - -GTAGS: - here=`$(am__cd) $(top_builddir) && pwd` \ - && $(am__cd) $(top_srcdir) \ - && gtags -i $(GTAGS_ARGS) "$$here" - -distclean-tags: - -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags - -distdir: $(DISTFILES) - @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ - topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ - list='$(DISTFILES)'; \ - dist_files=`for file in $$list; do echo $$file; done | \ - sed -e "s|^$$srcdirstrip/||;t" \ - -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ - case $$dist_files in \ - */*) $(MKDIR_P) `echo "$$dist_files" | \ - sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ - sort -u` ;; \ - esac; \ - for file in $$dist_files; do \ - if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ - if test -d $$d/$$file; then \ - dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ - if test -d "$(distdir)/$$file"; then \ - find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ - fi; \ - if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ - cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ - find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ - fi; \ - cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ - else \ - test -f "$(distdir)/$$file" \ - || cp -p $$d/$$file "$(distdir)/$$file" \ - || exit 1; \ - fi; \ - done -check-am: all-am -check: check-am -all-am: Makefile $(LTLIBRARIES) -installdirs: - for dir in "$(DESTDIR)$(libdir)"; do \ - test -z "$$dir" || $(MKDIR_P) "$$dir"; \ - done -install: install-am -install-exec: install-exec-am -install-data: install-data-am -uninstall: uninstall-am - -install-am: all-am - @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am - -installcheck: installcheck-am -install-strip: - $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ - install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ - `test -z '$(STRIP)' || \ - echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install -mostlyclean-generic: - -clean-generic: - -distclean-generic: - -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) - -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) - -maintainer-clean-generic: - @echo "This command is intended for maintainers to use" - @echo "it deletes files that may require special tools to rebuild." - -test -z "$(MAINTAINERCLEANFILES)" || rm -f $(MAINTAINERCLEANFILES) -clean: clean-am - -clean-am: clean-generic clean-libLTLIBRARIES clean-libtool \ - mostlyclean-am - -distclean: distclean-am - -rm -rf ./$(DEPDIR) - -rm -f Makefile -distclean-am: clean-am distclean-compile distclean-generic \ - distclean-tags - -dvi: dvi-am - -dvi-am: - -html: html-am - -html-am: - -info: info-am - -info-am: - -install-data-am: - @$(NORMAL_INSTALL) - $(MAKE) $(AM_MAKEFLAGS) install-data-hook -install-dvi: install-dvi-am - -install-dvi-am: - -install-exec-am: install-libLTLIBRARIES - -install-html: install-html-am - -install-html-am: - -install-info: install-info-am - -install-info-am: - -install-man: - -install-pdf: install-pdf-am - -install-pdf-am: - -install-ps: install-ps-am - -install-ps-am: - -installcheck-am: - -maintainer-clean: maintainer-clean-am - -rm -rf ./$(DEPDIR) - -rm -f Makefile -maintainer-clean-am: distclean-am maintainer-clean-generic - -mostlyclean: mostlyclean-am - -mostlyclean-am: mostlyclean-compile mostlyclean-generic \ - mostlyclean-libtool - -pdf: pdf-am - -pdf-am: - -ps: ps-am - -ps-am: - -uninstall-am: uninstall-libLTLIBRARIES - -.MAKE: install-am install-data-am install-strip - -.PHONY: CTAGS GTAGS all all-am check check-am clean clean-generic \ - clean-libLTLIBRARIES clean-libtool ctags distclean \ - distclean-compile distclean-generic distclean-libtool \ - distclean-tags distdir dvi dvi-am html html-am info info-am \ - install install-am install-data install-data-am \ - install-data-hook install-dvi install-dvi-am install-exec \ - install-exec-am install-html install-html-am install-info \ - install-info-am install-libLTLIBRARIES install-man install-pdf \ - install-pdf-am install-ps install-ps-am install-strip \ - installcheck installcheck-am installdirs maintainer-clean \ - maintainer-clean-generic mostlyclean mostlyclean-compile \ - mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ - tags uninstall uninstall-am uninstall-libLTLIBRARIES - - -install-data-hook: - @echo -e " (LA)\t$(libdir)/libopenjpeg_JPWL.la" >> $(top_builddir)/report.txt - @( $(call solist) ) >> $(top_builddir)/report.txt - @echo -e " (A)\t$(base)/$(a)" >> $(top_builddir)/report.txt - -# Tell versions [3.59,3.63) of GNU make to not export all variables. -# Otherwise a system limit (for SysV at least) may be exceeded. -.NOEXPORT: diff --git a/openjpeg-dotnet/libopenjpeg/jpwl/Makefile.am b/openjpeg-dotnet/libopenjpeg/jpwl/Makefile.am deleted file mode 100644 index f1eda310..00000000 --- a/openjpeg-dotnet/libopenjpeg/jpwl/Makefile.am +++ /dev/null @@ -1,77 +0,0 @@ -MAINTAINERCLEANFILES = Makefile.in - -lib_LTLIBRARIES = libopenjpeg_JPWL.la - -OPJ_SRC = \ -../bio.c \ -../cio.c \ -../dwt.c \ -../event.c \ -../image.c \ -../j2k.c \ -../j2k_lib.c \ -../jp2.c \ -../jpt.c \ -../mct.c \ -../mqc.c \ -../openjpeg.c \ -../pi.c \ -../raw.c \ -../t1.c \ -../t1_generate_luts.c \ -../t2.c \ -../tcd.c \ -../tgt.c \ -../cidx_manager.c \ -../phix_manager.c \ -../ppix_manager.c \ -../thix_manager.c \ -../tpix_manager.c - -libopenjpeg_JPWL_la_CPPFLAGS = \ --I. \ --I$(top_srcdir)/libopenjpeg \ --I$(top_builddir)/libopenjpeg \ --I$(top_srcdir)/libopenjpeg/jpwl \ --I$(top_builddir)/libopenjpeg/jpwl \ --DUSE_JPWL -libopenjpeg_JPWL_la_CFLAGS = -libopenjpeg_JPWL_la_LIBADD = -lm -libopenjpeg_JPWL_la_LDFLAGS = -no-undefined -version-info @lt_version@ -libopenjpeg_JPWL_la_SOURCES = \ -$(OPJ_SRC) \ -crc.c \ -jpwl.c \ -jpwl_lib.c \ -rs.c \ -crc.h \ -jpwl.h \ -rs.h - -install-data-hook: - @echo -e " (LA)\t$(libdir)/libopenjpeg_JPWL.la" >> $(top_builddir)/report.txt -if BUILD_SHARED - @( $(call solist) ) >> $(top_builddir)/report.txt -endif -if BUILD_STATIC - @echo -e " (A)\t$(base)/$(a)" >> $(top_builddir)/report.txt -endif - -solist = $(foreach f, $(dll) $(so), echo -e ' $(SO_PREFIX)\t$(base)/$(f)' ;) -get_tok = $(shell grep -E "^$(1)=" $(lib_LTLIBRARIES) | cut -d "'" -f 2) -base = $(call get_tok,libdir) -so = $(call get_tok,library_names) -a = $(call get_tok,old_library) - -if HAVE_WIN32 -SO_PREFIX = (DLL) -dll = $(call get_tok,dlname) -else -if HAVE_DARWIN -SO_PREFIX = (DY) -dll = -else -SO_PREFIX = (SO) -dll = -endif -endif diff --git a/openjpeg-dotnet/libopenjpeg/jpwl/Makefile.in b/openjpeg-dotnet/libopenjpeg/jpwl/Makefile.in deleted file mode 100644 index ace28875..00000000 --- a/openjpeg-dotnet/libopenjpeg/jpwl/Makefile.in +++ /dev/null @@ -1,908 +0,0 @@ -# Makefile.in generated by automake 1.11.1 from Makefile.am. -# @configure_input@ - -# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, -# 2003, 2004, 2005, 2006, 2007, 2008, 2009 Free Software Foundation, -# Inc. -# This Makefile.in is free software; the Free Software Foundation -# gives unlimited permission to copy and/or distribute it, -# with or without modifications, as long as this notice is preserved. - -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY, to the extent permitted by law; without -# even the implied warranty of MERCHANTABILITY or FITNESS FOR A -# PARTICULAR PURPOSE. - -@SET_MAKE@ - -VPATH = @srcdir@ -pkgdatadir = $(datadir)/@PACKAGE@ -pkgincludedir = $(includedir)/@PACKAGE@ -pkglibdir = $(libdir)/@PACKAGE@ -pkglibexecdir = $(libexecdir)/@PACKAGE@ -am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd -install_sh_DATA = $(install_sh) -c -m 644 -install_sh_PROGRAM = $(install_sh) -c -install_sh_SCRIPT = $(install_sh) -c -INSTALL_HEADER = $(INSTALL_DATA) -transform = $(program_transform_name) -NORMAL_INSTALL = : -PRE_INSTALL = : -POST_INSTALL = : -NORMAL_UNINSTALL = : -PRE_UNINSTALL = : -POST_UNINSTALL = : -build_triplet = @build@ -host_triplet = @host@ -target_triplet = @target@ -subdir = libopenjpeg/jpwl -DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in -ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/libtool.m4 \ - $(top_srcdir)/m4/ltoptions.m4 $(top_srcdir)/m4/ltsugar.m4 \ - $(top_srcdir)/m4/ltversion.m4 $(top_srcdir)/m4/lt~obsolete.m4 \ - $(top_srcdir)/m4/opj_check_lib.m4 \ - $(top_srcdir)/m4/opj_compiler_flag.m4 \ - $(top_srcdir)/m4/opj_doxygen.m4 $(top_srcdir)/m4/pkg.m4 \ - $(top_srcdir)/configure.ac -am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ - $(ACLOCAL_M4) -mkinstalldirs = $(install_sh) -d -CONFIG_HEADER = $(top_builddir)/opj_config.h -CONFIG_CLEAN_FILES = -CONFIG_CLEAN_VPATH_FILES = -am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; -am__vpath_adj = case $$p in \ - $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ - *) f=$$p;; \ - esac; -am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; -am__install_max = 40 -am__nobase_strip_setup = \ - srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` -am__nobase_strip = \ - for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" -am__nobase_list = $(am__nobase_strip_setup); \ - for p in $$list; do echo "$$p $$p"; done | \ - sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ - $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ - if (++n[$$2] == $(am__install_max)) \ - { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ - END { for (dir in files) print dir, files[dir] }' -am__base_list = \ - sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ - sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' -am__installdirs = "$(DESTDIR)$(libdir)" -LTLIBRARIES = $(lib_LTLIBRARIES) -libopenjpeg_JPWL_la_DEPENDENCIES = -am__objects_1 = libopenjpeg_JPWL_la-bio.lo libopenjpeg_JPWL_la-cio.lo \ - libopenjpeg_JPWL_la-dwt.lo libopenjpeg_JPWL_la-event.lo \ - libopenjpeg_JPWL_la-image.lo libopenjpeg_JPWL_la-j2k.lo \ - libopenjpeg_JPWL_la-j2k_lib.lo libopenjpeg_JPWL_la-jp2.lo \ - libopenjpeg_JPWL_la-jpt.lo libopenjpeg_JPWL_la-mct.lo \ - libopenjpeg_JPWL_la-mqc.lo libopenjpeg_JPWL_la-openjpeg.lo \ - libopenjpeg_JPWL_la-pi.lo libopenjpeg_JPWL_la-raw.lo \ - libopenjpeg_JPWL_la-t1.lo \ - libopenjpeg_JPWL_la-t1_generate_luts.lo \ - libopenjpeg_JPWL_la-t2.lo libopenjpeg_JPWL_la-tcd.lo \ - libopenjpeg_JPWL_la-tgt.lo libopenjpeg_JPWL_la-cidx_manager.lo \ - libopenjpeg_JPWL_la-phix_manager.lo \ - libopenjpeg_JPWL_la-ppix_manager.lo \ - libopenjpeg_JPWL_la-thix_manager.lo \ - libopenjpeg_JPWL_la-tpix_manager.lo -am_libopenjpeg_JPWL_la_OBJECTS = $(am__objects_1) \ - libopenjpeg_JPWL_la-crc.lo libopenjpeg_JPWL_la-jpwl.lo \ - libopenjpeg_JPWL_la-jpwl_lib.lo libopenjpeg_JPWL_la-rs.lo -libopenjpeg_JPWL_la_OBJECTS = $(am_libopenjpeg_JPWL_la_OBJECTS) -AM_V_lt = $(am__v_lt_$(V)) -am__v_lt_ = $(am__v_lt_$(AM_DEFAULT_VERBOSITY)) -am__v_lt_0 = --silent -libopenjpeg_JPWL_la_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ - $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ - $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) \ - $(libopenjpeg_JPWL_la_LDFLAGS) $(LDFLAGS) -o $@ -DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) -depcomp = $(SHELL) $(top_srcdir)/depcomp -am__depfiles_maybe = depfiles -am__mv = mv -f -COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ - $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ - $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \ - $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ - $(AM_CFLAGS) $(CFLAGS) -AM_V_CC = $(am__v_CC_$(V)) -am__v_CC_ = $(am__v_CC_$(AM_DEFAULT_VERBOSITY)) -am__v_CC_0 = @echo " CC " $@; -AM_V_at = $(am__v_at_$(V)) -am__v_at_ = $(am__v_at_$(AM_DEFAULT_VERBOSITY)) -am__v_at_0 = @ -CCLD = $(CC) -LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ - $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ - $(AM_LDFLAGS) $(LDFLAGS) -o $@ -AM_V_CCLD = $(am__v_CCLD_$(V)) -am__v_CCLD_ = $(am__v_CCLD_$(AM_DEFAULT_VERBOSITY)) -am__v_CCLD_0 = @echo " CCLD " $@; -AM_V_GEN = $(am__v_GEN_$(V)) -am__v_GEN_ = $(am__v_GEN_$(AM_DEFAULT_VERBOSITY)) -am__v_GEN_0 = @echo " GEN " $@; -SOURCES = $(libopenjpeg_JPWL_la_SOURCES) -DIST_SOURCES = $(libopenjpeg_JPWL_la_SOURCES) -ETAGS = etags -CTAGS = ctags -DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) -ACLOCAL = @ACLOCAL@ -AMTAR = @AMTAR@ -AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ -AR = @AR@ -AS = @AS@ -AUTOCONF = @AUTOCONF@ -AUTOHEADER = @AUTOHEADER@ -AUTOMAKE = @AUTOMAKE@ -AWK = @AWK@ -CC = @CC@ -CCDEPMODE = @CCDEPMODE@ -CFLAGS = @CFLAGS@ -CPP = @CPP@ -CPPFLAGS = @CPPFLAGS@ -CYGPATH_W = @CYGPATH_W@ -DEFS = @DEFS@ -DEPDIR = @DEPDIR@ -DLLTOOL = @DLLTOOL@ -DSYMUTIL = @DSYMUTIL@ -DUMPBIN = @DUMPBIN@ -ECHO_C = @ECHO_C@ -ECHO_N = @ECHO_N@ -ECHO_T = @ECHO_T@ -EGREP = @EGREP@ -EXEEXT = @EXEEXT@ -FCGI_CFLAGS = @FCGI_CFLAGS@ -FCGI_LIBS = @FCGI_LIBS@ -FGREP = @FGREP@ -GREP = @GREP@ -INSTALL = @INSTALL@ -INSTALL_DATA = @INSTALL_DATA@ -INSTALL_PROGRAM = @INSTALL_PROGRAM@ -INSTALL_SCRIPT = @INSTALL_SCRIPT@ -INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ -LCMS1_CFLAGS = @LCMS1_CFLAGS@ -LCMS1_LIBS = @LCMS1_LIBS@ -LCMS2_CFLAGS = @LCMS2_CFLAGS@ -LCMS2_LIBS = @LCMS2_LIBS@ -LD = @LD@ -LDFLAGS = @LDFLAGS@ -LIBCURL_CFLAGS = @LIBCURL_CFLAGS@ -LIBCURL_LIBS = @LIBCURL_LIBS@ -LIBOBJS = @LIBOBJS@ -LIBS = @LIBS@ -LIBTOOL = @LIBTOOL@ -LIPO = @LIPO@ -LN_S = @LN_S@ -LTLIBOBJS = @LTLIBOBJS@ -MAJOR_NR = @MAJOR_NR@ -MAKEINFO = @MAKEINFO@ -MICRO_NR = @MICRO_NR@ -MINOR_NR = @MINOR_NR@ -MKDIR_P = @MKDIR_P@ -NM = @NM@ -NMEDIT = @NMEDIT@ -OBJDUMP = @OBJDUMP@ -OBJEXT = @OBJEXT@ -OTOOL = @OTOOL@ -OTOOL64 = @OTOOL64@ -PACKAGE = @PACKAGE@ -PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ -PACKAGE_NAME = @PACKAGE_NAME@ -PACKAGE_STRING = @PACKAGE_STRING@ -PACKAGE_TARNAME = @PACKAGE_TARNAME@ -PACKAGE_URL = @PACKAGE_URL@ -PACKAGE_VERSION = @PACKAGE_VERSION@ -PATH_SEPARATOR = @PATH_SEPARATOR@ -PKG_CONFIG = @PKG_CONFIG@ -PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ -PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ -PNG_CFLAGS = @PNG_CFLAGS@ -PNG_LIBS = @PNG_LIBS@ -RANLIB = @RANLIB@ -SED = @SED@ -SET_MAKE = @SET_MAKE@ -SHELL = @SHELL@ -STRIP = @STRIP@ -THREAD_CFLAGS = @THREAD_CFLAGS@ -THREAD_LIBS = @THREAD_LIBS@ -TIFF_CFLAGS = @TIFF_CFLAGS@ -TIFF_LIBS = @TIFF_LIBS@ -VERSION = @VERSION@ -Z_CFLAGS = @Z_CFLAGS@ -Z_LIBS = @Z_LIBS@ -abs_builddir = @abs_builddir@ -abs_srcdir = @abs_srcdir@ -abs_top_builddir = @abs_top_builddir@ -abs_top_srcdir = @abs_top_srcdir@ -ac_ct_CC = @ac_ct_CC@ -ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ -am__include = @am__include@ -am__leading_dot = @am__leading_dot@ -am__quote = @am__quote@ -am__tar = @am__tar@ -am__untar = @am__untar@ -bindir = @bindir@ -build = @build@ -build_alias = @build_alias@ -build_cpu = @build_cpu@ -build_os = @build_os@ -build_vendor = @build_vendor@ -builddir = @builddir@ -datadir = @datadir@ -datarootdir = @datarootdir@ -docdir = @docdir@ -dvidir = @dvidir@ -exec_prefix = @exec_prefix@ -host = @host@ -host_alias = @host_alias@ -host_cpu = @host_cpu@ -host_os = @host_os@ -host_vendor = @host_vendor@ -htmldir = @htmldir@ -includedir = @includedir@ -infodir = @infodir@ -install_sh = @install_sh@ -libdir = @libdir@ -libexecdir = @libexecdir@ -localedir = @localedir@ -localstatedir = @localstatedir@ -lt_ECHO = @lt_ECHO@ -lt_version = @lt_version@ -mandir = @mandir@ -mkdir_p = @mkdir_p@ -oldincludedir = @oldincludedir@ -opj_doxygen = @opj_doxygen@ -opj_have_doxygen = @opj_have_doxygen@ -pdfdir = @pdfdir@ -pkgconfig_requires_private = @pkgconfig_requires_private@ -prefix = @prefix@ -program_transform_name = @program_transform_name@ -psdir = @psdir@ -requirements = @requirements@ -sbindir = @sbindir@ -sharedstatedir = @sharedstatedir@ -srcdir = @srcdir@ -sysconfdir = @sysconfdir@ -target = @target@ -target_alias = @target_alias@ -target_cpu = @target_cpu@ -target_os = @target_os@ -target_vendor = @target_vendor@ -top_build_prefix = @top_build_prefix@ -top_builddir = @top_builddir@ -top_srcdir = @top_srcdir@ -MAINTAINERCLEANFILES = Makefile.in -lib_LTLIBRARIES = libopenjpeg_JPWL.la -OPJ_SRC = \ -../bio.c \ -../cio.c \ -../dwt.c \ -../event.c \ -../image.c \ -../j2k.c \ -../j2k_lib.c \ -../jp2.c \ -../jpt.c \ -../mct.c \ -../mqc.c \ -../openjpeg.c \ -../pi.c \ -../raw.c \ -../t1.c \ -../t1_generate_luts.c \ -../t2.c \ -../tcd.c \ -../tgt.c \ -../cidx_manager.c \ -../phix_manager.c \ -../ppix_manager.c \ -../thix_manager.c \ -../tpix_manager.c - -libopenjpeg_JPWL_la_CPPFLAGS = \ --I. \ --I$(top_srcdir)/libopenjpeg \ --I$(top_builddir)/libopenjpeg \ --I$(top_srcdir)/libopenjpeg/jpwl \ --I$(top_builddir)/libopenjpeg/jpwl \ --DUSE_JPWL - -libopenjpeg_JPWL_la_CFLAGS = -libopenjpeg_JPWL_la_LIBADD = -lm -libopenjpeg_JPWL_la_LDFLAGS = -no-undefined -version-info @lt_version@ -libopenjpeg_JPWL_la_SOURCES = \ -$(OPJ_SRC) \ -crc.c \ -jpwl.c \ -jpwl_lib.c \ -rs.c \ -crc.h \ -jpwl.h \ -rs.h - -solist = $(foreach f, $(dll) $(so), echo -e ' $(SO_PREFIX)\t$(base)/$(f)' ;) -get_tok = $(shell grep -E "^$(1)=" $(lib_LTLIBRARIES) | cut -d "'" -f 2) -base = $(call get_tok,libdir) -so = $(call get_tok,library_names) -a = $(call get_tok,old_library) -@HAVE_DARWIN_FALSE@@HAVE_WIN32_FALSE@SO_PREFIX = (SO) -@HAVE_DARWIN_TRUE@@HAVE_WIN32_FALSE@SO_PREFIX = (DY) -@HAVE_WIN32_TRUE@SO_PREFIX = (DLL) -@HAVE_DARWIN_FALSE@@HAVE_WIN32_FALSE@dll = -@HAVE_DARWIN_TRUE@@HAVE_WIN32_FALSE@dll = -@HAVE_WIN32_TRUE@dll = $(call get_tok,dlname) -all: all-am - -.SUFFIXES: -.SUFFIXES: .c .lo .o .obj -$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) - @for dep in $?; do \ - case '$(am__configure_deps)' in \ - *$$dep*) \ - ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ - && { if test -f $@; then exit 0; else break; fi; }; \ - exit 1;; \ - esac; \ - done; \ - echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign libopenjpeg/jpwl/Makefile'; \ - $(am__cd) $(top_srcdir) && \ - $(AUTOMAKE) --foreign libopenjpeg/jpwl/Makefile -.PRECIOUS: Makefile -Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status - @case '$?' in \ - *config.status*) \ - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ - *) \ - echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ - cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ - esac; - -$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh - -$(top_srcdir)/configure: $(am__configure_deps) - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh -$(ACLOCAL_M4): $(am__aclocal_m4_deps) - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh -$(am__aclocal_m4_deps): -install-libLTLIBRARIES: $(lib_LTLIBRARIES) - @$(NORMAL_INSTALL) - test -z "$(libdir)" || $(MKDIR_P) "$(DESTDIR)$(libdir)" - @list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \ - list2=; for p in $$list; do \ - if test -f $$p; then \ - list2="$$list2 $$p"; \ - else :; fi; \ - done; \ - test -z "$$list2" || { \ - echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(libdir)'"; \ - $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(libdir)"; \ - } - -uninstall-libLTLIBRARIES: - @$(NORMAL_UNINSTALL) - @list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \ - for p in $$list; do \ - $(am__strip_dir) \ - echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f '$(DESTDIR)$(libdir)/$$f'"; \ - $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f "$(DESTDIR)$(libdir)/$$f"; \ - done - -clean-libLTLIBRARIES: - -test -z "$(lib_LTLIBRARIES)" || rm -f $(lib_LTLIBRARIES) - @list='$(lib_LTLIBRARIES)'; for p in $$list; do \ - dir="`echo $$p | sed -e 's|/[^/]*$$||'`"; \ - test "$$dir" != "$$p" || dir=.; \ - echo "rm -f \"$${dir}/so_locations\""; \ - rm -f "$${dir}/so_locations"; \ - done -libopenjpeg_JPWL.la: $(libopenjpeg_JPWL_la_OBJECTS) $(libopenjpeg_JPWL_la_DEPENDENCIES) - $(AM_V_CCLD)$(libopenjpeg_JPWL_la_LINK) -rpath $(libdir) $(libopenjpeg_JPWL_la_OBJECTS) $(libopenjpeg_JPWL_la_LIBADD) $(LIBS) - -mostlyclean-compile: - -rm -f *.$(OBJEXT) - -distclean-compile: - -rm -f *.tab.c - -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libopenjpeg_JPWL_la-bio.Plo@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libopenjpeg_JPWL_la-cidx_manager.Plo@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libopenjpeg_JPWL_la-cio.Plo@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libopenjpeg_JPWL_la-crc.Plo@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libopenjpeg_JPWL_la-dwt.Plo@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libopenjpeg_JPWL_la-event.Plo@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libopenjpeg_JPWL_la-image.Plo@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libopenjpeg_JPWL_la-j2k.Plo@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libopenjpeg_JPWL_la-j2k_lib.Plo@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libopenjpeg_JPWL_la-jp2.Plo@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libopenjpeg_JPWL_la-jpt.Plo@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libopenjpeg_JPWL_la-jpwl.Plo@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libopenjpeg_JPWL_la-jpwl_lib.Plo@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libopenjpeg_JPWL_la-mct.Plo@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libopenjpeg_JPWL_la-mqc.Plo@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libopenjpeg_JPWL_la-openjpeg.Plo@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libopenjpeg_JPWL_la-phix_manager.Plo@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libopenjpeg_JPWL_la-pi.Plo@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libopenjpeg_JPWL_la-ppix_manager.Plo@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libopenjpeg_JPWL_la-raw.Plo@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libopenjpeg_JPWL_la-rs.Plo@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libopenjpeg_JPWL_la-t1.Plo@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libopenjpeg_JPWL_la-t1_generate_luts.Plo@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libopenjpeg_JPWL_la-t2.Plo@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libopenjpeg_JPWL_la-tcd.Plo@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libopenjpeg_JPWL_la-tgt.Plo@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libopenjpeg_JPWL_la-thix_manager.Plo@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libopenjpeg_JPWL_la-tpix_manager.Plo@am__quote@ - -.c.o: -@am__fastdepCC_TRUE@ $(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< -@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po -@am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCC_FALSE@ $(COMPILE) -c $< - -.c.obj: -@am__fastdepCC_TRUE@ $(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` -@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po -@am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCC_FALSE@ $(COMPILE) -c `$(CYGPATH_W) '$<'` - -.c.lo: -@am__fastdepCC_TRUE@ $(AM_V_CC)$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< -@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo -@am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCC_FALSE@ $(LTCOMPILE) -c -o $@ $< - -libopenjpeg_JPWL_la-bio.lo: ../bio.c -@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -MT libopenjpeg_JPWL_la-bio.lo -MD -MP -MF $(DEPDIR)/libopenjpeg_JPWL_la-bio.Tpo -c -o libopenjpeg_JPWL_la-bio.lo `test -f '../bio.c' || echo '$(srcdir)/'`../bio.c -@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libopenjpeg_JPWL_la-bio.Tpo $(DEPDIR)/libopenjpeg_JPWL_la-bio.Plo -@am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='../bio.c' object='libopenjpeg_JPWL_la-bio.lo' libtool=yes @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCC_FALSE@ $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -c -o libopenjpeg_JPWL_la-bio.lo `test -f '../bio.c' || echo '$(srcdir)/'`../bio.c - -libopenjpeg_JPWL_la-cio.lo: ../cio.c -@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -MT libopenjpeg_JPWL_la-cio.lo -MD -MP -MF $(DEPDIR)/libopenjpeg_JPWL_la-cio.Tpo -c -o libopenjpeg_JPWL_la-cio.lo `test -f '../cio.c' || echo '$(srcdir)/'`../cio.c -@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libopenjpeg_JPWL_la-cio.Tpo $(DEPDIR)/libopenjpeg_JPWL_la-cio.Plo -@am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='../cio.c' object='libopenjpeg_JPWL_la-cio.lo' libtool=yes @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCC_FALSE@ $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -c -o libopenjpeg_JPWL_la-cio.lo `test -f '../cio.c' || echo '$(srcdir)/'`../cio.c - -libopenjpeg_JPWL_la-dwt.lo: ../dwt.c -@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -MT libopenjpeg_JPWL_la-dwt.lo -MD -MP -MF $(DEPDIR)/libopenjpeg_JPWL_la-dwt.Tpo -c -o libopenjpeg_JPWL_la-dwt.lo `test -f '../dwt.c' || echo '$(srcdir)/'`../dwt.c -@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libopenjpeg_JPWL_la-dwt.Tpo $(DEPDIR)/libopenjpeg_JPWL_la-dwt.Plo -@am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='../dwt.c' object='libopenjpeg_JPWL_la-dwt.lo' libtool=yes @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCC_FALSE@ $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -c -o libopenjpeg_JPWL_la-dwt.lo `test -f '../dwt.c' || echo '$(srcdir)/'`../dwt.c - -libopenjpeg_JPWL_la-event.lo: ../event.c -@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -MT libopenjpeg_JPWL_la-event.lo -MD -MP -MF $(DEPDIR)/libopenjpeg_JPWL_la-event.Tpo -c -o libopenjpeg_JPWL_la-event.lo `test -f '../event.c' || echo '$(srcdir)/'`../event.c -@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libopenjpeg_JPWL_la-event.Tpo $(DEPDIR)/libopenjpeg_JPWL_la-event.Plo -@am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='../event.c' object='libopenjpeg_JPWL_la-event.lo' libtool=yes @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCC_FALSE@ $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -c -o libopenjpeg_JPWL_la-event.lo `test -f '../event.c' || echo '$(srcdir)/'`../event.c - -libopenjpeg_JPWL_la-image.lo: ../image.c -@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -MT libopenjpeg_JPWL_la-image.lo -MD -MP -MF $(DEPDIR)/libopenjpeg_JPWL_la-image.Tpo -c -o libopenjpeg_JPWL_la-image.lo `test -f '../image.c' || echo '$(srcdir)/'`../image.c -@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libopenjpeg_JPWL_la-image.Tpo $(DEPDIR)/libopenjpeg_JPWL_la-image.Plo -@am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='../image.c' object='libopenjpeg_JPWL_la-image.lo' libtool=yes @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCC_FALSE@ $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -c -o libopenjpeg_JPWL_la-image.lo `test -f '../image.c' || echo '$(srcdir)/'`../image.c - -libopenjpeg_JPWL_la-j2k.lo: ../j2k.c -@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -MT libopenjpeg_JPWL_la-j2k.lo -MD -MP -MF $(DEPDIR)/libopenjpeg_JPWL_la-j2k.Tpo -c -o libopenjpeg_JPWL_la-j2k.lo `test -f '../j2k.c' || echo '$(srcdir)/'`../j2k.c -@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libopenjpeg_JPWL_la-j2k.Tpo $(DEPDIR)/libopenjpeg_JPWL_la-j2k.Plo -@am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='../j2k.c' object='libopenjpeg_JPWL_la-j2k.lo' libtool=yes @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCC_FALSE@ $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -c -o libopenjpeg_JPWL_la-j2k.lo `test -f '../j2k.c' || echo '$(srcdir)/'`../j2k.c - -libopenjpeg_JPWL_la-j2k_lib.lo: ../j2k_lib.c -@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -MT libopenjpeg_JPWL_la-j2k_lib.lo -MD -MP -MF $(DEPDIR)/libopenjpeg_JPWL_la-j2k_lib.Tpo -c -o libopenjpeg_JPWL_la-j2k_lib.lo `test -f '../j2k_lib.c' || echo '$(srcdir)/'`../j2k_lib.c -@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libopenjpeg_JPWL_la-j2k_lib.Tpo $(DEPDIR)/libopenjpeg_JPWL_la-j2k_lib.Plo -@am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='../j2k_lib.c' object='libopenjpeg_JPWL_la-j2k_lib.lo' libtool=yes @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCC_FALSE@ $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -c -o libopenjpeg_JPWL_la-j2k_lib.lo `test -f '../j2k_lib.c' || echo '$(srcdir)/'`../j2k_lib.c - -libopenjpeg_JPWL_la-jp2.lo: ../jp2.c -@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -MT libopenjpeg_JPWL_la-jp2.lo -MD -MP -MF $(DEPDIR)/libopenjpeg_JPWL_la-jp2.Tpo -c -o libopenjpeg_JPWL_la-jp2.lo `test -f '../jp2.c' || echo '$(srcdir)/'`../jp2.c -@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libopenjpeg_JPWL_la-jp2.Tpo $(DEPDIR)/libopenjpeg_JPWL_la-jp2.Plo -@am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='../jp2.c' object='libopenjpeg_JPWL_la-jp2.lo' libtool=yes @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCC_FALSE@ $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -c -o libopenjpeg_JPWL_la-jp2.lo `test -f '../jp2.c' || echo '$(srcdir)/'`../jp2.c - -libopenjpeg_JPWL_la-jpt.lo: ../jpt.c -@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -MT libopenjpeg_JPWL_la-jpt.lo -MD -MP -MF $(DEPDIR)/libopenjpeg_JPWL_la-jpt.Tpo -c -o libopenjpeg_JPWL_la-jpt.lo `test -f '../jpt.c' || echo '$(srcdir)/'`../jpt.c -@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libopenjpeg_JPWL_la-jpt.Tpo $(DEPDIR)/libopenjpeg_JPWL_la-jpt.Plo -@am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='../jpt.c' object='libopenjpeg_JPWL_la-jpt.lo' libtool=yes @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCC_FALSE@ $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -c -o libopenjpeg_JPWL_la-jpt.lo `test -f '../jpt.c' || echo '$(srcdir)/'`../jpt.c - -libopenjpeg_JPWL_la-mct.lo: ../mct.c -@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -MT libopenjpeg_JPWL_la-mct.lo -MD -MP -MF $(DEPDIR)/libopenjpeg_JPWL_la-mct.Tpo -c -o libopenjpeg_JPWL_la-mct.lo `test -f '../mct.c' || echo '$(srcdir)/'`../mct.c -@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libopenjpeg_JPWL_la-mct.Tpo $(DEPDIR)/libopenjpeg_JPWL_la-mct.Plo -@am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='../mct.c' object='libopenjpeg_JPWL_la-mct.lo' libtool=yes @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCC_FALSE@ $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -c -o libopenjpeg_JPWL_la-mct.lo `test -f '../mct.c' || echo '$(srcdir)/'`../mct.c - -libopenjpeg_JPWL_la-mqc.lo: ../mqc.c -@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -MT libopenjpeg_JPWL_la-mqc.lo -MD -MP -MF $(DEPDIR)/libopenjpeg_JPWL_la-mqc.Tpo -c -o libopenjpeg_JPWL_la-mqc.lo `test -f '../mqc.c' || echo '$(srcdir)/'`../mqc.c -@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libopenjpeg_JPWL_la-mqc.Tpo $(DEPDIR)/libopenjpeg_JPWL_la-mqc.Plo -@am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='../mqc.c' object='libopenjpeg_JPWL_la-mqc.lo' libtool=yes @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCC_FALSE@ $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -c -o libopenjpeg_JPWL_la-mqc.lo `test -f '../mqc.c' || echo '$(srcdir)/'`../mqc.c - -libopenjpeg_JPWL_la-openjpeg.lo: ../openjpeg.c -@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -MT libopenjpeg_JPWL_la-openjpeg.lo -MD -MP -MF $(DEPDIR)/libopenjpeg_JPWL_la-openjpeg.Tpo -c -o libopenjpeg_JPWL_la-openjpeg.lo `test -f '../openjpeg.c' || echo '$(srcdir)/'`../openjpeg.c -@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libopenjpeg_JPWL_la-openjpeg.Tpo $(DEPDIR)/libopenjpeg_JPWL_la-openjpeg.Plo -@am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='../openjpeg.c' object='libopenjpeg_JPWL_la-openjpeg.lo' libtool=yes @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCC_FALSE@ $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -c -o libopenjpeg_JPWL_la-openjpeg.lo `test -f '../openjpeg.c' || echo '$(srcdir)/'`../openjpeg.c - -libopenjpeg_JPWL_la-pi.lo: ../pi.c -@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -MT libopenjpeg_JPWL_la-pi.lo -MD -MP -MF $(DEPDIR)/libopenjpeg_JPWL_la-pi.Tpo -c -o libopenjpeg_JPWL_la-pi.lo `test -f '../pi.c' || echo '$(srcdir)/'`../pi.c -@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libopenjpeg_JPWL_la-pi.Tpo $(DEPDIR)/libopenjpeg_JPWL_la-pi.Plo -@am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='../pi.c' object='libopenjpeg_JPWL_la-pi.lo' libtool=yes @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCC_FALSE@ $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -c -o libopenjpeg_JPWL_la-pi.lo `test -f '../pi.c' || echo '$(srcdir)/'`../pi.c - -libopenjpeg_JPWL_la-raw.lo: ../raw.c -@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -MT libopenjpeg_JPWL_la-raw.lo -MD -MP -MF $(DEPDIR)/libopenjpeg_JPWL_la-raw.Tpo -c -o libopenjpeg_JPWL_la-raw.lo `test -f '../raw.c' || echo '$(srcdir)/'`../raw.c -@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libopenjpeg_JPWL_la-raw.Tpo $(DEPDIR)/libopenjpeg_JPWL_la-raw.Plo -@am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='../raw.c' object='libopenjpeg_JPWL_la-raw.lo' libtool=yes @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCC_FALSE@ $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -c -o libopenjpeg_JPWL_la-raw.lo `test -f '../raw.c' || echo '$(srcdir)/'`../raw.c - -libopenjpeg_JPWL_la-t1.lo: ../t1.c -@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -MT libopenjpeg_JPWL_la-t1.lo -MD -MP -MF $(DEPDIR)/libopenjpeg_JPWL_la-t1.Tpo -c -o libopenjpeg_JPWL_la-t1.lo `test -f '../t1.c' || echo '$(srcdir)/'`../t1.c -@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libopenjpeg_JPWL_la-t1.Tpo $(DEPDIR)/libopenjpeg_JPWL_la-t1.Plo -@am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='../t1.c' object='libopenjpeg_JPWL_la-t1.lo' libtool=yes @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCC_FALSE@ $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -c -o libopenjpeg_JPWL_la-t1.lo `test -f '../t1.c' || echo '$(srcdir)/'`../t1.c - -libopenjpeg_JPWL_la-t1_generate_luts.lo: ../t1_generate_luts.c -@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -MT libopenjpeg_JPWL_la-t1_generate_luts.lo -MD -MP -MF $(DEPDIR)/libopenjpeg_JPWL_la-t1_generate_luts.Tpo -c -o libopenjpeg_JPWL_la-t1_generate_luts.lo `test -f '../t1_generate_luts.c' || echo '$(srcdir)/'`../t1_generate_luts.c -@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libopenjpeg_JPWL_la-t1_generate_luts.Tpo $(DEPDIR)/libopenjpeg_JPWL_la-t1_generate_luts.Plo -@am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='../t1_generate_luts.c' object='libopenjpeg_JPWL_la-t1_generate_luts.lo' libtool=yes @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCC_FALSE@ $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -c -o libopenjpeg_JPWL_la-t1_generate_luts.lo `test -f '../t1_generate_luts.c' || echo '$(srcdir)/'`../t1_generate_luts.c - -libopenjpeg_JPWL_la-t2.lo: ../t2.c -@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -MT libopenjpeg_JPWL_la-t2.lo -MD -MP -MF $(DEPDIR)/libopenjpeg_JPWL_la-t2.Tpo -c -o libopenjpeg_JPWL_la-t2.lo `test -f '../t2.c' || echo '$(srcdir)/'`../t2.c -@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libopenjpeg_JPWL_la-t2.Tpo $(DEPDIR)/libopenjpeg_JPWL_la-t2.Plo -@am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='../t2.c' object='libopenjpeg_JPWL_la-t2.lo' libtool=yes @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCC_FALSE@ $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -c -o libopenjpeg_JPWL_la-t2.lo `test -f '../t2.c' || echo '$(srcdir)/'`../t2.c - -libopenjpeg_JPWL_la-tcd.lo: ../tcd.c -@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -MT libopenjpeg_JPWL_la-tcd.lo -MD -MP -MF $(DEPDIR)/libopenjpeg_JPWL_la-tcd.Tpo -c -o libopenjpeg_JPWL_la-tcd.lo `test -f '../tcd.c' || echo '$(srcdir)/'`../tcd.c -@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libopenjpeg_JPWL_la-tcd.Tpo $(DEPDIR)/libopenjpeg_JPWL_la-tcd.Plo -@am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='../tcd.c' object='libopenjpeg_JPWL_la-tcd.lo' libtool=yes @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCC_FALSE@ $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -c -o libopenjpeg_JPWL_la-tcd.lo `test -f '../tcd.c' || echo '$(srcdir)/'`../tcd.c - -libopenjpeg_JPWL_la-tgt.lo: ../tgt.c -@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -MT libopenjpeg_JPWL_la-tgt.lo -MD -MP -MF $(DEPDIR)/libopenjpeg_JPWL_la-tgt.Tpo -c -o libopenjpeg_JPWL_la-tgt.lo `test -f '../tgt.c' || echo '$(srcdir)/'`../tgt.c -@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libopenjpeg_JPWL_la-tgt.Tpo $(DEPDIR)/libopenjpeg_JPWL_la-tgt.Plo -@am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='../tgt.c' object='libopenjpeg_JPWL_la-tgt.lo' libtool=yes @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCC_FALSE@ $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -c -o libopenjpeg_JPWL_la-tgt.lo `test -f '../tgt.c' || echo '$(srcdir)/'`../tgt.c - -libopenjpeg_JPWL_la-cidx_manager.lo: ../cidx_manager.c -@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -MT libopenjpeg_JPWL_la-cidx_manager.lo -MD -MP -MF $(DEPDIR)/libopenjpeg_JPWL_la-cidx_manager.Tpo -c -o libopenjpeg_JPWL_la-cidx_manager.lo `test -f '../cidx_manager.c' || echo '$(srcdir)/'`../cidx_manager.c -@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libopenjpeg_JPWL_la-cidx_manager.Tpo $(DEPDIR)/libopenjpeg_JPWL_la-cidx_manager.Plo -@am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='../cidx_manager.c' object='libopenjpeg_JPWL_la-cidx_manager.lo' libtool=yes @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCC_FALSE@ $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -c -o libopenjpeg_JPWL_la-cidx_manager.lo `test -f '../cidx_manager.c' || echo '$(srcdir)/'`../cidx_manager.c - -libopenjpeg_JPWL_la-phix_manager.lo: ../phix_manager.c -@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -MT libopenjpeg_JPWL_la-phix_manager.lo -MD -MP -MF $(DEPDIR)/libopenjpeg_JPWL_la-phix_manager.Tpo -c -o libopenjpeg_JPWL_la-phix_manager.lo `test -f '../phix_manager.c' || echo '$(srcdir)/'`../phix_manager.c -@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libopenjpeg_JPWL_la-phix_manager.Tpo $(DEPDIR)/libopenjpeg_JPWL_la-phix_manager.Plo -@am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='../phix_manager.c' object='libopenjpeg_JPWL_la-phix_manager.lo' libtool=yes @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCC_FALSE@ $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -c -o libopenjpeg_JPWL_la-phix_manager.lo `test -f '../phix_manager.c' || echo '$(srcdir)/'`../phix_manager.c - -libopenjpeg_JPWL_la-ppix_manager.lo: ../ppix_manager.c -@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -MT libopenjpeg_JPWL_la-ppix_manager.lo -MD -MP -MF $(DEPDIR)/libopenjpeg_JPWL_la-ppix_manager.Tpo -c -o libopenjpeg_JPWL_la-ppix_manager.lo `test -f '../ppix_manager.c' || echo '$(srcdir)/'`../ppix_manager.c -@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libopenjpeg_JPWL_la-ppix_manager.Tpo $(DEPDIR)/libopenjpeg_JPWL_la-ppix_manager.Plo -@am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='../ppix_manager.c' object='libopenjpeg_JPWL_la-ppix_manager.lo' libtool=yes @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCC_FALSE@ $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -c -o libopenjpeg_JPWL_la-ppix_manager.lo `test -f '../ppix_manager.c' || echo '$(srcdir)/'`../ppix_manager.c - -libopenjpeg_JPWL_la-thix_manager.lo: ../thix_manager.c -@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -MT libopenjpeg_JPWL_la-thix_manager.lo -MD -MP -MF $(DEPDIR)/libopenjpeg_JPWL_la-thix_manager.Tpo -c -o libopenjpeg_JPWL_la-thix_manager.lo `test -f '../thix_manager.c' || echo '$(srcdir)/'`../thix_manager.c -@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libopenjpeg_JPWL_la-thix_manager.Tpo $(DEPDIR)/libopenjpeg_JPWL_la-thix_manager.Plo -@am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='../thix_manager.c' object='libopenjpeg_JPWL_la-thix_manager.lo' libtool=yes @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCC_FALSE@ $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -c -o libopenjpeg_JPWL_la-thix_manager.lo `test -f '../thix_manager.c' || echo '$(srcdir)/'`../thix_manager.c - -libopenjpeg_JPWL_la-tpix_manager.lo: ../tpix_manager.c -@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -MT libopenjpeg_JPWL_la-tpix_manager.lo -MD -MP -MF $(DEPDIR)/libopenjpeg_JPWL_la-tpix_manager.Tpo -c -o libopenjpeg_JPWL_la-tpix_manager.lo `test -f '../tpix_manager.c' || echo '$(srcdir)/'`../tpix_manager.c -@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libopenjpeg_JPWL_la-tpix_manager.Tpo $(DEPDIR)/libopenjpeg_JPWL_la-tpix_manager.Plo -@am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='../tpix_manager.c' object='libopenjpeg_JPWL_la-tpix_manager.lo' libtool=yes @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCC_FALSE@ $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -c -o libopenjpeg_JPWL_la-tpix_manager.lo `test -f '../tpix_manager.c' || echo '$(srcdir)/'`../tpix_manager.c - -libopenjpeg_JPWL_la-crc.lo: crc.c -@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -MT libopenjpeg_JPWL_la-crc.lo -MD -MP -MF $(DEPDIR)/libopenjpeg_JPWL_la-crc.Tpo -c -o libopenjpeg_JPWL_la-crc.lo `test -f 'crc.c' || echo '$(srcdir)/'`crc.c -@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libopenjpeg_JPWL_la-crc.Tpo $(DEPDIR)/libopenjpeg_JPWL_la-crc.Plo -@am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='crc.c' object='libopenjpeg_JPWL_la-crc.lo' libtool=yes @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCC_FALSE@ $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -c -o libopenjpeg_JPWL_la-crc.lo `test -f 'crc.c' || echo '$(srcdir)/'`crc.c - -libopenjpeg_JPWL_la-jpwl.lo: jpwl.c -@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -MT libopenjpeg_JPWL_la-jpwl.lo -MD -MP -MF $(DEPDIR)/libopenjpeg_JPWL_la-jpwl.Tpo -c -o libopenjpeg_JPWL_la-jpwl.lo `test -f 'jpwl.c' || echo '$(srcdir)/'`jpwl.c -@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libopenjpeg_JPWL_la-jpwl.Tpo $(DEPDIR)/libopenjpeg_JPWL_la-jpwl.Plo -@am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='jpwl.c' object='libopenjpeg_JPWL_la-jpwl.lo' libtool=yes @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCC_FALSE@ $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -c -o libopenjpeg_JPWL_la-jpwl.lo `test -f 'jpwl.c' || echo '$(srcdir)/'`jpwl.c - -libopenjpeg_JPWL_la-jpwl_lib.lo: jpwl_lib.c -@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -MT libopenjpeg_JPWL_la-jpwl_lib.lo -MD -MP -MF $(DEPDIR)/libopenjpeg_JPWL_la-jpwl_lib.Tpo -c -o libopenjpeg_JPWL_la-jpwl_lib.lo `test -f 'jpwl_lib.c' || echo '$(srcdir)/'`jpwl_lib.c -@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libopenjpeg_JPWL_la-jpwl_lib.Tpo $(DEPDIR)/libopenjpeg_JPWL_la-jpwl_lib.Plo -@am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='jpwl_lib.c' object='libopenjpeg_JPWL_la-jpwl_lib.lo' libtool=yes @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCC_FALSE@ $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -c -o libopenjpeg_JPWL_la-jpwl_lib.lo `test -f 'jpwl_lib.c' || echo '$(srcdir)/'`jpwl_lib.c - -libopenjpeg_JPWL_la-rs.lo: rs.c -@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -MT libopenjpeg_JPWL_la-rs.lo -MD -MP -MF $(DEPDIR)/libopenjpeg_JPWL_la-rs.Tpo -c -o libopenjpeg_JPWL_la-rs.lo `test -f 'rs.c' || echo '$(srcdir)/'`rs.c -@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libopenjpeg_JPWL_la-rs.Tpo $(DEPDIR)/libopenjpeg_JPWL_la-rs.Plo -@am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='rs.c' object='libopenjpeg_JPWL_la-rs.lo' libtool=yes @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCC_FALSE@ $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libopenjpeg_JPWL_la_CPPFLAGS) $(CPPFLAGS) $(libopenjpeg_JPWL_la_CFLAGS) $(CFLAGS) -c -o libopenjpeg_JPWL_la-rs.lo `test -f 'rs.c' || echo '$(srcdir)/'`rs.c - -mostlyclean-libtool: - -rm -f *.lo - -clean-libtool: - -rm -rf .libs _libs - -ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ - END { if (nonempty) { for (i in files) print i; }; }'`; \ - mkid -fID $$unique -tags: TAGS - -TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - set x; \ - here=`pwd`; \ - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ - END { if (nonempty) { for (i in files) print i; }; }'`; \ - shift; \ - if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ - test -n "$$unique" || unique=$$empty_fix; \ - if test $$# -gt 0; then \ - $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ - "$$@" $$unique; \ - else \ - $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ - $$unique; \ - fi; \ - fi -ctags: CTAGS -CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ - END { if (nonempty) { for (i in files) print i; }; }'`; \ - test -z "$(CTAGS_ARGS)$$unique" \ - || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ - $$unique - -GTAGS: - here=`$(am__cd) $(top_builddir) && pwd` \ - && $(am__cd) $(top_srcdir) \ - && gtags -i $(GTAGS_ARGS) "$$here" - -distclean-tags: - -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags - -distdir: $(DISTFILES) - @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ - topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ - list='$(DISTFILES)'; \ - dist_files=`for file in $$list; do echo $$file; done | \ - sed -e "s|^$$srcdirstrip/||;t" \ - -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ - case $$dist_files in \ - */*) $(MKDIR_P) `echo "$$dist_files" | \ - sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ - sort -u` ;; \ - esac; \ - for file in $$dist_files; do \ - if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ - if test -d $$d/$$file; then \ - dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ - if test -d "$(distdir)/$$file"; then \ - find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ - fi; \ - if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ - cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ - find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ - fi; \ - cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ - else \ - test -f "$(distdir)/$$file" \ - || cp -p $$d/$$file "$(distdir)/$$file" \ - || exit 1; \ - fi; \ - done -check-am: all-am -check: check-am -all-am: Makefile $(LTLIBRARIES) -installdirs: - for dir in "$(DESTDIR)$(libdir)"; do \ - test -z "$$dir" || $(MKDIR_P) "$$dir"; \ - done -install: install-am -install-exec: install-exec-am -install-data: install-data-am -uninstall: uninstall-am - -install-am: all-am - @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am - -installcheck: installcheck-am -install-strip: - $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ - install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ - `test -z '$(STRIP)' || \ - echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install -mostlyclean-generic: - -clean-generic: - -distclean-generic: - -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) - -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) - -maintainer-clean-generic: - @echo "This command is intended for maintainers to use" - @echo "it deletes files that may require special tools to rebuild." - -test -z "$(MAINTAINERCLEANFILES)" || rm -f $(MAINTAINERCLEANFILES) -clean: clean-am - -clean-am: clean-generic clean-libLTLIBRARIES clean-libtool \ - mostlyclean-am - -distclean: distclean-am - -rm -rf ./$(DEPDIR) - -rm -f Makefile -distclean-am: clean-am distclean-compile distclean-generic \ - distclean-tags - -dvi: dvi-am - -dvi-am: - -html: html-am - -html-am: - -info: info-am - -info-am: - -install-data-am: - @$(NORMAL_INSTALL) - $(MAKE) $(AM_MAKEFLAGS) install-data-hook -install-dvi: install-dvi-am - -install-dvi-am: - -install-exec-am: install-libLTLIBRARIES - -install-html: install-html-am - -install-html-am: - -install-info: install-info-am - -install-info-am: - -install-man: - -install-pdf: install-pdf-am - -install-pdf-am: - -install-ps: install-ps-am - -install-ps-am: - -installcheck-am: - -maintainer-clean: maintainer-clean-am - -rm -rf ./$(DEPDIR) - -rm -f Makefile -maintainer-clean-am: distclean-am maintainer-clean-generic - -mostlyclean: mostlyclean-am - -mostlyclean-am: mostlyclean-compile mostlyclean-generic \ - mostlyclean-libtool - -pdf: pdf-am - -pdf-am: - -ps: ps-am - -ps-am: - -uninstall-am: uninstall-libLTLIBRARIES - -.MAKE: install-am install-data-am install-strip - -.PHONY: CTAGS GTAGS all all-am check check-am clean clean-generic \ - clean-libLTLIBRARIES clean-libtool ctags distclean \ - distclean-compile distclean-generic distclean-libtool \ - distclean-tags distdir dvi dvi-am html html-am info info-am \ - install install-am install-data install-data-am \ - install-data-hook install-dvi install-dvi-am install-exec \ - install-exec-am install-html install-html-am install-info \ - install-info-am install-libLTLIBRARIES install-man install-pdf \ - install-pdf-am install-ps install-ps-am install-strip \ - installcheck installcheck-am installdirs maintainer-clean \ - maintainer-clean-generic mostlyclean mostlyclean-compile \ - mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ - tags uninstall uninstall-am uninstall-libLTLIBRARIES - - -install-data-hook: - @echo -e " (LA)\t$(libdir)/libopenjpeg_JPWL.la" >> $(top_builddir)/report.txt -@BUILD_SHARED_TRUE@ @( $(call solist) ) >> $(top_builddir)/report.txt -@BUILD_STATIC_TRUE@ @echo -e " (A)\t$(base)/$(a)" >> $(top_builddir)/report.txt - -# Tell versions [3.59,3.63) of GNU make to not export all variables. -# Otherwise a system limit (for SysV at least) may be exceeded. -.NOEXPORT: diff --git a/openjpeg-dotnet/libopenjpeg/jpwl/README.txt b/openjpeg-dotnet/libopenjpeg/jpwl/README.txt deleted file mode 100644 index e289e9e4..00000000 --- a/openjpeg-dotnet/libopenjpeg/jpwl/README.txt +++ /dev/null @@ -1,136 +0,0 @@ -=============================================================================== - JPEG2000 Part 11 (ISO/IEC 15444-11 JPWL) Software - - - - Version 20061213 -=============================================================================== - - - - - -1. Scope -============= - -This document describes the installation and use of the JPWL module in the framework of OpenJPEG library. - -This implementation has been developed from OpenJPEG implementation of JPEG2000 standard, and for this reason it is written in C language. - -If you find some bugs or if you have problems using the encoder/decoder, please send an e-mail to jpwl@diei.unipg.it - - -2. Installing the code -========================== - -The JPWL code is integrated with the standard OpenJPEG library and codecs: it is activated by setting the macro USE_JPWL to defined in the preprocessor configuration options of your preferred C compiler. - -2.1. Compiling the source code in Windows -------------------------------------------- - -The "jpwl" directory is already populated with a couple of Visual C++ 6.0 workspaces - - * JPWL_image_to_j2k.dsw - Creates the encoder with JPWL functionalities - * JPWL_j2k_to_image.dsw - Creates the decoder with JPWL functionalities - -2.2. Compiling the source code in Unix-like systems ------------------------------------------------------ - -Under linux, enter the jpwl directory and type "make clean" and "make". - - -3. Running the JPWL software -========================= - -The options available at the command line are exactly the same of the base OpenJPEG codecs. In addition, there is a "-W" switch that activates JPWL functionalities. - -3.1. JPWL Encoder -------------------- - --W : adoption of JPWL (Part 11) capabilities (-W params) - The parameters can be written and repeated in any order: - [h<=type>,s<=method>,a=,z=,g=,... - ...,p<=type>] - - h selects the header error protection (EPB): 'type' can be - [0=none 1,absent=predefined 16=CRC-16 32=CRC-32 37-128=RS] - if 'tile' is absent, it applies to main and tile headers - if 'tile' is present, it applies from that tile - onwards, up to the next h spec, or to the last tile - in the codestream (max. 16 specs) - - p selects the packet error protection (EEP/UEP with EPBs) - to be applied to raw data: 'type' can be - [0=none 1,absent=predefined 16=CRC-16 32=CRC-32 37-128=RS] - if 'tile:pack' is absent, it starts from tile 0, packet 0 - if 'tile:pack' is present, it applies from that tile - and that packet onwards, up to the next packet spec - or to the last packet in the last tile in the codestream - (max. 16 specs) - - s enables sensitivity data insertion (ESD): 'method' can be - [-1=NO ESD 0=RELATIVE ERROR 1=MSE 2=MSE REDUCTION 3=PSNR - 4=PSNR INCREMENT 5=MAXERR 6=TSE 7=RESERVED] - if 'tile' is absent, it applies to main header only - if 'tile' is present, it applies from that tile - onwards, up to the next s spec, or to the last tile - in the codestream (max. 16 specs) - - g determines the addressing mode: can be - [0=PACKET 1=BYTE RANGE 2=PACKET RANGE] - - a determines the size of data addressing: can be - 2/4 bytes (small/large codestreams). If not set, auto-mode - - z determines the size of sensitivity values: can be - 1/2 bytes, for the transformed pseudo-floating point value - - ex.: - h,h0=64,h3=16,h5=32,p0=78,p0:24=56,p1,p3:0=0,p3:20=32,s=0,s0=6,s3=-1,a=0,g=1,z=1 - means - predefined EPB in MH, rs(64,32) from TPH 0 to TPH 2, - CRC-16 in TPH 3 and TPH 4, CRC-32 in remaining TPHs, - UEP rs(78,32) for packets 0 to 23 of tile 0, - UEP rs(56,32) for packets 24 to the last of tile 0, - UEP rs default for packets of tile 1, - no UEP for packets 0 to 19 of tile 3, - UEP CRC-32 for packets 20 of tile 3 to last tile, - relative sensitivity ESD for MH, - TSE ESD from TPH 0 to TPH 2, byte range with automatic - size of addresses and 1 byte for each sensitivity value - - ex.: - h,s,p - means - default protection to headers (MH and TPHs) as well as - data packets, one ESD in MH - - N.B.: use the following recommendations when specifying - the JPWL parameters list - - when you use UEP, always pair the 'p' option with 'h' - -3.2. JPWL Decoder -------------------- - - -W - Activates the JPWL correction capability, if the codestream complies. - Options can be a comma separated list of tokens: - c, c=numcomps - numcomps is the number of expected components in the codestream - (search of first EPB rely upon this, default is 3) - - -4. Known bugs and limitations -=============================== - -4.1. Bugs ------------ - -* It is not possible to save a JPWL encoded codestream using the wrapped file format (i.e. JP2): only raw file format (i.e. J2K) is working - -4.2. Limitations ------------------- - -* When specifying an UEP protection, you need to activate even TPH protection for those tiles where there is a protection of the packets -* RED insertion is not currently implemented at the decoder -* JPWL at entropy coding level is not implemented diff --git a/openjpeg-dotnet/libopenjpeg/jpwl/crc.c b/openjpeg-dotnet/libopenjpeg/jpwl/crc.c deleted file mode 100644 index 9cc57d7b..00000000 --- a/openjpeg-dotnet/libopenjpeg/jpwl/crc.c +++ /dev/null @@ -1,160 +0,0 @@ -/* - * Copyright (c) 2001-2003, David Janssens - * Copyright (c) 2002-2003, Yannick Verschueren - * Copyright (c) 2003-2005, Francois Devaux and Antonin Descampe - * Copyright (c) 2005, Herve Drolon, FreeImage Team - * Copyright (c) 2002-2005, Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium - * Copyright (c) 2005-2006, Dept. of Electronic and Information Engineering, Universita' degli Studi di Perugia, Italy - * 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. - */ - -#ifdef USE_JPWL - -#include "crc.h" - -/** -@file crc.c -@brief Functions used to compute the 16- and 32-bit CRC of byte arrays - -*/ - -/** file: CRC16.CPP - * - * CRC - Cyclic Redundancy Check (16-bit) - * - * A CRC-checksum is used to be sure, the data hasn't changed or is false. - * To create a CRC-checksum, initialise a check-variable (unsigned short), - * and set this to zero. Than call for every byte in the file (e.g.) the - * procedure updateCRC16 with this check-variable as the first parameter, - * and the byte as the second. At the end, the check-variable contains the - * CRC-checksum. - * - * implemented by Michael Neumann, 14.06.1998 - * - */ -const unsigned short CRC16_table[256] = { - 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, - 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef, - 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6, - 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de, - 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485, - 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d, - 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4, - 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc, - 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823, - 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b, - 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12, - 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a, - 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41, - 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49, - 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70, - 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78, - 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f, - 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067, - 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e, - 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256, - 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d, - 0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, - 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c, - 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634, - 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab, - 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3, - 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a, - 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92, - 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9, - 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1, - 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8, - 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0 -}; - -void updateCRC16(unsigned short *crc, unsigned char data) { - *crc = CRC16_table[(*crc >> 8) & 0xFF] ^ (*crc << 8) ^ data; -}; - - -/** file: CRC32.CPP - * - * CRC - Cyclic Redundancy Check (32-bit) - * - * A CRC-checksum is used to be sure, the data hasn't changed or is false. - * To create a CRC-checksum, initialise a check-variable (unsigned long), - * and set this to zero. Than call for every byte in the file (e.g.) the - * procedure updateCRC32 with this check-variable as the first parameter, - * and the byte as the second. At the end, the check-variable contains the - * CRC-checksum. - * - * implemented by Michael Neumann, 14.06.1998 - * - */ -const unsigned long CRC32_table[256] = { - 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, - 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, - 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, - 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, - 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, - 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, - 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, - 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, - 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, - 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, - 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, - 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, - 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, - 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, - 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, - 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, - 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, - 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, - 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, - 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, - 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, - 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, - 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, - 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, - 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, - 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, - 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, - 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, - 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, - 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, - 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, - 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, - 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, - 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, - 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, - 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, - 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, - 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, - 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, - 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, - 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, - 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, - 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d -}; - -void updateCRC32(unsigned long *crc, unsigned char data) { - *crc = CRC32_table[(unsigned char) *crc ^ data] ^ ((*crc >> 8) & 0x00FFFFFF); -}; - -#endif /* USE_JPWL */ diff --git a/openjpeg-dotnet/libopenjpeg/jpwl/crc.h b/openjpeg-dotnet/libopenjpeg/jpwl/crc.h deleted file mode 100644 index 4ea2c4ce..00000000 --- a/openjpeg-dotnet/libopenjpeg/jpwl/crc.h +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright (c) 2001-2003, David Janssens - * Copyright (c) 2002-2003, Yannick Verschueren - * Copyright (c) 2003-2005, Francois Devaux and Antonin Descampe - * Copyright (c) 2005, Herve Drolon, FreeImage Team - * Copyright (c) 2002-2005, Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium - * Copyright (c) 2005-2006, Dept. of Electronic and Information Engineering, Universita' degli Studi di Perugia, Italy - * 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. - */ - -#ifdef USE_JPWL - -/** -@file crc.h -@brief Functions used to compute the 16- and 32-bit CRC of byte arrays - -*/ - -#ifndef __CRC16_HEADER__ -#define __CRC16_HEADER__ - -/** file: CRC16.HPP - * - * CRC - Cyclic Redundancy Check (16-bit) - * - * A CRC-checksum is used to be sure, the data hasn't changed or is false. - * To create a CRC-checksum, initialise a check-variable (unsigned short), - * and set this to zero. Than call for every byte in the file (e.g.) the - * procedure updateCRC16 with this check-variable as the first parameter, - * and the byte as the second. At the end, the check-variable contains the - * CRC-checksum. - * - * implemented by Michael Neumann, 14.06.1998 - * - */ -void updateCRC16(unsigned short *, unsigned char); - -#endif /* __CRC16_HEADER__ */ - - -#ifndef __CRC32_HEADER__ -#define __CRC32_HEADER__ - -/** file: CRC32.HPP - * - * CRC - Cyclic Redundancy Check (32-bit) - * - * A CRC-checksum is used to be sure, the data hasn't changed or is false. - * To create a CRC-checksum, initialise a check-variable (unsigned short), - * and set this to zero. Than call for every byte in the file (e.g.) the - * procedure updateCRC32 with this check-variable as the first parameter, - * and the byte as the second. At the end, the check-variable contains the - * CRC-checksum. - * - * implemented by Michael Neumann, 14.06.1998 - * - */ -void updateCRC32(unsigned long *, unsigned char); - -#endif /* __CRC32_HEADER__ */ - - -#endif /* USE_JPWL */ diff --git a/openjpeg-dotnet/libopenjpeg/jpwl/jpwl.c b/openjpeg-dotnet/libopenjpeg/jpwl/jpwl.c deleted file mode 100644 index 33577189..00000000 --- a/openjpeg-dotnet/libopenjpeg/jpwl/jpwl.c +++ /dev/null @@ -1,1358 +0,0 @@ -/* - * Copyright (c) 2001-2003, David Janssens - * Copyright (c) 2002-2003, Yannick Verschueren - * Copyright (c) 2003-2005, Francois Devaux and Antonin Descampe - * Copyright (c) 2005, Herve Drolon, FreeImage Team - * Copyright (c) 2002-2005, Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium - * Copyright (c) 2005-2006, Dept. of Electronic and Information Engineering, Universita' degli Studi di Perugia, Italy - * 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 "opj_includes.h" - -#ifdef USE_JPWL - -/** @defgroup JPWL JPWL - JPEG-2000 Part11 (JPWL) codestream manager */ -/*@{*/ - -/** @name Local static variables */ -/*@{*/ - -/** number of JPWL prepared markers */ -static int jwmarker_num; -/** properties of JPWL markers to insert */ -static jpwl_marker_t jwmarker[JPWL_MAX_NO_MARKERS]; - -/*@}*/ - -/*@}*/ - -/** @name Local static functions */ -/*@{*/ - -/** create an EPC marker segment -@param j2k J2K compressor handle -@param esd_on true if ESD is activated -@param red_on true if RED is activated -@param epb_on true if EPB is activated -@param info_on true if informative techniques are activated -@return returns the freshly created EPC -*/ -jpwl_epc_ms_t *jpwl_epc_create(opj_j2k_t *j2k, opj_bool esd_on, opj_bool red_on, opj_bool epb_on, opj_bool info_on); - -/*@}*/ - -/** create an EPC marker segment -@param j2k J2K compressor handle -@param comps considered component (-1=average, 0/1/2/...=component no.) -@param addrm addressing mode (0=packet, 1=byte range, 2=packet range, 3=reserved) -@param ad_size size of addresses (2/4 bytes) -@param senst sensitivity type -@param se_size sensitivity values size (1/2 bytes) -@param tileno tile where this ESD lies (-1 means MH) -@param svalnum number of sensitivity values (if 0, they will be automatically filled) -@param sensval pointer to an array of sensitivity values (if NULL, they will be automatically filled) -@return returns the freshly created ESD -*/ -jpwl_esd_ms_t *jpwl_esd_create(opj_j2k_t *j2k, int comps, - unsigned char addrm, unsigned char ad_size, - unsigned char senst, int se_size, int tileno, - unsigned long int svalnum, void *sensval); - -/** this function is used to compare two JPWL markers based on -their relevant wishlist position -@param arg1 pointer to first marker -@param arg2 pointer to second marker -@return 1 if arg1>arg2, 0 if arg1=arg2, -1 if arg1pos_correction = 0; - -} - -void j2k_add_marker(opj_codestream_info_t *cstr_info, unsigned short int type, int pos, int len) { - - if (!cstr_info) - return; - - /* expand the list? */ - if ((cstr_info->marknum + 1) > cstr_info->maxmarknum) { - cstr_info->maxmarknum += 100; - cstr_info->marker = (opj_marker_info_t*)opj_realloc(cstr_info->marker, cstr_info->maxmarknum * sizeof(opj_marker_info_t)); - } - - /* add the marker */ - cstr_info->marker[cstr_info->marknum].type = type; - cstr_info->marker[cstr_info->marknum].pos = pos; - cstr_info->marker[cstr_info->marknum].len = len; - cstr_info->marknum++; - -} - -void jpwl_prepare_marks(opj_j2k_t *j2k, opj_cio_t *cio, opj_image_t *image) { - - unsigned short int socsiz_len = 0; - int ciopos = cio_tell(cio), soc_pos = j2k->cstr_info->main_head_start; - unsigned char *socp = NULL; - - int tileno, acc_tpno, tpno, tilespec, hprot, sens, pprot, packspec, lastileno, packno; - - jpwl_epb_ms_t *epb_mark; - jpwl_epc_ms_t *epc_mark; - jpwl_esd_ms_t *esd_mark; - - /* find (SOC + SIZ) length */ - /* I assume SIZ is always the first marker after SOC */ - cio_seek(cio, soc_pos + 4); - socsiz_len = (unsigned short int) cio_read(cio, 2) + 4; /* add the 2 marks length itself */ - cio_seek(cio, soc_pos + 0); - socp = cio_getbp(cio); /* pointer to SOC */ - - /* - EPC MS for Main Header: if we are here it's required - */ - /* create the EPC */ - if ((epc_mark = jpwl_epc_create( - j2k, - j2k->cp->esd_on, /* is ESD present? */ - j2k->cp->red_on, /* is RED present? */ - j2k->cp->epb_on, /* is EPB present? */ - OPJ_FALSE /* are informative techniques present? */ - ))) { - - /* Add this marker to the 'insertanda' list */ - if (epc_mark) { - jwmarker[jwmarker_num].id = J2K_MS_EPC; /* its type */ - jwmarker[jwmarker_num].m.epcmark = epc_mark; /* the EPC */ - jwmarker[jwmarker_num].pos = soc_pos + socsiz_len; /* after SIZ */ - jwmarker[jwmarker_num].dpos = (double) jwmarker[jwmarker_num].pos + 0.1; /* not so first */ - jwmarker[jwmarker_num].len = epc_mark->Lepc; /* its length */ - jwmarker[jwmarker_num].len_ready = OPJ_TRUE; /* ready */ - jwmarker[jwmarker_num].pos_ready = OPJ_TRUE; /* ready */ - jwmarker[jwmarker_num].parms_ready = OPJ_FALSE; /* not ready */ - jwmarker[jwmarker_num].data_ready = OPJ_TRUE; /* ready */ - jwmarker_num++; - }; - - opj_event_msg(j2k->cinfo, EVT_INFO, - "MH EPC : setting %s%s%s\n", - j2k->cp->esd_on ? "ESD, " : "", - j2k->cp->red_on ? "RED, " : "", - j2k->cp->epb_on ? "EPB, " : "" - ); - - } else { - /* ooops, problems */ - opj_event_msg(j2k->cinfo, EVT_ERROR, "Could not create MH EPC\n"); - }; - - /* - ESD MS for Main Header - */ - /* first of all, must MH have an ESD MS? */ - if (j2k->cp->esd_on && (j2k->cp->sens_MH >= 0)) { - - /* Create the ESD */ - if ((esd_mark = jpwl_esd_create( - j2k, /* this encoder handle */ - -1, /* we are averaging over all components */ - (unsigned char) j2k->cp->sens_range, /* range method */ - (unsigned char) j2k->cp->sens_addr, /* sensitivity addressing */ - (unsigned char) j2k->cp->sens_MH, /* sensitivity method */ - j2k->cp->sens_size, /* sensitivity size */ - -1, /* this ESD is in main header */ - 0 /*j2k->cstr_info->num*/, /* number of packets in codestream */ - NULL /*sensval*/ /* pointer to sensitivity data of packets */ - ))) { - - /* Add this marker to the 'insertanda' list */ - if (jwmarker_num < JPWL_MAX_NO_MARKERS) { - jwmarker[jwmarker_num].id = J2K_MS_ESD; /* its type */ - jwmarker[jwmarker_num].m.esdmark = esd_mark; /* the EPB */ - jwmarker[jwmarker_num].pos = soc_pos + socsiz_len; /* we choose to place it after SIZ */ - jwmarker[jwmarker_num].dpos = (double) jwmarker[jwmarker_num].pos + 0.2; /* not first at all! */ - jwmarker[jwmarker_num].len = esd_mark->Lesd; /* its length */ - jwmarker[jwmarker_num].len_ready = OPJ_TRUE; /* not ready, yet */ - jwmarker[jwmarker_num].pos_ready = OPJ_TRUE; /* ready */ - jwmarker[jwmarker_num].parms_ready = OPJ_TRUE; /* not ready */ - jwmarker[jwmarker_num].data_ready = OPJ_FALSE; /* not ready */ - jwmarker_num++; - } - - opj_event_msg(j2k->cinfo, EVT_INFO, - "MH ESDs: method %d\n", - j2k->cp->sens_MH - ); - - } else { - /* ooops, problems */ - opj_event_msg(j2k->cinfo, EVT_ERROR, "Could not create MH ESD\n"); - }; - - } - - /* - ESD MSs for Tile Part Headers - */ - /* cycle through tiles */ - sens = -1; /* default spec: no ESD */ - tilespec = 0; /* first tile spec */ - acc_tpno = 0; - for (tileno = 0; tileno < j2k->cstr_info->tw * j2k->cstr_info->th; tileno++) { - - opj_event_msg(j2k->cinfo, EVT_INFO, - "Tile %d has %d tile part(s)\n", - tileno, j2k->cstr_info->tile[tileno].num_tps - ); - - /* for every tile part in the tile */ - for (tpno = 0; tpno < j2k->cstr_info->tile[tileno].num_tps; tpno++, acc_tpno++) { - - int sot_len, Psot, Psotp, mm; - unsigned long sot_pos, post_sod_pos; - - unsigned long int left_THmarks_len; - - /******* sot_pos = j2k->cstr_info->tile[tileno].start_pos; */ - sot_pos = j2k->cstr_info->tile[tileno].tp[tpno].tp_start_pos; - cio_seek(cio, sot_pos + 2); - sot_len = cio_read(cio, 2); /* SOT Len */ - cio_skip(cio, 2); - Psotp = cio_tell(cio); - Psot = cio_read(cio, 4); /* tile length */ - - /******* post_sod_pos = j2k->cstr_info->tile[tileno].end_header + 1; */ - post_sod_pos = j2k->cstr_info->tile[tileno].tp[tpno].tp_end_header + 1; - left_THmarks_len = post_sod_pos - sot_pos; - - /* add all the lengths of the markers which are len-ready and stay within SOT and SOD */ - for (mm = 0; mm < jwmarker_num; mm++) { - if ((jwmarker[mm].pos >= sot_pos) && (jwmarker[mm].pos < post_sod_pos)) { - if (jwmarker[mm].len_ready) - left_THmarks_len += jwmarker[mm].len + 2; - else { - opj_event_msg(j2k->cinfo, EVT_ERROR, "MS %x in %f is not len-ready: could not set up TH EPB\n", - jwmarker[mm].id, jwmarker[mm].dpos); - exit(1); - } - } - } - - /******* if ((tilespec < JPWL_MAX_NO_TILESPECS) && (j2k->cp->sens_TPH_tileno[tilespec] == tileno)) */ - if ((tilespec < JPWL_MAX_NO_TILESPECS) && (j2k->cp->sens_TPH_tileno[tilespec] == acc_tpno)) - /* we got a specification from this tile onwards */ - sens = j2k->cp->sens_TPH[tilespec++]; - - /* must this TPH have an ESD MS? */ - if (j2k->cp->esd_on && (sens >= 0)) { - - /* Create the ESD */ - if ((esd_mark = jpwl_esd_create( - j2k, /* this encoder handle */ - -1, /* we are averaging over all components */ - (unsigned char) j2k->cp->sens_range, /* range method */ - (unsigned char) j2k->cp->sens_addr, /* sensitivity addressing size */ - (unsigned char) sens, /* sensitivity method */ - j2k->cp->sens_size, /* sensitivity value size */ - tileno, /* this ESD is in a tile */ - 0, /* number of packets in codestream */ - NULL /* pointer to sensitivity data of packets */ - ))) { - - /* Add this marker to the 'insertanda' list */ - if (jwmarker_num < JPWL_MAX_NO_MARKERS) { - jwmarker[jwmarker_num].id = J2K_MS_ESD; /* its type */ - jwmarker[jwmarker_num].m.esdmark = esd_mark; /* the EPB */ - /****** jwmarker[jwmarker_num].pos = j2k->cstr_info->tile[tileno].start_pos + sot_len + 2; */ /* after SOT */ - jwmarker[jwmarker_num].pos = j2k->cstr_info->tile[tileno].tp[tpno].tp_start_pos + sot_len + 2; /* after SOT */ - jwmarker[jwmarker_num].dpos = (double) jwmarker[jwmarker_num].pos + 0.2; /* not first at all! */ - jwmarker[jwmarker_num].len = esd_mark->Lesd; /* its length */ - jwmarker[jwmarker_num].len_ready = OPJ_TRUE; /* ready, yet */ - jwmarker[jwmarker_num].pos_ready = OPJ_TRUE; /* ready */ - jwmarker[jwmarker_num].parms_ready = OPJ_TRUE; /* not ready */ - jwmarker[jwmarker_num].data_ready = OPJ_FALSE; /* ready */ - jwmarker_num++; - } - - /* update Psot of the tile */ - cio_seek(cio, Psotp); - cio_write(cio, Psot + esd_mark->Lesd + 2, 4); - - opj_event_msg(j2k->cinfo, EVT_INFO, - /******* "TPH ESDs: tile %02d, method %d\n", */ - "TPH ESDs: tile %02d, part %02d, method %d\n", - /******* tileno, */ - tileno, tpno, - sens - ); - - } else { - /* ooops, problems */ - /***** opj_event_msg(j2k->cinfo, EVT_ERROR, "Could not create TPH ESD #%d\n", tileno); */ - opj_event_msg(j2k->cinfo, EVT_ERROR, "Could not create TPH ESD #%d,%d\n", tileno, tpno); - }; - - } - - } - - }; - - /* - EPB MS for Main Header - */ - /* first of all, must MH have an EPB MS? */ - if (j2k->cp->epb_on && (j2k->cp->hprot_MH > 0)) { - - int mm; - - /* position of SOT */ - unsigned int sot_pos = j2k->cstr_info->main_head_end + 1; - - /* how much space is there between end of SIZ and beginning of SOT? */ - int left_MHmarks_len = sot_pos - socsiz_len; - - /* add all the lengths of the markers which are len-ready and stay within SOC and SOT */ - for (mm = 0; mm < jwmarker_num; mm++) { - if ((jwmarker[mm].pos >=0) && (jwmarker[mm].pos < sot_pos)) { - if (jwmarker[mm].len_ready) - left_MHmarks_len += jwmarker[mm].len + 2; - else { - opj_event_msg(j2k->cinfo, EVT_ERROR, "MS %x in %f is not len-ready: could not set up MH EPB\n", - jwmarker[mm].id, jwmarker[mm].dpos); - exit(1); - } - } - } - - /* Create the EPB */ - if ((epb_mark = jpwl_epb_create( - j2k, /* this encoder handle */ - OPJ_TRUE, /* is it the latest? */ - OPJ_TRUE, /* is it packed? not for now */ - -1, /* we are in main header */ - 0, /* its index is 0 (first) */ - j2k->cp->hprot_MH, /* protection type parameters of data */ - socsiz_len, /* pre-data: only SOC+SIZ */ - left_MHmarks_len /* post-data: from SOC to SOT, and all JPWL markers within */ - ))) { - - /* Add this marker to the 'insertanda' list */ - if (jwmarker_num < JPWL_MAX_NO_MARKERS) { - jwmarker[jwmarker_num].id = J2K_MS_EPB; /* its type */ - jwmarker[jwmarker_num].m.epbmark = epb_mark; /* the EPB */ - jwmarker[jwmarker_num].pos = soc_pos + socsiz_len; /* after SIZ */ - jwmarker[jwmarker_num].dpos = (double) jwmarker[jwmarker_num].pos; /* first first first! */ - jwmarker[jwmarker_num].len = epb_mark->Lepb; /* its length */ - jwmarker[jwmarker_num].len_ready = OPJ_TRUE; /* ready */ - jwmarker[jwmarker_num].pos_ready = OPJ_TRUE; /* ready */ - jwmarker[jwmarker_num].parms_ready = OPJ_TRUE; /* ready */ - jwmarker[jwmarker_num].data_ready = OPJ_FALSE; /* not ready */ - jwmarker_num++; - } - - opj_event_msg(j2k->cinfo, EVT_INFO, - "MH EPB : prot. %d\n", - j2k->cp->hprot_MH - ); - - } else { - /* ooops, problems */ - opj_event_msg(j2k->cinfo, EVT_ERROR, "Could not create MH EPB\n"); - }; - } - - /* - EPB MSs for Tile Parts - */ - /* cycle through TPHs */ - hprot = j2k->cp->hprot_MH; /* default spec */ - tilespec = 0; /* first tile spec */ - lastileno = 0; - packspec = 0; - pprot = -1; - acc_tpno = 0; - for (tileno = 0; tileno < j2k->cstr_info->tw * j2k->cstr_info->th; tileno++) { - - opj_event_msg(j2k->cinfo, EVT_INFO, - "Tile %d has %d tile part(s)\n", - tileno, j2k->cstr_info->tile[tileno].num_tps - ); - - /* for every tile part in the tile */ - for (tpno = 0; tpno < j2k->cstr_info->tile[tileno].num_tps; tpno++, acc_tpno++) { - - int sot_len, Psot, Psotp, mm, epb_index = 0, prot_len = 0; - unsigned long sot_pos, post_sod_pos; - unsigned long int left_THmarks_len/*, epbs_len = 0*/; - int startpack = 0, stoppack = j2k->cstr_info->packno; - int first_tp_pack, last_tp_pack; - jpwl_epb_ms_t *tph_epb = NULL; - - /****** sot_pos = j2k->cstr_info->tile[tileno].start_pos; */ - sot_pos = j2k->cstr_info->tile[tileno].tp[tpno].tp_start_pos; - cio_seek(cio, sot_pos + 2); - sot_len = cio_read(cio, 2); /* SOT Len */ - cio_skip(cio, 2); - Psotp = cio_tell(cio); - Psot = cio_read(cio, 4); /* tile length */ - - /* a-priori length of the data dwelling between SOT and SOD */ - /****** post_sod_pos = j2k->cstr_info->tile[tileno].end_header + 1; */ - post_sod_pos = j2k->cstr_info->tile[tileno].tp[tpno].tp_end_header + 1; - left_THmarks_len = post_sod_pos - (sot_pos + sot_len + 2); - - /* add all the lengths of the JPWL markers which are len-ready and stay within SOT and SOD */ - for (mm = 0; mm < jwmarker_num; mm++) { - if ((jwmarker[mm].pos >= sot_pos) && (jwmarker[mm].pos < post_sod_pos)) { - if (jwmarker[mm].len_ready) - left_THmarks_len += jwmarker[mm].len + 2; - else { - opj_event_msg(j2k->cinfo, EVT_ERROR, "MS %x in %f is not len-ready: could not set up TH EPB\n", - jwmarker[mm].id, jwmarker[mm].dpos); - exit(1); - } - } - } - - /****** if ((tilespec < JPWL_MAX_NO_TILESPECS) && (j2k->cp->hprot_TPH_tileno[tilespec] == tileno)) */ - if ((tilespec < JPWL_MAX_NO_TILESPECS) && (j2k->cp->hprot_TPH_tileno[tilespec] == acc_tpno)) - /* we got a specification from this tile part onwards */ - hprot = j2k->cp->hprot_TPH[tilespec++]; - - /* must this TPH have an EPB MS? */ - if (j2k->cp->epb_on && (hprot > 0)) { - - /* Create the EPB */ - if ((epb_mark = jpwl_epb_create( - j2k, /* this encoder handle */ - OPJ_FALSE, /* is it the latest? in TPH, no for now (if huge data size in TPH, we'd need more) */ - OPJ_TRUE, /* is it packed? yes for now */ - tileno, /* we are in TPH */ - epb_index++, /* its index is 0 (first) */ - hprot, /* protection type parameters of following data */ - sot_len + 2, /* pre-data length: only SOT */ - left_THmarks_len /* post-data length: from SOT end to SOD inclusive */ - ))) { - - /* Add this marker to the 'insertanda' list */ - if (jwmarker_num < JPWL_MAX_NO_MARKERS) { - jwmarker[jwmarker_num].id = J2K_MS_EPB; /* its type */ - jwmarker[jwmarker_num].m.epbmark = epb_mark; /* the EPB */ - /****** jwmarker[jwmarker_num].pos = j2k->cstr_info->tile[tileno].start_pos + sot_len + 2; */ /* after SOT */ - jwmarker[jwmarker_num].pos = j2k->cstr_info->tile[tileno].tp[tpno].tp_start_pos + sot_len + 2; /* after SOT */ - jwmarker[jwmarker_num].dpos = (double) jwmarker[jwmarker_num].pos; /* first first first! */ - jwmarker[jwmarker_num].len = epb_mark->Lepb; /* its length */ - jwmarker[jwmarker_num].len_ready = OPJ_TRUE; /* ready */ - jwmarker[jwmarker_num].pos_ready = OPJ_TRUE; /* ready */ - jwmarker[jwmarker_num].parms_ready = OPJ_TRUE; /* ready */ - jwmarker[jwmarker_num].data_ready = OPJ_FALSE; /* not ready */ - jwmarker_num++; - } - - /* update Psot of the tile */ - Psot += epb_mark->Lepb + 2; - - opj_event_msg(j2k->cinfo, EVT_INFO, - /***** "TPH EPB : tile %02d, prot. %d\n", */ - "TPH EPB : tile %02d, part %02d, prot. %d\n", - /***** tileno, */ - tileno, tpno, - hprot - ); - - /* save this TPH EPB address */ - tph_epb = epb_mark; - - } else { - /* ooops, problems */ - /****** opj_event_msg(j2k->cinfo, EVT_ERROR, "Could not create TPH EPB #%d\n", tileno); */ - opj_event_msg(j2k->cinfo, EVT_ERROR, "Could not create TPH EPB in #%d,d\n", tileno, tpno); - }; - - } - - startpack = 0; - /* EPB MSs for UEP packet data protection in Tile Parts */ - /****** for (packno = 0; packno < j2k->cstr_info->num; packno++) { */ - /*first_tp_pack = (tpno > 0) ? (first_tp_pack + j2k->cstr_info->tile[tileno].tp[tpno - 1].tp_numpacks) : 0;*/ - first_tp_pack = j2k->cstr_info->tile[tileno].tp[tpno].tp_start_pack; - last_tp_pack = first_tp_pack + j2k->cstr_info->tile[tileno].tp[tpno].tp_numpacks - 1; - for (packno = 0; packno < j2k->cstr_info->tile[tileno].tp[tpno].tp_numpacks; packno++) { - - /******** if ((packspec < JPWL_MAX_NO_PACKSPECS) && - (j2k->cp->pprot_tileno[packspec] == tileno) && (j2k->cp->pprot_packno[packspec] == packno)) { */ - if ((packspec < JPWL_MAX_NO_PACKSPECS) && - (j2k->cp->pprot_tileno[packspec] == acc_tpno) && (j2k->cp->pprot_packno[packspec] == packno)) { - - /* we got a specification from this tile and packet onwards */ - /* print the previous spec */ - if (packno > 0) { - stoppack = packno - 1; - opj_event_msg(j2k->cinfo, EVT_INFO, - /***** "UEP EPBs: tile %02d, packs. %02d-%02d (B %d-%d), prot. %d\n", */ - "UEP EPBs: tile %02d, part %02d, packs. %02d-%02d (B %d-%d), prot. %d\n", - /***** tileno, */ - tileno, tpno, - startpack, - stoppack, - /***** j2k->cstr_info->tile[tileno].packet[startpack].start_pos, */ - j2k->cstr_info->tile[tileno].packet[first_tp_pack + startpack].start_pos, - /***** j2k->cstr_info->tile[tileno].packet[stoppack].end_pos, */ - j2k->cstr_info->tile[tileno].packet[first_tp_pack + stoppack].end_pos, - pprot); - - /***** prot_len = j2k->cstr_info->tile[tileno].packet[stoppack].end_pos + 1 - - j2k->cstr_info->tile[tileno].packet[startpack].start_pos; */ - prot_len = j2k->cstr_info->tile[tileno].packet[first_tp_pack + stoppack].end_pos + 1 - - j2k->cstr_info->tile[tileno].packet[first_tp_pack + startpack].start_pos; - - /* - particular case: if this is the last header and the last packet, - then it is better to protect even the EOC marker - */ - /****** if ((tileno == ((j2k->cstr_info->tw * j2k->cstr_info->th) - 1)) && - (stoppack == (j2k->cstr_info->num - 1))) */ - if ((tileno == ((j2k->cstr_info->tw * j2k->cstr_info->th) - 1)) && - (tpno == (j2k->cstr_info->tile[tileno].num_tps - 1)) && - (stoppack == last_tp_pack)) - /* add the EOC len */ - prot_len += 2; - - /* let's add the EPBs */ - Psot += jpwl_epbs_add( - j2k, /* J2K handle */ - jwmarker, /* pointer to JPWL markers list */ - &jwmarker_num, /* pointer to the number of current markers */ - OPJ_FALSE, /* latest */ - OPJ_TRUE, /* packed */ - OPJ_FALSE, /* inside MH */ - &epb_index, /* pointer to EPB index */ - pprot, /* protection type */ - /****** (double) (j2k->cstr_info->tile[tileno].start_pos + sot_len + 2) + 0.0001, */ /* position */ - (double) (j2k->cstr_info->tile[tileno].tp[tpno].tp_start_pos + sot_len + 2) + 0.0001, /* position */ - tileno, /* number of tile */ - 0, /* length of pre-data */ - prot_len /*4000*/ /* length of post-data */ - ); - } - - startpack = packno; - pprot = j2k->cp->pprot[packspec++]; - } - - //printf("Tile %02d, pack %02d ==> %d\n", tileno, packno, pprot); - - } - - /* we are at the end: print the remaining spec */ - stoppack = packno - 1; - if (pprot >= 0) { - - opj_event_msg(j2k->cinfo, EVT_INFO, - /**** "UEP EPBs: tile %02d, packs. %02d-%02d (B %d-%d), prot. %d\n", */ - "UEP EPBs: tile %02d, part %02d, packs. %02d-%02d (B %d-%d), prot. %d\n", - /**** tileno, */ - tileno, tpno, - startpack, - stoppack, - /***** j2k->image_info->tile[tileno].packet[startpack].start_pos, - j2k->image_info->tile[tileno].packet[stoppack].end_pos, */ - j2k->cstr_info->tile[tileno].packet[first_tp_pack + startpack].start_pos, - j2k->cstr_info->tile[tileno].packet[first_tp_pack + stoppack].end_pos, - pprot); - - /***** prot_len = j2k->cstr_info->tile[tileno].packet[stoppack].end_pos + 1 - - j2k->cstr_info->tile[tileno].packet[startpack].start_pos; */ - prot_len = j2k->cstr_info->tile[tileno].packet[first_tp_pack + stoppack].end_pos + 1 - - j2k->cstr_info->tile[tileno].packet[first_tp_pack + startpack].start_pos; - - /* - particular case: if this is the last header and the last packet, - then it is better to protect even the EOC marker - */ - /***** if ((tileno == ((j2k->cstr_info->tw * j2k->cstr_info->th) - 1)) && - (stoppack == (j2k->cstr_info->num - 1))) */ - if ((tileno == ((j2k->cstr_info->tw * j2k->cstr_info->th) - 1)) && - (tpno == (j2k->cstr_info->tile[tileno].num_tps - 1)) && - (stoppack == last_tp_pack)) - /* add the EOC len */ - prot_len += 2; - - /* let's add the EPBs */ - Psot += jpwl_epbs_add( - j2k, /* J2K handle */ - jwmarker, /* pointer to JPWL markers list */ - &jwmarker_num, /* pointer to the number of current markers */ - OPJ_TRUE, /* latest */ - OPJ_TRUE, /* packed */ - OPJ_FALSE, /* inside MH */ - &epb_index, /* pointer to EPB index */ - pprot, /* protection type */ - /***** (double) (j2k->cstr_info->tile[tileno].start_pos + sot_len + 2) + 0.0001,*/ /* position */ - (double) (j2k->cstr_info->tile[tileno].tp[tpno].tp_start_pos + sot_len + 2) + 0.0001, /* position */ - tileno, /* number of tile */ - 0, /* length of pre-data */ - prot_len /*4000*/ /* length of post-data */ - ); - } - - /* we can now check if the TPH EPB was really the last one */ - if (tph_epb && (epb_index == 1)) { - /* set the TPH EPB to be the last one in current header */ - tph_epb->Depb |= (unsigned char) ((OPJ_TRUE & 0x0001) << 6); - tph_epb = NULL; - } - - /* write back Psot */ - cio_seek(cio, Psotp); - cio_write(cio, Psot, 4); - - } - - }; - - /* reset the position */ - cio_seek(cio, ciopos); - -} - -void jpwl_dump_marks(opj_j2k_t *j2k, opj_cio_t *cio, opj_image_t *image) { - - int mm; - unsigned long int old_size = j2k->cstr_info->codestream_size; - unsigned long int new_size = old_size; - int /*ciopos = cio_tell(cio),*/ soc_pos = j2k->cstr_info->main_head_start; - unsigned char *jpwl_buf, *orig_buf; - unsigned long int orig_pos; - double epbcoding_time = 0.0, esdcoding_time = 0.0; - - /* Order JPWL markers according to their wishlist position */ - qsort((void *) jwmarker, (size_t) jwmarker_num, sizeof (jpwl_marker_t), jpwl_markcomp); - - /* compute markers total size */ - for (mm = 0; mm < jwmarker_num; mm++) { - /*printf("%x, %d, %.10f, %d long\n", jwmarker[mm].id, jwmarker[mm].pos, - jwmarker[mm].dpos, jwmarker[mm].len);*/ - new_size += jwmarker[mm].len + 2; - } - - /* allocate a new buffer of proper size */ - if (!(jpwl_buf = (unsigned char *) opj_malloc((size_t) (new_size + soc_pos) * sizeof(unsigned char)))) { - opj_event_msg(j2k->cinfo, EVT_ERROR, "Could not allocate room for JPWL codestream buffer\n"); - exit(1); - }; - - /* copy the jp2 part, if any */ - orig_buf = jpwl_buf; - memcpy(jpwl_buf, cio->buffer, soc_pos); - jpwl_buf += soc_pos; - - /* cycle through markers */ - orig_pos = soc_pos + 0; /* start from the beginning */ - cio_seek(cio, soc_pos + 0); /* rewind the original */ - for (mm = 0; mm < jwmarker_num; mm++) { - - /* - need to copy a piece of the original codestream - if there is such - */ - memcpy(jpwl_buf, cio_getbp(cio), jwmarker[mm].pos - orig_pos); - jpwl_buf += jwmarker[mm].pos - orig_pos; - orig_pos = jwmarker[mm].pos; - cio_seek(cio, orig_pos); - - /* - then write down the marker - */ - switch (jwmarker[mm].id) { - - case J2K_MS_EPB: - jpwl_epb_write(j2k, jwmarker[mm].m.epbmark, jpwl_buf); - break; - - case J2K_MS_EPC: - jpwl_epc_write(j2k, jwmarker[mm].m.epcmark, jpwl_buf); - break; - - case J2K_MS_ESD: - jpwl_esd_write(j2k, jwmarker[mm].m.esdmark, jpwl_buf); - break; - - case J2K_MS_RED: - memset(jpwl_buf, 0, jwmarker[mm].len + 2); /* placeholder */ - break; - - default: - break; - }; - - /* we update the markers struct */ - if (j2k->cstr_info) - j2k->cstr_info->marker[j2k->cstr_info->marknum - 1].pos = (jpwl_buf - orig_buf); - - /* we set the marker dpos to the new position in the JPWL codestream */ - jwmarker[mm].dpos = (double) (jpwl_buf - orig_buf); - - /* advance JPWL buffer position */ - jpwl_buf += jwmarker[mm].len + 2; - - } - - /* finish remaining original codestream */ - memcpy(jpwl_buf, cio_getbp(cio), old_size - (orig_pos - soc_pos)); - jpwl_buf += old_size - (orig_pos - soc_pos); - cio_seek(cio, soc_pos + old_size); - - /* - update info file based on added markers - */ - if (!jpwl_update_info(j2k, jwmarker, jwmarker_num)) - opj_event_msg(j2k->cinfo, EVT_ERROR, "Could not update OPJ cstr_info structure\n"); - - /* now we need to repass some markers and fill their data fields */ - - /* first of all, DL and Pcrc in EPCs */ - for (mm = 0; mm < jwmarker_num; mm++) { - - /* find the EPCs */ - if (jwmarker[mm].id == J2K_MS_EPC) { - - int epc_pos = (int) jwmarker[mm].dpos, pp; - unsigned short int mycrc = 0x0000; - - /* fix and fill the DL field */ - jwmarker[mm].m.epcmark->DL = new_size; - orig_buf[epc_pos + 6] = (unsigned char) (jwmarker[mm].m.epcmark->DL >> 24); - orig_buf[epc_pos + 7] = (unsigned char) (jwmarker[mm].m.epcmark->DL >> 16); - orig_buf[epc_pos + 8] = (unsigned char) (jwmarker[mm].m.epcmark->DL >> 8); - orig_buf[epc_pos + 9] = (unsigned char) (jwmarker[mm].m.epcmark->DL >> 0); - - /* compute the CRC field (excluding itself) */ - for (pp = 0; pp < 4; pp++) - jpwl_updateCRC16(&mycrc, orig_buf[epc_pos + pp]); - for (pp = 6; pp < (jwmarker[mm].len + 2); pp++) - jpwl_updateCRC16(&mycrc, orig_buf[epc_pos + pp]); - - /* fix and fill the CRC */ - jwmarker[mm].m.epcmark->Pcrc = mycrc; - orig_buf[epc_pos + 4] = (unsigned char) (jwmarker[mm].m.epcmark->Pcrc >> 8); - orig_buf[epc_pos + 5] = (unsigned char) (jwmarker[mm].m.epcmark->Pcrc >> 0); - - } - } - - /* then, sensitivity data in ESDs */ - esdcoding_time = opj_clock(); - for (mm = 0; mm < jwmarker_num; mm++) { - - /* find the ESDs */ - if (jwmarker[mm].id == J2K_MS_ESD) { - - /* remember that they are now in a new position (dpos) */ - int esd_pos = (int) jwmarker[mm].dpos; - - jpwl_esd_fill(j2k, jwmarker[mm].m.esdmark, &orig_buf[esd_pos]); - - } - - } - esdcoding_time = opj_clock() - esdcoding_time; - if (j2k->cp->esd_on) - opj_event_msg(j2k->cinfo, EVT_INFO, "ESDs sensitivities computed in %f s\n", esdcoding_time); - - /* finally, RS or CRC parity in EPBs */ - epbcoding_time = opj_clock(); - for (mm = 0; mm < jwmarker_num; mm++) { - - /* find the EPBs */ - if (jwmarker[mm].id == J2K_MS_EPB) { - - /* remember that they are now in a new position (dpos) */ - int nn, accum_len; - - /* let's see how many EPBs are following this one, included itself */ - /* for this to work, we suppose that the markers are correctly ordered */ - /* and, overall, that they are in packed mode inside headers */ - accum_len = 0; - for (nn = mm; (nn < jwmarker_num) && (jwmarker[nn].id == J2K_MS_EPB) && - (jwmarker[nn].pos == jwmarker[mm].pos); nn++) - accum_len += jwmarker[nn].m.epbmark->Lepb + 2; - - /* fill the current (first) EPB with post-data starting from the computed position */ - jpwl_epb_fill(j2k, jwmarker[mm].m.epbmark, &orig_buf[(int) jwmarker[mm].dpos], - &orig_buf[(int) jwmarker[mm].dpos + accum_len]); - - /* fill the remaining EPBs in the header with post-data starting from the last position */ - for (nn = mm + 1; (nn < jwmarker_num) && (jwmarker[nn].id == J2K_MS_EPB) && - (jwmarker[nn].pos == jwmarker[mm].pos); nn++) - jpwl_epb_fill(j2k, jwmarker[nn].m.epbmark, &orig_buf[(int) jwmarker[nn].dpos], NULL); - - /* skip all the processed EPBs */ - mm = nn - 1; - } - - } - epbcoding_time = opj_clock() - epbcoding_time; - if (j2k->cp->epb_on) - opj_event_msg(j2k->cinfo, EVT_INFO, "EPBs redundancy computed in %f s\n", epbcoding_time); - - /* free original cio buffer and set it to the JPWL one */ - opj_free(cio->buffer); - cio->cinfo = cio->cinfo; /* no change */ - cio->openmode = cio->openmode; /* no change */ - cio->buffer = orig_buf; - cio->length = new_size + soc_pos; - cio->start = cio->buffer; - cio->end = cio->buffer + cio->length; - cio->bp = cio->buffer; - cio_seek(cio, soc_pos + new_size); - -} - - -void j2k_read_epc(opj_j2k_t *j2k) { - unsigned long int DL, Lepcp, Pcrcp, l; - unsigned short int Lepc, Pcrc = 0x0000; - unsigned char Pepc; - opj_cio_t *cio = j2k->cio; - const char *ans1; - - /* Simply read the EPC parameters */ - Lepcp = cio_tell(cio); - Lepc = cio_read(cio, 2); - Pcrcp = cio_tell(cio); - cio_skip(cio, 2); /* Pcrc */ - DL = cio_read(cio, 4); - Pepc = cio_read(cio, 1); - - /* compute Pcrc */ - cio_seek(cio, Lepcp - 2); - - /* Marker */ - jpwl_updateCRC16(&Pcrc, (unsigned char) cio_read(cio, 1)); - jpwl_updateCRC16(&Pcrc, (unsigned char) cio_read(cio, 1)); - - /* Length */ - jpwl_updateCRC16(&Pcrc, (unsigned char) cio_read(cio, 1)); - jpwl_updateCRC16(&Pcrc, (unsigned char) cio_read(cio, 1)); - - /* skip Pcrc */ - cio_skip(cio, 2); - - /* read all remaining */ - for (l = 4; l < Lepc; l++) - jpwl_updateCRC16(&Pcrc, (unsigned char) cio_read(cio, 1)); - - /* check Pcrc with the result */ - cio_seek(cio, Pcrcp); - ans1 = (Pcrc == (unsigned short int) cio_read(cio, 2)) ? "crc-ok" : "crc-ko"; - - /* now we write them to screen */ - opj_event_msg(j2k->cinfo, EVT_INFO, - "EPC(%u,%d): %s, DL=%d%s %s %s\n", - Lepcp - 2, - Lepc, - ans1, - DL, /* data length this EPC is referring to */ - (Pepc & 0x10) ? ", esd" : "", /* ESD is present */ - (Pepc & 0x20) ? ", red" : "", /* RED is present */ - (Pepc & 0x40) ? ", epb" : ""); /* EPB is present */ - - cio_seek(cio, Lepcp + Lepc); -} - -void j2k_write_epc(opj_j2k_t *j2k) { - - unsigned long int DL, Lepcp, Pcrcp, l; - unsigned short int Lepc, Pcrc; - unsigned char Pepc; - - opj_cio_t *cio = j2k->cio; - - cio_write(cio, J2K_MS_EPC, 2); /* EPC */ - Lepcp = cio_tell(cio); - cio_skip(cio, 2); - - /* CRC-16 word of the EPC */ - Pcrc = 0x0000; /* initialize */ - Pcrcp = cio_tell(cio); - cio_write(cio, Pcrc, 2); /* Pcrc placeholder*/ - - /* data length of the EPC protection domain */ - DL = 0x00000000; /* we leave this set to 0, as if the information is not available */ - cio_write(cio, DL, 4); /* DL */ - - /* jpwl capabilities */ - Pepc = 0x00; - cio_write(cio, Pepc, 1); /* Pepc */ - - /* ID section */ - /* no ID's, as of now */ - - Lepc = (unsigned short) (cio_tell(cio) - Lepcp); - cio_seek(cio, Lepcp); - cio_write(cio, Lepc, 2); /* Lepc */ - - /* compute Pcrc */ - cio_seek(cio, Lepcp - 2); - - /* Marker */ - jpwl_updateCRC16(&Pcrc, (unsigned char) cio_read(cio, 1)); - jpwl_updateCRC16(&Pcrc, (unsigned char) cio_read(cio, 1)); - - /* Length */ - jpwl_updateCRC16(&Pcrc, (unsigned char) cio_read(cio, 1)); - jpwl_updateCRC16(&Pcrc, (unsigned char) cio_read(cio, 1)); - - /* skip Pcrc */ - cio_skip(cio, 2); - - /* read all remaining */ - for (l = 4; l < Lepc; l++) - jpwl_updateCRC16(&Pcrc, (unsigned char) cio_read(cio, 1)); - - /* fill Pcrc with the result */ - cio_seek(cio, Pcrcp); - cio_write(cio, Pcrc, 2); - - cio_seek(cio, Lepcp + Lepc); - - /* marker struct update */ - j2k_add_marker(j2k->cstr_info, J2K_MS_EPC, Lepcp - 2, Lepc + 2); - -} - -void j2k_read_epb(opj_j2k_t *j2k) { - unsigned long int LDPepb, Pepb; - unsigned short int Lepb; - unsigned char Depb; - char str1[25] = ""; - opj_bool status; - static opj_bool first_in_tph = OPJ_TRUE; - int type, pre_len, post_len; - static unsigned char *redund = NULL; - - opj_cio_t *cio = j2k->cio; - - /* B/W = 45, RGB = 51 */ - /* SIZ SIZ_FIELDS SIZ_COMPS FOLLOWING_MARKER */ - int skipnum = 2 + 38 + 3 * j2k->cp->exp_comps + 2; - - if (j2k->cp->correct) { - - /* go back to EPB marker value */ - cio_seek(cio, cio_tell(cio) - 2); - - /* we need to understand where we are */ - if (j2k->state == J2K_STATE_MH) { - /* we are in MH */ - type = 0; /* MH */ - pre_len = skipnum; /* SOC+SIZ */ - post_len = -1; /* auto */ - - } else if ((j2k->state == J2K_STATE_TPH) && first_in_tph) { - /* we are in TPH */ - type = 1; /* TPH */ - pre_len = 12; /* SOC+SIZ */ - first_in_tph = OPJ_FALSE; - post_len = -1; /* auto */ - - } else { - /* we are elsewhere */ - type = 2; /* other */ - pre_len = 0; /* nada */ - post_len = -1; /* auto */ - - } - - /* call EPB corrector */ - /*printf("before %x, ", redund);*/ - status = jpwl_epb_correct(j2k, /* J2K decompressor handle */ - cio->bp, /* pointer to EPB in codestream buffer */ - type, /* EPB type: MH */ - pre_len, /* length of pre-data */ - post_len, /* length of post-data: -1 means auto */ - NULL, /* do everything auto */ - &redund - ); - /*printf("after %x\n", redund);*/ - - /* Read the (possibly corrected) EPB parameters */ - cio_skip(cio, 2); - Lepb = cio_read(cio, 2); - Depb = cio_read(cio, 1); - LDPepb = cio_read(cio, 4); - Pepb = cio_read(cio, 4); - - if (!status) { - - opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL correction could not be performed\n"); - - /* advance to EPB endpoint */ - cio_skip(cio, Lepb + 2); - - return; - } - - /* last in current header? */ - if (Depb & 0x40) { - redund = NULL; /* reset the pointer to L4 buffer */ - first_in_tph = OPJ_TRUE; - } - - /* advance to EPB endpoint */ - cio_skip(cio, Lepb - 11); - - } else { - - /* Simply read the EPB parameters */ - Lepb = cio_read(cio, 2); - Depb = cio_read(cio, 1); - LDPepb = cio_read(cio, 4); - Pepb = cio_read(cio, 4); - - /* What does Pepb tells us about the protection method? */ - if (((Pepb & 0xF0000000) >> 28) == 0) - sprintf(str1, "pred"); /* predefined */ - else if (((Pepb & 0xF0000000) >> 28) == 1) - sprintf(str1, "crc-%lu", 16 * ((Pepb & 0x00000001) + 1)); /* CRC mode */ - else if (((Pepb & 0xF0000000) >> 28) == 2) - sprintf(str1, "rs(%lu,32)", (Pepb & 0x0000FF00) >> 8); /* RS mode */ - else if (Pepb == 0xFFFFFFFF) - sprintf(str1, "nometh"); /* RS mode */ - else - sprintf(str1, "unknown"); /* unknown */ - - /* Now we write them to screen */ - opj_event_msg(j2k->cinfo, EVT_INFO, - "EPB(%d): (%sl, %sp, %u), %lu, %s\n", - cio_tell(cio) - 13, - (Depb & 0x40) ? "" : "n", /* latest EPB or not? */ - (Depb & 0x80) ? "" : "n", /* packed or unpacked EPB? */ - (Depb & 0x3F), /* EPB index value */ - LDPepb, /*length of the data protected by the EPB */ - str1); /* protection method */ - - cio_skip(cio, Lepb - 11); - } -} - -void j2k_write_epb(opj_j2k_t *j2k) { - unsigned long int LDPepb, Pepb, Lepbp; - unsigned short int Lepb; - unsigned char Depb; - - opj_cio_t *cio = j2k->cio; - - cio_write(cio, J2K_MS_EPB, 2); /* EPB */ - Lepbp = cio_tell(cio); - cio_skip(cio, 2); - - /* EPB style */ - Depb = 0x00; /* test */ - cio_write(cio, Depb, 1); /* Depb */ - - /* length of the data to be protected by this EPB */ - LDPepb = 0x00000000; /* test */ - cio_write(cio, LDPepb, 4); /* LDPepb */ - - /* next error correction tool */ - Pepb = 0x00000000; /* test */ - cio_write(cio, Pepb, 4); /* Pepb */ - - /* EPB data */ - /* no data, as of now */ - - Lepb = (unsigned short) (cio_tell(cio) - Lepbp); - cio_seek(cio, Lepbp); - cio_write(cio, Lepb, 2); /* Lepb */ - - cio_seek(cio, Lepbp + Lepb); - - /* marker struct update */ - j2k_add_marker(j2k->cstr_info, J2K_MS_EPB, Lepbp - 2, Lepb + 2); -} - -void j2k_read_esd(opj_j2k_t *j2k) { - unsigned short int Lesd, Cesd; - unsigned char Pesd; - - int cesdsize = (j2k->image->numcomps >= 257) ? 2 : 1; - - char str1[4][4] = {"p", "br", "pr", "res"}; - char str2[8][8] = {"res", "mse", "mse-r", "psnr", "psnr-i", "maxerr", "tse", "res"}; - - opj_cio_t *cio = j2k->cio; - - /* Simply read the ESD parameters */ - Lesd = cio_read(cio, 2); - Cesd = cio_read(cio, cesdsize); - Pesd = cio_read(cio, 1); - - /* Now we write them to screen */ - opj_event_msg(j2k->cinfo, EVT_INFO, - "ESD(%d): c%d, %s, %s, %s, %s, %s\n", - cio_tell(cio) - (5 + cesdsize), - Cesd, /* component number for this ESD */ - str1[(Pesd & (unsigned char) 0xC0) >> 6], /* addressing mode */ - str2[(Pesd & (unsigned char) 0x38) >> 3], /* sensitivity type */ - ((Pesd & (unsigned char) 0x04) >> 2) ? "2Bs" : "1Bs", - ((Pesd & (unsigned char) 0x02) >> 1) ? "4Ba" : "2Ba", - (Pesd & (unsigned char) 0x01) ? "avgc" : ""); - - cio_skip(cio, Lesd - (3 + cesdsize)); -} - -void j2k_read_red(opj_j2k_t *j2k) { - unsigned short int Lred; - unsigned char Pred; - char str1[4][4] = {"p", "br", "pr", "res"}; - - opj_cio_t *cio = j2k->cio; - - /* Simply read the RED parameters */ - Lred = cio_read(cio, 2); - Pred = cio_read(cio, 1); - - /* Now we write them to screen */ - opj_event_msg(j2k->cinfo, EVT_INFO, - "RED(%d): %s, %dc, %s, %s\n", - cio_tell(cio) - 5, - str1[(Pred & (unsigned char) 0xC0) >> 6], /* addressing mode */ - (Pred & (unsigned char) 0x38) >> 3, /* corruption level */ - ((Pred & (unsigned char) 0x02) >> 1) ? "4Ba" : "2Ba", /* address range */ - (Pred & (unsigned char) 0x01) ? "errs" : "free"); /* error free? */ - - cio_skip(cio, Lred - 3); -} - -opj_bool jpwl_check_tile(opj_j2k_t *j2k, opj_tcd_t *tcd, int tileno) { - -#ifdef oerhgierhgvhreit4u - /* - we navigate through the tile and find possible invalid parameters: - this saves a lot of crashes!!!!! - */ - int compno, resno, precno, /*layno,*/ bandno, blockno; - int numprecincts, numblocks; - - /* this is the selected tile */ - opj_tcd_tile_t *tile = &(tcd->tcd_image->tiles[tileno]); - - /* will keep the component */ - opj_tcd_tilecomp_t *comp = NULL; - - /* will keep the resolution */ - opj_tcd_resolution_t *res; - - /* will keep the subband */ - opj_tcd_band_t *band; - - /* will keep the precinct */ - opj_tcd_precinct_t *prec; - - /* will keep the codeblock */ - opj_tcd_cblk_t *block; - - /* check all tile components */ - for (compno = 0; compno < tile->numcomps; compno++) { - comp = &(tile->comps[compno]); - - /* check all component resolutions */ - for (resno = 0; resno < comp->numresolutions; resno++) { - res = &(comp->resolutions[resno]); - numprecincts = res->pw * res->ph; - - /* check all the subbands */ - for (bandno = 0; bandno < res->numbands; bandno++) { - band = &(res->bands[bandno]); - - /* check all the precincts */ - for (precno = 0; precno < numprecincts; precno++) { - prec = &(band->precincts[precno]); - numblocks = prec->ch * prec->cw; - - /* check all the codeblocks */ - for (blockno = 0; blockno < numblocks; blockno++) { - block = &(prec->cblks[blockno]); - - /* x-origin is invalid */ - if ((block->x0 < prec->x0) || (block->x0 > prec->x1)) { - opj_event_msg(j2k->cinfo, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR, - "JPWL: wrong x-cord of block origin %d => x-prec is (%d, %d)\n", - block->x0, prec->x0, prec->x1); - if (!JPWL_ASSUME || JPWL_ASSUME) - return OPJ_FALSE; - }; - } - } - } - } - } - -#endif - - return OPJ_TRUE; -} - -/*@}*/ - -#endif /* USE_JPWL */ - - -#ifdef USE_JPSEC - -/** @defgroup JPSEC JPSEC - JPEG-2000 Part 8 (JPSEC) codestream manager */ -/*@{*/ - - -/** @name Local static functions */ -/*@{*/ - -void j2k_read_sec(opj_j2k_t *j2k) { - unsigned short int Lsec; - - opj_cio_t *cio = j2k->cio; - - /* Simply read the SEC length */ - Lsec = cio_read(cio, 2); - - /* Now we write them to screen */ - opj_event_msg(j2k->cinfo, EVT_INFO, - "SEC(%d)\n", - cio_tell(cio) - 2 - ); - - cio_skip(cio, Lsec - 2); -} - -void j2k_write_sec(opj_j2k_t *j2k) { - unsigned short int Lsec = 24; - int i; - - opj_cio_t *cio = j2k->cio; - - cio_write(cio, J2K_MS_SEC, 2); /* SEC */ - cio_write(cio, Lsec, 2); - - /* write dummy data */ - for (i = 0; i < Lsec - 2; i++) - cio_write(cio, 0, 1); -} - -void j2k_read_insec(opj_j2k_t *j2k) { - unsigned short int Linsec; - - opj_cio_t *cio = j2k->cio; - - /* Simply read the INSEC length */ - Linsec = cio_read(cio, 2); - - /* Now we write them to screen */ - opj_event_msg(j2k->cinfo, EVT_INFO, - "INSEC(%d)\n", - cio_tell(cio) - 2 - ); - - cio_skip(cio, Linsec - 2); -} - - -/*@}*/ - -/*@}*/ - -#endif /* USE_JPSEC */ - diff --git a/openjpeg-dotnet/libopenjpeg/jpwl/jpwl.h b/openjpeg-dotnet/libopenjpeg/jpwl/jpwl.h deleted file mode 100644 index b77afdd6..00000000 --- a/openjpeg-dotnet/libopenjpeg/jpwl/jpwl.h +++ /dev/null @@ -1,425 +0,0 @@ -/* - * Copyright (c) 2001-2003, David Janssens - * Copyright (c) 2002-2003, Yannick Verschueren - * Copyright (c) 2003-2005, Francois Devaux and Antonin Descampe - * Copyright (c) 2005, Herve Drolon, FreeImage Team - * Copyright (c) 2002-2005, Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium - * Copyright (c) 2005-2006, Dept. of Electronic and Information Engineering, Universita' degli Studi di Perugia, Italy - * 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 __JPWL_H -#define __JPWL_H - -#ifdef USE_JPWL - -#include "crc.h" -#include "rs.h" - -/** -@file jpwl.h -@brief The JPEG-2000 Part11 (JPWL) marker segments manager - -The functions in JPWL.C have for goal to read/write the markers added by JPWL. -*/ - -/** @defgroup JPWL JPWL - JPEG-2000 Part11 (JPWL) codestream manager */ -/*@{*/ - -/** -Assume a basic codestream structure, so you can resort better from uncorrected errors -*/ -#define JPWL_ASSUME OPJ_TRUE - -/** -EPB (Error Protection Block) Marker segment -*/ -typedef struct jpwl_epb_ms { - /**@name Private fields set by epb_create */ - /*@{*/ - /** is the latest in header? */ - opj_bool latest; - /** is it in packed mode? */ - opj_bool packed; - /** TH where this marker has been placed (-1 means MH) */ - int tileno; - /** index in current header (0-63) */ - unsigned char index; - /** error protection method [-1=absent 0=none 1=predefined 16=CRC-16 32=CRC-32 37-128=RS] */ - int hprot; - /** message word length of pre-data */ - int k_pre; - /** code word length of pre-data */ - int n_pre; - /** length of pre-data */ - int pre_len; - /** message word length of post-data */ - int k_post; - /** code word length of post-data */ - int n_post; - /** length of post-data */ - int post_len; - /*@}*/ - /**@name Marker segment fields */ - /*@{*/ - /** two bytes for the length of EPB MS, exluding the marker itself (11 to 65535 bytes) */ - unsigned short int Lepb; - /** single byte for the style */ - unsigned char Depb; - /** four bytes, from 0 to 2^31-1 */ - unsigned long int LDPepb; - /** four bytes, next error management method */ - unsigned long int Pepb; - /** EPB data, variable size */ - unsigned char *data; - /*@}*/ -} jpwl_epb_ms_t; - -/** -EPC (Error Protection Capability) Marker segment -*/ -typedef struct jpwl_epc_ms { - /** is ESD active? */ - opj_bool esd_on; - /** is RED active? */ - opj_bool red_on; - /** is EPB active? */ - opj_bool epb_on; - /** are informative techniques active? */ - opj_bool info_on; - /**@name Marker segment fields */ - /*@{*/ - /** two bytes for the length of EPC MS, exluding the marker itself (9 to 65535 bytes) */ - unsigned short int Lepc; - /** two bytes, CRC for the EPC, excluding Pcrc itself */ - unsigned short int Pcrc; - /** four bytes, the codestream length from SOC to EOC */ - unsigned long int DL; - /** one byte, signals JPWL techniques adoption */ - unsigned char Pepc; - /** EPC data, variable length */ - unsigned char *data; - /*@}*/ -} jpwl_epc_ms_t; - -/** -ESD (Error Sensitivity Descriptor) Marker segment -*/ -typedef struct jpwl_esd_ms { - /** codestream addressing mode [0=packet, 1=byte range, 2=packet range, 3=reserved] */ - unsigned char addrm; - /** size of codestream addresses [2/4 bytes] */ - unsigned char ad_size; - /** type of sensitivity - [0=relative error, 1=MSE, 2=MSE reduction, 3=PSNR, 4=PSNR increment, - 5=MAXERR (absolute peak error), 6=TSE (total squared error), 7=reserved */ - unsigned char senst; - /** size of sensitivity data (1/2 bytes) */ - unsigned char se_size; - /**@name Marker segment fields */ - /*@{*/ - /** two bytes for the length of ESD MS, exluding the marker itself (4 to 65535 bytes) */ - unsigned short int Lesd; - /** two bytes, component of error sensitivity */ - unsigned short int Cesd; - /** one byte, signals JPWL techniques adoption */ - unsigned char Pesd; - /** ESD data, variable length */ - unsigned char *data; - /*@}*/ - /**@name Fields set by esd_create (only internal use) */ - /*@{*/ - /** number of components in the image */ - int numcomps; - /** tile where this marker has been placed (-1 means MH) */ - int tileno; - /** number of sensitivity values */ - unsigned long int svalnum; - /** size of a single sensitivity pair (address+value) */ - size_t sensval_size; - /*@}*/ -} jpwl_esd_ms_t; - -/** -RED (Residual Error Descriptor) Marker segment -*/ -typedef struct jpwl_red_ms { - /** two bytes for the length of RED MS, exluding the marker itself (3 to 65535 bytes) */ - unsigned short int Lred; - /** one byte, signals JPWL techniques adoption */ - unsigned char Pred; - /** RED data, variable length */ - unsigned char *data; -} jpwl_red_ms_t; - -/** -Structure used to store JPWL markers temporary position and readyness -*/ -typedef struct jpwl_marker { - /** marker value (J2K_MS_EPC, etc.) */ - int id; - /** union keeping the pointer to the real marker struct */ - union jpwl_marks { - /** pointer to EPB marker */ - jpwl_epb_ms_t *epbmark; - /** pointer to EPC marker */ - jpwl_epc_ms_t *epcmark; - /** pointer to ESD marker */ - jpwl_esd_ms_t *esdmark; - /** pointer to RED marker */ - jpwl_red_ms_t *redmark; - } m; - /** position where the marker should go, in the pre-JPWL codestream */ - unsigned long int pos; - /** same as before, only written as a double, so we can sort it better */ - double dpos; - /** length of the marker segment (marker excluded) */ - unsigned short int len; - /** the marker length is ready or not? */ - opj_bool len_ready; - /** the marker position is ready or not? */ - opj_bool pos_ready; - /** the marker parameters are ready or not? */ - opj_bool parms_ready; - /** are the written data ready or not */ - opj_bool data_ready; -} jpwl_marker_t; - -/** -Encode according to JPWL specs -@param j2k J2K handle -@param cio codestream handle -@param image image handle -*/ -void jpwl_encode(opj_j2k_t *j2k, opj_cio_t *cio, opj_image_t *image); - -/** -Prepare the list of JPWL markers, after the Part 1 codestream -has been finalized (index struct is full) -@param j2k J2K handle -@param cio codestream handle -@param image image handle -*/ -void jpwl_prepare_marks(opj_j2k_t *j2k, opj_cio_t *cio, opj_image_t *image); - -/** -Dump the list of JPWL markers, after it has been prepared -@param j2k J2K handle -@param cio codestream handle -@param image image handle -*/ -void jpwl_dump_marks(opj_j2k_t *j2k, opj_cio_t *cio, opj_image_t *image); - -/** -Read the EPC marker (Error Protection Capability) -@param j2k J2K handle -*/ -void j2k_read_epc(opj_j2k_t *j2k); - -/** -Write the EPC marker (Error Protection Capability), BUT the DL field is always set to 0 -(this simplifies the management of EPBs and it is openly stated in the standard -as a possible value, mening that the information is not available) and the informative techniques -are not yet implemented -@param j2k J2K handle -*/ -void j2k_write_epc(opj_j2k_t *j2k); - -/** -Read the EPB marker (Error Protection Block) -@param j2k J2K handle -*/ -void j2k_read_epb(opj_j2k_t *j2k); - -/** -Write the EPB marker (Error Protection Block) -@param j2k J2K handle -*/ -void j2k_write_epb(opj_j2k_t *j2k); - -/** -Read the ESD marker (Error Sensitivity Descriptor) -@param j2k J2K handle -*/ -void j2k_read_esd(opj_j2k_t *j2k); - -/** -Read the RED marker (Residual Error Descriptor) -@param j2k J2K handle -*/ -void j2k_read_red(opj_j2k_t *j2k); - -/** create an EPB marker segment -@param j2k J2K compressor handle -@param latest it is the latest EPB in the header -@param packed EPB is in packed style -@param tileno tile number where the marker has been placed (-1 means MH) -@param idx current EPB running index -@param hprot applied protection type (-1/0,1,16,32,37-128) -@param pre_len length of pre-protected data -@param post_len length of post-protected data -@return returns the freshly created EPB -*/ -jpwl_epb_ms_t *jpwl_epb_create(opj_j2k_t *j2k, opj_bool latest, opj_bool packed, int tileno, int idx, int hprot, - unsigned long int pre_len, unsigned long int post_len); - -/** add a number of EPB marker segments -@param j2k J2K compressor handle -@param jwmarker pointer to the JPWL markers list -@param jwmarker_num pointer to the number of JPWL markers (gets updated) -@param latest it is the latest group of EPBs in the header -@param packed EPBs are in packed style -@param insideMH it is in the MH -@param idx pointer to the starting EPB running index (gets updated) -@param hprot applied protection type (-1/0,1,16,32,37-128) -@param place_pos place in original codestream where EPBs should go -@param tileno tile number of these EPBs -@param pre_len length of pre-protected data -@param post_len length of post-protected data -@return returns the length of all added markers -*/ -int jpwl_epbs_add(opj_j2k_t *j2k, jpwl_marker_t *jwmarker, int *jwmarker_num, - opj_bool latest, opj_bool packed, opj_bool insideMH, int *idx, int hprot, - double place_pos, int tileno, - unsigned long int pre_len, unsigned long int post_len); - -/** add a number of ESD marker segments -@param j2k J2K compressor handle -@param jwmarker pointer to the JPWL markers list -@param jwmarker_num pointer to the number of JPWL markers (gets updated) -@param comps considered component (-1=average, 0/1/2/...=component no.) -@param addrm addressing mode (0=packet, 1=byte range, 2=packet range, 3=reserved) -@param ad_size size of addresses (2/4 bytes) -@param senst sensitivity type -@param se_size sensitivity values size (1/2 bytes) -@param place_pos place in original codestream where EPBs should go -@param tileno tile number of these EPBs -@return returns the length of all added markers -*/ -int jpwl_esds_add(opj_j2k_t *j2k, jpwl_marker_t *jwmarker, int *jwmarker_num, - int comps, unsigned char addrm, unsigned char ad_size, - unsigned char senst, unsigned char se_size, - double place_pos, int tileno); - -/** updates the information structure by modifying the positions and lengths -@param j2k J2K compressor handle -@param jwmarker pointer to JPWL markers list -@param jwmarker_num number of JPWL markers -@return returns true in case of success -*/ -opj_bool jpwl_update_info(opj_j2k_t *j2k, jpwl_marker_t *jwmarker, int jwmarker_num); - - -opj_bool jpwl_esd_fill(opj_j2k_t *j2k, jpwl_esd_ms_t *esdmark, unsigned char *buf); - -opj_bool jpwl_epb_fill(opj_j2k_t *j2k, jpwl_epb_ms_t *epbmark, unsigned char *buf, unsigned char *post_buf); - -void j2k_add_marker(opj_codestream_info_t *cstr_info, unsigned short int type, int pos, int len); - -/** corrects the data in the JPWL codestream -@param j2k J2K compressor handle -@return true if correction is performed correctly -*/ -opj_bool jpwl_correct(opj_j2k_t *j2k); - -/** corrects the data protected by an EPB -@param j2k J2K compressor handle -@param buffer pointer to the EPB position -@param type type of EPB: 0=MH, 1=TPH, 2=other, 3=auto -@param pre_len length of pre-data -@param post_len length of post_data -@param conn is a pointer to the length of all connected (packed) EPBs -@param L4_bufp is a pointer to the buffer pointer of redundancy data -@return returns true if correction could be succesfully performed -*/ -opj_bool jpwl_epb_correct(opj_j2k_t *j2k, unsigned char *buffer, int type, int pre_len, int post_len, int *conn, - unsigned char **L4_bufp); - -/** check that a tile and its children have valid data -@param j2k J2K decompressor handle -@param tcd Tile decompressor handle -@param tileno number of the tile to check -*/ -opj_bool jpwl_check_tile(opj_j2k_t *j2k, opj_tcd_t *tcd, int tileno); - -/** Macro functions for CRC computation */ - -/** -Computes the CRC-16, as stated in JPWL specs -@param CRC two bytes containing the CRC value (must be initialized with 0x0000) -@param DATA byte for which the CRC is computed; call this on every byte of the sequence -and get the CRC at the end -*/ -#define jpwl_updateCRC16(CRC, DATA) updateCRC16(CRC, DATA) - -/** -Computes the CRC-32, as stated in JPWL specs -@param CRC four bytes containing the CRC value (must be initialized with 0x00000000) -@param DATA byte for which the CRC is computed; call this on every byte of the sequence -and get the CRC at the end -*/ -#define jpwl_updateCRC32(CRC, DATA) updateCRC32(CRC, DATA) - -/** -Computes the minimum between two integers -@param a first integer to compare -@param b second integer to compare -@return returns the minimum integer between a and b -*/ -#ifndef min -#define min(a,b) (((a) < (b)) ? (a) : (b)) -#endif /* min */ - -/*@}*/ - -#endif /* USE_JPWL */ - -#ifdef USE_JPSEC - -/** @defgroup JPSEC JPSEC - JPEG-2000 Part 8 (JPSEC) codestream manager */ -/*@{*/ - -/** -Read the SEC marker (SEcured Codestream) -@param j2k J2K handle -*/ -void j2k_read_sec(opj_j2k_t *j2k); - -/** -Write the SEC marker (SEcured Codestream) -@param j2k J2K handle -*/ -void j2k_write_sec(opj_j2k_t *j2k); - -/** -Read the INSEC marker (SEcured Codestream) -@param j2k J2K handle -*/ -void j2k_read_insec(opj_j2k_t *j2k); - -/*@}*/ - -#endif /* USE_JPSEC */ - -#endif /* __JPWL_H */ - diff --git a/openjpeg-dotnet/libopenjpeg/jpwl/jpwl_lib.c b/openjpeg-dotnet/libopenjpeg/jpwl/jpwl_lib.c deleted file mode 100644 index 90a71cec..00000000 --- a/openjpeg-dotnet/libopenjpeg/jpwl/jpwl_lib.c +++ /dev/null @@ -1,1797 +0,0 @@ -/* - * Copyright (c) 2001-2003, David Janssens - * Copyright (c) 2002-2003, Yannick Verschueren - * Copyright (c) 2003-2005, Francois Devaux and Antonin Descampe - * Copyright (c) 2005, Herve Drolon, FreeImage Team - * Copyright (c) 2002-2005, Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium - * Copyright (c) 2005-2006, Dept. of Electronic and Information Engineering, Universita' degli Studi di Perugia, Italy - * 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. - */ - -#ifdef USE_JPWL - -#include "opj_includes.h" -#include - -/** Minimum and maximum values for the double->pfp conversion */ -#define MIN_V1 0.0 -#define MAX_V1 17293822569102704640.0 -#define MIN_V2 0.000030517578125 -#define MAX_V2 131040.0 - -/** conversion between a double precision floating point -number and the corresponding pseudo-floating point used -to represent sensitivity values -@param V the double precision value -@param bytes the number of bytes of the representation -@return the pseudo-floating point value (cast accordingly) -*/ -unsigned short int jpwl_double_to_pfp(double V, int bytes); - -/** conversion between a pseudo-floating point used -to represent sensitivity values and the corresponding -double precision floating point number -@param em the pseudo-floating point value (cast accordingly) -@param bytes the number of bytes of the representation -@return the double precision value -*/ -double jpwl_pfp_to_double(unsigned short int em, int bytes); - - /*-------------------------------------------------------------*/ - -int jpwl_markcomp(const void *arg1, const void *arg2) -{ - /* Compare the two markers' positions */ - double diff = (((jpwl_marker_t *) arg1)->dpos - ((jpwl_marker_t *) arg2)->dpos); - - if (diff == 0.0) - return (0); - else if (diff < 0) - return (-1); - else - return (+1); -} - -int jpwl_epbs_add(opj_j2k_t *j2k, jpwl_marker_t *jwmarker, int *jwmarker_num, - opj_bool latest, opj_bool packed, opj_bool insideMH, int *idx, int hprot, - double place_pos, int tileno, - unsigned long int pre_len, unsigned long int post_len) { - - jpwl_epb_ms_t *epb_mark = NULL; - - int k_pre, k_post, n_pre, n_post; - - unsigned long int L1, L2, dL4, max_postlen, epbs_len = 0; - - /* We find RS(n,k) for EPB parms and pre-data, if any */ - if (insideMH && (*idx == 0)) { - /* First EPB in MH */ - k_pre = 64; - n_pre = 160; - } else if (!insideMH && (*idx == 0)) { - /* First EPB in TH */ - k_pre = 25; - n_pre = 80; - } else { - /* Following EPBs in MH or TH */ - k_pre = 13; - n_pre = 40; - }; - - /* Find lengths, Figs. B3 and B4 */ - /* size of pre data: pre_buf(pre_len) + EPB(2) + Lepb(2) + Depb(1) + LDPepb(4) + Pepb(4) */ - L1 = pre_len + 13; - - /* size of pre-data redundancy */ - /* (redundancy per codeword) * (number of codewords, rounded up) */ - L2 = (n_pre - k_pre) * (unsigned long int) ceil((double) L1 / (double) k_pre); - - /* Find protection type for post data and its associated redundancy field length*/ - if ((hprot == 16) || (hprot == 32)) { - /* there is a CRC for post-data */ - k_post = post_len; - n_post = post_len + (hprot >> 3); - /*L3 = hprot >> 3;*/ /* 2 (CRC-16) or 4 (CRC-32) bytes */ - - } else if ((hprot >= 37) && (hprot <= 128)) { - /* there is a RS for post-data */ - k_post = 32; - n_post = hprot; - - } else { - /* Use predefined codes */ - n_post = n_pre; - k_post = k_pre; - }; - - /* Create the EPB(s) */ - while (post_len > 0) { - - /* maximum postlen in order to respect EPB size - (we use JPWL_MAXIMUM_EPB_ROOM instead of 65535 for keeping room for EPB parms)*/ - /* (message word size) * (number of containable parity words) */ - max_postlen = k_post * (unsigned long int) floor((double) JPWL_MAXIMUM_EPB_ROOM / (double) (n_post - k_post)); - - /* maximum postlen in order to respect EPB size */ - if (*idx == 0) - /* (we use (JPWL_MAXIMUM_EPB_ROOM - L2) instead of 65535 for keeping room for EPB parms + pre-data) */ - /* (message word size) * (number of containable parity words) */ - max_postlen = k_post * (unsigned long int) floor((double) (JPWL_MAXIMUM_EPB_ROOM - L2) / (double) (n_post - k_post)); - - else - /* (we use JPWL_MAXIMUM_EPB_ROOM instead of 65535 for keeping room for EPB parms) */ - /* (message word size) * (number of containable parity words) */ - max_postlen = k_post * (unsigned long int) floor((double) JPWL_MAXIMUM_EPB_ROOM / (double) (n_post - k_post)); - - /* null protection case */ - /* the max post length can be as large as the LDPepb field can host */ - if (hprot == 0) - max_postlen = INT_MAX; - - /* length to use */ - dL4 = min(max_postlen, post_len); - - if ((epb_mark = jpwl_epb_create( - j2k, /* this encoder handle */ - latest ? (dL4 < max_postlen) : OPJ_FALSE, /* is it the latest? */ - packed, /* is it packed? */ - tileno, /* we are in TPH */ - *idx, /* its index */ - hprot, /* protection type parameters of following data */ - 0, /* pre-data: nothing for now */ - dL4 /* post-data: the stub computed previously */ - ))) { - - /* Add this marker to the 'insertanda' list */ - if (*jwmarker_num < JPWL_MAX_NO_MARKERS) { - jwmarker[*jwmarker_num].id = J2K_MS_EPB; /* its type */ - jwmarker[*jwmarker_num].m.epbmark = epb_mark; /* the EPB */ - jwmarker[*jwmarker_num].pos = (int) place_pos; /* after SOT */ - jwmarker[*jwmarker_num].dpos = place_pos + 0.0000001 * (double)(*idx); /* not very first! */ - jwmarker[*jwmarker_num].len = epb_mark->Lepb; /* its length */ - jwmarker[*jwmarker_num].len_ready = OPJ_TRUE; /* ready */ - jwmarker[*jwmarker_num].pos_ready = OPJ_TRUE; /* ready */ - jwmarker[*jwmarker_num].parms_ready = OPJ_TRUE; /* ready */ - jwmarker[*jwmarker_num].data_ready = OPJ_FALSE; /* not ready */ - (*jwmarker_num)++; - } - - /* increment epb index */ - (*idx)++; - - /* decrease postlen */ - post_len -= dL4; - - /* increase the total length of EPBs */ - epbs_len += epb_mark->Lepb + 2; - - } else { - /* ooops, problems */ - opj_event_msg(j2k->cinfo, EVT_ERROR, "Could not create TPH EPB for UEP in tile %d\n", tileno); - }; - } - - return epbs_len; -} - - -jpwl_epb_ms_t *jpwl_epb_create(opj_j2k_t *j2k, opj_bool latest, opj_bool packed, int tileno, int idx, int hprot, - unsigned long int pre_len, unsigned long int post_len) { - - jpwl_epb_ms_t *epb = NULL; - /*unsigned short int data_len = 0;*/ - unsigned short int L2, L3; - unsigned long int L1, L4; - /*unsigned char *predata_in = NULL;*/ - - opj_bool insideMH = (tileno == -1); - - /* Alloc space */ - if (!(epb = (jpwl_epb_ms_t *) opj_malloc((size_t) 1 * sizeof (jpwl_epb_ms_t)))) { - opj_event_msg(j2k->cinfo, EVT_ERROR, "Could not allocate room for one EPB MS\n"); - return NULL; - }; - - /* We set RS(n,k) for EPB parms and pre-data, if any */ - if (insideMH && (idx == 0)) { - /* First EPB in MH */ - epb->k_pre = 64; - epb->n_pre = 160; - } else if (!insideMH && (idx == 0)) { - /* First EPB in TH */ - epb->k_pre = 25; - epb->n_pre = 80; - } else { - /* Following EPBs in MH or TH */ - epb->k_pre = 13; - epb->n_pre = 40; - }; - - /* Find lengths, Figs. B3 and B4 */ - /* size of pre data: pre_buf(pre_len) + EPB(2) + Lepb(2) + Depb(1) + LDPepb(4) + Pepb(4) */ - L1 = pre_len + 13; - epb->pre_len = pre_len; - - /* size of pre-data redundancy */ - /* (redundancy per codeword) * (number of codewords, rounded up) */ - L2 = (epb->n_pre - epb->k_pre) * (unsigned short int) ceil((double) L1 / (double) epb->k_pre); - - /* length of post-data */ - L4 = post_len; - epb->post_len = post_len; - - /* Find protection type for post data and its associated redundancy field length*/ - if ((hprot == 16) || (hprot == 32)) { - /* there is a CRC for post-data */ - epb->Pepb = 0x10000000 | ((unsigned long int) hprot >> 5); /* 0=CRC-16, 1=CRC-32 */ - epb->k_post = post_len; - epb->n_post = post_len + (hprot >> 3); - /*L3 = hprot >> 3;*/ /* 2 (CRC-16) or 4 (CRC-32) bytes */ - - } else if ((hprot >= 37) && (hprot <= 128)) { - /* there is a RS for post-data */ - epb->Pepb = 0x20000020 | (((unsigned long int) hprot & 0x000000FF) << 8); - epb->k_post = 32; - epb->n_post = hprot; - - } else if (hprot == 1) { - /* Use predefined codes */ - epb->Pepb = (unsigned long int) 0x00000000; - epb->n_post = epb->n_pre; - epb->k_post = epb->k_pre; - - } else if (hprot == 0) { - /* Placeholder EPB: only protects its parameters, no protection method */ - epb->Pepb = (unsigned long int) 0xFFFFFFFF; - epb->n_post = 1; - epb->k_post = 1; - - } else { - opj_event_msg(j2k->cinfo, EVT_ERROR, "Invalid protection value for EPB h = %d\n", hprot); - return NULL; - } - - epb->hprot = hprot; - - /* (redundancy per codeword) * (number of codewords, rounded up) */ - L3 = (epb->n_post - epb->k_post) * (unsigned short int) ceil((double) L4 / (double) epb->k_post); - - /* private fields */ - epb->tileno = tileno; - - /* Fill some fields of the EPB */ - - /* total length of the EPB MS (less the EPB marker itself): */ - /* Lepb(2) + Depb(1) + LDPepb(4) + Pepb(4) + pre_redundancy + post-redundancy */ - epb->Lepb = 11 + L2 + L3; - - /* EPB style */ - epb->Depb = ((packed & 0x0001) << 7) | ((latest & 0x0001) << 6) | (idx & 0x003F); - - /* length of data protected by EPB: */ - epb->LDPepb = L1 + L4; - - return epb; -} - -void jpwl_epb_write(opj_j2k_t *j2k, jpwl_epb_ms_t *epb, unsigned char *buf) { - - /* Marker */ - *(buf++) = (unsigned char) (J2K_MS_EPB >> 8); - *(buf++) = (unsigned char) (J2K_MS_EPB >> 0); - - /* Lepb */ - *(buf++) = (unsigned char) (epb->Lepb >> 8); - *(buf++) = (unsigned char) (epb->Lepb >> 0); - - /* Depb */ - *(buf++) = (unsigned char) (epb->Depb >> 0); - - /* LDPepb */ - *(buf++) = (unsigned char) (epb->LDPepb >> 24); - *(buf++) = (unsigned char) (epb->LDPepb >> 16); - *(buf++) = (unsigned char) (epb->LDPepb >> 8); - *(buf++) = (unsigned char) (epb->LDPepb >> 0); - - /* Pepb */ - *(buf++) = (unsigned char) (epb->Pepb >> 24); - *(buf++) = (unsigned char) (epb->Pepb >> 16); - *(buf++) = (unsigned char) (epb->Pepb >> 8); - *(buf++) = (unsigned char) (epb->Pepb >> 0); - - /* Data */ - /*memcpy(buf, epb->data, (size_t) epb->Lepb - 11);*/ - memset(buf, 0, (size_t) epb->Lepb - 11); - - /* update markers struct */ - j2k_add_marker(j2k->cstr_info, J2K_MS_EPB, -1, epb->Lepb + 2); - -}; - - -jpwl_epc_ms_t *jpwl_epc_create(opj_j2k_t *j2k, opj_bool esd_on, opj_bool red_on, opj_bool epb_on, opj_bool info_on) { - - jpwl_epc_ms_t *epc = NULL; - - /* Alloc space */ - if (!(epc = (jpwl_epc_ms_t *) opj_malloc((size_t) 1 * sizeof (jpwl_epc_ms_t)))) { - opj_event_msg(j2k->cinfo, EVT_ERROR, "Could not allocate room for EPC MS\n"); - return NULL; - }; - - /* Set the EPC parameters */ - epc->esd_on = esd_on; - epc->epb_on = epb_on; - epc->red_on = red_on; - epc->info_on = info_on; - - /* Fill the EPC fields with default values */ - epc->Lepc = 9; - epc->Pcrc = 0x0000; - epc->DL = 0x00000000; - epc->Pepc = ((j2k->cp->esd_on & 0x0001) << 4) | ((j2k->cp->red_on & 0x0001) << 5) | - ((j2k->cp->epb_on & 0x0001) << 6) | ((j2k->cp->info_on & 0x0001) << 7); - - return (epc); -} - -opj_bool jpwl_epb_fill(opj_j2k_t *j2k, jpwl_epb_ms_t *epb, unsigned char *buf, unsigned char *post_buf) { - - unsigned long int L1, L2, L3, L4; - int remaining; - unsigned long int P, NN_P; - - /* Operating buffer */ - static unsigned char codeword[NN], *parityword; - - unsigned char *L1_buf, *L2_buf; - /* these ones are static, since we need to keep memory of - the exact place from one call to the other */ - static unsigned char *L3_buf, *L4_buf; - - /* some consistency check */ - if (!buf) { - opj_event_msg(j2k->cinfo, EVT_ERROR, "There is no operating buffer for EPBs\n"); - return OPJ_FALSE; - } - - if (!post_buf && !L4_buf) { - opj_event_msg(j2k->cinfo, EVT_ERROR, "There is no operating buffer for EPBs data\n"); - return OPJ_FALSE; - } - - /* - * Compute parity bytes on pre-data, ALWAYS present (at least only for EPB parms) - */ - - /* Initialize RS structures */ - P = epb->n_pre - epb->k_pre; - NN_P = NN - P; - memset(codeword, 0, NN); - parityword = codeword + NN_P; - init_rs(NN_P); - - /* pre-data begins pre_len bytes before of EPB buf */ - L1_buf = buf - epb->pre_len; - L1 = epb->pre_len + 13; - - /* redundancy for pre-data begins immediately after EPB parms */ - L2_buf = buf + 13; - L2 = (epb->n_pre - epb->k_pre) * (unsigned short int) ceil((double) L1 / (double) epb->k_pre); - - /* post-data - the position of L4 buffer can be: - 1) passed as a parameter: in that case use it - 2) null: in that case use the previous (static) one - */ - if (post_buf) - L4_buf = post_buf; - L4 = epb->post_len; - - /* post-data redundancy begins immediately after pre-data redundancy */ - L3_buf = L2_buf + L2; - L3 = (epb->n_post - epb->k_post) * (unsigned short int) ceil((double) L4 / (double) epb->k_post); - - /* let's check whether EPB length is sufficient to contain all these data */ - if (epb->Lepb < (11 + L2 + L3)) - opj_event_msg(j2k->cinfo, EVT_ERROR, "There is no room in EPB data field for writing redundancy data\n"); - /*printf("Env. %d, nec. %d (%d + %d)\n", epb->Lepb - 11, L2 + L3, L2, L3);*/ - - /* Compute redundancy of pre-data message words */ - remaining = L1; - while (remaining) { - - /* copy message data into codeword buffer */ - if (remaining < epb->k_pre) { - /* the last message word is zero-padded */ - memset(codeword, 0, NN); - memcpy(codeword, L1_buf, remaining); - L1_buf += remaining; - remaining = 0; - - } else { - memcpy(codeword, L1_buf, epb->k_pre); - L1_buf += epb->k_pre; - remaining -= epb->k_pre; - - } - - /* Encode the buffer and obtain parity bytes */ - if (encode_rs(codeword, parityword)) - opj_event_msg(j2k->cinfo, EVT_WARNING, - "Possible encoding error in codeword @ position #%d\n", (L1_buf - buf) / epb->k_pre); - - /* copy parity bytes only in redundancy buffer */ - memcpy(L2_buf, parityword, P); - - /* advance parity buffer */ - L2_buf += P; - } - - /* - * Compute parity bytes on post-data, may be absent if there are no data - */ - /*printf("Hprot is %d (tileno=%d, k_pre=%d, n_pre=%d, k_post=%d, n_post=%d, pre_len=%d, post_len=%d)\n", - epb->hprot, epb->tileno, epb->k_pre, epb->n_pre, epb->k_post, epb->n_post, epb->pre_len, - epb->post_len);*/ - if (epb->hprot < 0) { - - /* there should be no EPB */ - - } else if (epb->hprot == 0) { - - /* no protection for the data */ - /* advance anyway */ - L4_buf += epb->post_len; - - } else if (epb->hprot == 16) { - - /* CRC-16 */ - unsigned short int mycrc = 0x0000; - - /* compute the CRC field (excluding itself) */ - remaining = L4; - while (remaining--) - jpwl_updateCRC16(&mycrc, *(L4_buf++)); - - /* write the CRC field */ - *(L3_buf++) = (unsigned char) (mycrc >> 8); - *(L3_buf++) = (unsigned char) (mycrc >> 0); - - } else if (epb->hprot == 32) { - - /* CRC-32 */ - unsigned long int mycrc = 0x00000000; - - /* compute the CRC field (excluding itself) */ - remaining = L4; - while (remaining--) - jpwl_updateCRC32(&mycrc, *(L4_buf++)); - - /* write the CRC field */ - *(L3_buf++) = (unsigned char) (mycrc >> 24); - *(L3_buf++) = (unsigned char) (mycrc >> 16); - *(L3_buf++) = (unsigned char) (mycrc >> 8); - *(L3_buf++) = (unsigned char) (mycrc >> 0); - - } else { - - /* RS */ - - /* Initialize RS structures */ - P = epb->n_post - epb->k_post; - NN_P = NN - P; - memset(codeword, 0, NN); - parityword = codeword + NN_P; - init_rs(NN_P); - - /* Compute redundancy of post-data message words */ - remaining = L4; - while (remaining) { - - /* copy message data into codeword buffer */ - if (remaining < epb->k_post) { - /* the last message word is zero-padded */ - memset(codeword, 0, NN); - memcpy(codeword, L4_buf, remaining); - L4_buf += remaining; - remaining = 0; - - } else { - memcpy(codeword, L4_buf, epb->k_post); - L4_buf += epb->k_post; - remaining -= epb->k_post; - - } - - /* Encode the buffer and obtain parity bytes */ - if (encode_rs(codeword, parityword)) - opj_event_msg(j2k->cinfo, EVT_WARNING, - "Possible encoding error in codeword @ position #%d\n", (L4_buf - buf) / epb->k_post); - - /* copy parity bytes only in redundancy buffer */ - memcpy(L3_buf, parityword, P); - - /* advance parity buffer */ - L3_buf += P; - } - - } - - return OPJ_TRUE; -} - - -opj_bool jpwl_correct(opj_j2k_t *j2k) { - - opj_cio_t *cio = j2k->cio; - opj_bool status; - static opj_bool mh_done = OPJ_FALSE; - int mark_pos, id, len, skips, sot_pos; - unsigned long int Psot = 0; - - /* go back to marker position */ - mark_pos = cio_tell(cio) - 2; - cio_seek(cio, mark_pos); - - if ((j2k->state == J2K_STATE_MHSOC) && !mh_done) { - - int mark_val = 0, skipnum = 0; - - /* - COLOR IMAGE - first thing to do, if we are here, is to look whether - 51 (skipnum) positions ahead there is an EPB, in case of MH - */ - /* - B/W IMAGE - first thing to do, if we are here, is to look whether - 45 (skipnum) positions ahead there is an EPB, in case of MH - */ - /* SIZ SIZ_FIELDS SIZ_COMPS FOLLOWING_MARKER */ - skipnum = 2 + 38 + 3 * j2k->cp->exp_comps + 2; - if ((cio->bp + skipnum) < cio->end) { - - cio_skip(cio, skipnum); - - /* check that you are not going beyond the end of codestream */ - - /* call EPB corrector */ - status = jpwl_epb_correct(j2k, /* J2K decompressor handle */ - cio->bp, /* pointer to EPB in codestream buffer */ - 0, /* EPB type: MH */ - skipnum, /* length of pre-data */ - -1, /* length of post-data: -1 means auto */ - NULL, - NULL - ); - - /* read the marker value */ - mark_val = (*(cio->bp) << 8) | *(cio->bp + 1); - - if (status && (mark_val == J2K_MS_EPB)) { - /* we found it! */ - mh_done = OPJ_TRUE; - return OPJ_TRUE; - } - - /* Disable correction in case of missing or bad head EPB */ - /* We can't do better! */ - /* PATCHED: 2008-01-25 */ - /* MOVED UP: 2008-02-01 */ - if (!status) { - j2k->cp->correct = OPJ_FALSE; - opj_event_msg(j2k->cinfo, EVT_WARNING, "Couldn't find the MH EPB: disabling JPWL\n"); - } - - } - - } - - if (OPJ_TRUE /*(j2k->state == J2K_STATE_TPHSOT) || (j2k->state == J2K_STATE_TPH)*/) { - /* else, look if 12 positions ahead there is an EPB, in case of TPH */ - cio_seek(cio, mark_pos); - if ((cio->bp + 12) < cio->end) { - - cio_skip(cio, 12); - - /* call EPB corrector */ - status = jpwl_epb_correct(j2k, /* J2K decompressor handle */ - cio->bp, /* pointer to EPB in codestream buffer */ - 1, /* EPB type: TPH */ - 12, /* length of pre-data */ - -1, /* length of post-data: -1 means auto */ - NULL, - NULL - ); - if (status) - /* we found it! */ - return OPJ_TRUE; - } - } - - return OPJ_FALSE; - - /* for now, don't use this code */ - - /* else, look if here is an EPB, in case of other */ - if (mark_pos > 64) { - /* it cannot stay before the first MH EPB */ - cio_seek(cio, mark_pos); - cio_skip(cio, 0); - - /* call EPB corrector */ - status = jpwl_epb_correct(j2k, /* J2K decompressor handle */ - cio->bp, /* pointer to EPB in codestream buffer */ - 2, /* EPB type: TPH */ - 0, /* length of pre-data */ - -1, /* length of post-data: -1 means auto */ - NULL, - NULL - ); - if (status) - /* we found it! */ - return OPJ_TRUE; - } - - /* nope, no EPBs probably, or they are so damaged that we can give up */ - return OPJ_FALSE; - - return OPJ_TRUE; - - /* AN ATTEMPT OF PARSER */ - /* NOT USED ACTUALLY */ - - /* go to the beginning of the file */ - cio_seek(cio, 0); - - /* let's begin */ - j2k->state = J2K_STATE_MHSOC; - - /* cycle all over the markers */ - while (cio_tell(cio) < cio->length) { - - /* read the marker */ - mark_pos = cio_tell(cio); - id = cio_read(cio, 2); - - /* details */ - printf("Marker@%d: %X\n", cio_tell(cio) - 2, id); - - /* do an action in response to the read marker */ - switch (id) { - - /* short markers */ - - /* SOC */ - case J2K_MS_SOC: - j2k->state = J2K_STATE_MHSIZ; - len = 0; - skips = 0; - break; - - /* EOC */ - case J2K_MS_EOC: - j2k->state = J2K_STATE_MT; - len = 0; - skips = 0; - break; - - /* particular case of SOD */ - case J2K_MS_SOD: - len = Psot - (mark_pos - sot_pos) - 2; - skips = len; - break; - - /* long markers */ - - /* SOT */ - case J2K_MS_SOT: - j2k->state = J2K_STATE_TPH; - sot_pos = mark_pos; /* position of SOT */ - len = cio_read(cio, 2); /* read the length field */ - cio_skip(cio, 2); /* this field is unnecessary */ - Psot = cio_read(cio, 4); /* tile length */ - skips = len - 8; - break; - - /* remaining */ - case J2K_MS_SIZ: - j2k->state = J2K_STATE_MH; - /* read the length field */ - len = cio_read(cio, 2); - skips = len - 2; - break; - - /* remaining */ - default: - /* read the length field */ - len = cio_read(cio, 2); - skips = len - 2; - break; - - } - - /* skip to marker's end */ - cio_skip(cio, skips); - - } - - -} - -opj_bool jpwl_epb_correct(opj_j2k_t *j2k, unsigned char *buffer, int type, int pre_len, int post_len, int *conn, - unsigned char **L4_bufp) { - - /* Operating buffer */ - unsigned char codeword[NN], *parityword; - - unsigned long int P, NN_P; - unsigned long int L1, L4; - int remaining, n_pre, k_pre, n_post, k_post; - - int status, tt; - - int orig_pos = cio_tell(j2k->cio); - - unsigned char *L1_buf, *L2_buf; - unsigned char *L3_buf, *L4_buf; - - unsigned long int LDPepb, Pepb; - unsigned short int Lepb; - unsigned char Depb; - char str1[25] = ""; - int myconn, errnum = 0; - opj_bool errflag = OPJ_FALSE; - - opj_cio_t *cio = j2k->cio; - - /* check for common errors */ - if (!buffer) { - opj_event_msg(j2k->cinfo, EVT_ERROR, "The EPB pointer is a NULL buffer\n"); - return OPJ_FALSE; - } - - /* set bignesses */ - L1 = pre_len + 13; - - /* pre-data correction */ - switch (type) { - - case 0: - /* MH EPB */ - k_pre = 64; - n_pre = 160; - break; - - case 1: - /* TPH EPB */ - k_pre = 25; - n_pre = 80; - break; - - case 2: - /* other EPBs */ - k_pre = 13; - n_pre = 40; - break; - - case 3: - /* automatic setup */ - opj_event_msg(j2k->cinfo, EVT_ERROR, "Auto. setup not yet implemented\n"); - return OPJ_FALSE; - break; - - default: - /* unknown type */ - opj_event_msg(j2k->cinfo, EVT_ERROR, "Unknown expected EPB type\n"); - return OPJ_FALSE; - break; - - } - - /* Initialize RS structures */ - P = n_pre - k_pre; - NN_P = NN - P; - tt = (int) floor((float) P / 2.0F); /* correction capability of the code */ - memset(codeword, 0, NN); - parityword = codeword + NN_P; - init_rs(NN_P); - - /* Correct pre-data message words */ - L1_buf = buffer - pre_len; - L2_buf = buffer + 13; - remaining = L1; - while (remaining) { - - /* always zero-pad codewords */ - /* (this is required, since after decoding the zeros in the long codeword - could change, and keep unchanged in subsequent calls) */ - memset(codeword, 0, NN); - - /* copy codeword buffer into message bytes */ - if (remaining < k_pre) - memcpy(codeword, L1_buf, remaining); - else - memcpy(codeword, L1_buf, k_pre); - - /* copy redundancy buffer in parity bytes */ - memcpy(parityword, L2_buf, P); - - /* Decode the buffer and possibly obtain corrected bytes */ - status = eras_dec_rs(codeword, NULL, 0); - if (status == -1) { - /*if (conn == NULL) - opj_event_msg(j2k->cinfo, EVT_WARNING, - "Possible decoding error in codeword @ position #%d\n", (L1_buf - buffer) / k_pre);*/ - errflag = OPJ_TRUE; - /* we can try to safely get out from the function: - if we are here, either this is not an EPB or the first codeword - is too damaged to be helpful */ - /*return OPJ_FALSE;*/ - - } else if (status == 0) { - /*if (conn == NULL) - opj_event_msg(j2k->cinfo, EVT_INFO, "codeword is correctly decoded\n");*/ - - } else if (status <= tt) { - /* it has corrected 0 <= errs <= tt */ - /*if (conn == NULL) - opj_event_msg(j2k->cinfo, EVT_WARNING, "%d errors corrected in codeword\n", status);*/ - errnum += status; - - } else { - /*if (conn == NULL) - opj_event_msg(j2k->cinfo, EVT_WARNING, "EPB correction capability exceeded\n"); - return OPJ_FALSE;*/ - errflag = OPJ_TRUE; - } - - - /* advance parity buffer */ - if ((status >= 0) && (status <= tt)) - /* copy back corrected parity only if all is OK */ - memcpy(L2_buf, parityword, P); - L2_buf += P; - - /* advance message buffer */ - if (remaining < k_pre) { - if ((status >= 0) && (status <= tt)) - /* copy back corrected data only if all is OK */ - memcpy(L1_buf, codeword, remaining); - L1_buf += remaining; - remaining = 0; - - } else { - if ((status >= 0) && (status <= tt)) - /* copy back corrected data only if all is OK */ - memcpy(L1_buf, codeword, k_pre); - L1_buf += k_pre; - remaining -= k_pre; - - } - } - - /* print summary */ - if (!conn) { - - /*if (errnum) - opj_event_msg(j2k->cinfo, EVT_INFO, "+ %d symbol errors corrected (Ps=%.1e)\n", errnum, - (float) errnum / ((float) n_pre * (float) L1 / (float) k_pre));*/ - if (errflag) { - /*opj_event_msg(j2k->cinfo, EVT_INFO, "+ there were unrecoverable errors\n");*/ - return OPJ_FALSE; - } - - } - - /* presumably, now, EPB parameters are correct */ - /* let's get them */ - - /* Simply read the EPB parameters */ - if (conn) - cio->bp = buffer; - cio_skip(cio, 2); /* the marker */ - Lepb = cio_read(cio, 2); - Depb = cio_read(cio, 1); - LDPepb = cio_read(cio, 4); - Pepb = cio_read(cio, 4); - - /* What does Pepb tells us about the protection method? */ - if (((Pepb & 0xF0000000) >> 28) == 0) - sprintf(str1, "pred"); /* predefined */ - else if (((Pepb & 0xF0000000) >> 28) == 1) - sprintf(str1, "crc-%lu", 16 * ((Pepb & 0x00000001) + 1)); /* CRC mode */ - else if (((Pepb & 0xF0000000) >> 28) == 2) - sprintf(str1, "rs(%lu,32)", (Pepb & 0x0000FF00) >> 8); /* RS mode */ - else if (Pepb == 0xFFFFFFFF) - sprintf(str1, "nometh"); /* RS mode */ - else - sprintf(str1, "unknown"); /* unknown */ - - /* Now we write them to screen */ - if (!conn && post_len) - opj_event_msg(j2k->cinfo, EVT_INFO, - "EPB(%d): (%sl, %sp, %u), %lu, %s\n", - cio_tell(cio) - 13, - (Depb & 0x40) ? "" : "n", /* latest EPB or not? */ - (Depb & 0x80) ? "" : "n", /* packed or unpacked EPB? */ - (Depb & 0x3F), /* EPB index value */ - LDPepb, /*length of the data protected by the EPB */ - str1); /* protection method */ - - - /* well, we need to investigate how long is the connected length of packed EPBs */ - myconn = Lepb + 2; - if ((Depb & 0x40) == 0) /* not latest in header */ - jpwl_epb_correct(j2k, /* J2K decompressor handle */ - buffer + Lepb + 2, /* pointer to next EPB in codestream buffer */ - 2, /* EPB type: should be of other type */ - 0, /* only EPB fields */ - 0, /* do not look after */ - &myconn, - NULL - ); - if (conn) - *conn += myconn; - - /*if (!conn) - printf("connected = %d\n", myconn);*/ - - /*cio_seek(j2k->cio, orig_pos); - return OPJ_TRUE;*/ - - /* post-data - the position of L4 buffer is at the end of currently connected EPBs - */ - if (!(L4_bufp)) - L4_buf = buffer + myconn; - else if (!(*L4_bufp)) - L4_buf = buffer + myconn; - else - L4_buf = *L4_bufp; - if (post_len == -1) - L4 = LDPepb - pre_len - 13; - else if (post_len == 0) - L4 = 0; - else - L4 = post_len; - - L3_buf = L2_buf; - - /* Do a further check here on the read parameters */ - if (L4 > (unsigned long) cio_numbytesleft(j2k->cio)) - /* overflow */ - return OPJ_FALSE; - - /* we are ready for decoding the remaining data */ - if (((Pepb & 0xF0000000) >> 28) == 1) { - /* CRC here */ - if ((16 * ((Pepb & 0x00000001) + 1)) == 16) { - - /* CRC-16 */ - unsigned short int mycrc = 0x0000, filecrc = 0x0000; - - /* compute the CRC field */ - remaining = L4; - while (remaining--) - jpwl_updateCRC16(&mycrc, *(L4_buf++)); - - /* read the CRC field */ - filecrc = *(L3_buf++) << 8; - filecrc |= *(L3_buf++); - - /* check the CRC field */ - if (mycrc == filecrc) { - if (conn == NULL) - opj_event_msg(j2k->cinfo, EVT_INFO, "- CRC is OK\n"); - } else { - if (conn == NULL) - opj_event_msg(j2k->cinfo, EVT_WARNING, "- CRC is KO (r=%d, c=%d)\n", filecrc, mycrc); - errflag = OPJ_TRUE; - } - } - - if ((16 * ((Pepb & 0x00000001) + 1)) == 32) { - - /* CRC-32 */ - unsigned long int mycrc = 0x00000000, filecrc = 0x00000000; - - /* compute the CRC field */ - remaining = L4; - while (remaining--) - jpwl_updateCRC32(&mycrc, *(L4_buf++)); - - /* read the CRC field */ - filecrc = *(L3_buf++) << 24; - filecrc |= *(L3_buf++) << 16; - filecrc |= *(L3_buf++) << 8; - filecrc |= *(L3_buf++); - - /* check the CRC field */ - if (mycrc == filecrc) { - if (conn == NULL) - opj_event_msg(j2k->cinfo, EVT_INFO, "- CRC is OK\n"); - } else { - if (conn == NULL) - opj_event_msg(j2k->cinfo, EVT_WARNING, "- CRC is KO (r=%d, c=%d)\n", filecrc, mycrc); - errflag = OPJ_TRUE; - } - } - - } else if (Pepb == 0xFFFFFFFF) { - /* no method */ - - /* advance without doing anything */ - remaining = L4; - while (remaining--) - L4_buf++; - - } else if ((((Pepb & 0xF0000000) >> 28) == 2) || (((Pepb & 0xF0000000) >> 28) == 0)) { - /* RS coding here */ - - if (((Pepb & 0xF0000000) >> 28) == 0) { - - k_post = k_pre; - n_post = n_pre; - - } else { - - k_post = 32; - n_post = (Pepb & 0x0000FF00) >> 8; - } - - /* Initialize RS structures */ - P = n_post - k_post; - NN_P = NN - P; - tt = (int) floor((float) P / 2.0F); /* again, correction capability */ - memset(codeword, 0, NN); - parityword = codeword + NN_P; - init_rs(NN_P); - - /* Correct post-data message words */ - /*L4_buf = buffer + Lepb + 2;*/ - L3_buf = L2_buf; - remaining = L4; - while (remaining) { - - /* always zero-pad codewords */ - /* (this is required, since after decoding the zeros in the long codeword - could change, and keep unchanged in subsequent calls) */ - memset(codeword, 0, NN); - - /* copy codeword buffer into message bytes */ - if (remaining < k_post) - memcpy(codeword, L4_buf, remaining); - else - memcpy(codeword, L4_buf, k_post); - - /* copy redundancy buffer in parity bytes */ - memcpy(parityword, L3_buf, P); - - /* Decode the buffer and possibly obtain corrected bytes */ - status = eras_dec_rs(codeword, NULL, 0); - if (status == -1) { - /*if (conn == NULL) - opj_event_msg(j2k->cinfo, EVT_WARNING, - "Possible decoding error in codeword @ position #%d\n", (L4_buf - (buffer + Lepb + 2)) / k_post);*/ - errflag = OPJ_TRUE; - - } else if (status == 0) { - /*if (conn == NULL) - opj_event_msg(j2k->cinfo, EVT_INFO, "codeword is correctly decoded\n");*/ - - } else if (status <= tt) { - /*if (conn == NULL) - opj_event_msg(j2k->cinfo, EVT_WARNING, "%d errors corrected in codeword\n", status);*/ - errnum += status; - - } else { - /*if (conn == NULL) - opj_event_msg(j2k->cinfo, EVT_WARNING, "EPB correction capability exceeded\n"); - return OPJ_FALSE;*/ - errflag = OPJ_TRUE; - } - - - /* advance parity buffer */ - if ((status >= 0) && (status <= tt)) - /* copy back corrected data only if all is OK */ - memcpy(L3_buf, parityword, P); - L3_buf += P; - - /* advance message buffer */ - if (remaining < k_post) { - if ((status >= 0) && (status <= tt)) - /* copy back corrected data only if all is OK */ - memcpy(L4_buf, codeword, remaining); - L4_buf += remaining; - remaining = 0; - - } else { - if ((status >= 0) && (status <= tt)) - /* copy back corrected data only if all is OK */ - memcpy(L4_buf, codeword, k_post); - L4_buf += k_post; - remaining -= k_post; - - } - } - } - - /* give back the L4_buf address */ - if (L4_bufp) - *L4_bufp = L4_buf; - - /* print summary */ - if (!conn) { - - if (errnum) - opj_event_msg(j2k->cinfo, EVT_INFO, "- %d symbol errors corrected (Ps=%.1e)\n", errnum, - (float) errnum / (float) LDPepb); - if (errflag) - opj_event_msg(j2k->cinfo, EVT_INFO, "- there were unrecoverable errors\n"); - - } - - cio_seek(j2k->cio, orig_pos); - - return OPJ_TRUE; -} - -void jpwl_epc_write(opj_j2k_t *j2k, jpwl_epc_ms_t *epc, unsigned char *buf) { - - /* Marker */ - *(buf++) = (unsigned char) (J2K_MS_EPC >> 8); - *(buf++) = (unsigned char) (J2K_MS_EPC >> 0); - - /* Lepc */ - *(buf++) = (unsigned char) (epc->Lepc >> 8); - *(buf++) = (unsigned char) (epc->Lepc >> 0); - - /* Pcrc */ - *(buf++) = (unsigned char) (epc->Pcrc >> 8); - *(buf++) = (unsigned char) (epc->Pcrc >> 0); - - /* DL */ - *(buf++) = (unsigned char) (epc->DL >> 24); - *(buf++) = (unsigned char) (epc->DL >> 16); - *(buf++) = (unsigned char) (epc->DL >> 8); - *(buf++) = (unsigned char) (epc->DL >> 0); - - /* Pepc */ - *(buf++) = (unsigned char) (epc->Pepc >> 0); - - /* Data */ - /*memcpy(buf, epc->data, (size_t) epc->Lepc - 9);*/ - memset(buf, 0, (size_t) epc->Lepc - 9); - - /* update markers struct */ - j2k_add_marker(j2k->cstr_info, J2K_MS_EPC, -1, epc->Lepc + 2); - -}; - -int jpwl_esds_add(opj_j2k_t *j2k, jpwl_marker_t *jwmarker, int *jwmarker_num, - int comps, unsigned char addrm, unsigned char ad_size, - unsigned char senst, unsigned char se_size, - double place_pos, int tileno) { - - return 0; -} - -jpwl_esd_ms_t *jpwl_esd_create(opj_j2k_t *j2k, int comp, - unsigned char addrm, unsigned char ad_size, - unsigned char senst, int se_size, int tileno, - unsigned long int svalnum, void *sensval) { - - jpwl_esd_ms_t *esd = NULL; - - /* Alloc space */ - if (!(esd = (jpwl_esd_ms_t *) opj_malloc((size_t) 1 * sizeof (jpwl_esd_ms_t)))) { - opj_event_msg(j2k->cinfo, EVT_ERROR, "Could not allocate room for ESD MS\n"); - return NULL; - }; - - /* if relative sensitivity, activate byte range mode */ - if (senst == 0) - addrm = 1; - - /* size of sensval's ... */ - if ((ad_size != 0) && (ad_size != 2) && (ad_size != 4)) { - opj_event_msg(j2k->cinfo, EVT_ERROR, "Address size %d for ESD MS is forbidden\n", ad_size); - return NULL; - } - if ((se_size != 1) && (se_size != 2)) { - opj_event_msg(j2k->cinfo, EVT_ERROR, "Sensitivity size %d for ESD MS is forbidden\n", se_size); - return NULL; - } - - /* ... depends on the addressing mode */ - switch (addrm) { - - /* packet mode */ - case (0): - ad_size = 0; /* as per the standard */ - esd->sensval_size = (unsigned int)se_size; - break; - - /* byte range */ - case (1): - /* auto sense address size */ - if (ad_size == 0) - /* if there are more than 66% of (2^16 - 1) bytes, switch to 4 bytes - (we keep space for possible EPBs being inserted) */ - ad_size = (j2k->cstr_info->codestream_size > (1 * 65535 / 3)) ? 4 : 2; - esd->sensval_size = ad_size + ad_size + se_size; - break; - - /* packet range */ - case (2): - /* auto sense address size */ - if (ad_size == 0) - /* if there are more than 2^16 - 1 packets, switch to 4 bytes */ - ad_size = (j2k->cstr_info->packno > 65535) ? 4 : 2; - esd->sensval_size = ad_size + ad_size + se_size; - break; - - case (3): - opj_event_msg(j2k->cinfo, EVT_ERROR, "Address mode %d for ESD MS is unimplemented\n", addrm); - return NULL; - - default: - opj_event_msg(j2k->cinfo, EVT_ERROR, "Address mode %d for ESD MS is forbidden\n", addrm); - return NULL; - } - - /* set or unset sensitivity values */ - if (svalnum <= 0) { - - switch (senst) { - - /* just based on the portions of a codestream */ - case (0): - /* MH + no. of THs + no. of packets */ - svalnum = 1 + (j2k->cstr_info->tw * j2k->cstr_info->th) * (1 + j2k->cstr_info->packno); - break; - - /* all the ones that are based on the packets */ - default: - if (tileno < 0) - /* MH: all the packets and all the tiles info is written */ - svalnum = j2k->cstr_info->tw * j2k->cstr_info->th * j2k->cstr_info->packno; - else - /* TPH: only that tile info is written */ - svalnum = j2k->cstr_info->packno; - break; - - } - } - - /* fill private fields */ - esd->senst = senst; - esd->ad_size = ad_size; - esd->se_size = se_size; - esd->addrm = addrm; - esd->svalnum = svalnum; - esd->numcomps = j2k->image->numcomps; - esd->tileno = tileno; - - /* Set the ESD parameters */ - /* length, excluding data field */ - if (esd->numcomps < 257) - esd->Lesd = 4 + (unsigned short int) (esd->svalnum * esd->sensval_size); - else - esd->Lesd = 5 + (unsigned short int) (esd->svalnum * esd->sensval_size); - - /* component data field */ - if (comp >= 0) - esd->Cesd = comp; - else - /* we are averaging */ - esd->Cesd = 0; - - /* Pesd field */ - esd->Pesd = 0x00; - esd->Pesd |= (esd->addrm & 0x03) << 6; /* addressing mode */ - esd->Pesd |= (esd->senst & 0x07) << 3; /* sensitivity type */ - esd->Pesd |= ((esd->se_size >> 1) & 0x01) << 2; /* sensitivity size */ - esd->Pesd |= ((esd->ad_size >> 2) & 0x01) << 1; /* addressing size */ - esd->Pesd |= (comp < 0) ? 0x01 : 0x00; /* averaging components */ - - /* if pointer to sensval is NULL, we can fill data field by ourselves */ - if (!sensval) { - - /* old code moved to jpwl_esd_fill() */ - esd->data = NULL; - - } else { - /* we set the data field as the sensitivity values poinnter passed to the function */ - esd->data = (unsigned char *) sensval; - } - - return (esd); -} - -opj_bool jpwl_esd_fill(opj_j2k_t *j2k, jpwl_esd_ms_t *esd, unsigned char *buf) { - - int i; - unsigned long int vv; - unsigned long int addr1 = 0L, addr2 = 0L; - double dvalue = 0.0, Omax2, tmp, TSE = 0.0, MSE, oldMSE = 0.0, PSNR, oldPSNR = 0.0; - unsigned short int pfpvalue; - unsigned long int addrmask = 0x00000000; - opj_bool doneMH = OPJ_FALSE, doneTPH = OPJ_FALSE; - - /* sensitivity values in image info are as follows: - - for each tile, distotile is the starting distortion for that tile, sum of all components - - for each packet in a tile, disto is the distortion reduction caused by that packet to that tile - - the TSE for a single tile should be given by distotile - sum(disto) , for all components - - the MSE for a single tile is given by TSE / nbpix , for all components - - the PSNR for a single tile is given by 10*log10( Omax^2 / MSE) , for all components - (Omax is given by 2^bpp - 1 for unsigned images and by 2^(bpp - 1) - 1 for signed images - */ - - /* browse all components and find Omax */ - Omax2 = 0.0; - for (i = 0; i < j2k->image->numcomps; i++) { - tmp = pow(2.0, (double) (j2k->image->comps[i].sgnd ? - (j2k->image->comps[i].bpp - 1) : (j2k->image->comps[i].bpp))) - 1; - if (tmp > Omax2) - Omax2 = tmp; - } - Omax2 = Omax2 * Omax2; - - /* if pointer of esd->data is not null, simply write down all the values byte by byte */ - if (esd->data) { - for (i = 0; i < (int) esd->svalnum; i++) - *(buf++) = esd->data[i]; - return OPJ_TRUE; - } - - /* addressing mask */ - if (esd->ad_size == 2) - addrmask = 0x0000FFFF; /* two bytes */ - else - addrmask = 0xFFFFFFFF; /* four bytes */ - - /* set on precise point where sensitivity starts */ - if (esd->numcomps < 257) - buf += 6; - else - buf += 7; - - /* let's fill the data fields */ - for (vv = (esd->tileno < 0) ? 0 : (j2k->cstr_info->packno * esd->tileno); vv < esd->svalnum; vv++) { - - int thistile = vv / j2k->cstr_info->packno, thispacket = vv % j2k->cstr_info->packno; - - /* skip for the hack some lines below */ - if (thistile == j2k->cstr_info->tw * j2k->cstr_info->th) - break; - - /* starting tile distortion */ - if (thispacket == 0) { - TSE = j2k->cstr_info->tile[thistile].distotile; - oldMSE = TSE / j2k->cstr_info->tile[thistile].numpix; - oldPSNR = 10.0 * log10(Omax2 / oldMSE); - } - - /* TSE */ - TSE -= j2k->cstr_info->tile[thistile].packet[thispacket].disto; - - /* MSE */ - MSE = TSE / j2k->cstr_info->tile[thistile].numpix; - - /* PSNR */ - PSNR = 10.0 * log10(Omax2 / MSE); - - /* fill the address range */ - switch (esd->addrm) { - - /* packet mode */ - case (0): - /* nothing, there is none */ - break; - - /* byte range */ - case (1): - /* start address of packet */ - addr1 = (j2k->cstr_info->tile[thistile].packet[thispacket].start_pos) & addrmask; - /* end address of packet */ - addr2 = (j2k->cstr_info->tile[thistile].packet[thispacket].end_pos) & addrmask; - break; - - /* packet range */ - case (2): - /* not implemented here */ - opj_event_msg(j2k->cinfo, EVT_WARNING, "Addressing mode packet_range is not implemented\n"); - break; - - /* unknown addressing method */ - default: - /* not implemented here */ - opj_event_msg(j2k->cinfo, EVT_WARNING, "Unknown addressing mode\n"); - break; - - } - - /* hack for writing relative sensitivity of MH and TPHs */ - if ((esd->senst == 0) && (thispacket == 0)) { - - /* possible MH */ - if ((thistile == 0) && !doneMH) { - /* we have to manage MH addresses */ - addr1 = 0; /* start of MH */ - addr2 = j2k->cstr_info->main_head_end; /* end of MH */ - /* set special dvalue for this MH */ - dvalue = -10.0; - doneMH = OPJ_TRUE; /* don't come here anymore */ - vv--; /* wrap back loop counter */ - - } else if (!doneTPH) { - /* we have to manage TPH addresses */ - addr1 = j2k->cstr_info->tile[thistile].start_pos; - addr2 = j2k->cstr_info->tile[thistile].end_header; - /* set special dvalue for this TPH */ - dvalue = -1.0; - doneTPH = OPJ_TRUE; /* don't come here till the next tile */ - vv--; /* wrap back loop counter */ - } - - } else - doneTPH = OPJ_FALSE; /* reset TPH counter */ - - /* write the addresses to the buffer */ - switch (esd->ad_size) { - - case (0): - /* do nothing */ - break; - - case (2): - /* two bytes */ - *(buf++) = (unsigned char) (addr1 >> 8); - *(buf++) = (unsigned char) (addr1 >> 0); - *(buf++) = (unsigned char) (addr2 >> 8); - *(buf++) = (unsigned char) (addr2 >> 0); - break; - - case (4): - /* four bytes */ - *(buf++) = (unsigned char) (addr1 >> 24); - *(buf++) = (unsigned char) (addr1 >> 16); - *(buf++) = (unsigned char) (addr1 >> 8); - *(buf++) = (unsigned char) (addr1 >> 0); - *(buf++) = (unsigned char) (addr2 >> 24); - *(buf++) = (unsigned char) (addr2 >> 16); - *(buf++) = (unsigned char) (addr2 >> 8); - *(buf++) = (unsigned char) (addr2 >> 0); - break; - - default: - /* do nothing */ - break; - } - - - /* let's fill the value field */ - switch (esd->senst) { - - /* relative sensitivity */ - case (0): - /* we just write down the packet ordering */ - if (dvalue == -10) - /* MH */ - dvalue = MAX_V1 + 1000.0; /* this will cause pfpvalue set to 0xFFFF */ - else if (dvalue == -1) - /* TPH */ - dvalue = MAX_V1 + 1000.0; /* this will cause pfpvalue set to 0xFFFF */ - else - /* packet: first is most important, and then in decreasing order - down to the last, which counts for 1 */ - dvalue = jpwl_pfp_to_double((unsigned short) (j2k->cstr_info->packno - thispacket), esd->se_size); - break; - - /* MSE */ - case (1): - /* !!! WRONG: let's put here disto field of packets !!! */ - dvalue = MSE; - break; - - /* MSE reduction */ - case (2): - dvalue = oldMSE - MSE; - oldMSE = MSE; - break; - - /* PSNR */ - case (3): - dvalue = PSNR; - break; - - /* PSNR increase */ - case (4): - dvalue = PSNR - oldPSNR; - oldPSNR = PSNR; - break; - - /* MAXERR */ - case (5): - dvalue = 0.0; - opj_event_msg(j2k->cinfo, EVT_WARNING, "MAXERR sensitivity mode is not implemented\n"); - break; - - /* TSE */ - case (6): - dvalue = TSE; - break; - - /* reserved */ - case (7): - dvalue = 0.0; - opj_event_msg(j2k->cinfo, EVT_WARNING, "Reserved sensitivity mode is not implemented\n"); - break; - - default: - dvalue = 0.0; - break; - } - - /* compute the pseudo-floating point value */ - pfpvalue = jpwl_double_to_pfp(dvalue, esd->se_size); - - /* write the pfp value to the buffer */ - switch (esd->se_size) { - - case (1): - /* one byte */ - *(buf++) = (unsigned char) (pfpvalue >> 0); - break; - - case (2): - /* two bytes */ - *(buf++) = (unsigned char) (pfpvalue >> 8); - *(buf++) = (unsigned char) (pfpvalue >> 0); - break; - } - - } - - return OPJ_TRUE; -} - -void jpwl_esd_write(opj_j2k_t *j2k, jpwl_esd_ms_t *esd, unsigned char *buf) { - - /* Marker */ - *(buf++) = (unsigned char) (J2K_MS_ESD >> 8); - *(buf++) = (unsigned char) (J2K_MS_ESD >> 0); - - /* Lesd */ - *(buf++) = (unsigned char) (esd->Lesd >> 8); - *(buf++) = (unsigned char) (esd->Lesd >> 0); - - /* Cesd */ - if (esd->numcomps >= 257) - *(buf++) = (unsigned char) (esd->Cesd >> 8); - *(buf++) = (unsigned char) (esd->Cesd >> 0); - - /* Pesd */ - *(buf++) = (unsigned char) (esd->Pesd >> 0); - - /* Data */ - if (esd->numcomps < 257) - memset(buf, 0xAA, (size_t) esd->Lesd - 4); - /*memcpy(buf, esd->data, (size_t) esd->Lesd - 4);*/ - else - memset(buf, 0xAA, (size_t) esd->Lesd - 5); - /*memcpy(buf, esd->data, (size_t) esd->Lesd - 5);*/ - - /* update markers struct */ - j2k_add_marker(j2k->cstr_info, J2K_MS_ESD, -1, esd->Lesd + 2); - -} - -unsigned short int jpwl_double_to_pfp(double V, int bytes) { - - unsigned short int em, e, m; - - switch (bytes) { - - case (1): - - if (V < MIN_V1) { - e = 0x0000; - m = 0x0000; - } else if (V > MAX_V1) { - e = 0x000F; - m = 0x000F; - } else { - e = (unsigned short int) (floor(log(V) * 1.44269504088896) / 4.0); - m = (unsigned short int) (0.5 + (V / (pow(2.0, (double) (4 * e))))); - } - em = ((e & 0x000F) << 4) + (m & 0x000F); - break; - - case (2): - - if (V < MIN_V2) { - e = 0x0000; - m = 0x0000; - } else if (V > MAX_V2) { - e = 0x001F; - m = 0x07FF; - } else { - e = (unsigned short int) floor(log(V) * 1.44269504088896) + 15; - m = (unsigned short int) (0.5 + 2048.0 * ((V / (pow(2.0, (double) e - 15.0))) - 1.0)); - } - em = ((e & 0x001F) << 11) + (m & 0x07FF); - break; - - default: - - em = 0x0000; - break; - }; - - return em; -} - -double jpwl_pfp_to_double(unsigned short int em, int bytes) { - - double V; - - switch (bytes) { - - case 1: - V = (double) (em & 0x0F) * pow(2.0, (double) (em & 0xF0)); - break; - - case 2: - - V = pow(2.0, (double) ((em & 0xF800) >> 11) - 15.0) * (1.0 + (double) (em & 0x07FF) / 2048.0); - break; - - default: - V = 0.0; - break; - - } - - return V; - -} - -opj_bool jpwl_update_info(opj_j2k_t *j2k, jpwl_marker_t *jwmarker, int jwmarker_num) { - - int mm; - unsigned long int addlen; - - opj_codestream_info_t *info = j2k->cstr_info; - int tileno, tpno, packno, numtiles = info->th * info->tw, numpacks = info->packno; - - if (!j2k || !jwmarker ) { - opj_event_msg(j2k->cinfo, EVT_ERROR, "J2K handle or JPWL markers list badly allocated\n"); - return OPJ_FALSE; - } - - /* main_head_end: how many markers are there before? */ - addlen = 0; - for (mm = 0; mm < jwmarker_num; mm++) - if (jwmarker[mm].pos < (unsigned long int) info->main_head_end) - addlen += jwmarker[mm].len + 2; - info->main_head_end += addlen; - - /* codestream_size: always increment with all markers */ - addlen = 0; - for (mm = 0; mm < jwmarker_num; mm++) - addlen += jwmarker[mm].len + 2; - info->codestream_size += addlen; - - /* navigate through all the tiles */ - for (tileno = 0; tileno < numtiles; tileno++) { - - /* start_pos: increment with markers before SOT */ - addlen = 0; - for (mm = 0; mm < jwmarker_num; mm++) - if (jwmarker[mm].pos < (unsigned long int) info->tile[tileno].start_pos) - addlen += jwmarker[mm].len + 2; - info->tile[tileno].start_pos += addlen; - - /* end_header: increment with markers before of it */ - addlen = 0; - for (mm = 0; mm < jwmarker_num; mm++) - if (jwmarker[mm].pos < (unsigned long int) info->tile[tileno].end_header) - addlen += jwmarker[mm].len + 2; - info->tile[tileno].end_header += addlen; - - /* end_pos: increment with markers before the end of this tile */ - /* code is disabled, since according to JPWL no markers can be beyond TPH */ - addlen = 0; - for (mm = 0; mm < jwmarker_num; mm++) - if (jwmarker[mm].pos < (unsigned long int) info->tile[tileno].end_pos) - addlen += jwmarker[mm].len + 2; - info->tile[tileno].end_pos += addlen; - - /* navigate through all the tile parts */ - for (tpno = 0; tpno < info->tile[tileno].num_tps; tpno++) { - - /* start_pos: increment with markers before SOT */ - addlen = 0; - for (mm = 0; mm < jwmarker_num; mm++) - if (jwmarker[mm].pos < (unsigned long int) info->tile[tileno].tp[tpno].tp_start_pos) - addlen += jwmarker[mm].len + 2; - info->tile[tileno].tp[tpno].tp_start_pos += addlen; - - /* end_header: increment with markers before of it */ - addlen = 0; - for (mm = 0; mm < jwmarker_num; mm++) - if (jwmarker[mm].pos < (unsigned long int) info->tile[tileno].tp[tpno].tp_end_header) - addlen += jwmarker[mm].len + 2; - info->tile[tileno].tp[tpno].tp_end_header += addlen; - - /* end_pos: increment with markers before the end of this tile part */ - addlen = 0; - for (mm = 0; mm < jwmarker_num; mm++) - if (jwmarker[mm].pos < (unsigned long int) info->tile[tileno].tp[tpno].tp_end_pos) - addlen += jwmarker[mm].len + 2; - info->tile[tileno].tp[tpno].tp_end_pos += addlen; - - } - - /* navigate through all the packets in this tile */ - for (packno = 0; packno < numpacks; packno++) { - - /* start_pos: increment with markers before the packet */ - /* disabled for the same reason as before */ - addlen = 0; - for (mm = 0; mm < jwmarker_num; mm++) - if (jwmarker[mm].pos <= (unsigned long int) info->tile[tileno].packet[packno].start_pos) - addlen += jwmarker[mm].len + 2; - info->tile[tileno].packet[packno].start_pos += addlen; - - /* end_ph_pos: increment with markers before the packet */ - /* disabled for the same reason as before */ - /*addlen = 0; - for (mm = 0; mm < jwmarker_num; mm++) - if (jwmarker[mm].pos < (unsigned long int) info->tile[tileno].packet[packno].end_ph_pos) - addlen += jwmarker[mm].len + 2;*/ - info->tile[tileno].packet[packno].end_ph_pos += addlen; - - /* end_pos: increment if marker is before the end of packet */ - /* disabled for the same reason as before */ - /*addlen = 0; - for (mm = 0; mm < jwmarker_num; mm++) - if (jwmarker[mm].pos < (unsigned long int) info->tile[tileno].packet[packno].end_pos) - addlen += jwmarker[mm].len + 2;*/ - info->tile[tileno].packet[packno].end_pos += addlen; - - } - } - - /* reorder the markers list */ - - return OPJ_TRUE; -} - -#endif /* USE_JPWL */ diff --git a/openjpeg-dotnet/libopenjpeg/jpwl/rs.c b/openjpeg-dotnet/libopenjpeg/jpwl/rs.c deleted file mode 100644 index 0841c637..00000000 --- a/openjpeg-dotnet/libopenjpeg/jpwl/rs.c +++ /dev/null @@ -1,597 +0,0 @@ - /* - * Copyright (c) 2001-2003, David Janssens - * Copyright (c) 2002-2003, Yannick Verschueren - * Copyright (c) 2003-2005, Francois Devaux and Antonin Descampe - * Copyright (c) 2005, Herve Drolon, FreeImage Team - * Copyright (c) 2002-2005, Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium - * Copyright (c) 2005-2006, Dept. of Electronic and Information Engineering, Universita' degli Studi di Perugia, Italy - * 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. - */ - -#ifdef USE_JPWL - -/** -@file rs.c -@brief Functions used to compute the Reed-Solomon parity and check of byte arrays - -*/ - -/** - * Reed-Solomon coding and decoding - * Phil Karn (karn@ka9q.ampr.org) September 1996 - * - * This file is derived from the program "new_rs_erasures.c" by Robert - * Morelos-Zaragoza (robert@spectra.eng.hawaii.edu) and Hari Thirumoorthy - * (harit@spectra.eng.hawaii.edu), Aug 1995 - * - * I've made changes to improve performance, clean up the code and make it - * easier to follow. Data is now passed to the encoding and decoding functions - * through arguments rather than in global arrays. The decode function returns - * the number of corrected symbols, or -1 if the word is uncorrectable. - * - * This code supports a symbol size from 2 bits up to 16 bits, - * implying a block size of 3 2-bit symbols (6 bits) up to 65535 - * 16-bit symbols (1,048,560 bits). The code parameters are set in rs.h. - * - * Note that if symbols larger than 8 bits are used, the type of each - * data array element switches from unsigned char to unsigned int. The - * caller must ensure that elements larger than the symbol range are - * not passed to the encoder or decoder. - * - */ -#include -#include -#include "rs.h" - -/* This defines the type used to store an element of the Galois Field - * used by the code. Make sure this is something larger than a char if - * if anything larger than GF(256) is used. - * - * Note: unsigned char will work up to GF(256) but int seems to run - * faster on the Pentium. - */ -typedef int gf; - -/* KK = number of information symbols */ -static int KK; - -/* Primitive polynomials - see Lin & Costello, Appendix A, - * and Lee & Messerschmitt, p. 453. - */ -#if(MM == 2)/* Admittedly silly */ -int Pp[MM+1] = { 1, 1, 1 }; - -#elif(MM == 3) -/* 1 + x + x^3 */ -int Pp[MM+1] = { 1, 1, 0, 1 }; - -#elif(MM == 4) -/* 1 + x + x^4 */ -int Pp[MM+1] = { 1, 1, 0, 0, 1 }; - -#elif(MM == 5) -/* 1 + x^2 + x^5 */ -int Pp[MM+1] = { 1, 0, 1, 0, 0, 1 }; - -#elif(MM == 6) -/* 1 + x + x^6 */ -int Pp[MM+1] = { 1, 1, 0, 0, 0, 0, 1 }; - -#elif(MM == 7) -/* 1 + x^3 + x^7 */ -int Pp[MM+1] = { 1, 0, 0, 1, 0, 0, 0, 1 }; - -#elif(MM == 8) -/* 1+x^2+x^3+x^4+x^8 */ -int Pp[MM+1] = { 1, 0, 1, 1, 1, 0, 0, 0, 1 }; - -#elif(MM == 9) -/* 1+x^4+x^9 */ -int Pp[MM+1] = { 1, 0, 0, 0, 1, 0, 0, 0, 0, 1 }; - -#elif(MM == 10) -/* 1+x^3+x^10 */ -int Pp[MM+1] = { 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1 }; - -#elif(MM == 11) -/* 1+x^2+x^11 */ -int Pp[MM+1] = { 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1 }; - -#elif(MM == 12) -/* 1+x+x^4+x^6+x^12 */ -int Pp[MM+1] = { 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1 }; - -#elif(MM == 13) -/* 1+x+x^3+x^4+x^13 */ -int Pp[MM+1] = { 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1 }; - -#elif(MM == 14) -/* 1+x+x^6+x^10+x^14 */ -int Pp[MM+1] = { 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1 }; - -#elif(MM == 15) -/* 1+x+x^15 */ -int Pp[MM+1] = { 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }; - -#elif(MM == 16) -/* 1+x+x^3+x^12+x^16 */ -int Pp[MM+1] = { 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1 }; - -#else -#error "MM must be in range 2-16" -#endif - -/* Alpha exponent for the first root of the generator polynomial */ -#define B0 0 /* Different from the default 1 */ - -/* index->polynomial form conversion table */ -gf Alpha_to[NN + 1]; - -/* Polynomial->index form conversion table */ -gf Index_of[NN + 1]; - -/* No legal value in index form represents zero, so - * we need a special value for this purpose - */ -#define A0 (NN) - -/* Generator polynomial g(x) - * Degree of g(x) = 2*TT - * has roots @**B0, @**(B0+1), ... ,@^(B0+2*TT-1) - */ -/*gf Gg[NN - KK + 1];*/ -gf Gg[NN - 1]; - -/* Compute x % NN, where NN is 2**MM - 1, - * without a slow divide - */ -static /*inline*/ gf -modnn(int x) -{ - while (x >= NN) { - x -= NN; - x = (x >> MM) + (x & NN); - } - return x; -} - -/*#define min(a,b) ((a) < (b) ? (a) : (b))*/ - -#define CLEAR(a,n) {\ - int ci;\ - for(ci=(n)-1;ci >=0;ci--)\ - (a)[ci] = 0;\ - } - -#define COPY(a,b,n) {\ - int ci;\ - for(ci=(n)-1;ci >=0;ci--)\ - (a)[ci] = (b)[ci];\ - } -#define COPYDOWN(a,b,n) {\ - int ci;\ - for(ci=(n)-1;ci >=0;ci--)\ - (a)[ci] = (b)[ci];\ - } - -void init_rs(int k) -{ - KK = k; - if (KK >= NN) { - printf("KK must be less than 2**MM - 1\n"); - exit(1); - } - - generate_gf(); - gen_poly(); -} - -/* generate GF(2**m) from the irreducible polynomial p(X) in p[0]..p[m] - lookup tables: index->polynomial form alpha_to[] contains j=alpha**i; - polynomial form -> index form index_of[j=alpha**i] = i - alpha=2 is the primitive element of GF(2**m) - HARI's COMMENT: (4/13/94) alpha_to[] can be used as follows: - Let @ represent the primitive element commonly called "alpha" that - is the root of the primitive polynomial p(x). Then in GF(2^m), for any - 0 <= i <= 2^m-2, - @^i = a(0) + a(1) @ + a(2) @^2 + ... + a(m-1) @^(m-1) - where the binary vector (a(0),a(1),a(2),...,a(m-1)) is the representation - of the integer "alpha_to[i]" with a(0) being the LSB and a(m-1) the MSB. Thus for - example the polynomial representation of @^5 would be given by the binary - representation of the integer "alpha_to[5]". - Similarily, index_of[] can be used as follows: - As above, let @ represent the primitive element of GF(2^m) that is - the root of the primitive polynomial p(x). In order to find the power - of @ (alpha) that has the polynomial representation - a(0) + a(1) @ + a(2) @^2 + ... + a(m-1) @^(m-1) - we consider the integer "i" whose binary representation with a(0) being LSB - and a(m-1) MSB is (a(0),a(1),...,a(m-1)) and locate the entry - "index_of[i]". Now, @^index_of[i] is that element whose polynomial - representation is (a(0),a(1),a(2),...,a(m-1)). - NOTE: - The element alpha_to[2^m-1] = 0 always signifying that the - representation of "@^infinity" = 0 is (0,0,0,...,0). - Similarily, the element index_of[0] = A0 always signifying - that the power of alpha which has the polynomial representation - (0,0,...,0) is "infinity". - -*/ - -void -generate_gf(void) -{ - register int i, mask; - - mask = 1; - Alpha_to[MM] = 0; - for (i = 0; i < MM; i++) { - Alpha_to[i] = mask; - Index_of[Alpha_to[i]] = i; - /* If Pp[i] == 1 then, term @^i occurs in poly-repr of @^MM */ - if (Pp[i] != 0) - Alpha_to[MM] ^= mask; /* Bit-wise EXOR operation */ - mask <<= 1; /* single left-shift */ - } - Index_of[Alpha_to[MM]] = MM; - /* - * Have obtained poly-repr of @^MM. Poly-repr of @^(i+1) is given by - * poly-repr of @^i shifted left one-bit and accounting for any @^MM - * term that may occur when poly-repr of @^i is shifted. - */ - mask >>= 1; - for (i = MM + 1; i < NN; i++) { - if (Alpha_to[i - 1] >= mask) - Alpha_to[i] = Alpha_to[MM] ^ ((Alpha_to[i - 1] ^ mask) << 1); - else - Alpha_to[i] = Alpha_to[i - 1] << 1; - Index_of[Alpha_to[i]] = i; - } - Index_of[0] = A0; - Alpha_to[NN] = 0; -} - - -/* - * Obtain the generator polynomial of the TT-error correcting, length - * NN=(2**MM -1) Reed Solomon code from the product of (X+@**(B0+i)), i = 0, - * ... ,(2*TT-1) - * - * Examples: - * - * If B0 = 1, TT = 1. deg(g(x)) = 2*TT = 2. - * g(x) = (x+@) (x+@**2) - * - * If B0 = 0, TT = 2. deg(g(x)) = 2*TT = 4. - * g(x) = (x+1) (x+@) (x+@**2) (x+@**3) - */ -void -gen_poly(void) -{ - register int i, j; - - Gg[0] = Alpha_to[B0]; - Gg[1] = 1; /* g(x) = (X+@**B0) initially */ - for (i = 2; i <= NN - KK; i++) { - Gg[i] = 1; - /* - * Below multiply (Gg[0]+Gg[1]*x + ... +Gg[i]x^i) by - * (@**(B0+i-1) + x) - */ - for (j = i - 1; j > 0; j--) - if (Gg[j] != 0) - Gg[j] = Gg[j - 1] ^ Alpha_to[modnn((Index_of[Gg[j]]) + B0 + i - 1)]; - else - Gg[j] = Gg[j - 1]; - /* Gg[0] can never be zero */ - Gg[0] = Alpha_to[modnn((Index_of[Gg[0]]) + B0 + i - 1)]; - } - /* convert Gg[] to index form for quicker encoding */ - for (i = 0; i <= NN - KK; i++) - Gg[i] = Index_of[Gg[i]]; -} - - -/* - * take the string of symbols in data[i], i=0..(k-1) and encode - * systematically to produce NN-KK parity symbols in bb[0]..bb[NN-KK-1] data[] - * is input and bb[] is output in polynomial form. Encoding is done by using - * a feedback shift register with appropriate connections specified by the - * elements of Gg[], which was generated above. Codeword is c(X) = - * data(X)*X**(NN-KK)+ b(X) - */ -int -encode_rs(dtype *data, dtype *bb) -{ - register int i, j; - gf feedback; - - CLEAR(bb,NN-KK); - for (i = KK - 1; i >= 0; i--) { -#if (MM != 8) - if(data[i] > NN) - return -1; /* Illegal symbol */ -#endif - feedback = Index_of[data[i] ^ bb[NN - KK - 1]]; - if (feedback != A0) { /* feedback term is non-zero */ - for (j = NN - KK - 1; j > 0; j--) - if (Gg[j] != A0) - bb[j] = bb[j - 1] ^ Alpha_to[modnn(Gg[j] + feedback)]; - else - bb[j] = bb[j - 1]; - bb[0] = Alpha_to[modnn(Gg[0] + feedback)]; - } else { /* feedback term is zero. encoder becomes a - * single-byte shifter */ - for (j = NN - KK - 1; j > 0; j--) - bb[j] = bb[j - 1]; - bb[0] = 0; - } - } - return 0; -} - -/* - * Performs ERRORS+ERASURES decoding of RS codes. If decoding is successful, - * writes the codeword into data[] itself. Otherwise data[] is unaltered. - * - * Return number of symbols corrected, or -1 if codeword is illegal - * or uncorrectable. - * - * First "no_eras" erasures are declared by the calling program. Then, the - * maximum # of errors correctable is t_after_eras = floor((NN-KK-no_eras)/2). - * If the number of channel errors is not greater than "t_after_eras" the - * transmitted codeword will be recovered. Details of algorithm can be found - * in R. Blahut's "Theory ... of Error-Correcting Codes". - */ -int -eras_dec_rs(dtype *data, int *eras_pos, int no_eras) -{ - int deg_lambda, el, deg_omega; - int i, j, r; - gf u,q,tmp,num1,num2,den,discr_r; - gf recd[NN]; - /* Err+Eras Locator poly and syndrome poly */ - /*gf lambda[NN-KK + 1], s[NN-KK + 1]; - gf b[NN-KK + 1], t[NN-KK + 1], omega[NN-KK + 1]; - gf root[NN-KK], reg[NN-KK + 1], loc[NN-KK];*/ - gf lambda[NN + 1], s[NN + 1]; - gf b[NN + 1], t[NN + 1], omega[NN + 1]; - gf root[NN], reg[NN + 1], loc[NN]; - int syn_error, count; - - /* data[] is in polynomial form, copy and convert to index form */ - for (i = NN-1; i >= 0; i--){ -#if (MM != 8) - if(data[i] > NN) - return -1; /* Illegal symbol */ -#endif - recd[i] = Index_of[data[i]]; - } - /* first form the syndromes; i.e., evaluate recd(x) at roots of g(x) - * namely @**(B0+i), i = 0, ... ,(NN-KK-1) - */ - syn_error = 0; - for (i = 1; i <= NN-KK; i++) { - tmp = 0; - for (j = 0; j < NN; j++) - if (recd[j] != A0) /* recd[j] in index form */ - tmp ^= Alpha_to[modnn(recd[j] + (B0+i-1)*j)]; - syn_error |= tmp; /* set flag if non-zero syndrome => - * error */ - /* store syndrome in index form */ - s[i] = Index_of[tmp]; - } - if (!syn_error) { - /* - * if syndrome is zero, data[] is a codeword and there are no - * errors to correct. So return data[] unmodified - */ - return 0; - } - CLEAR(&lambda[1],NN-KK); - lambda[0] = 1; - if (no_eras > 0) { - /* Init lambda to be the erasure locator polynomial */ - lambda[1] = Alpha_to[eras_pos[0]]; - for (i = 1; i < no_eras; i++) { - u = eras_pos[i]; - for (j = i+1; j > 0; j--) { - tmp = Index_of[lambda[j - 1]]; - if(tmp != A0) - lambda[j] ^= Alpha_to[modnn(u + tmp)]; - } - } -#ifdef ERASURE_DEBUG - /* find roots of the erasure location polynomial */ - for(i=1;i<=no_eras;i++) - reg[i] = Index_of[lambda[i]]; - count = 0; - for (i = 1; i <= NN; i++) { - q = 1; - for (j = 1; j <= no_eras; j++) - if (reg[j] != A0) { - reg[j] = modnn(reg[j] + j); - q ^= Alpha_to[reg[j]]; - } - if (!q) { - /* store root and error location - * number indices - */ - root[count] = i; - loc[count] = NN - i; - count++; - } - } - if (count != no_eras) { - printf("\n lambda(x) is WRONG\n"); - return -1; - } -#ifndef NO_PRINT - printf("\n Erasure positions as determined by roots of Eras Loc Poly:\n"); - for (i = 0; i < count; i++) - printf("%d ", loc[i]); - printf("\n"); -#endif -#endif - } - for(i=0;i 0; j--) - if (reg[j] != A0) { - reg[j] = modnn(reg[j] + j); - q ^= Alpha_to[reg[j]]; - } - if (!q) { - /* store root (index-form) and error location number */ - root[count] = i; - loc[count] = NN - i; - count++; - } - } - -#ifdef DEBUG - printf("\n Final error positions:\t"); - for (i = 0; i < count; i++) - printf("%d ", loc[i]); - printf("\n"); -#endif - if (deg_lambda != count) { - /* - * deg(lambda) unequal to number of roots => uncorrectable - * error detected - */ - return -1; - } - /* - * Compute err+eras evaluator poly omega(x) = s(x)*lambda(x) (modulo - * x**(NN-KK)). in index form. Also find deg(omega). - */ - deg_omega = 0; - for (i = 0; i < NN-KK;i++){ - tmp = 0; - j = (deg_lambda < i) ? deg_lambda : i; - for(;j >= 0; j--){ - if ((s[i + 1 - j] != A0) && (lambda[j] != A0)) - tmp ^= Alpha_to[modnn(s[i + 1 - j] + lambda[j])]; - } - if(tmp != 0) - deg_omega = i; - omega[i] = Index_of[tmp]; - } - omega[NN-KK] = A0; - - /* - * Compute error values in poly-form. num1 = omega(inv(X(l))), num2 = - * inv(X(l))**(B0-1) and den = lambda_pr(inv(X(l))) all in poly-form - */ - for (j = count-1; j >=0; j--) { - num1 = 0; - for (i = deg_omega; i >= 0; i--) { - if (omega[i] != A0) - num1 ^= Alpha_to[modnn(omega[i] + i * root[j])]; - } - num2 = Alpha_to[modnn(root[j] * (B0 - 1) + NN)]; - den = 0; - - /* lambda[i+1] for i even is the formal derivative lambda_pr of lambda[i] */ - for (i = min(deg_lambda,NN-KK-1) & ~1; i >= 0; i -=2) { - if(lambda[i+1] != A0) - den ^= Alpha_to[modnn(lambda[i+1] + i * root[j])]; - } - if (den == 0) { -#ifdef DEBUG - printf("\n ERROR: denominator = 0\n"); -#endif - return -1; - } - /* Apply error to data */ - if (num1 != 0) { - data[loc[j]] ^= Alpha_to[modnn(Index_of[num1] + Index_of[num2] + NN - Index_of[den])]; - } - } - return count; -} - - -#endif /* USE_JPWL */ diff --git a/openjpeg-dotnet/libopenjpeg/jpwl/rs.h b/openjpeg-dotnet/libopenjpeg/jpwl/rs.h deleted file mode 100644 index 7d02a477..00000000 --- a/openjpeg-dotnet/libopenjpeg/jpwl/rs.h +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright (c) 2001-2003, David Janssens - * Copyright (c) 2002-2003, Yannick Verschueren - * Copyright (c) 2003-2005, Francois Devaux and Antonin Descampe - * Copyright (c) 2005, Herve Drolon, FreeImage Team - * Copyright (c) 2002-2005, Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium - * Copyright (c) 2005-2006, Dept. of Electronic and Information Engineering, Universita' degli Studi di Perugia, Italy - * 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. - */ - -#ifdef USE_JPWL - -/** -@file rs.h -@brief Functions used to compute Reed-Solomon parity and check of byte arrays - -*/ - -#ifndef __RS_HEADER__ -#define __RS_HEADER__ - -/** Global definitions for Reed-Solomon encoder/decoder - * Phil Karn KA9Q, September 1996 - * - * The parameters MM and KK specify the Reed-Solomon code parameters. - * - * Set MM to be the size of each code symbol in bits. The Reed-Solomon - * block size will then be NN = 2**M - 1 symbols. Supported values are - * defined in rs.c. - * - * Set KK to be the number of data symbols in each block, which must be - * less than the block size. The code will then be able to correct up - * to NN-KK erasures or (NN-KK)/2 errors, or combinations thereof with - * each error counting as two erasures. - */ -#define MM 8 /* RS code over GF(2**MM) - change to suit */ - -/* KK defined in rs.c */ - -#define NN ((1 << MM) - 1) - -#if (MM <= 8) -typedef unsigned char dtype; -#else -typedef unsigned int dtype; -#endif - -/** Initialization function */ -void init_rs(int); - -/** These two functions *must* be called in this order (e.g., - * by init_rs()) before any encoding/decoding - */ -void generate_gf(void); /* Generate Galois Field */ -void gen_poly(void); /* Generate generator polynomial */ - -/** Reed-Solomon encoding - * data[] is the input block, parity symbols are placed in bb[] - * bb[] may lie past the end of the data, e.g., for (255,223): - * encode_rs(&data[0],&data[223]); - */ -int encode_rs(dtype data[], dtype bb[]); - -/** Reed-Solomon erasures-and-errors decoding - * The received block goes into data[], and a list of zero-origin - * erasure positions, if any, goes in eras_pos[] with a count in no_eras. - * - * The decoder corrects the symbols in place, if possible and returns - * the number of corrected symbols. If the codeword is illegal or - * uncorrectible, the data array is unchanged and -1 is returned - */ -int eras_dec_rs(dtype data[], int eras_pos[], int no_eras); - -/** -Computes the minimum between two integers -@param a first integer to compare -@param b second integer to compare -@return returns the minimum integer between a and b -*/ -#ifndef min -#define min(a,b) (((a) < (b)) ? (a) : (b)) -#endif /* min */ - -#endif /* __RS_HEADER__ */ - - -#endif /* USE_JPWL */ diff --git a/openjpeg-dotnet/libopenjpeg/mct.c b/openjpeg-dotnet/libopenjpeg/mct.c deleted file mode 100644 index 870993b0..00000000 --- a/openjpeg-dotnet/libopenjpeg/mct.c +++ /dev/null @@ -1,190 +0,0 @@ -/* - * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium - * Copyright (c) 2002-2007, Professor Benoit Macq - * Copyright (c) 2001-2003, David Janssens - * Copyright (c) 2002-2003, Yannick Verschueren - * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe - * Copyright (c) 2005, Herve Drolon, FreeImage Team - * 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. - */ - -#ifdef __SSE__ -#include -#endif - -#include "opj_includes.h" - -/* */ -/* This table contains the norms of the basis function of the reversible MCT. */ -/* */ -static const double mct_norms[3] = { 1.732, .8292, .8292 }; - -/* */ -/* This table contains the norms of the basis function of the irreversible MCT. */ -/* */ -static const double mct_norms_real[3] = { 1.732, 1.805, 1.573 }; - -/* */ -/* Foward reversible MCT. */ -/* */ -void mct_encode( - int* restrict c0, - int* restrict c1, - int* restrict c2, - int n) -{ - int i; - for(i = 0; i < n; ++i) { - int r = c0[i]; - int g = c1[i]; - int b = c2[i]; - int y = (r + (g * 2) + b) >> 2; - int u = b - g; - int v = r - g; - c0[i] = y; - c1[i] = u; - c2[i] = v; - } -} - -/* */ -/* Inverse reversible MCT. */ -/* */ -void mct_decode( - int* restrict c0, - int* restrict c1, - int* restrict c2, - int n) -{ - int i; - for (i = 0; i < n; ++i) { - int y = c0[i]; - int u = c1[i]; - int v = c2[i]; - int g = y - ((u + v) >> 2); - int r = v + g; - int 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* restrict c0, - int* restrict c1, - int* restrict c2, - int n) -{ - int i; - for(i = 0; i < n; ++i) { - int r = c0[i]; - int g = c1[i]; - int b = c2[i]; - int y = fix_mul(r, 2449) + fix_mul(g, 4809) + fix_mul(b, 934); - int u = -fix_mul(r, 1382) - fix_mul(g, 2714) + fix_mul(b, 4096); - int v = fix_mul(r, 4096) - fix_mul(g, 3430) - fix_mul(b, 666); - c0[i] = y; - c1[i] = u; - c2[i] = v; - } -} - -/* */ -/* Inverse irreversible MCT. */ -/* */ -void mct_decode_real( - float* restrict c0, - float* restrict c1, - float* restrict c2, - int n) -{ - int i; -#ifdef __SSE__ - __m128 vrv, vgu, vgv, vbu; - vrv = _mm_set1_ps(1.402f); - vgu = _mm_set1_ps(0.34413f); - vgv = _mm_set1_ps(0.71414f); - vbu = _mm_set1_ps(1.772f); - for (i = 0; i < (n >> 3); ++i) { - __m128 vy, vu, vv; - __m128 vr, vg, vb; - - vy = _mm_load_ps(c0); - vu = _mm_load_ps(c1); - vv = _mm_load_ps(c2); - vr = _mm_add_ps(vy, _mm_mul_ps(vv, vrv)); - vg = _mm_sub_ps(_mm_sub_ps(vy, _mm_mul_ps(vu, vgu)), _mm_mul_ps(vv, vgv)); - vb = _mm_add_ps(vy, _mm_mul_ps(vu, vbu)); - _mm_store_ps(c0, vr); - _mm_store_ps(c1, vg); - _mm_store_ps(c2, vb); - c0 += 4; - c1 += 4; - c2 += 4; - - vy = _mm_load_ps(c0); - vu = _mm_load_ps(c1); - vv = _mm_load_ps(c2); - vr = _mm_add_ps(vy, _mm_mul_ps(vv, vrv)); - vg = _mm_sub_ps(_mm_sub_ps(vy, _mm_mul_ps(vu, vgu)), _mm_mul_ps(vv, vgv)); - vb = _mm_add_ps(vy, _mm_mul_ps(vu, vbu)); - _mm_store_ps(c0, vr); - _mm_store_ps(c1, vg); - _mm_store_ps(c2, vb); - c0 += 4; - c1 += 4; - c2 += 4; - } - n &= 7; -#endif - for(i = 0; i < n; ++i) { - float y = c0[i]; - float u = c1[i]; - float v = c2[i]; - float r = y + (v * 1.402f); - float g = y - (u * 0.34413f) - (v * (0.71414f)); - float b = y + (u * 1.772f); - c0[i] = r; - c1[i] = g; - c2[i] = b; - } -} - -/* */ -/* Get norm of basis function of irreversible MCT. */ -/* */ -double mct_getnorm_real(int compno) { - return mct_norms_real[compno]; -} diff --git a/openjpeg-dotnet/libopenjpeg/mct.h b/openjpeg-dotnet/libopenjpeg/mct.h deleted file mode 100644 index 84e3f8ad..00000000 --- a/openjpeg-dotnet/libopenjpeg/mct.h +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium - * Copyright (c) 2002-2007, Professor Benoit Macq - * Copyright (c) 2001-2003, David Janssens - * Copyright (c) 2002-2003, Yannick Verschueren - * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe - * Copyright (c) 2005, Herve Drolon, FreeImage Team - * 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 -/** -@file mct.h -@brief Implementation of a multi-component transforms (MCT) - -The functions in MCT.C have for goal to realize reversible and irreversible multicomponent -transform. The functions in MCT.C are used by some function in TCD.C. -*/ - -/** @defgroup MCT MCT - Implementation of a multi-component transform */ -/*@{*/ - -/** @name Exported functions */ -/*@{*/ -/* ----------------------------------------------------------------------- */ -/** -Apply a reversible multi-component transform to an image -@param c0 Samples for red component -@param c1 Samples for green component -@param c2 Samples blue component -@param n Number of samples for each component -*/ -void mct_encode(int *c0, int *c1, int *c2, int n); -/** -Apply a reversible multi-component inverse transform to an image -@param c0 Samples for luminance component -@param c1 Samples for red chrominance component -@param c2 Samples for blue chrominance component -@param n Number of samples for each component -*/ -void mct_decode(int *c0, int *c1, int *c2, int n); -/** -Get norm of the basis function used for the reversible multi-component transform -@param compno Number of the component (0->Y, 1->U, 2->V) -@return -*/ -double mct_getnorm(int compno); - -/** -Apply an irreversible multi-component transform to an image -@param c0 Samples for red component -@param c1 Samples for green component -@param c2 Samples blue component -@param n Number of samples for each component -*/ -void mct_encode_real(int *c0, int *c1, int *c2, int n); -/** -Apply an irreversible multi-component inverse transform to an image -@param c0 Samples for luminance component -@param c1 Samples for red chrominance component -@param c2 Samples for blue chrominance component -@param n Number of samples for each component -*/ -void mct_decode_real(float* c0, float* c1, float* c2, int n); -/** -Get norm of the basis function used for the irreversible multi-component transform -@param compno Number of the component (0->Y, 1->U, 2->V) -@return -*/ -double mct_getnorm_real(int compno); -/* ----------------------------------------------------------------------- */ -/*@}*/ - -/*@}*/ - -#endif /* __MCT_H */ diff --git a/openjpeg-dotnet/libopenjpeg/mqc.c b/openjpeg-dotnet/libopenjpeg/mqc.c deleted file mode 100644 index 14129fbf..00000000 --- a/openjpeg-dotnet/libopenjpeg/mqc.c +++ /dev/null @@ -1,592 +0,0 @@ -/* - * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium - * Copyright (c) 2002-2007, Professor Benoit Macq - * Copyright (c) 2001-2003, David Janssens - * Copyright (c) 2002-2003, Yannick Verschueren - * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe - * Copyright (c) 2005, Herve Drolon, FreeImage Team - * 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 "opj_includes.h" - -/** @defgroup MQC MQC - Implementation of an MQ-Coder */ -/*@{*/ - -/** @name Local static functions */ -/*@{*/ - -/** -Output a byte, doing bit-stuffing if necessary. -After a 0xff byte, the next byte must be smaller than 0x90. -@param mqc MQC handle -*/ -static void mqc_byteout(opj_mqc_t *mqc); -/** -Renormalize mqc->a and mqc->c while encoding, so that mqc->a stays between 0x8000 and 0x10000 -@param mqc MQC handle -*/ -static void mqc_renorme(opj_mqc_t *mqc); -/** -Encode the most probable symbol -@param mqc MQC handle -*/ -static void mqc_codemps(opj_mqc_t *mqc); -/** -Encode the most least symbol -@param mqc MQC handle -*/ -static void mqc_codelps(opj_mqc_t *mqc); -/** -Fill mqc->c with 1's for flushing -@param mqc MQC handle -*/ -static void mqc_setbits(opj_mqc_t *mqc); -/** -FIXME: documentation ??? -@param mqc MQC handle -@return -*/ -static INLINE int mqc_mpsexchange(opj_mqc_t *const mqc); -/** -FIXME: documentation ??? -@param mqc MQC handle -@return -*/ -static INLINE int mqc_lpsexchange(opj_mqc_t *const mqc); -/** -Input a byte -@param mqc MQC handle -*/ -static INLINE void mqc_bytein(opj_mqc_t *const mqc); -/** -Renormalize mqc->a and mqc->c while decoding -@param mqc MQC handle -*/ -static INLINE void mqc_renormd(opj_mqc_t *const mqc); -/*@}*/ - -/*@}*/ - -/* */ -/* This array defines all the possible states for a context. */ -/* */ -static opj_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]}, -}; - -/* -========================================================== - local functions -========================================================== -*/ - -static void mqc_byteout(opj_mqc_t *mqc) { - if (*mqc->bp == 0xff) { - mqc->bp++; - *mqc->bp = mqc->c >> 20; - mqc->c &= 0xfffff; - mqc->ct = 7; - } else { - if ((mqc->c & 0x8000000) == 0) { /* ((mqc->c&0x8000000)==0) CHANGE */ - 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; - } - } - } -} - -static void mqc_renorme(opj_mqc_t *mqc) { - do { - mqc->a <<= 1; - mqc->c <<= 1; - mqc->ct--; - if (mqc->ct == 0) { - mqc_byteout(mqc); - } - } while ((mqc->a & 0x8000) == 0); -} - -static void mqc_codemps(opj_mqc_t *mqc) { - 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(mqc); - } else { - mqc->c += (*mqc->curctx)->qeval; - } -} - -static void mqc_codelps(opj_mqc_t *mqc) { - 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(mqc); -} - -static void mqc_setbits(opj_mqc_t *mqc) { - unsigned int tempc = mqc->c + mqc->a; - mqc->c |= 0xffff; - if (mqc->c >= tempc) { - mqc->c -= 0x8000; - } -} - -static INLINE int mqc_mpsexchange(opj_mqc_t *const mqc) { - 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; -} - -static INLINE int mqc_lpsexchange(opj_mqc_t *const mqc) { - 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; -} - -#ifdef MQC_PERF_OPT -static INLINE void mqc_bytein(opj_mqc_t *const mqc) { - unsigned int i = *((unsigned int *) mqc->bp); - mqc->c += i & 0xffff00; - mqc->ct = i & 0x0f; - mqc->bp += (i >> 2) & 0x04; -} -#else -static void mqc_bytein(opj_mqc_t *const mqc) { - 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; - } -} -#endif - -static INLINE void mqc_renormd(opj_mqc_t *const mqc) { - do { - if (mqc->ct == 0) { - mqc_bytein(mqc); - } - mqc->a <<= 1; - mqc->c <<= 1; - mqc->ct--; - } while (mqc->a < 0x8000); -} - -/* -========================================================== - MQ-Coder interface -========================================================== -*/ - -opj_mqc_t* mqc_create(void) { - opj_mqc_t *mqc = (opj_mqc_t*)opj_malloc(sizeof(opj_mqc_t)); -#ifdef MQC_PERF_OPT - mqc->buffer = NULL; -#endif - return mqc; -} - -void mqc_destroy(opj_mqc_t *mqc) { - if(mqc) { -#ifdef MQC_PERF_OPT - if (mqc->buffer) { - opj_free(mqc->buffer); - } -#endif - opj_free(mqc); - } -} - -int mqc_numbytes(opj_mqc_t *mqc) { - return mqc->bp - mqc->start; -} - -void mqc_init_enc(opj_mqc_t *mqc, unsigned char *bp) { - mqc_setcurctx(mqc, 0); - mqc->a = 0x8000; - mqc->c = 0; - mqc->bp = bp - 1; - mqc->ct = 12; - if (*mqc->bp == 0xff) { - mqc->ct = 13; - } - mqc->start = bp; -} - -void mqc_encode(opj_mqc_t *mqc, int d) { - if ((*mqc->curctx)->mps == d) { - mqc_codemps(mqc); - } else { - mqc_codelps(mqc); - } -} - -void mqc_flush(opj_mqc_t *mqc) { - mqc_setbits(mqc); - mqc->c <<= mqc->ct; - mqc_byteout(mqc); - mqc->c <<= mqc->ct; - mqc_byteout(mqc); - - if (*mqc->bp != 0xff) { - mqc->bp++; - } -} - -void mqc_bypass_init_enc(opj_mqc_t *mqc) { - mqc->c = 0; - mqc->ct = 8; - /*if (*mqc->bp == 0xff) { - mqc->ct = 7; - } */ -} - -void mqc_bypass_enc(opj_mqc_t *mqc, int d) { - mqc->ct--; - mqc->c = mqc->c + (d << mqc->ct); - if (mqc->ct == 0) { - mqc->bp++; - *mqc->bp = mqc->c; - mqc->ct = 8; - if (*mqc->bp == 0xff) { - mqc->ct = 7; - } - mqc->c = 0; - } -} - -int mqc_bypass_flush_enc(opj_mqc_t *mqc) { - unsigned char bit_padding; - - bit_padding = 0; - - if (mqc->ct != 0) { - while (mqc->ct > 0) { - mqc->ct--; - mqc->c += bit_padding << mqc->ct; - bit_padding = (bit_padding + 1) & 0x01; - } - mqc->bp++; - *mqc->bp = mqc->c; - mqc->ct = 8; - mqc->c = 0; - } - - return 1; -} - -void mqc_reset_enc(opj_mqc_t *mqc) { - mqc_resetstates(mqc); - mqc_setstate(mqc, T1_CTXNO_UNI, 0, 46); - mqc_setstate(mqc, T1_CTXNO_AGG, 0, 3); - mqc_setstate(mqc, T1_CTXNO_ZC, 0, 4); -} - -int mqc_restart_enc(opj_mqc_t *mqc) { - int correction = 1; - - /* */ - int n = 27 - 15 - mqc->ct; - mqc->c <<= mqc->ct; - while (n > 0) { - mqc_byteout(mqc); - n -= mqc->ct; - mqc->c <<= mqc->ct; - } - mqc_byteout(mqc); - - return correction; -} - -void mqc_restart_init_enc(opj_mqc_t *mqc) { - /* */ - mqc_setcurctx(mqc, 0); - mqc->a = 0x8000; - mqc->c = 0; - mqc->ct = 12; - mqc->bp--; - if (*mqc->bp == 0xff) { - mqc->ct = 13; - } -} - -void mqc_erterm_enc(opj_mqc_t *mqc) { - int k = 11 - mqc->ct + 1; - - while (k > 0) { - mqc->c <<= mqc->ct; - mqc->ct = 0; - mqc_byteout(mqc); - k -= mqc->ct; - } - - if (*mqc->bp != 0xff) { - mqc_byteout(mqc); - } -} - -void mqc_segmark_enc(opj_mqc_t *mqc) { - int i; - mqc_setcurctx(mqc, 18); - - for (i = 1; i < 5; i++) { - mqc_encode(mqc, i % 2); - } -} - -void mqc_init_dec(opj_mqc_t *mqc, unsigned char *bp, int len) { - mqc_setcurctx(mqc, 0); - mqc->start = bp; - mqc->end = bp + len; - mqc->bp = bp; - if (len==0) mqc->c = 0xff << 16; - else mqc->c = *mqc->bp << 16; - -#ifdef MQC_PERF_OPT - { - unsigned int c; - unsigned int *ip; - unsigned char *end = mqc->end - 1; - mqc->buffer = opj_realloc(mqc->buffer, (len + 1) * sizeof(unsigned int)); - ip = (unsigned int *) mqc->buffer; - - while (bp < end) { - c = *(bp + 1); - if (*bp == 0xff) { - if (c > 0x8f) { - break; - } else { - *ip = 0x00000017 | (c << 9); - } - } else { - *ip = 0x00000018 | (c << 8); - } - bp++; - ip++; - } - - /* Handle last byte of data */ - c = 0xff; - if (*bp == 0xff) { - *ip = 0x0000ff18; - } else { - bp++; - *ip = 0x00000018 | (c << 8); - } - ip++; - - *ip = 0x0000ff08; - mqc->bp = mqc->buffer; - } -#endif - mqc_bytein(mqc); - mqc->c <<= 7; - mqc->ct -= 7; - mqc->a = 0x8000; -} - -int mqc_decode(opj_mqc_t *const mqc) { - int d; - mqc->a -= (*mqc->curctx)->qeval; - if ((mqc->c >> 16) < (*mqc->curctx)->qeval) { - d = mqc_lpsexchange(mqc); - mqc_renormd(mqc); - } else { - mqc->c -= (*mqc->curctx)->qeval << 16; - if ((mqc->a & 0x8000) == 0) { - d = mqc_mpsexchange(mqc); - mqc_renormd(mqc); - } else { - d = (*mqc->curctx)->mps; - } - } - - return d; -} - -void mqc_resetstates(opj_mqc_t *mqc) { - int i; - for (i = 0; i < MQC_NUMCTXS; i++) { - mqc->ctxs[i] = mqc_states; - } -} - -void mqc_setstate(opj_mqc_t *mqc, int ctxno, int msb, int prob) { - mqc->ctxs[ctxno] = &mqc_states[msb + (prob << 1)]; -} - - diff --git a/openjpeg-dotnet/libopenjpeg/mqc.h b/openjpeg-dotnet/libopenjpeg/mqc.h deleted file mode 100644 index d00cd106..00000000 --- a/openjpeg-dotnet/libopenjpeg/mqc.h +++ /dev/null @@ -1,200 +0,0 @@ -/* - * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium - * Copyright (c) 2002-2007, Professor Benoit Macq - * Copyright (c) 2001-2003, David Janssens - * Copyright (c) 2002-2003, Yannick Verschueren - * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe - * Copyright (c) 2005, Herve Drolon, FreeImage Team - * 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 -/** -@file mqc.h -@brief Implementation of an MQ-Coder (MQC) - -The functions in MQC.C have for goal to realize the MQ-coder operations. The functions -in MQC.C are used by some function in T1.C. -*/ - -/** @defgroup MQC MQC - Implementation of an MQ-Coder */ -/*@{*/ - -/** -This struct defines the state of a context. -*/ -typedef struct opj_mqc_state { - /** the probability of the Least Probable Symbol (0.75->0x8000, 1.5->0xffff) */ - unsigned int qeval; - /** the Most Probable Symbol (0 or 1) */ - int mps; - /** next state if the next encoded symbol is the MPS */ - struct opj_mqc_state *nmps; - /** next state if the next encoded symbol is the LPS */ - struct opj_mqc_state *nlps; -} opj_mqc_state_t; - -#define MQC_NUMCTXS 19 - -/** -MQ coder -*/ -typedef struct opj_mqc { - unsigned int c; - unsigned int a; - unsigned int ct; - unsigned char *bp; - unsigned char *start; - unsigned char *end; - opj_mqc_state_t *ctxs[MQC_NUMCTXS]; - opj_mqc_state_t **curctx; -#ifdef MQC_PERF_OPT - unsigned char *buffer; -#endif -} opj_mqc_t; - -/** @name Exported functions */ -/*@{*/ -/* ----------------------------------------------------------------------- */ -/** -Create a new MQC handle -@return Returns a new MQC handle if successful, returns NULL otherwise -*/ -opj_mqc_t* mqc_create(void); -/** -Destroy a previously created MQC handle -@param mqc MQC handle to destroy -*/ -void mqc_destroy(opj_mqc_t *mqc); -/** -Return the number of bytes written/read since initialisation -@param mqc MQC handle -@return Returns the number of bytes already encoded -*/ -int mqc_numbytes(opj_mqc_t *mqc); -/** -Reset the states of all the context of the coder/decoder -(each context is set to a state where 0 and 1 are more or less equiprobable) -@param mqc MQC handle -*/ -void mqc_resetstates(opj_mqc_t *mqc); -/** -Set the state of a particular context -@param mqc MQC handle -@param ctxno Number that identifies the context -@param msb The MSB of the new state of the context -@param prob Number that identifies the probability of the symbols for the new state of the context -*/ -void mqc_setstate(opj_mqc_t *mqc, int ctxno, int msb, int prob); -/** -Initialize the encoder -@param mqc MQC handle -@param bp Pointer to the start of the buffer where the bytes will be written -*/ -void mqc_init_enc(opj_mqc_t *mqc, unsigned char *bp); -/** -Set the current context used for coding/decoding -@param mqc MQC handle -@param ctxno Number that identifies the context -*/ -#define mqc_setcurctx(mqc, ctxno) (mqc)->curctx = &(mqc)->ctxs[(int)(ctxno)] -/** -Encode a symbol using the MQ-coder -@param mqc MQC handle -@param d The symbol to be encoded (0 or 1) -*/ -void mqc_encode(opj_mqc_t *mqc, int d); -/** -Flush the encoder, so that all remaining data is written -@param mqc MQC handle -*/ -void mqc_flush(opj_mqc_t *mqc); -/** -BYPASS mode switch, initialization operation. -JPEG 2000 p 505. -

    Not fully implemented and tested !!

    -@param mqc MQC handle -*/ -void mqc_bypass_init_enc(opj_mqc_t *mqc); -/** -BYPASS mode switch, coding operation. -JPEG 2000 p 505. -

    Not fully implemented and tested !!

    -@param mqc MQC handle -@param d The symbol to be encoded (0 or 1) -*/ -void mqc_bypass_enc(opj_mqc_t *mqc, int d); -/** -BYPASS mode switch, flush operation -

    Not fully implemented and tested !!

    -@param mqc MQC handle -@return Returns 1 (always) -*/ -int mqc_bypass_flush_enc(opj_mqc_t *mqc); -/** -RESET mode switch -@param mqc MQC handle -*/ -void mqc_reset_enc(opj_mqc_t *mqc); -/** -RESTART mode switch (TERMALL) -@param mqc MQC handle -@return Returns 1 (always) -*/ -int mqc_restart_enc(opj_mqc_t *mqc); -/** -RESTART mode switch (TERMALL) reinitialisation -@param mqc MQC handle -*/ -void mqc_restart_init_enc(opj_mqc_t *mqc); -/** -ERTERM mode switch (PTERM) -@param mqc MQC handle -*/ -void mqc_erterm_enc(opj_mqc_t *mqc); -/** -SEGMARK mode switch (SEGSYM) -@param mqc MQC handle -*/ -void mqc_segmark_enc(opj_mqc_t *mqc); -/** -Initialize the decoder -@param mqc MQC handle -@param bp Pointer to the start of the buffer from which the bytes will be read -@param len Length of the input buffer -*/ -void mqc_init_dec(opj_mqc_t *mqc, unsigned char *bp, int len); -/** -Decode a symbol -@param mqc MQC handle -@return Returns the decoded symbol (0 or 1) -*/ -int mqc_decode(opj_mqc_t *const mqc); -/* ----------------------------------------------------------------------- */ -/*@}*/ - -/*@}*/ - -#endif /* __MQC_H */ diff --git a/openjpeg-dotnet/libopenjpeg/openjpeg.c b/openjpeg-dotnet/libopenjpeg/openjpeg.c deleted file mode 100644 index 180cc844..00000000 --- a/openjpeg-dotnet/libopenjpeg/openjpeg.c +++ /dev/null @@ -1,343 +0,0 @@ -/* - * Copyright (c) 2005, Herve Drolon, FreeImage Team - * 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. - */ - -#ifdef _WIN32 -#include -#endif /* _WIN32 */ - -#include "opj_config.h" -#include "opj_includes.h" - -/* ---------------------------------------------------------------------- */ -#ifdef _WIN32 -#ifndef OPJ_STATIC -BOOL APIENTRY -DllMain(HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { - - OPJ_ARG_NOT_USED(lpReserved); - OPJ_ARG_NOT_USED(hModule); - - switch (ul_reason_for_call) { - case DLL_PROCESS_ATTACH : - break; - case DLL_PROCESS_DETACH : - break; - case DLL_THREAD_ATTACH : - case DLL_THREAD_DETACH : - break; - } - - return TRUE; -} -#endif /* OPJ_STATIC */ -#endif /* _WIN32 */ - -/* ---------------------------------------------------------------------- */ - - -const char* OPJ_CALLCONV opj_version(void) { - return PACKAGE_VERSION; -} - -opj_dinfo_t* OPJ_CALLCONV opj_create_decompress(OPJ_CODEC_FORMAT format) { - opj_dinfo_t *dinfo = (opj_dinfo_t*)opj_calloc(1, sizeof(opj_dinfo_t)); - if(!dinfo) return NULL; - dinfo->is_decompressor = OPJ_TRUE; - switch(format) { - case CODEC_J2K: - case CODEC_JPT: - /* get a J2K decoder handle */ - dinfo->j2k_handle = (void*)j2k_create_decompress((opj_common_ptr)dinfo); - if(!dinfo->j2k_handle) { - opj_free(dinfo); - return NULL; - } - break; - case CODEC_JP2: - /* get a JP2 decoder handle */ - dinfo->jp2_handle = (void*)jp2_create_decompress((opj_common_ptr)dinfo); - if(!dinfo->jp2_handle) { - opj_free(dinfo); - return NULL; - } - break; - case CODEC_UNKNOWN: - default: - opj_free(dinfo); - return NULL; - } - - dinfo->codec_format = format; - - return dinfo; -} - -void OPJ_CALLCONV opj_destroy_decompress(opj_dinfo_t *dinfo) { - if(dinfo) { - /* destroy the codec */ - switch(dinfo->codec_format) { - case CODEC_J2K: - case CODEC_JPT: - j2k_destroy_decompress((opj_j2k_t*)dinfo->j2k_handle); - break; - case CODEC_JP2: - jp2_destroy_decompress((opj_jp2_t*)dinfo->jp2_handle); - break; - case CODEC_UNKNOWN: - default: - break; - } - /* destroy the decompressor */ - opj_free(dinfo); - } -} - -void OPJ_CALLCONV opj_set_default_decoder_parameters(opj_dparameters_t *parameters) { - if(parameters) { - memset(parameters, 0, sizeof(opj_dparameters_t)); - /* default decoding parameters */ - parameters->cp_layer = 0; - parameters->cp_reduce = 0; - parameters->cp_limit_decoding = NO_LIMITATION; - - parameters->decod_format = -1; - parameters->cod_format = -1; - parameters->flags = 0; -/* UniPG>> */ -#ifdef USE_JPWL - parameters->jpwl_correct = OPJ_FALSE; - parameters->jpwl_exp_comps = JPWL_EXPECTED_COMPONENTS; - parameters->jpwl_max_tiles = JPWL_MAXIMUM_TILES; -#endif /* USE_JPWL */ -/* <codec_format) { - case CODEC_J2K: - case CODEC_JPT: - j2k_setup_decoder((opj_j2k_t*)dinfo->j2k_handle, parameters); - break; - case CODEC_JP2: - jp2_setup_decoder((opj_jp2_t*)dinfo->jp2_handle, parameters); - break; - case CODEC_UNKNOWN: - default: - break; - } - } -} - -opj_image_t* OPJ_CALLCONV opj_decode(opj_dinfo_t *dinfo, opj_cio_t *cio) { - return opj_decode_with_info(dinfo, cio, NULL); -} - -opj_image_t* OPJ_CALLCONV opj_decode_with_info(opj_dinfo_t *dinfo, opj_cio_t *cio, opj_codestream_info_t *cstr_info) { - if(dinfo && cio) { - switch(dinfo->codec_format) { - case CODEC_J2K: - return j2k_decode((opj_j2k_t*)dinfo->j2k_handle, cio, cstr_info); - case CODEC_JPT: - return j2k_decode_jpt_stream((opj_j2k_t*)dinfo->j2k_handle, cio, cstr_info); - case CODEC_JP2: - return opj_jp2_decode((opj_jp2_t*)dinfo->jp2_handle, cio, cstr_info); - case CODEC_UNKNOWN: - default: - break; - } - } - return NULL; -} - -opj_cinfo_t* OPJ_CALLCONV opj_create_compress(OPJ_CODEC_FORMAT format) { - opj_cinfo_t *cinfo = (opj_cinfo_t*)opj_calloc(1, sizeof(opj_cinfo_t)); - if(!cinfo) return NULL; - cinfo->is_decompressor = OPJ_FALSE; - switch(format) { - case CODEC_J2K: - /* get a J2K coder handle */ - cinfo->j2k_handle = (void*)j2k_create_compress((opj_common_ptr)cinfo); - if(!cinfo->j2k_handle) { - opj_free(cinfo); - return NULL; - } - break; - case CODEC_JP2: - /* get a JP2 coder handle */ - cinfo->jp2_handle = (void*)jp2_create_compress((opj_common_ptr)cinfo); - if(!cinfo->jp2_handle) { - opj_free(cinfo); - return NULL; - } - break; - case CODEC_JPT: - case CODEC_UNKNOWN: - default: - opj_free(cinfo); - return NULL; - } - - cinfo->codec_format = format; - - return cinfo; -} - -void OPJ_CALLCONV opj_destroy_compress(opj_cinfo_t *cinfo) { - if(cinfo) { - /* destroy the codec */ - switch(cinfo->codec_format) { - case CODEC_J2K: - j2k_destroy_compress((opj_j2k_t*)cinfo->j2k_handle); - break; - case CODEC_JP2: - jp2_destroy_compress((opj_jp2_t*)cinfo->jp2_handle); - break; - case CODEC_JPT: - case CODEC_UNKNOWN: - default: - break; - } - /* destroy the decompressor */ - opj_free(cinfo); - } -} - -void OPJ_CALLCONV opj_set_default_encoder_parameters(opj_cparameters_t *parameters) { - if(parameters) { - memset(parameters, 0, sizeof(opj_cparameters_t)); - /* default coding parameters */ - parameters->cp_cinema = OFF; - parameters->max_comp_size = 0; - parameters->numresolution = 6; - parameters->cp_rsiz = STD_RSIZ; - parameters->cblockw_init = 64; - parameters->cblockh_init = 64; - parameters->prog_order = LRCP; - parameters->roi_compno = -1; /* no ROI */ - parameters->subsampling_dx = 1; - parameters->subsampling_dy = 1; - parameters->tp_on = 0; - parameters->decod_format = -1; - parameters->cod_format = -1; - parameters->tcp_rates[0] = 0; - parameters->tcp_numlayers = 0; - parameters->cp_disto_alloc = 0; - parameters->cp_fixed_alloc = 0; - parameters->cp_fixed_quality = 0; - parameters->jpip_on = OPJ_FALSE; -/* UniPG>> */ -#ifdef USE_JPWL - parameters->jpwl_epc_on = OPJ_FALSE; - parameters->jpwl_hprot_MH = -1; /* -1 means unassigned */ - { - int i; - for (i = 0; i < JPWL_MAX_NO_TILESPECS; i++) { - parameters->jpwl_hprot_TPH_tileno[i] = -1; /* unassigned */ - parameters->jpwl_hprot_TPH[i] = 0; /* absent */ - } - }; - { - int i; - for (i = 0; i < JPWL_MAX_NO_PACKSPECS; i++) { - parameters->jpwl_pprot_tileno[i] = -1; /* unassigned */ - parameters->jpwl_pprot_packno[i] = -1; /* unassigned */ - parameters->jpwl_pprot[i] = 0; /* absent */ - } - }; - parameters->jpwl_sens_size = 0; /* 0 means no ESD */ - parameters->jpwl_sens_addr = 0; /* 0 means auto */ - parameters->jpwl_sens_range = 0; /* 0 means packet */ - parameters->jpwl_sens_MH = -1; /* -1 means unassigned */ - { - int i; - for (i = 0; i < JPWL_MAX_NO_TILESPECS; i++) { - parameters->jpwl_sens_TPH_tileno[i] = -1; /* unassigned */ - parameters->jpwl_sens_TPH[i] = -1; /* absent */ - } - }; -#endif /* USE_JPWL */ -/* <codec_format) { - case CODEC_J2K: - j2k_setup_encoder((opj_j2k_t*)cinfo->j2k_handle, parameters, image); - break; - case CODEC_JP2: - jp2_setup_encoder((opj_jp2_t*)cinfo->jp2_handle, parameters, image); - break; - case CODEC_JPT: - case CODEC_UNKNOWN: - default: - break; - } - } -} - -opj_bool OPJ_CALLCONV opj_encode(opj_cinfo_t *cinfo, opj_cio_t *cio, opj_image_t *image, char *index) { - if (index != NULL) - opj_event_msg((opj_common_ptr)cinfo, EVT_WARNING, "Set index to NULL when calling the opj_encode function.\n" - "To extract the index, use the opj_encode_with_info() function.\n" - "No index will be generated during this encoding\n"); - return opj_encode_with_info(cinfo, cio, image, NULL); -} - -opj_bool OPJ_CALLCONV opj_encode_with_info(opj_cinfo_t *cinfo, opj_cio_t *cio, opj_image_t *image, opj_codestream_info_t *cstr_info) { - if(cinfo && cio && image) { - switch(cinfo->codec_format) { - case CODEC_J2K: - return j2k_encode((opj_j2k_t*)cinfo->j2k_handle, cio, image, cstr_info); - case CODEC_JP2: - return opj_jp2_encode((opj_jp2_t*)cinfo->jp2_handle, cio, image, cstr_info); - case CODEC_JPT: - case CODEC_UNKNOWN: - default: - break; - } - } - return OPJ_FALSE; -} - -void OPJ_CALLCONV opj_destroy_cstr_info(opj_codestream_info_t *cstr_info) { - if (cstr_info) { - int tileno; - for (tileno = 0; tileno < cstr_info->tw * cstr_info->th; tileno++) { - opj_tile_info_t *tile_info = &cstr_info->tile[tileno]; - opj_free(tile_info->thresh); - opj_free(tile_info->packet); - opj_free(tile_info->tp); - opj_free(tile_info->marker); - } - opj_free(cstr_info->tile); - opj_free(cstr_info->marker); - opj_free(cstr_info->numdecompos); - } -} diff --git a/openjpeg-dotnet/libopenjpeg/openjpeg.h b/openjpeg-dotnet/libopenjpeg/openjpeg.h deleted file mode 100644 index 53e9fac0..00000000 --- a/openjpeg-dotnet/libopenjpeg/openjpeg.h +++ /dev/null @@ -1,910 +0,0 @@ - /* - * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium - * Copyright (c) 2002-2007, Professor Benoit Macq - * Copyright (c) 2001-2003, David Janssens - * Copyright (c) 2002-2003, Yannick Verschueren - * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe - * Copyright (c) 2005, Herve Drolon, FreeImage Team - * Copyright (c) 2006-2007, Parvatha Elangovan - * Copyright (c) 2010-2011, Kaori Hagihara - * 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 OPENJPEG_H -#define OPENJPEG_H - - -/* -========================================================== - Compiler directives -========================================================== -*/ - -#if defined(OPJ_STATIC) || !defined(_WIN32) -#define OPJ_API -#define OPJ_CALLCONV -#else -#define OPJ_CALLCONV __stdcall -/* -The following ifdef block is the standard way of creating macros which make exporting -from a DLL simpler. All files within this DLL are compiled with the OPJ_EXPORTS -symbol defined on the command line. this symbol should not be defined on any project -that uses this DLL. This way any other project whose source files include this file see -OPJ_API functions as being imported from a DLL, wheras this DLL sees symbols -defined with this macro as being exported. -*/ -#if defined(OPJ_EXPORTS) || defined(DLL_EXPORT) -#define OPJ_API __declspec(dllexport) -#else -#define OPJ_API __declspec(dllimport) -#endif /* OPJ_EXPORTS */ -#endif /* !OPJ_STATIC || !_WIN32 */ - -typedef int opj_bool; -#define OPJ_TRUE 1 -#define OPJ_FALSE 0 - -/* Avoid compile-time warning because parameter is not used */ -#define OPJ_ARG_NOT_USED(x) (void)(x) -/* -========================================================== - Useful constant definitions -========================================================== -*/ - -#define OPJ_PATH_LEN 4096 /**< Maximum allowed size for filenames */ - -#define J2K_MAXRLVLS 33 /**< Number of maximum resolution level authorized */ -#define J2K_MAXBANDS (3*J2K_MAXRLVLS-2) /**< Number of maximum sub-band linked to number of resolution level */ - -/* UniPG>> */ -#define JPWL_MAX_NO_TILESPECS 16 /**< Maximum number of tile parts expected by JPWL: increase at your will */ -#define JPWL_MAX_NO_PACKSPECS 16 /**< Maximum number of packet parts expected by JPWL: increase at your will */ -#define JPWL_MAX_NO_MARKERS 512 /**< Maximum number of JPWL markers: increase at your will */ -#define JPWL_PRIVATEINDEX_NAME "jpwl_index_privatefilename" /**< index file name used when JPWL is on */ -#define JPWL_EXPECTED_COMPONENTS 3 /**< Expect this number of components, so you'll find better the first EPB */ -#define JPWL_MAXIMUM_TILES 8192 /**< Expect this maximum number of tiles, to avoid some crashes */ -#define JPWL_MAXIMUM_HAMMING 2 /**< Expect this maximum number of bit errors in marker id's */ -#define JPWL_MAXIMUM_EPB_ROOM 65450 /**< Expect this maximum number of bytes for composition of EPBs */ -/* < -
  • Error messages -
  • Warning messages -
  • Debugging messages - -*/ -typedef struct opj_event_mgr { - /** Error message callback if available, NULL otherwise */ - opj_msg_callback error_handler; - /** Warning message callback if available, NULL otherwise */ - opj_msg_callback warning_handler; - /** Debug message callback if available, NULL otherwise */ - opj_msg_callback info_handler; -} opj_event_mgr_t; - - -/* -========================================================== - codec typedef definitions -========================================================== -*/ - -/** -Progression order changes -*/ -typedef struct opj_poc { - /** Resolution num start, Component num start, given by POC */ - int resno0, compno0; - /** Layer num end,Resolution num end, Component num end, given by POC */ - int layno1, resno1, compno1; - /** Layer num start,Precinct num start, Precinct num end */ - int layno0, precno0, precno1; - /** Progression order enum*/ - OPJ_PROG_ORDER prg1,prg; - /** Progression order string*/ - char progorder[5]; - /** Tile number */ - int tile; - /** Start and end values for Tile width and height*/ - int tx0,tx1,ty0,ty1; - /** Start value, initialised in pi_initialise_encode*/ - int layS, resS, compS, prcS; - /** End value, initialised in pi_initialise_encode */ - int layE, resE, compE, prcE; - /** Start and end values of Tile width and height, initialised in pi_initialise_encode*/ - int txS,txE,tyS,tyE,dx,dy; - /** Temporary values for Tile parts, initialised in pi_create_encode */ - int lay_t, res_t, comp_t, prc_t,tx0_t,ty0_t; -} opj_poc_t; - -/** -Compression parameters -*/ -typedef struct opj_cparameters { - /** size of tile: tile_size_on = false (not in argument) or = true (in argument) */ - opj_bool tile_size_on; - /** XTOsiz */ - int cp_tx0; - /** YTOsiz */ - int cp_ty0; - /** XTsiz */ - int cp_tdx; - /** YTsiz */ - int cp_tdy; - /** allocation by rate/distortion */ - int cp_disto_alloc; - /** allocation by fixed layer */ - int cp_fixed_alloc; - /** add fixed_quality */ - int cp_fixed_quality; - /** fixed layer */ - int *cp_matrice; - /** comment for coding */ - char *cp_comment; - /** csty : coding style */ - int csty; - /** progression order (default LRCP) */ - OPJ_PROG_ORDER prog_order; - /** progression order changes */ - opj_poc_t POC[32]; - /** number of progression order changes (POC), default to 0 */ - int numpocs; - /** number of layers */ - int tcp_numlayers; - /** rates of layers */ - float tcp_rates[100]; - /** different psnr for successive layers */ - float tcp_distoratio[100]; - /** number of resolutions */ - int numresolution; - /** initial code block width, default to 64 */ - int cblockw_init; - /** initial code block height, default to 64 */ - int cblockh_init; - /** mode switch (cblk_style) */ - int mode; - /** 1 : use the irreversible DWT 9-7, 0 : use lossless compression (default) */ - int irreversible; - /** region of interest: affected component in [0..3], -1 means no ROI */ - int roi_compno; - /** region of interest: upshift value */ - int roi_shift; - /* number of precinct size specifications */ - int res_spec; - /** initial precinct width */ - int prcw_init[J2K_MAXRLVLS]; - /** initial precinct height */ - int prch_init[J2K_MAXRLVLS]; - - /**@name command line encoder parameters (not used inside the library) */ - /*@{*/ - /** input file name */ - char infile[OPJ_PATH_LEN]; - /** output file name */ - char outfile[OPJ_PATH_LEN]; - /** DEPRECATED. Index generation is now handeld with the opj_encode_with_info() function. Set to NULL */ - int index_on; - /** DEPRECATED. Index generation is now handeld with the opj_encode_with_info() function. Set to NULL */ - char index[OPJ_PATH_LEN]; - /** subimage encoding: origin image offset in x direction */ - int image_offset_x0; - /** subimage encoding: origin image offset in y direction */ - int image_offset_y0; - /** subsampling value for dx */ - int subsampling_dx; - /** subsampling value for dy */ - int subsampling_dy; - /** input file format 0: PGX, 1: PxM, 2: BMP 3:TIF*/ - int decod_format; - /** output file format 0: J2K, 1: JP2, 2: JPT */ - int cod_format; - /*@}*/ - -/* UniPG>> */ - /**@name JPWL encoding parameters */ - /*@{*/ - /** enables writing of EPC in MH, thus activating JPWL */ - opj_bool jpwl_epc_on; - /** error protection method for MH (0,1,16,32,37-128) */ - int jpwl_hprot_MH; - /** tile number of header protection specification (>=0) */ - int jpwl_hprot_TPH_tileno[JPWL_MAX_NO_TILESPECS]; - /** error protection methods for TPHs (0,1,16,32,37-128) */ - int jpwl_hprot_TPH[JPWL_MAX_NO_TILESPECS]; - /** tile number of packet protection specification (>=0) */ - int jpwl_pprot_tileno[JPWL_MAX_NO_PACKSPECS]; - /** packet number of packet protection specification (>=0) */ - int jpwl_pprot_packno[JPWL_MAX_NO_PACKSPECS]; - /** error protection methods for packets (0,1,16,32,37-128) */ - int jpwl_pprot[JPWL_MAX_NO_PACKSPECS]; - /** enables writing of ESD, (0=no/1/2 bytes) */ - int jpwl_sens_size; - /** sensitivity addressing size (0=auto/2/4 bytes) */ - int jpwl_sens_addr; - /** sensitivity range (0-3) */ - int jpwl_sens_range; - /** sensitivity method for MH (-1=no,0-7) */ - int jpwl_sens_MH; - /** tile number of sensitivity specification (>=0) */ - int jpwl_sens_TPH_tileno[JPWL_MAX_NO_TILESPECS]; - /** sensitivity methods for TPHs (-1=no,0-7) */ - int jpwl_sens_TPH[JPWL_MAX_NO_TILESPECS]; - /*@}*/ -/* <> */ - /**@name JPWL decoding parameters */ - /*@{*/ - /** activates the JPWL correction capabilities */ - opj_bool jpwl_correct; - /** expected number of components */ - int jpwl_exp_comps; - /** maximum number of tiles */ - int jpwl_max_tiles; - /*@}*/ -/* <> */ -/** -Marker structure -*/ -typedef struct opj_marker_info_t { - /** marker type */ - unsigned short int type; - /** position in codestream */ - int pos; - /** length, marker val included */ - int len; -} opj_marker_info_t; -/* <> */ - /** number of markers */ - int marknum; - /** list of markers */ - opj_marker_info_t *marker; - /** actual size of markers array */ - int maxmarknum; -/* <cp. -@param dinfo decompressor handle -@param parameters decompression parameters -*/ -OPJ_API void OPJ_CALLCONV opj_setup_decoder(opj_dinfo_t *dinfo, opj_dparameters_t *parameters); -/** -Decode an image from a JPEG-2000 codestream -@param dinfo decompressor handle -@param cio Input buffer stream -@return Returns a decoded image if successful, returns NULL otherwise -*/ -OPJ_API opj_image_t* OPJ_CALLCONV opj_decode(opj_dinfo_t *dinfo, opj_cio_t *cio); - -/** -Decode an image from a JPEG-2000 codestream and extract the codestream information -@param dinfo decompressor handle -@param cio Input buffer stream -@param cstr_info Codestream information structure if needed afterwards, NULL otherwise -@return Returns a decoded image if successful, returns NULL otherwise -*/ -OPJ_API opj_image_t* OPJ_CALLCONV opj_decode_with_info(opj_dinfo_t *dinfo, opj_cio_t *cio, opj_codestream_info_t *cstr_info); -/** -Creates a J2K/JP2 compression structure -@param format Coder to select -@return Returns a handle to a compressor if successful, returns NULL otherwise -*/ -OPJ_API opj_cinfo_t* OPJ_CALLCONV opj_create_compress(OPJ_CODEC_FORMAT format); -/** -Destroy a compressor handle -@param cinfo compressor handle to destroy -*/ -OPJ_API void OPJ_CALLCONV opj_destroy_compress(opj_cinfo_t *cinfo); -/** -Set encoding parameters to default values, that means : -
      -
    • Lossless -
    • 1 tile -
    • Size of precinct : 2^15 x 2^15 (means 1 precinct) -
    • Size of code-block : 64 x 64 -
    • Number of resolutions: 6 -
    • No SOP marker in the codestream -
    • No EPH marker in the codestream -
    • No sub-sampling in x or y direction -
    • No mode switch activated -
    • Progression order: LRCP -
    • No index file -
    • No ROI upshifted -
    • No offset of the origin of the image -
    • No offset of the origin of the tiles -
    • Reversible DWT 5-3 -
    -@param parameters Compression parameters -*/ -OPJ_API void OPJ_CALLCONV opj_set_default_encoder_parameters(opj_cparameters_t *parameters); -/** -Setup the encoder parameters using the current image and using user parameters. -@param cinfo Compressor handle -@param parameters Compression parameters -@param image Input filled image -*/ -OPJ_API void OPJ_CALLCONV opj_setup_encoder(opj_cinfo_t *cinfo, opj_cparameters_t *parameters, opj_image_t *image); -/** -Encode an image into a JPEG-2000 codestream -3@param cinfo compressor handle -@param cio Output buffer stream -@param image Image to encode -@param index Depreacted -> Set to NULL. To extract index, used opj_encode_wci() -@return Returns true if successful, returns false otherwise -*/ -OPJ_API opj_bool OPJ_CALLCONV opj_encode(opj_cinfo_t *cinfo, opj_cio_t *cio, opj_image_t *image, char *index); -/** -Encode an image into a JPEG-2000 codestream and extract the codestream information -@param cinfo compressor handle -@param cio Output buffer stream -@param image Image to encode -@param cstr_info Codestream information structure if needed afterwards, NULL otherwise -@return Returns true if successful, returns false otherwise -*/ -OPJ_API opj_bool OPJ_CALLCONV opj_encode_with_info(opj_cinfo_t *cinfo, opj_cio_t *cio, opj_image_t *image, opj_codestream_info_t *cstr_info); -/** -Destroy Codestream information after compression or decompression -@param cstr_info Codestream information structure -*/ -OPJ_API void OPJ_CALLCONV opj_destroy_cstr_info(opj_codestream_info_t *cstr_info); - - -#ifdef __cplusplus -} -#endif - -#endif /* OPENJPEG_H */ diff --git a/openjpeg-dotnet/libopenjpeg/opj_config.h b/openjpeg-dotnet/libopenjpeg/opj_config.h deleted file mode 100644 index 53e1c0bd..00000000 --- a/openjpeg-dotnet/libopenjpeg/opj_config.h +++ /dev/null @@ -1,117 +0,0 @@ -/* opj_config.h. Generated from opj_config.h.in by configure. */ -/* opj_config.h.in. Generated from configure.ac by autoheader. */ - -/* Define if building universal (internal helper macro) */ -/* #undef AC_APPLE_UNIVERSAL_BUILD */ - -/* Define to 1 if you have the header file, and it defines `DIR'. - */ -#define HAVE_DIRENT_H 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_DLFCN_H 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_INTTYPES_H 1 - -/* define to 1 if you have lcms version 1.x */ -/* #undef HAVE_LIBLCMS1 */ - -/* define to 1 if you have lcms version 2.x */ -/* #undef HAVE_LIBLCMS2 */ - -/* define to 1 if you have libpng */ -#define HAVE_LIBPNG 1 - -/* define to 1 if you have libtiff */ -#define HAVE_LIBTIFF 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_MEMORY_H 1 - -/* Define to 1 if you have the header file, and it defines `DIR'. */ -/* #undef HAVE_NDIR_H */ - -/* Define to 1 if you have the header file. */ -#define HAVE_STDINT_H 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_STDLIB_H 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_STRINGS_H 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_STRING_H 1 - -/* Define to 1 if you have the header file, and it defines `DIR'. - */ -/* #undef HAVE_SYS_DIR_H */ - -/* Define to 1 if you have the header file, and it defines `DIR'. - */ -/* #undef HAVE_SYS_NDIR_H */ - -/* Define to 1 if you have the header file. */ -#define HAVE_SYS_STAT_H 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_SYS_TYPES_H 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_UNISTD_H 1 - -/* Define to the sub-directory in which libtool stores uninstalled libraries. - */ -#define LT_OBJDIR ".libs/" - -/* Define to 1 if your C compiler doesn't accept -c and -o together. */ -/* #undef NO_MINUS_C_MINUS_O */ - -/* Name of package */ -#define PACKAGE "openjpeg" - -/* Define to the address where bug reports for this package should be sent. */ -#define PACKAGE_BUGREPORT "openjpeg@googlegroups.com" - -/* Define to the full name of this package. */ -#define PACKAGE_NAME "OpenJPEG" - -/* Define to the full name and version of this package. */ -#define PACKAGE_STRING "OpenJPEG 1.5.0" - -/* Define to the one symbol short name of this package. */ -#define PACKAGE_TARNAME "openjpeg" - -/* Define to the home page for this package. */ -#define PACKAGE_URL "http://www.openjpeg.org" - -/* Define to the version of this package. */ -#define PACKAGE_VERSION "1.5.0" - -/* Define to 1 if you have the ANSI C header files. */ -#define STDC_HEADERS 1 - -/* define to 1 if you use jpip */ -/* #undef USE_JPIP */ - -/* define to 1 if you use jpip server */ -/* #undef USE_JPIP_SERVER */ - -/* define to 1 if you use mj2 */ -/* #undef USE_MJ2 */ - -/* Version number of package */ -#define VERSION "1.5.0" - -/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most - significant byte first (like Motorola and SPARC, unlike Intel). */ -#if defined AC_APPLE_UNIVERSAL_BUILD -# if defined __BIG_ENDIAN__ -# define WORDS_BIGENDIAN 1 -# endif -#else -# ifndef WORDS_BIGENDIAN -/* # undef WORDS_BIGENDIAN */ -# endif -#endif diff --git a/openjpeg-dotnet/libopenjpeg/opj_includes.h b/openjpeg-dotnet/libopenjpeg/opj_includes.h deleted file mode 100644 index 2b5866a9..00000000 --- a/openjpeg-dotnet/libopenjpeg/opj_includes.h +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Copyright (c) 2005, Herve Drolon, FreeImage Team - * 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 OPJ_INCLUDES_H -#define OPJ_INCLUDES_H - -/* - ========================================================== - Standard includes used by the library - ========================================================== -*/ -#include -#include -#include -#include -#include -#include -#include -#include -#include - -/* - ========================================================== - OpenJPEG interface - ========================================================== - */ -#include "openjpeg.h" - -/* - ========================================================== - OpenJPEG modules - ========================================================== -*/ - -/* Ignore GCC attributes if this is not GCC */ -#ifndef __GNUC__ - #define __attribute__(x) /* __attribute__(x) */ -#endif - -/* -The inline keyword is supported by C99 but not by C90. -Most compilers implement their own version of this keyword ... -*/ -#ifndef INLINE - #if defined(_MSC_VER) - #define INLINE __forceinline - #elif defined(__GNUC__) - #define INLINE __inline__ - #elif defined(__MWERKS__) - #define INLINE inline - #else - /* add other compilers here ... */ - #define INLINE - #endif /* defined() */ -#endif /* INLINE */ - -/* Are restricted pointers available? (C99) */ -#if (__STDC_VERSION__ != 199901L) - /* Not a C99 compiler */ - #ifdef __GNUC__ - #define restrict __restrict__ - #else - #define restrict /* restrict */ - #endif -#endif - -/* MSVC and Borland C do not have lrintf */ -#if defined(_MSC_VER) || defined(__BORLANDC__) -static INLINE long lrintf(float f){ -#ifdef _M_X64 - return (long)((f>0.0f) ? (f + 0.5f):(f -0.5f)); -#else - int i; - - _asm{ - fld f - fistp i - }; - - return i; -#endif -} -#endif - -#include "j2k_lib.h" -#include "opj_malloc.h" -#include "event.h" -#include "bio.h" -#include "cio.h" - -#include "image.h" -#include "j2k.h" -#include "jp2.h" -#include "jpt.h" - -#include "mqc.h" -#include "raw.h" -#include "bio.h" -#include "tgt.h" -#include "pi.h" -#include "tcd.h" -#include "t1.h" -#include "dwt.h" -#include "t2.h" -#include "mct.h" -#include "int.h" -#include "fix.h" - -#include "cidx_manager.h" -#include "indexbox_manager.h" - -/* JPWL>> */ -#ifdef USE_JPWL -#include "./jpwl/jpwl.h" -#endif /* USE_JPWL */ -/* < - * 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 __OPJ_MALLOC_H -#define __OPJ_MALLOC_H -/** -@file opj_malloc.h -@brief Internal functions - -The functions in opj_malloc.h are internal utilities used for memory management. -*/ - -/** @defgroup MISC MISC - Miscellaneous internal functions */ -/*@{*/ - -/** @name Exported functions */ -/*@{*/ -/* ----------------------------------------------------------------------- */ - -/** -Allocate an uninitialized memory block -@param size Bytes to allocate -@return Returns a void pointer to the allocated space, or NULL if there is insufficient memory available -*/ -#ifdef ALLOC_PERF_OPT -void * OPJ_CALLCONV opj_malloc(size_t size); -#else -#define opj_malloc(size) malloc(size) -#endif - -/** -Allocate a memory block with elements initialized to 0 -@param num Blocks to allocate -@param size Bytes per block to allocate -@return Returns a void pointer to the allocated space, or NULL if there is insufficient memory available -*/ -#ifdef ALLOC_PERF_OPT -void * OPJ_CALLCONV opj_calloc(size_t _NumOfElements, size_t _SizeOfElements); -#else -#define opj_calloc(num, size) calloc(num, size) -#endif - -/** -Allocate memory aligned to a 16 byte boundry -@param size Bytes to allocate -@return Returns a void pointer to the allocated space, or NULL if there is insufficient memory available -*/ -/* FIXME: These should be set with cmake tests, but we're currently not requiring use of cmake */ -#ifdef _WIN32 - /* Someone should tell the mingw people that their malloc.h ought to provide _mm_malloc() */ - #ifdef __GNUC__ - #include - #define HAVE_MM_MALLOC - #else /* MSVC, Intel C++ */ - #include - #ifdef _mm_malloc - #define HAVE_MM_MALLOC - #endif - #endif -#else /* Not _WIN32 */ - #if defined(__sun) - #define HAVE_MEMALIGN - /* Linux x86_64 and OSX always align allocations to 16 bytes */ - #elif !defined(__amd64__) && !defined(__APPLE__) - #define HAVE_MEMALIGN - #include - #endif -#endif - -#define opj_aligned_malloc(size) malloc(size) -#define opj_aligned_free(m) free(m) - -#ifdef HAVE_MM_MALLOC - #undef opj_aligned_malloc - #define opj_aligned_malloc(size) _mm_malloc(size, 16) - #undef opj_aligned_free - #define opj_aligned_free(m) _mm_free(m) -#endif - -#ifdef HAVE_MEMALIGN - extern void* memalign(size_t, size_t); - #undef opj_aligned_malloc - #define opj_aligned_malloc(size) memalign(16, (size)) - #undef opj_aligned_free - #define opj_aligned_free(m) free(m) -#endif - -#ifdef HAVE_POSIX_MEMALIGN - #undef opj_aligned_malloc - extern int posix_memalign(void**, size_t, size_t); - - static INLINE void* __attribute__ ((malloc)) opj_aligned_malloc(size_t size){ - void* mem = NULL; - posix_memalign(&mem, 16, size); - return mem; - } - #undef opj_aligned_free - #define opj_aligned_free(m) free(m) -#endif - -#ifdef ALLOC_PERF_OPT - #undef opj_aligned_malloc - #define opj_aligned_malloc(size) opj_malloc(size) - #undef opj_aligned_free - #define opj_aligned_free(m) opj_free(m) -#endif - -/** -Reallocate memory blocks. -@param m Pointer to previously allocated memory block -@param s New size in bytes -@return Returns a void pointer to the reallocated (and possibly moved) memory block -*/ -#ifdef ALLOC_PERF_OPT -void * OPJ_CALLCONV opj_realloc(void * m, size_t s); -#else -#define opj_realloc(m, s) realloc(m, s) -#endif - -/** -Deallocates or frees a memory block. -@param m Previously allocated memory block to be freed -*/ -#ifdef ALLOC_PERF_OPT -void OPJ_CALLCONV opj_free(void * m); -#else -#define opj_free(m) free(m) -#endif - -#ifdef __GNUC__ -#pragma GCC poison malloc calloc realloc free -#endif - -/* ----------------------------------------------------------------------- */ -/*@}*/ - -/*@}*/ - -#endif /* __OPJ_MALLOC_H */ - diff --git a/openjpeg-dotnet/libopenjpeg/phix_manager.c b/openjpeg-dotnet/libopenjpeg/phix_manager.c deleted file mode 100644 index 60a02811..00000000 --- a/openjpeg-dotnet/libopenjpeg/phix_manager.c +++ /dev/null @@ -1,170 +0,0 @@ -/* - * $Id: phix_manager.c 897 2011-08-28 21:43:57Z Kaori.Hagihara@gmail.com $ - * - * Copyright (c) 2002-2011, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium - * Copyright (c) 2002-2011, Professor Benoit Macq - * Copyright (c) 2003-2004, Yannick Verschueren - * Copyright (c) 2010-2011, Kaori Hagihara - * 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. - */ - -/*! \file - * \brief Modification of jpip.c from 2KAN indexer - */ - -#include -#include -#include "opj_includes.h" - -/* - * Write faix box of phix - * - * @param[in] coff offset of j2k codestream - * @param[in] compno component number - * @param[in] cstr_info codestream information - * @param[in] EPHused true if if EPH option used - * @param[in] j2klen length of j2k codestream - * @param[in] cio file output handle - * @return length of faix box - */ -int write_phixfaix( int coff, int compno, opj_codestream_info_t cstr_info, opj_bool EPHused, int j2klen, opj_cio_t *cio); - -int write_phix( int coff, opj_codestream_info_t cstr_info, opj_bool EPHused, int j2klen, opj_cio_t *cio) -{ - int len, lenp=0, compno, i; - opj_jp2_box_t *box; - - box = (opj_jp2_box_t *)opj_calloc( cstr_info.numcomps, sizeof(opj_jp2_box_t)); - - for( i=0;i<2;i++){ - if (i) cio_seek( cio, lenp); - - lenp = cio_tell( cio); - cio_skip( cio, 4); /* L [at the end] */ - cio_write( cio, JPIP_PHIX, 4); /* PHIX */ - - write_manf( i, cstr_info.numcomps, box, cio); - - for( compno=0; compno pow( 2, 32)){ - size_of_coding = 8; - version = 1; - } - else{ - size_of_coding = 4; - version = 0; - } - - lenp = cio_tell( cio); - cio_skip( cio, 4); /* L [at the end] */ - cio_write( cio, JPIP_FAIX, 4); /* FAIX */ - cio_write( cio, version,1); /* Version 0 = 4 bytes */ - - nmax = 0; - for( i=0; i<=cstr_info.numdecompos[compno]; i++) - nmax += cstr_info.tile[0].ph[i] * cstr_info.tile[0].pw[i] * cstr_info.numlayers; - - cio_write( cio, nmax, size_of_coding); /* NMAX */ - cio_write( cio, cstr_info.tw*cstr_info.th, size_of_coding); /* M */ - - for( tileno=0; tilenopw[resno]*tile_Idx->ph[resno]; - for( precno=0; precnopacket[ ((layno*numOfres+resno)*cstr_info.numcomps+compno)*numOfprec+precno]; - break; - case RLCP: - packet = tile_Idx->packet[ ((resno*numOflayers+layno)*cstr_info.numcomps+compno)*numOfprec+precno]; - break; - case RPCL: - packet = tile_Idx->packet[ ((resno*numOfprec+precno)*cstr_info.numcomps+compno)*numOflayers+layno]; - break; - case PCRL: - packet = tile_Idx->packet[ ((precno*cstr_info.numcomps+compno)*numOfres+resno)*numOflayers + layno]; - break; - case CPRL: - packet = tile_Idx->packet[ ((compno*numOfprec+precno)*numOfres+resno)*numOflayers + layno]; - break; - default: - fprintf( stderr, "failed to ppix indexing\n"); - } - - cio_write( cio, packet.start_pos-coff, size_of_coding); /* start position */ - cio_write( cio, packet.end_ph_pos-packet.start_pos+1, size_of_coding); /* length */ - - num_packet++; - } - } - } - - /* PADDING */ - while( num_packet < nmax){ - cio_write( cio, 0, size_of_coding); /* start position */ - cio_write( cio, 0, size_of_coding); /* length */ - num_packet++; - } - } - - len = cio_tell( cio)-lenp; - cio_seek( cio, lenp); - cio_write( cio, len, 4); /* L */ - cio_seek( cio, lenp+len); - - return len; -} diff --git a/openjpeg-dotnet/libopenjpeg/pi.c b/openjpeg-dotnet/libopenjpeg/pi.c deleted file mode 100644 index e8e33bfe..00000000 --- a/openjpeg-dotnet/libopenjpeg/pi.c +++ /dev/null @@ -1,963 +0,0 @@ -/* - * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium - * Copyright (c) 2002-2007, Professor Benoit Macq - * Copyright (c) 2001-2003, David Janssens - * Copyright (c) 2002-2003, Yannick Verschueren - * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe - * Copyright (c) 2005, Herve Drolon, FreeImage Team - * Copyright (c) 2006-2007, Parvatha Elangovan - * 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 "opj_includes.h" - -/** @defgroup PI PI - Implementation of a packet iterator */ -/*@{*/ - -/** @name Local static functions */ -/*@{*/ - -/** -Get next packet in layer-resolution-component-precinct order. -@param pi packet iterator to modify -@return returns false if pi pointed to the last packet or else returns true -*/ -static opj_bool pi_next_lrcp(opj_pi_iterator_t * pi); -/** -Get next packet in resolution-layer-component-precinct order. -@param pi packet iterator to modify -@return returns false if pi pointed to the last packet or else returns true -*/ -static opj_bool pi_next_rlcp(opj_pi_iterator_t * pi); -/** -Get next packet in resolution-precinct-component-layer order. -@param pi packet iterator to modify -@return returns false if pi pointed to the last packet or else returns true -*/ -static opj_bool pi_next_rpcl(opj_pi_iterator_t * pi); -/** -Get next packet in precinct-component-resolution-layer order. -@param pi packet iterator to modify -@return returns false if pi pointed to the last packet or else returns true -*/ -static opj_bool pi_next_pcrl(opj_pi_iterator_t * pi); -/** -Get next packet in component-precinct-resolution-layer order. -@param pi packet iterator to modify -@return returns false if pi pointed to the last packet or else returns true -*/ -static opj_bool pi_next_cprl(opj_pi_iterator_t * pi); - -/*@}*/ - -/*@}*/ - -/* -========================================================== - local functions -========================================================== -*/ - -static opj_bool pi_next_lrcp(opj_pi_iterator_t * pi) { - opj_pi_comp_t *comp = NULL; - opj_pi_resolution_t *res = NULL; - long index = 0; - - if (!pi->first) { - comp = &pi->comps[pi->compno]; - res = &comp->resolutions[pi->resno]; - goto LABEL_SKIP; - } else { - pi->first = 0; - } - - for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { - for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; - pi->resno++) { - for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { - comp = &pi->comps[pi->compno]; - if (pi->resno >= comp->numresolutions) { - continue; - } - res = &comp->resolutions[pi->resno]; - if (!pi->tp_on){ - pi->poc.precno1 = res->pw * res->ph; - } - for (pi->precno = pi->poc.precno0; pi->precno < pi->poc.precno1; pi->precno++) { - index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; - if (!pi->include[index]) { - pi->include[index] = 1; - return OPJ_TRUE; - } -LABEL_SKIP:; - } - } - } - } - - return OPJ_FALSE; -} - -static opj_bool pi_next_rlcp(opj_pi_iterator_t * pi) { - opj_pi_comp_t *comp = NULL; - opj_pi_resolution_t *res = NULL; - long index = 0; - - if (!pi->first) { - comp = &pi->comps[pi->compno]; - res = &comp->resolutions[pi->resno]; - goto LABEL_SKIP; - } else { - pi->first = 0; - } - - for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) { - for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { - for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { - comp = &pi->comps[pi->compno]; - if (pi->resno >= comp->numresolutions) { - continue; - } - res = &comp->resolutions[pi->resno]; - if(!pi->tp_on){ - pi->poc.precno1 = res->pw * res->ph; - } - for (pi->precno = pi->poc.precno0; pi->precno < pi->poc.precno1; pi->precno++) { - index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; - if (!pi->include[index]) { - pi->include[index] = 1; - return OPJ_TRUE; - } -LABEL_SKIP:; - } - } - } - } - - return OPJ_FALSE; -} - -static opj_bool pi_next_rpcl(opj_pi_iterator_t * pi) { - opj_pi_comp_t *comp = NULL; - opj_pi_resolution_t *res = NULL; - long index = 0; - - if (!pi->first) { - goto LABEL_SKIP; - } else { - int compno, resno; - pi->first = 0; - pi->dx = 0; - pi->dy = 0; - for (compno = 0; compno < pi->numcomps; compno++) { - comp = &pi->comps[compno]; - for (resno = 0; resno < comp->numresolutions; 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); - } - } - } -if (!pi->tp_on){ - pi->poc.ty0 = pi->ty0; - pi->poc.tx0 = pi->tx0; - pi->poc.ty1 = pi->ty1; - pi->poc.tx1 = pi->tx1; - } - for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) { - for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1; pi->y += pi->dy - (pi->y % pi->dy)) { - for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1; pi->x += pi->dx - (pi->x % pi->dx)) { - for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { - int levelno; - int trx0, try0; - int trx1, try1; - 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 << levelno); - try0 = int_ceildiv(pi->ty0, comp->dy << levelno); - trx1 = int_ceildiv(pi->tx1, comp->dx << levelno); - try1 = int_ceildiv(pi->ty1, comp->dy << levelno); - rpx = res->pdx + levelno; - rpy = res->pdy + levelno; - if (!((pi->y % (comp->dy << rpy) == 0) || ((pi->y == pi->ty0) && ((try0 << levelno) % (1 << rpy))))){ - continue; - } - if (!((pi->x % (comp->dx << rpx) == 0) || ((pi->x == pi->tx0) && ((trx0 << levelno) % (1 << rpx))))){ - continue; - } - - if ((res->pw==0)||(res->ph==0)) continue; - - if ((trx0==trx1)||(try0==try1)) continue; - - prci = int_floordivpow2(int_ceildiv(pi->x, comp->dx << levelno), res->pdx) - - int_floordivpow2(trx0, res->pdx); - prcj = int_floordivpow2(int_ceildiv(pi->y, comp->dy << levelno), res->pdy) - - int_floordivpow2(try0, res->pdy); - pi->precno = prci + prcj * res->pw; - for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { - index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; - if (!pi->include[index]) { - pi->include[index] = 1; - return OPJ_TRUE; - } -LABEL_SKIP:; - } - } - } - } - } - - return OPJ_FALSE; -} - -static opj_bool pi_next_pcrl(opj_pi_iterator_t * pi) { - opj_pi_comp_t *comp = NULL; - opj_pi_resolution_t *res = NULL; - long index = 0; - - if (!pi->first) { - comp = &pi->comps[pi->compno]; - goto LABEL_SKIP; - } else { - int compno, resno; - pi->first = 0; - pi->dx = 0; - pi->dy = 0; - for (compno = 0; compno < pi->numcomps; compno++) { - comp = &pi->comps[compno]; - for (resno = 0; resno < comp->numresolutions; 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); - } - } - } - if (!pi->tp_on){ - pi->poc.ty0 = pi->ty0; - pi->poc.tx0 = pi->tx0; - pi->poc.ty1 = pi->ty1; - pi->poc.tx1 = pi->tx1; - } - for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1; pi->y += pi->dy - (pi->y % pi->dy)) { - for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1; pi->x += pi->dx - (pi->x % pi->dx)) { - for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { - comp = &pi->comps[pi->compno]; - for (pi->resno = pi->poc.resno0; pi->resno < int_min(pi->poc.resno1, comp->numresolutions); pi->resno++) { - int levelno; - int trx0, try0; - int trx1, try1; - int rpx, rpy; - int prci, prcj; - res = &comp->resolutions[pi->resno]; - levelno = comp->numresolutions - 1 - pi->resno; - trx0 = int_ceildiv(pi->tx0, comp->dx << levelno); - try0 = int_ceildiv(pi->ty0, comp->dy << levelno); - trx1 = int_ceildiv(pi->tx1, comp->dx << levelno); - try1 = int_ceildiv(pi->ty1, comp->dy << levelno); - rpx = res->pdx + levelno; - rpy = res->pdy + levelno; - if (!((pi->y % (comp->dy << rpy) == 0) || ((pi->y == pi->ty0) && ((try0 << levelno) % (1 << rpy))))){ - continue; - } - if (!((pi->x % (comp->dx << rpx) == 0) || ((pi->x == pi->tx0) && ((trx0 << levelno) % (1 << rpx))))){ - continue; - } - - if ((res->pw==0)||(res->ph==0)) continue; - - if ((trx0==trx1)||(try0==try1)) continue; - - prci = int_floordivpow2(int_ceildiv(pi->x, comp->dx << levelno), res->pdx) - - int_floordivpow2(trx0, res->pdx); - prcj = int_floordivpow2(int_ceildiv(pi->y, comp->dy << levelno), res->pdy) - - int_floordivpow2(try0, res->pdy); - pi->precno = prci + prcj * res->pw; - for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { - index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; - if (!pi->include[index]) { - pi->include[index] = 1; - return OPJ_TRUE; - } -LABEL_SKIP:; - } - } - } - } - } - - return OPJ_FALSE; -} - -static opj_bool pi_next_cprl(opj_pi_iterator_t * pi) { - opj_pi_comp_t *comp = NULL; - opj_pi_resolution_t *res = NULL; - long index = 0; - - if (!pi->first) { - comp = &pi->comps[pi->compno]; - goto LABEL_SKIP; - } else { - pi->first = 0; - } - - for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { - int resno; - comp = &pi->comps[pi->compno]; - pi->dx = 0; - pi->dy = 0; - for (resno = 0; resno < comp->numresolutions; 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); - } - if (!pi->tp_on){ - pi->poc.ty0 = pi->ty0; - pi->poc.tx0 = pi->tx0; - pi->poc.ty1 = pi->ty1; - pi->poc.tx1 = pi->tx1; - } - for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1; pi->y += pi->dy - (pi->y % pi->dy)) { - for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1; pi->x += pi->dx - (pi->x % pi->dx)) { - for (pi->resno = pi->poc.resno0; pi->resno < int_min(pi->poc.resno1, comp->numresolutions); pi->resno++) { - int levelno; - int trx0, try0; - int trx1, try1; - int rpx, rpy; - int prci, prcj; - res = &comp->resolutions[pi->resno]; - levelno = comp->numresolutions - 1 - pi->resno; - trx0 = int_ceildiv(pi->tx0, comp->dx << levelno); - try0 = int_ceildiv(pi->ty0, comp->dy << levelno); - trx1 = int_ceildiv(pi->tx1, comp->dx << levelno); - try1 = int_ceildiv(pi->ty1, comp->dy << levelno); - rpx = res->pdx + levelno; - rpy = res->pdy + levelno; - if (!((pi->y % (comp->dy << rpy) == 0) || ((pi->y == pi->ty0) && ((try0 << levelno) % (1 << rpy))))){ - continue; - } - if (!((pi->x % (comp->dx << rpx) == 0) || ((pi->x == pi->tx0) && ((trx0 << levelno) % (1 << rpx))))){ - continue; - } - - if ((res->pw==0)||(res->ph==0)) continue; - - if ((trx0==trx1)||(try0==try1)) continue; - - prci = int_floordivpow2(int_ceildiv(pi->x, comp->dx << levelno), res->pdx) - - int_floordivpow2(trx0, res->pdx); - prcj = int_floordivpow2(int_ceildiv(pi->y, comp->dy << levelno), res->pdy) - - int_floordivpow2(try0, res->pdy); - pi->precno = prci + prcj * res->pw; - for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { - index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; - if (!pi->include[index]) { - pi->include[index] = 1; - return OPJ_TRUE; - } -LABEL_SKIP:; - } - } - } - } - } - - return OPJ_FALSE; -} - -/* -========================================================== - Packet iterator interface -========================================================== -*/ - -opj_pi_iterator_t *pi_create_decode(opj_image_t *image, opj_cp_t *cp, int tileno) { - int p, q; - int compno, resno, pino; - opj_pi_iterator_t *pi = NULL; - opj_tcp_t *tcp = NULL; - opj_tccp_t *tccp = NULL; - - tcp = &cp->tcps[tileno]; - - pi = (opj_pi_iterator_t*) opj_calloc((tcp->numpocs + 1), sizeof(opj_pi_iterator_t)); - if(!pi) { - /* TODO: throw an error */ - return NULL; - } - - for (pino = 0; pino < tcp->numpocs + 1; pino++) { /* change */ - int maxres = 0; - int maxprec = 0; - p = tileno % cp->tw; - q = tileno / cp->tw; - - pi[pino].tx0 = int_max(cp->tx0 + p * cp->tdx, image->x0); - pi[pino].ty0 = int_max(cp->ty0 + q * cp->tdy, image->y0); - pi[pino].tx1 = int_min(cp->tx0 + (p + 1) * cp->tdx, image->x1); - pi[pino].ty1 = int_min(cp->ty0 + (q + 1) * cp->tdy, image->y1); - pi[pino].numcomps = image->numcomps; - - pi[pino].comps = (opj_pi_comp_t*) opj_calloc(image->numcomps, sizeof(opj_pi_comp_t)); - if(!pi[pino].comps) { - /* TODO: throw an error */ - pi_destroy(pi, cp, tileno); - return NULL; - } - - for (compno = 0; compno < pi->numcomps; compno++) { - int tcx0, tcy0, tcx1, tcy1; - opj_pi_comp_t *comp = &pi[pino].comps[compno]; - tccp = &tcp->tccps[compno]; - comp->dx = image->comps[compno].dx; - comp->dy = image->comps[compno].dy; - comp->numresolutions = tccp->numresolutions; - - comp->resolutions = (opj_pi_resolution_t*) opj_calloc(comp->numresolutions, sizeof(opj_pi_resolution_t)); - if(!comp->resolutions) { - /* TODO: throw an error */ - pi_destroy(pi, cp, tileno); - return NULL; - } - - 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; resno < comp->numresolutions; resno++) { - int levelno; - int rx0, ry0, rx1, ry1; - int px0, py0, px1, py1; - opj_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) << res->pdx; - py0 = int_floordivpow2(ry0, res->pdy) << res->pdy; - px1 = int_ceildivpow2(rx1, res->pdx) << res->pdx; - py1 = int_ceildivpow2(ry1, res->pdy) << res->pdy; - res->pw = (rx0==rx1)?0:((px1 - px0) >> res->pdx); - res->ph = (ry0==ry1)?0:((py1 - py0) >> res->pdy); - - if (res->pw*res->ph > maxprec) { - maxprec = res->pw*res->ph; - } - - } - } - - tccp = &tcp->tccps[0]; - pi[pino].step_p = 1; - pi[pino].step_c = maxprec * pi[pino].step_p; - pi[pino].step_r = image->numcomps * pi[pino].step_c; - pi[pino].step_l = maxres * pi[pino].step_r; - - if (pino == 0) { - pi[pino].include = (short int*) opj_calloc(image->numcomps * maxres * tcp->numlayers * maxprec, sizeof(short int)); - if(!pi[pino].include) { - /* TODO: throw an error */ - pi_destroy(pi, cp, tileno); - return NULL; - } - } - else { - pi[pino].include = pi[pino - 1].include; - } - - if (tcp->POC == 0) { - pi[pino].first = 1; - pi[pino].poc.resno0 = 0; - pi[pino].poc.compno0 = 0; - pi[pino].poc.layno1 = tcp->numlayers; - pi[pino].poc.resno1 = maxres; - pi[pino].poc.compno1 = image->numcomps; - pi[pino].poc.prg = tcp->prg; - } else { - pi[pino].first = 1; - pi[pino].poc.resno0 = tcp->pocs[pino].resno0; - pi[pino].poc.compno0 = tcp->pocs[pino].compno0; - pi[pino].poc.layno1 = tcp->pocs[pino].layno1; - pi[pino].poc.resno1 = tcp->pocs[pino].resno1; - pi[pino].poc.compno1 = tcp->pocs[pino].compno1; - pi[pino].poc.prg = tcp->pocs[pino].prg; - } - pi[pino].poc.layno0 = 0; - pi[pino].poc.precno0 = 0; - pi[pino].poc.precno1 = maxprec; - - } - - return pi; -} - - -opj_pi_iterator_t *pi_initialise_encode(opj_image_t *image, opj_cp_t *cp, int tileno, J2K_T2_MODE t2_mode){ - int p, q, pino; - int compno, resno; - int maxres = 0; - int maxprec = 0; - opj_pi_iterator_t *pi = NULL; - opj_tcp_t *tcp = NULL; - opj_tccp_t *tccp = NULL; - - tcp = &cp->tcps[tileno]; - - pi = (opj_pi_iterator_t*) opj_calloc((tcp->numpocs + 1), sizeof(opj_pi_iterator_t)); - if(!pi) { return NULL;} - pi->tp_on = cp->tp_on; - - for(pino = 0;pino < tcp->numpocs+1 ; pino ++){ - p = tileno % cp->tw; - q = tileno / cp->tw; - - pi[pino].tx0 = int_max(cp->tx0 + p * cp->tdx, image->x0); - pi[pino].ty0 = int_max(cp->ty0 + q * cp->tdy, image->y0); - pi[pino].tx1 = int_min(cp->tx0 + (p + 1) * cp->tdx, image->x1); - pi[pino].ty1 = int_min(cp->ty0 + (q + 1) * cp->tdy, image->y1); - pi[pino].numcomps = image->numcomps; - - pi[pino].comps = (opj_pi_comp_t*) opj_calloc(image->numcomps, sizeof(opj_pi_comp_t)); - if(!pi[pino].comps) { - pi_destroy(pi, cp, tileno); - return NULL; - } - - for (compno = 0; compno < pi[pino].numcomps; compno++) { - int tcx0, tcy0, tcx1, tcy1; - opj_pi_comp_t *comp = &pi[pino].comps[compno]; - tccp = &tcp->tccps[compno]; - comp->dx = image->comps[compno].dx; - comp->dy = image->comps[compno].dy; - comp->numresolutions = tccp->numresolutions; - - comp->resolutions = (opj_pi_resolution_t*) opj_malloc(comp->numresolutions * sizeof(opj_pi_resolution_t)); - if(!comp->resolutions) { - pi_destroy(pi, cp, tileno); - return NULL; - } - - tcx0 = int_ceildiv(pi[pino].tx0, comp->dx); - tcy0 = int_ceildiv(pi[pino].ty0, comp->dy); - tcx1 = int_ceildiv(pi[pino].tx1, comp->dx); - tcy1 = int_ceildiv(pi[pino].ty1, comp->dy); - if (comp->numresolutions > maxres) { - maxres = comp->numresolutions; - } - - for (resno = 0; resno < comp->numresolutions; resno++) { - int levelno; - int rx0, ry0, rx1, ry1; - int px0, py0, px1, py1; - opj_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) << res->pdx; - py0 = int_floordivpow2(ry0, res->pdy) << res->pdy; - px1 = int_ceildivpow2(rx1, res->pdx) << res->pdx; - py1 = int_ceildivpow2(ry1, res->pdy) << res->pdy; - res->pw = (rx0==rx1)?0:((px1 - px0) >> res->pdx); - res->ph = (ry0==ry1)?0:((py1 - py0) >> res->pdy); - - if (res->pw*res->ph > maxprec) { - maxprec = res->pw * res->ph; - } - } - } - - tccp = &tcp->tccps[0]; - pi[pino].step_p = 1; - pi[pino].step_c = maxprec * pi[pino].step_p; - pi[pino].step_r = image->numcomps * pi[pino].step_c; - pi[pino].step_l = maxres * pi[pino].step_r; - - for (compno = 0; compno < pi->numcomps; compno++) { - opj_pi_comp_t *comp = &pi->comps[compno]; - for (resno = 0; resno < comp->numresolutions; resno++) { - int dx, dy; - opj_pi_resolution_t *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[pino].dx = !pi->dx ? dx : int_min(pi->dx, dx); - pi[pino].dy = !pi->dy ? dy : int_min(pi->dy, dy); - } - } - - if (pino == 0) { - pi[pino].include = (short int*) opj_calloc(tcp->numlayers * pi[pino].step_l, sizeof(short int)); - if(!pi[pino].include) { - pi_destroy(pi, cp, tileno); - return NULL; - } - } - else { - pi[pino].include = pi[pino - 1].include; - } - - /* Generation of boundaries for each prog flag*/ - if(tcp->POC && ( cp->cinema || ((!cp->cinema) && (t2_mode == FINAL_PASS)))){ - tcp->pocs[pino].compS= tcp->pocs[pino].compno0; - tcp->pocs[pino].compE= tcp->pocs[pino].compno1; - tcp->pocs[pino].resS = tcp->pocs[pino].resno0; - tcp->pocs[pino].resE = tcp->pocs[pino].resno1; - tcp->pocs[pino].layE = tcp->pocs[pino].layno1; - tcp->pocs[pino].prg = tcp->pocs[pino].prg1; - if (pino > 0) - tcp->pocs[pino].layS = (tcp->pocs[pino].layE > tcp->pocs[pino - 1].layE) ? tcp->pocs[pino - 1].layE : 0; - }else { - tcp->pocs[pino].compS= 0; - tcp->pocs[pino].compE= image->numcomps; - tcp->pocs[pino].resS = 0; - tcp->pocs[pino].resE = maxres; - tcp->pocs[pino].layS = 0; - tcp->pocs[pino].layE = tcp->numlayers; - tcp->pocs[pino].prg = tcp->prg; - } - tcp->pocs[pino].prcS = 0; - tcp->pocs[pino].prcE = maxprec;; - tcp->pocs[pino].txS = pi[pino].tx0; - tcp->pocs[pino].txE = pi[pino].tx1; - tcp->pocs[pino].tyS = pi[pino].ty0; - tcp->pocs[pino].tyE = pi[pino].ty1; - tcp->pocs[pino].dx = pi[pino].dx; - tcp->pocs[pino].dy = pi[pino].dy; - } - return pi; - } - - - -void pi_destroy(opj_pi_iterator_t *pi, opj_cp_t *cp, int tileno) { - int compno, pino; - opj_tcp_t *tcp = &cp->tcps[tileno]; - if(pi) { - for (pino = 0; pino < tcp->numpocs + 1; pino++) { - if(pi[pino].comps) { - for (compno = 0; compno < pi->numcomps; compno++) { - opj_pi_comp_t *comp = &pi[pino].comps[compno]; - if(comp->resolutions) { - opj_free(comp->resolutions); - } - } - opj_free(pi[pino].comps); - } - } - if(pi->include) { - opj_free(pi->include); - } - opj_free(pi); - } -} - -opj_bool pi_next(opj_pi_iterator_t * pi) { - switch (pi->poc.prg) { - case LRCP: - return pi_next_lrcp(pi); - case RLCP: - return pi_next_rlcp(pi); - case RPCL: - return pi_next_rpcl(pi); - case PCRL: - return pi_next_pcrl(pi); - case CPRL: - return pi_next_cprl(pi); - case PROG_UNKNOWN: - return OPJ_FALSE; - } - - return OPJ_FALSE; -} - -opj_bool pi_create_encode( opj_pi_iterator_t *pi, opj_cp_t *cp,int tileno, int pino,int tpnum, int tppos, J2K_T2_MODE t2_mode,int cur_totnum_tp){ - char prog[4]; - int i; - int incr_top=1,resetX=0; - opj_tcp_t *tcps =&cp->tcps[tileno]; - opj_poc_t *tcp= &tcps->pocs[pino]; - - pi[pino].first = 1; - pi[pino].poc.prg = tcp->prg; - - switch(tcp->prg){ - case CPRL: strncpy(prog, "CPRL",4); - break; - case LRCP: strncpy(prog, "LRCP",4); - break; - case PCRL: strncpy(prog, "PCRL",4); - break; - case RLCP: strncpy(prog, "RLCP",4); - break; - case RPCL: strncpy(prog, "RPCL",4); - break; - case PROG_UNKNOWN: - return OPJ_TRUE; - } - - if(!(cp->tp_on && ((!cp->cinema && (t2_mode == FINAL_PASS)) || cp->cinema))){ - pi[pino].poc.resno0 = tcp->resS; - pi[pino].poc.resno1 = tcp->resE; - pi[pino].poc.compno0 = tcp->compS; - pi[pino].poc.compno1 = tcp->compE; - pi[pino].poc.layno0 = tcp->layS; - pi[pino].poc.layno1 = tcp->layE; - pi[pino].poc.precno0 = tcp->prcS; - pi[pino].poc.precno1 = tcp->prcE; - pi[pino].poc.tx0 = tcp->txS; - pi[pino].poc.ty0 = tcp->tyS; - pi[pino].poc.tx1 = tcp->txE; - pi[pino].poc.ty1 = tcp->tyE; - }else { - if( tpnum < cur_totnum_tp){ - for(i=3;i>=0;i--){ - switch(prog[i]){ - case 'C': - if (i > tppos){ - pi[pino].poc.compno0 = tcp->compS; - pi[pino].poc.compno1 = tcp->compE; - }else{ - if (tpnum == 0){ - tcp->comp_t = tcp->compS; - pi[pino].poc.compno0 = tcp->comp_t; - pi[pino].poc.compno1 = tcp->comp_t+1; - tcp->comp_t+=1; - }else{ - if (incr_top == 1){ - if(tcp->comp_t ==tcp->compE){ - tcp->comp_t = tcp->compS; - pi[pino].poc.compno0 = tcp->comp_t; - pi[pino].poc.compno1 = tcp->comp_t+1; - tcp->comp_t+=1; - incr_top=1; - }else{ - pi[pino].poc.compno0 = tcp->comp_t; - pi[pino].poc.compno1 = tcp->comp_t+1; - tcp->comp_t+=1; - incr_top=0; - } - }else{ - pi[pino].poc.compno0 = tcp->comp_t-1; - pi[pino].poc.compno1 = tcp->comp_t; - } - } - } - break; - - case 'R': - if (i > tppos){ - pi[pino].poc.resno0 = tcp->resS; - pi[pino].poc.resno1 = tcp->resE; - }else{ - if (tpnum == 0){ - tcp->res_t = tcp->resS; - pi[pino].poc.resno0 = tcp->res_t; - pi[pino].poc.resno1 = tcp->res_t+1; - tcp->res_t+=1; - }else{ - if (incr_top == 1){ - if(tcp->res_t==tcp->resE){ - tcp->res_t = tcp->resS; - pi[pino].poc.resno0 = tcp->res_t; - pi[pino].poc.resno1 = tcp->res_t+1; - tcp->res_t+=1; - incr_top=1; - }else{ - pi[pino].poc.resno0 = tcp->res_t; - pi[pino].poc.resno1 = tcp->res_t+1; - tcp->res_t+=1; - incr_top=0; - } - }else{ - pi[pino].poc.resno0 = tcp->res_t - 1; - pi[pino].poc.resno1 = tcp->res_t; - } - } - } - break; - - case 'L': - if (i > tppos){ - pi[pino].poc.layno0 = tcp->layS; - pi[pino].poc.layno1 = tcp->layE; - }else{ - if (tpnum == 0){ - tcp->lay_t = tcp->layS; - pi[pino].poc.layno0 = tcp->lay_t; - pi[pino].poc.layno1 = tcp->lay_t+1; - tcp->lay_t+=1; - }else{ - if (incr_top == 1){ - if(tcp->lay_t == tcp->layE){ - tcp->lay_t = tcp->layS; - pi[pino].poc.layno0 = tcp->lay_t; - pi[pino].poc.layno1 = tcp->lay_t+1; - tcp->lay_t+=1; - incr_top=1; - }else{ - pi[pino].poc.layno0 = tcp->lay_t; - pi[pino].poc.layno1 = tcp->lay_t+1; - tcp->lay_t+=1; - incr_top=0; - } - }else{ - pi[pino].poc.layno0 = tcp->lay_t - 1; - pi[pino].poc.layno1 = tcp->lay_t; - } - } - } - break; - - case 'P': - switch(tcp->prg){ - case LRCP: - case RLCP: - if (i > tppos){ - pi[pino].poc.precno0 = tcp->prcS; - pi[pino].poc.precno1 = tcp->prcE; - }else{ - if (tpnum == 0){ - tcp->prc_t = tcp->prcS; - pi[pino].poc.precno0 = tcp->prc_t; - pi[pino].poc.precno1 = tcp->prc_t+1; - tcp->prc_t+=1; - }else{ - if (incr_top == 1){ - if(tcp->prc_t == tcp->prcE){ - tcp->prc_t = tcp->prcS; - pi[pino].poc.precno0 = tcp->prc_t; - pi[pino].poc.precno1 = tcp->prc_t+1; - tcp->prc_t+=1; - incr_top=1; - }else{ - pi[pino].poc.precno0 = tcp->prc_t; - pi[pino].poc.precno1 = tcp->prc_t+1; - tcp->prc_t+=1; - incr_top=0; - } - }else{ - pi[pino].poc.precno0 = tcp->prc_t - 1; - pi[pino].poc.precno1 = tcp->prc_t; - } - } - } - break; - default: - if (i > tppos){ - pi[pino].poc.tx0 = tcp->txS; - pi[pino].poc.ty0 = tcp->tyS; - pi[pino].poc.tx1 = tcp->txE; - pi[pino].poc.ty1 = tcp->tyE; - }else{ - if (tpnum == 0){ - tcp->tx0_t = tcp->txS; - tcp->ty0_t = tcp->tyS; - pi[pino].poc.tx0 = tcp->tx0_t; - pi[pino].poc.tx1 = tcp->tx0_t + tcp->dx - (tcp->tx0_t % tcp->dx); - pi[pino].poc.ty0 = tcp->ty0_t; - pi[pino].poc.ty1 = tcp->ty0_t + tcp->dy - (tcp->ty0_t % tcp->dy); - tcp->tx0_t = pi[pino].poc.tx1; - tcp->ty0_t = pi[pino].poc.ty1; - }else{ - if (incr_top == 1){ - if(tcp->tx0_t >= tcp->txE){ - if(tcp->ty0_t >= tcp->tyE){ - tcp->ty0_t = tcp->tyS; - pi[pino].poc.ty0 = tcp->ty0_t; - pi[pino].poc.ty1 = tcp->ty0_t + tcp->dy - (tcp->ty0_t % tcp->dy); - tcp->ty0_t = pi[pino].poc.ty1; - incr_top=1;resetX=1; - }else{ - pi[pino].poc.ty0 = tcp->ty0_t; - pi[pino].poc.ty1 = tcp->ty0_t + tcp->dy - (tcp->ty0_t % tcp->dy); - tcp->ty0_t = pi[pino].poc.ty1; - incr_top=0;resetX=1; - } - if(resetX==1){ - tcp->tx0_t = tcp->txS; - pi[pino].poc.tx0 = tcp->tx0_t; - pi[pino].poc.tx1 = tcp->tx0_t + tcp->dx- (tcp->tx0_t % tcp->dx); - tcp->tx0_t = pi[pino].poc.tx1; - } - }else{ - pi[pino].poc.tx0 = tcp->tx0_t; - pi[pino].poc.tx1 = tcp->tx0_t + tcp->dx- (tcp->tx0_t % tcp->dx); - tcp->tx0_t = pi[pino].poc.tx1; - pi[pino].poc.ty0 = tcp->ty0_t - tcp->dy - (tcp->ty0_t % tcp->dy); - pi[pino].poc.ty1 = tcp->ty0_t ; - incr_top=0; - } - }else{ - pi[pino].poc.tx0 = tcp->tx0_t - tcp->dx - (tcp->tx0_t % tcp->dx); - pi[pino].poc.tx1 = tcp->tx0_t ; - pi[pino].poc.ty0 = tcp->ty0_t - tcp->dy - (tcp->ty0_t % tcp->dy); - pi[pino].poc.ty1 = tcp->ty0_t ; - } - } - } - break; - } - break; - } - } - } - } - return OPJ_FALSE; -} - diff --git a/openjpeg-dotnet/libopenjpeg/pi.h b/openjpeg-dotnet/libopenjpeg/pi.h deleted file mode 100644 index cf9135fd..00000000 --- a/openjpeg-dotnet/libopenjpeg/pi.h +++ /dev/null @@ -1,156 +0,0 @@ -/* - * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium - * Copyright (c) 2002-2007, Professor Benoit Macq - * Copyright (c) 2001-2003, David Janssens - * Copyright (c) 2002-2003, Yannick Verschueren - * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe - * Copyright (c) 2005, Herve Drolon, FreeImage Team - * 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 -/** -@file pi.h -@brief Implementation of a packet iterator (PI) - -The functions in PI.C have for goal to realize a packet iterator that permits to get the next -packet following the progression order and change of it. The functions in PI.C are used -by some function in T2.C. -*/ - -/** @defgroup PI PI - Implementation of a packet iterator */ -/*@{*/ - -/** -FIXME: documentation -*/ -typedef struct opj_pi_resolution { - int pdx, pdy; - int pw, ph; -} opj_pi_resolution_t; - -/** -FIXME: documentation -*/ -typedef struct opj_pi_comp { - int dx, dy; - /** number of resolution levels */ - int numresolutions; - opj_pi_resolution_t *resolutions; -} opj_pi_comp_t; - -/** -Packet iterator -*/ -typedef struct opj_pi_iterator { - /** Enabling Tile part generation*/ - char tp_on; - /** precise if the packet has been already used (usefull for progression order change) */ - short int *include; - /** layer step used to localize the packet in the include vector */ - int step_l; - /** resolution step used to localize the packet in the include vector */ - int step_r; - /** component step used to localize the packet in the include vector */ - int step_c; - /** precinct step used to localize the packet in the include vector */ - int step_p; - /** component that identify the packet */ - int compno; - /** resolution that identify the packet */ - int resno; - /** precinct that identify the packet */ - int precno; - /** layer that identify the packet */ - int layno; - /** 0 if the first packet */ - int first; - /** progression order change information */ - opj_poc_t poc; - /** number of components in the image */ - int numcomps; - /** Components*/ - opj_pi_comp_t *comps; - int tx0, ty0, tx1, ty1; - int x, y, dx, dy; -} opj_pi_iterator_t; - -/** @name Exported functions */ -/*@{*/ -/* ----------------------------------------------------------------------- */ -/** -Create a packet iterator for Encoder -@param image Raw image for which the packets will be listed -@param cp Coding parameters -@param tileno Number that identifies the tile for which to list the packets -@param t2_mode If == 0 In Threshold calculation ,If == 1 Final pass -@return Returns a packet iterator that points to the first packet of the tile -@see pi_destroy -*/ -opj_pi_iterator_t *pi_initialise_encode(opj_image_t *image, opj_cp_t *cp, int tileno,J2K_T2_MODE t2_mode); -/** -Modify the packet iterator for enabling tile part generation -@param pi Handle to the packet iterator generated in pi_initialise_encode -@param cp Coding parameters -@param tileno Number that identifies the tile for which to list the packets -@param pino Iterator index for pi -@param tpnum Tile part number of the current tile -@param tppos The position of the tile part flag in the progression order -@param t2_mode If == 0 In Threshold calculation ,If == 1 Final pass -@param cur_totnum_tp The total number of tile parts in the current tile -@return Returns true if an error is detected -*/ -opj_bool pi_create_encode(opj_pi_iterator_t *pi, opj_cp_t *cp,int tileno, int pino,int tpnum, int tppos, J2K_T2_MODE t2_mode,int cur_totnum_tp); -/** -Create a packet iterator for Decoder -@param image Raw image for which the packets will be listed -@param cp Coding parameters -@param tileno Number that identifies the tile for which to list the packets -@return Returns a packet iterator that points to the first packet of the tile -@see pi_destroy -*/ -opj_pi_iterator_t *pi_create_decode(opj_image_t * image, opj_cp_t * cp, int tileno); - -/** -Destroy a packet iterator -@param pi Previously created packet iterator -@param cp Coding parameters -@param tileno Number that identifies the tile for which the packets were listed -@see pi_create -*/ -void pi_destroy(opj_pi_iterator_t *pi, opj_cp_t *cp, int tileno); - -/** -Modify the packet iterator to point to the next packet -@param pi Packet iterator to modify -@return Returns false if pi pointed to the last packet or else returns true -*/ -opj_bool pi_next(opj_pi_iterator_t * pi); -/* ----------------------------------------------------------------------- */ -/*@}*/ - -/*@}*/ - -#endif /* __PI_H */ diff --git a/openjpeg-dotnet/libopenjpeg/ppix_manager.c b/openjpeg-dotnet/libopenjpeg/ppix_manager.c deleted file mode 100644 index 58d324ce..00000000 --- a/openjpeg-dotnet/libopenjpeg/ppix_manager.c +++ /dev/null @@ -1,173 +0,0 @@ -/* - * $Id: ppix_manager.c 897 2011-08-28 21:43:57Z Kaori.Hagihara@gmail.com $ - * - * Copyright (c) 2002-2011, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium - * Copyright (c) 2002-2011, Professor Benoit Macq - * Copyright (c) 2003-2004, Yannick Verschueren - * Copyright (c) 2010-2011, Kaori Hagihara - * 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. - */ - -/*! \file - * \brief Modification of jpip.c from 2KAN indexer - */ - -#include -#include -#include -#include "opj_includes.h" - -/* - * Write faix box of ppix - * - * @param[in] coff offset of j2k codestream - * @param[in] compno component number - * @param[in] cstr_info codestream information - * @param[in] EPHused true if if EPH option used - * @param[in] j2klen length of j2k codestream - * @param[in] cio file output handle - * @return length of faix box - */ -int write_ppixfaix( int coff, int compno, opj_codestream_info_t cstr_info, opj_bool EPHused, int j2klen, opj_cio_t *cio); - -int write_ppix( int coff, opj_codestream_info_t cstr_info, opj_bool EPHused, int j2klen, opj_cio_t *cio) -{ - int len, lenp, compno, i; - opj_jp2_box_t *box; - - /* printf("cstr_info.packno %d\n", cstr_info.packno); //NMAX? */ - - lenp = -1; - box = (opj_jp2_box_t *)opj_calloc( cstr_info.numcomps, sizeof(opj_jp2_box_t)); - - for (i=0;i<2;i++){ - if (i) cio_seek( cio, lenp); - - lenp = cio_tell( cio); - cio_skip( cio, 4); /* L [at the end] */ - cio_write( cio, JPIP_PPIX, 4); /* PPIX */ - - write_manf( i, cstr_info.numcomps, box, cio); - - for (compno=0; compno pow( 2, 32)){ - size_of_coding = 8; - version = 1; - } - else{ - size_of_coding = 4; - version = 0; - } - - lenp = cio_tell( cio); - cio_skip( cio, 4); /* L [at the end] */ - cio_write( cio, JPIP_FAIX, 4); /* FAIX */ - cio_write( cio, version, 1); /* Version 0 = 4 bytes */ - - nmax = 0; - for( i=0; i<=cstr_info.numdecompos[compno]; i++) - nmax += cstr_info.tile[0].ph[i] * cstr_info.tile[0].pw[i] * cstr_info.numlayers; - - cio_write( cio, nmax, size_of_coding); /* NMAX */ - cio_write( cio, cstr_info.tw*cstr_info.th, size_of_coding); /* M */ - - for( tileno=0; tilenopw[resno]*tile_Idx->ph[resno]; - for( precno=0; precnopacket[ ((layno*numOfres+resno)*cstr_info.numcomps+compno)*numOfprec+precno]; - break; - case RLCP: - packet = tile_Idx->packet[ ((resno*numOflayers+layno)*cstr_info.numcomps+compno)*numOfprec+precno]; - break; - case RPCL: - packet = tile_Idx->packet[ ((resno*numOfprec+precno)*cstr_info.numcomps+compno)*numOflayers+layno]; - break; - case PCRL: - packet = tile_Idx->packet[ ((precno*cstr_info.numcomps+compno)*numOfres+resno)*numOflayers + layno]; - break; - case CPRL: - packet = tile_Idx->packet[ ((compno*numOfprec+precno)*numOfres+resno)*numOflayers + layno]; - break; - default: - fprintf( stderr, "failed to ppix indexing\n"); - } - - cio_write( cio, packet.start_pos-coff, size_of_coding); /* start position */ - cio_write( cio, packet.end_pos-packet.start_pos+1, size_of_coding); /* length */ - - num_packet++; - } - } - } - - while( num_packet < nmax){ /* PADDING */ - cio_write( cio, 0, size_of_coding); /* start position */ - cio_write( cio, 0, size_of_coding); /* length */ - num_packet++; - } - } - - len = cio_tell( cio)-lenp; - cio_seek( cio, lenp); - cio_write( cio, len, 4); /* L */ - cio_seek( cio, lenp+len); - - return len; -} diff --git a/openjpeg-dotnet/libopenjpeg/raw.c b/openjpeg-dotnet/libopenjpeg/raw.c deleted file mode 100644 index 3d231bfd..00000000 --- a/openjpeg-dotnet/libopenjpeg/raw.c +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium - * Copyright (c) 2002-2007, Professor Benoit Macq - * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe - * Copyright (c) 2005, Herve Drolon, FreeImage Team - * 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 "opj_includes.h" - -/* -========================================================== - local functions -========================================================== -*/ - - -/* -========================================================== - RAW encoding interface -========================================================== -*/ - -opj_raw_t* raw_create(void) { - opj_raw_t *raw = (opj_raw_t*)opj_malloc(sizeof(opj_raw_t)); - return raw; -} - -void raw_destroy(opj_raw_t *raw) { - if(raw) { - opj_free(raw); - } -} - -int raw_numbytes(opj_raw_t *raw) { - return raw->bp - raw->start; -} - -void raw_init_dec(opj_raw_t *raw, unsigned char *bp, int len) { - raw->start = bp; - raw->lenmax = len; - raw->len = 0; - raw->c = 0; - raw->ct = 0; -} - -int raw_decode(opj_raw_t *raw) { - int d; - if (raw->ct == 0) { - raw->ct = 8; - if (raw->len == raw->lenmax) { - raw->c = 0xff; - } else { - if (raw->c == 0xff) { - raw->ct = 7; - } - raw->c = *(raw->start + raw->len); - raw->len++; - } - } - raw->ct--; - d = (raw->c >> raw->ct) & 0x01; - - return d; -} - diff --git a/openjpeg-dotnet/libopenjpeg/raw.h b/openjpeg-dotnet/libopenjpeg/raw.h deleted file mode 100644 index 3c4b372f..00000000 --- a/openjpeg-dotnet/libopenjpeg/raw.h +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium - * Copyright (c) 2002-2007, Professor Benoit Macq - * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe - * Copyright (c) 2005, Herve Drolon, FreeImage Team - * 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 __RAW_H -#define __RAW_H -/** -@file raw.h -@brief Implementation of operations for raw encoding (RAW) - -The functions in RAW.C have for goal to realize the operation of raw encoding linked -with the corresponding mode switch. -*/ - -/** @defgroup RAW RAW - Implementation of operations for raw encoding */ -/*@{*/ - -/** -RAW encoding operations -*/ -typedef struct opj_raw { - /** temporary buffer where bits are coded or decoded */ - unsigned char c; - /** number of bits already read or free to write */ - unsigned int ct; - /** maximum length to decode */ - unsigned int lenmax; - /** length decoded */ - unsigned int len; - /** pointer to the current position in the buffer */ - unsigned char *bp; - /** pointer to the start of the buffer */ - unsigned char *start; - /** pointer to the end of the buffer */ - unsigned char *end; -} opj_raw_t; - -/** @name Exported functions */ -/*@{*/ -/* ----------------------------------------------------------------------- */ -/** -Create a new RAW handle -@return Returns a new RAW handle if successful, returns NULL otherwise -*/ -opj_raw_t* raw_create(void); -/** -Destroy a previously created RAW handle -@param raw RAW handle to destroy -*/ -void raw_destroy(opj_raw_t *raw); -/** -Return the number of bytes written/read since initialisation -@param raw RAW handle to destroy -@return Returns the number of bytes already encoded -*/ -int raw_numbytes(opj_raw_t *raw); -/** -Initialize the decoder -@param raw RAW handle -@param bp Pointer to the start of the buffer from which the bytes will be read -@param len Length of the input buffer -*/ -void raw_init_dec(opj_raw_t *raw, unsigned char *bp, int len); -/** -Decode a symbol using raw-decoder. Cfr p.506 TAUBMAN -@param raw RAW handle -@return Returns the decoded symbol (0 or 1) -*/ -int raw_decode(opj_raw_t *raw); -/* ----------------------------------------------------------------------- */ -/*@}*/ - -/*@}*/ - -#endif /* __RAW_H */ diff --git a/openjpeg-dotnet/libopenjpeg/t1.c b/openjpeg-dotnet/libopenjpeg/t1.c deleted file mode 100644 index 47772041..00000000 --- a/openjpeg-dotnet/libopenjpeg/t1.c +++ /dev/null @@ -1,1584 +0,0 @@ -/* - * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium - * Copyright (c) 2002-2007, Professor Benoit Macq - * Copyright (c) 2001-2003, David Janssens - * Copyright (c) 2002-2003, Yannick Verschueren - * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe - * Copyright (c) 2005, Herve Drolon, FreeImage Team - * Copyright (c) 2007, Callum Lerwick - * 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 "opj_includes.h" -#include "t1_luts.h" - -/** @defgroup T1 T1 - Implementation of the tier-1 coding */ -/*@{*/ - -/** @name Local static functions */ -/*@{*/ - -static INLINE char t1_getctxno_zc(int f, int orient); -static char t1_getctxno_sc(int f); -static INLINE int t1_getctxno_mag(int f); -static char t1_getspb(int f); -static short t1_getnmsedec_sig(int x, int bitpos); -static short t1_getnmsedec_ref(int x, int bitpos); -static void t1_updateflags(flag_t *flagsp, int s, int stride); -/** -Encode significant pass -*/ -static void t1_enc_sigpass_step( - opj_t1_t *t1, - flag_t *flagsp, - int *datap, - int orient, - int bpno, - int one, - int *nmsedec, - char type, - int vsc); -/** -Decode significant pass -*/ -static INLINE void t1_dec_sigpass_step_raw( - opj_t1_t *t1, - flag_t *flagsp, - int *datap, - int orient, - int oneplushalf, - int vsc); -static INLINE void t1_dec_sigpass_step_mqc( - opj_t1_t *t1, - flag_t *flagsp, - int *datap, - int orient, - int oneplushalf); -static INLINE void t1_dec_sigpass_step_mqc_vsc( - opj_t1_t *t1, - flag_t *flagsp, - int *datap, - int orient, - int oneplushalf, - int vsc); -/** -Encode significant pass -*/ -static void t1_enc_sigpass( - opj_t1_t *t1, - int bpno, - int orient, - int *nmsedec, - char type, - int cblksty); -/** -Decode significant pass -*/ -static void t1_dec_sigpass_raw( - opj_t1_t *t1, - int bpno, - int orient, - int cblksty); -static void t1_dec_sigpass_mqc( - opj_t1_t *t1, - int bpno, - int orient); -static void t1_dec_sigpass_mqc_vsc( - opj_t1_t *t1, - int bpno, - int orient); -/** -Encode refinement pass -*/ -static void t1_enc_refpass_step( - opj_t1_t *t1, - flag_t *flagsp, - int *datap, - int bpno, - int one, - int *nmsedec, - char type, - int vsc); -/** -Decode refinement pass -*/ -static INLINE void t1_dec_refpass_step_raw( - opj_t1_t *t1, - flag_t *flagsp, - int *datap, - int poshalf, - int neghalf, - int vsc); -static INLINE void t1_dec_refpass_step_mqc( - opj_t1_t *t1, - flag_t *flagsp, - int *datap, - int poshalf, - int neghalf); -static INLINE void t1_dec_refpass_step_mqc_vsc( - opj_t1_t *t1, - flag_t *flagsp, - int *datap, - int poshalf, - int neghalf, - int vsc); - -/** -Encode refinement pass -*/ -static void t1_enc_refpass( - opj_t1_t *t1, - int bpno, - int *nmsedec, - char type, - int cblksty); -/** -Decode refinement pass -*/ -static void t1_dec_refpass_raw( - opj_t1_t *t1, - int bpno, - int cblksty); -static void t1_dec_refpass_mqc( - opj_t1_t *t1, - int bpno); -static void t1_dec_refpass_mqc_vsc( - opj_t1_t *t1, - int bpno); -/** -Encode clean-up pass -*/ -static void t1_enc_clnpass_step( - opj_t1_t *t1, - flag_t *flagsp, - int *datap, - int orient, - int bpno, - int one, - int *nmsedec, - int partial, - int vsc); -/** -Decode clean-up pass -*/ -static void t1_dec_clnpass_step_partial( - opj_t1_t *t1, - flag_t *flagsp, - int *datap, - int orient, - int oneplushalf); -static void t1_dec_clnpass_step( - opj_t1_t *t1, - flag_t *flagsp, - int *datap, - int orient, - int oneplushalf); -static void t1_dec_clnpass_step_vsc( - opj_t1_t *t1, - flag_t *flagsp, - int *datap, - int orient, - int oneplushalf, - int partial, - int vsc); -/** -Encode clean-up pass -*/ -static void t1_enc_clnpass( - opj_t1_t *t1, - int bpno, - int orient, - int *nmsedec, - int cblksty); -/** -Decode clean-up pass -*/ -static void t1_dec_clnpass( - opj_t1_t *t1, - int bpno, - int orient, - int cblksty); -static double t1_getwmsedec( - int nmsedec, - int compno, - int level, - int orient, - int bpno, - int qmfbid, - double stepsize, - int numcomps, - int mct); -/** -Encode 1 code-block -@param t1 T1 handle -@param cblk Code-block coding parameters -@param orient -@param compno Component number -@param level -@param qmfbid -@param stepsize -@param cblksty Code-block style -@param numcomps -@param mct -@param tile -*/ -static void t1_encode_cblk( - opj_t1_t *t1, - opj_tcd_cblk_enc_t* cblk, - int orient, - int compno, - int level, - int qmfbid, - double stepsize, - int cblksty, - int numcomps, - int mct, - opj_tcd_tile_t * tile); -/** -Decode 1 code-block -@param t1 T1 handle -@param cblk Code-block coding parameters -@param orient -@param roishift Region of interest shifting value -@param cblksty Code-block style -*/ -static void t1_decode_cblk( - opj_t1_t *t1, - opj_tcd_cblk_dec_t* cblk, - int orient, - int roishift, - int cblksty); - -/*@}*/ - -/*@}*/ - -/* ----------------------------------------------------------------------- */ - -static char t1_getctxno_zc(int f, int orient) { - return lut_ctxno_zc[(orient << 8) | (f & T1_SIG_OTH)]; -} - -static char t1_getctxno_sc(int f) { - return lut_ctxno_sc[(f & (T1_SIG_PRIM | T1_SGN)) >> 4]; -} - -static int t1_getctxno_mag(int f) { - int tmp1 = (f & T1_SIG_OTH) ? T1_CTXNO_MAG + 1 : T1_CTXNO_MAG; - int tmp2 = (f & T1_REFINE) ? T1_CTXNO_MAG + 2 : tmp1; - return (tmp2); -} - -static char t1_getspb(int f) { - return lut_spb[(f & (T1_SIG_PRIM | T1_SGN)) >> 4]; -} - -static short t1_getnmsedec_sig(int x, int bitpos) { - if (bitpos > T1_NMSEDEC_FRACBITS) { - return lut_nmsedec_sig[(x >> (bitpos - T1_NMSEDEC_FRACBITS)) & ((1 << T1_NMSEDEC_BITS) - 1)]; - } - - return lut_nmsedec_sig0[x & ((1 << T1_NMSEDEC_BITS) - 1)]; -} - -static short t1_getnmsedec_ref(int x, int bitpos) { - if (bitpos > T1_NMSEDEC_FRACBITS) { - return lut_nmsedec_ref[(x >> (bitpos - T1_NMSEDEC_FRACBITS)) & ((1 << T1_NMSEDEC_BITS) - 1)]; - } - - return lut_nmsedec_ref0[x & ((1 << T1_NMSEDEC_BITS) - 1)]; -} - -static void t1_updateflags(flag_t *flagsp, int s, int stride) { - flag_t *np = flagsp - stride; - flag_t *sp = flagsp + stride; - - static const flag_t mod[] = { - T1_SIG_S, T1_SIG_S|T1_SGN_S, - T1_SIG_E, T1_SIG_E|T1_SGN_E, - T1_SIG_W, T1_SIG_W|T1_SGN_W, - T1_SIG_N, T1_SIG_N|T1_SGN_N - }; - - np[-1] |= T1_SIG_SE; - np[0] |= mod[s]; - np[1] |= T1_SIG_SW; - - flagsp[-1] |= mod[s+2]; - flagsp[0] |= T1_SIG; - flagsp[1] |= mod[s+4]; - - sp[-1] |= T1_SIG_NE; - sp[0] |= mod[s+6]; - sp[1] |= T1_SIG_NW; -} - -static void t1_enc_sigpass_step( - opj_t1_t *t1, - flag_t *flagsp, - int *datap, - int orient, - int bpno, - int one, - int *nmsedec, - char type, - int vsc) -{ - int v, flag; - - opj_mqc_t *mqc = t1->mqc; /* MQC component */ - - flag = vsc ? ((*flagsp) & (~(T1_SIG_S | T1_SIG_SE | T1_SIG_SW | T1_SGN_S))) : (*flagsp); - if ((flag & T1_SIG_OTH) && !(flag & (T1_SIG | T1_VISIT))) { - v = int_abs(*datap) & one ? 1 : 0; - mqc_setcurctx(mqc, t1_getctxno_zc(flag, orient)); /* ESSAI */ - if (type == T1_TYPE_RAW) { /* BYPASS/LAZY MODE */ - mqc_bypass_enc(mqc, v); - } else { - mqc_encode(mqc, v); - } - if (v) { - v = *datap < 0 ? 1 : 0; - *nmsedec += t1_getnmsedec_sig(int_abs(*datap), bpno + T1_NMSEDEC_FRACBITS); - mqc_setcurctx(mqc, t1_getctxno_sc(flag)); /* ESSAI */ - if (type == T1_TYPE_RAW) { /* BYPASS/LAZY MODE */ - mqc_bypass_enc(mqc, v); - } else { - mqc_encode(mqc, v ^ t1_getspb(flag)); - } - t1_updateflags(flagsp, v, t1->flags_stride); - } - *flagsp |= T1_VISIT; - } -} - -static INLINE void t1_dec_sigpass_step_raw( - opj_t1_t *t1, - flag_t *flagsp, - int *datap, - int orient, - int oneplushalf, - int vsc) -{ - int v, flag; - opj_raw_t *raw = t1->raw; /* RAW component */ - - OPJ_ARG_NOT_USED(orient); - - flag = vsc ? ((*flagsp) & (~(T1_SIG_S | T1_SIG_SE | T1_SIG_SW | T1_SGN_S))) : (*flagsp); - if ((flag & T1_SIG_OTH) && !(flag & (T1_SIG | T1_VISIT))) { - if (raw_decode(raw)) { - v = raw_decode(raw); /* ESSAI */ - *datap = v ? -oneplushalf : oneplushalf; - t1_updateflags(flagsp, v, t1->flags_stride); - } - *flagsp |= T1_VISIT; - } -} /* VSC and BYPASS by Antonin */ - -static INLINE void t1_dec_sigpass_step_mqc( - opj_t1_t *t1, - flag_t *flagsp, - int *datap, - int orient, - int oneplushalf) -{ - int v, flag; - - opj_mqc_t *mqc = t1->mqc; /* MQC component */ - - flag = *flagsp; - if ((flag & T1_SIG_OTH) && !(flag & (T1_SIG | T1_VISIT))) { - mqc_setcurctx(mqc, t1_getctxno_zc(flag, orient)); - if (mqc_decode(mqc)) { - mqc_setcurctx(mqc, t1_getctxno_sc(flag)); - v = mqc_decode(mqc) ^ t1_getspb(flag); - *datap = v ? -oneplushalf : oneplushalf; - t1_updateflags(flagsp, v, t1->flags_stride); - } - *flagsp |= T1_VISIT; - } -} /* VSC and BYPASS by Antonin */ - -static INLINE void t1_dec_sigpass_step_mqc_vsc( - opj_t1_t *t1, - flag_t *flagsp, - int *datap, - int orient, - int oneplushalf, - int vsc) -{ - int v, flag; - - opj_mqc_t *mqc = t1->mqc; /* MQC component */ - - flag = vsc ? ((*flagsp) & (~(T1_SIG_S | T1_SIG_SE | T1_SIG_SW | T1_SGN_S))) : (*flagsp); - if ((flag & T1_SIG_OTH) && !(flag & (T1_SIG | T1_VISIT))) { - mqc_setcurctx(mqc, t1_getctxno_zc(flag, orient)); - if (mqc_decode(mqc)) { - mqc_setcurctx(mqc, t1_getctxno_sc(flag)); - v = mqc_decode(mqc) ^ t1_getspb(flag); - *datap = v ? -oneplushalf : oneplushalf; - t1_updateflags(flagsp, v, t1->flags_stride); - } - *flagsp |= T1_VISIT; - } -} /* VSC and BYPASS by Antonin */ - -static void t1_enc_sigpass( - opj_t1_t *t1, - int bpno, - int orient, - int *nmsedec, - char type, - int cblksty) -{ - int i, j, k, one, vsc; - *nmsedec = 0; - one = 1 << (bpno + T1_NMSEDEC_FRACBITS); - for (k = 0; k < t1->h; k += 4) { - for (i = 0; i < t1->w; ++i) { - for (j = k; j < k + 4 && j < t1->h; ++j) { - vsc = ((cblksty & J2K_CCP_CBLKSTY_VSC) && (j == k + 3 || j == t1->h - 1)) ? 1 : 0; - t1_enc_sigpass_step( - t1, - &t1->flags[((j+1) * t1->flags_stride) + i + 1], - &t1->data[(j * t1->w) + i], - orient, - bpno, - one, - nmsedec, - type, - vsc); - } - } - } -} - -static void t1_dec_sigpass_raw( - opj_t1_t *t1, - int bpno, - int orient, - int cblksty) -{ - int i, j, k, one, half, oneplushalf, vsc; - one = 1 << bpno; - half = one >> 1; - oneplushalf = one | half; - for (k = 0; k < t1->h; k += 4) { - for (i = 0; i < t1->w; ++i) { - for (j = k; j < k + 4 && j < t1->h; ++j) { - vsc = ((cblksty & J2K_CCP_CBLKSTY_VSC) && (j == k + 3 || j == t1->h - 1)) ? 1 : 0; - t1_dec_sigpass_step_raw( - t1, - &t1->flags[((j+1) * t1->flags_stride) + i + 1], - &t1->data[(j * t1->w) + i], - orient, - oneplushalf, - vsc); - } - } - } -} /* VSC and BYPASS by Antonin */ - -static void t1_dec_sigpass_mqc( - opj_t1_t *t1, - int bpno, - int orient) -{ - int i, j, k, one, half, oneplushalf; - int *data1 = t1->data; - flag_t *flags1 = &t1->flags[1]; - one = 1 << bpno; - half = one >> 1; - oneplushalf = one | half; - for (k = 0; k < (t1->h & ~3); k += 4) { - for (i = 0; i < t1->w; ++i) { - int *data2 = data1 + i; - flag_t *flags2 = flags1 + i; - flags2 += t1->flags_stride; - t1_dec_sigpass_step_mqc(t1, flags2, data2, orient, oneplushalf); - data2 += t1->w; - flags2 += t1->flags_stride; - t1_dec_sigpass_step_mqc(t1, flags2, data2, orient, oneplushalf); - data2 += t1->w; - flags2 += t1->flags_stride; - t1_dec_sigpass_step_mqc(t1, flags2, data2, orient, oneplushalf); - data2 += t1->w; - flags2 += t1->flags_stride; - t1_dec_sigpass_step_mqc(t1, flags2, data2, orient, oneplushalf); - data2 += t1->w; - } - data1 += t1->w << 2; - flags1 += t1->flags_stride << 2; - } - for (i = 0; i < t1->w; ++i) { - int *data2 = data1 + i; - flag_t *flags2 = flags1 + i; - for (j = k; j < t1->h; ++j) { - flags2 += t1->flags_stride; - t1_dec_sigpass_step_mqc(t1, flags2, data2, orient, oneplushalf); - data2 += t1->w; - } - } -} /* VSC and BYPASS by Antonin */ - -static void t1_dec_sigpass_mqc_vsc( - opj_t1_t *t1, - int bpno, - int orient) -{ - int i, j, k, one, half, oneplushalf, vsc; - one = 1 << bpno; - half = one >> 1; - oneplushalf = one | half; - for (k = 0; k < t1->h; k += 4) { - for (i = 0; i < t1->w; ++i) { - for (j = k; j < k + 4 && j < t1->h; ++j) { - vsc = (j == k + 3 || j == t1->h - 1) ? 1 : 0; - t1_dec_sigpass_step_mqc_vsc( - t1, - &t1->flags[((j+1) * t1->flags_stride) + i + 1], - &t1->data[(j * t1->w) + i], - orient, - oneplushalf, - vsc); - } - } - } -} /* VSC and BYPASS by Antonin */ - -static void t1_enc_refpass_step( - opj_t1_t *t1, - flag_t *flagsp, - int *datap, - int bpno, - int one, - int *nmsedec, - char type, - int vsc) -{ - int v, flag; - - opj_mqc_t *mqc = t1->mqc; /* MQC component */ - - flag = vsc ? ((*flagsp) & (~(T1_SIG_S | T1_SIG_SE | T1_SIG_SW | T1_SGN_S))) : (*flagsp); - if ((flag & (T1_SIG | T1_VISIT)) == T1_SIG) { - *nmsedec += t1_getnmsedec_ref(int_abs(*datap), bpno + T1_NMSEDEC_FRACBITS); - v = int_abs(*datap) & one ? 1 : 0; - mqc_setcurctx(mqc, t1_getctxno_mag(flag)); /* ESSAI */ - if (type == T1_TYPE_RAW) { /* BYPASS/LAZY MODE */ - mqc_bypass_enc(mqc, v); - } else { - mqc_encode(mqc, v); - } - *flagsp |= T1_REFINE; - } -} - -static INLINE void t1_dec_refpass_step_raw( - opj_t1_t *t1, - flag_t *flagsp, - int *datap, - int poshalf, - int neghalf, - int vsc) -{ - int v, t, flag; - - opj_raw_t *raw = t1->raw; /* RAW component */ - - flag = vsc ? ((*flagsp) & (~(T1_SIG_S | T1_SIG_SE | T1_SIG_SW | T1_SGN_S))) : (*flagsp); - if ((flag & (T1_SIG | T1_VISIT)) == T1_SIG) { - v = raw_decode(raw); - t = v ? poshalf : neghalf; - *datap += *datap < 0 ? -t : t; - *flagsp |= T1_REFINE; - } -} /* VSC and BYPASS by Antonin */ - -static INLINE void t1_dec_refpass_step_mqc( - opj_t1_t *t1, - flag_t *flagsp, - int *datap, - int poshalf, - int neghalf) -{ - int v, t, flag; - - opj_mqc_t *mqc = t1->mqc; /* MQC component */ - - flag = *flagsp; - if ((flag & (T1_SIG | T1_VISIT)) == T1_SIG) { - mqc_setcurctx(mqc, t1_getctxno_mag(flag)); /* ESSAI */ - v = mqc_decode(mqc); - t = v ? poshalf : neghalf; - *datap += *datap < 0 ? -t : t; - *flagsp |= T1_REFINE; - } -} /* VSC and BYPASS by Antonin */ - -static INLINE void t1_dec_refpass_step_mqc_vsc( - opj_t1_t *t1, - flag_t *flagsp, - int *datap, - int poshalf, - int neghalf, - int vsc) -{ - int v, t, flag; - - opj_mqc_t *mqc = t1->mqc; /* MQC component */ - - flag = vsc ? ((*flagsp) & (~(T1_SIG_S | T1_SIG_SE | T1_SIG_SW | T1_SGN_S))) : (*flagsp); - if ((flag & (T1_SIG | T1_VISIT)) == T1_SIG) { - mqc_setcurctx(mqc, t1_getctxno_mag(flag)); /* ESSAI */ - v = mqc_decode(mqc); - t = v ? poshalf : neghalf; - *datap += *datap < 0 ? -t : t; - *flagsp |= T1_REFINE; - } -} /* VSC and BYPASS by Antonin */ - -static void t1_enc_refpass( - opj_t1_t *t1, - int bpno, - int *nmsedec, - char type, - int cblksty) -{ - int i, j, k, one, vsc; - *nmsedec = 0; - one = 1 << (bpno + T1_NMSEDEC_FRACBITS); - for (k = 0; k < t1->h; k += 4) { - for (i = 0; i < t1->w; ++i) { - for (j = k; j < k + 4 && j < t1->h; ++j) { - vsc = ((cblksty & J2K_CCP_CBLKSTY_VSC) && (j == k + 3 || j == t1->h - 1)) ? 1 : 0; - t1_enc_refpass_step( - t1, - &t1->flags[((j+1) * t1->flags_stride) + i + 1], - &t1->data[(j * t1->w) + i], - bpno, - one, - nmsedec, - type, - vsc); - } - } - } -} - -static void t1_dec_refpass_raw( - opj_t1_t *t1, - int bpno, - int cblksty) -{ - int i, j, k, one, poshalf, neghalf; - int vsc; - one = 1 << bpno; - poshalf = one >> 1; - neghalf = bpno > 0 ? -poshalf : -1; - for (k = 0; k < t1->h; k += 4) { - for (i = 0; i < t1->w; ++i) { - for (j = k; j < k + 4 && j < t1->h; ++j) { - vsc = ((cblksty & J2K_CCP_CBLKSTY_VSC) && (j == k + 3 || j == t1->h - 1)) ? 1 : 0; - t1_dec_refpass_step_raw( - t1, - &t1->flags[((j+1) * t1->flags_stride) + i + 1], - &t1->data[(j * t1->w) + i], - poshalf, - neghalf, - vsc); - } - } - } -} /* VSC and BYPASS by Antonin */ - -static void t1_dec_refpass_mqc( - opj_t1_t *t1, - int bpno) -{ - int i, j, k, one, poshalf, neghalf; - int *data1 = t1->data; - flag_t *flags1 = &t1->flags[1]; - one = 1 << bpno; - poshalf = one >> 1; - neghalf = bpno > 0 ? -poshalf : -1; - for (k = 0; k < (t1->h & ~3); k += 4) { - for (i = 0; i < t1->w; ++i) { - int *data2 = data1 + i; - flag_t *flags2 = flags1 + i; - flags2 += t1->flags_stride; - t1_dec_refpass_step_mqc(t1, flags2, data2, poshalf, neghalf); - data2 += t1->w; - flags2 += t1->flags_stride; - t1_dec_refpass_step_mqc(t1, flags2, data2, poshalf, neghalf); - data2 += t1->w; - flags2 += t1->flags_stride; - t1_dec_refpass_step_mqc(t1, flags2, data2, poshalf, neghalf); - data2 += t1->w; - flags2 += t1->flags_stride; - t1_dec_refpass_step_mqc(t1, flags2, data2, poshalf, neghalf); - data2 += t1->w; - } - data1 += t1->w << 2; - flags1 += t1->flags_stride << 2; - } - for (i = 0; i < t1->w; ++i) { - int *data2 = data1 + i; - flag_t *flags2 = flags1 + i; - for (j = k; j < t1->h; ++j) { - flags2 += t1->flags_stride; - t1_dec_refpass_step_mqc(t1, flags2, data2, poshalf, neghalf); - data2 += t1->w; - } - } -} /* VSC and BYPASS by Antonin */ - -static void t1_dec_refpass_mqc_vsc( - opj_t1_t *t1, - int bpno) -{ - int i, j, k, one, poshalf, neghalf; - int vsc; - one = 1 << bpno; - poshalf = one >> 1; - neghalf = bpno > 0 ? -poshalf : -1; - for (k = 0; k < t1->h; k += 4) { - for (i = 0; i < t1->w; ++i) { - for (j = k; j < k + 4 && j < t1->h; ++j) { - vsc = ((j == k + 3 || j == t1->h - 1)) ? 1 : 0; - t1_dec_refpass_step_mqc_vsc( - t1, - &t1->flags[((j+1) * t1->flags_stride) + i + 1], - &t1->data[(j * t1->w) + i], - poshalf, - neghalf, - vsc); - } - } - } -} /* VSC and BYPASS by Antonin */ - -static void t1_enc_clnpass_step( - opj_t1_t *t1, - flag_t *flagsp, - int *datap, - int orient, - int bpno, - int one, - int *nmsedec, - int partial, - int vsc) -{ - int v, flag; - - opj_mqc_t *mqc = t1->mqc; /* MQC component */ - - flag = vsc ? ((*flagsp) & (~(T1_SIG_S | T1_SIG_SE | T1_SIG_SW | T1_SGN_S))) : (*flagsp); - if (partial) { - goto LABEL_PARTIAL; - } - if (!(*flagsp & (T1_SIG | T1_VISIT))) { - mqc_setcurctx(mqc, t1_getctxno_zc(flag, orient)); - v = int_abs(*datap) & one ? 1 : 0; - mqc_encode(mqc, v); - if (v) { -LABEL_PARTIAL: - *nmsedec += t1_getnmsedec_sig(int_abs(*datap), bpno + T1_NMSEDEC_FRACBITS); - mqc_setcurctx(mqc, t1_getctxno_sc(flag)); - v = *datap < 0 ? 1 : 0; - mqc_encode(mqc, v ^ t1_getspb(flag)); - t1_updateflags(flagsp, v, t1->flags_stride); - } - } - *flagsp &= ~T1_VISIT; -} - -static void t1_dec_clnpass_step_partial( - opj_t1_t *t1, - flag_t *flagsp, - int *datap, - int orient, - int oneplushalf) -{ - int v, flag; - opj_mqc_t *mqc = t1->mqc; /* MQC component */ - - OPJ_ARG_NOT_USED(orient); - - flag = *flagsp; - mqc_setcurctx(mqc, t1_getctxno_sc(flag)); - v = mqc_decode(mqc) ^ t1_getspb(flag); - *datap = v ? -oneplushalf : oneplushalf; - t1_updateflags(flagsp, v, t1->flags_stride); - *flagsp &= ~T1_VISIT; -} /* VSC and BYPASS by Antonin */ - -static void t1_dec_clnpass_step( - opj_t1_t *t1, - flag_t *flagsp, - int *datap, - int orient, - int oneplushalf) -{ - int v, flag; - - opj_mqc_t *mqc = t1->mqc; /* MQC component */ - - flag = *flagsp; - if (!(flag & (T1_SIG | T1_VISIT))) { - mqc_setcurctx(mqc, t1_getctxno_zc(flag, orient)); - if (mqc_decode(mqc)) { - mqc_setcurctx(mqc, t1_getctxno_sc(flag)); - v = mqc_decode(mqc) ^ t1_getspb(flag); - *datap = v ? -oneplushalf : oneplushalf; - t1_updateflags(flagsp, v, t1->flags_stride); - } - } - *flagsp &= ~T1_VISIT; -} /* VSC and BYPASS by Antonin */ - -static void t1_dec_clnpass_step_vsc( - opj_t1_t *t1, - flag_t *flagsp, - int *datap, - int orient, - int oneplushalf, - int partial, - int vsc) -{ - int v, flag; - - opj_mqc_t *mqc = t1->mqc; /* MQC component */ - - flag = vsc ? ((*flagsp) & (~(T1_SIG_S | T1_SIG_SE | T1_SIG_SW | T1_SGN_S))) : (*flagsp); - if (partial) { - goto LABEL_PARTIAL; - } - if (!(flag & (T1_SIG | T1_VISIT))) { - mqc_setcurctx(mqc, t1_getctxno_zc(flag, orient)); - if (mqc_decode(mqc)) { -LABEL_PARTIAL: - mqc_setcurctx(mqc, t1_getctxno_sc(flag)); - v = mqc_decode(mqc) ^ t1_getspb(flag); - *datap = v ? -oneplushalf : oneplushalf; - t1_updateflags(flagsp, v, t1->flags_stride); - } - } - *flagsp &= ~T1_VISIT; -} - -static void t1_enc_clnpass( - opj_t1_t *t1, - int bpno, - int orient, - int *nmsedec, - int cblksty) -{ - int i, j, k, one, agg, runlen, vsc; - - opj_mqc_t *mqc = t1->mqc; /* MQC component */ - - *nmsedec = 0; - one = 1 << (bpno + T1_NMSEDEC_FRACBITS); - for (k = 0; k < t1->h; k += 4) { - for (i = 0; i < t1->w; ++i) { - if (k + 3 < t1->h) { - if (cblksty & J2K_CCP_CBLKSTY_VSC) { - agg = !(MACRO_t1_flags(1 + k,1 + i) & (T1_SIG | T1_VISIT | T1_SIG_OTH) - || MACRO_t1_flags(1 + k + 1,1 + i) & (T1_SIG | T1_VISIT | T1_SIG_OTH) - || MACRO_t1_flags(1 + k + 2,1 + i) & (T1_SIG | T1_VISIT | T1_SIG_OTH) - || (MACRO_t1_flags(1 + k + 3,1 + i) - & (~(T1_SIG_S | T1_SIG_SE | T1_SIG_SW | T1_SGN_S))) & (T1_SIG | T1_VISIT | T1_SIG_OTH)); - } else { - agg = !(MACRO_t1_flags(1 + k,1 + i) & (T1_SIG | T1_VISIT | T1_SIG_OTH) - || MACRO_t1_flags(1 + k + 1,1 + i) & (T1_SIG | T1_VISIT | T1_SIG_OTH) - || MACRO_t1_flags(1 + k + 2,1 + i) & (T1_SIG | T1_VISIT | T1_SIG_OTH) - || MACRO_t1_flags(1 + k + 3,1 + i) & (T1_SIG | T1_VISIT | T1_SIG_OTH)); - } - } else { - agg = 0; - } - if (agg) { - for (runlen = 0; runlen < 4; ++runlen) { - if (int_abs(t1->data[((k + runlen)*t1->w) + i]) & one) - break; - } - mqc_setcurctx(mqc, T1_CTXNO_AGG); - mqc_encode(mqc, runlen != 4); - if (runlen == 4) { - continue; - } - mqc_setcurctx(mqc, T1_CTXNO_UNI); - mqc_encode(mqc, runlen >> 1); - mqc_encode(mqc, runlen & 1); - } else { - runlen = 0; - } - for (j = k + runlen; j < k + 4 && j < t1->h; ++j) { - vsc = ((cblksty & J2K_CCP_CBLKSTY_VSC) && (j == k + 3 || j == t1->h - 1)) ? 1 : 0; - t1_enc_clnpass_step( - t1, - &t1->flags[((j+1) * t1->flags_stride) + i + 1], - &t1->data[(j * t1->w) + i], - orient, - bpno, - one, - nmsedec, - agg && (j == k + runlen), - vsc); - } - } - } -} - -static void t1_dec_clnpass( - opj_t1_t *t1, - int bpno, - int orient, - int cblksty) -{ - int i, j, k, one, half, oneplushalf, agg, runlen, vsc; - int segsym = cblksty & J2K_CCP_CBLKSTY_SEGSYM; - - opj_mqc_t *mqc = t1->mqc; /* MQC component */ - - one = 1 << bpno; - half = one >> 1; - oneplushalf = one | half; - if (cblksty & J2K_CCP_CBLKSTY_VSC) { - for (k = 0; k < t1->h; k += 4) { - for (i = 0; i < t1->w; ++i) { - if (k + 3 < t1->h) { - agg = !(MACRO_t1_flags(1 + k,1 + i) & (T1_SIG | T1_VISIT | T1_SIG_OTH) - || MACRO_t1_flags(1 + k + 1,1 + i) & (T1_SIG | T1_VISIT | T1_SIG_OTH) - || MACRO_t1_flags(1 + k + 2,1 + i) & (T1_SIG | T1_VISIT | T1_SIG_OTH) - || (MACRO_t1_flags(1 + k + 3,1 + i) - & (~(T1_SIG_S | T1_SIG_SE | T1_SIG_SW | T1_SGN_S))) & (T1_SIG | T1_VISIT | T1_SIG_OTH)); - } else { - agg = 0; - } - if (agg) { - mqc_setcurctx(mqc, T1_CTXNO_AGG); - if (!mqc_decode(mqc)) { - continue; - } - mqc_setcurctx(mqc, T1_CTXNO_UNI); - runlen = mqc_decode(mqc); - runlen = (runlen << 1) | mqc_decode(mqc); - } else { - runlen = 0; - } - for (j = k + runlen; j < k + 4 && j < t1->h; ++j) { - vsc = (j == k + 3 || j == t1->h - 1) ? 1 : 0; - t1_dec_clnpass_step_vsc( - t1, - &t1->flags[((j+1) * t1->flags_stride) + i + 1], - &t1->data[(j * t1->w) + i], - orient, - oneplushalf, - agg && (j == k + runlen), - vsc); - } - } - } - } else { - int *data1 = t1->data; - flag_t *flags1 = &t1->flags[1]; - for (k = 0; k < (t1->h & ~3); k += 4) { - for (i = 0; i < t1->w; ++i) { - int *data2 = data1 + i; - flag_t *flags2 = flags1 + i; - agg = !(MACRO_t1_flags(1 + k,1 + i) & (T1_SIG | T1_VISIT | T1_SIG_OTH) - || MACRO_t1_flags(1 + k + 1,1 + i) & (T1_SIG | T1_VISIT | T1_SIG_OTH) - || MACRO_t1_flags(1 + k + 2,1 + i) & (T1_SIG | T1_VISIT | T1_SIG_OTH) - || MACRO_t1_flags(1 + k + 3,1 + i) & (T1_SIG | T1_VISIT | T1_SIG_OTH)); - if (agg) { - mqc_setcurctx(mqc, T1_CTXNO_AGG); - if (!mqc_decode(mqc)) { - continue; - } - mqc_setcurctx(mqc, T1_CTXNO_UNI); - runlen = mqc_decode(mqc); - runlen = (runlen << 1) | mqc_decode(mqc); - flags2 += runlen * t1->flags_stride; - data2 += runlen * t1->w; - for (j = k + runlen; j < k + 4 && j < t1->h; ++j) { - flags2 += t1->flags_stride; - if (agg && (j == k + runlen)) { - t1_dec_clnpass_step_partial(t1, flags2, data2, orient, oneplushalf); - } else { - t1_dec_clnpass_step(t1, flags2, data2, orient, oneplushalf); - } - data2 += t1->w; - } - } else { - flags2 += t1->flags_stride; - t1_dec_clnpass_step(t1, flags2, data2, orient, oneplushalf); - data2 += t1->w; - flags2 += t1->flags_stride; - t1_dec_clnpass_step(t1, flags2, data2, orient, oneplushalf); - data2 += t1->w; - flags2 += t1->flags_stride; - t1_dec_clnpass_step(t1, flags2, data2, orient, oneplushalf); - data2 += t1->w; - flags2 += t1->flags_stride; - t1_dec_clnpass_step(t1, flags2, data2, orient, oneplushalf); - data2 += t1->w; - } - } - data1 += t1->w << 2; - flags1 += t1->flags_stride << 2; - } - for (i = 0; i < t1->w; ++i) { - int *data2 = data1 + i; - flag_t *flags2 = flags1 + i; - for (j = k; j < t1->h; ++j) { - flags2 += t1->flags_stride; - t1_dec_clnpass_step(t1, flags2, data2, orient, oneplushalf); - data2 += t1->w; - } - } - } - - if (segsym) { - int v = 0; - mqc_setcurctx(mqc, T1_CTXNO_UNI); - v = mqc_decode(mqc); - v = (v << 1) | mqc_decode(mqc); - v = (v << 1) | mqc_decode(mqc); - v = (v << 1) | mqc_decode(mqc); - /* - if (v!=0xa) { - opj_event_msg(t1->cinfo, EVT_WARNING, "Bad segmentation symbol %x\n", v); - } - */ - } -} /* VSC and BYPASS by Antonin */ - - -/** mod fixed_quality */ -static double t1_getwmsedec( - int nmsedec, - int compno, - int level, - int orient, - int bpno, - int qmfbid, - double stepsize, - int numcomps, - int mct) -{ - double w1, w2, wmsedec; - if (qmfbid == 1) { - w1 = (mct && numcomps==3) ? mct_getnorm(compno) : 1.0; - w2 = dwt_getnorm(level, orient); - } else { /* if (qmfbid == 0) */ - w1 = (mct && numcomps==3) ? mct_getnorm_real(compno) : 1.0; - w2 = dwt_getnorm_real(level, orient); - } - wmsedec = w1 * w2 * stepsize * (1 << bpno); - wmsedec *= wmsedec * nmsedec / 8192.0; - - return wmsedec; -} - -static opj_bool allocate_buffers( - opj_t1_t *t1, - int w, - int h) -{ - int datasize=w * h; - int flagssize; - - if(datasize > t1->datasize){ - opj_aligned_free(t1->data); - t1->data = (int*) opj_aligned_malloc(datasize * sizeof(int)); - if(!t1->data){ - return OPJ_FALSE; - } - t1->datasize=datasize; - } - memset(t1->data,0,datasize * sizeof(int)); - - t1->flags_stride=w+2; - flagssize=t1->flags_stride * (h+2); - - if(flagssize > t1->flagssize){ - opj_aligned_free(t1->flags); - t1->flags = (flag_t*) opj_aligned_malloc(flagssize * sizeof(flag_t)); - if(!t1->flags){ - return OPJ_FALSE; - } - t1->flagssize=flagssize; - } - memset(t1->flags,0,flagssize * sizeof(flag_t)); - - t1->w=w; - t1->h=h; - - return OPJ_TRUE; -} - -/** mod fixed_quality */ -static void t1_encode_cblk( - opj_t1_t *t1, - opj_tcd_cblk_enc_t* cblk, - int orient, - int compno, - int level, - int qmfbid, - double stepsize, - int cblksty, - int numcomps, - int mct, - opj_tcd_tile_t * tile) -{ - double cumwmsedec = 0.0; - - opj_mqc_t *mqc = t1->mqc; /* MQC component */ - - int passno, bpno, passtype; - int nmsedec = 0; - int i, max; - char type = T1_TYPE_MQ; - double tempwmsedec; - - max = 0; - for (i = 0; i < t1->w * t1->h; ++i) { - int tmp = abs(t1->data[i]); - max = int_max(max, tmp); - } - - cblk->numbps = max ? (int_floorlog2(max) + 1) - T1_NMSEDEC_FRACBITS : 0; - - bpno = cblk->numbps - 1; - passtype = 2; - - mqc_resetstates(mqc); - mqc_setstate(mqc, T1_CTXNO_UNI, 0, 46); - mqc_setstate(mqc, T1_CTXNO_AGG, 0, 3); - mqc_setstate(mqc, T1_CTXNO_ZC, 0, 4); - mqc_init_enc(mqc, cblk->data); - - for (passno = 0; bpno >= 0; ++passno) { - opj_tcd_pass_t *pass = &cblk->passes[passno]; - int correction = 3; - type = ((bpno < (cblk->numbps - 4)) && (passtype < 2) && (cblksty & J2K_CCP_CBLKSTY_LAZY)) ? T1_TYPE_RAW : T1_TYPE_MQ; - - switch (passtype) { - case 0: - t1_enc_sigpass(t1, bpno, orient, &nmsedec, type, cblksty); - break; - case 1: - t1_enc_refpass(t1, bpno, &nmsedec, type, cblksty); - break; - case 2: - t1_enc_clnpass(t1, bpno, orient, &nmsedec, cblksty); - /* code switch SEGMARK (i.e. SEGSYM) */ - if (cblksty & J2K_CCP_CBLKSTY_SEGSYM) - mqc_segmark_enc(mqc); - break; - } - - /* fixed_quality */ - tempwmsedec = t1_getwmsedec(nmsedec, compno, level, orient, bpno, qmfbid, stepsize, numcomps, mct); - cumwmsedec += tempwmsedec; - tile->distotile += tempwmsedec; - - /* Code switch "RESTART" (i.e. TERMALL) */ - if ((cblksty & J2K_CCP_CBLKSTY_TERMALL) && !((passtype == 2) && (bpno - 1 < 0))) { - if (type == T1_TYPE_RAW) { - mqc_flush(mqc); - correction = 1; - /* correction = mqc_bypass_flush_enc(); */ - } else { /* correction = mqc_restart_enc(); */ - mqc_flush(mqc); - correction = 1; - } - pass->term = 1; - } else { - if (((bpno < (cblk->numbps - 4) && (passtype > 0)) - || ((bpno == (cblk->numbps - 4)) && (passtype == 2))) && (cblksty & J2K_CCP_CBLKSTY_LAZY)) { - if (type == T1_TYPE_RAW) { - mqc_flush(mqc); - correction = 1; - /* correction = mqc_bypass_flush_enc(); */ - } else { /* correction = mqc_restart_enc(); */ - mqc_flush(mqc); - correction = 1; - } - pass->term = 1; - } else { - pass->term = 0; - } - } - - if (++passtype == 3) { - passtype = 0; - bpno--; - } - - if (pass->term && bpno > 0) { - type = ((bpno < (cblk->numbps - 4)) && (passtype < 2) && (cblksty & J2K_CCP_CBLKSTY_LAZY)) ? T1_TYPE_RAW : T1_TYPE_MQ; - if (type == T1_TYPE_RAW) - mqc_bypass_init_enc(mqc); - else - mqc_restart_init_enc(mqc); - } - - pass->distortiondec = cumwmsedec; - pass->rate = mqc_numbytes(mqc) + correction; /* FIXME */ - - /* Code-switch "RESET" */ - if (cblksty & J2K_CCP_CBLKSTY_RESET) - mqc_reset_enc(mqc); - } - - /* Code switch "ERTERM" (i.e. PTERM) */ - if (cblksty & J2K_CCP_CBLKSTY_PTERM) - mqc_erterm_enc(mqc); - else /* Default coding */ if (!(cblksty & J2K_CCP_CBLKSTY_LAZY)) - mqc_flush(mqc); - - cblk->totalpasses = passno; - - for (passno = 0; passnototalpasses; passno++) { - opj_tcd_pass_t *pass = &cblk->passes[passno]; - if (pass->rate > mqc_numbytes(mqc)) - pass->rate = mqc_numbytes(mqc); - /*Preventing generation of FF as last data byte of a pass*/ - if((pass->rate>1) && (cblk->data[pass->rate - 1] == 0xFF)){ - pass->rate--; - } - pass->len = pass->rate - (passno == 0 ? 0 : cblk->passes[passno - 1].rate); - } -} - -static void t1_decode_cblk( - opj_t1_t *t1, - opj_tcd_cblk_dec_t* cblk, - int orient, - int roishift, - int cblksty) -{ - opj_raw_t *raw = t1->raw; /* RAW component */ - opj_mqc_t *mqc = t1->mqc; /* MQC component */ - - int bpno, passtype; - int segno, passno; - char type = T1_TYPE_MQ; /* BYPASS mode */ - - if(!allocate_buffers( - t1, - cblk->x1 - cblk->x0, - cblk->y1 - cblk->y0)) - { - return; - } - - bpno = roishift + cblk->numbps - 1; - passtype = 2; - - mqc_resetstates(mqc); - mqc_setstate(mqc, T1_CTXNO_UNI, 0, 46); - mqc_setstate(mqc, T1_CTXNO_AGG, 0, 3); - mqc_setstate(mqc, T1_CTXNO_ZC, 0, 4); - - for (segno = 0; segno < cblk->numsegs; ++segno) { - opj_tcd_seg_t *seg = &cblk->segs[segno]; - - /* BYPASS mode */ - type = ((bpno <= (cblk->numbps - 1) - 4) && (passtype < 2) && (cblksty & J2K_CCP_CBLKSTY_LAZY)) ? T1_TYPE_RAW : T1_TYPE_MQ; - /* FIXME: slviewer gets here with a null pointer. Why? Partially downloaded and/or corrupt textures? */ - if(seg->data == NULL){ - continue; - } - if (type == T1_TYPE_RAW) { - raw_init_dec(raw, (*seg->data) + seg->dataindex, seg->len); - } else { - mqc_init_dec(mqc, (*seg->data) + seg->dataindex, seg->len); - } - - for (passno = 0; passno < seg->numpasses; ++passno) { - switch (passtype) { - case 0: - if (type == T1_TYPE_RAW) { - t1_dec_sigpass_raw(t1, bpno+1, orient, cblksty); - } else { - if (cblksty & J2K_CCP_CBLKSTY_VSC) { - t1_dec_sigpass_mqc_vsc(t1, bpno+1, orient); - } else { - t1_dec_sigpass_mqc(t1, bpno+1, orient); - } - } - break; - case 1: - if (type == T1_TYPE_RAW) { - t1_dec_refpass_raw(t1, bpno+1, cblksty); - } else { - if (cblksty & J2K_CCP_CBLKSTY_VSC) { - t1_dec_refpass_mqc_vsc(t1, bpno+1); - } else { - t1_dec_refpass_mqc(t1, bpno+1); - } - } - break; - case 2: - t1_dec_clnpass(t1, bpno+1, orient, cblksty); - break; - } - - if ((cblksty & J2K_CCP_CBLKSTY_RESET) && type == T1_TYPE_MQ) { - mqc_resetstates(mqc); - mqc_setstate(mqc, T1_CTXNO_UNI, 0, 46); - mqc_setstate(mqc, T1_CTXNO_AGG, 0, 3); - mqc_setstate(mqc, T1_CTXNO_ZC, 0, 4); - } - if (++passtype == 3) { - passtype = 0; - bpno--; - } - } - } -} - -/* ----------------------------------------------------------------------- */ - -opj_t1_t* t1_create(opj_common_ptr cinfo) { - opj_t1_t *t1 = (opj_t1_t*) opj_malloc(sizeof(opj_t1_t)); - if(!t1) - return NULL; - - t1->cinfo = cinfo; - /* create MQC and RAW handles */ - t1->mqc = mqc_create(); - t1->raw = raw_create(); - - t1->data=NULL; - t1->flags=NULL; - t1->datasize=0; - t1->flagssize=0; - - return t1; -} - -void t1_destroy(opj_t1_t *t1) { - if(t1) { - /* destroy MQC and RAW handles */ - mqc_destroy(t1->mqc); - raw_destroy(t1->raw); - opj_aligned_free(t1->data); - opj_aligned_free(t1->flags); - opj_free(t1); - } -} - -void t1_encode_cblks( - opj_t1_t *t1, - opj_tcd_tile_t *tile, - opj_tcp_t *tcp) -{ - int compno, resno, bandno, precno, cblkno; - - tile->distotile = 0; /* fixed_quality */ - - for (compno = 0; compno < tile->numcomps; ++compno) { - opj_tcd_tilecomp_t* tilec = &tile->comps[compno]; - opj_tccp_t* tccp = &tcp->tccps[compno]; - int tile_w = tilec->x1 - tilec->x0; - - for (resno = 0; resno < tilec->numresolutions; ++resno) { - opj_tcd_resolution_t *res = &tilec->resolutions[resno]; - - for (bandno = 0; bandno < res->numbands; ++bandno) { - opj_tcd_band_t* restrict band = &res->bands[bandno]; - int bandconst = 8192 * 8192 / ((int) floor(band->stepsize * 8192)); - - for (precno = 0; precno < res->pw * res->ph; ++precno) { - opj_tcd_precinct_t *prc = &band->precincts[precno]; - - for (cblkno = 0; cblkno < prc->cw * prc->ch; ++cblkno) { - opj_tcd_cblk_enc_t* cblk = &prc->cblks.enc[cblkno]; - int* restrict datap; - int* restrict tiledp; - int cblk_w; - int cblk_h; - int i, j; - - int x = cblk->x0 - band->x0; - int y = cblk->y0 - band->y0; - if (band->bandno & 1) { - opj_tcd_resolution_t *pres = &tilec->resolutions[resno - 1]; - x += pres->x1 - pres->x0; - } - if (band->bandno & 2) { - opj_tcd_resolution_t *pres = &tilec->resolutions[resno - 1]; - y += pres->y1 - pres->y0; - } - - if(!allocate_buffers( - t1, - cblk->x1 - cblk->x0, - cblk->y1 - cblk->y0)) - { - return; - } - - datap=t1->data; - cblk_w = t1->w; - cblk_h = t1->h; - - tiledp=&tilec->data[(y * tile_w) + x]; - if (tccp->qmfbid == 1) { - for (j = 0; j < cblk_h; ++j) { - for (i = 0; i < cblk_w; ++i) { - int tmp = tiledp[(j * tile_w) + i]; - datap[(j * cblk_w) + i] = tmp << T1_NMSEDEC_FRACBITS; - } - } - } else { /* if (tccp->qmfbid == 0) */ - for (j = 0; j < cblk_h; ++j) { - for (i = 0; i < cblk_w; ++i) { - int tmp = tiledp[(j * tile_w) + i]; - datap[(j * cblk_w) + i] = - fix_mul( - tmp, - bandconst) >> (11 - T1_NMSEDEC_FRACBITS); - } - } - } - - t1_encode_cblk( - t1, - cblk, - band->bandno, - compno, - tilec->numresolutions - 1 - resno, - tccp->qmfbid, - band->stepsize, - tccp->cblksty, - tile->numcomps, - tcp->mct, - tile); - - } /* cblkno */ - } /* precno */ - } /* bandno */ - } /* resno */ - } /* compno */ -} - -void t1_decode_cblks( - opj_t1_t* t1, - opj_tcd_tilecomp_t* tilec, - opj_tccp_t* tccp) -{ - int resno, bandno, precno, cblkno; - - int tile_w = tilec->x1 - tilec->x0; - - for (resno = 0; resno < tilec->numresolutions; ++resno) { - opj_tcd_resolution_t* res = &tilec->resolutions[resno]; - - for (bandno = 0; bandno < res->numbands; ++bandno) { - opj_tcd_band_t* restrict band = &res->bands[bandno]; - - for (precno = 0; precno < res->pw * res->ph; ++precno) { - opj_tcd_precinct_t* precinct = &band->precincts[precno]; - - for (cblkno = 0; cblkno < precinct->cw * precinct->ch; ++cblkno) { - opj_tcd_cblk_dec_t* cblk = &precinct->cblks.dec[cblkno]; - int* restrict datap; - int cblk_w, cblk_h; - int x, y; - int i, j; - - t1_decode_cblk( - t1, - cblk, - band->bandno, - tccp->roishift, - tccp->cblksty); - - x = cblk->x0 - band->x0; - y = cblk->y0 - band->y0; - if (band->bandno & 1) { - opj_tcd_resolution_t* pres = &tilec->resolutions[resno - 1]; - x += pres->x1 - pres->x0; - } - if (band->bandno & 2) { - opj_tcd_resolution_t* pres = &tilec->resolutions[resno - 1]; - y += pres->y1 - pres->y0; - } - - datap=t1->data; - cblk_w = t1->w; - cblk_h = t1->h; - - if (tccp->roishift) { - int thresh = 1 << tccp->roishift; - for (j = 0; j < cblk_h; ++j) { - for (i = 0; i < cblk_w; ++i) { - int val = datap[(j * cblk_w) + i]; - int mag = abs(val); - if (mag >= thresh) { - mag >>= tccp->roishift; - datap[(j * cblk_w) + i] = val < 0 ? -mag : mag; - } - } - } - } - - if (tccp->qmfbid == 1) { - int* restrict tiledp = &tilec->data[(y * tile_w) + x]; - for (j = 0; j < cblk_h; ++j) { - for (i = 0; i < cblk_w; ++i) { - int tmp = datap[(j * cblk_w) + i]; - ((int*)tiledp)[(j * tile_w) + i] = tmp / 2; - } - } - } else { /* if (tccp->qmfbid == 0) */ - float* restrict tiledp = (float*) &tilec->data[(y * tile_w) + x]; - for (j = 0; j < cblk_h; ++j) { - float* restrict tiledp2 = tiledp; - for (i = 0; i < cblk_w; ++i) { - float tmp = *datap * band->stepsize; - *tiledp2 = tmp; - datap++; - tiledp2++; - } - tiledp += tile_w; - } - } - opj_free(cblk->data); - opj_free(cblk->segs); - } /* cblkno */ - opj_free(precinct->cblks.dec); - } /* precno */ - } /* bandno */ - } /* resno */ -} - diff --git a/openjpeg-dotnet/libopenjpeg/t1.h b/openjpeg-dotnet/libopenjpeg/t1.h deleted file mode 100644 index 572ec88d..00000000 --- a/openjpeg-dotnet/libopenjpeg/t1.h +++ /dev/null @@ -1,147 +0,0 @@ -/* - * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium - * Copyright (c) 2002-2007, Professor Benoit Macq - * Copyright (c) 2001-2003, David Janssens - * Copyright (c) 2002-2003, Yannick Verschueren - * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe - * Copyright (c) 2005, Herve Drolon, FreeImage Team - * 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 __T1_H -#define __T1_H -/** -@file t1.h -@brief Implementation of the tier-1 coding (coding of code-block coefficients) (T1) - -The functions in T1.C have for goal to realize the tier-1 coding operation. The functions -in T1.C are used by some function in TCD.C. -*/ - -/** @defgroup T1 T1 - Implementation of the tier-1 coding */ -/*@{*/ - -/* ----------------------------------------------------------------------- */ -#define T1_NMSEDEC_BITS 7 - -#define T1_SIG_NE 0x0001 /**< Context orientation : North-East direction */ -#define T1_SIG_SE 0x0002 /**< Context orientation : South-East direction */ -#define T1_SIG_SW 0x0004 /**< Context orientation : South-West direction */ -#define T1_SIG_NW 0x0008 /**< Context orientation : North-West direction */ -#define T1_SIG_N 0x0010 /**< Context orientation : North direction */ -#define T1_SIG_E 0x0020 /**< Context orientation : East direction */ -#define T1_SIG_S 0x0040 /**< Context orientation : South direction */ -#define T1_SIG_W 0x0080 /**< Context orientation : West direction */ -#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_ZC 9 -#define T1_NUMCTXS_SC 5 -#define T1_NUMCTXS_MAG 3 -#define T1_NUMCTXS_AGG 1 -#define T1_NUMCTXS_UNI 1 - -#define T1_CTXNO_ZC 0 -#define T1_CTXNO_SC (T1_CTXNO_ZC+T1_NUMCTXS_ZC) -#define T1_CTXNO_MAG (T1_CTXNO_SC+T1_NUMCTXS_SC) -#define T1_CTXNO_AGG (T1_CTXNO_MAG+T1_NUMCTXS_MAG) -#define T1_CTXNO_UNI (T1_CTXNO_AGG+T1_NUMCTXS_AGG) -#define T1_NUMCTXS (T1_CTXNO_UNI+T1_NUMCTXS_UNI) - -#define T1_NMSEDEC_FRACBITS (T1_NMSEDEC_BITS-1) - -#define T1_TYPE_MQ 0 /**< Normal coding using entropy coder */ -#define T1_TYPE_RAW 1 /**< No encoding the information is store under raw format in codestream (mode switch RAW)*/ - -/* ----------------------------------------------------------------------- */ - -typedef short flag_t; - -/** -Tier-1 coding (coding of code-block coefficients) -*/ -typedef struct opj_t1 { - /** codec context */ - opj_common_ptr cinfo; - - /** MQC component */ - opj_mqc_t *mqc; - /** RAW component */ - opj_raw_t *raw; - - int *data; - flag_t *flags; - int w; - int h; - int datasize; - int flagssize; - int flags_stride; -} opj_t1_t; - -#define MACRO_t1_flags(x,y) t1->flags[((x)*(t1->flags_stride))+(y)] - -/** @name Exported functions */ -/*@{*/ -/* ----------------------------------------------------------------------- */ -/** -Create a new T1 handle -and initialize the look-up tables of the Tier-1 coder/decoder -@return Returns a new T1 handle if successful, returns NULL otherwise -@see t1_init_luts -*/ -opj_t1_t* t1_create(opj_common_ptr cinfo); -/** -Destroy a previously created T1 handle -@param t1 T1 handle to destroy -*/ -void t1_destroy(opj_t1_t *t1); -/** -Encode the code-blocks of a tile -@param t1 T1 handle -@param tile The tile to encode -@param tcp Tile coding parameters -*/ -void t1_encode_cblks(opj_t1_t *t1, opj_tcd_tile_t *tile, opj_tcp_t *tcp); -/** -Decode the code-blocks of a tile -@param t1 T1 handle -@param tilec The tile to decode -@param tccp Tile coding parameters -*/ -void t1_decode_cblks(opj_t1_t* t1, opj_tcd_tilecomp_t* tilec, opj_tccp_t* tccp); -/* ----------------------------------------------------------------------- */ -/*@}*/ - -/*@}*/ - -#endif /* __T1_H */ diff --git a/openjpeg-dotnet/libopenjpeg/t1_generate_luts.c b/openjpeg-dotnet/libopenjpeg/t1_generate_luts.c deleted file mode 100644 index 39880414..00000000 --- a/openjpeg-dotnet/libopenjpeg/t1_generate_luts.c +++ /dev/null @@ -1,275 +0,0 @@ -/* - * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium - * Copyright (c) 2002-2007, Professor Benoit Macq - * Copyright (c) 2001-2003, David Janssens - * Copyright (c) 2002-2003, Yannick Verschueren - * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe - * Copyright (c) 2005, Herve Drolon, FreeImage Team - * Copyright (c) 2007, Callum Lerwick - * 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 "opj_includes.h" -#include - -static 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); -} - -static 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); -} - -static 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 dump_array16(int array[],int size){ - int i; - --size; - for (i = 0; i < size; ++i) { - printf("0x%04x, ", array[i]); - if(!((i+1)&0x7)) - printf("\n "); - } - printf("0x%04x\n};\n\n", array[size]); -} - -int main(){ - int i, j; - double u, v, t; - - int lut_ctxno_zc[1024]; - int lut_nmsedec_sig[1 << T1_NMSEDEC_BITS]; - int lut_nmsedec_sig0[1 << T1_NMSEDEC_BITS]; - int lut_nmsedec_ref[1 << T1_NMSEDEC_BITS]; - int lut_nmsedec_ref0[1 << T1_NMSEDEC_BITS]; - - printf("/* This file was automatically generated by t1_generate_luts.c */\n\n"); - - // lut_ctxno_zc - for (j = 0; j < 4; ++j) { - for (i = 0; i < 256; ++i) { - int orient = j; - if (orient == 2) { - orient = 1; - } else if (orient == 1) { - orient = 2; - } - lut_ctxno_zc[(orient << 8) | i] = t1_init_ctxno_zc(i, j); - } - } - - printf("static char lut_ctxno_zc[1024] = {\n "); - for (i = 0; i < 1023; ++i) { - printf("%i, ", lut_ctxno_zc[i]); - if(!((i+1)&0x1f)) - printf("\n "); - } - printf("%i\n};\n\n", lut_ctxno_zc[1023]); - - // lut_ctxno_sc - printf("static char lut_ctxno_sc[256] = {\n "); - for (i = 0; i < 255; ++i) { - printf("0x%x, ", t1_init_ctxno_sc(i << 4)); - if(!((i+1)&0xf)) - printf("\n "); - } - printf("0x%x\n};\n\n", t1_init_ctxno_sc(255 << 4)); - - // lut_spb - printf("static char lut_spb[256] = {\n "); - for (i = 0; i < 255; ++i) { - printf("%i, ", t1_init_spb(i << 4)); - if(!((i+1)&0x1f)) - printf("\n "); - } - printf("%i\n};\n\n", t1_init_spb(255 << 4)); - - /* FIXME FIXME FIXME */ - /* fprintf(stdout,"nmsedec luts:\n"); */ - for (i = 0; i < (1 << T1_NMSEDEC_BITS); ++i) { - t = i / pow(2, T1_NMSEDEC_FRACBITS); - u = t; - v = t - 1.5; - lut_nmsedec_sig[i] = - int_max(0, - (int) (floor((u * u - v * v) * pow(2, T1_NMSEDEC_FRACBITS) + 0.5) / pow(2, T1_NMSEDEC_FRACBITS) * 8192.0)); - lut_nmsedec_sig0[i] = - int_max(0, - (int) (floor((u * u) * pow(2, T1_NMSEDEC_FRACBITS) + 0.5) / pow(2, T1_NMSEDEC_FRACBITS) * 8192.0)); - u = t - 1.0; - if (i & (1 << (T1_NMSEDEC_BITS - 1))) { - v = t - 1.5; - } else { - v = t - 0.5; - } - lut_nmsedec_ref[i] = - int_max(0, - (int) (floor((u * u - v * v) * pow(2, T1_NMSEDEC_FRACBITS) + 0.5) / pow(2, T1_NMSEDEC_FRACBITS) * 8192.0)); - lut_nmsedec_ref0[i] = - int_max(0, - (int) (floor((u * u) * pow(2, T1_NMSEDEC_FRACBITS) + 0.5) / pow(2, T1_NMSEDEC_FRACBITS) * 8192.0)); - } - - printf("static short lut_nmsedec_sig[1 << T1_NMSEDEC_BITS] = {\n "); - dump_array16(lut_nmsedec_sig, 1 << T1_NMSEDEC_BITS); - - printf("static short lut_nmsedec_sig0[1 << T1_NMSEDEC_BITS] = {\n "); - dump_array16(lut_nmsedec_sig0, 1 << T1_NMSEDEC_BITS); - - printf("static short lut_nmsedec_ref[1 << T1_NMSEDEC_BITS] = {\n "); - dump_array16(lut_nmsedec_ref, 1 << T1_NMSEDEC_BITS); - - printf("static short lut_nmsedec_ref0[1 << T1_NMSEDEC_BITS] = {\n "); - dump_array16(lut_nmsedec_ref0, 1 << T1_NMSEDEC_BITS); - - return 0; -} diff --git a/openjpeg-dotnet/libopenjpeg/t1_luts.h b/openjpeg-dotnet/libopenjpeg/t1_luts.h deleted file mode 100644 index e5e33f66..00000000 --- a/openjpeg-dotnet/libopenjpeg/t1_luts.h +++ /dev/null @@ -1,143 +0,0 @@ -/* This file was automatically generated by t1_generate_luts.c */ - -static char lut_ctxno_zc[1024] = { - 0, 1, 1, 2, 1, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, - 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, - 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, - 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, - 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, - 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, - 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, - 0, 1, 1, 2, 1, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, - 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, - 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, - 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, - 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, - 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, - 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, - 0, 1, 1, 2, 1, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, - 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, - 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, - 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, - 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, - 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, - 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, - 0, 3, 3, 6, 3, 6, 6, 8, 3, 6, 6, 8, 6, 8, 8, 8, 1, 4, 4, 7, 4, 7, 7, 8, 4, 7, 7, 8, 7, 8, 8, 8, - 1, 4, 4, 7, 4, 7, 7, 8, 4, 7, 7, 8, 7, 8, 8, 8, 2, 5, 5, 7, 5, 7, 7, 8, 5, 7, 7, 8, 7, 8, 8, 8, - 1, 4, 4, 7, 4, 7, 7, 8, 4, 7, 7, 8, 7, 8, 8, 8, 2, 5, 5, 7, 5, 7, 7, 8, 5, 7, 7, 8, 7, 8, 8, 8, - 2, 5, 5, 7, 5, 7, 7, 8, 5, 7, 7, 8, 7, 8, 8, 8, 2, 5, 5, 7, 5, 7, 7, 8, 5, 7, 7, 8, 7, 8, 8, 8, - 1, 4, 4, 7, 4, 7, 7, 8, 4, 7, 7, 8, 7, 8, 8, 8, 2, 5, 5, 7, 5, 7, 7, 8, 5, 7, 7, 8, 7, 8, 8, 8, - 2, 5, 5, 7, 5, 7, 7, 8, 5, 7, 7, 8, 7, 8, 8, 8, 2, 5, 5, 7, 5, 7, 7, 8, 5, 7, 7, 8, 7, 8, 8, 8, - 2, 5, 5, 7, 5, 7, 7, 8, 5, 7, 7, 8, 7, 8, 8, 8, 2, 5, 5, 7, 5, 7, 7, 8, 5, 7, 7, 8, 7, 8, 8, 8, - 2, 5, 5, 7, 5, 7, 7, 8, 5, 7, 7, 8, 7, 8, 8, 8, 2, 5, 5, 7, 5, 7, 7, 8, 5, 7, 7, 8, 7, 8, 8, 8 -}; - -static char lut_ctxno_sc[256] = { - 0x9, 0xa, 0xc, 0xd, 0xa, 0xa, 0xd, 0xd, 0xc, 0xd, 0xc, 0xd, 0xd, 0xd, 0xd, 0xd, - 0x9, 0xa, 0xc, 0xb, 0xa, 0x9, 0xd, 0xc, 0xc, 0xb, 0xc, 0xb, 0xd, 0xc, 0xd, 0xc, - 0x9, 0xa, 0xc, 0xb, 0xa, 0xa, 0xb, 0xb, 0xc, 0xd, 0x9, 0xa, 0xd, 0xd, 0xa, 0xa, - 0x9, 0xa, 0xc, 0xd, 0xa, 0x9, 0xb, 0xc, 0xc, 0xb, 0x9, 0xa, 0xd, 0xc, 0xa, 0x9, - 0x9, 0xa, 0xc, 0xd, 0xa, 0x9, 0xb, 0xc, 0xc, 0xd, 0xc, 0xd, 0xb, 0xc, 0xb, 0xc, - 0x9, 0xa, 0xc, 0xb, 0xa, 0xa, 0xb, 0xb, 0xc, 0xb, 0xc, 0xb, 0xb, 0xb, 0xb, 0xb, - 0x9, 0xa, 0xc, 0xb, 0xa, 0x9, 0xd, 0xc, 0xc, 0xd, 0x9, 0xa, 0xb, 0xc, 0xa, 0x9, - 0x9, 0xa, 0xc, 0xd, 0xa, 0xa, 0xd, 0xd, 0xc, 0xb, 0x9, 0xa, 0xb, 0xb, 0xa, 0xa, - 0x9, 0xa, 0xc, 0xd, 0xa, 0xa, 0xd, 0xd, 0xc, 0xb, 0x9, 0xa, 0xb, 0xb, 0xa, 0xa, - 0x9, 0xa, 0xc, 0xb, 0xa, 0x9, 0xd, 0xc, 0xc, 0xd, 0x9, 0xa, 0xb, 0xc, 0xa, 0x9, - 0x9, 0xa, 0xc, 0xb, 0xa, 0xa, 0xb, 0xb, 0xc, 0xb, 0xc, 0xb, 0xb, 0xb, 0xb, 0xb, - 0x9, 0xa, 0xc, 0xd, 0xa, 0x9, 0xb, 0xc, 0xc, 0xd, 0xc, 0xd, 0xb, 0xc, 0xb, 0xc, - 0x9, 0xa, 0xc, 0xd, 0xa, 0x9, 0xb, 0xc, 0xc, 0xb, 0x9, 0xa, 0xd, 0xc, 0xa, 0x9, - 0x9, 0xa, 0xc, 0xb, 0xa, 0xa, 0xb, 0xb, 0xc, 0xd, 0x9, 0xa, 0xd, 0xd, 0xa, 0xa, - 0x9, 0xa, 0xc, 0xb, 0xa, 0x9, 0xd, 0xc, 0xc, 0xb, 0xc, 0xb, 0xd, 0xc, 0xd, 0xc, - 0x9, 0xa, 0xc, 0xd, 0xa, 0xa, 0xd, 0xd, 0xc, 0xd, 0xc, 0xd, 0xd, 0xd, 0xd, 0xd -}; - -static char lut_spb[256] = { - 0, 0, 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, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, - 0, 0, 0, 0, 1, 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, 0, 0, - 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, - 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, - 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, - 0, 0, 1, 1, 1, 0, 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 -}; - -static short lut_nmsedec_sig[1 << T1_NMSEDEC_BITS] = { - 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, - 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, - 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, - 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, - 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, - 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, - 0x0000, 0x0180, 0x0300, 0x0480, 0x0600, 0x0780, 0x0900, 0x0a80, - 0x0c00, 0x0d80, 0x0f00, 0x1080, 0x1200, 0x1380, 0x1500, 0x1680, - 0x1800, 0x1980, 0x1b00, 0x1c80, 0x1e00, 0x1f80, 0x2100, 0x2280, - 0x2400, 0x2580, 0x2700, 0x2880, 0x2a00, 0x2b80, 0x2d00, 0x2e80, - 0x3000, 0x3180, 0x3300, 0x3480, 0x3600, 0x3780, 0x3900, 0x3a80, - 0x3c00, 0x3d80, 0x3f00, 0x4080, 0x4200, 0x4380, 0x4500, 0x4680, - 0x4800, 0x4980, 0x4b00, 0x4c80, 0x4e00, 0x4f80, 0x5100, 0x5280, - 0x5400, 0x5580, 0x5700, 0x5880, 0x5a00, 0x5b80, 0x5d00, 0x5e80, - 0x6000, 0x6180, 0x6300, 0x6480, 0x6600, 0x6780, 0x6900, 0x6a80, - 0x6c00, 0x6d80, 0x6f00, 0x7080, 0x7200, 0x7380, 0x7500, 0x7680 -}; - -static short lut_nmsedec_sig0[1 << T1_NMSEDEC_BITS] = { - 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0080, 0x0080, - 0x0080, 0x0080, 0x0100, 0x0100, 0x0100, 0x0180, 0x0180, 0x0200, - 0x0200, 0x0280, 0x0280, 0x0300, 0x0300, 0x0380, 0x0400, 0x0400, - 0x0480, 0x0500, 0x0580, 0x0580, 0x0600, 0x0680, 0x0700, 0x0780, - 0x0800, 0x0880, 0x0900, 0x0980, 0x0a00, 0x0a80, 0x0b80, 0x0c00, - 0x0c80, 0x0d00, 0x0e00, 0x0e80, 0x0f00, 0x1000, 0x1080, 0x1180, - 0x1200, 0x1300, 0x1380, 0x1480, 0x1500, 0x1600, 0x1700, 0x1780, - 0x1880, 0x1980, 0x1a80, 0x1b00, 0x1c00, 0x1d00, 0x1e00, 0x1f00, - 0x2000, 0x2100, 0x2200, 0x2300, 0x2400, 0x2500, 0x2680, 0x2780, - 0x2880, 0x2980, 0x2b00, 0x2c00, 0x2d00, 0x2e80, 0x2f80, 0x3100, - 0x3200, 0x3380, 0x3480, 0x3600, 0x3700, 0x3880, 0x3a00, 0x3b00, - 0x3c80, 0x3e00, 0x3f80, 0x4080, 0x4200, 0x4380, 0x4500, 0x4680, - 0x4800, 0x4980, 0x4b00, 0x4c80, 0x4e00, 0x4f80, 0x5180, 0x5300, - 0x5480, 0x5600, 0x5800, 0x5980, 0x5b00, 0x5d00, 0x5e80, 0x6080, - 0x6200, 0x6400, 0x6580, 0x6780, 0x6900, 0x6b00, 0x6d00, 0x6e80, - 0x7080, 0x7280, 0x7480, 0x7600, 0x7800, 0x7a00, 0x7c00, 0x7e00 -}; - -static short lut_nmsedec_ref[1 << T1_NMSEDEC_BITS] = { - 0x1800, 0x1780, 0x1700, 0x1680, 0x1600, 0x1580, 0x1500, 0x1480, - 0x1400, 0x1380, 0x1300, 0x1280, 0x1200, 0x1180, 0x1100, 0x1080, - 0x1000, 0x0f80, 0x0f00, 0x0e80, 0x0e00, 0x0d80, 0x0d00, 0x0c80, - 0x0c00, 0x0b80, 0x0b00, 0x0a80, 0x0a00, 0x0980, 0x0900, 0x0880, - 0x0800, 0x0780, 0x0700, 0x0680, 0x0600, 0x0580, 0x0500, 0x0480, - 0x0400, 0x0380, 0x0300, 0x0280, 0x0200, 0x0180, 0x0100, 0x0080, - 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, - 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, - 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, - 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, - 0x0000, 0x0080, 0x0100, 0x0180, 0x0200, 0x0280, 0x0300, 0x0380, - 0x0400, 0x0480, 0x0500, 0x0580, 0x0600, 0x0680, 0x0700, 0x0780, - 0x0800, 0x0880, 0x0900, 0x0980, 0x0a00, 0x0a80, 0x0b00, 0x0b80, - 0x0c00, 0x0c80, 0x0d00, 0x0d80, 0x0e00, 0x0e80, 0x0f00, 0x0f80, - 0x1000, 0x1080, 0x1100, 0x1180, 0x1200, 0x1280, 0x1300, 0x1380, - 0x1400, 0x1480, 0x1500, 0x1580, 0x1600, 0x1680, 0x1700, 0x1780 -}; - -static short lut_nmsedec_ref0[1 << T1_NMSEDEC_BITS] = { - 0x2000, 0x1f00, 0x1e00, 0x1d00, 0x1c00, 0x1b00, 0x1a80, 0x1980, - 0x1880, 0x1780, 0x1700, 0x1600, 0x1500, 0x1480, 0x1380, 0x1300, - 0x1200, 0x1180, 0x1080, 0x1000, 0x0f00, 0x0e80, 0x0e00, 0x0d00, - 0x0c80, 0x0c00, 0x0b80, 0x0a80, 0x0a00, 0x0980, 0x0900, 0x0880, - 0x0800, 0x0780, 0x0700, 0x0680, 0x0600, 0x0580, 0x0580, 0x0500, - 0x0480, 0x0400, 0x0400, 0x0380, 0x0300, 0x0300, 0x0280, 0x0280, - 0x0200, 0x0200, 0x0180, 0x0180, 0x0100, 0x0100, 0x0100, 0x0080, - 0x0080, 0x0080, 0x0080, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, - 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0080, 0x0080, - 0x0080, 0x0080, 0x0100, 0x0100, 0x0100, 0x0180, 0x0180, 0x0200, - 0x0200, 0x0280, 0x0280, 0x0300, 0x0300, 0x0380, 0x0400, 0x0400, - 0x0480, 0x0500, 0x0580, 0x0580, 0x0600, 0x0680, 0x0700, 0x0780, - 0x0800, 0x0880, 0x0900, 0x0980, 0x0a00, 0x0a80, 0x0b80, 0x0c00, - 0x0c80, 0x0d00, 0x0e00, 0x0e80, 0x0f00, 0x1000, 0x1080, 0x1180, - 0x1200, 0x1300, 0x1380, 0x1480, 0x1500, 0x1600, 0x1700, 0x1780, - 0x1880, 0x1980, 0x1a80, 0x1b00, 0x1c00, 0x1d00, 0x1e00, 0x1f00 -}; - diff --git a/openjpeg-dotnet/libopenjpeg/t2.c b/openjpeg-dotnet/libopenjpeg/t2.c deleted file mode 100644 index 232a5437..00000000 --- a/openjpeg-dotnet/libopenjpeg/t2.c +++ /dev/null @@ -1,793 +0,0 @@ -/* - * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium - * Copyright (c) 2002-2007, Professor Benoit Macq - * Copyright (c) 2001-2003, David Janssens - * Copyright (c) 2002-2003, Yannick Verschueren - * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe - * Copyright (c) 2005, Herve Drolon, FreeImage Team - * 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 "opj_includes.h" - -/** @defgroup T2 T2 - Implementation of a tier-2 coding */ -/*@{*/ - -/** @name Local static functions */ -/*@{*/ - -static void t2_putcommacode(opj_bio_t *bio, int n); -static int t2_getcommacode(opj_bio_t *bio); -/** -Variable length code for signalling delta Zil (truncation point) -@param bio Bit Input/Output component -@param n delta Zil -*/ -static void t2_putnumpasses(opj_bio_t *bio, int n); -static int t2_getnumpasses(opj_bio_t *bio); -/** -Encode a packet of a tile to a destination buffer -@param tile Tile for which to write the packets -@param tcp Tile coding parameters -@param pi Packet identity -@param dest Destination buffer -@param len Length of the destination buffer -@param cstr_info Codestream information structure -@param tileno Number of the tile encoded -@return -*/ -static int t2_encode_packet(opj_tcd_tile_t *tile, opj_tcp_t *tcp, opj_pi_iterator_t *pi, unsigned char *dest, int len, opj_codestream_info_t *cstr_info, int tileno); -/** -@param cblk -@param index -@param cblksty -@param first -*/ -static void t2_init_seg(opj_tcd_cblk_dec_t* cblk, int index, int cblksty, int first); -/** -Decode a packet of a tile from a source buffer -@param t2 T2 handle -@param src Source buffer -@param len Length of the source buffer -@param tile Tile for which to write the packets -@param tcp Tile coding parameters -@param pi Packet identity -@param pack_info Packet information -@return -*/ -static int t2_decode_packet(opj_t2_t* t2, unsigned char *src, int len, opj_tcd_tile_t *tile, - opj_tcp_t *tcp, opj_pi_iterator_t *pi, opj_packet_info_t *pack_info); - -/*@}*/ - -/*@}*/ - -/* ----------------------------------------------------------------------- */ - -/* #define RESTART 0x04 */ - -static void t2_putcommacode(opj_bio_t *bio, int n) { - while (--n >= 0) { - bio_write(bio, 1, 1); - } - bio_write(bio, 0, 1); -} - -static int t2_getcommacode(opj_bio_t *bio) { - int n; - for (n = 0; bio_read(bio, 1); n++) { - ; - } - return n; -} - -static void t2_putnumpasses(opj_bio_t *bio, int n) { - if (n == 1) { - bio_write(bio, 0, 1); - } else if (n == 2) { - bio_write(bio, 2, 2); - } else if (n <= 5) { - bio_write(bio, 0xc | (n - 3), 4); - } else if (n <= 36) { - bio_write(bio, 0x1e0 | (n - 6), 9); - } else if (n <= 164) { - bio_write(bio, 0xff80 | (n - 37), 16); - } -} - -static int t2_getnumpasses(opj_bio_t *bio) { - int n; - if (!bio_read(bio, 1)) - return 1; - if (!bio_read(bio, 1)) - return 2; - if ((n = bio_read(bio, 2)) != 3) - return (3 + n); - if ((n = bio_read(bio, 5)) != 31) - return (6 + n); - return (37 + bio_read(bio, 7)); -} - -static int t2_encode_packet(opj_tcd_tile_t * tile, opj_tcp_t * tcp, opj_pi_iterator_t *pi, unsigned char *dest, int length, opj_codestream_info_t *cstr_info, int tileno) { - int bandno, cblkno; - unsigned char *c = dest; - - int compno = pi->compno; /* component value */ - int resno = pi->resno; /* resolution level value */ - int precno = pi->precno; /* precinct value */ - int layno = pi->layno; /* quality layer value */ - - opj_tcd_tilecomp_t *tilec = &tile->comps[compno]; - opj_tcd_resolution_t *res = &tilec->resolutions[resno]; - - opj_bio_t *bio = NULL; /* BIO component */ - - /* */ - if (tcp->csty & J2K_CP_CSTY_SOP) { - c[0] = 255; - c[1] = 145; - c[2] = 0; - c[3] = 4; - c[4] = (unsigned char)((tile->packno % 65536) / 256); - c[5] = (unsigned char)((tile->packno % 65536) % 256); - c += 6; - } - /* */ - - if (!layno) { - for (bandno = 0; bandno < res->numbands; bandno++) { - opj_tcd_band_t *band = &res->bands[bandno]; - opj_tcd_precinct_t *prc = &band->precincts[precno]; - tgt_reset(prc->incltree); - tgt_reset(prc->imsbtree); - for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) { - opj_tcd_cblk_enc_t* cblk = &prc->cblks.enc[cblkno]; - cblk->numpasses = 0; - tgt_setvalue(prc->imsbtree, cblkno, band->numbps - cblk->numbps); - } - } - } - - bio = bio_create(); - bio_init_enc(bio, c, length); - bio_write(bio, 1, 1); /* Empty header bit */ - - /* Writing Packet header */ - for (bandno = 0; bandno < res->numbands; bandno++) { - opj_tcd_band_t *band = &res->bands[bandno]; - opj_tcd_precinct_t *prc = &band->precincts[precno]; - for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) { - opj_tcd_cblk_enc_t* cblk = &prc->cblks.enc[cblkno]; - opj_tcd_layer_t *layer = &cblk->layers[layno]; - if (!cblk->numpasses && layer->numpasses) { - tgt_setvalue(prc->incltree, cblkno, layno); - } - } - for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) { - opj_tcd_cblk_enc_t* cblk = &prc->cblks.enc[cblkno]; - opj_tcd_layer_t *layer = &cblk->layers[layno]; - int increment = 0; - int nump = 0; - int len = 0, passno; - /* cblk inclusion bits */ - if (!cblk->numpasses) { - tgt_encode(bio, prc->incltree, cblkno, layno + 1); - } else { - bio_write(bio, layer->numpasses != 0, 1); - } - /* if cblk not included, go to the next cblk */ - if (!layer->numpasses) { - continue; - } - /* if first instance of cblk --> zero bit-planes information */ - if (!cblk->numpasses) { - cblk->numlenbits = 3; - tgt_encode(bio, prc->imsbtree, cblkno, 999); - } - /* number of coding passes included */ - t2_putnumpasses(bio, layer->numpasses); - - /* computation of the increase of the length indicator and insertion in the header */ - for (passno = cblk->numpasses; passno < cblk->numpasses + layer->numpasses; passno++) { - opj_tcd_pass_t *pass = &cblk->passes[passno]; - nump++; - len += pass->len; - if (pass->term || passno == (cblk->numpasses + layer->numpasses) - 1) { - increment = int_max(increment, int_floorlog2(len) + 1 - (cblk->numlenbits + int_floorlog2(nump))); - len = 0; - nump = 0; - } - } - t2_putcommacode(bio, increment); - - /* computation of the new Length indicator */ - cblk->numlenbits += increment; - - /* insertion of the codeword segment length */ - for (passno = cblk->numpasses; passno < cblk->numpasses + layer->numpasses; passno++) { - opj_tcd_pass_t *pass = &cblk->passes[passno]; - nump++; - len += pass->len; - if (pass->term || passno == (cblk->numpasses + layer->numpasses) - 1) { - bio_write(bio, len, cblk->numlenbits + int_floorlog2(nump)); - len = 0; - nump = 0; - } - } - } - } - - if (bio_flush(bio)) { - bio_destroy(bio); - return -999; /* modified to eliminate longjmp !! */ - } - - c += bio_numbytes(bio); - bio_destroy(bio); - - /* */ - if (tcp->csty & J2K_CP_CSTY_EPH) { - c[0] = 255; - c[1] = 146; - c += 2; - } - /* */ - - /* << INDEX */ - /* End of packet header position. Currently only represents the distance to start of packet - // Will be updated later by incrementing with packet start value */ - if(cstr_info && cstr_info->index_write) { - opj_packet_info_t *info_PK = &cstr_info->tile[tileno].packet[cstr_info->packno]; - info_PK->end_ph_pos = (int)(c - dest); - } - /* INDEX >> */ - - /* Writing the packet body */ - - for (bandno = 0; bandno < res->numbands; bandno++) { - opj_tcd_band_t *band = &res->bands[bandno]; - opj_tcd_precinct_t *prc = &band->precincts[precno]; - for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) { - opj_tcd_cblk_enc_t* cblk = &prc->cblks.enc[cblkno]; - opj_tcd_layer_t *layer = &cblk->layers[layno]; - if (!layer->numpasses) { - continue; - } - if (c + layer->len > dest + length) { - return -999; - } - - memcpy(c, layer->data, layer->len); - cblk->numpasses += layer->numpasses; - c += layer->len; - /* << INDEX */ - if(cstr_info && cstr_info->index_write) { - opj_packet_info_t *info_PK = &cstr_info->tile[tileno].packet[cstr_info->packno]; - info_PK->disto += layer->disto; - if (cstr_info->D_max < info_PK->disto) { - cstr_info->D_max = info_PK->disto; - } - } - /* INDEX >> */ - } - } - - return (c - dest); -} - -static void t2_init_seg(opj_tcd_cblk_dec_t* cblk, int index, int cblksty, int first) { - opj_tcd_seg_t* seg; - cblk->segs = (opj_tcd_seg_t*) opj_realloc(cblk->segs, (index + 1) * sizeof(opj_tcd_seg_t)); - seg = &cblk->segs[index]; - seg->data = NULL; - seg->dataindex = 0; - seg->numpasses = 0; - seg->len = 0; - if (cblksty & J2K_CCP_CBLKSTY_TERMALL) { - seg->maxpasses = 1; - } - else if (cblksty & J2K_CCP_CBLKSTY_LAZY) { - if (first) { - seg->maxpasses = 10; - } else { - seg->maxpasses = (((seg - 1)->maxpasses == 1) || ((seg - 1)->maxpasses == 10)) ? 2 : 1; - } - } else { - seg->maxpasses = 109; - } -} - -static int t2_decode_packet(opj_t2_t* t2, unsigned char *src, int len, opj_tcd_tile_t *tile, - opj_tcp_t *tcp, opj_pi_iterator_t *pi, opj_packet_info_t *pack_info) { - int bandno, cblkno; - unsigned char *c = src; - - opj_cp_t *cp = t2->cp; - - int compno = pi->compno; /* component value */ - int resno = pi->resno; /* resolution level value */ - int precno = pi->precno; /* precinct value */ - int layno = pi->layno; /* quality layer value */ - - opj_tcd_resolution_t* res = &tile->comps[compno].resolutions[resno]; - - unsigned char *hd = NULL; - int present; - - opj_bio_t *bio = NULL; /* BIO component */ - - if (layno == 0) { - for (bandno = 0; bandno < res->numbands; bandno++) { - opj_tcd_band_t *band = &res->bands[bandno]; - opj_tcd_precinct_t *prc = &band->precincts[precno]; - - if ((band->x1-band->x0 == 0)||(band->y1-band->y0 == 0)) continue; - - tgt_reset(prc->incltree); - tgt_reset(prc->imsbtree); - for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) { - opj_tcd_cblk_dec_t* cblk = &prc->cblks.dec[cblkno]; - cblk->numsegs = 0; - } - } - } - - /* SOP markers */ - - if (tcp->csty & J2K_CP_CSTY_SOP) { - if ((*c) != 0xff || (*(c + 1) != 0x91)) { - opj_event_msg(t2->cinfo, EVT_WARNING, "Expected SOP marker\n"); - } else { - c += 6; - } - - /** TODO : check the Nsop value */ - } - - /* - When the marker PPT/PPM is used the packet header are store in PPT/PPM marker - This part deal with this caracteristic - step 1: Read packet header in the saved structure - step 2: Return to codestream for decoding - */ - - bio = bio_create(); - - if (cp->ppm == 1) { /* PPM */ - hd = cp->ppm_data; - bio_init_dec(bio, hd, cp->ppm_len); - } else if (tcp->ppt == 1) { /* PPT */ - hd = tcp->ppt_data; - bio_init_dec(bio, hd, tcp->ppt_len); - } else { /* Normal Case */ - hd = c; - bio_init_dec(bio, hd, src+len-hd); - } - - present = bio_read(bio, 1); - - if (!present) { - bio_inalign(bio); - hd += bio_numbytes(bio); - bio_destroy(bio); - - /* EPH markers */ - - if (tcp->csty & J2K_CP_CSTY_EPH) { - if ((*hd) != 0xff || (*(hd + 1) != 0x92)) { - printf("Error : expected EPH marker\n"); - } else { - hd += 2; - } - } - - /* << INDEX */ - /* End of packet header position. Currently only represents the distance to start of packet - // Will be updated later by incrementing with packet start value*/ - if(pack_info) { - pack_info->end_ph_pos = (int)(c - src); - } - /* INDEX >> */ - - if (cp->ppm == 1) { /* PPM case */ - cp->ppm_len += cp->ppm_data-hd; - cp->ppm_data = hd; - return (c - src); - } - if (tcp->ppt == 1) { /* PPT case */ - tcp->ppt_len+=tcp->ppt_data-hd; - tcp->ppt_data = hd; - return (c - src); - } - - return (hd - src); - } - - for (bandno = 0; bandno < res->numbands; bandno++) { - opj_tcd_band_t *band = &res->bands[bandno]; - opj_tcd_precinct_t *prc = &band->precincts[precno]; - - if ((band->x1-band->x0 == 0)||(band->y1-band->y0 == 0)) continue; - - for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) { - int included, increment, n, segno; - opj_tcd_cblk_dec_t* cblk = &prc->cblks.dec[cblkno]; - /* if cblk not yet included before --> inclusion tagtree */ - if (!cblk->numsegs) { - included = tgt_decode(bio, prc->incltree, cblkno, layno + 1); - /* else one bit */ - } else { - included = bio_read(bio, 1); - } - /* if cblk not included */ - if (!included) { - cblk->numnewpasses = 0; - continue; - } - /* if cblk not yet included --> zero-bitplane tagtree */ - if (!cblk->numsegs) { - int i, numimsbs; - for (i = 0; !tgt_decode(bio, prc->imsbtree, cblkno, i); i++) { - ; - } - numimsbs = i - 1; - cblk->numbps = band->numbps - numimsbs; - cblk->numlenbits = 3; - } - /* number of coding passes */ - cblk->numnewpasses = t2_getnumpasses(bio); - increment = t2_getcommacode(bio); - /* length indicator increment */ - cblk->numlenbits += increment; - segno = 0; - if (!cblk->numsegs) { - t2_init_seg(cblk, segno, tcp->tccps[compno].cblksty, 1); - } else { - segno = cblk->numsegs - 1; - if (cblk->segs[segno].numpasses == cblk->segs[segno].maxpasses) { - ++segno; - t2_init_seg(cblk, segno, tcp->tccps[compno].cblksty, 0); - } - } - n = cblk->numnewpasses; - - do { - cblk->segs[segno].numnewpasses = int_min(cblk->segs[segno].maxpasses - cblk->segs[segno].numpasses, n); - cblk->segs[segno].newlen = bio_read(bio, cblk->numlenbits + int_floorlog2(cblk->segs[segno].numnewpasses)); - n -= cblk->segs[segno].numnewpasses; - if (n > 0) { - ++segno; - t2_init_seg(cblk, segno, tcp->tccps[compno].cblksty, 0); - } - } while (n > 0); - } - } - - if (bio_inalign(bio)) { - bio_destroy(bio); - return -999; - } - - hd += bio_numbytes(bio); - bio_destroy(bio); - - /* EPH markers */ - if (tcp->csty & J2K_CP_CSTY_EPH) { - if ((*hd) != 0xff || (*(hd + 1) != 0x92)) { - opj_event_msg(t2->cinfo, EVT_ERROR, "Expected EPH marker\n"); - return -999; - } else { - hd += 2; - } - } - - /* << INDEX */ - /* End of packet header position. Currently only represents the distance to start of packet - // Will be updated later by incrementing with packet start value*/ - if(pack_info) { - pack_info->end_ph_pos = (int)(hd - src); - } - /* INDEX >> */ - - if (cp->ppm==1) { - cp->ppm_len+=cp->ppm_data-hd; - cp->ppm_data = hd; - } else if (tcp->ppt == 1) { - tcp->ppt_len+=tcp->ppt_data-hd; - tcp->ppt_data = hd; - } else { - c=hd; - } - - for (bandno = 0; bandno < res->numbands; bandno++) { - opj_tcd_band_t *band = &res->bands[bandno]; - opj_tcd_precinct_t *prc = &band->precincts[precno]; - - if ((band->x1-band->x0 == 0)||(band->y1-band->y0 == 0)) continue; - - for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) { - opj_tcd_cblk_dec_t* cblk = &prc->cblks.dec[cblkno]; - opj_tcd_seg_t *seg = NULL; - if (!cblk->numnewpasses) - continue; - if (!cblk->numsegs) { - seg = &cblk->segs[0]; - 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) { - return -999; - } - -#ifdef USE_JPWL - /* we need here a j2k handle to verify if making a check to - the validity of cblocks parameters is selected from user (-W) */ - - /* let's check that we are not exceeding */ - if ((cblk->len + seg->newlen) > 8192) { - opj_event_msg(t2->cinfo, EVT_WARNING, - "JPWL: segment too long (%d) for codeblock %d (p=%d, b=%d, r=%d, c=%d)\n", - seg->newlen, cblkno, precno, bandno, resno, compno); - if (!JPWL_ASSUME) { - opj_event_msg(t2->cinfo, EVT_ERROR, "JPWL: giving up\n"); - return -999; - } - seg->newlen = 8192 - cblk->len; - opj_event_msg(t2->cinfo, EVT_WARNING, " - truncating segment to %d\n", seg->newlen); - break; - }; - -#endif /* USE_JPWL */ - - cblk->data = (unsigned char*) opj_realloc(cblk->data, (cblk->len + seg->newlen) * sizeof(unsigned char)); - memcpy(cblk->data + cblk->len, c, seg->newlen); - if (seg->numpasses == 0) { - seg->data = &cblk->data; - seg->dataindex = 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(opj_t2_t* t2,int tileno, opj_tcd_tile_t *tile, int maxlayers, unsigned char *dest, int len, opj_codestream_info_t *cstr_info,int tpnum, int tppos,int pino, J2K_T2_MODE t2_mode, int cur_totnum_tp){ - unsigned char *c = dest; - int e = 0; - int compno; - opj_pi_iterator_t *pi = NULL; - int poc; - opj_image_t *image = t2->image; - opj_cp_t *cp = t2->cp; - opj_tcp_t *tcp = &cp->tcps[tileno]; - int pocno = cp->cinema == CINEMA4K_24? 2: 1; - int maxcomp = cp->max_comp_size > 0 ? image->numcomps : 1; - - pi = pi_initialise_encode(image, cp, tileno, t2_mode); - if(!pi) { - /* TODO: throw an error */ - return -999; - } - - if(t2_mode == THRESH_CALC ){ /* Calculating threshold */ - for(compno = 0; compno < maxcomp; compno++ ){ - for(poc = 0; poc < pocno ; poc++){ - int comp_len = 0; - int tpnum = compno; - if (pi_create_encode(pi, cp,tileno,poc,tpnum,tppos,t2_mode,cur_totnum_tp)) { - opj_event_msg(t2->cinfo, EVT_ERROR, "Error initializing Packet Iterator\n"); - pi_destroy(pi, cp, tileno); - return -999; - } - while (pi_next(&pi[poc])) { - if (pi[poc].layno < maxlayers) { - e = t2_encode_packet(tile, &cp->tcps[tileno], &pi[poc], c, dest + len - c, cstr_info, tileno); - comp_len = comp_len + e; - if (e == -999) { - break; - } else { - c += e; - } - } - } - if (e == -999) break; - if (cp->max_comp_size){ - if (comp_len > cp->max_comp_size){ - e = -999; - break; - } - } - } - if (e == -999) break; - } - }else{ /* t2_mode == FINAL_PASS */ - pi_create_encode(pi, cp,tileno,pino,tpnum,tppos,t2_mode,cur_totnum_tp); - while (pi_next(&pi[pino])) { - if (pi[pino].layno < maxlayers) { - e = t2_encode_packet(tile, &cp->tcps[tileno], &pi[pino], c, dest + len - c, cstr_info, tileno); - if (e == -999) { - break; - } else { - c += e; - } - /* INDEX >> */ - if(cstr_info) { - if(cstr_info->index_write) { - opj_tile_info_t *info_TL = &cstr_info->tile[tileno]; - opj_packet_info_t *info_PK = &info_TL->packet[cstr_info->packno]; - if (!cstr_info->packno) { - info_PK->start_pos = info_TL->end_header + 1; - } else { - info_PK->start_pos = ((cp->tp_on | tcp->POC)&& info_PK->start_pos) ? info_PK->start_pos : info_TL->packet[cstr_info->packno - 1].end_pos + 1; - } - info_PK->end_pos = info_PK->start_pos + e - 1; - info_PK->end_ph_pos += info_PK->start_pos - 1; /* End of packet header which now only represents the distance - // to start of packet is incremented by value of start of packet*/ - } - - cstr_info->packno++; - } - /* << INDEX */ - tile->packno++; - } - } - } - - pi_destroy(pi, cp, tileno); - - if (e == -999) { - return e; - } - - return (c - dest); -} - -int t2_decode_packets(opj_t2_t *t2, unsigned char *src, int len, int tileno, opj_tcd_tile_t *tile, opj_codestream_info_t *cstr_info) { - unsigned char *c = src; - opj_pi_iterator_t *pi; - int pino, e = 0; - int n = 0, curtp = 0; - int tp_start_packno; - - opj_image_t *image = t2->image; - opj_cp_t *cp = t2->cp; - - /* create a packet iterator */ - pi = pi_create_decode(image, cp, tileno); - if(!pi) { - /* TODO: throw an error */ - return -999; - } - - tp_start_packno = 0; - - for (pino = 0; pino <= cp->tcps[tileno].numpocs; pino++) { - while (pi_next(&pi[pino])) { - if ((cp->layer==0) || (cp->layer>=((pi[pino].layno)+1))) { - opj_packet_info_t *pack_info; - if (cstr_info) - pack_info = &cstr_info->tile[tileno].packet[cstr_info->packno]; - else - pack_info = NULL; - e = t2_decode_packet(t2, c, src + len - c, tile, &cp->tcps[tileno], &pi[pino], pack_info); - } else { - e = 0; - } - if(e == -999) return -999; - /* progression in resolution */ - image->comps[pi[pino].compno].resno_decoded = - (e > 0) ? - int_max(pi[pino].resno, image->comps[pi[pino].compno].resno_decoded) - : image->comps[pi[pino].compno].resno_decoded; - n++; - - /* INDEX >> */ - if(cstr_info) { - opj_tile_info_t *info_TL = &cstr_info->tile[tileno]; - opj_packet_info_t *info_PK = &info_TL->packet[cstr_info->packno]; - if (!cstr_info->packno) { - info_PK->start_pos = info_TL->end_header + 1; - } else if (info_TL->packet[cstr_info->packno-1].end_pos >= (int)cstr_info->tile[tileno].tp[curtp].tp_end_pos){ /* New tile part*/ - info_TL->tp[curtp].tp_numpacks = cstr_info->packno - tp_start_packno; /* Number of packets in previous tile-part*/ - info_TL->tp[curtp].tp_start_pack = tp_start_packno; - tp_start_packno = cstr_info->packno; - curtp++; - info_PK->start_pos = cstr_info->tile[tileno].tp[curtp].tp_end_header+1; - } else { - info_PK->start_pos = (cp->tp_on && info_PK->start_pos) ? info_PK->start_pos : info_TL->packet[cstr_info->packno - 1].end_pos + 1; - } - info_PK->end_pos = info_PK->start_pos + e - 1; - info_PK->end_ph_pos += info_PK->start_pos - 1; /* End of packet header which now only represents the distance - // to start of packet is incremented by value of start of packet*/ - cstr_info->packno++; - } - /* << INDEX */ - - if (e == -999) { /* ADD */ - break; - } else { - c += e; - } - } - } - /* INDEX >> */ - if(cstr_info) { - cstr_info->tile[tileno].tp[curtp].tp_numpacks = cstr_info->packno - tp_start_packno; /* Number of packets in last tile-part*/ - cstr_info->tile[tileno].tp[curtp].tp_start_pack = tp_start_packno; - } - /* << INDEX */ - - /* don't forget to release pi */ - pi_destroy(pi, cp, tileno); - - if (e == -999) { - return e; - } - - return (c - src); -} - -/* ----------------------------------------------------------------------- */ - -opj_t2_t* t2_create(opj_common_ptr cinfo, opj_image_t *image, opj_cp_t *cp) { - /* create the tcd structure */ - opj_t2_t *t2 = (opj_t2_t*)opj_malloc(sizeof(opj_t2_t)); - if(!t2) return NULL; - t2->cinfo = cinfo; - t2->image = image; - t2->cp = cp; - - return t2; -} - -void t2_destroy(opj_t2_t *t2) { - if(t2) { - opj_free(t2); - } -} - - - - - diff --git a/openjpeg-dotnet/libopenjpeg/t2.h b/openjpeg-dotnet/libopenjpeg/t2.h deleted file mode 100644 index 2151ba67..00000000 --- a/openjpeg-dotnet/libopenjpeg/t2.h +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium - * Copyright (c) 2002-2007, Professor Benoit Macq - * Copyright (c) 2001-2003, David Janssens - * Copyright (c) 2002-2003, Yannick Verschueren - * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe - * Copyright (c) 2005, Herve Drolon, FreeImage Team - * 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 -/** -@file t2.h -@brief Implementation of a tier-2 coding (packetization of code-block data) (T2) - -*/ - -/** @defgroup T2 T2 - Implementation of a tier-2 coding */ -/*@{*/ - -/** -Tier-2 coding -*/ -typedef struct opj_t2 { - /** codec context */ - opj_common_ptr cinfo; - - /** Encoding: pointer to the src image. Decoding: pointer to the dst image. */ - opj_image_t *image; - /** pointer to the image coding parameters */ - opj_cp_t *cp; -} opj_t2_t; - -/** @name Exported functions */ -/*@{*/ -/* ----------------------------------------------------------------------- */ - -/** -Encode the packets of a tile to a destination buffer -@param t2 T2 handle -@param tileno number of the tile encoded -@param tile the tile for which to write the packets -@param maxlayers maximum number of layers -@param dest the destination buffer -@param len the length of the destination buffer -@param cstr_info Codestream information structure -@param tpnum Tile part number of the current tile -@param tppos The position of the tile part flag in the progression order -@param pino -@param t2_mode If == 0 In Threshold calculation ,If == 1 Final pass -@param cur_totnum_tp The total number of tile parts in the current tile -*/ -int t2_encode_packets(opj_t2_t* t2,int tileno, opj_tcd_tile_t *tile, int maxlayers, unsigned char *dest, int len, opj_codestream_info_t *cstr_info,int tpnum, int tppos,int pino,J2K_T2_MODE t2_mode,int cur_totnum_tp); -/** -Decode the packets of a tile from a source buffer -@param t2 T2 handle -@param src the source buffer -@param len length of the source buffer -@param tileno number that identifies the tile for which to decode the packets -@param tile tile for which to decode the packets -@param cstr_info Codestream information structure - */ -int t2_decode_packets(opj_t2_t *t2, unsigned char *src, int len, int tileno, opj_tcd_tile_t *tile, opj_codestream_info_t *cstr_info); - -/** -Create a T2 handle -@param cinfo Codec context info -@param image Source or destination image -@param cp Image coding parameters -@return Returns a new T2 handle if successful, returns NULL otherwise -*/ -opj_t2_t* t2_create(opj_common_ptr cinfo, opj_image_t *image, opj_cp_t *cp); -/** -Destroy a T2 handle -@param t2 T2 handle to destroy -*/ -void t2_destroy(opj_t2_t *t2); - -/* ----------------------------------------------------------------------- */ -/*@}*/ - -/*@}*/ - -#endif /* __T2_H */ diff --git a/openjpeg-dotnet/libopenjpeg/tcd.c b/openjpeg-dotnet/libopenjpeg/tcd.c deleted file mode 100644 index 18cdbc78..00000000 --- a/openjpeg-dotnet/libopenjpeg/tcd.c +++ /dev/null @@ -1,1524 +0,0 @@ -/* - * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium - * Copyright (c) 2002-2007, Professor Benoit Macq - * Copyright (c) 2001-2003, David Janssens - * Copyright (c) 2002-2003, Yannick Verschueren - * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe - * Copyright (c) 2005, Herve Drolon, FreeImage Team - * Copyright (c) 2006-2007, Parvatha Elangovan - * 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 "opj_includes.h" - -void tcd_dump(FILE *fd, opj_tcd_t *tcd, opj_tcd_image_t * img) { - int tileno, compno, resno, bandno, precno;/*, cblkno;*/ - - fprintf(fd, "image {\n"); - fprintf(fd, " tw=%d, th=%d x0=%d x1=%d y0=%d y1=%d\n", - img->tw, img->th, tcd->image->x0, tcd->image->x1, tcd->image->y0, tcd->image->y1); - - for (tileno = 0; tileno < img->th * img->tw; tileno++) { - opj_tcd_tile_t *tile = &tcd->tcd_image->tiles[tileno]; - fprintf(fd, " tile {\n"); - fprintf(fd, " x0=%d, y0=%d, x1=%d, y1=%d, numcomps=%d\n", - tile->x0, tile->y0, tile->x1, tile->y1, tile->numcomps); - for (compno = 0; compno < tile->numcomps; compno++) { - opj_tcd_tilecomp_t *tilec = &tile->comps[compno]; - fprintf(fd, " tilec {\n"); - fprintf(fd, - " x0=%d, y0=%d, x1=%d, y1=%d, numresolutions=%d\n", - tilec->x0, tilec->y0, tilec->x1, tilec->y1, tilec->numresolutions); - for (resno = 0; resno < tilec->numresolutions; resno++) { - opj_tcd_resolution_t *res = &tilec->resolutions[resno]; - fprintf(fd, "\n res {\n"); - fprintf(fd, - " 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; bandno < res->numbands; bandno++) { - opj_tcd_band_t *band = &res->bands[bandno]; - fprintf(fd, " band {\n"); - fprintf(fd, - " x0=%d, y0=%d, x1=%d, y1=%d, stepsize=%f, numbps=%d\n", - band->x0, band->y0, band->x1, band->y1, band->stepsize, band->numbps); - for (precno = 0; precno < res->pw * res->ph; precno++) { - opj_tcd_precinct_t *prec = &band->precincts[precno]; - fprintf(fd, " prec {\n"); - fprintf(fd, - " 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; cblkno < prec->cw * prec->ch; cblkno++) { - opj_tcd_cblk_t *cblk = &prec->cblks[cblkno]; - fprintf(fd, " cblk {\n"); - fprintf(fd, - " x0=%d, y0=%d, x1=%d, y1=%d\n", - cblk->x0, cblk->y0, cblk->x1, cblk->y1); - fprintf(fd, " }\n"); - } - */ - fprintf(fd, " }\n"); - } - fprintf(fd, " }\n"); - } - fprintf(fd, " }\n"); - } - fprintf(fd, " }\n"); - } - fprintf(fd, " }\n"); - } - fprintf(fd, "}\n"); -} - -/* ----------------------------------------------------------------------- */ - -/** -Create a new TCD handle -*/ -opj_tcd_t* tcd_create(opj_common_ptr cinfo) { - /* create the tcd structure */ - opj_tcd_t *tcd = (opj_tcd_t*)opj_malloc(sizeof(opj_tcd_t)); - if(!tcd) return NULL; - tcd->cinfo = cinfo; - tcd->tcd_image = (opj_tcd_image_t*)opj_malloc(sizeof(opj_tcd_image_t)); - if(!tcd->tcd_image) { - opj_free(tcd); - return NULL; - } - - return tcd; -} - -/** -Destroy a previously created TCD handle -*/ -void tcd_destroy(opj_tcd_t *tcd) { - if(tcd) { - opj_free(tcd->tcd_image); - opj_free(tcd); - } -} - -/* ----------------------------------------------------------------------- */ - -void tcd_malloc_encode(opj_tcd_t *tcd, opj_image_t * image, opj_cp_t * cp, int curtileno) { - int tileno, compno, resno, bandno, precno, cblkno; - - tcd->image = image; - tcd->cp = cp; - tcd->tcd_image->tw = cp->tw; - tcd->tcd_image->th = cp->th; - tcd->tcd_image->tiles = (opj_tcd_tile_t *) opj_malloc(sizeof(opj_tcd_tile_t)); - - for (tileno = 0; tileno < 1; tileno++) { - opj_tcp_t *tcp = &cp->tcps[curtileno]; - int j; - - /* cfr p59 ISO/IEC FDIS15444-1 : 2000 (18 august 2000) */ - int p = curtileno % cp->tw; /* si numerotation matricielle .. */ - int q = curtileno / cp->tw; /* .. coordonnees de la tile (q,p) q pour ligne et p pour colonne */ - - /* opj_tcd_tile_t *tile=&tcd->tcd_image->tiles[tileno]; */ - opj_tcd_tile_t *tile = tcd->tcd_image->tiles; - - /* 4 borders of the tile rescale on the image if necessary */ - tile->x0 = int_max(cp->tx0 + p * cp->tdx, image->x0); - tile->y0 = int_max(cp->ty0 + q * cp->tdy, image->y0); - tile->x1 = int_min(cp->tx0 + (p + 1) * cp->tdx, image->x1); - tile->y1 = int_min(cp->ty0 + (q + 1) * cp->tdy, image->y1); - tile->numcomps = image->numcomps; - /* tile->PPT=image->PPT; */ - - /* Modification of the RATE >> */ - for (j = 0; j < tcp->numlayers; j++) { - tcp->rates[j] = tcp->rates[j] ? - cp->tp_on ? - (((float) (tile->numcomps - * (tile->x1 - tile->x0) - * (tile->y1 - tile->y0) - * image->comps[0].prec)) - /(tcp->rates[j] * 8 * image->comps[0].dx * image->comps[0].dy)) - (((tcd->cur_totnum_tp - 1) * 14 )/ tcp->numlayers) - : - ((float) (tile->numcomps - * (tile->x1 - tile->x0) - * (tile->y1 - tile->y0) - * image->comps[0].prec))/ - (tcp->rates[j] * 8 * image->comps[0].dx * image->comps[0].dy) - : 0; - - if (tcp->rates[j]) { - if (j && tcp->rates[j] < tcp->rates[j - 1] + 10) { - tcp->rates[j] = tcp->rates[j - 1] + 20; - } else { - if (!j && tcp->rates[j] < 30) - tcp->rates[j] = 30; - } - - if(j == (tcp->numlayers-1)){ - tcp->rates[j] = tcp->rates[j]- 2; - } - } - } - /* << Modification of the RATE */ - - tile->comps = (opj_tcd_tilecomp_t *) opj_malloc(image->numcomps * sizeof(opj_tcd_tilecomp_t)); - for (compno = 0; compno < tile->numcomps; compno++) { - opj_tccp_t *tccp = &tcp->tccps[compno]; - - opj_tcd_tilecomp_t *tilec = &tile->comps[compno]; - - /* border of each tile component (global) */ - tilec->x0 = int_ceildiv(tile->x0, image->comps[compno].dx); - tilec->y0 = int_ceildiv(tile->y0, image->comps[compno].dy); - tilec->x1 = int_ceildiv(tile->x1, image->comps[compno].dx); - tilec->y1 = int_ceildiv(tile->y1, image->comps[compno].dy); - - tilec->data = (int *) opj_aligned_malloc((tilec->x1 - tilec->x0) * (tilec->y1 - tilec->y0) * sizeof(int)); - tilec->numresolutions = tccp->numresolutions; - - tilec->resolutions = (opj_tcd_resolution_t *) opj_malloc(tilec->numresolutions * sizeof(opj_tcd_resolution_t)); - - for (resno = 0; resno < tilec->numresolutions; 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; - - opj_tcd_resolution_t *res = &tilec->resolutions[resno]; - - /* border for each resolution level (global) */ - 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; - /* p. 35, table A-23, ISO/IEC FDIS154444-1 : 2000 (18 august 2000) */ - if (tccp->csty & J2K_CCP_CSTY_PRT) { - pdx = tccp->prcw[resno]; - pdy = tccp->prch[resno]; - } else { - pdx = 15; - pdy = 15; - } - /* p. 64, B.6, ISO/IEC FDIS15444-1 : 2000 (18 august 2000) */ - tlprcxstart = int_floordivpow2(res->x0, pdx) << pdx; - tlprcystart = int_floordivpow2(res->y0, pdy) << pdy; - - brprcxend = int_ceildivpow2(res->x1, pdx) << pdx; - brprcyend = int_ceildivpow2(res->y1, pdy) << pdy; - - res->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; bandno < res->numbands; bandno++) { - int x0b, y0b, i; - int gain, numbps; - opj_stepsize_t *ss = NULL; - - opj_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 border (global) */ - 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 border (global) */ - band->x0 = int_ceildivpow2(tilec->x0 - (1 << levelno) * x0b, levelno + 1); - band->y0 = int_ceildivpow2(tilec->y0 - (1 << levelno) * y0b, levelno + 1); - band->x1 = int_ceildivpow2(tilec->x1 - (1 << levelno) * x0b, levelno + 1); - band->y1 = int_ceildivpow2(tilec->y1 - (1 << levelno) * y0b, levelno + 1); - } - - ss = &tccp->stepsizes[resno == 0 ? 0 : 3 * (resno - 1) + bandno + 1]; - gain = tccp->qmfbid == 0 ? dwt_getgain_real(band->bandno) : dwt_getgain(band->bandno); - numbps = image->comps[compno].prec + gain; - - band->stepsize = (float)((1.0 + ss->mant / 2048.0) * pow(2.0, numbps - ss->expn)); - band->numbps = ss->expn + tccp->numgbits - 1; /* WHY -1 ? */ - - band->precincts = (opj_tcd_precinct_t *) opj_malloc(3 * res->pw * res->ph * sizeof(opj_tcd_precinct_t)); - - for (i = 0; i < res->pw * res->ph * 3; i++) { - band->precincts[i].imsbtree = NULL; - band->precincts[i].incltree = NULL; - band->precincts[i].cblks.enc = NULL; - } - - for (precno = 0; precno < res->pw * res->ph; precno++) { - int tlcblkxstart, tlcblkystart, brcblkxend, brcblkyend; - - int cbgxstart = tlcbgxstart + (precno % res->pw) * (1 << cbgwidthexpn); - int cbgystart = tlcbgystart + (precno / res->pw) * (1 << cbgheightexpn); - int cbgxend = cbgxstart + (1 << cbgwidthexpn); - int cbgyend = cbgystart + (1 << cbgheightexpn); - - opj_tcd_precinct_t *prc = &band->precincts[precno]; - - /* precinct size (global) */ - 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) << cblkwidthexpn; - tlcblkystart = int_floordivpow2(prc->y0, cblkheightexpn) << cblkheightexpn; - brcblkxend = int_ceildivpow2(prc->x1, cblkwidthexpn) << cblkwidthexpn; - brcblkyend = int_ceildivpow2(prc->y1, cblkheightexpn) << cblkheightexpn; - prc->cw = (brcblkxend - tlcblkxstart) >> cblkwidthexpn; - prc->ch = (brcblkyend - tlcblkystart) >> cblkheightexpn; - - prc->cblks.enc = (opj_tcd_cblk_enc_t*) opj_calloc((prc->cw * prc->ch), sizeof(opj_tcd_cblk_enc_t)); - prc->incltree = tgt_create(prc->cw, prc->ch); - prc->imsbtree = tgt_create(prc->cw, prc->ch); - - for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) { - int cblkxstart = tlcblkxstart + (cblkno % prc->cw) * (1 << cblkwidthexpn); - int cblkystart = tlcblkystart + (cblkno / prc->cw) * (1 << cblkheightexpn); - int cblkxend = cblkxstart + (1 << cblkwidthexpn); - int cblkyend = cblkystart + (1 << cblkheightexpn); - - opj_tcd_cblk_enc_t* cblk = &prc->cblks.enc[cblkno]; - - /* code-block size (global) */ - 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); - cblk->data = (unsigned char*) opj_calloc(8192+2, sizeof(unsigned char)); - /* FIXME: mqc_init_enc and mqc_byteout underrun the buffer if we don't do this. Why? */ - cblk->data += 2; - cblk->layers = (opj_tcd_layer_t*) opj_calloc(100, sizeof(opj_tcd_layer_t)); - cblk->passes = (opj_tcd_pass_t*) opj_calloc(100, sizeof(opj_tcd_pass_t)); - } - } - } - } - } - } - - /* tcd_dump(stdout, tcd, &tcd->tcd_image); */ -} - -void tcd_free_encode(opj_tcd_t *tcd) { - int tileno, compno, resno, bandno, precno, cblkno; - - for (tileno = 0; tileno < 1; tileno++) { - opj_tcd_tile_t *tile = tcd->tcd_image->tiles; - - for (compno = 0; compno < tile->numcomps; compno++) { - opj_tcd_tilecomp_t *tilec = &tile->comps[compno]; - - for (resno = 0; resno < tilec->numresolutions; resno++) { - opj_tcd_resolution_t *res = &tilec->resolutions[resno]; - - for (bandno = 0; bandno < res->numbands; bandno++) { - opj_tcd_band_t *band = &res->bands[bandno]; - - for (precno = 0; precno < res->pw * res->ph; precno++) { - opj_tcd_precinct_t *prc = &band->precincts[precno]; - - if (prc->incltree != NULL) { - tgt_destroy(prc->incltree); - prc->incltree = NULL; - } - if (prc->imsbtree != NULL) { - tgt_destroy(prc->imsbtree); - prc->imsbtree = NULL; - } - for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) { - opj_free(prc->cblks.enc[cblkno].data - 2); - opj_free(prc->cblks.enc[cblkno].layers); - opj_free(prc->cblks.enc[cblkno].passes); - } - opj_free(prc->cblks.enc); - } /* for (precno */ - opj_free(band->precincts); - band->precincts = NULL; - } /* for (bandno */ - } /* for (resno */ - opj_free(tilec->resolutions); - tilec->resolutions = NULL; - } /* for (compno */ - opj_free(tile->comps); - tile->comps = NULL; - } /* for (tileno */ - opj_free(tcd->tcd_image->tiles); - tcd->tcd_image->tiles = NULL; -} - -void tcd_init_encode(opj_tcd_t *tcd, opj_image_t * image, opj_cp_t * cp, int curtileno) { - int tileno, compno, resno, bandno, precno, cblkno; - - for (tileno = 0; tileno < 1; tileno++) { - opj_tcp_t *tcp = &cp->tcps[curtileno]; - int j; - /* cfr p59 ISO/IEC FDIS15444-1 : 2000 (18 august 2000) */ - int p = curtileno % cp->tw; - int q = curtileno / cp->tw; - - opj_tcd_tile_t *tile = tcd->tcd_image->tiles; - - /* 4 borders of the tile rescale on the image if necessary */ - tile->x0 = int_max(cp->tx0 + p * cp->tdx, image->x0); - tile->y0 = int_max(cp->ty0 + q * cp->tdy, image->y0); - tile->x1 = int_min(cp->tx0 + (p + 1) * cp->tdx, image->x1); - tile->y1 = int_min(cp->ty0 + (q + 1) * cp->tdy, image->y1); - - tile->numcomps = image->numcomps; - /* tile->PPT=image->PPT; */ - - /* Modification of the RATE >> */ - for (j = 0; j < tcp->numlayers; j++) { - tcp->rates[j] = tcp->rates[j] ? - cp->tp_on ? - (((float) (tile->numcomps - * (tile->x1 - tile->x0) - * (tile->y1 - tile->y0) - * image->comps[0].prec)) - /(tcp->rates[j] * 8 * image->comps[0].dx * image->comps[0].dy)) - (((tcd->cur_totnum_tp - 1) * 14 )/ tcp->numlayers) - : - ((float) (tile->numcomps - * (tile->x1 - tile->x0) - * (tile->y1 - tile->y0) - * image->comps[0].prec))/ - (tcp->rates[j] * 8 * image->comps[0].dx * image->comps[0].dy) - : 0; - - if (tcp->rates[j]) { - if (j && tcp->rates[j] < tcp->rates[j - 1] + 10) { - tcp->rates[j] = tcp->rates[j - 1] + 20; - } else { - if (!j && tcp->rates[j] < 30) - tcp->rates[j] = 30; - } - } - } - /* << Modification of the RATE */ - - /* tile->comps=(opj_tcd_tilecomp_t*)opj_realloc(tile->comps,image->numcomps*sizeof(opj_tcd_tilecomp_t)); */ - for (compno = 0; compno < tile->numcomps; compno++) { - opj_tccp_t *tccp = &tcp->tccps[compno]; - - opj_tcd_tilecomp_t *tilec = &tile->comps[compno]; - - /* border of each tile component (global) */ - tilec->x0 = int_ceildiv(tile->x0, image->comps[compno].dx); - tilec->y0 = int_ceildiv(tile->y0, image->comps[compno].dy); - tilec->x1 = int_ceildiv(tile->x1, image->comps[compno].dx); - tilec->y1 = int_ceildiv(tile->y1, image->comps[compno].dy); - - tilec->data = (int *) opj_aligned_malloc((tilec->x1 - tilec->x0) * (tilec->y1 - tilec->y0) * sizeof(int)); - tilec->numresolutions = tccp->numresolutions; - /* tilec->resolutions=(opj_tcd_resolution_t*)opj_realloc(tilec->resolutions,tilec->numresolutions*sizeof(opj_tcd_resolution_t)); */ - for (resno = 0; resno < tilec->numresolutions; 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; - - opj_tcd_resolution_t *res = &tilec->resolutions[resno]; - - /* border for each resolution level (global) */ - 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; - - /* p. 35, table A-23, ISO/IEC FDIS154444-1 : 2000 (18 august 2000) */ - if (tccp->csty & J2K_CCP_CSTY_PRT) { - pdx = tccp->prcw[resno]; - pdy = tccp->prch[resno]; - } else { - pdx = 15; - pdy = 15; - } - /* p. 64, B.6, ISO/IEC FDIS15444-1 : 2000 (18 august 2000) */ - tlprcxstart = int_floordivpow2(res->x0, pdx) << pdx; - tlprcystart = int_floordivpow2(res->y0, pdy) << pdy; - brprcxend = int_ceildivpow2(res->x1, pdx) << pdx; - brprcyend = int_ceildivpow2(res->y1, pdy) << pdy; - - res->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; bandno < res->numbands; bandno++) { - int x0b, y0b; - int gain, numbps; - opj_stepsize_t *ss = NULL; - - opj_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 border */ - 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 << levelno) * x0b, levelno + 1); - band->y0 = int_ceildivpow2(tilec->y0 - (1 << levelno) * y0b, levelno + 1); - band->x1 = int_ceildivpow2(tilec->x1 - (1 << levelno) * x0b, levelno + 1); - band->y1 = int_ceildivpow2(tilec->y1 - (1 << levelno) * y0b, levelno + 1); - } - - ss = &tccp->stepsizes[resno == 0 ? 0 : 3 * (resno - 1) + bandno + 1]; - gain = tccp->qmfbid == 0 ? dwt_getgain_real(band->bandno) : dwt_getgain(band->bandno); - numbps = image->comps[compno].prec + gain; - band->stepsize = (float)((1.0 + ss->mant / 2048.0) * pow(2.0, numbps - ss->expn)); - band->numbps = ss->expn + tccp->numgbits - 1; /* WHY -1 ? */ - - for (precno = 0; precno < res->pw * res->ph; precno++) { - int tlcblkxstart, tlcblkystart, brcblkxend, brcblkyend; - - int cbgxstart = tlcbgxstart + (precno % res->pw) * (1 << cbgwidthexpn); - int cbgystart = tlcbgystart + (precno / res->pw) * (1 << cbgheightexpn); - int cbgxend = cbgxstart + (1 << cbgwidthexpn); - int cbgyend = cbgystart + (1 << cbgheightexpn); - - opj_tcd_precinct_t *prc = &band->precincts[precno]; - - /* precinct size (global) */ - 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) << cblkwidthexpn; - tlcblkystart = int_floordivpow2(prc->y0, cblkheightexpn) << cblkheightexpn; - brcblkxend = int_ceildivpow2(prc->x1, cblkwidthexpn) << cblkwidthexpn; - brcblkyend = int_ceildivpow2(prc->y1, cblkheightexpn) << cblkheightexpn; - prc->cw = (brcblkxend - tlcblkxstart) >> cblkwidthexpn; - prc->ch = (brcblkyend - tlcblkystart) >> cblkheightexpn; - - opj_free(prc->cblks.enc); - prc->cblks.enc = (opj_tcd_cblk_enc_t*) opj_calloc(prc->cw * prc->ch, sizeof(opj_tcd_cblk_enc_t)); - - if (prc->incltree != NULL) { - tgt_destroy(prc->incltree); - } - if (prc->imsbtree != NULL) { - tgt_destroy(prc->imsbtree); - } - - prc->incltree = tgt_create(prc->cw, prc->ch); - prc->imsbtree = tgt_create(prc->cw, prc->ch); - - for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) { - int cblkxstart = tlcblkxstart + (cblkno % prc->cw) * (1 << cblkwidthexpn); - int cblkystart = tlcblkystart + (cblkno / prc->cw) * (1 << cblkheightexpn); - int cblkxend = cblkxstart + (1 << cblkwidthexpn); - int cblkyend = cblkystart + (1 << cblkheightexpn); - - opj_tcd_cblk_enc_t* cblk = &prc->cblks.enc[cblkno]; - - /* code-block size (global) */ - 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); - cblk->data = (unsigned char*) opj_calloc(8192+2, sizeof(unsigned char)); - /* FIXME: mqc_init_enc and mqc_byteout underrun the buffer if we don't do this. Why? */ - cblk->data += 2; - cblk->layers = (opj_tcd_layer_t*) opj_calloc(100, sizeof(opj_tcd_layer_t)); - cblk->passes = (opj_tcd_pass_t*) opj_calloc(100, sizeof(opj_tcd_pass_t)); - } - } /* precno */ - } /* bandno */ - } /* resno */ - } /* compno */ - } /* tileno */ - - /* tcd_dump(stdout, tcd, &tcd->tcd_image); */ -} - -void tcd_malloc_decode(opj_tcd_t *tcd, opj_image_t * image, opj_cp_t * cp) { - int i, j, tileno, p, q; - unsigned int x0 = 0, y0 = 0, x1 = 0, y1 = 0, w, h; - - tcd->image = image; - tcd->tcd_image->tw = cp->tw; - tcd->tcd_image->th = cp->th; - tcd->tcd_image->tiles = (opj_tcd_tile_t *) opj_malloc(cp->tw * cp->th * sizeof(opj_tcd_tile_t)); - - /* - Allocate place to store the decoded data = final image - Place limited by the tile really present in the codestream - */ - - for (j = 0; j < cp->tileno_size; j++) { - opj_tcd_tile_t *tile; - - tileno = cp->tileno[j]; - tile = &(tcd->tcd_image->tiles[cp->tileno[tileno]]); - tile->numcomps = image->numcomps; - tile->comps = (opj_tcd_tilecomp_t*) opj_calloc(image->numcomps, sizeof(opj_tcd_tilecomp_t)); - } - - for (i = 0; i < image->numcomps; i++) { - for (j = 0; j < cp->tileno_size; j++) { - opj_tcd_tile_t *tile; - opj_tcd_tilecomp_t *tilec; - - /* cfr p59 ISO/IEC FDIS15444-1 : 2000 (18 august 2000) */ - - tileno = cp->tileno[j]; - - tile = &(tcd->tcd_image->tiles[cp->tileno[tileno]]); - tilec = &tile->comps[i]; - - p = tileno % cp->tw; /* si numerotation matricielle .. */ - q = tileno / cp->tw; /* .. coordonnees de la tile (q,p) q pour ligne et p pour colonne */ - - /* 4 borders of the tile rescale on the image if necessary */ - tile->x0 = int_max(cp->tx0 + p * cp->tdx, image->x0); - tile->y0 = int_max(cp->ty0 + q * cp->tdy, image->y0); - tile->x1 = int_min(cp->tx0 + (p + 1) * cp->tdx, image->x1); - tile->y1 = int_min(cp->ty0 + (q + 1) * cp->tdy, image->y1); - - tilec->x0 = int_ceildiv(tile->x0, image->comps[i].dx); - tilec->y0 = int_ceildiv(tile->y0, image->comps[i].dy); - tilec->x1 = int_ceildiv(tile->x1, image->comps[i].dx); - tilec->y1 = int_ceildiv(tile->y1, image->comps[i].dy); - - x0 = j == 0 ? tilec->x0 : int_min(x0, (unsigned int) tilec->x0); - y0 = j == 0 ? tilec->y0 : int_min(y0, (unsigned int) tilec->y0); - x1 = j == 0 ? tilec->x1 : int_max(x1, (unsigned int) tilec->x1); - y1 = j == 0 ? tilec->y1 : int_max(y1, (unsigned int) tilec->y1); - } - - w = int_ceildivpow2(x1 - x0, image->comps[i].factor); - h = int_ceildivpow2(y1 - y0, image->comps[i].factor); - - image->comps[i].w = w; - image->comps[i].h = h; - image->comps[i].x0 = x0; - image->comps[i].y0 = y0; - } -} - -void tcd_malloc_decode_tile(opj_tcd_t *tcd, opj_image_t * image, opj_cp_t * cp, int tileno, opj_codestream_info_t *cstr_info) { - int compno, resno, bandno, precno, cblkno; - opj_tcp_t *tcp; - opj_tcd_tile_t *tile; - - OPJ_ARG_NOT_USED(cstr_info); - - tcd->cp = cp; - - tcp = &(cp->tcps[cp->tileno[tileno]]); - tile = &(tcd->tcd_image->tiles[cp->tileno[tileno]]); - - tileno = cp->tileno[tileno]; - - for (compno = 0; compno < tile->numcomps; compno++) { - opj_tccp_t *tccp = &tcp->tccps[compno]; - opj_tcd_tilecomp_t *tilec = &tile->comps[compno]; - - /* border of each tile component (global) */ - tilec->x0 = int_ceildiv(tile->x0, image->comps[compno].dx); - tilec->y0 = int_ceildiv(tile->y0, image->comps[compno].dy); - tilec->x1 = int_ceildiv(tile->x1, image->comps[compno].dx); - tilec->y1 = int_ceildiv(tile->y1, image->comps[compno].dy); - - tilec->numresolutions = tccp->numresolutions; - tilec->resolutions = (opj_tcd_resolution_t *) opj_malloc(tilec->numresolutions * sizeof(opj_tcd_resolution_t)); - - for (resno = 0; resno < tilec->numresolutions; 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; - - opj_tcd_resolution_t *res = &tilec->resolutions[resno]; - - /* border for each resolution level (global) */ - 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; - - /* p. 35, table A-23, ISO/IEC FDIS154444-1 : 2000 (18 august 2000) */ - if (tccp->csty & J2K_CCP_CSTY_PRT) { - pdx = tccp->prcw[resno]; - pdy = tccp->prch[resno]; - } else { - pdx = 15; - pdy = 15; - } - - /* p. 64, B.6, ISO/IEC FDIS15444-1 : 2000 (18 august 2000) */ - tlprcxstart = int_floordivpow2(res->x0, pdx) << pdx; - tlprcystart = int_floordivpow2(res->y0, pdy) << pdy; - brprcxend = int_ceildivpow2(res->x1, pdx) << pdx; - brprcyend = int_ceildivpow2(res->y1, pdy) << pdy; - - res->pw = (res->x0 == res->x1) ? 0 : ((brprcxend - tlprcxstart) >> pdx); - res->ph = (res->y0 == res->y1) ? 0 : ((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; bandno < res->numbands; bandno++) { - int x0b, y0b; - int gain, numbps; - opj_stepsize_t *ss = NULL; - - opj_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 border (global) */ - 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 border (global) */ - band->x0 = int_ceildivpow2(tilec->x0 - (1 << levelno) * x0b, levelno + 1); - band->y0 = int_ceildivpow2(tilec->y0 - (1 << levelno) * y0b, levelno + 1); - band->x1 = int_ceildivpow2(tilec->x1 - (1 << levelno) * x0b, levelno + 1); - band->y1 = int_ceildivpow2(tilec->y1 - (1 << levelno) * y0b, levelno + 1); - } - - ss = &tccp->stepsizes[resno == 0 ? 0 : 3 * (resno - 1) + bandno + 1]; - gain = tccp->qmfbid == 0 ? dwt_getgain_real(band->bandno) : dwt_getgain(band->bandno); - numbps = image->comps[compno].prec + gain; - band->stepsize = (float)(((1.0 + ss->mant / 2048.0) * pow(2.0, numbps - ss->expn)) * 0.5); - band->numbps = ss->expn + tccp->numgbits - 1; /* WHY -1 ? */ - - band->precincts = (opj_tcd_precinct_t *) opj_malloc(res->pw * res->ph * sizeof(opj_tcd_precinct_t)); - - for (precno = 0; precno < res->pw * res->ph; precno++) { - int tlcblkxstart, tlcblkystart, brcblkxend, brcblkyend; - int cbgxstart = tlcbgxstart + (precno % res->pw) * (1 << cbgwidthexpn); - int cbgystart = tlcbgystart + (precno / res->pw) * (1 << cbgheightexpn); - int cbgxend = cbgxstart + (1 << cbgwidthexpn); - int cbgyend = cbgystart + (1 << cbgheightexpn); - - opj_tcd_precinct_t *prc = &band->precincts[precno]; - /* precinct size (global) */ - 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) << cblkwidthexpn; - tlcblkystart = int_floordivpow2(prc->y0, cblkheightexpn) << cblkheightexpn; - brcblkxend = int_ceildivpow2(prc->x1, cblkwidthexpn) << cblkwidthexpn; - brcblkyend = int_ceildivpow2(prc->y1, cblkheightexpn) << cblkheightexpn; - prc->cw = (brcblkxend - tlcblkxstart) >> cblkwidthexpn; - prc->ch = (brcblkyend - tlcblkystart) >> cblkheightexpn; - - prc->cblks.dec = (opj_tcd_cblk_dec_t*) opj_malloc(prc->cw * prc->ch * sizeof(opj_tcd_cblk_dec_t)); - - prc->incltree = tgt_create(prc->cw, prc->ch); - prc->imsbtree = tgt_create(prc->cw, prc->ch); - - for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) { - int cblkxstart = tlcblkxstart + (cblkno % prc->cw) * (1 << cblkwidthexpn); - int cblkystart = tlcblkystart + (cblkno / prc->cw) * (1 << cblkheightexpn); - int cblkxend = cblkxstart + (1 << cblkwidthexpn); - int cblkyend = cblkystart + (1 << cblkheightexpn); - - opj_tcd_cblk_dec_t* cblk = &prc->cblks.dec[cblkno]; - cblk->data = NULL; - cblk->segs = NULL; - /* code-block size (global) */ - 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); - cblk->numsegs = 0; - } - } /* precno */ - } /* bandno */ - } /* resno */ - } /* compno */ - /* tcd_dump(stdout, tcd, &tcd->tcd_image); */ -} - -void tcd_makelayer_fixed(opj_tcd_t *tcd, int layno, int final) { - int compno, resno, bandno, precno, cblkno; - int value; /*, matrice[tcd_tcp->numlayers][tcd_tile->comps[0].numresolutions][3]; */ - int matrice[10][10][3]; - int i, j, k; - - opj_cp_t *cp = tcd->cp; - opj_tcd_tile_t *tcd_tile = tcd->tcd_tile; - opj_tcp_t *tcd_tcp = tcd->tcp; - - /*matrice=(int*)opj_malloc(tcd_tcp->numlayers*tcd_tile->comps[0].numresolutions*3*sizeof(int)); */ - - for (compno = 0; compno < tcd_tile->numcomps; compno++) { - opj_tcd_tilecomp_t *tilec = &tcd_tile->comps[compno]; - for (i = 0; i < tcd_tcp->numlayers; i++) { - for (j = 0; j < tilec->numresolutions; j++) { - for (k = 0; k < 3; k++) { - matrice[i][j][k] = - (int) (cp->matrice[i * tilec->numresolutions * 3 + j * 3 + k] - * (float) (tcd->image->comps[compno].prec / 16.0)); - } - } - } - - for (resno = 0; resno < tilec->numresolutions; resno++) { - opj_tcd_resolution_t *res = &tilec->resolutions[resno]; - for (bandno = 0; bandno < res->numbands; bandno++) { - opj_tcd_band_t *band = &res->bands[bandno]; - for (precno = 0; precno < res->pw * res->ph; precno++) { - opj_tcd_precinct_t *prc = &band->precincts[precno]; - for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) { - opj_tcd_cblk_enc_t *cblk = &prc->cblks.enc[cblkno]; - opj_tcd_layer_t *layer = &cblk->layers[layno]; - int n; - int imsb = tcd->image->comps[compno].prec - cblk->numbps; /* number of bit-plan equal to zero */ - /* Correction of the matrix of coefficient to include the IMSB information */ - if (layno == 0) { - value = matrice[layno][resno][bandno]; - if (imsb >= value) { - value = 0; - } else { - value -= imsb; - } - } else { - value = matrice[layno][resno][bandno] - matrice[layno - 1][resno][bandno]; - if (imsb >= matrice[layno - 1][resno][bandno]) { - value -= (imsb - matrice[layno - 1][resno][bandno]); - if (value < 0) { - value = 0; - } - } - } - - if (layno == 0) { - cblk->numpassesinlayers = 0; - } - - n = cblk->numpassesinlayers; - if (cblk->numpassesinlayers == 0) { - if (value != 0) { - n = 3 * value - 2 + cblk->numpassesinlayers; - } else { - n = cblk->numpassesinlayers; - } - } else { - n = 3 * value + cblk->numpassesinlayers; - } - - 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_fixed(opj_tcd_t *tcd) { - int layno; - for (layno = 0; layno < tcd->tcp->numlayers; layno++) { - tcd_makelayer_fixed(tcd, layno, 1); - } -} - -void tcd_makelayer(opj_tcd_t *tcd, int layno, double thresh, int final) { - int compno, resno, bandno, precno, cblkno, passno; - - opj_tcd_tile_t *tcd_tile = tcd->tcd_tile; - - tcd_tile->distolayer[layno] = 0; /* fixed_quality */ - - for (compno = 0; compno < tcd_tile->numcomps; compno++) { - opj_tcd_tilecomp_t *tilec = &tcd_tile->comps[compno]; - for (resno = 0; resno < tilec->numresolutions; resno++) { - opj_tcd_resolution_t *res = &tilec->resolutions[resno]; - for (bandno = 0; bandno < res->numbands; bandno++) { - opj_tcd_band_t *band = &res->bands[bandno]; - for (precno = 0; precno < res->pw * res->ph; precno++) { - opj_tcd_precinct_t *prc = &band->precincts[precno]; - for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) { - opj_tcd_cblk_enc_t *cblk = &prc->cblks.enc[cblkno]; - opj_tcd_layer_t *layer = &cblk->layers[layno]; - - int n; - if (layno == 0) { - cblk->numpassesinlayers = 0; - } - n = cblk->numpassesinlayers; - for (passno = cblk->numpassesinlayers; passno < cblk->totalpasses; passno++) { - int dr; - double dd; - opj_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) { - if (dd != 0) - n = passno + 1; - continue; - } - if (dd / dr >= thresh) - n = passno + 1; - } - layer->numpasses = n - cblk->numpassesinlayers; - - if (!layer->numpasses) { - layer->disto = 0; - continue; - } - if (cblk->numpassesinlayers == 0) { - layer->len = cblk->passes[n - 1].rate; - layer->data = cblk->data; - layer->disto = cblk->passes[n - 1].distortiondec; - } else { - layer->len = cblk->passes[n - 1].rate - cblk->passes[cblk->numpassesinlayers - 1].rate; - layer->data = cblk->data + cblk->passes[cblk->numpassesinlayers - 1].rate; - layer->disto = cblk->passes[n - 1].distortiondec - cblk->passes[cblk->numpassesinlayers - 1].distortiondec; - } - - tcd_tile->distolayer[layno] += layer->disto; /* fixed_quality */ - - if (final) - cblk->numpassesinlayers = n; - } - } - } - } - } -} - -opj_bool tcd_rateallocate(opj_tcd_t *tcd, unsigned char *dest, int len, opj_codestream_info_t *cstr_info) { - int compno, resno, bandno, precno, cblkno, passno, layno; - double min, max; - double cumdisto[100]; /* fixed_quality */ - const double K = 1; /* 1.1; fixed_quality */ - double maxSE = 0; - - opj_cp_t *cp = tcd->cp; - opj_tcd_tile_t *tcd_tile = tcd->tcd_tile; - opj_tcp_t *tcd_tcp = tcd->tcp; - - min = DBL_MAX; - max = 0; - - tcd_tile->numpix = 0; /* fixed_quality */ - - for (compno = 0; compno < tcd_tile->numcomps; compno++) { - opj_tcd_tilecomp_t *tilec = &tcd_tile->comps[compno]; - tilec->numpix = 0; - - for (resno = 0; resno < tilec->numresolutions; resno++) { - opj_tcd_resolution_t *res = &tilec->resolutions[resno]; - - for (bandno = 0; bandno < res->numbands; bandno++) { - opj_tcd_band_t *band = &res->bands[bandno]; - - for (precno = 0; precno < res->pw * res->ph; precno++) { - opj_tcd_precinct_t *prc = &band->precincts[precno]; - - for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) { - opj_tcd_cblk_enc_t *cblk = &prc->cblks.enc[cblkno]; - - for (passno = 0; passno < cblk->totalpasses; passno++) { - opj_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 (rdslope < min) { - min = rdslope; - } - if (rdslope > max) { - max = rdslope; - } - } /* passno */ - - /* fixed_quality */ - tcd_tile->numpix += ((cblk->x1 - cblk->x0) * (cblk->y1 - cblk->y0)); - tilec->numpix += ((cblk->x1 - cblk->x0) * (cblk->y1 - cblk->y0)); - } /* cbklno */ - } /* precno */ - } /* bandno */ - } /* resno */ - - maxSE += (((double)(1 << tcd->image->comps[compno].prec) - 1.0) - * ((double)(1 << tcd->image->comps[compno].prec) -1.0)) - * ((double)(tilec->numpix)); - } /* compno */ - - /* index file */ - if(cstr_info) { - opj_tile_info_t *tile_info = &cstr_info->tile[tcd->tcd_tileno]; - tile_info->numpix = tcd_tile->numpix; - tile_info->distotile = tcd_tile->distotile; - tile_info->thresh = (double *) opj_malloc(tcd_tcp->numlayers * sizeof(double)); - } - - for (layno = 0; layno < tcd_tcp->numlayers; layno++) { - double lo = min; - double hi = max; - int success = 0; - int maxlen = tcd_tcp->rates[layno] ? int_min(((int) ceil(tcd_tcp->rates[layno])), len) : len; - double goodthresh = 0; - double stable_thresh = 0; - int i; - double distotarget; /* fixed_quality */ - - /* fixed_quality */ - distotarget = tcd_tile->distotile - ((K * maxSE) / pow((float)10, tcd_tcp->distoratio[layno] / 10)); - - /* Don't try to find an optimal threshold but rather take everything not included yet, if - -r xx,yy,zz,0 (disto_alloc == 1 and rates == 0) - -q xx,yy,zz,0 (fixed_quality == 1 and distoratio == 0) - ==> possible to have some lossy layers and the last layer for sure lossless */ - if ( ((cp->disto_alloc==1) && (tcd_tcp->rates[layno]>0)) || ((cp->fixed_quality==1) && (tcd_tcp->distoratio[layno]>0))) { - opj_t2_t *t2 = t2_create(tcd->cinfo, tcd->image, cp); - double thresh = 0; - - for (i = 0; i < 128; i++) { - int l = 0; - double distoachieved = 0; /* fixed_quality */ - thresh = (lo + hi) / 2; - - tcd_makelayer(tcd, layno, thresh, 0); - - if (cp->fixed_quality) { /* fixed_quality */ - if(cp->cinema){ - l = t2_encode_packets(t2,tcd->tcd_tileno, tcd_tile, layno + 1, dest, maxlen, cstr_info,tcd->cur_tp_num,tcd->tp_pos,tcd->cur_pino,THRESH_CALC, tcd->cur_totnum_tp); - if (l == -999) { - lo = thresh; - continue; - }else{ - distoachieved = layno == 0 ? - tcd_tile->distolayer[0] : cumdisto[layno - 1] + tcd_tile->distolayer[layno]; - if (distoachieved < distotarget) { - hi=thresh; - stable_thresh = thresh; - continue; - }else{ - lo=thresh; - } - } - }else{ - distoachieved = (layno == 0) ? - tcd_tile->distolayer[0] : (cumdisto[layno - 1] + tcd_tile->distolayer[layno]); - if (distoachieved < distotarget) { - hi = thresh; - stable_thresh = thresh; - continue; - } - lo = thresh; - } - } else { - l = t2_encode_packets(t2, tcd->tcd_tileno, tcd_tile, layno + 1, dest, maxlen, cstr_info,tcd->cur_tp_num,tcd->tp_pos,tcd->cur_pino,THRESH_CALC, tcd->cur_totnum_tp); - /* TODO: what to do with l ??? seek / tell ??? */ - /* opj_event_msg(tcd->cinfo, EVT_INFO, "rate alloc: len=%d, max=%d\n", l, maxlen); */ - if (l == -999) { - lo = thresh; - continue; - } - hi = thresh; - stable_thresh = thresh; - } - } - success = 1; - goodthresh = stable_thresh == 0? thresh : stable_thresh; - t2_destroy(t2); - } else { - success = 1; - goodthresh = min; - } - - if (!success) { - return OPJ_FALSE; - } - - if(cstr_info) { /* Threshold for Marcela Index */ - cstr_info->tile[tcd->tcd_tileno].thresh[layno] = goodthresh; - } - tcd_makelayer(tcd, layno, goodthresh, 1); - - /* fixed_quality */ - cumdisto[layno] = (layno == 0) ? tcd_tile->distolayer[0] : (cumdisto[layno - 1] + tcd_tile->distolayer[layno]); - } - - return OPJ_TRUE; -} - -int tcd_encode_tile(opj_tcd_t *tcd, int tileno, unsigned char *dest, int len, opj_codestream_info_t *cstr_info) { - int compno; - int l, i, numpacks = 0; - opj_tcd_tile_t *tile = NULL; - opj_tcp_t *tcd_tcp = NULL; - opj_cp_t *cp = NULL; - - opj_tcp_t *tcp = &tcd->cp->tcps[0]; - opj_tccp_t *tccp = &tcp->tccps[0]; - opj_image_t *image = tcd->image; - - opj_t1_t *t1 = NULL; /* T1 component */ - opj_t2_t *t2 = NULL; /* T2 component */ - - tcd->tcd_tileno = tileno; - tcd->tcd_tile = tcd->tcd_image->tiles; - tcd->tcp = &tcd->cp->tcps[tileno]; - - tile = tcd->tcd_tile; - tcd_tcp = tcd->tcp; - cp = tcd->cp; - - if(tcd->cur_tp_num == 0){ - tcd->encoding_time = opj_clock(); /* time needed to encode a tile */ - /* INDEX >> "Precinct_nb_X et Precinct_nb_Y" */ - if(cstr_info) { - opj_tcd_tilecomp_t *tilec_idx = &tile->comps[0]; /* based on component 0 */ - for (i = 0; i < tilec_idx->numresolutions; i++) { - opj_tcd_resolution_t *res_idx = &tilec_idx->resolutions[i]; - - cstr_info->tile[tileno].pw[i] = res_idx->pw; - cstr_info->tile[tileno].ph[i] = res_idx->ph; - - numpacks += res_idx->pw * res_idx->ph; - - cstr_info->tile[tileno].pdx[i] = tccp->prcw[i]; - cstr_info->tile[tileno].pdy[i] = tccp->prch[i]; - } - cstr_info->tile[tileno].packet = (opj_packet_info_t*) opj_calloc(cstr_info->numcomps * cstr_info->numlayers * numpacks, sizeof(opj_packet_info_t)); - } - /* << INDEX */ - - /*---------------TILE-------------------*/ - - for (compno = 0; compno < tile->numcomps; compno++) { - int x, y; - - int adjust = image->comps[compno].sgnd ? 0 : 1 << (image->comps[compno].prec - 1); - int offset_x = int_ceildiv(image->x0, image->comps[compno].dx); - int offset_y = int_ceildiv(image->y0, image->comps[compno].dy); - - opj_tcd_tilecomp_t *tilec = &tile->comps[compno]; - int tw = tilec->x1 - tilec->x0; - int w = int_ceildiv(image->x1 - image->x0, image->comps[compno].dx); - - /* extract tile data */ - - if (tcd_tcp->tccps[compno].qmfbid == 1) { - for (y = tilec->y0; y < tilec->y1; y++) { - /* start of the src tile scanline */ - int *data = &image->comps[compno].data[(tilec->x0 - offset_x) + (y - offset_y) * w]; - /* start of the dst tile scanline */ - int *tile_data = &tilec->data[(y - tilec->y0) * tw]; - for (x = tilec->x0; x < tilec->x1; x++) { - *tile_data++ = *data++ - adjust; - } - } - } else if (tcd_tcp->tccps[compno].qmfbid == 0) { - for (y = tilec->y0; y < tilec->y1; y++) { - /* start of the src tile scanline */ - int *data = &image->comps[compno].data[(tilec->x0 - offset_x) + (y - offset_y) * w]; - /* start of the dst tile scanline */ - int *tile_data = &tilec->data[(y - tilec->y0) * tw]; - for (x = tilec->x0; x < tilec->x1; x++) { - *tile_data++ = (*data++ - adjust) << 11; - } - - } - } - } - - /*----------------MCT-------------------*/ - if (tcd_tcp->mct) { - int samples = (tile->comps[0].x1 - tile->comps[0].x0) * (tile->comps[0].y1 - tile->comps[0].y0); - if (tcd_tcp->tccps[0].qmfbid == 0) { - mct_encode_real(tile->comps[0].data, tile->comps[1].data, tile->comps[2].data, samples); - } else { - mct_encode(tile->comps[0].data, tile->comps[1].data, tile->comps[2].data, samples); - } - } - - /*----------------DWT---------------------*/ - - for (compno = 0; compno < tile->numcomps; compno++) { - opj_tcd_tilecomp_t *tilec = &tile->comps[compno]; - if (tcd_tcp->tccps[compno].qmfbid == 1) { - dwt_encode(tilec); - } else if (tcd_tcp->tccps[compno].qmfbid == 0) { - dwt_encode_real(tilec); - } - } - - /*------------------TIER1-----------------*/ - t1 = t1_create(tcd->cinfo); - t1_encode_cblks(t1, tile, tcd_tcp); - t1_destroy(t1); - - /*-----------RATE-ALLOCATE------------------*/ - - /* INDEX */ - if(cstr_info) { - cstr_info->index_write = 0; - } - if (cp->disto_alloc || cp->fixed_quality) { /* fixed_quality */ - /* Normal Rate/distortion allocation */ - tcd_rateallocate(tcd, dest, len, cstr_info); - } else { - /* Fixed layer allocation */ - tcd_rateallocate_fixed(tcd); - } - } - /*--------------TIER2------------------*/ - - /* INDEX */ - if(cstr_info) { - cstr_info->index_write = 1; - } - - t2 = t2_create(tcd->cinfo, image, cp); - l = t2_encode_packets(t2,tileno, tile, tcd_tcp->numlayers, dest, len, cstr_info,tcd->tp_num,tcd->tp_pos,tcd->cur_pino,FINAL_PASS,tcd->cur_totnum_tp); - t2_destroy(t2); - - /*---------------CLEAN-------------------*/ - - - if(tcd->cur_tp_num == tcd->cur_totnum_tp - 1){ - tcd->encoding_time = opj_clock() - tcd->encoding_time; - opj_event_msg(tcd->cinfo, EVT_INFO, "- tile encoded in %f s\n", tcd->encoding_time); - - /* cleaning memory */ - for (compno = 0; compno < tile->numcomps; compno++) { - opj_tcd_tilecomp_t *tilec = &tile->comps[compno]; - opj_aligned_free(tilec->data); - } - } - - return l; -} - -opj_bool tcd_decode_tile(opj_tcd_t *tcd, unsigned char *src, int len, int tileno, opj_codestream_info_t *cstr_info) { - int l; - int compno; - int eof = 0; - double tile_time, t1_time, dwt_time; - opj_tcd_tile_t *tile = NULL; - - opj_t1_t *t1 = NULL; /* T1 component */ - opj_t2_t *t2 = NULL; /* T2 component */ - - tcd->tcd_tileno = tileno; - tcd->tcd_tile = &(tcd->tcd_image->tiles[tileno]); - tcd->tcp = &(tcd->cp->tcps[tileno]); - tile = tcd->tcd_tile; - - tile_time = opj_clock(); /* time needed to decode a tile */ - opj_event_msg(tcd->cinfo, EVT_INFO, "tile %d of %d\n", tileno + 1, tcd->cp->tw * tcd->cp->th); - - /* INDEX >> */ - if(cstr_info) { - int resno, compno, numprec = 0; - for (compno = 0; compno < cstr_info->numcomps; compno++) { - opj_tcp_t *tcp = &tcd->cp->tcps[0]; - opj_tccp_t *tccp = &tcp->tccps[compno]; - opj_tcd_tilecomp_t *tilec_idx = &tile->comps[compno]; - for (resno = 0; resno < tilec_idx->numresolutions; resno++) { - opj_tcd_resolution_t *res_idx = &tilec_idx->resolutions[resno]; - cstr_info->tile[tileno].pw[resno] = res_idx->pw; - cstr_info->tile[tileno].ph[resno] = res_idx->ph; - numprec += res_idx->pw * res_idx->ph; - if (tccp->csty & J2K_CP_CSTY_PRT) { - cstr_info->tile[tileno].pdx[resno] = tccp->prcw[resno]; - cstr_info->tile[tileno].pdy[resno] = tccp->prch[resno]; - } - else { - cstr_info->tile[tileno].pdx[resno] = 15; - cstr_info->tile[tileno].pdy[resno] = 15; - } - } - } - cstr_info->tile[tileno].packet = (opj_packet_info_t *) opj_malloc(cstr_info->numlayers * numprec * sizeof(opj_packet_info_t)); - cstr_info->packno = 0; - } - /* << INDEX */ - - /*--------------TIER2------------------*/ - - t2 = t2_create(tcd->cinfo, tcd->image, tcd->cp); - l = t2_decode_packets(t2, src, len, tileno, tile, cstr_info); - t2_destroy(t2); - - if (l == -999) { - eof = 1; - opj_event_msg(tcd->cinfo, EVT_ERROR, "tcd_decode: incomplete bistream\n"); - } - - /*------------------TIER1-----------------*/ - - t1_time = opj_clock(); /* time needed to decode a tile */ - t1 = t1_create(tcd->cinfo); - for (compno = 0; compno < tile->numcomps; ++compno) { - opj_tcd_tilecomp_t* tilec = &tile->comps[compno]; - /* The +3 is headroom required by the vectorized DWT */ - tilec->data = (int*) opj_aligned_malloc((((tilec->x1 - tilec->x0) * (tilec->y1 - tilec->y0))+3) * sizeof(int)); - t1_decode_cblks(t1, tilec, &tcd->tcp->tccps[compno]); - } - t1_destroy(t1); - t1_time = opj_clock() - t1_time; - opj_event_msg(tcd->cinfo, EVT_INFO, "- tiers-1 took %f s\n", t1_time); - - /*----------------DWT---------------------*/ - - dwt_time = opj_clock(); /* time needed to decode a tile */ - for (compno = 0; compno < tile->numcomps; compno++) { - opj_tcd_tilecomp_t *tilec = &tile->comps[compno]; - int numres2decode; - - if (tcd->cp->reduce != 0) { - tcd->image->comps[compno].resno_decoded = - tile->comps[compno].numresolutions - tcd->cp->reduce - 1; - if (tcd->image->comps[compno].resno_decoded < 0) { - opj_event_msg(tcd->cinfo, EVT_ERROR, "Error decoding tile. The number of resolutions to remove [%d+1] is higher than the number " - " of resolutions in the original codestream [%d]\nModify the cp_reduce parameter.\n", tcd->cp->reduce, tile->comps[compno].numresolutions); - return OPJ_FALSE; - } - } - - numres2decode = tcd->image->comps[compno].resno_decoded + 1; - if(numres2decode > 0){ - if (tcd->tcp->tccps[compno].qmfbid == 1) { - dwt_decode(tilec, numres2decode); - } else { - dwt_decode_real(tilec, numres2decode); - } - } - } - dwt_time = opj_clock() - dwt_time; - opj_event_msg(tcd->cinfo, EVT_INFO, "- dwt took %f s\n", dwt_time); - - /*----------------MCT-------------------*/ - - if (tcd->tcp->mct) { - int n = (tile->comps[0].x1 - tile->comps[0].x0) * (tile->comps[0].y1 - tile->comps[0].y0); - - if (tile->numcomps >= 3 ){ - if (tcd->tcp->tccps[0].qmfbid == 1) { - mct_decode( - tile->comps[0].data, - tile->comps[1].data, - tile->comps[2].data, - n); - } else { - mct_decode_real( - (float*)tile->comps[0].data, - (float*)tile->comps[1].data, - (float*)tile->comps[2].data, - n); - } - } else{ - opj_event_msg(tcd->cinfo, EVT_WARNING,"Number of components (%d) is inconsistent with a MCT. Skip the MCT step.\n",tile->numcomps); - } - } - - /*---------------TILE-------------------*/ - - for (compno = 0; compno < tile->numcomps; ++compno) { - opj_tcd_tilecomp_t* tilec = &tile->comps[compno]; - opj_image_comp_t* imagec = &tcd->image->comps[compno]; - opj_tcd_resolution_t* res = &tilec->resolutions[imagec->resno_decoded]; - int adjust = imagec->sgnd ? 0 : 1 << (imagec->prec - 1); - int min = imagec->sgnd ? -(1 << (imagec->prec - 1)) : 0; - int max = imagec->sgnd ? (1 << (imagec->prec - 1)) - 1 : (1 << imagec->prec) - 1; - - int tw = tilec->x1 - tilec->x0; - int w = imagec->w; - - int offset_x = int_ceildivpow2(imagec->x0, imagec->factor); - int offset_y = int_ceildivpow2(imagec->y0, imagec->factor); - - int i, j; - if(!imagec->data){ - imagec->data = (int*) opj_malloc(imagec->w * imagec->h * sizeof(int)); - } - if(tcd->tcp->tccps[compno].qmfbid == 1) { - for(j = res->y0; j < res->y1; ++j) { - for(i = res->x0; i < res->x1; ++i) { - int v = tilec->data[i - res->x0 + (j - res->y0) * tw]; - v += adjust; - imagec->data[(i - offset_x) + (j - offset_y) * w] = int_clamp(v, min, max); - } - } - }else{ - for(j = res->y0; j < res->y1; ++j) { - for(i = res->x0; i < res->x1; ++i) { - float tmp = ((float*)tilec->data)[i - res->x0 + (j - res->y0) * tw]; - int v = lrintf(tmp); - v += adjust; - imagec->data[(i - offset_x) + (j - offset_y) * w] = int_clamp(v, min, max); - } - } - } - opj_aligned_free(tilec->data); - } - - tile_time = opj_clock() - tile_time; /* time needed to decode a tile */ - opj_event_msg(tcd->cinfo, EVT_INFO, "- tile decoded in %f s\n", tile_time); - - if (eof) { - return OPJ_FALSE; - } - - return OPJ_TRUE; -} - -void tcd_free_decode(opj_tcd_t *tcd) { - opj_tcd_image_t *tcd_image = tcd->tcd_image; - opj_free(tcd_image->tiles); -} - -void tcd_free_decode_tile(opj_tcd_t *tcd, int tileno) { - int compno,resno,bandno,precno; - - opj_tcd_image_t *tcd_image = tcd->tcd_image; - - opj_tcd_tile_t *tile = &tcd_image->tiles[tileno]; - for (compno = 0; compno < tile->numcomps; compno++) { - opj_tcd_tilecomp_t *tilec = &tile->comps[compno]; - for (resno = 0; resno < tilec->numresolutions; resno++) { - opj_tcd_resolution_t *res = &tilec->resolutions[resno]; - for (bandno = 0; bandno < res->numbands; bandno++) { - opj_tcd_band_t *band = &res->bands[bandno]; - for (precno = 0; precno < res->ph * res->pw; precno++) { - opj_tcd_precinct_t *prec = &band->precincts[precno]; - if (prec->imsbtree != NULL) tgt_destroy(prec->imsbtree); - if (prec->incltree != NULL) tgt_destroy(prec->incltree); - } - opj_free(band->precincts); - } - } - opj_free(tilec->resolutions); - } - opj_free(tile->comps); -} - - - diff --git a/openjpeg-dotnet/libopenjpeg/tcd.h b/openjpeg-dotnet/libopenjpeg/tcd.h deleted file mode 100644 index e3f93adc..00000000 --- a/openjpeg-dotnet/libopenjpeg/tcd.h +++ /dev/null @@ -1,286 +0,0 @@ -/* - * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium - * Copyright (c) 2002-2007, Professor Benoit Macq - * Copyright (c) 2001-2003, David Janssens - * Copyright (c) 2002-2003, Yannick Verschueren - * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe - * Copyright (c) 2005, Herve Drolon, FreeImage Team - * 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 -/** -@file tcd.h -@brief Implementation of a tile coder/decoder (TCD) - -The functions in TCD.C have for goal to encode or decode each tile independently from -each other. The functions in TCD.C are used by some function in J2K.C. -*/ - -/** @defgroup TCD TCD - Implementation of a tile coder/decoder */ -/*@{*/ - -/** -FIXME: documentation -*/ -typedef struct opj_tcd_seg { - unsigned char** data; - int dataindex; - int numpasses; - int len; - int maxpasses; - int numnewpasses; - int newlen; -} opj_tcd_seg_t; - -/** -FIXME: documentation -*/ -typedef struct opj_tcd_pass { - int rate; - double distortiondec; - int term, len; -} opj_tcd_pass_t; - -/** -FIXME: documentation -*/ -typedef struct opj_tcd_layer { - int numpasses; /* Number of passes in the layer */ - int len; /* len of information */ - double disto; /* add for index (Cfr. Marcela) */ - unsigned char *data; /* data */ -} opj_tcd_layer_t; - -/** -FIXME: documentation -*/ -typedef struct opj_tcd_cblk_enc { - unsigned char* data; /* Data */ - opj_tcd_layer_t* layers; /* layer information */ - opj_tcd_pass_t* passes; /* information about the passes */ - int x0, y0, x1, y1; /* dimension of the code-blocks : left upper corner (x0, y0) right low corner (x1,y1) */ - int numbps; - int numlenbits; - int numpasses; /* number of pass already done for the code-blocks */ - int numpassesinlayers; /* number of passes in the layer */ - int totalpasses; /* total number of passes */ -} opj_tcd_cblk_enc_t; - -typedef struct opj_tcd_cblk_dec { - unsigned char* data; /* Data */ - opj_tcd_seg_t* segs; /* segments informations */ - int x0, y0, x1, y1; /* dimension of the code-blocks : left upper corner (x0, y0) right low corner (x1,y1) */ - int numbps; - int numlenbits; - int len; /* length */ - int numnewpasses; /* number of pass added to the code-blocks */ - int numsegs; /* number of segments */ -} opj_tcd_cblk_dec_t; - -/** -FIXME: documentation -*/ -typedef struct opj_tcd_precinct { - int x0, y0, x1, y1; /* dimension of the precinct : left upper corner (x0, y0) right low corner (x1,y1) */ - int cw, ch; /* number of precinct in width and heigth */ - union{ /* code-blocks informations */ - opj_tcd_cblk_enc_t* enc; - opj_tcd_cblk_dec_t* dec; - } cblks; - opj_tgt_tree_t *incltree; /* inclusion tree */ - opj_tgt_tree_t *imsbtree; /* IMSB tree */ -} opj_tcd_precinct_t; - -/** -FIXME: documentation -*/ -typedef struct opj_tcd_band { - int x0, y0, x1, y1; /* dimension of the subband : left upper corner (x0, y0) right low corner (x1,y1) */ - int bandno; - opj_tcd_precinct_t *precincts; /* precinct information */ - int numbps; - float stepsize; -} opj_tcd_band_t; - -/** -FIXME: documentation -*/ -typedef struct opj_tcd_resolution { - int x0, y0, x1, y1; /* dimension of the resolution level : left upper corner (x0, y0) right low corner (x1,y1) */ - int pw, ph; - int numbands; /* number sub-band for the resolution level */ - opj_tcd_band_t bands[3]; /* subband information */ -} opj_tcd_resolution_t; - -/** -FIXME: documentation -*/ -typedef struct opj_tcd_tilecomp { - int x0, y0, x1, y1; /* dimension of component : left upper corner (x0, y0) right low corner (x1,y1) */ - int numresolutions; /* number of resolutions level */ - opj_tcd_resolution_t *resolutions; /* resolutions information */ - int *data; /* data of the component */ - int numpix; /* add fixed_quality */ -} opj_tcd_tilecomp_t; - -/** -FIXME: documentation -*/ -typedef struct opj_tcd_tile { - int x0, y0, x1, y1; /* dimension of the tile : left upper corner (x0, y0) right low corner (x1,y1) */ - int numcomps; /* number of components in tile */ - opj_tcd_tilecomp_t *comps; /* Components information */ - int numpix; /* add fixed_quality */ - double distotile; /* add fixed_quality */ - double distolayer[100]; /* add fixed_quality */ - /** packet number */ - int packno; -} opj_tcd_tile_t; - -/** -FIXME: documentation -*/ -typedef struct opj_tcd_image { - int tw, th; /* number of tiles in width and heigth */ - opj_tcd_tile_t *tiles; /* Tiles information */ -} opj_tcd_image_t; - -/** -Tile coder/decoder -*/ -typedef struct opj_tcd { - /** Position of the tilepart flag in Progression order*/ - int tp_pos; - /** Tile part number*/ - int tp_num; - /** Current tile part number*/ - int cur_tp_num; - /** Total number of tileparts of the current tile*/ - int cur_totnum_tp; - /** Current Packet iterator number */ - int cur_pino; - /** codec context */ - opj_common_ptr cinfo; - - /** info on each image tile */ - opj_tcd_image_t *tcd_image; - /** image */ - opj_image_t *image; - /** coding parameters */ - opj_cp_t *cp; - /** pointer to the current encoded/decoded tile */ - opj_tcd_tile_t *tcd_tile; - /** coding/decoding parameters common to all tiles */ - opj_tcp_t *tcp; - /** current encoded/decoded tile */ - int tcd_tileno; - /** Time taken to encode a tile*/ - double encoding_time; -} opj_tcd_t; - -/** @name Exported functions */ -/*@{*/ -/* ----------------------------------------------------------------------- */ - -/** -Dump the content of a tcd structure -*/ -void tcd_dump(FILE *fd, opj_tcd_t *tcd, opj_tcd_image_t *img); -/** -Create a new TCD handle -@param cinfo Codec context info -@return Returns a new TCD handle if successful returns NULL otherwise -*/ -opj_tcd_t* tcd_create(opj_common_ptr cinfo); -/** -Destroy a previously created TCD handle -@param tcd TCD handle to destroy -*/ -void tcd_destroy(opj_tcd_t *tcd); -/** -Initialize the tile coder (allocate the memory) -@param tcd TCD handle -@param image Raw image -@param cp Coding parameters -@param curtileno Number that identifies the tile that will be encoded -*/ -void tcd_malloc_encode(opj_tcd_t *tcd, opj_image_t * image, opj_cp_t * cp, int curtileno); -/** -Free the memory allocated for encoding -@param tcd TCD handle -*/ -void tcd_free_encode(opj_tcd_t *tcd); -/** -Initialize the tile coder (reuses the memory allocated by tcd_malloc_encode) -@param tcd TCD handle -@param image Raw image -@param cp Coding parameters -@param curtileno Number that identifies the tile that will be encoded -*/ -void tcd_init_encode(opj_tcd_t *tcd, opj_image_t * image, opj_cp_t * cp, int curtileno); -/** -Initialize the tile decoder -@param tcd TCD handle -@param image Raw image -@param cp Coding parameters -*/ -void tcd_malloc_decode(opj_tcd_t *tcd, opj_image_t * image, opj_cp_t * cp); -void tcd_malloc_decode_tile(opj_tcd_t *tcd, opj_image_t * image, opj_cp_t * cp, int tileno, opj_codestream_info_t *cstr_info); -void tcd_makelayer_fixed(opj_tcd_t *tcd, int layno, int final); -void tcd_rateallocate_fixed(opj_tcd_t *tcd); -void tcd_makelayer(opj_tcd_t *tcd, int layno, double thresh, int final); -opj_bool tcd_rateallocate(opj_tcd_t *tcd, unsigned char *dest, int len, opj_codestream_info_t *cstr_info); -/** -Encode a tile from the raw image into a buffer -@param tcd TCD handle -@param tileno Number that identifies one of the tiles to be encoded -@param dest Destination buffer -@param len Length of destination buffer -@param cstr_info Codestream information structure -@return -*/ -int tcd_encode_tile(opj_tcd_t *tcd, int tileno, unsigned char *dest, int len, opj_codestream_info_t *cstr_info); -/** -Decode a tile from a buffer into a raw image -@param tcd TCD handle -@param src Source buffer -@param len Length of source buffer -@param tileno Number that identifies one of the tiles to be decoded -@param cstr_info Codestream information structure -*/ -opj_bool tcd_decode_tile(opj_tcd_t *tcd, unsigned char *src, int len, int tileno, opj_codestream_info_t *cstr_info); -/** -Free the memory allocated for decoding -@param tcd TCD handle -*/ -void tcd_free_decode(opj_tcd_t *tcd); -void tcd_free_decode_tile(opj_tcd_t *tcd, int tileno); - -/* ----------------------------------------------------------------------- */ -/*@}*/ - -/*@}*/ - -#endif /* __TCD_H */ diff --git a/openjpeg-dotnet/libopenjpeg/tgt.c b/openjpeg-dotnet/libopenjpeg/tgt.c deleted file mode 100644 index a5dbcd3c..00000000 --- a/openjpeg-dotnet/libopenjpeg/tgt.c +++ /dev/null @@ -1,213 +0,0 @@ -/* - * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium - * Copyright (c) 2002-2007, Professor Benoit Macq - * Copyright (c) 2001-2003, David Janssens - * Copyright (c) 2002-2003, Yannick Verschueren - * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe - * Copyright (c) 2005, Herve Drolon, FreeImage Team - * 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 "opj_includes.h" - -/* -========================================================== - Tag-tree coder interface -========================================================== -*/ - -opj_tgt_tree_t *tgt_create(int numleafsh, int numleafsv) { - int nplh[32]; - int nplv[32]; - opj_tgt_node_t *node = NULL; - opj_tgt_node_t *parentnode = NULL; - opj_tgt_node_t *parentnode0 = NULL; - opj_tgt_tree_t *tree = NULL; - int i, j, k; - int numlvls; - int n; - - tree = (opj_tgt_tree_t *) opj_malloc(sizeof(opj_tgt_tree_t)); - if(!tree) return NULL; - 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); - - /* ADD */ - if (tree->numnodes == 0) { - opj_free(tree); - return NULL; - } - - tree->nodes = (opj_tgt_node_t*) opj_calloc(tree->numnodes, sizeof(opj_tgt_node_t)); - if(!tree->nodes) { - opj_free(tree); - return NULL; - } - - 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; - - tgt_reset(tree); - - return tree; -} - -void tgt_destroy(opj_tgt_tree_t *tree) { - opj_free(tree->nodes); - opj_free(tree); -} - -void tgt_reset(opj_tgt_tree_t *tree) { - int i; - - if (NULL == tree) - return; - - for (i = 0; i < tree->numnodes; i++) { - tree->nodes[i].value = 999; - tree->nodes[i].low = 0; - tree->nodes[i].known = 0; - } -} - -void tgt_setvalue(opj_tgt_tree_t *tree, int leafno, int value) { - opj_tgt_node_t *node; - node = &tree->nodes[leafno]; - while (node && node->value > value) { - node->value = value; - node = node->parent; - } -} - -void tgt_encode(opj_bio_t *bio, opj_tgt_tree_t *tree, int leafno, int threshold) { - opj_tgt_node_t *stk[31]; - opj_tgt_node_t **stkptr; - opj_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 < threshold) { - if (low >= node->value) { - if (!node->known) { - bio_write(bio, 1, 1); - node->known = 1; - } - break; - } - bio_write(bio, 0, 1); - ++low; - } - - node->low = low; - if (stkptr == stk) - break; - node = *--stkptr; - } -} - -int tgt_decode(opj_bio_t *bio, opj_tgt_tree_t *tree, int leafno, int threshold) { - opj_tgt_node_t *stk[31]; - opj_tgt_node_t **stkptr; - opj_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 < threshold && low < node->value) { - if (bio_read(bio, 1)) { - node->value = low; - } else { - ++low; - } - } - node->low = low; - if (stkptr == stk) { - break; - } - node = *--stkptr; - } - - return (node->value < threshold) ? 1 : 0; -} diff --git a/openjpeg-dotnet/libopenjpeg/tgt.h b/openjpeg-dotnet/libopenjpeg/tgt.h deleted file mode 100644 index c08c8da0..00000000 --- a/openjpeg-dotnet/libopenjpeg/tgt.h +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium - * Copyright (c) 2002-2007, Professor Benoit Macq - * Copyright (c) 2001-2003, David Janssens - * Copyright (c) 2002-2003, Yannick Verschueren - * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe - * Copyright (c) 2005, Herve Drolon, FreeImage Team - * 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 __TGT_H -#define __TGT_H -/** -@file tgt.h -@brief Implementation of a tag-tree coder (TGT) - -The functions in TGT.C have for goal to realize a tag-tree coder. The functions in TGT.C -are used by some function in T2.C. -*/ - -/** @defgroup TGT TGT - Implementation of a tag-tree coder */ -/*@{*/ - -/** -Tag node -*/ -typedef struct opj_tgt_node { - struct opj_tgt_node *parent; - int value; - int low; - int known; -} opj_tgt_node_t; - -/** -Tag tree -*/ -typedef struct opj_tgt_tree { - int numleafsh; - int numleafsv; - int numnodes; - opj_tgt_node_t *nodes; -} opj_tgt_tree_t; - -/** @name Exported functions */ -/*@{*/ -/* ----------------------------------------------------------------------- */ -/** -Create a tag-tree -@param numleafsh Width of the array of leafs of the tree -@param numleafsv Height of the array of leafs of the tree -@return Returns a new tag-tree if successful, returns NULL otherwise -*/ -opj_tgt_tree_t *tgt_create(int numleafsh, int numleafsv); -/** -Destroy a tag-tree, liberating memory -@param tree Tag-tree to destroy -*/ -void tgt_destroy(opj_tgt_tree_t *tree); -/** -Reset a tag-tree (set all leaves to 0) -@param tree Tag-tree to reset -*/ -void tgt_reset(opj_tgt_tree_t *tree); -/** -Set the value of a leaf of a tag-tree -@param tree Tag-tree to modify -@param leafno Number that identifies the leaf to modify -@param value New value of the leaf -*/ -void tgt_setvalue(opj_tgt_tree_t *tree, int leafno, int value); -/** -Encode the value of a leaf of the tag-tree up to a given threshold -@param bio Pointer to a BIO handle -@param tree Tag-tree to modify -@param leafno Number that identifies the leaf to encode -@param threshold Threshold to use when encoding value of the leaf -*/ -void tgt_encode(opj_bio_t *bio, opj_tgt_tree_t *tree, int leafno, int threshold); -/** -Decode the value of a leaf of the tag-tree up to a given threshold -@param bio Pointer to a BIO handle -@param tree Tag-tree to decode -@param leafno Number that identifies the leaf to decode -@param threshold Threshold to use when decoding value of the leaf -@return Returns 1 if the node's value < threshold, returns 0 otherwise -*/ -int tgt_decode(opj_bio_t *bio, opj_tgt_tree_t *tree, int leafno, int threshold); -/* ----------------------------------------------------------------------- */ -/*@}*/ - -/*@}*/ - -#endif /* __TGT_H */ diff --git a/openjpeg-dotnet/libopenjpeg/thix_manager.c b/openjpeg-dotnet/libopenjpeg/thix_manager.c deleted file mode 100644 index aa55f217..00000000 --- a/openjpeg-dotnet/libopenjpeg/thix_manager.c +++ /dev/null @@ -1,120 +0,0 @@ -/* - * $Id: thix_manager.c 897 2011-08-28 21:43:57Z Kaori.Hagihara@gmail.com $ - * - * Copyright (c) 2002-2011, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium - * Copyright (c) 2002-2011, Professor Benoit Macq - * Copyright (c) 2003-2004, Yannick Verschueren - * Copyright (c) 2010-2011, Kaori Hagihara - * 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. - */ - -/*! \file - * \brief Modification of jpip.c from 2KAN indexer - */ - -#include -#include -#include -#include "opj_includes.h" - -/* - * Write tile-part headers mhix box - * - * @param[in] coff offset of j2k codestream - * @param[in] cstr_info codestream information - * @param[in] tileno tile number - * @param[in] cio file output handle - * @return length of mhix box - */ -int write_tilemhix( int coff, opj_codestream_info_t cstr_info, int tileno, opj_cio_t *cio); - -int write_thix( int coff, opj_codestream_info_t cstr_info, opj_cio_t *cio) -{ - int len, lenp, i; - int tileno; - opj_jp2_box_t *box; - - lenp = 0; - box = (opj_jp2_box_t *)opj_calloc( cstr_info.tw*cstr_info.th, sizeof(opj_jp2_box_t)); - - for ( i = 0; i < 2 ; i++ ){ - if (i) - cio_seek( cio, lenp); - - lenp = cio_tell( cio); - cio_skip( cio, 4); /* L [at the end] */ - cio_write( cio, JPIP_THIX, 4); /* THIX */ - write_manf( i, cstr_info.tw*cstr_info.th, box, cio); - - for (tileno = 0; tileno < cstr_info.tw*cstr_info.th; tileno++){ - box[tileno].length = write_tilemhix( coff, cstr_info, tileno, cio); - box[tileno].type = JPIP_MHIX; - } - - len = cio_tell( cio)-lenp; - cio_seek( cio, lenp); - cio_write( cio, len, 4); /* L */ - cio_seek( cio, lenp+len); - } - - opj_free(box); - - return len; -} - -int write_tilemhix( int coff, opj_codestream_info_t cstr_info, int tileno, opj_cio_t *cio) -{ - int i; - opj_tile_info_t tile; - opj_tp_info_t tp; - int len, lenp; - opj_marker_info_t *marker; - - lenp = cio_tell( cio); - cio_skip( cio, 4); /* L [at the end] */ - cio_write( cio, JPIP_MHIX, 4); /* MHIX */ - - tile = cstr_info.tile[tileno]; - tp = tile.tp[0]; - - cio_write( cio, tp.tp_end_header-tp.tp_start_pos+1, 8); /* TLEN */ - - marker = cstr_info.tile[tileno].marker; - - for( i=0; i -#include "opj_includes.h" - -#define MAX(a,b) ((a)>(b)?(a):(b)) - - -/* - * Write faix box of tpix - * - * @param[in] coff offset of j2k codestream - * @param[in] compno component number - * @param[in] cstr_info codestream information - * @param[in] j2klen length of j2k codestream - * @param[in] cio file output handle - * @return length of faix box - */ -int write_tpixfaix( int coff, int compno, opj_codestream_info_t cstr_info, int j2klen, opj_cio_t *cio); - - -int write_tpix( int coff, opj_codestream_info_t cstr_info, int j2klen, opj_cio_t *cio) -{ - int len, lenp; - lenp = cio_tell( cio); - cio_skip( cio, 4); /* L [at the end] */ - cio_write( cio, JPIP_TPIX, 4); /* TPIX */ - - write_tpixfaix( coff, 0, cstr_info, j2klen, cio); - - len = cio_tell( cio)-lenp; - cio_seek( cio, lenp); - cio_write( cio, len, 4); /* L */ - cio_seek( cio, lenp+len); - - return len; -} - - -/* - * Get number of maximum tile parts per tile - * - * @param[in] cstr_info codestream information - * @return number of maximum tile parts per tile - */ -int get_num_max_tile_parts( opj_codestream_info_t cstr_info); - -int write_tpixfaix( int coff, int compno, opj_codestream_info_t cstr_info, int j2klen, opj_cio_t *cio) -{ - int len, lenp; - int i, j; - int Aux; - int num_max_tile_parts; - int size_of_coding; /* 4 or 8 */ - opj_tp_info_t tp; - int version; - - num_max_tile_parts = get_num_max_tile_parts( cstr_info); - - if( j2klen > pow( 2, 32)){ - size_of_coding = 8; - version = num_max_tile_parts == 1 ? 1:3; - } - else{ - size_of_coding = 4; - version = num_max_tile_parts == 1 ? 0:2; - } - - lenp = cio_tell( cio); - cio_skip( cio, 4); /* L [at the end] */ - cio_write( cio, JPIP_FAIX, 4); /* FAIX */ - cio_write( cio, version, 1); /* Version 0 = 4 bytes */ - - cio_write( cio, num_max_tile_parts, size_of_coding); /* NMAX */ - cio_write( cio, cstr_info.tw*cstr_info.th, size_of_coding); /* M */ - for (i = 0; i < cstr_info.tw*cstr_info.th; i++){ - for (j = 0; j < cstr_info.tile[i].num_tps; j++){ - tp = cstr_info.tile[i].tp[j]; - cio_write( cio, tp.tp_start_pos-coff, size_of_coding); /* start position */ - cio_write( cio, tp.tp_end_pos-tp.tp_start_pos+1, size_of_coding); /* length */ - if (version & 0x02){ - if( cstr_info.tile[i].num_tps == 1 && cstr_info.numdecompos[compno] > 1) - Aux = cstr_info.numdecompos[compno] + 1; - else - Aux = j + 1; - - cio_write( cio, Aux,4); - /*cio_write(img.tile[i].tile_parts[j].num_reso_AUX,4);*/ /* Aux_i,j : Auxiliary value */ - /* fprintf(stderr,"AUX value %d\n",Aux);*/ - } - /*cio_write(0,4);*/ - } - /* PADDING */ - while (j < num_max_tile_parts){ - cio_write( cio, 0, size_of_coding); /* start position */ - cio_write( cio, 0, size_of_coding); /* length */ - if (version & 0x02) - cio_write( cio, 0,4); /* Aux_i,j : Auxiliary value */ - j++; - } - } - - len = cio_tell( cio)-lenp; - cio_seek( cio, lenp); - cio_write( cio, len, 4); /* L */ - cio_seek( cio, lenp+len); - - return len; - -} - -int get_num_max_tile_parts( opj_codestream_info_t cstr_info) -{ - int num_max_tp = 0, i; - - for( i=0; i