Filter:   InfoImg
download MpqStream.cs
Language: C#
Copyright: (C) 2006 Foole (fooleau@gmail.com)
LOC: 308
Project Info
mpqtool - Blizzard MPQ Archive Tool(mpqtool)
Server: Google
Type: svn
...\trunk\MpqTool\SCSharp.Mpq\
   BitStream.cs
   Mpq.cs
   MpqArchive.cs
   MpqHuffman.cs
   MpqParserException.cs
   MpqStream.cs
   MpqStructs.cs
   MpqWavCompression.cs
   PKLibDecompress.cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
#define WITH_ZLIB
#define WITH_BZIP

//
// MpqHuffman.cs
//
// Authors:
//		Foole (fooleau@gmail.com)
//
// (C) 2006 Foole (fooleau@gmail.com)
// Based on code from StormLib by Ladislav Zezula
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.IO;
#if WITH_ZLIB
using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
#endif
#if WITH_BZIP
using ICSharpCode.SharpZipLib.BZip2;
#endif

namespace MpqReader
{
    /// <summary>
    /// A Stream based class for reading a file from an MPQ file
    /// </summary>
    public class MpqStream : Stream
    {
        private Stream mStream;
        private int mBlockSize;

        private MpqBlock mBlock;
        private uint[] mBlockPositions;
        private uint mSeed1;

        private long mPosition;
        private byte[] mCurrentData;
        private int mCurrentBlockIndex = -1;

        private MpqStream()
        { }

        internal MpqStream(MpqArchive File, MpqBlock Block)
        {
            mBlock = Block;

            mStream = File.BaseStream;
            mBlockSize = File.BlockSize;

            if(mBlock.IsCompressed)
                LoadBlockPositions();
        }

        // Compressed files start with an array of offsets to make seeking possible
        private void LoadBlockPositions()
        {
            int blockposcount = (int) ((mBlock.FileSize + mBlockSize - 1) / mBlockSize) + 1;

            mBlockPositions = new uint[blockposcount];

            lock(mStream)
            {
                mStream.Seek(mBlock.FilePos, SeekOrigin.Begin);
                BinaryReader br = new BinaryReader(mStream);
                for(int i = 0; i < blockposcount; i++)
                    mBlockPositions[i] = br.ReadUInt32();
            }

            uint blockpossize = (uint) blockposcount * 4;
#if true
            // OW:

            // If the archive if protected some way, perform additional check
            // Sometimes, the file appears not to be encrypted, but it is.
            // Edit: In WoW 1.10+, there's a new flag. With this flag present,
            // there's one additional entry in the block table. If this flag
            // is present, we skip this test to keep the file readable.

            if((mBlock.Flags & MpqFileFlags.FileHasMetadata) == 0)
            {
                if(mBlockPositions[0] != blockpossize)
                    mBlock.Flags |= MpqFileFlags.Encrypted;
            }

            if(mBlock.IsEncrypted)
            {
                if(mSeed1 == 0)
                {
                    mSeed1 = MpqArchive.DetectFileSeed(mBlockPositions, blockpossize);
                    if (mSeed1 == 0)
                        throw new MpqParserException("Unable to determine encyption seed");
                }
                
                MpqArchive.DecryptBlock(mBlockPositions, mSeed1);
                mSeed1++; // Add 1 because the first block is the offset list
            }
#else
            // StormLib takes this to mean the data is encrypted
            if (mBlockPositions[0] != blockpossize)
            {
                if (mSeed1 == 0)
                {
                    mSeed1 = MpqArchive.DetectFileSeed(mBlockPositions, blockpossize);
                    if (mSeed1 == 0)
                        throw new Exception("Unable to determine encyption seed");
                }
                MpqArchive.DecryptBlock(mBlockPositions, mSeed1);
                mSeed1++; // Add 1 because the first block is the offset list
            }
#endif
        }

        private byte[] LoadBlock(int BlockIndex, int ExpectedLength)
        {
            uint offset;
            int toread;

            if (mBlock.IsCompressed)
            {
                offset = mBlockPositions[BlockIndex];
                toread = (int)(mBlockPositions[BlockIndex + 1] - offset);
            }
            else
            {
                offset = (uint)(BlockIndex * mBlockSize);
                toread = ExpectedLength;
            }
            offset += mBlock.FilePos;

            byte[] data = new byte[toread];
            lock (mStream)
            {
                mStream.Seek(offset, SeekOrigin.Begin);
                mStream.Read(data, 0, toread);
            }

            if (mBlock.IsEncrypted && mBlock.FileSize > 3)
            {
                if (mSeed1 == 0)
                {
                    uint value0 = BitConverter.ToUInt32(data, 0);
                    uint value1 = BitConverter.ToUInt32(data, 4);
					mSeed1 = MpqArchive.DetectFileSeed(value0, value1, 0x2fbfbbef, 0x3d3d3d2f); // .J unicode magic
                    if (mSeed1 == 0)
                    {
                        mSeed1 = MpqArchive.DetectFileSeed(value0, value1, 0x3d3d2f2f, 0x3d3d3d3d); // .J ascii
	                    if (mSeed1 == 0)
	                    {
                            mSeed1 = MpqArchive.DetectFileSeed(value0, value1, 0x46464952, mBlock.FileSize - 8); // RIFF
                            if (mSeed1 == 0) throw new MpqParserException("Unable to determine encryption key");
                    	}
                    }
                }
                MpqArchive.DecryptBlock(data, (uint)(mSeed1 + BlockIndex));
            }

            if (mBlock.IsCompressed && data.Length != ExpectedLength)
            {
                if ((mBlock.Flags & MpqFileFlags.CompressedMulti) != 0)
                    data = DecompressMulti(data, ExpectedLength);
                else
                    data = PKDecompress(new MemoryStream(data), ExpectedLength);
            }

            return data;
        }

        #region Stream overrides
        public override bool CanRead
        { get { return true; } }

        public override bool CanSeek
        { get { return true; } }

        public override bool CanWrite
        { get { return false; } }

        public override long Length
        { get { return mBlock.FileSize; } }

        public override long Position
        {
            get
            {
                return mPosition;
            }
            set
            {
                Seek(value, SeekOrigin.Begin);
            }
        }

        public override void Flush()
        {
            // NOP
        }

        public override long Seek(long Offset, SeekOrigin Origin)
        {
            long target;

            switch (Origin)
            {
                case SeekOrigin.Begin:
                    target = Offset;
                    break;
                case SeekOrigin.Current:
                    target = Position + Offset;
                    break;
                case SeekOrigin.End:
                    target = Length + Offset;
                    break;
                default:
                    throw new ArgumentException("Origin", "Invalid SeekOrigin");
            }

            if (target < 0)
                throw new ArgumentOutOfRangeException("Attmpted to Seek before the beginning of the stream");
            if (target >= Length)
                throw new ArgumentOutOfRangeException("Attmpted to Seek beyond the end of the stream");

            mPosition = target;

            return mPosition;
        }

        public override void SetLength(long Value)
        {
            throw new NotSupportedException("SetLength is not supported");
        }

        public override int Read(byte[] Buffer, int Offset, int Count)
        {
            int toread = Count;
            int readtotal = 0;

            while (toread > 0)
            {
                int read = ReadInternal(Buffer, Offset, toread);
                if (read == 0) break;
                readtotal += read;
                Offset += read;
                toread -= read;
            }
            return readtotal;
        }

        private int ReadInternal(byte[] Buffer, int Offset, int Count)
        {
            // OW: avoid reading past the contents of the file
            if (mPosition >= Length)
                return 0;
            
            BufferData();

            int localposition = (int)(mPosition % mBlockSize);
            int bytestocopy = Math.Min(mCurrentData.Length - localposition, Count);
            if (bytestocopy <= 0) return 0;

            Array.Copy(mCurrentData, localposition, Buffer, Offset, bytestocopy);

            mPosition += bytestocopy;
            return bytestocopy;
        }

        public override int ReadByte()
        {
            if (mPosition >= Length) return -1;

            BufferData();

            int localposition = (int)(mPosition % mBlockSize);
            mPosition++;
            return mCurrentData[localposition];
        }

        private void BufferData()
        {
            int requiredblock = (int)(mPosition / mBlockSize);
            if (requiredblock != mCurrentBlockIndex)
            {
                int expectedlength = (int)Math.Min(Length - (requiredblock * mBlockSize), mBlockSize);
                mCurrentData = LoadBlock(requiredblock, expectedlength);
                mCurrentBlockIndex = requiredblock;
            }
        }

        public override void Write(byte[] Buffer, int Offset, int Count)
        {
            throw new NotSupportedException("Writing is not supported");
        }
        #endregion Strem overrides

        /* Compression types in order:
		 *  10 = BZip2
		 *   8 = PKLib
		 *   2 = ZLib
		 *   1 = Huffman
		 *  80 = IMA ADPCM Stereo
		 *  40 = IMA ADPCM Mono
		 */
        private static byte[] DecompressMulti(byte[] Input, int OutputLength)
        {
            Stream sinput = new MemoryStream(Input);

            byte comptype = (byte)sinput.ReadByte();

#if WITH_BZIP
            // BZip2
            if ((comptype & 0x10) != 0)
            {
                byte[] result = BZip2Decompress(sinput, OutputLength);
                comptype &= 0xEF;
                if (comptype == 0) return result;
                sinput = new MemoryStream(result);
            }
#endif

            // PKLib
            if ((comptype & 8) != 0)
            {
                byte[] result = PKDecompress(sinput, OutputLength);
                comptype &= 0xF7;
                if (comptype == 0) return result;
                sinput = new MemoryStream(result);
            }

#if WITH_ZLIB
            // ZLib
            if ((comptype & 2) != 0)
            {
                byte[] result = ZlibDecompress(sinput, OutputLength);
                comptype &= 0xFD;
                if (comptype == 0) return result;
                sinput = new MemoryStream(result);
            }
#endif

            if ((comptype & 1) != 0)
            {
                byte[] result = MpqHuffman.Decompress(sinput);
                comptype &= 0xfe;
                if (comptype == 0) return result;
                sinput = new MemoryStream(result);
            }

            if ((comptype & 0x80) != 0)
            {
                byte[] result = MpqWavCompression.Decompress(sinput, 2);
                comptype &= 0x7f;
                if (comptype == 0) return result;
                sinput = new MemoryStream(result);
            }

            if ((comptype & 0x40) != 0)
            {
                byte[] result = MpqWavCompression.Decompress(sinput, 1);
                comptype &= 0xbf;
                if (comptype == 0) return result;
                sinput = new MemoryStream(result);
            }
            throw new MpqParserException(String.Format("Unhandled compression flags: 0x{0:X}", comptype));
        }

#if WITH_BZIP
        private static byte[] BZip2Decompress(Stream Data, int ExpectedLength)
        {
            MemoryStream output = new MemoryStream();
            BZip2.Decompress(Data, output);
            return output.ToArray();
        }
#endif

        private static byte[] PKDecompress(Stream Data, int ExpectedLength)
        {
            PKLibDecompress pk = new PKLibDecompress(Data);
            return pk.Explode(ExpectedLength);
        }

#if WITH_ZLIB
        private static byte[] ZlibDecompress(Stream Data, int ExpectedLength)
        {
            // This assumes that Zlib won't be used in combination with another compression type
            byte[] Output = new byte[ExpectedLength];
            Stream s = new InflaterInputStream(Data);
            int Offset = 0;
            while (true)
            {
                if (ExpectedLength == 0) break;
                int size = s.Read(Output, Offset, ExpectedLength);
                if (size == 0) break;
                Offset += size;
                ExpectedLength -= size;
            }
            return Output;
        }
#endif
    }
}