Example #1
0
        private void DoInit()
        {
            if (initdone)
            {
                return;
            }

            initdone = true;
            // http://stackoverflow.com/a/2331025/277304
            const int cmf = 0x78;
            var       flg = 218; // sorry about the following lines

            if (CompressLevel >= 5 && CompressLevel <= 6)
            {
                flg = 156;
            }
            else if (CompressLevel >= 3 && CompressLevel <= 4)
            {
                flg = 94;
            }
            else if (CompressLevel <= 2)
            {
                flg = 1;
            }

            flg -= (((cmf * 256) + flg) % 31); // just in case
            if (flg < 0)
            {
                flg += 31;
            }

            RawStream.WriteByte(cmf);
            RawStream.WriteByte((byte)flg);
        }
Example #2
0
        public override void Flush()

        {
            FlushBuffer();

            RawStream.Flush();
        }
Example #3
0
        private async Task <Stream> ApplyConnectionAdaptersAsync(RawStream stream)
        {
            var connectionAdapters = _context.ConnectionAdapters;
            var adapterContext     = new ConnectionAdapterContext(_context.ConnectionContext, stream);

            _adaptedConnections = new List <IAdaptedConnection>(connectionAdapters.Count);

            try
            {
                for (var i = 0; i < connectionAdapters.Count; i++)
                {
                    var adaptedConnection = await connectionAdapters[i].OnConnectionAsync(adapterContext);
                    _adaptedConnections.Add(adaptedConnection);
                    adapterContext = new ConnectionAdapterContext(_context.ConnectionContext, adaptedConnection.ConnectionStream);
                }
            }
            catch (Exception ex)
            {
                Log.LogError(0, ex, $"Uncaught exception from the {nameof(IConnectionAdapter.OnConnectionAsync)} method of an {nameof(IConnectionAdapter)}.");

                return(null);
            }

            return(adapterContext.ConnectionStream);
        }
Example #4
0
        public override void Flush()

        {
            RawStream.Flush();

            m_Uncomp.Flush();
        }
Example #5
0
        private async Task <Stream> ApplyConnectionAdaptersAsync()
        {
            Debug.Assert(_http1Connection != null, $"{nameof(_http1Connection)} is null");
            Debug.Assert(_http2Connection != null, $"{nameof(_http2Connection)} is null");

            var connectionAdapters = _context.ConnectionAdapters;
            var stream             = new RawStream(_context.Transport.Input, _context.Transport.Output);
            var adapterContext     = new ConnectionAdapterContext(_context.ConnectionFeatures, stream);

            _adaptedConnections = new List <IAdaptedConnection>(connectionAdapters.Count);

            try
            {
                for (var i = 0; i < connectionAdapters.Count; i++)
                {
                    var adaptedConnection = await connectionAdapters[i].OnConnectionAsync(adapterContext);
                    _adaptedConnections.Add(adaptedConnection);
                    adapterContext = new ConnectionAdapterContext(_context.ConnectionFeatures, adaptedConnection.ConnectionStream);
                }
            }
            catch (Exception ex)
            {
                Log.LogError(0, ex, $"Uncaught exception from the {nameof(IConnectionAdapter.OnConnectionAsync)} method of an {nameof(IConnectionAdapter)}.");

                return(null);
            }

            return(adapterContext.ConnectionStream);
        }
 public void Dispose()
 {
     if (!_disposed)
     {
         RawStream.Close();
         _disposed = true;
     }
 }
        public override int Read(byte[] buffer, int offset, int length)
        {
            // Todo: count already read bytes from previous Read calls and use it to compute remaining expected length
            int maxLength    = (int)Math.Min(length, ContentLength ?? length);
            int actualLength = RawStream.Read(buffer, offset, maxLength);

            return(actualLength);
        }
Example #8
0
        protected override void Dispose(bool disposing)
        {
            if (disposing && !LeaveOpen)
            {
                RawStream.Dispose();
            }

            base.Dispose(disposing);
        }
Example #9
0
        public override long Seek(long offset, SeekOrigin origin)
        {
            if (m_Compressed)
            {
                long absPos = offset;
                if (origin == SeekOrigin.Current)
                {
                    absPos += m_Uncomp.Position;
                }

                if (absPos < 0)
                {
                    throw new Exception("Cannot seek past the begining of the stream.");
                }

                long pos = m_Uncomp.Position;
                m_Uncomp.Seek(0, SeekOrigin.End);

                while ((origin == SeekOrigin.End || absPos >= m_Uncomp.Length) && RawStream.Position < RawStream.Length)
                {
                    int block = Raw.ReadInt32();
                    int ucLen = Raw.ReadInt32();
                    if (m_ReadBuff == null || m_ReadBuff.Length < block)
                    {
                        m_ReadBuff = new byte[block];
                    }

                    if (m_CompBuff == null || m_CompBuff.Length < ucLen)
                    {
                        m_CompBuff = new byte[ucLen];
                    }
                    else
                    {
                        ucLen = m_CompBuff.Length;
                    }

                    Raw.Read(m_ReadBuff, 0, block);

                    ZLibError error = ZLib.uncompress(m_CompBuff, ref ucLen, m_ReadBuff, block);
                    if (error != ZLibError.Z_OK)
                    {
                        throw new Exception("ZLib error uncompressing: " + error.ToString());
                    }

                    m_Uncomp.Write(m_CompBuff, 0, ucLen);
                }

                m_Uncomp.Position = pos;
                return(m_Uncomp.Seek(offset, origin));
            }
            else
            {
                return(RawStream.Seek(offset, origin));
            }
        }
Example #10
0
        public override int Read(byte[] buffer, int offset, int count)
        {
            if (m_Compressed)
            {
                long pos = m_Uncomp.Position;
                m_Uncomp.Seek(0, SeekOrigin.End);

                while (pos + count > m_Uncomp.Length && RawStream.Position + 8 < RawStream.Length)
                {
                    int block = Raw.ReadInt32();
                    int ucLen = Raw.ReadInt32();

                    if (block > 0x10000000 || block <= 0 || ucLen > 0x10000000 || ucLen <= 0)
                    {
                        break;
                    }

                    if (RawStream.Position + block > RawStream.Length)
                    {
                        break;
                    }

                    if (m_ReadBuff == null || m_ReadBuff.Length < block)
                    {
                        m_ReadBuff = new byte[block];
                    }

                    if (m_CompBuff == null || m_CompBuff.Length < ucLen)
                    {
                        m_CompBuff = new byte[ucLen];
                    }
                    else
                    {
                        ucLen = m_CompBuff.Length;
                    }

                    Raw.Read(m_ReadBuff, 0, block);

                    ZLibError error = ZLib.uncompress(m_CompBuff, ref ucLen, m_ReadBuff, block);
                    if (error != ZLibError.Z_OK)
                    {
                        throw new Exception("ZLib error uncompressing: " + error.ToString());
                    }

                    m_Uncomp.Write(m_CompBuff, 0, ucLen);
                }

                m_Uncomp.Position = pos;
                return(m_Uncomp.Read(buffer, offset, count));
            }
            else
            {
                return(RawStream.Read(buffer, offset, count));
            }
        }
Example #11
0
 public override long Seek(long offset, SeekOrigin origin)
 {
     if (m_IsCompressed)
     {
         return(m_Buffer.Seek(offset, origin));
     }
     else
     {
         return(RawStream.Seek(offset, origin));
     }
 }
Example #12
0
        internal NodeHeader ReadTree(ulong logical, byte level)
        {
            var physical = MapToPhysical(logical);

            RawStream.Seek((long)physical, SeekOrigin.Begin);
            var dataSize = level > 0 ? SuperBlock.NodeSize : SuperBlock.LeafSize;
            var buffer   = new byte[dataSize];

            RawStream.Read(buffer, 0, buffer.Length);
            var result = NodeHeader.Create(buffer, 0);

            VerifyChecksum(result.Checksum, buffer, 0x20, (int)dataSize - 0x20);
            return(result);
        }
Example #13
0
 public override void Write(byte[] buffer, int offset, int count)
 {
     if (m_IsCompressed)
     {
         m_Buffer.Write(buffer, offset, count);
         if (m_Buffer.Position >= m_BlockSize)
         {
             FlushBuffer();
         }
     }
     else
     {
         RawStream.Write(buffer, offset, count);
     }
 }
Example #14
0
 public override void WriteByte(byte value)
 {
     if (m_IsCompressed)
     {
         m_Buffer.WriteByte(value);
         if (m_Buffer.Position >= m_BlockSize)
         {
             FlushBuffer();
         }
     }
     else
     {
         RawStream.WriteByte(value);
     }
 }
Example #15
0
        public SoundHandle PlaySound(int id, byte[] sound, int size)
        {
            var flags = AudioFlags.Unsigned;
            var sizeOfDataFileHeader = ServiceLocator.Platform.SizeOf <DataFileHeader>();

            size -= sizeOfDataFileHeader;
            var buffer = new byte[size];

            Array.Copy(sound, sizeOfDataFileHeader, buffer, 0, size);

            _mixer.StopID(id);

            var stream = new RawStream(flags, 11025, true, new MemoryStream(buffer, 0, size));

            return(_mixer.PlayStream(SoundType.SFX, stream, id));
        }
Example #16
0
        public async Task Connect()
        {
            Socket mSocket  = null;
            var    endpoint = this.Endpoint;

            if (ShouldTryIPv6(endpoint))
            {
                try
                {
                    mSocket = await ConnectUsingIPv6(endpoint, m_socketFactory, m_connectionTimeout);
                }
                catch (ConnectFailureException)
                {
                    mSocket = null;
                }
            }

            if (mSocket == null && endpoint.AddressFamily != AddressFamily.InterNetworkV6)
            {
                mSocket = await ConnectUsingIPv4(endpoint, m_socketFactory, m_connectionTimeout);
            }

            socketConnection = new SocketConnection(mSocket)
            {
                ReceiveTimeout = m_readTimeout,
                SendTimeout    = m_writeTimeout
            };

            Stream netstream = new RawStream(socketConnection.Transport.Input, socketConnection.Transport.Output);

            if (endpoint.Ssl.Enabled)
            {
                try
                {
                    netstream = await SslHelper.TcpUpgrade(netstream, endpoint.Ssl);
                }
                catch (Exception)
                {
                    Close();
                    throw;
                }
            }

            m_netstream = netstream;

            _ = socketConnection.StartAsync();
        }
 protected override void Dispose(bool disposing)
 {
     if (disposing)
     {
         if (_decStream != null)
         {
             _decStream.Close();
             _decStream = null;
         }
         if (_rawStream != null)
         {
             _rawStream.Close();
             _rawStream = null;
         }
     }
     _streamsBytes = null;
 }
        public override int Read(byte[] buffer, int offset, int length)
        {
            if (EndOfDataReached)
            {
                return(0);
            }

            int totalRead = 0;

            while (totalRead < length)
            {
                if (CurrentChunkRemaining == 0)
                {
                    if (CurrentChunkLength > 0)
                    {
                        // Read the empty line that follows the previous chunk
                        HttpLineReader.ReadLine(RawStream);
                    }

                    NextChunk();

                    // Chunk length zero means end of data.
                    if (CurrentChunkLength == 0)
                    {
                        Close();
                        EndOfDataReached = true;
                        break;
                    }
                }

                int maxLength    = (int)Math.Min(length - totalRead, CurrentChunkRemaining);
                int actualLength = RawStream.Read(buffer, offset, maxLength);
                totalRead += actualLength;
                offset    += actualLength;

                CurrentChunkRemaining -= actualLength;

                if (actualLength == 0)
                {
                    break;
                }
            }

            return(totalRead);
        }
Example #19
0
        public bool StartSpeech(ushort textNum)
        {
            if (!SystemVars.Instance.SystemFlags.HasFlag(SystemFlags.AllowSpeech))
            {
                return(false);
            }
            var speechFileNum = (ushort)(_speechConvertTable[textNum >> 12] + (textNum & 0xFFF));

            var speechData = _skyDisk.LoadFile(speechFileNum + 50000);

            if (speechData == null)
            {
                // TODO: debug(9, "File %d (speechFile %d from section %d) wasn't found", speechFileNum + 50000, textNum & 0xFFF, textNum >> 12);
                return(false);
            }

            var header     = ServiceLocator.Platform.ToStructure <DataFileHeader>(speechData, 0);
            var speechSize = header.s_tot_size - ServiceLocator.Platform.SizeOf <DataFileHeader>();
            var playBuffer = new byte[speechSize];

            Array.Copy(speechData, ServiceLocator.Platform.SizeOf <DataFileHeader>(), playBuffer, 0, speechSize);

            // Workaround for BASS bug #897775 - some voice-overs are played at
            // half speed in 0.0368 (the freeware CD version), in 0.0372 they sound
            // just fine.

            int rate;

            if (_skyDisk.DetermineGameVersion().Version.Minor == 368 && (textNum == 20905 || textNum == 20906))
            {
                rate = 22050;
            }
            else
            {
                rate = 11025;
            }

            _mixer.StopID(SoundSpeech);

            var stream = new RawStream(AudioFlags.Unsigned, rate, true, new MemoryStream(playBuffer, 0, speechSize));

            _ingameSpeech = _mixer.PlayStream(SoundType.Speech, stream, SoundSpeech);
            return(true);
        }
Example #20
0
        public void StartChannel(int id, byte[] data, int size, int rate, int vol, int loopStart = 0, int loopEnd = 0, int pan = 0)
        {
            int i;

            if (id == 0)
            {
                Debug.WriteLine("player_mod - attempted to start channel id 0");
            }

            for (i = 0; i < MOD_MAXCHANS; i++)
            {
                if (_channels[i].id == 0)
                {
                    break;
                }
            }
            if (i == MOD_MAXCHANS)
            {
                Debug.WriteLine("player_mod - too many music channels playing ({0} max)", MOD_MAXCHANS);
                return;
            }
            _channels[i].id   = id;
            _channels[i].vol  = (byte)vol;
            _channels[i].pan  = (sbyte)pan;
            _channels[i].freq = (ushort)rate;
            _channels[i].ctr  = 0;

            var stream = new RawStream(AudioFlags.None, rate, true, new MemoryStream(data));

            if (loopStart != loopEnd)
            {
                _channels[i].input = new SubLoopingAudioStream(stream, 0, new Timestamp(0, loopStart, rate), new Timestamp(0, loopEnd, rate));
            }
            else
            {
                _channels[i].input = stream;
            }

            // read the first sample
            var sample = new short[1];

            _channels[i].input.ReadBuffer(sample, 1);
            _channels[i].pos = sample[0];
        }
Example #21
0
        public IEnumerable <short[, ]> Run()
        {
            if (Format.Channels <= 0)
            {
                yield break;
            }

            if (ProgressNotifier != null)
            {
                ProgressNotifier.Reset();
            }

            RawStream.Seek(0, SeekMode.Origin);
            uint decodedSize = 0;

            while (decodedSize < RawStream.Length)
            {
                // Calculate the size of the block
                int blockLen = 0x2000;
                if (decodedSize + blockLen > RawStream.Length)
                {
                    blockLen = (int)(RawStream.Length - decodedSize);
                }

                // Decode
                yield return(DecodeBlock(blockLen));

                // Increase decoded size
                decodedSize += (uint)blockLen;

                // Show progress
                if (ProgressNotifier != null)
                {
                    ProgressNotifier.Update((int)decodedSize, RawStream.Length);
                }
            }

            if (ProgressNotifier != null)
            {
                ProgressNotifier.End();
            }
        }
        public override int Read(byte[] buffer, int offset, int length)
        {
            if (RemainingContentLength != null && RemainingContentLength <= 0)
            {
                Close();
                return(0);
            }

            int maxLength    = (int)Math.Min(length, RemainingContentLength ?? length);
            int actualLength = RawStream.Read(buffer, offset, maxLength);

            if (RemainingContentLength != null)
            {
                RemainingContentLength -= actualLength;
            }

            if (actualLength == 0)
            {
                Close();
            }

            return(actualLength);
        }
Example #23
0
        /// <summary>
        /// Finds the childless tags.
        /// </summary>
        /// <param name="tagName">Name of the tag.</param>
        /// <param name="caseSensitive">if set to <c>true</c> [case sensitive].</param>
        /// <returns></returns>
        public IList <string> FindChildlessTags(string tagName, bool caseSensitive)
        {
            IList <string> ret           = new List <string>();
            string         searchSubject = caseSensitive ? RawStream : RawStreamLowercase;

            if (!caseSensitive)
            {
                tagName = tagName.ToLower();
            }
            if (!tagName.StartsWith("<"))
            {
                tagName = "<" + tagName;
            }
            if (searchSubject != null)
            {
                int startpos = 0;
                while (true)
                {
                    int startIndex = searchSubject.IndexOf(tagName, startpos);
                    if (startIndex == -1)
                    {
                        break;
                    }
                    int endIndex = searchSubject.IndexOf(">", startIndex);
                    if (endIndex == -1)
                    {
                        break;
                    }

                    ret.Add(RawStream.Substring(startIndex, endIndex - startIndex + 1));

                    startpos = endIndex + 1;
                }
            }
            return(ret);
        }
        short[] DecodeChunk(int channel)
        {
            var reader = new DataReader(RawStream);

            // Get header
            RawStream.Seek(0xF, SeekMode.Current);
            sbyte header = reader.ReadSByte();

            header = (sbyte)(header ^ 0x80);
            RawStream.Seek(-0x10, SeekMode.Current);

            // ... get scale
            byte scale = (byte)(header & 0xF);

            // ... get coefficients
            int    coefIdx = header >> 4;
            double coef1   = CoefficientTable[coefIdx, 0];
            double coef2   = CoefficientTable[coefIdx, 1];

            // Get all the samples in the chunk
            uint chunkData = 0;
            var  samples   = new short[Format.SamplesPerChunk];

            for (int i = 0; i < Format.SamplesPerChunk; i++, chunkData >>= 4)
            {
                if (i % 8 == 0)
                {
                    chunkData = reader.ReadUInt32() ^ 0x80808080;
                }

                byte value = (byte)(chunkData & 0xF);
                samples[i] = DecodeSample(value, scale, coef1, coef2, channel);
            }

            return(samples);
        }
Example #25
0
        public override void Close()
        {
            if (!initdone)
            {
                DoInit(); // can happen if never called write
            }

            if (closed)
            {
                return;
            }

            closed = true;
            // sigh ... no only must I close the parent stream to force a flush, but I must save a reference
            // raw stream because (apparently) Close() sets it to null (shame on you, MS developers)
            if (deflateStream is object)
            {
                deflateStream.Close();
            }
            else
            {         // second hack: empty input?
                RawStream.WriteByte(3);
                RawStream.WriteByte(0);
            }
            // add crc
            var crcv = adler32.GetValue();

            RawStream.WriteByte((byte)((crcv >> 24) & 0xFF));
            RawStream.WriteByte((byte)((crcv >> 16) & 0xFF));
            RawStream.WriteByte((byte)((crcv >> 8) & 0xFF));
            RawStream.WriteByte((byte)(crcv & 0xFF));
            if (!LeaveOpen)
            {
                RawStream.Close();
            }
        }
Example #26
0
        public override void SetLength(long value)

        {
            RawStream.SetLength(value);
        }
Example #27
0
        public void QueueBuffer(byte[] data, int size, bool disposeAfterUse, AudioFlags flags)
        {
            var stream = new RawStream(flags, Rate, disposeAfterUse, new MemoryStream(data, 0, size));

            QueueAudioStream(stream, true);
        }
Example #28
0
        public bool StartSpeech(ushort roomNo, ushort localNo)
        {
            if (_cowHeader == null || ServiceLocator.AudioManager == null)
            {
                // TODO: warning("Sound::startSpeech: COW file isn't open");
                return(false);
            }

            uint locIndex   = 0xFFFFFFFF;
            int  sampleSize = 0;
            uint index      = 0;

            //            if (_cowMode == CowPSX)
            //            {
            //                Common::File file;
            //                uint16 i;

            //                if (!file.open("speech.lis"))
            //                {
            //                    warning("Could not open speech.lis");
            //                    return false;
            //                }

            //                for (i = 0; !file.eos() && !file.err(); i++)
            //                    if (file.readUint16LE() == roomNo)
            //                    {
            //                        locIndex = i;
            //                        break;
            //                    }
            //                file.close();

            //                if (locIndex == 0xFFFFFFFF)
            //                {
            //                    warning("Could not find room %d in speech.lis", roomNo);
            //                    return false;
            //                }

            //                if (!file.open("speech.inf"))
            //                {
            //                    warning("Could not open speech.inf");
            //                    return false;
            //                }

            //                uint16 numRooms = file.readUint16LE(); // Read number of rooms referenced in this file

            //                file.seek(locIndex * 4 + 2); // 4 bytes per room, skip first 2 bytes

            //                uint16 numLines = file.readUint16LE();
            //                uint16 roomOffset = file.readUint16LE();

            //                file.seek(2 + numRooms * 4 + roomOffset * 2); // The offset is in terms of uint16's, so multiply by 2. Skip the room indexes too.

            //                locIndex = 0xFFFFFFFF;

            //                for (i = 0; i < numLines; i++)
            //                    if (file.readUint16LE() == localNo)
            //                    {
            //                        locIndex = i;
            //                        break;
            //                    }

            //                if (locIndex == 0xFFFFFFFF)
            //                {
            //                    warning("Could not find local number %d in room %d in speech.inf", roomNo, localNo);
            //                    return false;
            //                }

            //                file.close();

            //                index = _cowHeader[(roomOffset + locIndex) * 2];
            //                sampleSize = _cowHeader[(roomOffset + locIndex) * 2 + 1];
            //            }
            //            else {
            locIndex   = _cowHeader[roomNo] >> 2;
            sampleSize = (int)_cowHeader[(int)(locIndex + (localNo * 2))];
            index      = _cowHeader[(int)(locIndex + (localNo * 2) - 1)];
            //            }

            //            debug(6, "startSpeech(%d, %d): locIndex %d, sampleSize %d, index %d", roomNo, localNo, locIndex, sampleSize, index);

            IAudioStream stream = null;

            if (sampleSize != 0)
            {
                byte  speechVol = (byte)((_speechVolR + _speechVolL) / 2);
                sbyte speechPan = (sbyte)((_speechVolR - _speechVolL) / 2);
                if ((_cowMode == CowMode.CowWave) || (_cowMode == CowMode.CowDemo))
                {
                    uint size;
                    var  data = UncompressSpeech(index + _cowHeaderSize, (uint)sampleSize, out size);
                    if (data != null)
                    {
                        stream        = new RawStream(SPEECH_FLAGS, 11025, true, new MemoryStream(data.Data, data.Offset, (int)size));
                        _speechHandle = _mixer.PlayStream(SoundType.Speech, stream, SOUND_SPEECH_ID, speechVol, speechPan);
                    }
                }
                //                else if (_cowMode == CowPSX && sampleSize != 0xffffffff)
                //                {
                //                    _cowFile.seek(index * 2048);
                //                    Common::SeekableReadStream* tmp = _cowFile.readStream(sampleSize);
                //                    assert(tmp);
                //                    stream = Audio::makeXAStream(tmp, 11025);
                //                    _mixer->playStream(Audio::Mixer::kSpeechSoundType, &_speechHandle, stream, SOUND_SPEECH_ID, speechVol, speechPan);
                //                    // with compressed audio, we can't calculate the wave volume.
                //                    // so default to talking.
                //                    for (int cnt = 0; cnt < 480; cnt++)
                //                        _waveVolume[cnt] = true;
                //                    _waveVolPos = 0;
                //                }
                else if (_cowMode == CowMode.CowFLAC)
                {
                    _cowFile.BaseStream.Seek(index, SeekOrigin.Begin);
                    var tmp = _cowFile.ReadBytes(sampleSize);
                    stream = ServiceLocator.AudioManager.MakeFlacStream(new MemoryStream(tmp));
                    if (stream != null)
                    {
                        _speechHandle = _mixer.PlayStream(SoundType.Speech, stream, SOUND_SPEECH_ID, speechVol, speechPan);
                        // with compressed audio, we can't calculate the wave volume.
                        // so default to talking.
                        for (int cnt = 0; cnt < 480; cnt++)
                        {
                            _waveVolume[cnt] = true;
                        }
                        _waveVolPos = 0;
                    }
                }
                else if (_cowMode == CowMode.CowVorbis)
                {
                    _cowFile.BaseStream.Seek(index, SeekOrigin.Begin);
                    var tmp = _cowFile.ReadBytes(sampleSize);
                    stream = ServiceLocator.AudioManager.MakeVorbisStream(new MemoryStream(tmp));
                    if (stream != null)
                    {
                        _speechHandle = _mixer.PlayStream(SoundType.Speech, stream, SOUND_SPEECH_ID, speechVol, speechPan);
                        // with compressed audio, we can't calculate the wave volume.
                        // so default to talking.
                        for (int cnt = 0; cnt < 480; cnt++)
                        {
                            _waveVolume[cnt] = true;
                        }
                        _waveVolPos = 0;
                    }
                }
                else if (_cowMode == CowMode.CowMP3)
                {
                    _cowFile.BaseStream.Seek(index, SeekOrigin.Begin);
                    var tmp = _cowFile.ReadBytes(sampleSize);
                    stream = ServiceLocator.AudioManager.MakeMp3Stream(new MemoryStream(tmp));
                    if (stream != null)
                    {
                        _speechHandle = _mixer.PlayStream(SoundType.Speech, stream, SOUND_SPEECH_ID, speechVol, speechPan);
                        // with compressed audio, we can't calculate the wave volume.
                        // so default to talking.
                        for (int cnt = 0; cnt < 480; cnt++)
                        {
                            _waveVolume[cnt] = true;
                        }
                        _waveVolPos = 0;
                    }
                }
                return(true);
            }
            else
            {
                return(false);
            }
        }
Example #29
0
        public override void LoadRaw()
        {
            ushort[,] vpred = new ushort[2, 2];
            ushort[] hpred = new ushort[2];
            ushort   csize;
            int      step  = 0;
            int      huff  = 0;
            int      split = 0;
            int      row;

            RawStream ifp = state.ifp;

            ifp.Seek(state.meta_offset, SeekOrigin.Begin);
            ushort ver0 = (ushort)ifp.ReadByte();
            ushort ver1 = (ushort)ifp.ReadByte();

            if (ver0 == 0x49 || ver1 == 0x58)
            {
                ifp.Seek(2110, SeekOrigin.Current);
            }

            if (ver0 == 0x46)
            {
                huff = 2;
            }
            if (state.tiff_bps == 14)
            {
                huff += 3;
            }

            vpred[0, 0] = ifp.get2();
            vpred[0, 1] = ifp.get2();
            vpred[1, 0] = ifp.get2();
            vpred[1, 1] = ifp.get2();

            int max = 1 << state.tiff_bps & 0x7fff;

            if ((csize = ifp.get2()) > 1)
            {
                step = max / (csize - 1);
            }
            if (ver0 == 0x44 && ver1 == 0x20 && step > 0)
            {
                int i;
                for (i = 0; i < csize; i++)
                {
                    state.curve[i * step] = ifp.get2();
                }

                for (i = 0; i < max; i++)
                {
                    state.curve[i] = (ushort)((state.curve[i - i % step] * (step - i % step) + state.curve[i - i % step + step] * (i % step)) / step);
                }

                ifp.Seek(state.meta_offset + 562, SeekOrigin.Begin);
                split = ifp.get2();
            }
            else if (ver0 != 0x46 && csize <= 0x4001)
            {
                max = csize;
                ifp.ReadShorts(state.curve, max);
            }

            int         tempIdx = 0;
            HuffmanTree htree   = new HuffmanTree(nikon_tree[huff], ref tempIdx);

            ifp.Seek(state.data_offset, SeekOrigin.Begin);
            ifp.ResetBits();

            for (row = 0; row < state.height; row++)
            {
                if (split != 0 && row == split)
                {
                    tempIdx = 0;
                    htree   = new HuffmanTree(nikon_tree[huff], ref tempIdx);
                }

                for (int col = 0; col < state.raw_width; col++)
                {
                    int leaf = htree.ReadNextSymbolLength(ifp);
                    int len  = leaf & 15;
                    int shl  = leaf >> 4;
                    int diff = (((int)ifp.GetBits(len - shl) << 1) + 1) << shl >> 1;
                    if ((diff & (1 << (len - 1))) == 0)
                    {
                        diff -= (1 << len) - (shl == 0 ? 1 : 0);
                    }

                    if (col < 2)
                    {
                        vpred[row & 1, col] = (ushort)(vpred[row & 1, col] + diff);
                        hpred[col]          = vpred[row & 1, col];
                    }
                    else
                    {
                        hpred[col & 1] = (ushort)(hpred[col & 1] + diff);
                    }

                    if (hpred[col & 1] >= max)
                    {
                        throw new Exception("derror()");
                    }

                    if ((uint)(col - state.left_margin) < state.width)
                    {
                        state.BAYER_set(row, col - state.left_margin, state.curve[hpred[col & 1] & 0x3fff]);
                    }
                }
            }
        }
Example #30
0
        private bool NextPart(ushort[] data, ref int i)
        {
            // return false means cancel intro
            var command = data[i++];

            switch (command)
            {
            case SHOWSCREEN:
                _skyScreen.ShowScreen(data[i++]);
                return(true);

            case FADEUP:
                _skyScreen.PaletteFadeUp(data[i++]);
                _relDelay += 32 * 20;     // hack: the screen uses a seperate delay function for the
                                          // blocking fadeups. So add 32*20 msecs to out delay counter.
                return(true);

            case FADEDOWN:
                _skyScreen.FnFadeDown(0);
                _relDelay += 32 * 20;     // hack: see above.
                return(true);

            case DELAY:
                if (!EscDelay(data[i++]))
                {
                    return(false);
                }
                return(true);

            case DOFLIRT:
                _skyScreen.StartSequence(data[i++]);
                while (_skyScreen.SequenceRunning())
                {
                    if (!EscDelay(50))
                    {
                        return(false);
                    }
                }
                return(true);

            case SCROLLFLIRT:
                return(FloppyScrollFlirt());

            case COMMANDFLIRT:
                return(CommandFlirt(data, ref i));

            case STOPFLIRT:
                _skyScreen.StopSequence();
                return(true);

            case STARTMUSIC:
                _skyMusic.StartMusic(data[i++]);
                return(true);

            case WAITMUSIC:
                while (_skyMusic.IsPlaying)
                {
                    if (!EscDelay(50))
                    {
                        return(false);
                    }
                }
                return(true);

            case BGFLIRT:
                _skyScreen.StartSequence(data[i++]);
                return(true);

            case WAITFLIRT:
                while (_skyScreen.SequenceRunning())
                {
                    if (!EscDelay(50))
                    {
                        return(false);
                    }
                }
                return(true);

            case PLAYVOICE:
            {
                if (!EscDelay(200))
                {
                    return(false);
                }
                var vData = _skyDisk.LoadFile(data[i++]);
                // HACK: Fill the header with silence. We should
                // probably use _skySound instead of calling playStream()
                // directly, but this will have to do for now.
                vData.Set(0, 127, ServiceLocator.Platform.SizeOf <DataFileHeader>());

                var stream = new RawStream(AudioFlags.Unsigned, 11025, true, new MemoryStream(vData));
                _voice = _mixer.PlayStream(SoundType.Speech, stream, Sound.SoundVoice);
            }
                return(true);

            case WAITVOICE:
                while (_mixer.IsSoundHandleActive(_voice))
                {
                    if (!EscDelay(50))
                    {
                        return(false);
                    }
                }
                return(true);

            case LOADBG:
                _mixer.StopID(Sound.SoundBg);
                _bgBuf = _skyDisk.LoadFile(data[i++]);
                return(true);

            case LOOPBG:
            {
                _mixer.StopID(Sound.SoundBg);
                var stream = new RawStream(AudioFlags.Unsigned, 11025, false, new MemoryStream(_bgBuf, 256, _bgBuf.Length - 768));
                _bgSfx = _mixer.PlayStream(SoundType.SFX, new LoopingAudioStream(stream, 0), Sound.SoundBg);
            }
                return(true);

            case PLAYBG:
            {
                _mixer.StopID(Sound.SoundBg);
                var stream = new RawStream(AudioFlags.Unsigned, 11025, false, new MemoryStream(_bgBuf, 256, _bgBuf.Length - 768));
                _bgSfx = _mixer.PlayStream(SoundType.SFX, stream, Sound.SoundBg);
            }
                return(true);

            case STOPBG:
                _mixer.StopID(Sound.SoundBg);
                return(true);

            default:
                throw new NotSupportedException(string.Format("Unknown intro command {0:X2}", command));
            }
        }