diff --git a/3rdparty/SoundTouch/AAFilter.cpp b/3rdparty/SoundTouch/AAFilter.cpp index c73b2c60b8..860f7d5223 100644 --- a/3rdparty/SoundTouch/AAFilter.cpp +++ b/3rdparty/SoundTouch/AAFilter.cpp @@ -1,9 +1,9 @@ //////////////////////////////////////////////////////////////////////////////// /// /// FIR low-pass (anti-alias) filter with filter coefficient design routine and -/// MMX optimization. -/// -/// Anti-alias filter is used to prevent folding of high frequencies when +/// MMX optimization. +/// +/// Anti-alias filter is used to prevent folding of high frequencies when /// transposing the sample rate with interpolation. /// /// Author : Copyright (c) Olli Parviainen @@ -12,7 +12,7 @@ /// //////////////////////////////////////////////////////////////////////////////// // -// Last changed : $Date: 2009-01-11 13:34:24 +0200 (Sun, 11 Jan 2009) $ +// Last changed : $Date: 2009-01-11 09:34:24 -0200 (dom, 11 jan 2009) $ // File revision : $Revision: 4 $ // // $Id: AAFilter.cpp 45 2009-01-11 11:34:24Z oparviai $ @@ -112,21 +112,21 @@ void AAFilter::calculateCoeffs() work = new double[length]; coeffs = new SAMPLETYPE[length]; - fc2 = 2.0 * cutoffFreq; + fc2 = 2.0 * cutoffFreq; wc = PI * fc2; tempCoeff = TWOPI / (double)length; sum = 0; - for (i = 0; i < length; i ++) + for (i = 0; i < length; i ++) { cntTemp = (double)i - (double)(length / 2); temp = cntTemp * wc; - if (temp != 0) + if (temp != 0) { h = fc2 * sin(temp) / temp; // sinc function - } - else + } + else { h = 1.0; } @@ -135,7 +135,7 @@ void AAFilter::calculateCoeffs() temp = w * h; work[i] = temp; - // calc net sum of coefficients + // calc net sum of coefficients sum += temp; } @@ -151,7 +151,7 @@ void AAFilter::calculateCoeffs() // divided by 16384 scaleCoeff = 16384.0f / sum; - for (i = 0; i < length; i ++) + for (i = 0; i < length; i ++) { // scale & round to nearest integer temp = work[i] * scaleCoeff; @@ -169,8 +169,8 @@ void AAFilter::calculateCoeffs() } -// Applies the filter to the given sequence of samples. -// Note : The amount of outputted samples is by value of 'filter length' +// Applies the filter to the given sequence of samples. +// Note : The amount of outputted samples is by value of 'filter length' // smaller than the amount of input samples. uint AAFilter::evaluate(SAMPLETYPE *dest, const SAMPLETYPE *src, uint numSamples, uint numChannels) const { diff --git a/3rdparty/SoundTouch/AAFilter.h b/3rdparty/SoundTouch/AAFilter.h index d92a3eac59..6b885e371c 100644 --- a/3rdparty/SoundTouch/AAFilter.h +++ b/3rdparty/SoundTouch/AAFilter.h @@ -1,10 +1,10 @@ //////////////////////////////////////////////////////////////////////////////// /// -/// Sampled sound tempo changer/time stretch algorithm. Changes the sound tempo -/// while maintaining the original pitch by using a time domain WSOLA-like method +/// Sampled sound tempo changer/time stretch algorithm. Changes the sound tempo +/// while maintaining the original pitch by using a time domain WSOLA-like method /// with several performance-increasing tweaks. /// -/// Anti-alias filter is used to prevent folding of high frequencies when +/// Anti-alias filter is used to prevent folding of high frequencies when /// transposing the sample rate with interpolation. /// /// Author : Copyright (c) Olli Parviainen @@ -13,7 +13,7 @@ /// //////////////////////////////////////////////////////////////////////////////// // -// Last changed : $Date: 2008-02-10 18:26:55 +0200 (Sun, 10 Feb 2008) $ +// Last changed : $Date: 2008-02-10 14:26:55 -0200 (dom, 10 fev 2008) $ // File revision : $Revision: 4 $ // // $Id: AAFilter.h 11 2008-02-10 16:26:55Z oparviai $ @@ -67,8 +67,8 @@ public: ~AAFilter(); - /// Sets new anti-alias filter cut-off edge frequency, scaled to sampling - /// frequency (nyquist frequency = 0.5). The filter will cut off the + /// Sets new anti-alias filter cut-off edge frequency, scaled to sampling + /// frequency (nyquist frequency = 0.5). The filter will cut off the /// frequencies than that. void setCutoffFreq(double newCutoffFreq); @@ -77,12 +77,12 @@ public: uint getLength() const; - /// Applies the filter to the given sequence of samples. - /// Note : The amount of outputted samples is by value of 'filter length' + /// Applies the filter to the given sequence of samples. + /// Note : The amount of outputted samples is by value of 'filter length' /// smaller than the amount of input samples. - uint evaluate(SAMPLETYPE *dest, - const SAMPLETYPE *src, - uint numSamples, + uint evaluate(SAMPLETYPE *dest, + const SAMPLETYPE *src, + uint numSamples, uint numChannels) const; }; diff --git a/3rdparty/SoundTouch/BPMDetect.cpp b/3rdparty/SoundTouch/BPMDetect.cpp new file mode 100644 index 0000000000..34dbb4730a --- /dev/null +++ b/3rdparty/SoundTouch/BPMDetect.cpp @@ -0,0 +1,370 @@ +//////////////////////////////////////////////////////////////////////////////// +/// +/// Beats-per-minute (BPM) detection routine. +/// +/// The beat detection algorithm works as follows: +/// - Use function 'inputSamples' to input a chunks of samples to the class for +/// analysis. It's a good idea to enter a large sound file or stream in smallish +/// chunks of around few kilosamples in order not to extinguish too much RAM memory. +/// - Inputted sound data is decimated to approx 500 Hz to reduce calculation burden, +/// which is basically ok as low (bass) frequencies mostly determine the beat rate. +/// Simple averaging is used for anti-alias filtering because the resulting signal +/// quality isn't of that high importance. +/// - Decimated sound data is enveloped, i.e. the amplitude shape is detected by +/// taking absolute value that's smoothed by sliding average. Signal levels that +/// are below a couple of times the general RMS amplitude level are cut away to +/// leave only notable peaks there. +/// - Repeating sound patterns (e.g. beats) are detected by calculating short-term +/// autocorrelation function of the enveloped signal. +/// - After whole sound data file has been analyzed as above, the bpm level is +/// detected by function 'getBpm' that finds the highest peak of the autocorrelation +/// function, calculates it's precise location and converts this reading to bpm's. +/// +/// Author : Copyright (c) Olli Parviainen +/// Author e-mail : oparviai 'at' iki.fi +/// SoundTouch WWW: http://www.surina.net/soundtouch +/// +//////////////////////////////////////////////////////////////////////////////// +// +// Last changed : $Date: 2012-08-30 16:45:25 -0300 (qui, 30 ago 2012) $ +// File revision : $Revision: 4 $ +// +// $Id: BPMDetect.cpp 149 2012-08-30 19:45:25Z oparviai $ +// +//////////////////////////////////////////////////////////////////////////////// +// +// License : +// +// SoundTouch audio processing library +// Copyright (c) Olli Parviainen +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +//////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include +#include +#include "FIFOSampleBuffer.h" +#include "PeakFinder.h" +#include "BPMDetect.h" + +using namespace soundtouch; + +#define INPUT_BLOCK_SAMPLES 2048 +#define DECIMATED_BLOCK_SAMPLES 256 + +/// decay constant for calculating RMS volume sliding average approximation +/// (time constant is about 10 sec) +const float avgdecay = 0.99986f; + +/// Normalization coefficient for calculating RMS sliding average approximation. +const float avgnorm = (1 - avgdecay); + + +//////////////////////////////////////////////////////////////////////////////// + +// Enable following define to create bpm analysis file: + +// #define _CREATE_BPM_DEBUG_FILE + +#ifdef _CREATE_BPM_DEBUG_FILE + + #define DEBUGFILE_NAME "c:\\temp\\soundtouch-bpm-debug.txt" + + static void _SaveDebugData(const float *data, int minpos, int maxpos, double coeff) + { + FILE *fptr = fopen(DEBUGFILE_NAME, "wt"); + int i; + + if (fptr) + { + printf("\n\nWriting BPM debug data into file " DEBUGFILE_NAME "\n\n"); + for (i = minpos; i < maxpos; i ++) + { + fprintf(fptr, "%d\t%.1lf\t%f\n", i, coeff / (double)i, data[i]); + } + fclose(fptr); + } + } +#else + #define _SaveDebugData(a,b,c,d) +#endif + +//////////////////////////////////////////////////////////////////////////////// + + +BPMDetect::BPMDetect(int numChannels, int aSampleRate) +{ + this->sampleRate = aSampleRate; + this->channels = numChannels; + + decimateSum = 0; + decimateCount = 0; + + envelopeAccu = 0; + + // Initialize RMS volume accumulator to RMS level of 1500 (out of 32768) that's + // safe initial RMS signal level value for song data. This value is then adapted + // to the actual level during processing. +#ifdef SOUNDTOUCH_INTEGER_SAMPLES + // integer samples + RMSVolumeAccu = (1500 * 1500) / avgnorm; +#else + // float samples, scaled to range [-1..+1[ + RMSVolumeAccu = (0.045f * 0.045f) / avgnorm; +#endif + + // choose decimation factor so that result is approx. 1000 Hz + decimateBy = sampleRate / 1000; + assert(decimateBy > 0); + assert(INPUT_BLOCK_SAMPLES < decimateBy * DECIMATED_BLOCK_SAMPLES); + + // Calculate window length & starting item according to desired min & max bpms + windowLen = (60 * sampleRate) / (decimateBy * MIN_BPM); + windowStart = (60 * sampleRate) / (decimateBy * MAX_BPM); + + assert(windowLen > windowStart); + + // allocate new working objects + xcorr = new float[windowLen]; + memset(xcorr, 0, windowLen * sizeof(float)); + + // allocate processing buffer + buffer = new FIFOSampleBuffer(); + // we do processing in mono mode + buffer->setChannels(1); + buffer->clear(); +} + + + +BPMDetect::~BPMDetect() +{ + delete[] xcorr; + delete buffer; +} + + + +/// convert to mono, low-pass filter & decimate to about 500 Hz. +/// return number of outputted samples. +/// +/// Decimation is used to remove the unnecessary frequencies and thus to reduce +/// the amount of data needed to be processed as calculating autocorrelation +/// function is a very-very heavy operation. +/// +/// Anti-alias filtering is done simply by averaging the samples. This is really a +/// poor-man's anti-alias filtering, but it's not so critical in this kind of application +/// (it'd also be difficult to design a high-quality filter with steep cut-off at very +/// narrow band) +int BPMDetect::decimate(SAMPLETYPE *dest, const SAMPLETYPE *src, int numsamples) +{ + int count, outcount; + LONG_SAMPLETYPE out; + + assert(channels > 0); + assert(decimateBy > 0); + outcount = 0; + for (count = 0; count < numsamples; count ++) + { + int j; + + // convert to mono and accumulate + for (j = 0; j < channels; j ++) + { + decimateSum += src[j]; + } + src += j; + + decimateCount ++; + if (decimateCount >= decimateBy) + { + // Store every Nth sample only + out = (LONG_SAMPLETYPE)(decimateSum / (decimateBy * channels)); + decimateSum = 0; + decimateCount = 0; +#ifdef SOUNDTOUCH_INTEGER_SAMPLES + // check ranges for sure (shouldn't actually be necessary) + if (out > 32767) + { + out = 32767; + } + else if (out < -32768) + { + out = -32768; + } +#endif // SOUNDTOUCH_INTEGER_SAMPLES + dest[outcount] = (SAMPLETYPE)out; + outcount ++; + } + } + return outcount; +} + + + +// Calculates autocorrelation function of the sample history buffer +void BPMDetect::updateXCorr(int process_samples) +{ + int offs; + SAMPLETYPE *pBuffer; + + assert(buffer->numSamples() >= (uint)(process_samples + windowLen)); + + pBuffer = buffer->ptrBegin(); + for (offs = windowStart; offs < windowLen; offs ++) + { + LONG_SAMPLETYPE sum; + int i; + + sum = 0; + for (i = 0; i < process_samples; i ++) + { + sum += pBuffer[i] * pBuffer[i + offs]; // scaling the sub-result shouldn't be necessary + } +// xcorr[offs] *= xcorr_decay; // decay 'xcorr' here with suitable coefficients + // if it's desired that the system adapts automatically to + // various bpms, e.g. in processing continouos music stream. + // The 'xcorr_decay' should be a value that's smaller than but + // close to one, and should also depend on 'process_samples' value. + + xcorr[offs] += (float)sum; + } +} + + +// Calculates envelope of the sample data +void BPMDetect::calcEnvelope(SAMPLETYPE *samples, int numsamples) +{ + const static double decay = 0.7f; // decay constant for smoothing the envelope + const static double norm = (1 - decay); + + int i; + LONG_SAMPLETYPE out; + double val; + + for (i = 0; i < numsamples; i ++) + { + // calc average RMS volume + RMSVolumeAccu *= avgdecay; + val = (float)fabs((float)samples[i]); + RMSVolumeAccu += val * val; + + // cut amplitudes that are below cutoff ~2 times RMS volume + // (we're interested in peak values, not the silent moments) + if (val < 0.5 * sqrt(RMSVolumeAccu * avgnorm)) + { + val = 0; + } + + // smooth amplitude envelope + envelopeAccu *= decay; + envelopeAccu += val; + out = (LONG_SAMPLETYPE)(envelopeAccu * norm); + +#ifdef SOUNDTOUCH_INTEGER_SAMPLES + // cut peaks (shouldn't be necessary though) + if (out > 32767) out = 32767; +#endif // SOUNDTOUCH_INTEGER_SAMPLES + samples[i] = (SAMPLETYPE)out; + } +} + + + +void BPMDetect::inputSamples(const SAMPLETYPE *samples, int numSamples) +{ + SAMPLETYPE decimated[DECIMATED_BLOCK_SAMPLES]; + + // iterate so that max INPUT_BLOCK_SAMPLES processed per iteration + while (numSamples > 0) + { + int block; + int decSamples; + + block = (numSamples > INPUT_BLOCK_SAMPLES) ? INPUT_BLOCK_SAMPLES : numSamples; + + // decimate. note that converts to mono at the same time + decSamples = decimate(decimated, samples, block); + samples += block * channels; + numSamples -= block; + + // envelope new samples and add them to buffer + calcEnvelope(decimated, decSamples); + buffer->putSamples(decimated, decSamples); + } + + // when the buffer has enought samples for processing... + if ((int)buffer->numSamples() > windowLen) + { + int processLength; + + // how many samples are processed + processLength = (int)buffer->numSamples() - windowLen; + + // ... calculate autocorrelations for oldest samples... + updateXCorr(processLength); + // ... and remove them from the buffer + buffer->receiveSamples(processLength); + } +} + + + +void BPMDetect::removeBias() +{ + int i; + float minval = 1e12f; // arbitrary large number + + for (i = windowStart; i < windowLen; i ++) + { + if (xcorr[i] < minval) + { + minval = xcorr[i]; + } + } + + for (i = windowStart; i < windowLen; i ++) + { + xcorr[i] -= minval; + } +} + + +float BPMDetect::getBpm() +{ + double peakPos; + double coeff; + PeakFinder peakFinder; + + coeff = 60.0 * ((double)sampleRate / (double)decimateBy); + + // save bpm debug analysis data if debug data enabled + _SaveDebugData(xcorr, windowStart, windowLen, coeff); + + // remove bias from xcorr data + removeBias(); + + // find peak position + peakPos = peakFinder.detectPeak(xcorr, windowStart, windowLen); + + assert(decimateBy != 0); + if (peakPos < 1e-9) return 0.0; // detection failed. + + // calculate BPM + return (float) (coeff / peakPos); +} diff --git a/3rdparty/SoundTouch/BPMDetect.h b/3rdparty/SoundTouch/BPMDetect.h index 75289c6b9b..88628def06 100644 --- a/3rdparty/SoundTouch/BPMDetect.h +++ b/3rdparty/SoundTouch/BPMDetect.h @@ -14,10 +14,10 @@ /// taking absolute value that's smoothed by sliding average. Signal levels that /// are below a couple of times the general RMS amplitude level are cut away to /// leave only notable peaks there. -/// - Repeating sound patterns (e.g. beats) are detected by calculating short-term +/// - Repeating sound patterns (e.g. beats) are detected by calculating short-term /// autocorrelation function of the enveloped signal. -/// - After whole sound data file has been analyzed as above, the bpm level is -/// detected by function 'getBpm' that finds the highest peak of the autocorrelation +/// - After whole sound data file has been analyzed as above, the bpm level is +/// detected by function 'getBpm' that finds the highest peak of the autocorrelation /// function, calculates it's precise location and converts this reading to bpm's. /// /// Author : Copyright (c) Olli Parviainen @@ -26,10 +26,10 @@ /// //////////////////////////////////////////////////////////////////////////////// // -// Last changed : $Date: 2009-02-21 18:00:14 +0200 (Sat, 21 Feb 2009) $ +// Last changed : $Date: 2012-08-30 16:53:44 -0300 (qui, 30 ago 2012) $ // File revision : $Revision: 4 $ // -// $Id: BPMDetect.h 63 2009-02-21 16:00:14Z oparviai $ +// $Id: BPMDetect.h 150 2012-08-30 19:53:44Z oparviai $ // //////////////////////////////////////////////////////////////////////////////// // @@ -67,7 +67,7 @@ namespace soundtouch #define MIN_BPM 29 /// Maximum allowed BPM rate. Used to restrict accepted result below a reasonable limit. -#define MAX_BPM 230 +#define MAX_BPM 200 /// Class for calculating BPM rate for audio data. @@ -76,12 +76,12 @@ class BPMDetect protected: /// Auto-correlation accumulator bins. float *xcorr; - + /// Amplitude envelope sliding average approximation level accumulator - float envelopeAccu; + double envelopeAccu; /// RMS volume sliding average approximation level accumulator - float RMSVolumeAccu; + double RMSVolumeAccu; /// Sample average counter. int decimateCount; @@ -104,12 +104,12 @@ protected: /// Beginning of auto-correlation window: Autocorrelation isn't being updated for /// the first these many correlation bins. int windowStart; - + /// FIFO-buffer for decimated processing samples. soundtouch::FIFOSampleBuffer *buffer; - /// Updates auto-correlation function for given number of decimated samples that - /// are read from the internal 'buffer' pipe (samples aren't removed from the pipe + /// Updates auto-correlation function for given number of decimated samples that + /// are read from the internal 'buffer' pipe (samples aren't removed from the pipe /// though). void updateXCorr(int process_samples /// How many samples are processed. ); @@ -128,6 +128,9 @@ protected: int numsamples ///< Number of samples in buffer ); + /// remove constant bias from xcorr data + void removeBias(); + public: /// Constructor. BPMDetect(int numChannels, ///< Number of channels in sample data. @@ -139,9 +142,9 @@ public: /// Inputs a block of samples for analyzing: Envelopes the samples and then /// updates the autocorrelation estimation. When whole song data has been input - /// in smaller blocks using this function, read the resulting bpm with 'getBpm' - /// function. - /// + /// in smaller blocks using this function, read the resulting bpm with 'getBpm' + /// function. + /// /// Notice that data in 'samples' array can be disrupted in processing. void inputSamples(const soundtouch::SAMPLETYPE *samples, ///< Pointer to input/working data buffer int numSamples ///< Number of samples in buffer diff --git a/3rdparty/SoundTouch/FIFOSampleBuffer.cpp b/3rdparty/SoundTouch/FIFOSampleBuffer.cpp index a395315ac7..80314d81f9 100644 --- a/3rdparty/SoundTouch/FIFOSampleBuffer.cpp +++ b/3rdparty/SoundTouch/FIFOSampleBuffer.cpp @@ -1,12 +1,12 @@ //////////////////////////////////////////////////////////////////////////////// /// -/// A buffer class for temporarily storaging sound samples, operates as a +/// A buffer class for temporarily storaging sound samples, operates as a /// first-in-first-out pipe. /// -/// Samples are added to the end of the sample buffer with the 'putSamples' +/// Samples are added to the end of the sample buffer with the 'putSamples' /// function, and are received from the beginning of the buffer by calling -/// the 'receiveSamples' function. The class automatically removes the -/// outputted samples from the buffer, as well as grows the buffer size +/// the 'receiveSamples' function. The class automatically removes the +/// outputted samples from the buffer, as well as grows the buffer size /// whenever necessary. /// /// Author : Copyright (c) Olli Parviainen @@ -15,10 +15,10 @@ /// //////////////////////////////////////////////////////////////////////////////// // -// Last changed : $Date: 2009-02-27 19:24:42 +0200 (Fri, 27 Feb 2009) $ +// Last changed : $Date: 2012-11-08 16:53:01 -0200 (qui, 08 nov 2012) $ // File revision : $Revision: 4 $ // -// $Id: FIFOSampleBuffer.cpp 68 2009-02-27 17:24:42Z oparviai $ +// $Id: FIFOSampleBuffer.cpp 160 2012-11-08 18:53:01Z oparviai $ // //////////////////////////////////////////////////////////////////////////////// // @@ -47,7 +47,6 @@ #include #include #include -#include #include "FIFOSampleBuffer.h" @@ -63,7 +62,7 @@ FIFOSampleBuffer::FIFOSampleBuffer(int numChannels) samplesInBuffer = 0; bufferPos = 0; channels = (uint)numChannels; - ensureCapacity(32); // allocate initial capacity + ensureCapacity(32); // allocate initial capacity } @@ -89,11 +88,11 @@ void FIFOSampleBuffer::setChannels(int numChannels) // if output location pointer 'bufferPos' isn't zero, 'rewinds' the buffer and -// zeroes this pointer by copying samples from the 'bufferPos' pointer +// zeroes this pointer by copying samples from the 'bufferPos' pointer // location on to the beginning of the buffer. void FIFOSampleBuffer::rewind() { - if (buffer && bufferPos) + if (buffer && bufferPos) { memmove(buffer, ptrBegin(), sizeof(SAMPLETYPE) * channels * samplesInBuffer); bufferPos = 0; @@ -101,7 +100,7 @@ void FIFOSampleBuffer::rewind() } -// Adds 'numSamples' pcs of samples from the 'samples' memory position to +// Adds 'numSamples' pcs of samples from the 'samples' memory position to // the sample buffer. void FIFOSampleBuffer::putSamples(const SAMPLETYPE *samples, uint nSamples) { @@ -114,7 +113,7 @@ void FIFOSampleBuffer::putSamples(const SAMPLETYPE *samples, uint nSamples) // samples. // // This function is used to update the number of samples in the sample buffer -// when accessing the buffer directly with 'ptrEnd' function. Please be +// when accessing the buffer directly with 'ptrEnd' function. Please be // careful though! void FIFOSampleBuffer::putSamples(uint nSamples) { @@ -126,31 +125,31 @@ void FIFOSampleBuffer::putSamples(uint nSamples) } -// Returns a pointer to the end of the used part of the sample buffer (i.e. -// where the new samples are to be inserted). This function may be used for -// inserting new samples into the sample buffer directly. Please be careful! +// Returns a pointer to the end of the used part of the sample buffer (i.e. +// where the new samples are to be inserted). This function may be used for +// inserting new samples into the sample buffer directly. Please be careful! // // Parameter 'slackCapacity' tells the function how much free capacity (in // terms of samples) there _at least_ should be, in order to the caller to -// succesfully insert all the required samples to the buffer. When necessary, +// succesfully insert all the required samples to the buffer. When necessary, // the function grows the buffer size to comply with this requirement. // -// When using this function as means for inserting new samples, also remember -// to increase the sample count afterwards, by calling the +// When using this function as means for inserting new samples, also remember +// to increase the sample count afterwards, by calling the // 'putSamples(numSamples)' function. -SAMPLETYPE *FIFOSampleBuffer::ptrEnd(uint slackCapacity) +SAMPLETYPE *FIFOSampleBuffer::ptrEnd(uint slackCapacity) { ensureCapacity(samplesInBuffer + slackCapacity); return buffer + samplesInBuffer * channels; } -// Returns a pointer to the beginning of the currently non-outputted samples. -// This function is provided for accessing the output samples directly. +// Returns a pointer to the beginning of the currently non-outputted samples. +// This function is provided for accessing the output samples directly. // Please be careful! // // When using this function to output samples, also remember to 'remove' the -// outputted samples from the buffer by calling the +// outputted samples from the buffer by calling the // 'receiveSamples(numSamples)' function SAMPLETYPE *FIFOSampleBuffer::ptrBegin() { @@ -167,7 +166,7 @@ void FIFOSampleBuffer::ensureCapacity(uint capacityRequirement) { SAMPLETYPE *tempUnaligned, *temp; - if (capacityRequirement > getCapacity()) + if (capacityRequirement > getCapacity()) { // enlarge the buffer in 4kbyte steps (round up to next 4k boundary) sizeInBytes = (capacityRequirement * channels * sizeof(SAMPLETYPE) + 4095) & (uint)-4096; @@ -175,10 +174,10 @@ void FIFOSampleBuffer::ensureCapacity(uint capacityRequirement) tempUnaligned = new SAMPLETYPE[sizeInBytes / sizeof(SAMPLETYPE) + 16 / sizeof(SAMPLETYPE)]; if (tempUnaligned == NULL) { - throw std::runtime_error("Couldn't allocate memory!\n"); + ST_THROW_RT_ERROR("Couldn't allocate memory!\n"); } // Align the buffer to begin at 16byte cache line boundary for optimal performance - temp = (SAMPLETYPE *)(((ulong)tempUnaligned + 15) & (ulong)-16); + temp = (SAMPLETYPE *)SOUNDTOUCH_ALIGN_POINTER_16(tempUnaligned); if (samplesInBuffer) { memcpy(temp, ptrBegin(), samplesInBuffer * channels * sizeof(SAMPLETYPE)); @@ -187,8 +186,8 @@ void FIFOSampleBuffer::ensureCapacity(uint capacityRequirement) buffer = temp; bufferUnaligned = tempUnaligned; bufferPos = 0; - } - else + } + else { // simply rewind the buffer (if necessary) rewind(); @@ -260,3 +259,16 @@ void FIFOSampleBuffer::clear() samplesInBuffer = 0; bufferPos = 0; } + + +/// allow trimming (downwards) amount of samples in pipeline. +/// Returns adjusted amount of samples +uint FIFOSampleBuffer::adjustAmountOfSamples(uint numSamples) +{ + if (numSamples < samplesInBuffer) + { + samplesInBuffer = numSamples; + } + return samplesInBuffer; +} + diff --git a/3rdparty/SoundTouch/FIFOSampleBuffer.h b/3rdparty/SoundTouch/FIFOSampleBuffer.h index ed31c8db63..5f1eb5f3da 100644 --- a/3rdparty/SoundTouch/FIFOSampleBuffer.h +++ b/3rdparty/SoundTouch/FIFOSampleBuffer.h @@ -1,12 +1,12 @@ //////////////////////////////////////////////////////////////////////////////// /// -/// A buffer class for temporarily storaging sound samples, operates as a +/// A buffer class for temporarily storaging sound samples, operates as a /// first-in-first-out pipe. /// -/// Samples are added to the end of the sample buffer with the 'putSamples' +/// Samples are added to the end of the sample buffer with the 'putSamples' /// function, and are received from the beginning of the buffer by calling -/// the 'receiveSamples' function. The class automatically removes the -/// output samples from the buffer as well as grows the storage size +/// the 'receiveSamples' function. The class automatically removes the +/// output samples from the buffer as well as grows the storage size /// whenever necessary. /// /// Author : Copyright (c) Olli Parviainen @@ -15,10 +15,10 @@ /// //////////////////////////////////////////////////////////////////////////////// // -// Last changed : $Date: 2009-02-21 18:00:14 +0200 (Sat, 21 Feb 2009) $ +// Last changed : $Date: 2012-06-13 16:29:53 -0300 (qua, 13 jun 2012) $ // File revision : $Revision: 4 $ // -// $Id: FIFOSampleBuffer.h 63 2009-02-21 16:00:14Z oparviai $ +// $Id: FIFOSampleBuffer.h 143 2012-06-13 19:29:53Z oparviai $ // //////////////////////////////////////////////////////////////////////////////// // @@ -54,7 +54,7 @@ namespace soundtouch /// Sample buffer working in FIFO (first-in-first-out) principle. The class takes /// care of storage size adjustment and data moving during input/output operations. /// -/// Notice that in case of stereo audio, one sample is considered to consist of +/// Notice that in case of stereo audio, one sample is considered to consist of /// both channel data. class FIFOSampleBuffer : public FIFOSamplePipe { @@ -75,12 +75,12 @@ private: /// Channels, 1=mono, 2=stereo. uint channels; - /// Current position pointer to the buffer. This pointer is increased when samples are + /// Current position pointer to the buffer. This pointer is increased when samples are /// removed from the pipe so that it's necessary to actually rewind buffer (move data) /// only new data when is put to the pipe. uint bufferPos; - /// Rewind the buffer by moving data from position pointed by 'bufferPos' to real + /// Rewind the buffer by moving data from position pointed by 'bufferPos' to real /// beginning of the buffer. void rewind(); @@ -100,27 +100,27 @@ public: /// destructor ~FIFOSampleBuffer(); - /// Returns a pointer to the beginning of the output samples. - /// This function is provided for accessing the output samples directly. + /// Returns a pointer to the beginning of the output samples. + /// This function is provided for accessing the output samples directly. /// Please be careful for not to corrupt the book-keeping! /// /// When using this function to output samples, also remember to 'remove' the - /// output samples from the buffer by calling the + /// output samples from the buffer by calling the /// 'receiveSamples(numSamples)' function virtual SAMPLETYPE *ptrBegin(); - /// Returns a pointer to the end of the used part of the sample buffer (i.e. - /// where the new samples are to be inserted). This function may be used for + /// Returns a pointer to the end of the used part of the sample buffer (i.e. + /// where the new samples are to be inserted). This function may be used for /// inserting new samples into the sample buffer directly. Please be careful /// not corrupt the book-keeping! /// - /// When using this function as means for inserting new samples, also remember - /// to increase the sample count afterwards, by calling the + /// When using this function as means for inserting new samples, also remember + /// to increase the sample count afterwards, by calling the /// 'putSamples(numSamples)' function. SAMPLETYPE *ptrEnd( - uint slackCapacity ///< How much free capacity (in samples) there _at least_ - ///< should be so that the caller can succesfully insert the - ///< desired samples to the buffer. If necessary, the function + uint slackCapacity ///< How much free capacity (in samples) there _at least_ + ///< should be so that the caller can succesfully insert the + ///< desired samples to the buffer. If necessary, the function ///< grows the buffer size to comply with this requirement. ); @@ -130,17 +130,17 @@ public: uint numSamples ///< Number of samples to insert. ); - /// Adjusts the book-keeping to increase number of samples in the buffer without + /// Adjusts the book-keeping to increase number of samples in the buffer without /// copying any actual samples. /// /// This function is used to update the number of samples in the sample buffer - /// when accessing the buffer directly with 'ptrEnd' function. Please be + /// when accessing the buffer directly with 'ptrEnd' function. Please be /// careful though! virtual void putSamples(uint numSamples ///< Number of samples been inserted. ); - /// Output samples from beginning of the sample buffer. Copies requested samples to - /// output buffer and removes them from the sample buffer. If there are less than + /// Output samples from beginning of the sample buffer. Copies requested samples to + /// output buffer and removes them from the sample buffer. If there are less than /// 'numsample' samples in the buffer, returns all that available. /// /// \return Number of samples returned. @@ -148,8 +148,8 @@ public: uint maxSamples ///< How many samples to receive at max. ); - /// Adjusts book-keeping so that given number of samples are removed from beginning of the - /// sample buffer without copying them anywhere. + /// Adjusts book-keeping so that given number of samples are removed from beginning of the + /// sample buffer without copying them anywhere. /// /// Used to reduce the number of samples in the buffer when accessing the sample buffer directly /// with 'ptrBegin' function. @@ -167,6 +167,10 @@ public: /// Clears all the samples. virtual void clear(); + + /// allow trimming (downwards) amount of samples in pipeline. + /// Returns adjusted amount of samples + uint adjustAmountOfSamples(uint numSamples); }; } diff --git a/3rdparty/SoundTouch/FIFOSamplePipe.h b/3rdparty/SoundTouch/FIFOSamplePipe.h index 31dc40f93d..805e92597e 100644 --- a/3rdparty/SoundTouch/FIFOSamplePipe.h +++ b/3rdparty/SoundTouch/FIFOSamplePipe.h @@ -5,7 +5,7 @@ /// into one end of the pipe with the 'putSamples' function, and the processed /// samples are received from the other end with the 'receiveSamples' function. /// -/// 'FIFOProcessor' : A base class for classes the do signal processing with +/// 'FIFOProcessor' : A base class for classes the do signal processing with /// the samples while operating like a first-in-first-out pipe. When samples /// are input with the 'putSamples' function, the class processes them /// and moves the processed samples to the given 'output' pipe object, which @@ -17,10 +17,10 @@ /// //////////////////////////////////////////////////////////////////////////////// // -// Last changed : $Date: 2009-04-13 16:18:48 +0300 (Mon, 13 Apr 2009) $ +// Last changed : $Date: 2012-06-13 16:29:53 -0300 (qua, 13 jun 2012) $ // File revision : $Revision: 4 $ // -// $Id: FIFOSamplePipe.h 69 2009-04-13 13:18:48Z oparviai $ +// $Id: FIFOSamplePipe.h 143 2012-06-13 19:29:53Z oparviai $ // //////////////////////////////////////////////////////////////////////////////// // @@ -63,12 +63,12 @@ public: virtual ~FIFOSamplePipe() {} - /// Returns a pointer to the beginning of the output samples. - /// This function is provided for accessing the output samples directly. + /// Returns a pointer to the beginning of the output samples. + /// This function is provided for accessing the output samples directly. /// Please be careful for not to corrupt the book-keeping! /// /// When using this function to output samples, also remember to 'remove' the - /// output samples from the buffer by calling the + /// output samples from the buffer by calling the /// 'receiveSamples(numSamples)' function virtual SAMPLETYPE *ptrBegin() = 0; @@ -89,8 +89,8 @@ public: other.receiveSamples(oNumSamples); }; - /// Output samples from beginning of the sample buffer. Copies requested samples to - /// output buffer and removes them from the sample buffer. If there are less than + /// Output samples from beginning of the sample buffer. Copies requested samples to + /// output buffer and removes them from the sample buffer. If there are less than /// 'numsample' samples in the buffer, returns all that available. /// /// \return Number of samples returned. @@ -98,8 +98,8 @@ public: uint maxSamples ///< How many samples to receive at max. ) = 0; - /// Adjusts book-keeping so that given number of samples are removed from beginning of the - /// sample buffer without copying them anywhere. + /// Adjusts book-keeping so that given number of samples are removed from beginning of the + /// sample buffer without copying them anywhere. /// /// Used to reduce the number of samples in the buffer when accessing the sample buffer directly /// with 'ptrBegin' function. @@ -114,16 +114,21 @@ public: /// Clears all the samples. virtual void clear() = 0; + + /// allow trimming (downwards) amount of samples in pipeline. + /// Returns adjusted amount of samples + virtual uint adjustAmountOfSamples(uint numSamples) = 0; + }; -/// Base-class for sound processing routines working in FIFO principle. With this base +/// Base-class for sound processing routines working in FIFO principle. With this base /// class it's easy to implement sound processing stages that can be chained together, -/// so that samples that are fed into beginning of the pipe automatically go through +/// so that samples that are fed into beginning of the pipe automatically go through /// all the processing stages. /// -/// When samples are input to this class, they're first processed and then put to +/// When samples are input to this class, they're first processed and then put to /// the FIFO pipe that's defined as output of this class. This output pipe can be /// either other processing stage or a FIFO sample buffer. class FIFOProcessor :public FIFOSamplePipe @@ -141,7 +146,7 @@ protected: } - /// Constructor. Doesn't define output pipe; it has to be set be + /// Constructor. Doesn't define output pipe; it has to be set be /// 'setOutPipe' function. FIFOProcessor() { @@ -163,12 +168,12 @@ protected: } - /// Returns a pointer to the beginning of the output samples. - /// This function is provided for accessing the output samples directly. + /// Returns a pointer to the beginning of the output samples. + /// This function is provided for accessing the output samples directly. /// Please be careful for not to corrupt the book-keeping! /// /// When using this function to output samples, also remember to 'remove' the - /// output samples from the buffer by calling the + /// output samples from the buffer by calling the /// 'receiveSamples(numSamples)' function virtual SAMPLETYPE *ptrBegin() { @@ -177,8 +182,8 @@ protected: public: - /// Output samples from beginning of the sample buffer. Copies requested samples to - /// output buffer and removes them from the sample buffer. If there are less than + /// Output samples from beginning of the sample buffer. Copies requested samples to + /// output buffer and removes them from the sample buffer. If there are less than /// 'numsample' samples in the buffer, returns all that available. /// /// \return Number of samples returned. @@ -190,8 +195,8 @@ public: } - /// Adjusts book-keeping so that given number of samples are removed from beginning of the - /// sample buffer without copying them anywhere. + /// Adjusts book-keeping so that given number of samples are removed from beginning of the + /// sample buffer without copying them anywhere. /// /// Used to reduce the number of samples in the buffer when accessing the sample buffer directly /// with 'ptrBegin' function. @@ -214,6 +219,14 @@ public: { return output->isEmpty(); } + + /// allow trimming (downwards) amount of samples in pipeline. + /// Returns adjusted amount of samples + virtual uint adjustAmountOfSamples(uint numSamples) + { + return output->adjustAmountOfSamples(numSamples); + } + }; } diff --git a/3rdparty/SoundTouch/FIRFilter.cpp b/3rdparty/SoundTouch/FIRFilter.cpp index 9f7351dce8..13a1896ce7 100644 --- a/3rdparty/SoundTouch/FIRFilter.cpp +++ b/3rdparty/SoundTouch/FIRFilter.cpp @@ -1,8 +1,8 @@ //////////////////////////////////////////////////////////////////////////////// /// -/// General FIR digital filter routines with MMX optimization. +/// General FIR digital filter routines with MMX optimization. /// -/// Note : MMX optimized functions reside in a separate, platform-specific file, +/// Note : MMX optimized functions reside in a separate, platform-specific file, /// e.g. 'mmx_win.cpp' or 'mmx_gcc.cpp' /// /// Author : Copyright (c) Olli Parviainen @@ -11,10 +11,10 @@ /// //////////////////////////////////////////////////////////////////////////////// // -// Last changed : $Date: 2009-02-25 19:13:51 +0200 (Wed, 25 Feb 2009) $ +// Last changed : $Date: 2011-09-02 15:56:11 -0300 (sex, 02 set 2011) $ // File revision : $Revision: 4 $ // -// $Id: FIRFilter.cpp 67 2009-02-25 17:13:51Z oparviai $ +// $Id: FIRFilter.cpp 131 2011-09-02 18:56:11Z oparviai $ // //////////////////////////////////////////////////////////////////////////////// // @@ -43,7 +43,6 @@ #include #include #include -#include #include "FIRFilter.h" #include "cpu_detect.h" @@ -75,7 +74,7 @@ uint FIRFilter::evaluateFilterStereo(SAMPLETYPE *dest, const SAMPLETYPE *src, ui { uint i, j, end; LONG_SAMPLETYPE suml, sumr; -#ifdef FLOAT_SAMPLES +#ifdef SOUNDTOUCH_FLOAT_SAMPLES // when using floating point samples, use a scaler instead of a divider // because division is much slower operation than multiplying. double dScaler = 1.0 / (double)resultDivider; @@ -88,14 +87,14 @@ uint FIRFilter::evaluateFilterStereo(SAMPLETYPE *dest, const SAMPLETYPE *src, ui end = 2 * (numSamples - length); - for (j = 0; j < end; j += 2) + for (j = 0; j < end; j += 2) { const SAMPLETYPE *ptr; suml = sumr = 0; ptr = src + j; - for (i = 0; i < length; i += 4) + for (i = 0; i < length; i += 4) { // loop is unrolled by factor of 4 here for efficiency suml += ptr[2 * i + 0] * filterCoeffs[i + 0] + @@ -108,7 +107,7 @@ uint FIRFilter::evaluateFilterStereo(SAMPLETYPE *dest, const SAMPLETYPE *src, ui ptr[2 * i + 7] * filterCoeffs[i + 3]; } -#ifdef INTEGER_SAMPLES +#ifdef SOUNDTOUCH_INTEGER_SAMPLES suml >>= resultDivFactor; sumr >>= resultDivFactor; // saturate to 16 bit integer limits @@ -118,7 +117,7 @@ uint FIRFilter::evaluateFilterStereo(SAMPLETYPE *dest, const SAMPLETYPE *src, ui #else suml *= dScaler; sumr *= dScaler; -#endif // INTEGER_SAMPLES +#endif // SOUNDTOUCH_INTEGER_SAMPLES dest[j] = (SAMPLETYPE)suml; dest[j + 1] = (SAMPLETYPE)sumr; } @@ -133,7 +132,7 @@ uint FIRFilter::evaluateFilterMono(SAMPLETYPE *dest, const SAMPLETYPE *src, uint { uint i, j, end; LONG_SAMPLETYPE sum; -#ifdef FLOAT_SAMPLES +#ifdef SOUNDTOUCH_FLOAT_SAMPLES // when using floating point samples, use a scaler instead of a divider // because division is much slower operation than multiplying. double dScaler = 1.0 / (double)resultDivider; @@ -143,24 +142,24 @@ uint FIRFilter::evaluateFilterMono(SAMPLETYPE *dest, const SAMPLETYPE *src, uint assert(length != 0); end = numSamples - length; - for (j = 0; j < end; j ++) + for (j = 0; j < end; j ++) { sum = 0; - for (i = 0; i < length; i += 4) + for (i = 0; i < length; i += 4) { // loop is unrolled by factor of 4 here for efficiency - sum += src[i + 0] * filterCoeffs[i + 0] + - src[i + 1] * filterCoeffs[i + 1] + - src[i + 2] * filterCoeffs[i + 2] + + sum += src[i + 0] * filterCoeffs[i + 0] + + src[i + 1] * filterCoeffs[i + 1] + + src[i + 2] * filterCoeffs[i + 2] + src[i + 3] * filterCoeffs[i + 3]; } -#ifdef INTEGER_SAMPLES +#ifdef SOUNDTOUCH_INTEGER_SAMPLES sum >>= resultDivFactor; // saturate to 16 bit integer limits sum = (sum < -32768) ? -32768 : (sum > 32767) ? 32767 : sum; #else sum *= dScaler; -#endif // INTEGER_SAMPLES +#endif // SOUNDTOUCH_INTEGER_SAMPLES dest[j] = (SAMPLETYPE)sum; src ++; } @@ -174,7 +173,7 @@ uint FIRFilter::evaluateFilterMono(SAMPLETYPE *dest, const SAMPLETYPE *src, uint void FIRFilter::setCoefficients(const SAMPLETYPE *coeffs, uint newLength, uint uResultDivFactor) { assert(newLength > 0); - if (newLength % 8) throw std::runtime_error("FIR filter length not divisible by 8"); + if (newLength % 8) ST_THROW_RT_ERROR("FIR filter length not divisible by 8"); lengthDiv8 = newLength / 8; length = lengthDiv8 * 8; @@ -196,9 +195,9 @@ uint FIRFilter::getLength() const -// Applies the filter to the given sequence of samples. +// Applies the filter to the given sequence of samples. // -// Note : The amount of outputted samples is by value of 'filter_length' +// Note : The amount of outputted samples is by value of 'filter_length' // smaller than the amount of input samples. uint FIRFilter::evaluate(SAMPLETYPE *dest, const SAMPLETYPE *src, uint numSamples, uint numChannels) const { @@ -207,7 +206,7 @@ uint FIRFilter::evaluate(SAMPLETYPE *dest, const SAMPLETYPE *src, uint numSample assert(length > 0); assert(lengthDiv8 * 8 == length); if (numSamples < length) return 0; - if (numChannels == 2) + if (numChannels == 2) { return evaluateFilterStereo(dest, src, numSamples); } else { @@ -217,13 +216,13 @@ uint FIRFilter::evaluate(SAMPLETYPE *dest, const SAMPLETYPE *src, uint numSample -// Operator 'new' is overloaded so that it automatically creates a suitable instance +// Operator 'new' is overloaded so that it automatically creates a suitable instance // depending on if we've a MMX-capable CPU available or not. void * FIRFilter::operator new(size_t s) { // Notice! don't use "new FIRFilter" directly, use "newInstance" to create a new instance instead! - throw std::runtime_error("Error in FIRFilter::new: Don't use 'new FIRFilter', use 'newInstance' member instead!"); - return NULL; + ST_THROW_RT_ERROR("Error in FIRFilter::new: Don't use 'new FIRFilter', use 'newInstance' member instead!"); + return newInstance(); } @@ -233,34 +232,25 @@ FIRFilter * FIRFilter::newInstance() uExtensions = detectCPUextensions(); - // Check if MMX/SSE/3DNow! instruction set extensions supported by CPU + // Check if MMX/SSE instruction set extensions supported by CPU -#ifdef ALLOW_MMX +#ifdef SOUNDTOUCH_ALLOW_MMX // MMX routines available only with integer sample types if (uExtensions & SUPPORT_MMX) { return ::new FIRFilterMMX; } else -#endif // ALLOW_MMX +#endif // SOUNDTOUCH_ALLOW_MMX -#ifdef ALLOW_SSE +#ifdef SOUNDTOUCH_ALLOW_SSE if (uExtensions & SUPPORT_SSE) { // SSE support return ::new FIRFilterSSE; } else -#endif // ALLOW_SSE - -#ifdef ALLOW_3DNOW - if (uExtensions & SUPPORT_3DNOW) - { - // 3DNow! support - return ::new FIRFilter3DNow; - } - else -#endif // ALLOW_3DNOW +#endif // SOUNDTOUCH_ALLOW_SSE { // ISA optimizations not supported, use plain C version diff --git a/3rdparty/SoundTouch/FIRFilter.h b/3rdparty/SoundTouch/FIRFilter.h index 2899c9bfd7..b593167452 100644 --- a/3rdparty/SoundTouch/FIRFilter.h +++ b/3rdparty/SoundTouch/FIRFilter.h @@ -1,8 +1,8 @@ //////////////////////////////////////////////////////////////////////////////// /// -/// General FIR digital filter routines with MMX optimization. +/// General FIR digital filter routines with MMX optimization. /// -/// Note : MMX optimized functions reside in a separate, platform-specific file, +/// Note : MMX optimized functions reside in a separate, platform-specific file, /// e.g. 'mmx_win.cpp' or 'mmx_gcc.cpp' /// /// Author : Copyright (c) Olli Parviainen @@ -11,10 +11,10 @@ /// //////////////////////////////////////////////////////////////////////////////// // -// Last changed : $Date: 2009-02-21 18:00:14 +0200 (Sat, 21 Feb 2009) $ +// Last changed : $Date: 2011-02-13 17:13:57 -0200 (dom, 13 fev 2011) $ // File revision : $Revision: 4 $ // -// $Id: FIRFilter.h 63 2009-02-21 16:00:14Z oparviai $ +// $Id: FIRFilter.h 104 2011-02-13 19:13:57Z oparviai $ // //////////////////////////////////////////////////////////////////////////////// // @@ -48,11 +48,11 @@ namespace soundtouch { -class FIRFilter +class FIRFilter { protected: // Number of FIR filter taps - uint length; + uint length; // Number of FIR filter taps divided by 8 uint lengthDiv8; @@ -65,44 +65,44 @@ protected: // Memory for filter coefficients SAMPLETYPE *filterCoeffs; - virtual uint evaluateFilterStereo(SAMPLETYPE *dest, - const SAMPLETYPE *src, + virtual uint evaluateFilterStereo(SAMPLETYPE *dest, + const SAMPLETYPE *src, uint numSamples) const; - virtual uint evaluateFilterMono(SAMPLETYPE *dest, - const SAMPLETYPE *src, + virtual uint evaluateFilterMono(SAMPLETYPE *dest, + const SAMPLETYPE *src, uint numSamples) const; public: FIRFilter(); virtual ~FIRFilter(); - /// Operator 'new' is overloaded so that it automatically creates a suitable instance + /// Operator 'new' is overloaded so that it automatically creates a suitable instance /// depending on if we've a MMX-capable CPU available or not. static void * operator new(size_t s); static FIRFilter *newInstance(); - /// Applies the filter to the given sequence of samples. - /// Note : The amount of outputted samples is by value of 'filter_length' + /// Applies the filter to the given sequence of samples. + /// Note : The amount of outputted samples is by value of 'filter_length' /// smaller than the amount of input samples. /// /// \return Number of samples copied to 'dest'. - uint evaluate(SAMPLETYPE *dest, - const SAMPLETYPE *src, - uint numSamples, + uint evaluate(SAMPLETYPE *dest, + const SAMPLETYPE *src, + uint numSamples, uint numChannels) const; uint getLength() const; - virtual void setCoefficients(const SAMPLETYPE *coeffs, - uint newLength, + virtual void setCoefficients(const SAMPLETYPE *coeffs, + uint newLength, uint uResultDivFactor); }; // Optional subclasses that implement CPU-specific optimizations: -#ifdef ALLOW_MMX +#ifdef SOUNDTOUCH_ALLOW_MMX /// Class that implements MMX optimized functions exclusive for 16bit integer samples type. class FIRFilterMMX : public FIRFilter @@ -119,29 +119,10 @@ public: virtual void setCoefficients(const short *coeffs, uint newLength, uint uResultDivFactor); }; -#endif // ALLOW_MMX +#endif // SOUNDTOUCH_ALLOW_MMX -#ifdef ALLOW_3DNOW - - /// Class that implements 3DNow! optimized functions exclusive for floating point samples type. - class FIRFilter3DNow : public FIRFilter - { - protected: - float *filterCoeffsUnalign; - float *filterCoeffsAlign; - - virtual uint evaluateFilterStereo(float *dest, const float *src, uint numSamples) const; - public: - FIRFilter3DNow(); - ~FIRFilter3DNow(); - virtual void setCoefficients(const float *coeffs, uint newLength, uint uResultDivFactor); - }; - -#endif // ALLOW_3DNOW - - -#ifdef ALLOW_SSE +#ifdef SOUNDTOUCH_ALLOW_SSE /// Class that implements SSE optimized functions exclusive for floating point samples type. class FIRFilterSSE : public FIRFilter { @@ -157,7 +138,7 @@ public: virtual void setCoefficients(const float *coeffs, uint newLength, uint uResultDivFactor); }; -#endif // ALLOW_SSE +#endif // SOUNDTOUCH_ALLOW_SSE } diff --git a/3rdparty/SoundTouch/Makefile.am b/3rdparty/SoundTouch/Makefile.am index eb39bcc96f..709f0cbd23 100644 --- a/3rdparty/SoundTouch/Makefile.am +++ b/3rdparty/SoundTouch/Makefile.am @@ -1,42 +1,71 @@ ## Process this file with automake to create Makefile.in ## -## $Id: Makefile.am,v 1.3 2006/02/05 18:33:34 Olli Exp $ -## -## Copyright (C) 2003 - David W. Durham +## $Id: Makefile.am 138 2012-04-01 20:00:09Z oparviai $ ## ## This file is part of SoundTouch, an audio processing library for pitch/time adjustments -## +## ## SoundTouch is free software; you can redistribute it and/or modify it under the ## terms of the GNU General Public License as published by the Free Software ## Foundation; either version 2 of the License, or (at your option) any later ## version. -## +## ## SoundTouch is distributed in the hope that it will be useful, but WITHOUT ANY ## WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR ## A PARTICULAR PURPOSE. See the GNU General Public License for more details. -## +## ## You should have received a copy of the GNU General Public License along with ## this program; if not, write to the Free Software Foundation, Inc., 59 Temple ## Place - Suite 330, Boston, MA 02111-1307, USA -AUTOMAKE_OPTIONS = foreign -noinst_HEADERS=AAFilter.h cpu_detect.h FIRFilter.h RateTransposer.h TDStretch.h cpu_detect_x86_gcc.cpp -noinst_LIBRARIES = libSoundTouch.a +include $(top_srcdir)/config/am_include.mk -libSoundTouch_a_CXXFLAGS = -msse -mmmx -libSoundTouch_a_CFLAGS = -msse -mmmx -#lib_LTLIBRARIES=libSoundTouch.la -# the mmx_gcc.cpp and cpu_detect_x86_gcc.cpp may need to be conditionally included here from things discovered in configure.ac -libSoundTouch_a_SOURCES=AAFilter.cpp FIRFilter.cpp FIFOSampleBuffer.cpp mmx_optimized.cpp sse_optimized.cpp \ -RateTransposer.cpp SoundTouch.cpp TDStretch.cpp WavFile.cpp cpu_detect_x86_gcc.cpp +# set to something if you want other stuff to be included in the distribution tarball +EXTRA_DIST=SoundTouch.dsp SoundTouch.dsw SoundTouch.sln SoundTouch.vcproj + +noinst_HEADERS=AAFilter.h cpu_detect.h cpu_detect_x86.cpp FIRFilter.h RateTransposer.h TDStretch.h PeakFinder.h + +lib_LTLIBRARIES=libSoundTouch.la +# +libSoundTouch_la_SOURCES=AAFilter.cpp FIRFilter.cpp FIFOSampleBuffer.cpp RateTransposer.cpp SoundTouch.cpp TDStretch.cpp cpu_detect_x86.cpp BPMDetect.cpp PeakFinder.cpp + + +# Compiler flags +AM_CXXFLAGS=-O3 -fcheck-new -I../../include + +# Compile the files that need MMX and SSE individually. +libSoundTouch_la_LIBADD=libSoundTouchMMX.la libSoundTouchSSE.la +noinst_LTLIBRARIES=libSoundTouchMMX.la libSoundTouchSSE.la +libSoundTouchMMX_la_SOURCES=mmx_optimized.cpp +libSoundTouchSSE_la_SOURCES=sse_optimized.cpp + +# We enable optimizations by default. +# If MMX is supported compile with -mmmx. +# Do not assume -msse is also supported. +if HAVE_MMX +libSoundTouchMMX_la_CXXFLAGS = -mmmx $(AM_CXXFLAGS) +else +libSoundTouchMMX_la_CXXFLAGS = $(AM_CXXFLAGS) +endif + +# We enable optimizations by default. +# If SSE is supported compile with -msse. +if HAVE_SSE +libSoundTouchSSE_la_CXXFLAGS = -msse $(AM_CXXFLAGS) +else +libSoundTouchSSE_la_CXXFLAGS = $(AM_CXXFLAGS) +endif + +# Let the user disable optimizations if he wishes to. +if !X86_OPTIMIZATIONS +libSoundTouchMMX_la_CXXFLAGS = $(AM_CXXFLAGS) +libSoundTouchSSE_la_CXXFLAGS = $(AM_CXXFLAGS) +endif -# ??? test for -fcheck-new in configure.ac -# other compiler flags to add -AM_CXXFLAGS=-O3 -msse -fcheck-new -#-I../../include # other linking flags to add -#libSoundTouch_la_LIBADD= - +# noinst_LTLIBRARIES = libSoundTouchOpt.la +# libSoundTouch_la_LIBADD = libSoundTouchOpt.la +# libSoundTouchOpt_la_SOURCES = mmx_optimized.cpp sse_optimized.cpp +# libSoundTouchOpt_la_CXXFLAGS = -O3 -msse -fcheck-new -I../../include diff --git a/3rdparty/SoundTouch/PeakFinder.cpp b/3rdparty/SoundTouch/PeakFinder.cpp new file mode 100644 index 0000000000..71203983f6 --- /dev/null +++ b/3rdparty/SoundTouch/PeakFinder.cpp @@ -0,0 +1,276 @@ +//////////////////////////////////////////////////////////////////////////////// +/// +/// Peak detection routine. +/// +/// The routine detects highest value on an array of values and calculates the +/// precise peak location as a mass-center of the 'hump' around the peak value. +/// +/// Author : Copyright (c) Olli Parviainen +/// Author e-mail : oparviai 'at' iki.fi +/// SoundTouch WWW: http://www.surina.net/soundtouch +/// +//////////////////////////////////////////////////////////////////////////////// +// +// Last changed : $Date: 2012-12-28 17:52:47 -0200 (sex, 28 dez 2012) $ +// File revision : $Revision: 4 $ +// +// $Id: PeakFinder.cpp 164 2012-12-28 19:52:47Z oparviai $ +// +//////////////////////////////////////////////////////////////////////////////// +// +// License : +// +// SoundTouch audio processing library +// Copyright (c) Olli Parviainen +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +//////////////////////////////////////////////////////////////////////////////// + +#include +#include + +#include "PeakFinder.h" + +using namespace soundtouch; + +#define max(x, y) (((x) > (y)) ? (x) : (y)) + + +PeakFinder::PeakFinder() +{ + minPos = maxPos = 0; +} + + +// Finds real 'top' of a peak hump from neighnourhood of the given 'peakpos'. +int PeakFinder::findTop(const float *data, int peakpos) const +{ + int i; + int start, end; + float refvalue; + + refvalue = data[peakpos]; + + // seek within ±10 points + start = peakpos - 10; + if (start < minPos) start = minPos; + end = peakpos + 10; + if (end > maxPos) end = maxPos; + + for (i = start; i <= end; i ++) + { + if (data[i] > refvalue) + { + peakpos = i; + refvalue = data[i]; + } + } + + // failure if max value is at edges of seek range => it's not peak, it's at slope. + if ((peakpos == start) || (peakpos == end)) return 0; + + return peakpos; +} + + +// Finds 'ground level' of a peak hump by starting from 'peakpos' and proceeding +// to direction defined by 'direction' until next 'hump' after minimum value will +// begin +int PeakFinder::findGround(const float *data, int peakpos, int direction) const +{ + int lowpos; + int pos; + int climb_count; + float refvalue; + float delta; + + climb_count = 0; + refvalue = data[peakpos]; + lowpos = peakpos; + + pos = peakpos; + + while ((pos > minPos+1) && (pos < maxPos-1)) + { + int prevpos; + + prevpos = pos; + pos += direction; + + // calculate derivate + delta = data[pos] - data[prevpos]; + if (delta <= 0) + { + // going downhill, ok + if (climb_count) + { + climb_count --; // decrease climb count + } + + // check if new minimum found + if (data[pos] < refvalue) + { + // new minimum found + lowpos = pos; + refvalue = data[pos]; + } + } + else + { + // going uphill, increase climbing counter + climb_count ++; + if (climb_count > 5) break; // we've been climbing too long => it's next uphill => quit + } + } + return lowpos; +} + + +// Find offset where the value crosses the given level, when starting from 'peakpos' and +// proceeds to direction defined in 'direction' +int PeakFinder::findCrossingLevel(const float *data, float level, int peakpos, int direction) const +{ + float peaklevel; + int pos; + + peaklevel = data[peakpos]; + assert(peaklevel >= level); + pos = peakpos; + while ((pos >= minPos) && (pos < maxPos)) + { + if (data[pos + direction] < level) return pos; // crossing found + pos += direction; + } + return -1; // not found +} + + +// Calculates the center of mass location of 'data' array items between 'firstPos' and 'lastPos' +double PeakFinder::calcMassCenter(const float *data, int firstPos, int lastPos) const +{ + int i; + float sum; + float wsum; + + sum = 0; + wsum = 0; + for (i = firstPos; i <= lastPos; i ++) + { + sum += (float)i * data[i]; + wsum += data[i]; + } + + if (wsum < 1e-6) return 0; + return sum / wsum; +} + + + +/// get exact center of peak near given position by calculating local mass of center +double PeakFinder::getPeakCenter(const float *data, int peakpos) const +{ + float peakLevel; // peak level + int crosspos1, crosspos2; // position where the peak 'hump' crosses cutting level + float cutLevel; // cutting value + float groundLevel; // ground level of the peak + int gp1, gp2; // bottom positions of the peak 'hump' + + // find ground positions. + gp1 = findGround(data, peakpos, -1); + gp2 = findGround(data, peakpos, 1); + + groundLevel = 0.5f * (data[gp1] + data[gp2]); + peakLevel = data[peakpos]; + + // calculate 70%-level of the peak + cutLevel = 0.70f * peakLevel + 0.30f * groundLevel; + // find mid-level crossings + crosspos1 = findCrossingLevel(data, cutLevel, peakpos, -1); + crosspos2 = findCrossingLevel(data, cutLevel, peakpos, 1); + + if ((crosspos1 < 0) || (crosspos2 < 0)) return 0; // no crossing, no peak.. + + // calculate mass center of the peak surroundings + return calcMassCenter(data, crosspos1, crosspos2); +} + + + +double PeakFinder::detectPeak(const float *data, int aminPos, int amaxPos) +{ + + int i; + int peakpos; // position of peak level + double highPeak, peak; + + this->minPos = aminPos; + this->maxPos = amaxPos; + + // find absolute peak + peakpos = minPos; + peak = data[minPos]; + for (i = minPos + 1; i < maxPos; i ++) + { + if (data[i] > peak) + { + peak = data[i]; + peakpos = i; + } + } + + // Calculate exact location of the highest peak mass center + highPeak = getPeakCenter(data, peakpos); + peak = highPeak; + + // Now check if the highest peak were in fact harmonic of the true base beat peak + // - sometimes the highest peak can be Nth harmonic of the true base peak yet + // just a slightly higher than the true base + + for (i = 3; i < 10; i ++) + { + double peaktmp, harmonic; + int i1,i2; + + harmonic = (double)i * 0.5; + peakpos = (int)(highPeak / harmonic + 0.5f); + if (peakpos < minPos) break; + peakpos = findTop(data, peakpos); // seek true local maximum index + if (peakpos == 0) continue; // no local max here + + // calculate mass-center of possible harmonic peak + peaktmp = getPeakCenter(data, peakpos); + + // accept harmonic peak if + // (a) it is found + // (b) is within ±4% of the expected harmonic interval + // (c) has at least half x-corr value of the max. peak + + double diff = harmonic * peaktmp / highPeak; + if ((diff < 0.96) || (diff > 1.04)) continue; // peak too afar from expected + + // now compare to highest detected peak + i1 = (int)(highPeak + 0.5); + i2 = (int)(peaktmp + 0.5); + if (data[i2] >= 0.4*data[i1]) + { + // The harmonic is at least half as high primary peak, + // thus use the harmonic peak instead + peak = peaktmp; + } + } + + return peak; +} diff --git a/3rdparty/SoundTouch/PeakFinder.h b/3rdparty/SoundTouch/PeakFinder.h new file mode 100644 index 0000000000..c781643304 --- /dev/null +++ b/3rdparty/SoundTouch/PeakFinder.h @@ -0,0 +1,97 @@ +//////////////////////////////////////////////////////////////////////////////// +/// +/// The routine detects highest value on an array of values and calculates the +/// precise peak location as a mass-center of the 'hump' around the peak value. +/// +/// Author : Copyright (c) Olli Parviainen +/// Author e-mail : oparviai 'at' iki.fi +/// SoundTouch WWW: http://www.surina.net/soundtouch +/// +//////////////////////////////////////////////////////////////////////////////// +// +// Last changed : $Date: 2011-12-30 18:33:46 -0200 (sex, 30 dez 2011) $ +// File revision : $Revision: 4 $ +// +// $Id: PeakFinder.h 132 2011-12-30 20:33:46Z oparviai $ +// +//////////////////////////////////////////////////////////////////////////////// +// +// License : +// +// SoundTouch audio processing library +// Copyright (c) Olli Parviainen +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +//////////////////////////////////////////////////////////////////////////////// + +#ifndef _PeakFinder_H_ +#define _PeakFinder_H_ + +namespace soundtouch +{ + +class PeakFinder +{ +protected: + /// Min, max allowed peak positions within the data vector + int minPos, maxPos; + + /// Calculates the mass center between given vector items. + double calcMassCenter(const float *data, ///< Data vector. + int firstPos, ///< Index of first vector item beloging to the peak. + int lastPos ///< Index of last vector item beloging to the peak. + ) const; + + /// Finds the data vector index where the monotoniously decreasing signal crosses the + /// given level. + int findCrossingLevel(const float *data, ///< Data vector. + float level, ///< Goal crossing level. + int peakpos, ///< Peak position index within the data vector. + int direction /// Direction where to proceed from the peak: 1 = right, -1 = left. + ) const; + + // Finds real 'top' of a peak hump from neighnourhood of the given 'peakpos'. + int findTop(const float *data, int peakpos) const; + + + /// Finds the 'ground' level, i.e. smallest level between two neighbouring peaks, to right- + /// or left-hand side of the given peak position. + int findGround(const float *data, /// Data vector. + int peakpos, /// Peak position index within the data vector. + int direction /// Direction where to proceed from the peak: 1 = right, -1 = left. + ) const; + + /// get exact center of peak near given position by calculating local mass of center + double getPeakCenter(const float *data, int peakpos) const; + +public: + /// Constructor. + PeakFinder(); + + /// Detect exact peak position of the data vector by finding the largest peak 'hump' + /// and calculating the mass-center location of the peak hump. + /// + /// \return The location of the largest base harmonic peak hump. + double detectPeak(const float *data, /// Data vector to be analyzed. The data vector has + /// to be at least 'maxPos' items long. + int minPos, ///< Min allowed peak location within the vector data. + int maxPos ///< Max allowed peak location within the vector data. + ); +}; + +} + +#endif // _PeakFinder_H_ diff --git a/3rdparty/SoundTouch/README.html b/3rdparty/SoundTouch/README.html index 15a34c8648..5b2bcbb240 100644 --- a/3rdparty/SoundTouch/README.html +++ b/3rdparty/SoundTouch/README.html @@ -1,6 +1,7 @@ + SoundTouch library README @@ -9,32 +10,26 @@ content="Readme file for SoundTouch audio processing library"> - SoundTouch library README - +
-

SoundTouch audio processing library v1.5.0 -

-

SoundTouch library Copyright (c) Olli -Parviainen 2002-2009

+

SoundTouch audio processing library v1.7.1

+

SoundTouch library Copyright © Olli Parviainen 2001-2012


1. Introduction

-

SoundTouch is an open-source audio -processing library that allows changing the sound tempo, pitch -and playback rate parameters independently from each other, i.e.:

+

SoundTouch is an open-source audio processing library that allows +changing the sound tempo, pitch and playback rate parameters +independently from each other, i.e.:

    -
  • Sound tempo can be increased or decreased while -maintaining the original pitch
  • -
  • Sound pitch can be increased or decreased while -maintaining the original tempo
  • -
  • Change playback rate that affects both tempo -and pitch at the same time
  • -
  • Choose any combination of tempo/pitch/rate
  • +
  • Sound tempo can be increased or decreased while maintaining the +original pitch
  • +
  • Sound pitch can be increased or decreased while maintaining the +original tempo
  • +
  • Change playback rate that affects both tempo and pitch at the +same time
  • +
  • Choose any combination of tempo/pitch/rate

1.1 Contact information

Author email: oparviai 'at' iki.fi

@@ -42,50 +37,54 @@ and pitch at the same time

2. Compiling SoundTouch

Before compiling, notice that you can choose the sample data format -if it's desirable to use floating point sample -data instead of 16bit integers. See section "sample data format" -for more information.

+if it's desirable to use floating point sample data instead of 16bit +integers. See section "sample data format" for more information.

2.1. Building in Microsoft Windows

Project files for Microsoft Visual C++ 6.0 and Visual C++ .NET are -supplied with the source code package. 

-

Please notice that SoundTouch -library uses processor-specific optimizations for Pentium III and AMD -processors. Visual Studio .NET and later versions supports the required -instructions by default, but Visual Studio 6.0 requires a processor pack upgrade -to be installed in order to support these optimizations. The processor pack upgrade can be downloaded from -Microsoft site at this URL:

-

http://msdn.microsoft.com/en-us/vstudio/aa718349.aspx

-

If the above URL is unavailable or removed, go -to http://msdn.microsoft.com -and perform a search with keywords "processor pack".

-

To build the binaries with Visual C++ -compiler, either run "make-win.bat" script, or open the -appropriate project files in source code directories with Visual -Studio. The final executable will appear under the "SoundTouch\bin" -directory. If using the Visual Studio IDE instead of the make-win.bat script, directories bin and -lib may need to be created manually to the SoundTouch -package root for the final executables. The make-win.bat script -creates these directories automatically. +supplied with the source code package.

+

Please notice that SoundTouch library uses processor-specific +optimizations for Pentium III and AMD processors. Visual Studio .NET +and later versions supports the required instructions by default, but +Visual Studio 6.0 requires a processor pack upgrade to be installed in +order to support these optimizations. The processor pack upgrade can be +downloaded from Microsoft site at this URL:

+

http://msdn.microsoft.com/en-us/vstudio/aa718349.aspx

+

If the above URL is unavailable or removed, go to http://msdn.microsoft.com and +perform a search with keywords "processor pack".

+

To build the binaries with Visual C++ compiler, either run +"make-win.bat" script, or open the appropriate project files in source +code directories with Visual Studio. The final executable will appear +under the "SoundTouch\bin" directory. If using the Visual Studio IDE +instead of the make-win.bat script, directories bin and lib may need to +be created manually to the SoundTouch package root for the final +executables. The make-win.bat script creates these directories +automatically.

2.2. Building in Gnu platforms

-

The SoundTouch library can be compiled in -practically any platform supporting GNU compiler (GCC) tools. -SoundTouch have been tested with gcc version 3.3.4., but it -shouldn't be very specific about the gcc version. Assembler-level -performance optimizations for GNU platform are currently available in -x86 platforms only, they are automatically disabled and replaced with -standard C routines in other processor platforms.

-

To build and install the binaries, run the -following commands in the SoundTouch/ directory:

+

The SoundTouch library compiles in practically any platform +supporting GNU compiler (GCC) tools. SoundTouch requires GCC version 4.3 or later.

+

To build and install the binaries, run the following commands in +/soundtouch directory:

+ + + + @@ -93,8 +92,7 @@ environment.

make         -
@@ -102,175 +100,163 @@ SoundStretch utility.

make install -
+
./bootstrap  -
+
Creates "configure" file with +local autoconf/automake toolset.
+
./configure  -
-

Configures the SoundTouch package for the local -environment.

+

Configures the SoundTouch package for the local environment. +Notice that "configure" file is not available before running the +"./bootstrap" command as above.
+

-

Builds the SoundTouch library & -SoundStretch utility.

+

Builds the SoundTouch library & SoundStretch utility.

-

Installs the SoundTouch & BPM libraries -to /usr/local/lib and SoundStretch utility to /usr/local/bin. -Please notice that 'root' privileges may be required to install the -binaries to the destination locations.

+

Installs the SoundTouch & BPM libraries to /usr/local/lib +and SoundStretch utility to /usr/local/bin. Please notice that +'root' privileges may be required to install the binaries to the +destination locations.

2.2.1 Required GNU tools 

-

Bash shell, GNU C++ compiler, libtool, autoconf and automake tools are required -for compiling -the SoundTouch library. These are usually included with the GNU/Linux distribution, but if -not, install these packages first. For example, in Ubuntu Linux these can be acquired and -installed with the following command:

-
sudo apt-get install automake autoconf libtool build-essential
+

Bash shell, GNU C++ compiler, libtool, autoconf and automake tools +are required for compiling the SoundTouch library. These are usually +included with the GNU/Linux distribution, but if not, install these +packages first. For example, Ubuntu Linux can acquire and install +these with the following command:

+
sudo apt-get install automake autoconf libtool build-essential

2.2.2 Problems with GCC compiler compatibility

-

At the release time the SoundTouch package has been tested to compile in -GNU/Linux platform. However, in past it's happened that new gcc versions aren't -necessarily compatible with the assembler settings used in the optimized -routines. If you have problems getting the -SoundTouch library compiled, try the workaround of disabling the optimizations -by editing the file "include/STTypes.h" and removing the following -definition there:

+

At the release time the SoundTouch package has been tested to +compile in GNU/Linux platform. However, If you have problems getting the +SoundTouch library compiled, try disabling optimizations that are specific for +x86 processors by running ./configure script with switch

-
#define ALLOW_OPTIMIZATIONS 1
+
--enable-x86-optimizations=no
-

2.2.3 Problems with configure script or build process 

-

Incompatibilities between various GNU toolchain versions may cause errors when running the "configure" script or building the source -codes, if your GNU tool versions are not compatible with the versions used for -preparing the SoundTouch kit. 

-

To resolve the issue, regenerate the configure scripts with your local tool -set by running -the "./bootstrap" script included in the SoundTouch source code -kit. After that, run the configure script and make as usually.

-

2.2.4 Compiler issues with non-x86 processors

-

SoundTouch library works also on non-x86 processors.

-

However, in case that you get compiler errors when trying to compile for non-Intel processor, edit the file -"source\SoundTouch\Makefile.am" and remove the "-msse2" -flag on the AM_CXXFLAGS line:

-
AM_CXXFLAGS=-O3 -fcheck-new -I../../include    # Note: -msse2 flag removed!
-

After that, run "./bootstrap" script, and then run configure -and make again.

+ +Alternatively, if you don't use GNU Configure system, edit file "include/STTypes.h" +directly and remove the following definition:
+
#define SOUNDTOUCH_ALLOW_X86_OPTIMIZATIONS 1
+
+ +

2.2.3 Compiling Shared Library / DLL version

+

+ The GNU compilation does not automatically create a shared-library version of + SoundTouch (.so or .dll). If such is desired, then you can create it as follows + after running the usual compilation:

+
+
g++ -shared -static -DDLL_EXPORTS -I../../include -o SoundTouch.dll \
+     SoundTouchDLL.cpp ../SoundTouch/.libs/libSoundTouch.a
+sstrip SoundTouch.dll
+
+ +

2.1. Building in Android

+

Android compilation instructions are within the + source code package, see file "source/Android-lib/README-SoundTouch-Android.html" + in the package.

+
-

3. About implementation & Usage tips

-

3.1. Supported sample data formats

-

The sample data format can be chosen -between 16bit signed integer and 32bit floating point values, the -default is 32bit floating point.

- -

-In Windows environment, the sample data format is chosen -in file "STTypes.h" by choosing one of the following -defines:

+

3. About implementation & Usage tips

3.1. Supported sample data formats

+

The sample data format can be chosen between 16bit signed integer +and 32bit floating point values, the default is 32bit floating point.

+

In Windows environment, the sample data format is chosen in file +"STTypes.h" by choosing one of the following defines:

    -
  • #define INTEGER_SAMPLES -for 16bit signed -integer
  • -
  • #define FLOAT_SAMPLES for -32bit floating point
  • +
  • #define +SOUNDTOUCH_INTEGER_SAMPLES for 16bit signed integer
  • +
  • #define SOUNDTOUCH_FLOAT_SAMPLES for 32bit floating +point
-

-In GNU environment, the floating sample format is used by default, but -integer sample format can be chosen by giving the -following switch to the configure script: +

In GNU environment, the floating sample format is used by default, +but integer sample format can be chosen by giving the following switch +to the configure script:

-
./configure --enable-integer-samples
+
./configure --enable-integer-samples
- -

The sample data can have either single (mono) -or double (stereo) audio channel. Stereo data is interleaved so -that every other data value is for left channel and every second -for right channel. Notice that while it'd be possible in theory -to process stereo sound as two separate mono channels, this isn't -recommended because processing the channels separately would -result in losing the phase coherency between the channels, which -consequently would ruin the stereo effect.

-

Sample rates between 8000-48000H are -supported.

+

The sample data can have either single (mono) or double (stereo) +audio channel. Stereo data is interleaved so that every other data +value is for left channel and every second for right channel. Notice +that while it'd be possible in theory to process stereo sound as two +separate mono channels, this isn't recommended because processing the +channels separately would result in losing the phase coherency between +the channels, which consequently would ruin the stereo effect.

+

Sample rates between 8000-48000H are supported.

3.2. Processing latency

-

The processing and latency constraints of -the SoundTouch library are:

+

The processing and latency constraints of the SoundTouch library are:

    -
  • Input/output processing latency for the -SoundTouch processor is around 100 ms. This is when time-stretching is -used. If the rate transposing effect alone is used, the latency -requirement -is much shorter, see section 'About algorithms'.
  • -
  • Processing CD-quality sound (16bit stereo -sound with 44100H sample rate) in real-time or faster is possible -starting from processors equivalent to Intel Pentium 133Mh or better, -if using the "quick" processing algorithm. If not using the "quick" -mode or -if floating point sample data are being used, several times more CPU -power is typically required.
  • +
  • Input/output processing latency for the SoundTouch processor is +around 100 ms. This is when time-stretching is used. If the rate +transposing effect alone is used, the latency requirement is much +shorter, see section 'About algorithms'.
  • +
  • Processing CD-quality sound (16bit stereo sound with 44100H +sample rate) in real-time or faster is possible starting from +processors equivalent to Intel Pentium 133Mh or better, if using the +"quick" processing algorithm. If not using the "quick" mode or if +floating point sample data are being used, several times more CPU power +is typically required.

3.3. About algorithms

-

SoundTouch provides three seemingly -independent effects: tempo, pitch and playback rate control. -These three controls are implemented as combination of two primary -effects, sample rate transposing and time-stretching.

-

Sample rate transposing affects -both the audio stream duration and pitch. It's implemented simply -by converting the original audio sample stream to the  desired -duration by interpolating from the original audio samples. In SoundTouch, linear interpolation with anti-alias filtering is -used. Theoretically a higher-order interpolation provide better -result than 1st order linear interpolation, but in audio -application linear interpolation together with anti-alias -filtering performs subjectively about as well as higher-order -filtering would.

-

Time-stretching means changing -the audio stream duration without affecting it's pitch. SoundTouch -uses WSOLA-like time-stretching routines that operate in the time -domain. Compared to sample rate transposing, time-stretching is a -much heavier operation and also requires a longer processing -"window" of sound samples used by the -processing algorithm, thus increasing the algorithm input/output -latency. Typical i/o latency for the SoundTouch -time-stretch algorithm is around 100 ms.

-

Sample rate transposing and time-stretching -are then used together to produce the tempo, pitch and rate -controls:

+

SoundTouch provides three seemingly independent effects: tempo, +pitch and playback rate control. These three controls are implemented +as combination of two primary effects, sample rate transposing +and time-stretching.

+

Sample rate transposing affects both the audio stream +duration and pitch. It's implemented simply by converting the original +audio sample stream to the  desired duration by interpolating from +the original audio samples. In SoundTouch, linear interpolation with +anti-alias filtering is used. Theoretically a higher-order +interpolation provide better result than 1st order linear +interpolation, but in audio application linear interpolation together +with anti-alias filtering performs subjectively about as well as +higher-order filtering would.

+

Time-stretching means changing the audio stream duration +without affecting it's pitch. SoundTouch uses WSOLA-like +time-stretching routines that operate in the time domain. Compared to +sample rate transposing, time-stretching is a much heavier operation +and also requires a longer processing "window" of sound samples used by +the processing algorithm, thus increasing the algorithm input/output +latency. Typical i/o latency for the SoundTouch time-stretch algorithm +is around 100 ms.

+

Sample rate transposing and time-stretching are then used together +to produce the tempo, pitch and rate controls:

    -
  • 'Tempo' control is -implemented purely by time-stretching.
  • -
  • 'Rate' control is implemented -purely by sample rate transposing.
  • -
  • 'Pitch' control is -implemented as a combination of time-stretching and sample rate -transposing. For example, to increase pitch the audio stream is first -time-stretched to longer duration (without affecting pitch) and then -transposed back to original duration by sample rate transposing, which -simultaneously reduces duration and increases pitch. The result is -original duration but increased pitch.
  • +
  • 'Tempo' control is implemented purely by +time-stretching.
  • +
  • 'Rate' control is implemented purely by sample +rate transposing.
  • +
  • 'Pitch' control is implemented as a +combination of time-stretching and sample rate transposing. For +example, to increase pitch the audio stream is first time-stretched to +longer duration (without affecting pitch) and then transposed back to +original duration by sample rate transposing, which simultaneously +reduces duration and increases pitch. The result is original duration +but increased pitch.

3.4 Tuning the algorithm parameters

-

The time-stretch algorithm has few -parameters that can be tuned to optimize sound quality for -certain application. The current default parameters have been -chosen by iterative if-then analysis (read: "trial and error") -to obtain best subjective sound quality in pop/rock music -processing, but in applications processing different kind of -sound the default parameter set may result into a sub-optimal -result.

-

The time-stretch algorithm default -parameter values are set by the following #defines in file "TDStretch.h":

+

The time-stretch algorithm has few parameters that can be tuned to +optimize sound quality for certain application. The current default +parameters have been chosen by iterative if-then analysis (read: "trial +and error") to obtain best subjective sound quality in pop/rock music +processing, but in applications processing different kind of sound the +default parameter set may result into a sub-optimal result.

+

The time-stretch algorithm default parameter values are set by the +following #defines in file "TDStretch.h":

-
#define DEFAULT_SEQUENCE_MS     AUTOMATIC
-#define DEFAULT_SEEKWINDOW_MS   AUTOMATIC
-#define DEFAULT_OVERLAP_MS      8
+
#define DEFAULT_SEQUENCE_MS     AUTOMATIC
#define DEFAULT_SEEKWINDOW_MS AUTOMATIC
#define DEFAULT_OVERLAP_MS 8
-

These parameters affect to the time-stretch -algorithm as follows:

+

These parameters affect to the time-stretch algorithm as follows:

    -
  • DEFAULT_SEQUENCE_MS: This is -the default length of a single processing sequence in milliseconds -which determines the how the original sound is chopped in -the time-stretch algorithm. Larger values mean fewer sequences -are used in processing. In principle a larger value sounds better when -slowing down the tempo, but worse when increasing the tempo and vice -versa. 
    +
  • DEFAULT_SEQUENCE_MS: This is the default +length of a single processing sequence in milliseconds which determines +the how the original sound is chopped in the time-stretch algorithm. +Larger values mean fewer sequences are used in processing. In principle +a larger value sounds better when slowing down the tempo, but worse +when increasing the tempo and vice versa. 

    - By default, this setting value is calculated automatically according to - tempo value.
    +By default, this setting value is calculated automatically according to +tempo value.
  • -
  • DEFAULT_SEEKWINDOW_MS: The seeking window +
  • DEFAULT_SEEKWINDOW_MS: The seeking window default length in milliseconds is for the algorithm that seeks the best -possible overlapping location. This determines from how -wide a sample "window" the algorithm can use to find an optimal mixing -location when the sound sequences are to be linked back together. 
    +possible overlapping location. This determines from how wide a sample +"window" the algorithm can use to find an optimal mixing location when +the sound sequences are to be linked back together. 

    The bigger this window setting is, the higher the possibility to find a better mixing position becomes, but at the same time large values may @@ -279,474 +265,513 @@ chosen at more uneven intervals. If there's a disturbing artifact that sounds as if a constant frequency was drifting around, try reducing this setting.

    - By default, this setting value is calculated automatically according to - tempo value.
    +By default, this setting value is calculated automatically according to +tempo value.
  • -
  • DEFAULT_OVERLAP_MS: Overlap -length in milliseconds. When the sound sequences are mixed back -together to form again a continuous sound stream, this parameter -defines how much the ends of the consecutive sequences will overlap with each other.
    +
  • DEFAULT_OVERLAP_MS: Overlap length in +milliseconds. When the sound sequences are mixed back together to form +again a continuous sound stream, this parameter defines how much the +ends of the consecutive sequences will overlap with each other.

    - This shouldn't be that critical parameter. If you reduce the +This shouldn't be that critical parameter. If you reduce the DEFAULT_SEQUENCE_MS setting by a large amount, you might wish to try a smaller value on this.
-

Notice that these parameters can also be -set during execution time with functions "TDStretch::setParameters()" -and "SoundTouch::setSetting()".

-

The table below summaries how the -parameters can be adjusted for different applications:

+

Notice that these parameters can also be set during execution time +with functions "TDStretch::setParameters()" and "SoundTouch::setSetting()".

+

The table below summaries how the parameters can be adjusted for +different applications:

- - - + + + - - - - + + + + - - - - + + + + - + - - + +
Parameter nameDefault value -magnitudeLarger value -affects...Smaller value -affects...Default value magnitudeLarger value affects...Smaller value affects... Effect to CPU burden
SEQUENCE_MS
Default value is relatively -large, chosen for slowing down music tempoLarger value is usually -better for slowing down tempo. Growing the value decelerates the -"echoing" artifact when slowing down the tempo.Smaller value might be better -for speeding up tempo. Reducing the value accelerates the "echoing" -artifact when slowing down the tempo Increasing the parameter -value reduces computation burdenDefault value is relatively large, chosen for +slowing down music tempoLarger value is usually better for slowing down +tempo. Growing the value decelerates the "echoing" artifact when +slowing down the tempo.Smaller value might be better for speeding up +tempo. Reducing the value accelerates the "echoing" artifact when +slowing down the tempo Increasing the parameter value reduces +computation burden
SEEKWINDOW_MS
Default value is relatively -large, chosen for slowing down music tempoLarger value eases finding a -good mixing position, but may cause a "drifting" artifactSmaller reduce possibility to -find a good mixing position, but reduce the "drifting" artifact.Increasing the parameter -value increases computation burdenDefault value is relatively large, chosen for +slowing down music tempoLarger value eases finding a good mixing +position, but may cause a "drifting" artifactSmaller reduce possibility to find a good mixing +position, but reduce the "drifting" artifact.Increasing the parameter value increases +computation burden
OVERLAP_MS
Default value is relatively -large, chosen to suit with above parameters.Default value is relatively large, chosen to +suit with above parameters.  If you reduce the "sequence -ms" setting, you might wish to try a smaller value.Increasing the parameter -value increases computation burdenIf you reduce the "sequence ms" setting, you +might wish to try a smaller value.Increasing the parameter value increases +computation burden

3.5 Performance Optimizations

General optimizations:

-

The time-stretch routine has a 'quick' mode -that substantially speeds up the algorithm but may degrade the -sound quality by a small amount. This mode is activated by -calling SoundTouch::setSetting() function with parameter  id -of SETTING_USE_QUICKSEEK and value "1", i.e.

+

The time-stretch routine has a 'quick' mode that substantially +speeds up the algorithm but may degrade the sound quality by a small +amount. This mode is activated by calling SoundTouch::setSetting() +function with parameter  id of SETTING_USE_QUICKSEEK and value +"1", i.e.

setSetting(SETTING_USE_QUICKSEEK, 1);

CPU-specific optimizations:

    -
  • Intel MMX optimized routines are used with -compatible CPUs when 16bit integer sample type is used. MMX optimizations are available both in Win32 and Gnu/x86 platforms. -Compatible processors are Intel PentiumMMX and later; AMD K6-2, Athlon -and later.
  • -
  • Intel SSE optimized routines are used with -compatible CPUs when floating point sample type is used. SSE optimizations are currently implemented for Win32 platform only. -Processors compatible with SSE extension are Intel processors starting -from Pentium-III, and AMD processors starting from Athlon XP.
  • -
  • AMD 3DNow! optimized routines are used with -compatible CPUs when floating point sample type is used, but SSE -extension isn't supported . 3DNow! optimizations are currently -implemented for Win32 platform only. These optimizations are used in -AMD K6-2 and Athlon (classic) CPU's; better performing SSE routines are -used with AMD processor starting from Athlon XP.
  • +
  • Intel MMX optimized routines are used with compatible CPUs when +16bit integer sample type is used. MMX optimizations are available both +in Win32 and Gnu/x86 platforms. Compatible processors are Intel +PentiumMMX and later; AMD K6-2, Athlon and later.
  • +
  • Intel SSE optimized routines are used with compatible CPUs when +floating point sample type is used. SSE optimizations are currently +implemented for Win32 platform only. Processors compatible with SSE +extension are Intel processors starting from Pentium-III, and AMD +processors starting from Athlon XP.
  • +
  • AMD 3DNow! optimized routines are used with compatible CPUs when +floating point sample type is used, but SSE extension isn't supported . +3DNow! optimizations are currently implemented for Win32 platform only. +These optimizations are used in AMD K6-2 and Athlon (classic) CPU's; +better performing SSE routines are used with AMD processor starting +from Athlon XP.

4. SoundStretch audio processing utility

SoundStretch audio processing utility
-Copyright (c) Olli Parviainen 2002-2009

-

SoundStretch is a simple command-line -application that can change tempo, pitch and playback rates of -WAV sound files. This program is intended primarily to -demonstrate how the "SoundTouch" library can be used to -process sound in your own program, but it can as well be used for -processing sound files.

+ Copyright (c) Olli Parviainen 2002-2012

+

SoundStretch is a simple command-line application that can change +tempo, pitch and playback rates of WAV sound files. This program is +intended primarily to demonstrate how the "SoundTouch" library can be +used to process sound in your own program, but it can as well be used +for processing sound files.

4.1. SoundStretch Usage Instructions

SoundStretch Usage syntax:

soundstretch infilename outfilename [switches]

Where:

- +
- + - + - +
-
"infilename"
+
"infilename"
Name of the input sound -data file (in .WAV audio file format). Give "stdin" as filename to use - standard input pipe. Name of the input sound data file (in .WAV audio +file format). Give "stdin" as filename to use standard input pipe.
-
"outfilename"
+
"outfilename"
Name of the output sound -file where the resulting sound is saved (in .WAV audio file format). -This parameter may be omitted if you  don't want to save the -output -(e.g. when only calculating BPM rate with '-bpm' switch). Give "stdout" - as filename to use standard output pipe.Name of the output sound file where the +resulting sound is saved (in .WAV audio file format). This parameter +may be omitted if you  don't want to save the output (e.g. when +only calculating BPM rate with '-bpm' switch). Give "stdout" as +filename to use standard output pipe.
 [switches]
Are one or more control -switches.Are one or more control switches.

Available control switches are:

- +
- + - + - + - + - + - + - +
-tempo=n 
Change the sound tempo by n -percents (n = -95.0 .. +5000.0 %) Change the sound tempo by n percents (n = -95.0 +.. +5000.0 %)
-pitch=n
Change the sound pitch by n -semitones (n = -60.0 .. + 60.0 semitones) Change the sound pitch by n semitones (n = -60.0 +.. + 60.0 semitones)
-rate=n
Change the sound playback rate by -n percents (n = -95.0 .. +5000.0 %) Change the sound playback rate by n percents (n += -95.0 .. +5000.0 %)
-bpm=n
Detect the Beats-Per-Minute (BPM) rate of the sound and adjust the tempo to meet 'n' - BPMs. When this switch is - applied, the "-tempo" switch is ignored. If "=n" is -omitted, i.e. switch "-bpm" is used alone, then the BPM rate is - estimated and displayed, but tempo not adjusted according to the BPM -value. Detect the Beats-Per-Minute (BPM) rate of the +sound and adjust the tempo to meet 'n' BPMs. When this switch is +applied, the "-tempo" switch is ignored. If "=n" is omitted, i.e. +switch "-bpm" is used alone, then the BPM rate is estimated and +displayed, but tempo not adjusted according to the BPM value.
-quick
Use quicker tempo change -algorithm. Gains speed but loses sound quality. Use quicker tempo change algorithm. Gains speed +but loses sound quality.
-naa
Don't use anti-alias -filtering in sample rate transposing. Gains speed but loses sound -quality. Don't use anti-alias filtering in sample rate +transposing. Gains speed but loses sound quality.
-license
Displays the program license -text (LGPL)Displays the program license text (LGPL)

Notes:

    -
  • To use standard input/output pipes for processing, give "stdin" - and "stdout" as input/output filenames correspondingly. The - standard input/output pipes will still carry the audio data in .wav audio - file format.
  • -
  • The numerical switches allow both integer (e.g. "-tempo=123") and decimal (e.g. -"-tempo=123.45") numbers.
  • -
  • The "-naa" and/or "-quick" switches can be -used to reduce CPU usage while compromising some sound quality
  • -
  • The BPM detection algorithm works by detecting -repeating bass or drum patterns at low frequencies of <250Hz. A - lower-than-expected BPM figure may be reported for music with uneven or - complex bass patterns.
  • +
  • To use standard input/output pipes for processing, give "stdin" +and "stdout" as input/output filenames correspondingly. The standard +input/output pipes will still carry the audio data in .wav audio file +format.
  • +
  • The numerical switches allow both integer (e.g. "-tempo=123") +and decimal (e.g. "-tempo=123.45") numbers.
  • +
  • The "-naa" and/or "-quick" switches can be used to reduce CPU +usage while compromising some sound quality
  • +
  • The BPM detection algorithm works by detecting repeating bass or +drum patterns at low frequencies of <250Hz. A lower-than-expected +BPM figure may be reported for music with uneven or complex bass +patterns.

4.2. SoundStretch usage examples

Example 1

-

The following command increases tempo of -the sound file "originalfile.wav" by 12.5% and stores result to file "destinationfile.wav":

+

The following command increases tempo of the sound file +"originalfile.wav" by 12.5% and stores result to file +"destinationfile.wav":

soundstretch originalfile.wav destinationfile.wav -tempo=12.5

Example 2

-

The following command decreases the sound -pitch (key) of the sound file "orig.wav" by two -semitones and stores the result to file "dest.wav":

+

The following command decreases the sound pitch (key) of the sound +file "orig.wav" by two semitones and stores the result to file +"dest.wav":

soundstretch orig.wav dest.wav -pitch=-2

Example 3

-

The following command processes the file "orig.wav" by decreasing the sound tempo by 25.3% and -increasing the sound pitch (key) by 1.5 semitones. Resulting .wav audio data is -directed to standard output pipe:

+

The following command processes the file "orig.wav" by decreasing +the sound tempo by 25.3% and increasing the sound pitch (key) by 1.5 +semitones. Resulting .wav audio data is directed to standard output +pipe:

soundstretch orig.wav stdout -tempo=-25.3 -pitch=1.5

Example 4

-

The following command detects the BPM rate -of the file "orig.wav" and adjusts the tempo to match -100 beats per minute. Result is stored to file "dest.wav":

+

The following command detects the BPM rate of the file "orig.wav" +and adjusts the tempo to match 100 beats per minute. Result is stored +to file "dest.wav":

soundstretch orig.wav dest.wav -bpm=100

Example 5

-

The following command reads .wav sound data from standard input pipe and -estimates the BPM rate:

+

The following command reads .wav sound data from standard input pipe +and estimates the BPM rate:

soundstretch stdin -bpm

5. Change History

5.1. SoundTouch library Change History

- +

1.7.1:

+
    +
  • Added files for Android compilation +
+

1.7.0:

+
    +
  • Sound quality improvements/li> +
  • Improved flush() to adjust output sound stream duration to match better with + ideal duration
  • +
  • Rewrote x86 cpu feature check to resolve compatibility problems
  • +
  • Configure script automatically checks if CPU supports mmx & sse compatibility for GNU platform, and + the script support now "--enable-x86-optimizations" switch to allow disabling x86-specific optimizations.
  • +
  • Revised #define conditions for 32bit/64bit compatibility
  • +
  • gnu autoconf/automake script compatibility fixes
  • +
  • Tuned beat-per-minute detection algorithm
  • +
+

1.6.0:

+
    +
  • Added automatic cutoff threshold adaptation to beat detection +routine to better adapt BPM calculation to different types of music
  • +
  • Retired 3DNow! optimization support as 3DNow! is nowadays +obsoleted and assembler code is nuisance to maintain
  • +
  • Retired "configure" file from source code package due to +autoconf/automake versio conflicts, so that it is from now on to be +generated by invoking "boostrap" script that uses locally available +toolchain version for generating the "configure" file
  • +
  • Resolved namespace/label naming conflicts with other libraries by +replacing global labels such as INTEGER_SAMPLES with more specific +SOUNDTOUCH_INTEGER_SAMPLES etc.
    +
  • +
  • Updated windows build scripts & project files for Visual +Studio 2008 support
  • +
  • Updated SoundTouch.dll API for .NET compatibility
  • +
  • Added API for querying nominal processing input & output +sample batch sizes
  • +

1.5.0:

    -
  • Added normalization to correlation calculation and improvement automatic seek/sequence parameter calculation to improve sound quality
  • - -
  • Bugfixes:  -
      -
    • Fixed negative array indexing in quick seek algorithm
    • -
    • FIR autoalias filter running too far in processing buffer
    • -
    • Check against zero sample count in rate transposing
    • -
    • Fix for x86-64 support: Removed pop/push instructions from the cpu detection algorithm. 
    • -
    • Check against empty buffers in FIFOSampleBuffer
    • -
    • Other minor fixes & code cleanup
    • -
    -
  • - -
  • Fixes in compilation scripts for non-Intel platforms
  • -
  • Added Dynamic-Link-Library (DLL) version of SoundTouch library build, - provided with Delphi/Pascal wrapper for calling the dll routines
  • -
  • Added #define PREVENT_CLICK_AT_RATE_CROSSOVER that prevents a click artifact - when crossing the nominal pitch from either positive to negative side or vice - versa
  • - +
  • Added normalization to correlation calculation and improvement +automatic seek/sequence parameter calculation to improve sound quality
  • +
  • Bugfixes:  +
      +
    • Fixed negative array indexing in quick seek algorithm
    • +
    • FIR autoalias filter running too far in processing buffer
    • +
    • Check against zero sample count in rate transposing
    • +
    • Fix for x86-64 support: Removed pop/push instructions from +the cpu detection algorithm. 
    • +
    • Check against empty buffers in FIFOSampleBuffer
    • +
    • Other minor fixes & code cleanup
    • +
    +
  • +
  • Fixes in compilation scripts for non-Intel platforms
  • +
  • Added Dynamic-Link-Library (DLL) version of SoundTouch library +build, provided with Delphi/Pascal wrapper for calling the dll routines +
  • +
  • Added #define PREVENT_CLICK_AT_RATE_CROSSOVER that prevents a +click artifact when crossing the nominal pitch from either positive to +negative side or vice versa
-

1.4.1:

    -
  • Fixed a buffer overflow bug in BPM detect algorithm routines if processing - more than 2048 samples at one call 
  • - +
  • Fixed a buffer overflow bug in BPM detect algorithm routines if +processing more than 2048 samples at one call 
-

1.4.0:

    -
  • Improved sound quality by automatic calculation of time stretch algorithm - processing parameters according to tempo setting
  • -
  • Moved BPM detection routines from SoundStretch application into SoundTouch - library
  • -
  • Bugfixes: Usage of uninitialied variables, GNU build scripts, compiler errors - due to 'const' keyword mismatch.
  • -
  • Source code cleanup
  • - +
  • Improved sound quality by automatic calculation of time stretch +algorithm processing parameters according to tempo setting
  • +
  • Moved BPM detection routines from SoundStretch application into +SoundTouch library
  • +
  • Bugfixes: Usage of uninitialied variables, GNU build scripts, +compiler errors due to 'const' keyword mismatch.
  • +
  • Source code cleanup
- -

v1.3.1: -

+

1.3.1:

    -
  • Changed static class declaration to GCC 4.x compiler compatible syntax.
  • -
  • Enabled MMX/SSE-optimized routines also for GCC compilers. Earlier -the MMX/SSE-optimized routines were written in compiler-specific inline -assembler, now these routines are migrated to use compiler intrinsic -syntax which allows compiling the same MMX/SSE-optimized source code with -both Visual C++ and GCC compilers.
  • -
  • Set floating point as the default sample format and added switch to -the GNU configure script for selecting the other sample format.
  • - +
  • Changed static class declaration to GCC 4.x compiler compatible +syntax.
  • +
  • Enabled MMX/SSE-optimized routines also for GCC compilers. +Earlier the MMX/SSE-optimized routines were written in +compiler-specific inline assembler, now these routines are migrated to +use compiler intrinsic syntax which allows compiling the same +MMX/SSE-optimized source code with both Visual C++ and GCC compilers.
  • +
  • Set floating point as the default sample format and added switch +to the GNU configure script for selecting the other sample format.
- -

v1.3.0: -

+

1.3.0:

    -
  • Fixed tempo routine output duration inaccuracy due to rounding +
  • Fixed tempo routine output duration inaccuracy due to rounding error
  • -
  • Implemented separate processing routines for integer and +
  • Implemented separate processing routines for integer and floating arithmetic to allow improvements to floating point routines (earlier used algorithms mostly optimized for integer arithmetic also for floating point samples)
  • -
  • Fixed a bug that distorts sound if sample rate changes during the -sound stream
  • -
  • Fixed a memory leak that appeared in MMX/SSE/3DNow! optimized +
  • Fixed a bug that distorts sound if sample rate changes during +the sound stream
  • +
  • Fixed a memory leak that appeared in MMX/SSE/3DNow! optimized routines
  • -
  • Reduced redundant code pieces in MMX/SSE/3DNow! optimized -routines vs. the standard C routines.
  • -
  • MMX routine incompatibility with new gcc compiler versions
  • -
  • Other miscellaneous bug fixes
  • +
  • Reduced redundant code pieces in MMX/SSE/3DNow! optimized +routines vs. the standard C routines.
  • +
  • MMX routine incompatibility with new gcc compiler versions
  • +
  • Other miscellaneous bug fixes
-

v1.2.1:

+

1.2.1:

    -
  • Added automake/autoconf scripts for GNU -platforms (in courtesy of David Durham)
  • -
  • Fixed SCALE overflow bug in rate transposer -routine.
  • -
  • Fixed 64bit address space bugs.
  • -
  • Created a 'soundtouch' namespace for -SAMPLETYPE definitions.
  • +
  • Added automake/autoconf scripts for GNU platforms (in courtesy +of David Durham)
  • +
  • Fixed SCALE overflow bug in rate transposer routine.
  • +
  • Fixed 64bit address space bugs.
  • +
  • Created a 'soundtouch' namespace for SAMPLETYPE definitions.
-

v1.2.0:

+

1.2.0:

    -
  • Added support for 32bit floating point sample -data type with SSE/3DNow! optimizations for Win32 platform (SSE/3DNow! optimizations currently not supported in GCC environment)
  • -
  • Replaced 'make-gcc' script for GNU environment -by master Makefile
  • -
  • Added time-stretch routine configurability to -SoundTouch main class
  • -
  • Bugfixes
  • +
  • Added support for 32bit floating point sample data type with +SSE/3DNow! optimizations for Win32 platform (SSE/3DNow! optimizations +currently not supported in GCC environment)
  • +
  • Replaced 'make-gcc' script for GNU environment by master +Makefile
  • +
  • Added time-stretch routine configurability to SoundTouch main +class
  • +
  • Bugfixes
-

v1.1.1:

+

1.1.1:

    -
  • Moved SoundTouch under lesser GPL license (LGPL). This allows using SoundTouch library in programs that aren't -released under GPL license.
  • -
  • Changed MMX routine organiation so that MMX optimized routines are now implemented in classes that are derived from -the basic classes having the standard non-mmx routines.
  • -
  • MMX routines to support gcc version 3.
  • -
  • Replaced windows makefiles by script using the .dsw files
  • +
  • Moved SoundTouch under lesser GPL license (LGPL). This allows +using SoundTouch library in programs that aren't released under GPL +license.
  • +
  • Changed MMX routine organiation so that MMX optimized routines +are now implemented in classes that are derived from the basic classes +having the standard non-mmx routines.
  • +
  • MMX routines to support gcc version 3.
  • +
  • Replaced windows makefiles by script using the .dsw files
-

v1.01:

+

1.0.1:

    -
  • "mmx_gcc.cpp": Added "using namespace std" and -removed "return 0" from a function with void return value to fix -compiler errors when compiling the library in Solaris environment.
  • -
  • Moved file "FIFOSampleBuffer.h" to "include" -directory to allow accessing the FIFOSampleBuffer class from external -files.
  • +
  • "mmx_gcc.cpp": Added "using namespace std" and removed "return +0" from a function with void return value to fix compiler errors when +compiling the library in Solaris environment.
  • +
  • Moved file "FIFOSampleBuffer.h" to "include" directory to allow +accessing the FIFOSampleBuffer class from external files.
-

v1.0:

+

1.0:

    -
  • Initial release
  • +
  • Initial release

 

-

5.2. SoundStretch application Change -History

- +

5.2. SoundStretch application Change History

+

1.7.0:

+
    +
  • Bugfixes in Wavfile: exception string formatting, avoid getLengthMs() integer + precision overflow, support WAV files using 24/32bit sample format.
  • +
+

1.5.0:

+
    +
  • Added "-speech" switch to activate algorithm parameters more +suitable for speech processing than the default parameters tuned for +music processing.
  • +

1.4.0:

    -
  • Moved BPM detection routines from SoundStretch application into SoundTouch - library
  • -
  • Allow using standard input/output pipes as audio processing input/output - streams
  • - +
  • Moved BPM detection routines from SoundStretch application into +SoundTouch library
  • +
  • Allow using standard input/output pipes as audio processing +input/output streams
- -

v1.3.0:

+

1.3.0:

    -
  • Simplified accessing WAV files with floating -point sample format. -
  • +
  • Simplified accessing WAV files with floating point sample +format.
-

v1.2.1:

+

1.2.1:

    -
  • Fixed 64bit address space bugs.
  • +
  • Fixed 64bit address space bugs.
-

v1.2.0:

+

1.2.0:

    -
  • Added support for 32bit floating point sample -data type
  • -
  • Restructured the BPM routines into separate -library
  • -
  • Fixed big-endian conversion bugs in WAV file -routines (hopefully :)
  • +
  • Added support for 32bit floating point sample data type
  • +
  • Restructured the BPM routines into separate library
  • +
  • Fixed big-endian conversion bugs in WAV file routines (hopefully +:)
-

v1.1.1:

+

1.1.1:

    -
  • Fixed bugs in WAV file reading & added -byte-order conversion for big-endian processors.
  • -
  • Moved SoundStretch source code under 'example' -directory to highlight difference from SoundTouch stuff.
  • -
  • Replaced windows makefiles by script using the .dsw files
  • -
  • Output file name isn't required if output -isn't desired (e.g. if using the switch '-bpm' in plain format only)
  • +
  • Fixed bugs in WAV file reading & added byte-order conversion +for big-endian processors.
  • +
  • Moved SoundStretch source code under 'example' directory to +highlight difference from SoundTouch stuff.
  • +
  • Replaced windows makefiles by script using the .dsw files
  • +
  • Output file name isn't required if output isn't desired (e.g. if +using the switch '-bpm' in plain format only)
-

v1.1:

+

1.1:

    -
  • Fixed "Release" settings in Microsoft Visual -C++ project file (.dsp)
  • -
  • Added beats-per-minute (BPM) detection routine -and command-line switch "-bpm"
  • +
  • Fixed "Release" settings in Microsoft Visual C++ project file +(.dsp)
  • +
  • Added beats-per-minute (BPM) detection routine and command-line +switch "-bpm"
-

v1.01:

+

1.01:

    -
  • Initial release
  • +
  • Initial release

-

6. Acknowledgements

-

Kudos for these people who have contributed to development or submitted -bugfixes since -SoundTouch v1.3.1:

+

6. Acknowledgements

+

Kudos for these people who have contributed to development or +submitted bugfixes since SoundTouch v1.3.1:

    -
  • Arthur A
  • -
  • Richard Ash
  • -
  • Stanislav Brabec
  • -
  • Christian Budde
  • -
  • Brian Cameron
  • -
  • Jason Champion
  • -
  • Patrick Colis
  • -
  • Justin Frankel
  • -
  • Jason Garland
  • -
  • Takashi Iwai
  • -
  • Paulo Pizarro
  • -
  • RJ Ryan
  • -
  • John Sheehy
  • +
  • Arthur A
  • +
  • Richard Ash
  • +
  • Stanislav Brabec
  • +
  • Christian Budde
  • +
  • Jacek Caban
  • +
  • Brian Cameron
  • +
  • Jason Champion
  • +
  • David Clark
  • +
  • Patrick Colis
  • +
  • Miquel Colon
  • +
  • Justin Frankel
  • +
  • Jason Garland
  • +
  • Takashi Iwai
  • +
  • Yuval Naveh
  • +
  • Paulo Pizarro
  • +
  • Blaise Potard
  • +
  • RJ Ryan
  • +
  • Patrick Colis
  • +
  • Miquel Colon
  • +
  • Sandro Cumerlato
  • +
  • Justin Frankel
  • +
  • Jason Garland
  • +
  • Takashi Iwai
  • +
  • Mathias Möhl
  • +
  • Yuval Naveh
  • +
  • Paulo Pizarro
  • +
  • Blaise Potard
  • +
  • RJ Ryan
  • +
  • John Sheehy
  • +
  • Tim Shuttleworth
  • +
  • John Stumpo
  • +
  • Tim Shuttleworth
  • +
  • Katja Vetter
-

Moral greetings to all other contributors and users also!

+

Moral greetings to all other contributors and users also!


-

7. LICENSE

+

7. LICENSE

SoundTouch audio processing library
Copyright (c) Olli Parviainen

-

This library is free software; you can -redistribute it and/or modify it under the terms of the GNU -Lesser General Public License version 2.1 as published by the Free Software -Foundation.

-

This library is distributed in the hope -that it will be useful, but WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A -PARTICULAR PURPOSE. See the GNU Lesser General Public License for -more details.

-

You should have received a copy of the GNU -Lesser General Public License along with this library; if not, -write to the Free Software Foundation, Inc., 59 Temple Place, -Suite 330, Boston, MA 02111-1307 USA

-
- +

This library is free software; you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License version 2.1 +as published by the Free Software Foundation.

+

This library is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser +General Public License for more details.

+

You should have received a copy of the GNU Lesser General Public +License along with this library; if not, write to the Free Software +Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

+
+

+ RREADME.html file updated on 28-Dec-2012

diff --git a/3rdparty/SoundTouch/RateTransposer.cpp b/3rdparty/SoundTouch/RateTransposer.cpp index 7d992f8ce2..19d4bf8ef2 100644 --- a/3rdparty/SoundTouch/RateTransposer.cpp +++ b/3rdparty/SoundTouch/RateTransposer.cpp @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// -/// -/// Sample rate transposer. Changes sample rate by using linear interpolation +/// +/// Sample rate transposer. Changes sample rate by using linear interpolation /// together with anti-alias filtering (first order interpolation with anti- /// alias filtering should be quite adequate for this application) /// @@ -10,10 +10,10 @@ /// //////////////////////////////////////////////////////////////////////////////// // -// Last changed : $Date: 2009-10-31 16:37:24 +0200 (Sat, 31 Oct 2009) $ +// Last changed : $Date: 2011-09-02 15:56:11 -0300 (sex, 02 set 2011) $ // File revision : $Revision: 4 $ // -// $Id: RateTransposer.cpp 74 2009-10-31 14:37:24Z oparviai $ +// $Id: RateTransposer.cpp 131 2011-09-02 18:56:11Z oparviai $ // //////////////////////////////////////////////////////////////////////////////// // @@ -42,11 +42,9 @@ #include #include #include -#include #include "RateTransposer.h" #include "AAFilter.h" -using namespace std; using namespace soundtouch; @@ -61,18 +59,18 @@ protected: virtual void resetRegisters(); - virtual uint transposeStereo(SAMPLETYPE *dest, - const SAMPLETYPE *src, + virtual uint transposeStereo(SAMPLETYPE *dest, + const SAMPLETYPE *src, uint numSamples); - virtual uint transposeMono(SAMPLETYPE *dest, - const SAMPLETYPE *src, + virtual uint transposeMono(SAMPLETYPE *dest, + const SAMPLETYPE *src, uint numSamples); public: RateTransposerInteger(); virtual ~RateTransposerInteger(); - /// Sets new target rate. Normal rate = 1.0, smaller values represent slower + /// Sets new target rate. Normal rate = 1.0, smaller values represent slower /// rate, larger faster rates. virtual void setRate(float newRate); @@ -89,11 +87,11 @@ protected: virtual void resetRegisters(); - virtual uint transposeStereo(SAMPLETYPE *dest, - const SAMPLETYPE *src, + virtual uint transposeStereo(SAMPLETYPE *dest, + const SAMPLETYPE *src, uint numSamples); - virtual uint transposeMono(SAMPLETYPE *dest, - const SAMPLETYPE *src, + virtual uint transposeMono(SAMPLETYPE *dest, + const SAMPLETYPE *src, uint numSamples); public: @@ -104,18 +102,18 @@ public: -// Operator 'new' is overloaded so that it automatically creates a suitable instance +// Operator 'new' is overloaded so that it automatically creates a suitable instance // depending on if we've a MMX/SSE/etc-capable CPU available or not. void * RateTransposer::operator new(size_t s) { - throw runtime_error("Error in RateTransoser::new: don't use \"new TDStretch\" directly, use \"newInstance\" to create a new instance instead!"); - return NULL; + ST_THROW_RT_ERROR("Error in RateTransoser::new: don't use \"new TDStretch\" directly, use \"newInstance\" to create a new instance instead!"); + return newInstance(); } RateTransposer *RateTransposer::newInstance() { -#ifdef INTEGER_SAMPLES +#ifdef SOUNDTOUCH_INTEGER_SAMPLES return ::new RateTransposerInteger; #else return ::new RateTransposerFloat; @@ -165,7 +163,7 @@ AAFilter *RateTransposer::getAAFilter() -// Sets new target iRate. Normal iRate = 1.0, smaller values represent slower +// Sets new target iRate. Normal iRate = 1.0, smaller values represent slower // iRate, larger faster iRates. void RateTransposer::setRate(float newRate) { @@ -174,11 +172,11 @@ void RateTransposer::setRate(float newRate) fRate = newRate; // design a new anti-alias filter - if (newRate > 1.0f) + if (newRate > 1.0f) { fCutoff = 0.5f / newRate; - } - else + } + else { fCutoff = 0.5f * newRate; } @@ -220,7 +218,7 @@ void RateTransposer::upsample(const SAMPLETYPE *src, uint nSamples) // If the parameter 'uRate' value is smaller than 'SCALE', first transpose // the samples and then apply the anti-alias filter to remove aliasing. - // First check that there's enough room in 'storeBuffer' + // First check that there's enough room in 'storeBuffer' // (+16 is to reserve some slack in the destination buffer) sizeTemp = (uint)((float)nSamples / fRate + 16.0f); @@ -231,7 +229,7 @@ void RateTransposer::upsample(const SAMPLETYPE *src, uint nSamples) // Apply the anti-alias filter to samples in "store output", output the // result to "dest" num = storeBuffer.numSamples(); - count = pAAFilter->evaluate(outputBuffer.ptrEnd(num), + count = pAAFilter->evaluate(outputBuffer.ptrEnd(num), storeBuffer.ptrBegin(), num, (uint)numChannels); outputBuffer.putSamples(count); @@ -253,13 +251,13 @@ void RateTransposer::downsample(const SAMPLETYPE *src, uint nSamples) // Add the new samples to the end of the storeBuffer storeBuffer.putSamples(src, nSamples); - // Anti-alias filter the samples to prevent folding and output the filtered + // Anti-alias filter the samples to prevent folding and output the filtered // data to tempBuffer. Note : because of the FIR filter length, the // filtering routine takes in 'filter_length' more samples than it outputs. assert(tempBuffer.isEmpty()); sizeTemp = storeBuffer.numSamples(); - count = pAAFilter->evaluate(tempBuffer.ptrEnd(sizeTemp), + count = pAAFilter->evaluate(tempBuffer.ptrEnd(sizeTemp), storeBuffer.ptrBegin(), sizeTemp, (uint)numChannels); if (count == 0) return; @@ -274,7 +272,7 @@ void RateTransposer::downsample(const SAMPLETYPE *src, uint nSamples) } -// Transposes sample rate by applying anti-alias filter to prevent folding. +// Transposes sample rate by applying anti-alias filter to prevent folding. // Returns amount of samples returned in the "dest" buffer. // The maximum amount of samples that can be returned at a time is set by // the 'set_returnBuffer_size' function. @@ -288,7 +286,7 @@ void RateTransposer::processSamples(const SAMPLETYPE *src, uint nSamples) // If anti-alias filter is turned off, simply transpose without applying // the filter - if (bUseAAFilter == FALSE) + if (bUseAAFilter == FALSE) { sizeReq = (uint)((float)nSamples / fRate + 1.0f); count = transpose(outputBuffer.ptrEnd(sizeReq), src, nSamples); @@ -297,26 +295,26 @@ void RateTransposer::processSamples(const SAMPLETYPE *src, uint nSamples) } // Transpose with anti-alias filter - if (fRate < 1.0f) + if (fRate < 1.0f) { upsample(src, nSamples); - } - else + } + else { downsample(src, nSamples); } } -// Transposes the sample rate of the given samples using linear interpolation. +// Transposes the sample rate of the given samples using linear interpolation. // Returns the number of samples returned in the "dest" buffer inline uint RateTransposer::transpose(SAMPLETYPE *dest, const SAMPLETYPE *src, uint nSamples) { - if (numChannels == 2) + if (numChannels == 2) { return transposeStereo(dest, src, nSamples); - } - else + } + else { return transposeMono(dest, src, nSamples); } @@ -363,7 +361,7 @@ int RateTransposer::isEmpty() const ////////////////////////////////////////////////////////////////////////////// // // RateTransposerInteger - integer arithmetic implementation -// +// /// fixed-point interpolation routine precision #define SCALE 65536 @@ -371,7 +369,7 @@ int RateTransposer::isEmpty() const // Constructor RateTransposerInteger::RateTransposerInteger() : RateTransposer() { - // Notice: use local function calling syntax for sake of clarity, + // Notice: use local function calling syntax for sake of clarity, // to indicate the fact that C++ constructor can't call virtual functions. RateTransposerInteger::resetRegisters(); RateTransposerInteger::setRate(1.0f); @@ -386,14 +384,14 @@ RateTransposerInteger::~RateTransposerInteger() void RateTransposerInteger::resetRegisters() { iSlopeCount = 0; - sPrevSampleL = + sPrevSampleL = sPrevSampleR = 0; } -// Transposes the sample rate of the given samples using linear interpolation. -// 'Mono' version of the routine. Returns the number of samples returned in +// Transposes the sample rate of the given samples using linear interpolation. +// 'Mono' version of the routine. Returns the number of samples returned in // the "dest" buffer uint RateTransposerInteger::transposeMono(SAMPLETYPE *dest, const SAMPLETYPE *src, uint nSamples) { @@ -402,11 +400,11 @@ uint RateTransposerInteger::transposeMono(SAMPLETYPE *dest, const SAMPLETYPE *sr if (nSamples == 0) return 0; // no samples, no work - used = 0; + used = 0; i = 0; // Process the last sample saved from the previous call first... - while (iSlopeCount <= SCALE) + while (iSlopeCount <= SCALE) { vol1 = (LONG_SAMPLETYPE)(SCALE - iSlopeCount); temp = vol1 * sPrevSampleL + iSlopeCount * src[0]; @@ -419,7 +417,7 @@ uint RateTransposerInteger::transposeMono(SAMPLETYPE *dest, const SAMPLETYPE *sr while (1) { - while (iSlopeCount > SCALE) + while (iSlopeCount > SCALE) { iSlopeCount -= SCALE; used ++; @@ -440,8 +438,8 @@ end: } -// Transposes the sample rate of the given samples using linear interpolation. -// 'Stereo' version of the routine. Returns the number of samples returned in +// Transposes the sample rate of the given samples using linear interpolation. +// 'Stereo' version of the routine. Returns the number of samples returned in // the "dest" buffer uint RateTransposerInteger::transposeStereo(SAMPLETYPE *dest, const SAMPLETYPE *src, uint nSamples) { @@ -450,11 +448,11 @@ uint RateTransposerInteger::transposeStereo(SAMPLETYPE *dest, const SAMPLETYPE * if (nSamples == 0) return 0; // no samples, no work - used = 0; + used = 0; i = 0; // Process the last sample saved from the sPrevSampleLious call first... - while (iSlopeCount <= SCALE) + while (iSlopeCount <= SCALE) { vol1 = (LONG_SAMPLETYPE)(SCALE - iSlopeCount); temp = vol1 * sPrevSampleL + iSlopeCount * src[0]; @@ -469,7 +467,7 @@ uint RateTransposerInteger::transposeStereo(SAMPLETYPE *dest, const SAMPLETYPE * while (1) { - while (iSlopeCount > SCALE) + while (iSlopeCount > SCALE) { iSlopeCount -= SCALE; used ++; @@ -494,7 +492,7 @@ end: } -// Sets new target iRate. Normal iRate = 1.0, smaller values represent slower +// Sets new target iRate. Normal iRate = 1.0, smaller values represent slower // iRate, larger faster iRates. void RateTransposerInteger::setRate(float newRate) { @@ -506,13 +504,13 @@ void RateTransposerInteger::setRate(float newRate) ////////////////////////////////////////////////////////////////////////////// // // RateTransposerFloat - floating point arithmetic implementation -// +// ////////////////////////////////////////////////////////////////////////////// // Constructor RateTransposerFloat::RateTransposerFloat() : RateTransposer() { - // Notice: use local function calling syntax for sake of clarity, + // Notice: use local function calling syntax for sake of clarity, // to indicate the fact that C++ constructor can't call virtual functions. RateTransposerFloat::resetRegisters(); RateTransposerFloat::setRate(1.0f); @@ -527,24 +525,24 @@ RateTransposerFloat::~RateTransposerFloat() void RateTransposerFloat::resetRegisters() { fSlopeCount = 0; - sPrevSampleL = + sPrevSampleL = sPrevSampleR = 0; } -// Transposes the sample rate of the given samples using linear interpolation. -// 'Mono' version of the routine. Returns the number of samples returned in +// Transposes the sample rate of the given samples using linear interpolation. +// 'Mono' version of the routine. Returns the number of samples returned in // the "dest" buffer uint RateTransposerFloat::transposeMono(SAMPLETYPE *dest, const SAMPLETYPE *src, uint nSamples) { unsigned int i, used; - used = 0; + used = 0; i = 0; // Process the last sample saved from the previous call first... - while (fSlopeCount <= 1.0f) + while (fSlopeCount <= 1.0f) { dest[i] = (SAMPLETYPE)((1.0f - fSlopeCount) * sPrevSampleL + fSlopeCount * src[0]); i++; @@ -556,7 +554,7 @@ uint RateTransposerFloat::transposeMono(SAMPLETYPE *dest, const SAMPLETYPE *src, { while (1) { - while (fSlopeCount > 1.0f) + while (fSlopeCount > 1.0f) { fSlopeCount -= 1.0f; used ++; @@ -575,8 +573,8 @@ end: } -// Transposes the sample rate of the given samples using linear interpolation. -// 'Mono' version of the routine. Returns the number of samples returned in +// Transposes the sample rate of the given samples using linear interpolation. +// 'Mono' version of the routine. Returns the number of samples returned in // the "dest" buffer uint RateTransposerFloat::transposeStereo(SAMPLETYPE *dest, const SAMPLETYPE *src, uint nSamples) { @@ -584,11 +582,11 @@ uint RateTransposerFloat::transposeStereo(SAMPLETYPE *dest, const SAMPLETYPE *sr if (nSamples == 0) return 0; // no samples, no work - used = 0; + used = 0; i = 0; // Process the last sample saved from the sPrevSampleLious call first... - while (fSlopeCount <= 1.0f) + while (fSlopeCount <= 1.0f) { dest[2 * i] = (SAMPLETYPE)((1.0f - fSlopeCount) * sPrevSampleL + fSlopeCount * src[0]); dest[2 * i + 1] = (SAMPLETYPE)((1.0f - fSlopeCount) * sPrevSampleR + fSlopeCount * src[1]); @@ -602,7 +600,7 @@ uint RateTransposerFloat::transposeStereo(SAMPLETYPE *dest, const SAMPLETYPE *sr { while (1) { - while (fSlopeCount > 1.0f) + while (fSlopeCount > 1.0f) { fSlopeCount -= 1.0f; used ++; @@ -610,9 +608,9 @@ uint RateTransposerFloat::transposeStereo(SAMPLETYPE *dest, const SAMPLETYPE *sr } srcPos = 2 * used; - dest[2 * i] = (SAMPLETYPE)((1.0f - fSlopeCount) * src[srcPos] + dest[2 * i] = (SAMPLETYPE)((1.0f - fSlopeCount) * src[srcPos] + fSlopeCount * src[srcPos + 2]); - dest[2 * i + 1] = (SAMPLETYPE)((1.0f - fSlopeCount) * src[srcPos + 1] + dest[2 * i + 1] = (SAMPLETYPE)((1.0f - fSlopeCount) * src[srcPos + 1] + fSlopeCount * src[srcPos + 3]); i++; diff --git a/3rdparty/SoundTouch/RateTransposer.h b/3rdparty/SoundTouch/RateTransposer.h index 6ab0586484..8374a0f834 100644 --- a/3rdparty/SoundTouch/RateTransposer.h +++ b/3rdparty/SoundTouch/RateTransposer.h @@ -1,10 +1,10 @@ //////////////////////////////////////////////////////////////////////////////// -/// -/// Sample rate transposer. Changes sample rate by using linear interpolation +/// +/// Sample rate transposer. Changes sample rate by using linear interpolation /// together with anti-alias filtering (first order interpolation with anti- /// alias filtering should be quite adequate for this application). /// -/// Use either of the derived classes of 'RateTransposerInteger' or +/// Use either of the derived classes of 'RateTransposerInteger' or /// 'RateTransposerFloat' for corresponding integer/floating point tranposing /// algorithm implementation. /// @@ -14,7 +14,7 @@ /// //////////////////////////////////////////////////////////////////////////////// // -// Last changed : $Date: 2009-02-21 18:00:14 +0200 (Sat, 21 Feb 2009) $ +// Last changed : $Date: 2009-02-21 13:00:14 -0300 (sáb, 21 fev 2009) $ // File revision : $Revision: 4 $ // // $Id: RateTransposer.h 63 2009-02-21 16:00:14Z oparviai $ @@ -57,9 +57,9 @@ namespace soundtouch /// A common linear samplerate transposer class. /// -/// Note: Use function "RateTransposer::newInstance()" to create a new class -/// instance instead of the "new" operator; that function automatically -/// chooses a correct implementation depending on if integer or floating +/// Note: Use function "RateTransposer::newInstance()" to create a new class +/// instance instead of the "new" operator; that function automatically +/// chooses a correct implementation depending on if integer or floating /// arithmetics are to be used. class RateTransposer : public FIFOProcessor { @@ -85,26 +85,26 @@ protected: virtual void resetRegisters() = 0; - virtual uint transposeStereo(SAMPLETYPE *dest, - const SAMPLETYPE *src, + virtual uint transposeStereo(SAMPLETYPE *dest, + const SAMPLETYPE *src, uint numSamples) = 0; - virtual uint transposeMono(SAMPLETYPE *dest, - const SAMPLETYPE *src, + virtual uint transposeMono(SAMPLETYPE *dest, + const SAMPLETYPE *src, uint numSamples) = 0; - inline uint transpose(SAMPLETYPE *dest, - const SAMPLETYPE *src, + inline uint transpose(SAMPLETYPE *dest, + const SAMPLETYPE *src, uint numSamples); - void downsample(const SAMPLETYPE *src, + void downsample(const SAMPLETYPE *src, uint numSamples); - void upsample(const SAMPLETYPE *src, + void upsample(const SAMPLETYPE *src, uint numSamples); - /// Transposes sample rate by applying anti-alias filter to prevent folding. + /// Transposes sample rate by applying anti-alias filter to prevent folding. /// Returns amount of samples returned in the "dest" buffer. /// The maximum amount of samples that can be returned at a time is set by /// the 'set_returnBuffer_size' function. - void processSamples(const SAMPLETYPE *src, + void processSamples(const SAMPLETYPE *src, uint numSamples); @@ -112,12 +112,12 @@ public: RateTransposer(); virtual ~RateTransposer(); - /// Operator 'new' is overloaded so that it automatically creates a suitable instance + /// Operator 'new' is overloaded so that it automatically creates a suitable instance /// depending on if we're to use integer or floating point arithmetics. static void *operator new(size_t s); - /// Use this function instead of "new" operator to create a new instance of this class. - /// This function automatically chooses a correct implementation, depending on if + /// Use this function instead of "new" operator to create a new instance of this class. + /// This function automatically chooses a correct implementation, depending on if /// integer ot floating point arithmetics are to be used. static RateTransposer *newInstance(); @@ -136,7 +136,7 @@ public: /// Returns nonzero if anti-alias filter is enabled. BOOL isAAFilterEnabled() const; - /// Sets new target rate. Normal rate = 1.0, smaller values represent slower + /// Sets new target rate. Normal rate = 1.0, smaller values represent slower /// rate, larger faster rates. virtual void setRate(float newRate); diff --git a/3rdparty/SoundTouch/STTypes.h b/3rdparty/SoundTouch/STTypes.h index 1fcd9e2da9..2c4584a142 100644 --- a/3rdparty/SoundTouch/STTypes.h +++ b/3rdparty/SoundTouch/STTypes.h @@ -8,10 +8,10 @@ /// //////////////////////////////////////////////////////////////////////////////// // -// Last changed : $Date: 2009-05-17 14:30:57 +0300 (Sun, 17 May 2009) $ +// Last changed : $Date: 2012-12-28 12:53:56 -0200 (sex, 28 dez 2012) $ // File revision : $Revision: 3 $ // -// $Id: STTypes.h 70 2009-05-17 11:30:57Z oparviai $ +// $Id: STTypes.h 162 2012-12-28 14:53:56Z oparviai $ // //////////////////////////////////////////////////////////////////////////////// // @@ -42,8 +42,21 @@ typedef unsigned int uint; typedef unsigned long ulong; -#ifdef __GNUC__ - // In GCC, include soundtouch_config.h made by config scritps +// Patch for MinGW: on Win64 long is 32-bit +#ifdef _WIN64 + typedef unsigned long long ulongptr; +#else + typedef ulong ulongptr; +#endif + + +// Helper macro for aligning pointer up to next 16-byte boundary +#define SOUNDTOUCH_ALIGN_POINTER_16(x) ( ( (ulongptr)(x) + 15 ) & ~(ulongptr)15 ) + + +#if (defined(__GNUC__) && !defined(ANDROID)) + // In GCC, include soundtouch_config.h made by config scritps. + // Skip this in Android compilation that uses GCC but without configure scripts. #include "soundtouch_config.h" #endif @@ -60,64 +73,81 @@ typedef unsigned long ulong; namespace soundtouch { + /// Activate these undef's to overrule the possible sampletype + /// setting inherited from some other header file: + //#undef SOUNDTOUCH_INTEGER_SAMPLES + //#undef SOUNDTOUCH_FLOAT_SAMPLES -/// Activate these undef's to overrule the possible sampletype -/// setting inherited from some other header file: -//#undef INTEGER_SAMPLES -//#undef FLOAT_SAMPLES + #if (defined(__SOFTFP__)) + // For Android compilation: Force use of Integer samples in case that + // compilation uses soft-floating point emulation - soft-fp is way too slow + #undef SOUNDTOUCH_FLOAT_SAMPLES + #define SOUNDTOUCH_INTEGER_SAMPLES 1 + #endif -#if !(INTEGER_SAMPLES || FLOAT_SAMPLES) + #if !(SOUNDTOUCH_INTEGER_SAMPLES || SOUNDTOUCH_FLOAT_SAMPLES) + + /// Choose either 32bit floating point or 16bit integer sampletype + /// by choosing one of the following defines, unless this selection + /// has already been done in some other file. + //// + /// Notes: + /// - In Windows environment, choose the sample format with the + /// following defines. + /// - In GNU environment, the floating point samples are used by + /// default, but integer samples can be chosen by giving the + /// following switch to the configure script: + /// ./configure --enable-integer-samples + /// However, if you still prefer to select the sample format here + /// also in GNU environment, then please #undef the INTEGER_SAMPLE + /// and FLOAT_SAMPLE defines first as in comments above. + //#define SOUNDTOUCH_INTEGER_SAMPLES 1 //< 16bit integer samples + #define SOUNDTOUCH_FLOAT_SAMPLES 1 //< 32bit float samples + + #endif - /// Choose either 32bit floating point or 16bit integer sampletype - /// by choosing one of the following defines, unless this selection - /// has already been done in some other file. - //// - /// Notes: - /// - In Windows environment, choose the sample format with the - /// following defines. - /// - In GNU environment, the floating point samples are used by - /// default, but integer samples can be chosen by giving the - /// following switch to the configure script: - /// ./configure --enable-integer-samples - /// However, if you still prefer to select the sample format here - /// also in GNU environment, then please #undef the INTEGER_SAMPLE - /// and FLOAT_SAMPLE defines first as in comments above. - //#define INTEGER_SAMPLES 1 //< 16bit integer samples - #define FLOAT_SAMPLES 1 //< 32bit float samples - - #endif - - #if (WIN32 || __i386__ || __x86_64__) - /// Define this to allow X86-specific assembler/intrinsic optimizations. + #if (_M_IX86 || __i386__ || __x86_64__ || _M_X64) + /// Define this to allow X86-specific assembler/intrinsic optimizations. /// Notice that library contains also usual C++ versions of each of these - /// these routines, so if you're having difficulties getting the optimized - /// routines compiled for whatever reason, you may disable these optimizations + /// these routines, so if you're having difficulties getting the optimized + /// routines compiled for whatever reason, you may disable these optimizations /// to make the library compile. - #define ALLOW_X86_OPTIMIZATIONS 1 + #define SOUNDTOUCH_ALLOW_X86_OPTIMIZATIONS 1 + + /// In GNU environment, allow the user to override this setting by + /// giving the following switch to the configure script: + /// ./configure --disable-x86-optimizations + /// ./configure --enable-x86-optimizations=no + #ifdef SOUNDTOUCH_DISABLE_X86_OPTIMIZATIONS + #undef SOUNDTOUCH_ALLOW_X86_OPTIMIZATIONS + #endif + #else + /// Always disable optimizations when not using a x86 systems. + #undef SOUNDTOUCH_ALLOW_X86_OPTIMIZATIONS #endif - // If defined, allows the SIMD-optimized routines to take minor shortcuts - // for improved performance. Undefine to require faithfully similar SIMD + // If defined, allows the SIMD-optimized routines to take minor shortcuts + // for improved performance. Undefine to require faithfully similar SIMD // calculations as in normal C implementation. - #define ALLOW_NONEXACT_SIMD_OPTIMIZATION 1 + #define SOUNDTOUCH_ALLOW_NONEXACT_SIMD_OPTIMIZATION 1 - #ifdef INTEGER_SAMPLES + #ifdef SOUNDTOUCH_INTEGER_SAMPLES // 16bit integer sample type typedef short SAMPLETYPE; // data type for sample accumulation: Use 32bit integer to prevent overflows typedef long LONG_SAMPLETYPE; - #ifdef FLOAT_SAMPLES + #ifdef SOUNDTOUCH_FLOAT_SAMPLES // check that only one sample type is defined #error "conflicting sample types defined" - #endif // FLOAT_SAMPLES + #endif // SOUNDTOUCH_FLOAT_SAMPLES - #ifdef ALLOW_X86_OPTIMIZATIONS + #ifdef SOUNDTOUCH_ALLOW_X86_OPTIMIZATIONS // Allow MMX optimizations - #define ALLOW_MMX 1 + #define SOUNDTOUCH_ALLOW_MMX 1 #endif #else @@ -127,23 +157,31 @@ namespace soundtouch // data type for sample accumulation: Use double to utilize full precision. typedef double LONG_SAMPLETYPE; - #ifdef ALLOW_X86_OPTIMIZATIONS - // Allow 3DNow! and SSE optimizations - #if WIN32 - #define ALLOW_3DNOW 1 - #endif - - #define ALLOW_SSE 1 + #ifdef SOUNDTOUCH_ALLOW_X86_OPTIMIZATIONS + // Allow SSE optimizations + #define SOUNDTOUCH_ALLOW_SSE 1 #endif - #endif // INTEGER_SAMPLES + #endif // SOUNDTOUCH_INTEGER_SAMPLES + }; +// define ST_NO_EXCEPTION_HANDLING switch to disable throwing std exceptions: +// #define ST_NO_EXCEPTION_HANDLING 1 +#ifdef ST_NO_EXCEPTION_HANDLING + // Exceptions disabled. Throw asserts instead if enabled. + #include + #define ST_THROW_RT_ERROR(x) {assert((const char *)x);} +#else + // use c++ standard exceptions + #include + #define ST_THROW_RT_ERROR(x) {throw std::runtime_error(x);} +#endif -// When this #define is active, eliminates a clicking sound when the "rate" or "pitch" -// parameter setting crosses from value <1 to >=1 or vice versa during processing. -// Default is off as such crossover is untypical case and involves a slight sound +// When this #define is active, eliminates a clicking sound when the "rate" or "pitch" +// parameter setting crosses from value <1 to >=1 or vice versa during processing. +// Default is off as such crossover is untypical case and involves a slight sound // quality compromise. -//#define PREVENT_CLICK_AT_RATE_CROSSOVER 1 +//#define SOUNDTOUCH_PREVENT_CLICK_AT_RATE_CROSSOVER 1 #endif diff --git a/3rdparty/SoundTouch/SoundTouch.cpp b/3rdparty/SoundTouch/SoundTouch.cpp index 8abfc23b27..c66c16c54a 100644 --- a/3rdparty/SoundTouch/SoundTouch.cpp +++ b/3rdparty/SoundTouch/SoundTouch.cpp @@ -1,27 +1,27 @@ ////////////////////////////////////////////////////////////////////////////// /// -/// SoundTouch - main class for tempo/pitch/rate adjusting routines. +/// SoundTouch - main class for tempo/pitch/rate adjusting routines. /// /// Notes: -/// - Initialize the SoundTouch object instance by setting up the sound stream -/// parameters with functions 'setSampleRate' and 'setChannels', then set +/// - Initialize the SoundTouch object instance by setting up the sound stream +/// parameters with functions 'setSampleRate' and 'setChannels', then set /// desired tempo/pitch/rate settings with the corresponding functions. /// -/// - The SoundTouch class behaves like a first-in-first-out pipeline: The +/// - The SoundTouch class behaves like a first-in-first-out pipeline: The /// samples that are to be processed are fed into one of the pipe by calling -/// function 'putSamples', while the ready processed samples can be read +/// function 'putSamples', while the ready processed samples can be read /// from the other end of the pipeline with function 'receiveSamples'. -/// -/// - The SoundTouch processing classes require certain sized 'batches' of -/// samples in order to process the sound. For this reason the classes buffer -/// incoming samples until there are enough of samples available for +/// +/// - The SoundTouch processing classes require certain sized 'batches' of +/// samples in order to process the sound. For this reason the classes buffer +/// incoming samples until there are enough of samples available for /// processing, then they carry out the processing step and consequently /// make the processed samples available for outputting. -/// -/// - For the above reason, the processing routines introduce a certain +/// +/// - For the above reason, the processing routines introduce a certain /// 'latency' between the input and output, so that the samples input to -/// SoundTouch may not be immediately available in the output, and neither -/// the amount of outputtable samples may not immediately be in direct +/// SoundTouch may not be immediately available in the output, and neither +/// the amount of outputtable samples may not immediately be in direct /// relationship with the amount of previously input samples. /// /// - The tempo/pitch/rate control parameters can be altered during processing. @@ -30,8 +30,8 @@ /// required. /// /// - This class utilizes classes 'TDStretch' for tempo change (without modifying -/// pitch) and 'RateTransposer' for changing the playback rate (that is, both -/// tempo and pitch in the same ratio) of the sound. The third available control +/// pitch) and 'RateTransposer' for changing the playback rate (that is, both +/// tempo and pitch in the same ratio) of the sound. The third available control /// 'pitch' (change pitch but maintain tempo) is produced by a combination of /// combining the two other controls. /// @@ -41,10 +41,10 @@ /// //////////////////////////////////////////////////////////////////////////////// // -// Last changed : $Date: 2009-05-19 07:57:30 +0300 (Tue, 19 May 2009) $ +// Last changed : $Date: 2012-06-13 16:29:53 -0300 (qua, 13 jun 2012) $ // File revision : $Revision: 4 $ // -// $Id: SoundTouch.cpp 73 2009-05-19 04:57:30Z oparviai $ +// $Id: SoundTouch.cpp 143 2012-06-13 19:29:53Z oparviai $ // //////////////////////////////////////////////////////////////////////////////// // @@ -73,7 +73,6 @@ #include #include #include -#include #include #include "SoundTouch.h" @@ -82,7 +81,7 @@ #include "cpu_detect.h" using namespace soundtouch; - + /// test if two floating point numbers are equal #define TEST_FLOAT_EQUAL(a, b) (fabs(a - b) < 1e-10) @@ -91,7 +90,7 @@ using namespace soundtouch; extern "C" void soundtouch_ac_test() { printf("SoundTouch Version: %s\n",SOUNDTOUCH_VERSION); -} +} SoundTouch::SoundTouch() @@ -105,8 +104,8 @@ SoundTouch::SoundTouch() rate = tempo = 0; - virtualPitch = - virtualRate = + virtualPitch = + virtualRate = virtualTempo = 1.0; calcEffectiveRateAndTempo(); @@ -144,9 +143,9 @@ uint SoundTouch::getVersionId() // Sets the number of channels, 1 = mono, 2 = stereo void SoundTouch::setChannels(uint numChannels) { - if (numChannels != 1 && numChannels != 2) + if (numChannels != 1 && numChannels != 2) { - throw std::runtime_error("Illegal number of channels"); + ST_THROW_RT_ERROR("Illegal number of channels"); } channels = numChannels; pRateTransposer->setChannels((int)numChannels); @@ -243,10 +242,10 @@ void SoundTouch::calcEffectiveRateAndTempo() if (!TEST_FLOAT_EQUAL(rate,oldRate)) pRateTransposer->setRate(rate); if (!TEST_FLOAT_EQUAL(tempo, oldTempo)) pTDStretch->setTempo(tempo); -#ifndef PREVENT_CLICK_AT_RATE_CROSSOVER - if (rate <= 1.0f) +#ifndef SOUNDTOUCH_PREVENT_CLICK_AT_RATE_CROSSOVER + if (rate <= 1.0f) { - if (output != pTDStretch) + if (output != pTDStretch) { FIFOSamplePipe *tempoOut; @@ -263,7 +262,7 @@ void SoundTouch::calcEffectiveRateAndTempo() else #endif { - if (output != pRateTransposer) + if (output != pRateTransposer) { FIFOSamplePipe *transOut; @@ -276,7 +275,7 @@ void SoundTouch::calcEffectiveRateAndTempo() output = pRateTransposer; } - } + } } @@ -293,42 +292,42 @@ void SoundTouch::setSampleRate(uint srate) // the input of the object. void SoundTouch::putSamples(const SAMPLETYPE *samples, uint nSamples) { - if (bSrateSet == FALSE) + if (bSrateSet == FALSE) { - throw std::runtime_error("SoundTouch : Sample rate not defined"); - } - else if (channels == 0) + ST_THROW_RT_ERROR("SoundTouch : Sample rate not defined"); + } + else if (channels == 0) { - throw std::runtime_error("SoundTouch : Number of channels not defined"); + ST_THROW_RT_ERROR("SoundTouch : Number of channels not defined"); } // Transpose the rate of the new samples if necessary /* Bypass the nominal setting - can introduce a click in sound when tempo/pitch control crosses the nominal value... - if (rate == 1.0f) + if (rate == 1.0f) { - // The rate value is same as the original, simply evaluate the tempo changer. + // The rate value is same as the original, simply evaluate the tempo changer. assert(output == pTDStretch); - if (pRateTransposer->isEmpty() == 0) + if (pRateTransposer->isEmpty() == 0) { // yet flush the last samples in the pitch transposer buffer // (may happen if 'rate' changes from a non-zero value to zero) pTDStretch->moveSamples(*pRateTransposer); } pTDStretch->putSamples(samples, nSamples); - } + } */ -#ifndef PREVENT_CLICK_AT_RATE_CROSSOVER - else if (rate <= 1.0f) +#ifndef SOUNDTOUCH_PREVENT_CLICK_AT_RATE_CROSSOVER + else if (rate <= 1.0f) { // transpose the rate down, output the transposed sound to tempo changer buffer assert(output == pTDStretch); pRateTransposer->putSamples(samples, nSamples); pTDStretch->moveSamples(*pRateTransposer); - } - else + } + else #endif { - // evaluate the tempo changer, then transpose the rate up, + // evaluate the tempo changer, then transpose the rate up, assert(output == pRateTransposer); pTDStretch->putSamples(samples, nSamples); pRateTransposer->moveSamples(*pTDStretch); @@ -346,20 +345,36 @@ void SoundTouch::putSamples(const SAMPLETYPE *samples, uint nSamples) void SoundTouch::flush() { int i; - uint nOut; - SAMPLETYPE buff[128]; + int nUnprocessed; + int nOut; + SAMPLETYPE buff[64*2]; // note: allocate 2*64 to cater 64 sample frames of stereo sound - nOut = numSamples(); + // check how many samples still await processing, and scale + // that by tempo & rate to get expected output sample count + nUnprocessed = numUnprocessedSamples(); + nUnprocessed = (int)((double)nUnprocessed / (tempo * rate) + 0.5); - memset(buff, 0, 128 * sizeof(SAMPLETYPE)); + nOut = numSamples(); // ready samples currently in buffer ... + nOut += nUnprocessed; // ... and how many we expect there to be in the end + + memset(buff, 0, 64 * channels * sizeof(SAMPLETYPE)); // "Push" the last active samples out from the processing pipeline by - // feeding blank samples into the processing pipeline until new, - // processed samples appear in the output (not however, more than + // feeding blank samples into the processing pipeline until new, + // processed samples appear in the output (not however, more than // 8ksamples in any case) - for (i = 0; i < 128; i ++) + for (i = 0; i < 128; i ++) { putSamples(buff, 64); - if (numSamples() != nOut) break; // new samples have appeared in the output! + if ((int)numSamples() >= nOut) + { + // Enough new samples have appeared into the output! + // As samples come from processing with bigger chunks, now truncate it + // back to maximum "nOut" samples to improve duration accuracy + adjustAmountOfSamples(nOut); + + // finish + break; + } } // Clear working buffers @@ -379,7 +394,7 @@ BOOL SoundTouch::setSetting(int settingId, int value) // read current tdstretch routine parameters pTDStretch->getParameters(&sampleRate, &sequenceMs, &seekWindowMs, &overlapMs); - switch (settingId) + switch (settingId) { case SETTING_USE_AA_FILTER : // enables / disabless anti-alias filter @@ -425,7 +440,7 @@ int SoundTouch::getSetting(int settingId) const { int temp; - switch (settingId) + switch (settingId) { case SETTING_USE_AA_FILTER : return (uint)pRateTransposer->isAAFilterEnabled(); @@ -448,7 +463,13 @@ int SoundTouch::getSetting(int settingId) const pTDStretch->getParameters(NULL, NULL, NULL, &temp); return temp; - default : + case SETTING_NOMINAL_INPUT_SEQUENCE : + return pTDStretch->getInputSampleReq(); + + case SETTING_NOMINAL_OUTPUT_SEQUENCE : + return pTDStretch->getOutputBatchSize(); + + default : return 0; } } diff --git a/3rdparty/SoundTouch/SoundTouch.h b/3rdparty/SoundTouch/SoundTouch.h index 9d82886aa9..6ae0e4a829 100644 --- a/3rdparty/SoundTouch/SoundTouch.h +++ b/3rdparty/SoundTouch/SoundTouch.h @@ -1,27 +1,27 @@ ////////////////////////////////////////////////////////////////////////////// /// -/// SoundTouch - main class for tempo/pitch/rate adjusting routines. +/// SoundTouch - main class for tempo/pitch/rate adjusting routines. /// /// Notes: -/// - Initialize the SoundTouch object instance by setting up the sound stream -/// parameters with functions 'setSampleRate' and 'setChannels', then set +/// - Initialize the SoundTouch object instance by setting up the sound stream +/// parameters with functions 'setSampleRate' and 'setChannels', then set /// desired tempo/pitch/rate settings with the corresponding functions. /// -/// - The SoundTouch class behaves like a first-in-first-out pipeline: The +/// - The SoundTouch class behaves like a first-in-first-out pipeline: The /// samples that are to be processed are fed into one of the pipe by calling -/// function 'putSamples', while the ready processed samples can be read +/// function 'putSamples', while the ready processed samples can be read /// from the other end of the pipeline with function 'receiveSamples'. -/// -/// - The SoundTouch processing classes require certain sized 'batches' of -/// samples in order to process the sound. For this reason the classes buffer -/// incoming samples until there are enough of samples available for +/// +/// - The SoundTouch processing classes require certain sized 'batches' of +/// samples in order to process the sound. For this reason the classes buffer +/// incoming samples until there are enough of samples available for /// processing, then they carry out the processing step and consequently /// make the processed samples available for outputting. -/// -/// - For the above reason, the processing routines introduce a certain +/// +/// - For the above reason, the processing routines introduce a certain /// 'latency' between the input and output, so that the samples input to -/// SoundTouch may not be immediately available in the output, and neither -/// the amount of outputtable samples may not immediately be in direct +/// SoundTouch may not be immediately available in the output, and neither +/// the amount of outputtable samples may not immediately be in direct /// relationship with the amount of previously input samples. /// /// - The tempo/pitch/rate control parameters can be altered during processing. @@ -30,8 +30,8 @@ /// required. /// /// - This class utilizes classes 'TDStretch' for tempo change (without modifying -/// pitch) and 'RateTransposer' for changing the playback rate (that is, both -/// tempo and pitch in the same ratio) of the sound. The third available control +/// pitch) and 'RateTransposer' for changing the playback rate (that is, both +/// tempo and pitch in the same ratio) of the sound. The third available control /// 'pitch' (change pitch but maintain tempo) is produced by a combination of /// combining the two other controls. /// @@ -41,10 +41,10 @@ /// //////////////////////////////////////////////////////////////////////////////// // -// Last changed : $Date: 2009-12-28 22:10:14 +0200 (Mon, 28 Dec 2009) $ +// Last changed : $Date: 2012-12-28 17:32:59 -0200 (sex, 28 dez 2012) $ // File revision : $Revision: 4 $ // -// $Id: SoundTouch.h 78 2009-12-28 20:10:14Z oparviai $ +// $Id: SoundTouch.h 163 2012-12-28 19:32:59Z oparviai $ // //////////////////////////////////////////////////////////////////////////////// // @@ -79,10 +79,10 @@ namespace soundtouch { /// Soundtouch library version string -#define SOUNDTOUCH_VERSION "1.5.0" +#define SOUNDTOUCH_VERSION "1.7.1" /// SoundTouch library version id -#define SOUNDTOUCH_VERSION_ID (10500) +#define SOUNDTOUCH_VERSION_ID (10701) // // Available setting IDs for the 'setSetting' & 'get_setting' functions: @@ -98,24 +98,49 @@ namespace soundtouch /// quality compromising) #define SETTING_USE_QUICKSEEK 2 -/// Time-stretch algorithm single processing sequence length in milliseconds. This determines -/// to how long sequences the original sound is chopped in the time-stretch algorithm. +/// Time-stretch algorithm single processing sequence length in milliseconds. This determines +/// to how long sequences the original sound is chopped in the time-stretch algorithm. /// See "STTypes.h" or README for more information. #define SETTING_SEQUENCE_MS 3 -/// Time-stretch algorithm seeking window length in milliseconds for algorithm that finds the -/// best possible overlapping location. This determines from how wide window the algorithm -/// may look for an optimal joining location when mixing the sound sequences back together. +/// Time-stretch algorithm seeking window length in milliseconds for algorithm that finds the +/// best possible overlapping location. This determines from how wide window the algorithm +/// may look for an optimal joining location when mixing the sound sequences back together. /// See "STTypes.h" or README for more information. #define SETTING_SEEKWINDOW_MS 4 -/// Time-stretch algorithm overlap length in milliseconds. When the chopped sound sequences -/// are mixed back together, to form a continuous sound stream, this parameter defines over -/// how long period the two consecutive sequences are let to overlap each other. +/// Time-stretch algorithm overlap length in milliseconds. When the chopped sound sequences +/// are mixed back together, to form a continuous sound stream, this parameter defines over +/// how long period the two consecutive sequences are let to overlap each other. /// See "STTypes.h" or README for more information. #define SETTING_OVERLAP_MS 5 +/// Call "getSetting" with this ID to query nominal average processing sequence +/// size in samples. This value tells approcimate value how many input samples +/// SoundTouch needs to gather before it does DSP processing run for the sample batch. +/// +/// Notices: +/// - This is read-only parameter, i.e. setSetting ignores this parameter +/// - Returned value is approximate average value, exact processing batch +/// size may wary from time to time +/// - This parameter value is not constant but may change depending on +/// tempo/pitch/rate/samplerate settings. +#define SETTING_NOMINAL_INPUT_SEQUENCE 6 + + +/// Call "getSetting" with this ID to query nominal average processing output +/// size in samples. This value tells approcimate value how many output samples +/// SoundTouch outputs once it does DSP processing run for a batch of input samples. +/// +/// Notices: +/// - This is read-only parameter, i.e. setSetting ignores this parameter +/// - Returned value is approximate average value, exact processing batch +/// size may wary from time to time +/// - This parameter value is not constant but may change depending on +/// tempo/pitch/rate/samplerate settings. +#define SETTING_NOMINAL_OUTPUT_SEQUENCE 7 + class SoundTouch : public FIFOProcessor { private: @@ -137,7 +162,7 @@ private: /// Flag: Has sample rate been set? BOOL bSrateSet; - /// Calculates effective rate & tempo valuescfrom 'virtualRate', 'virtualTempo' and + /// Calculates effective rate & tempo valuescfrom 'virtualRate', 'virtualTempo' and /// 'virtualPitch' parameters. void calcEffectiveRateAndTempo(); @@ -181,7 +206,7 @@ public: /// represent lower pitches, larger values higher pitch. void setPitch(float newPitch); - /// Sets pitch change in octaves compared to the original pitch + /// Sets pitch change in octaves compared to the original pitch /// (-1.00 .. +1.00) void setPitchOctaves(float newPitch); @@ -221,7 +246,7 @@ public: /// Changes a setting controlling the processing system behaviour. See the /// 'SETTING_...' defines for available setting ID's. - /// + /// /// \return 'TRUE' if the setting was succesfully changed BOOL setSetting(int settingId, ///< Setting ID number. see SETTING_... defines. int value ///< New setting value. @@ -242,7 +267,7 @@ public: /// classes 'FIFOProcessor' and 'FIFOSamplePipe') /// /// - receiveSamples() : Use this function to receive 'ready' processed samples from SoundTouch. - /// - numSamples() : Get number of 'ready' samples that can be received with + /// - numSamples() : Get number of 'ready' samples that can be received with /// function 'receiveSamples()' /// - isEmpty() : Returns nonzero if there aren't any 'ready' samples. /// - clear() : Clears all samples from ready/processing buffers. diff --git a/3rdparty/SoundTouch/TDStretch.cpp b/3rdparty/SoundTouch/TDStretch.cpp index e37a0f53b8..8fa598f61c 100644 --- a/3rdparty/SoundTouch/TDStretch.cpp +++ b/3rdparty/SoundTouch/TDStretch.cpp @@ -1,10 +1,10 @@ //////////////////////////////////////////////////////////////////////////////// -/// -/// Sampled sound tempo changer/time stretch algorithm. Changes the sound tempo -/// while maintaining the original pitch by using a time domain WSOLA-like +/// +/// Sampled sound tempo changer/time stretch algorithm. Changes the sound tempo +/// while maintaining the original pitch by using a time domain WSOLA-like /// method with several performance-increasing tweaks. /// -/// Note : MMX optimized functions reside in a separate, platform-specific +/// Note : MMX optimized functions reside in a separate, platform-specific /// file, e.g. 'mmx_win.cpp' or 'mmx_gcc.cpp' /// /// Author : Copyright (c) Olli Parviainen @@ -13,10 +13,10 @@ /// //////////////////////////////////////////////////////////////////////////////// // -// Last changed : $Date: 2009-12-28 21:27:04 +0200 (Mon, 28 Dec 2009) $ +// Last changed : $Date: 2012-11-08 16:53:01 -0200 (qui, 08 nov 2012) $ // File revision : $Revision: 1.12 $ // -// $Id: TDStretch.cpp 77 2009-12-28 19:27:04Z oparviai $ +// $Id: TDStretch.cpp 160 2012-11-08 18:53:01Z oparviai $ // //////////////////////////////////////////////////////////////////////////////// // @@ -46,7 +46,6 @@ #include #include #include -#include #include "STTypes.h" #include "cpu_detect.h" @@ -91,7 +90,7 @@ TDStretch::TDStretch() : FIFOProcessor(&outputBuffer) channels = 2; pMidBuffer = NULL; - pRefMidBufferUnaligned = NULL; + pMidBufferUnaligned = NULL; overlapLength = 0; bAutoSeqSetting = TRUE; @@ -101,7 +100,7 @@ TDStretch::TDStretch() : FIFOProcessor(&outputBuffer) skipFract = 0; tempo = 1.0f; - setParameters(48000, DEFAULT_SEQUENCE_MS, DEFAULT_SEEKWINDOW_MS, DEFAULT_OVERLAP_MS); + setParameters(44100, DEFAULT_SEQUENCE_MS, DEFAULT_SEEKWINDOW_MS, DEFAULT_OVERLAP_MS); setTempo(1.0f); clear(); @@ -111,8 +110,7 @@ TDStretch::TDStretch() : FIFOProcessor(&outputBuffer) TDStretch::~TDStretch() { - delete[] pMidBuffer; - delete[] pRefMidBufferUnaligned; + delete[] pMidBufferUnaligned; } @@ -122,11 +120,11 @@ TDStretch::~TDStretch() // // 'sampleRate' = sample rate of the sound // 'sequenceMS' = one processing sequence length in milliseconds (default = 82 ms) -// 'seekwindowMS' = seeking window length for scanning the best overlapping +// 'seekwindowMS' = seeking window length for scanning the best overlapping // position (default = 28 ms) // 'overlapMS' = overlapping length (default = 12 ms) -void TDStretch::setParameters(int aSampleRate, int aSequenceMS, +void TDStretch::setParameters(int aSampleRate, int aSequenceMS, int aSeekWindowMS, int aOverlapMS) { // accept only positive parameter values - if zero or negative, use old values instead @@ -137,19 +135,19 @@ void TDStretch::setParameters(int aSampleRate, int aSequenceMS, { this->sequenceMs = aSequenceMS; bAutoSeqSetting = FALSE; - } + } else if (aSequenceMS == 0) { // if zero, use automatic setting bAutoSeqSetting = TRUE; } - if (aSeekWindowMS > 0) + if (aSeekWindowMS > 0) { this->seekWindowMs = aSeekWindowMS; bAutoSeekSetting = FALSE; - } - else if (aSeekWindowMS == 0) + } + else if (aSeekWindowMS == 0) { // if zero, use automatic setting bAutoSeekSetting = TRUE; @@ -196,12 +194,17 @@ void TDStretch::getParameters(int *pSampleRate, int *pSequenceMs, int *pSeekWind // Overlaps samples in 'midBuffer' with the samples in 'pInput' void TDStretch::overlapMono(SAMPLETYPE *pOutput, const SAMPLETYPE *pInput) const { - int i, itemp; + int i; + SAMPLETYPE m1, m2; - for (i = 0; i < overlapLength ; i ++) + m1 = (SAMPLETYPE)0; + m2 = (SAMPLETYPE)overlapLength; + + for (i = 0; i < overlapLength ; i ++) { - itemp = overlapLength - i; - pOutput[i] = (pInput[i] * i + pMidBuffer[i] * itemp ) / overlapLength; // >> overlapDividerBits; + pOutput[i] = (pInput[i] * m1 + pMidBuffer[i] * m2 ) / overlapLength; + m1 += 1; + m2 -= 1; } } @@ -247,40 +250,22 @@ BOOL TDStretch::isQuickSeekEnabled() const // Seeks for the optimal overlap-mixing position. int TDStretch::seekBestOverlapPosition(const SAMPLETYPE *refPos) { - if (channels == 2) + if (bQuickSeek) { - // stereo sound - if (bQuickSeek) - { - return seekBestOverlapPositionStereoQuick(refPos); - } - else - { - return seekBestOverlapPositionStereo(refPos); - } - } - else + return seekBestOverlapPositionQuick(refPos); + } + else { - // mono sound - if (bQuickSeek) - { - return seekBestOverlapPositionMonoQuick(refPos); - } - else - { - return seekBestOverlapPositionMono(refPos); - } + return seekBestOverlapPositionFull(refPos); } } - - // Overlaps samples in 'midBuffer' with the samples in 'pInputBuffer' at position // of 'ovlPos'. inline void TDStretch::overlap(SAMPLETYPE *pOutput, const SAMPLETYPE *pInput, uint ovlPos) const { - if (channels == 2) + if (channels == 2) { // stereo sound overlapStereo(pOutput, pInput + 2 * ovlPos); @@ -292,38 +277,34 @@ inline void TDStretch::overlap(SAMPLETYPE *pOutput, const SAMPLETYPE *pInput, ui - // Seeks for the optimal overlap-mixing position. The 'stereo' version of the // routine // // The best position is determined as the position where the two overlapped // sample sequences are 'most alike', in terms of the highest cross-correlation // value over the overlapping period -int TDStretch::seekBestOverlapPositionStereo(const SAMPLETYPE *refPos) +int TDStretch::seekBestOverlapPositionFull(const SAMPLETYPE *refPos) { int bestOffs; double bestCorr, corr; int i; - // Slopes the amplitudes of the 'midBuffer' samples - precalcCorrReferenceStereo(); - bestCorr = FLT_MIN; bestOffs = 0; // Scans for the best correlation value by testing each possible position // over the permitted range. - for (i = 0; i < seekLength; i ++) + for (i = 0; i < seekLength; i ++) { // Calculates correlation value for the mixing position corresponding // to 'i' - corr = (double)calcCrossCorrStereo(refPos + 2 * i, pRefMidBuffer); + corr = calcCrossCorr(refPos + channels * i, pMidBuffer); // heuristic rule to slightly favour values close to mid of the range double tmp = (double)(2 * i - seekLength) / (double)seekLength; corr = ((corr + 0.1) * (1.0 - 0.25 * tmp * tmp)); // Checks for the highest correlation value - if (corr > bestCorr) + if (corr > bestCorr) { bestCorr = corr; bestOffs = i; @@ -342,16 +323,13 @@ int TDStretch::seekBestOverlapPositionStereo(const SAMPLETYPE *refPos) // The best position is determined as the position where the two overlapped // sample sequences are 'most alike', in terms of the highest cross-correlation // value over the overlapping period -int TDStretch::seekBestOverlapPositionStereoQuick(const SAMPLETYPE *refPos) +int TDStretch::seekBestOverlapPositionQuick(const SAMPLETYPE *refPos) { int j; int bestOffs; double bestCorr, corr; int scanCount, corrOffset, tempOffset; - // Slopes the amplitude of the 'midBuffer' samples - precalcCorrReferenceStereo(); - bestCorr = FLT_MIN; bestOffs = _scanOffsets[0][0]; corrOffset = 0; @@ -360,26 +338,26 @@ int TDStretch::seekBestOverlapPositionStereoQuick(const SAMPLETYPE *refPos) // Scans for the best correlation value using four-pass hierarchical search. // // The look-up table 'scans' has hierarchical position adjusting steps. - // In first pass the routine searhes for the highest correlation with + // In first pass the routine searhes for the highest correlation with // relatively coarse steps, then rescans the neighbourhood of the highest // correlation with better resolution and so on. - for (scanCount = 0;scanCount < 4; scanCount ++) + for (scanCount = 0;scanCount < 4; scanCount ++) { j = 0; - while (_scanOffsets[scanCount][j]) + while (_scanOffsets[scanCount][j]) { tempOffset = corrOffset + _scanOffsets[scanCount][j]; if (tempOffset >= seekLength) break; // Calculates correlation value for the mixing position corresponding // to 'tempOffset' - corr = (double)calcCrossCorrStereo(refPos + 2 * tempOffset, pRefMidBuffer); + corr = (double)calcCrossCorr(refPos + channels * tempOffset, pMidBuffer); // heuristic rule to slightly favour values close to mid of the range double tmp = (double)(2 * tempOffset - seekLength) / seekLength; corr = ((corr + 0.1) * (1.0 - 0.25 * tmp * tmp)); // Checks for the highest correlation value - if (corr > bestCorr) + if (corr > bestCorr) { bestCorr = corr; bestOffs = tempOffset; @@ -396,112 +374,7 @@ int TDStretch::seekBestOverlapPositionStereoQuick(const SAMPLETYPE *refPos) -// Seeks for the optimal overlap-mixing position. The 'mono' version of the -// routine -// -// The best position is determined as the position where the two overlapped -// sample sequences are 'most alike', in terms of the highest cross-correlation -// value over the overlapping period -int TDStretch::seekBestOverlapPositionMono(const SAMPLETYPE *refPos) -{ - int bestOffs; - double bestCorr, corr; - int tempOffset; - const SAMPLETYPE *compare; - - // Slopes the amplitude of the 'midBuffer' samples - precalcCorrReferenceMono(); - - bestCorr = FLT_MIN; - bestOffs = 0; - - // Scans for the best correlation value by testing each possible position - // over the permitted range. - for (tempOffset = 0; tempOffset < seekLength; tempOffset ++) - { - compare = refPos + tempOffset; - - // Calculates correlation value for the mixing position corresponding - // to 'tempOffset' - corr = (double)calcCrossCorrMono(pRefMidBuffer, compare); - // heuristic rule to slightly favour values close to mid of the range - double tmp = (double)(2 * tempOffset - seekLength) / seekLength; - corr = ((corr + 0.1) * (1.0 - 0.25 * tmp * tmp)); - - // Checks for the highest correlation value - if (corr > bestCorr) - { - bestCorr = corr; - bestOffs = tempOffset; - } - } - // clear cross correlation routine state if necessary (is so e.g. in MMX routines). - clearCrossCorrState(); - - return bestOffs; -} - - -// Seeks for the optimal overlap-mixing position. The 'mono' version of the -// routine -// -// The best position is determined as the position where the two overlapped -// sample sequences are 'most alike', in terms of the highest cross-correlation -// value over the overlapping period -int TDStretch::seekBestOverlapPositionMonoQuick(const SAMPLETYPE *refPos) -{ - int j; - int bestOffs; - double bestCorr, corr; - int scanCount, corrOffset, tempOffset; - - // Slopes the amplitude of the 'midBuffer' samples - precalcCorrReferenceMono(); - - bestCorr = FLT_MIN; - bestOffs = _scanOffsets[0][0]; - corrOffset = 0; - tempOffset = 0; - - // Scans for the best correlation value using four-pass hierarchical search. - // - // The look-up table 'scans' has hierarchical position adjusting steps. - // In first pass the routine searhes for the highest correlation with - // relatively coarse steps, then rescans the neighbourhood of the highest - // correlation with better resolution and so on. - for (scanCount = 0;scanCount < 4; scanCount ++) - { - j = 0; - while (_scanOffsets[scanCount][j]) - { - tempOffset = corrOffset + _scanOffsets[scanCount][j]; - if (tempOffset >= seekLength) break; - - // Calculates correlation value for the mixing position corresponding - // to 'tempOffset' - corr = (double)calcCrossCorrMono(refPos + tempOffset, pRefMidBuffer); - // heuristic rule to slightly favour values close to mid of the range - double tmp = (double)(2 * tempOffset - seekLength) / seekLength; - corr = ((corr + 0.1) * (1.0 - 0.25 * tmp * tmp)); - - // Checks for the highest correlation value - if (corr > bestCorr) - { - bestCorr = corr; - bestOffs = tempOffset; - } - j ++; - } - corrOffset = bestOffs; - } - // clear cross correlation routine state if necessary (is so e.g. in MMX routines). - clearCrossCorrState(); - - return bestOffs; -} - - -/// clear cross correlation routine state if necessary +/// clear cross correlation routine state if necessary void TDStretch::clearCrossCorrState() { // default implementation is empty. @@ -531,7 +404,7 @@ void TDStretch::calcSeqParameters() #define CHECK_LIMITS(x, mi, ma) (((x) < (mi)) ? (mi) : (((x) > (ma)) ? (ma) : (x))) double seq, seek; - + if (bAutoSeqSetting) { seq = AUTOSEQ_C + AUTOSEQ_K * tempo; @@ -548,7 +421,7 @@ void TDStretch::calcSeqParameters() // Update seek window lengths seekWindowLength = (sampleRate * sequenceMs) / 1000; - if (seekWindowLength < 2 * overlapLength) + if (seekWindowLength < 2 * overlapLength) { seekWindowLength = 2 * overlapLength; } @@ -557,7 +430,7 @@ void TDStretch::calcSeqParameters() -// Sets new target tempo. Normal tempo = 'SCALE', smaller values represent slower +// Sets new target tempo. Normal tempo = 'SCALE', smaller values represent slower // tempo, larger faster tempo. void TDStretch::setTempo(float newTempo) { @@ -568,11 +441,11 @@ void TDStretch::setTempo(float newTempo) // Calculate new sequence duration calcSeqParameters(); - // Calculate ideal skip length (according to tempo value) + // Calculate ideal skip length (according to tempo value) nominalSkip = tempo * (seekWindowLength - overlapLength); intskip = (int)(nominalSkip + 0.5f); - // Calculate how many samples are needed in the 'inputBuffer' to + // Calculate how many samples are needed in the 'inputBuffer' to // process another batch of samples //sampleReq = max(intskip + overlapLength, seekWindowLength) + seekLength / 2; sampleReq = max(intskip + overlapLength, seekWindowLength) + seekLength; @@ -600,18 +473,18 @@ void TDStretch::processNominalTempo() { assert(tempo == 1.0f); - if (bMidBufferDirty) + if (bMidBufferDirty) { // If there are samples in pMidBuffer waiting for overlapping, - // do a single sliding overlapping with them in order to prevent a + // do a single sliding overlapping with them in order to prevent a // clicking distortion in the output sound - if (inputBuffer.numSamples() < overlapLength) + if (inputBuffer.numSamples() < overlapLength) { // wait until we've got overlapLength input samples return; } - // Mix the samples in the beginning of 'inputBuffer' with the - // samples in 'midBuffer' using sliding overlapping + // Mix the samples in the beginning of 'inputBuffer' with the + // samples in 'midBuffer' using sliding overlapping overlap(outputBuffer.ptrEnd(overlapLength), inputBuffer.ptrBegin(), 0); outputBuffer.putSamples(overlapLength); inputBuffer.receiveSamples(overlapLength); @@ -636,7 +509,7 @@ void TDStretch::processSamples() /* Removed this small optimization - can introduce a click to sound when tempo setting crosses the nominal value - if (tempo == 1.0f) + if (tempo == 1.0f) { // tempo not changed from the original, so bypass the processing processNominalTempo(); @@ -646,14 +519,13 @@ void TDStretch::processSamples() // Process samples as long as there are enough samples in 'inputBuffer' // to form a processing frame. -// while ((int)inputBuffer.numSamples() >= sampleReq - (outDebt / 4)) - while ((int)inputBuffer.numSamples() >= sampleReq) + while ((int)inputBuffer.numSamples() >= sampleReq) { // If tempo differs from the normal ('SCALE'), scan for the best overlapping // position offset = seekBestOverlapPosition(inputBuffer.ptrBegin()); - // Mix the samples in the 'inputBuffer' at position of 'offset' with the + // Mix the samples in the 'inputBuffer' at position of 'offset' with the // samples in 'midBuffer' using sliding overlapping // ... first partially overlap with the end of the previous sequence // (that's in 'midBuffer') @@ -661,16 +533,8 @@ void TDStretch::processSamples() outputBuffer.putSamples((uint)overlapLength); // ... then copy sequence samples from 'inputBuffer' to output: - temp = (seekLength / 2 - offset); - - // compensate cumulated output length diff vs. ideal output -// temp -= outDebt / 4; - - // update ideal vs. true output difference -// outDebt += temp; // length of sequence -// temp += (seekWindowLength - 2 * overlapLength); temp = (seekWindowLength - 2 * overlapLength); // crosscheck that we don't have buffer overflow... @@ -681,11 +545,11 @@ void TDStretch::processSamples() outputBuffer.putSamples(inputBuffer.ptrBegin() + channels * (offset + overlapLength), (uint)temp); - // Copies the end of the current sequence from 'inputBuffer' to - // 'midBuffer' for being mixed with the beginning of the next + // Copies the end of the current sequence from 'inputBuffer' to + // 'midBuffer' for being mixed with the beginning of the next // processing sequence and so on assert((offset + temp + overlapLength * 2) <= (int)inputBuffer.numSamples()); - memcpy(pMidBuffer, inputBuffer.ptrBegin() + channels * (offset + temp + overlapLength), + memcpy(pMidBuffer, inputBuffer.ptrBegin() + channels * (offset + temp + overlapLength), channels * sizeof(SAMPLETYPE) * overlapLength); // Remove the processed samples from the input buffer. Update @@ -722,26 +586,24 @@ void TDStretch::acceptNewOverlapLength(int newOverlapLength) if (overlapLength > prevOvl) { - delete[] pMidBuffer; - delete[] pRefMidBufferUnaligned; + delete[] pMidBufferUnaligned; + + pMidBufferUnaligned = new SAMPLETYPE[overlapLength * 2 + 16 / sizeof(SAMPLETYPE)]; + // ensure that 'pMidBuffer' is aligned to 16 byte boundary for efficiency + pMidBuffer = (SAMPLETYPE *)SOUNDTOUCH_ALIGN_POINTER_16(pMidBufferUnaligned); - pMidBuffer = new SAMPLETYPE[overlapLength * 2]; clearMidBuffer(); - - pRefMidBufferUnaligned = new SAMPLETYPE[2 * overlapLength + 16 / sizeof(SAMPLETYPE)]; - // ensure that 'pRefMidBuffer' is aligned to 16 byte boundary for efficiency - pRefMidBuffer = (SAMPLETYPE *)((((ulong)pRefMidBufferUnaligned) + 15) & (ulong)-16); } } -// Operator 'new' is overloaded so that it automatically creates a suitable instance +// Operator 'new' is overloaded so that it automatically creates a suitable instance // depending on if we've a MMX/SSE/etc-capable CPU available or not. void * TDStretch::operator new(size_t s) { // Notice! don't use "new TDStretch" directly, use "newInstance" to create a new instance instead! - throw std::runtime_error("Error in TDStretch::new: Don't use 'new TDStretch' directly, use 'newInstance' member instead!"); - return NULL; + ST_THROW_RT_ERROR("Error in TDStretch::new: Don't use 'new TDStretch' directly, use 'newInstance' member instead!"); + return newInstance(); } @@ -751,36 +613,26 @@ TDStretch * TDStretch::newInstance() uExtensions = detectCPUextensions(); - // Check if MMX/SSE/3DNow! instruction set extensions supported by CPU + // Check if MMX/SSE instruction set extensions supported by CPU -#ifdef ALLOW_MMX +#ifdef SOUNDTOUCH_ALLOW_MMX // MMX routines available only with integer sample types if (uExtensions & SUPPORT_MMX) { return ::new TDStretchMMX; } else -#endif // ALLOW_MMX +#endif // SOUNDTOUCH_ALLOW_MMX -#ifdef ALLOW_SSE +#ifdef SOUNDTOUCH_ALLOW_SSE if (uExtensions & SUPPORT_SSE) { // SSE support return ::new TDStretchSSE; } else -#endif // ALLOW_SSE - - -#ifdef ALLOW_3DNOW - if (uExtensions & SUPPORT_3DNOW) - { - // 3DNow! support - return ::new TDStretch3DNow; - } - else -#endif // ALLOW_3DNOW +#endif // SOUNDTOUCH_ALLOW_SSE { // ISA optimizations not supported, use plain C version @@ -795,46 +647,9 @@ TDStretch * TDStretch::newInstance() // ////////////////////////////////////////////////////////////////////////////// -#ifdef INTEGER_SAMPLES +#ifdef SOUNDTOUCH_INTEGER_SAMPLES -// Slopes the amplitude of the 'midBuffer' samples so that cross correlation -// is faster to calculate -void TDStretch::precalcCorrReferenceStereo() -{ - int i, cnt2; - int temp, temp2; - - for (i=0 ; i < (int)overlapLength ;i ++) - { - temp = i * (overlapLength - i); - cnt2 = i * 2; - - temp2 = (pMidBuffer[cnt2] * temp) / slopingDivider; - pRefMidBuffer[cnt2] = (short)(temp2); - temp2 = (pMidBuffer[cnt2 + 1] * temp) / slopingDivider; - pRefMidBuffer[cnt2 + 1] = (short)(temp2); - } -} - - -// Slopes the amplitude of the 'midBuffer' samples so that cross correlation -// is faster to calculate -void TDStretch::precalcCorrReferenceMono() -{ - int i; - long temp; - long temp2; - - for (i=0 ; i < (int)overlapLength ;i ++) - { - temp = i * (overlapLength - i); - temp2 = (pMidBuffer[i] * temp) / slopingDivider; - pRefMidBuffer[i] = (short)temp2; - } -} - - -// Overlaps samples in 'midBuffer' with the samples in 'input'. The 'Stereo' +// Overlaps samples in 'midBuffer' with the samples in 'input'. The 'Stereo' // version of the routine. void TDStretch::overlapStereo(short *poutput, const short *input) const { @@ -842,7 +657,7 @@ void TDStretch::overlapStereo(short *poutput, const short *input) const short temp; int cnt2; - for (i = 0; i < overlapLength ; i ++) + for (i = 0; i < overlapLength ; i ++) { temp = (short)(overlapLength - i); cnt2 = 2 * i; @@ -868,8 +683,8 @@ void TDStretch::calculateOverlapLength(int aoverlapMs) assert(aoverlapMs >= 0); // calculate overlap length so that it's power of 2 - thus it's easy to do - // integer division by right-shifting. Term "-1" at end is to account for - // the extra most significatnt bit left unused in result by signed multiplication + // integer division by right-shifting. Term "-1" at end is to account for + // the extra most significatnt bit left unused in result by signed multiplication overlapDividerBits = _getClosest2Power((sampleRate * aoverlapMs) / 1000.0) - 1; if (overlapDividerBits > 9) overlapDividerBits = 9; if (overlapDividerBits < 3) overlapDividerBits = 3; @@ -877,113 +692,70 @@ void TDStretch::calculateOverlapLength(int aoverlapMs) acceptNewOverlapLength(newOvl); - // calculate sloping divider so that crosscorrelation operation won't - // overflow 32-bit register. Max. sum of the crosscorrelation sum without + // calculate sloping divider so that crosscorrelation operation won't + // overflow 32-bit register. Max. sum of the crosscorrelation sum without // divider would be 2^30*(N^3-N)/3, where N = overlap length slopingDivider = (newOvl * newOvl - 1) / 3; } -long TDStretch::calcCrossCorrMono(const short *mixingPos, const short *compare) const +double TDStretch::calcCrossCorr(const short *mixingPos, const short *compare) const { long corr; long norm; int i; corr = norm = 0; - for (i = 1; i < overlapLength; i ++) + // Same routine for stereo and mono. For stereo, unroll loop for better + // efficiency and gives slightly better resolution against rounding. + // For mono it same routine, just unrolls loop by factor of 4 + for (i = 0; i < channels * overlapLength; i += 4) { - corr += (mixingPos[i] * compare[i]) >> overlapDividerBits; - norm += (mixingPos[i] * mixingPos[i]) >> overlapDividerBits; + corr += (mixingPos[i] * compare[i] + + mixingPos[i + 1] * compare[i + 1] + + mixingPos[i + 2] * compare[i + 2] + + mixingPos[i + 3] * compare[i + 3]) >> overlapDividerBits; + norm += (mixingPos[i] * mixingPos[i] + + mixingPos[i + 1] * mixingPos[i + 1] + + mixingPos[i + 2] * mixingPos[i + 2] + + mixingPos[i + 3] * mixingPos[i + 3]) >> overlapDividerBits; } - // Normalize result by dividing by sqrt(norm) - this step is easiest + // Normalize result by dividing by sqrt(norm) - this step is easiest // done using floating point operation if (norm == 0) norm = 1; // to avoid div by zero - return (long)((double)corr * SHRT_MAX / sqrt((double)norm)); + return (double)corr / sqrt((double)norm); } - -long TDStretch::calcCrossCorrStereo(const short *mixingPos, const short *compare) const -{ - long corr; - long norm; - int i; - - corr = norm = 0; - for (i = 2; i < 2 * overlapLength; i += 2) - { - corr += (mixingPos[i] * compare[i] + - mixingPos[i + 1] * compare[i + 1]) >> overlapDividerBits; - norm += (mixingPos[i] * mixingPos[i] + mixingPos[i + 1] * mixingPos[i + 1]) >> overlapDividerBits; - } - - // Normalize result by dividing by sqrt(norm) - this step is easiest - // done using floating point operation - if (norm == 0) norm = 1; // to avoid div by zero - return (long)((double)corr * SHRT_MAX / sqrt((double)norm)); -} - -#endif // INTEGER_SAMPLES +#endif // SOUNDTOUCH_INTEGER_SAMPLES ////////////////////////////////////////////////////////////////////////////// // // Floating point arithmetics specific algorithm implementations. // -#ifdef FLOAT_SAMPLES - - -// Slopes the amplitude of the 'midBuffer' samples so that cross correlation -// is faster to calculate -void TDStretch::precalcCorrReferenceStereo() -{ - int i, cnt2; - float temp; - - for (i=0 ; i < (int)overlapLength ;i ++) - { - temp = (float)i * (float)(overlapLength - i); - cnt2 = i * 2; - pRefMidBuffer[cnt2] = (float)(pMidBuffer[cnt2] * temp); - pRefMidBuffer[cnt2 + 1] = (float)(pMidBuffer[cnt2 + 1] * temp); - } -} - - -// Slopes the amplitude of the 'midBuffer' samples so that cross correlation -// is faster to calculate -void TDStretch::precalcCorrReferenceMono() -{ - int i; - float temp; - - for (i=0 ; i < (int)overlapLength ;i ++) - { - temp = (float)i * (float)(overlapLength - i); - pRefMidBuffer[i] = (float)(pMidBuffer[i] * temp); - } -} - +#ifdef SOUNDTOUCH_FLOAT_SAMPLES // Overlaps samples in 'midBuffer' with the samples in 'pInput' void TDStretch::overlapStereo(float *pOutput, const float *pInput) const { int i; - int cnt2; - float fTemp; float fScale; - float fi; + float f1; + float f2; fScale = 1.0f / (float)overlapLength; - for (i = 0; i < (int)overlapLength ; i ++) + f1 = 0; + f2 = 1.0f; + + for (i = 0; i < 2 * (int)overlapLength ; i += 2) { - fTemp = (float)(overlapLength - i) * fScale; - fi = (float)i * fScale; - cnt2 = 2 * i; - pOutput[cnt2 + 0] = pInput[cnt2 + 0] * fi + pMidBuffer[cnt2 + 0] * fTemp; - pOutput[cnt2 + 1] = pInput[cnt2 + 1] * fi + pMidBuffer[cnt2 + 1] * fTemp; + pOutput[i + 0] = pInput[i + 0] * f1 + pMidBuffer[i + 0] * f2; + pOutput[i + 1] = pInput[i + 1] * f1 + pMidBuffer[i + 1] * f2; + + f1 += fScale; + f2 -= fScale; } } @@ -1004,42 +776,33 @@ void TDStretch::calculateOverlapLength(int overlapInMsec) } - -double TDStretch::calcCrossCorrMono(const float *mixingPos, const float *compare) const +double TDStretch::calcCrossCorr(const float *mixingPos, const float *compare) const { double corr; double norm; int i; corr = norm = 0; - for (i = 1; i < overlapLength; i ++) - { - corr += mixingPos[i] * compare[i]; - norm += mixingPos[i] * mixingPos[i]; - } - - if (norm < 1e-9) norm = 1.0; // to avoid div by zero - return corr / sqrt(norm); -} - - -double TDStretch::calcCrossCorrStereo(const float *mixingPos, const float *compare) const -{ - double corr; - double norm; - int i; - - corr = norm = 0; - for (i = 2; i < 2 * overlapLength; i += 2) + // Same routine for stereo and mono. For Stereo, unroll by factor of 2. + // For mono it's same routine yet unrollsd by factor of 4. + for (i = 0; i < channels * overlapLength; i += 4) { corr += mixingPos[i] * compare[i] + mixingPos[i + 1] * compare[i + 1]; - norm += mixingPos[i] * mixingPos[i] + + + norm += mixingPos[i] * mixingPos[i] + mixingPos[i + 1] * mixingPos[i + 1]; + + // unroll the loop for better CPU efficiency: + corr += mixingPos[i + 2] * compare[i + 2] + + mixingPos[i + 3] * compare[i + 3]; + + norm += mixingPos[i + 2] * mixingPos[i + 2] + + mixingPos[i + 3] * mixingPos[i + 3]; } if (norm < 1e-9) norm = 1.0; // to avoid div by zero return corr / sqrt(norm); } -#endif // FLOAT_SAMPLES +#endif // SOUNDTOUCH_FLOAT_SAMPLES diff --git a/3rdparty/SoundTouch/TDStretch.h b/3rdparty/SoundTouch/TDStretch.h index 1962d818a1..6861251014 100644 --- a/3rdparty/SoundTouch/TDStretch.h +++ b/3rdparty/SoundTouch/TDStretch.h @@ -1,10 +1,10 @@ //////////////////////////////////////////////////////////////////////////////// -/// -/// Sampled sound tempo changer/time stretch algorithm. Changes the sound tempo -/// while maintaining the original pitch by using a time domain WSOLA-like method +/// +/// Sampled sound tempo changer/time stretch algorithm. Changes the sound tempo +/// while maintaining the original pitch by using a time domain WSOLA-like method /// with several performance-increasing tweaks. /// -/// Note : MMX/SSE optimized functions reside in separate, platform-specific files +/// Note : MMX/SSE optimized functions reside in separate, platform-specific files /// 'mmx_optimized.cpp' and 'sse_optimized.cpp' /// /// Author : Copyright (c) Olli Parviainen @@ -13,10 +13,10 @@ /// //////////////////////////////////////////////////////////////////////////////// // -// Last changed : $Date: 2009-05-17 14:35:13 +0300 (Sun, 17 May 2009) $ +// Last changed : $Date: 2012-04-01 16:49:30 -0300 (dom, 01 abr 2012) $ // File revision : $Revision: 4 $ // -// $Id: TDStretch.h 71 2009-05-17 11:35:13Z oparviai $ +// $Id: TDStretch.h 137 2012-04-01 19:49:30Z oparviai $ // //////////////////////////////////////////////////////////////////////////////// // @@ -53,14 +53,14 @@ namespace soundtouch { /// Default values for sound processing parameters: -/// Notice that the default parameters are tuned for contemporary popular music +/// Notice that the default parameters are tuned for contemporary popular music /// processing. For speech processing applications these parameters suit better: /// #define DEFAULT_SEQUENCE_MS 40 /// #define DEFAULT_SEEKWINDOW_MS 15 /// #define DEFAULT_OVERLAP_MS 8 /// -/// Default length of a single processing sequence, in milliseconds. This determines to how +/// Default length of a single processing sequence, in milliseconds. This determines to how /// long sequences the original sound is chopped in the time-stretch algorithm. /// /// The larger this value is, the lesser sequences are used in processing. In principle @@ -75,15 +75,15 @@ namespace soundtouch /// according to tempo setting (recommended) #define USE_AUTO_SEQUENCE_LEN 0 -/// Seeking window default length in milliseconds for algorithm that finds the best possible -/// overlapping location. This determines from how wide window the algorithm may look for an -/// optimal joining location when mixing the sound sequences back together. +/// Seeking window default length in milliseconds for algorithm that finds the best possible +/// overlapping location. This determines from how wide window the algorithm may look for an +/// optimal joining location when mixing the sound sequences back together. /// /// The bigger this window setting is, the higher the possibility to find a better mixing /// position will become, but at the same time large values may cause a "drifting" artifact /// because consequent sequences will be taken at more uneven intervals. /// -/// If there's a disturbing artifact that sounds as if a constant frequency was drifting +/// If there's a disturbing artifact that sounds as if a constant frequency was drifting /// around, try reducing this setting. /// /// Increasing this value increases computational burden & vice versa. @@ -94,11 +94,11 @@ namespace soundtouch /// according to tempo setting (recommended) #define USE_AUTO_SEEKWINDOW_LEN 0 -/// Overlap length in milliseconds. When the chopped sound sequences are mixed back together, -/// to form a continuous sound stream, this parameter defines over how long period the two -/// consecutive sequences are let to overlap each other. +/// Overlap length in milliseconds. When the chopped sound sequences are mixed back together, +/// to form a continuous sound stream, this parameter defines over how long period the two +/// consecutive sequences are let to overlap each other. /// -/// This shouldn't be that critical parameter. If you reduce the DEFAULT_SEQUENCE_MS setting +/// This shouldn't be that critical parameter. If you reduce the DEFAULT_SEQUENCE_MS setting /// by a large amount, you might wish to try a smaller value on this. /// /// Increasing this value increases computational burden & vice versa. @@ -115,8 +115,7 @@ protected: float tempo; SAMPLETYPE *pMidBuffer; - SAMPLETYPE *pRefMidBuffer; - SAMPLETYPE *pRefMidBufferUnaligned; + SAMPLETYPE *pMidBufferUnaligned; int overlapLength; int seekLength; int seekWindowLength; @@ -127,8 +126,6 @@ protected: FIFOSampleBuffer outputBuffer; FIFOSampleBuffer inputBuffer; BOOL bQuickSeek; -// int outDebt; -// BOOL bMidBufferDirty; int sampleRate; int sequenceMs; @@ -142,13 +139,10 @@ protected: virtual void clearCrossCorrState(); void calculateOverlapLength(int overlapMs); - virtual LONG_SAMPLETYPE calcCrossCorrStereo(const SAMPLETYPE *mixingPos, const SAMPLETYPE *compare) const; - virtual LONG_SAMPLETYPE calcCrossCorrMono(const SAMPLETYPE *mixingPos, const SAMPLETYPE *compare) const; + virtual double calcCrossCorr(const SAMPLETYPE *mixingPos, const SAMPLETYPE *compare) const; - virtual int seekBestOverlapPositionStereo(const SAMPLETYPE *refPos); - virtual int seekBestOverlapPositionStereoQuick(const SAMPLETYPE *refPos); - virtual int seekBestOverlapPositionMono(const SAMPLETYPE *refPos); - virtual int seekBestOverlapPositionMonoQuick(const SAMPLETYPE *refPos); + virtual int seekBestOverlapPositionFull(const SAMPLETYPE *refPos); + virtual int seekBestOverlapPositionQuick(const SAMPLETYPE *refPos); int seekBestOverlapPosition(const SAMPLETYPE *refPos); virtual void overlapStereo(SAMPLETYPE *output, const SAMPLETYPE *input) const; @@ -157,9 +151,6 @@ protected: void clearMidBuffer(); void overlap(SAMPLETYPE *output, const SAMPLETYPE *input, uint ovlPos) const; - void precalcCorrReferenceMono(); - void precalcCorrReferenceStereo(); - void calcSeqParameters(); /// Changes the tempo of the given sound samples. @@ -167,27 +158,27 @@ protected: /// The maximum amount of samples that can be returned at a time is set by /// the 'set_returnBuffer_size' function. void processSamples(); - + public: TDStretch(); virtual ~TDStretch(); - /// Operator 'new' is overloaded so that it automatically creates a suitable instance + /// Operator 'new' is overloaded so that it automatically creates a suitable instance /// depending on if we've a MMX/SSE/etc-capable CPU available or not. static void *operator new(size_t s); - /// Use this function instead of "new" operator to create a new instance of this class. + /// Use this function instead of "new" operator to create a new instance of this class. /// This function automatically chooses a correct feature set depending on if the CPU /// supports MMX/SSE/etc extensions. static TDStretch *newInstance(); - + /// Returns the output buffer object FIFOSamplePipe *getOutput() { return &outputBuffer; }; /// Returns the input buffer object FIFOSamplePipe *getInput() { return &inputBuffer; }; - /// Sets new target tempo. Normal tempo = 'SCALE', smaller values represent slower + /// Sets new target tempo. Normal tempo = 'SCALE', smaller values represent slower /// tempo, larger faster tempo. void setTempo(float newTempo); @@ -200,7 +191,7 @@ public: /// Sets the number of channels, 1 = mono, 2 = stereo void setChannels(int numChannels); - /// Enables/disables the quick position seeking algorithm. Zero to disable, + /// Enables/disables the quick position seeking algorithm. Zero to disable, /// nonzero to enable void enableQuickSeek(BOOL enable); @@ -212,7 +203,7 @@ public: // /// 'sampleRate' = sample rate of the sound /// 'sequenceMS' = one processing sequence length in milliseconds - /// 'seekwindowMS' = seeking window length for scanning the best overlapping + /// 'seekwindowMS' = seeking window length for scanning the best overlapping /// position /// 'overlapMS' = overlapping length void setParameters(int sampleRate, ///< Samplerate of sound being processed (Hz) @@ -233,43 +224,45 @@ public: uint numSamples ///< Number of samples in 'samples' so that one sample ///< contains both channels if stereo ); + + /// return nominal input sample requirement for triggering a processing batch + int getInputSampleReq() const + { + return (int)(nominalSkip + 0.5); + } + + /// return nominal output sample amount when running a processing batch + int getOutputBatchSize() const + { + return seekWindowLength - overlapLength; + } }; // Implementation-specific class declarations: -#ifdef ALLOW_MMX +#ifdef SOUNDTOUCH_ALLOW_MMX /// Class that implements MMX optimized routines for 16bit integer samples type. class TDStretchMMX : public TDStretch { protected: - long calcCrossCorrStereo(const short *mixingPos, const short *compare) const; + double calcCrossCorr(const short *mixingPos, const short *compare) const; virtual void overlapStereo(short *output, const short *input) const; virtual void clearCrossCorrState(); }; -#endif /// ALLOW_MMX +#endif /// SOUNDTOUCH_ALLOW_MMX -#ifdef ALLOW_3DNOW - /// Class that implements 3DNow! optimized routines for floating point samples type. - class TDStretch3DNow : public TDStretch - { - protected: - double calcCrossCorrStereo(const float *mixingPos, const float *compare) const; - }; -#endif /// ALLOW_3DNOW - - -#ifdef ALLOW_SSE +#ifdef SOUNDTOUCH_ALLOW_SSE /// Class that implements SSE optimized routines for floating point samples type. class TDStretchSSE : public TDStretch { protected: - double calcCrossCorrStereo(const float *mixingPos, const float *compare) const; + double calcCrossCorr(const float *mixingPos, const float *compare) const; }; -#endif /// ALLOW_SSE +#endif /// SOUNDTOUCH_ALLOW_SSE } #endif /// TDStretch_H diff --git a/3rdparty/SoundTouch/cpu_detect.h b/3rdparty/SoundTouch/cpu_detect.h index 33c5026ce0..809f841b3d 100644 --- a/3rdparty/SoundTouch/cpu_detect.h +++ b/3rdparty/SoundTouch/cpu_detect.h @@ -2,8 +2,8 @@ /// /// A header file for detecting the Intel MMX instructions set extension. /// -/// Please see 'mmx_win.cpp', 'mmx_cpp.cpp' and 'mmx_non_x86.cpp' for the -/// routine implementations for x86 Windows, x86 gnu version and non-x86 +/// Please see 'mmx_win.cpp', 'mmx_cpp.cpp' and 'mmx_non_x86.cpp' for the +/// routine implementations for x86 Windows, x86 gnu version and non-x86 /// platforms, respectively. /// /// Author : Copyright (c) Olli Parviainen @@ -12,7 +12,7 @@ /// //////////////////////////////////////////////////////////////////////////////// // -// Last changed : $Date: 2008-02-10 18:26:55 +0200 (Sun, 10 Feb 2008) $ +// Last changed : $Date: 2008-02-10 14:26:55 -0200 (dom, 10 fev 2008) $ // File revision : $Revision: 4 $ // // $Id: cpu_detect.h 11 2008-02-10 16:26:55Z oparviai $ diff --git a/3rdparty/SoundTouch/cpu_detect_x86.cpp b/3rdparty/SoundTouch/cpu_detect_x86.cpp new file mode 100644 index 0000000000..4b09dba20b --- /dev/null +++ b/3rdparty/SoundTouch/cpu_detect_x86.cpp @@ -0,0 +1,137 @@ +//////////////////////////////////////////////////////////////////////////////// +/// +/// Generic version of the x86 CPU extension detection routine. +/// +/// This file is for GNU & other non-Windows compilers, see 'cpu_detect_x86_win.cpp' +/// for the Microsoft compiler version. +/// +/// Author : Copyright (c) Olli Parviainen +/// Author e-mail : oparviai 'at' iki.fi +/// SoundTouch WWW: http://www.surina.net/soundtouch +/// +//////////////////////////////////////////////////////////////////////////////// +// +// Last changed : $Date: 2012-11-08 16:44:37 -0200 (qui, 08 nov 2012) $ +// File revision : $Revision: 4 $ +// +// $Id: cpu_detect_x86.cpp 159 2012-11-08 18:44:37Z oparviai $ +// +//////////////////////////////////////////////////////////////////////////////// +// +// License : +// +// SoundTouch audio processing library +// Copyright (c) Olli Parviainen +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +//////////////////////////////////////////////////////////////////////////////// + +#include "cpu_detect.h" +#include "STTypes.h" + +#if defined(SOUNDTOUCH_ALLOW_X86_OPTIMIZATIONS) + + #if defined(__GNUC__) && defined(__i386__) + // gcc + #include "cpuid.h" + #elif defined(_M_IX86) + // windows non-gcc + #include + #define bit_MMX (1 << 23) + #define bit_SSE (1 << 25) + #define bit_SSE2 (1 << 26) + #endif + +#endif + + +////////////////////////////////////////////////////////////////////////////// +// +// processor instructions extension detection routines +// +////////////////////////////////////////////////////////////////////////////// + +// Flag variable indicating whick ISA extensions are disabled (for debugging) +static uint _dwDisabledISA = 0x00; // 0xffffffff; //<- use this to disable all extensions + +// Disables given set of instruction extensions. See SUPPORT_... defines. +void disableExtensions(uint dwDisableMask) +{ + _dwDisabledISA = dwDisableMask; +} + + + +/// Checks which instruction set extensions are supported by the CPU. +uint detectCPUextensions(void) +{ +/// If building for a 64bit system (no Itanium) and the user wants optimizations. +/// Return the OR of SUPPORT_{MMX,SSE,SSE2}. 11001 or 0x19. +/// Keep the _dwDisabledISA test (2 more operations, could be eliminated). +#if ((defined(__GNUC__) && defined(__x86_64__)) \ + || defined(_M_X64)) \ + && defined(SOUNDTOUCH_ALLOW_X86_OPTIMIZATIONS) + return 0x19 & ~_dwDisabledISA; + +/// If building for a 32bit system and the user wants optimizations. +/// Keep the _dwDisabledISA test (2 more operations, could be eliminated). +#elif ((defined(__GNUC__) && defined(__i386__)) \ + || defined(_M_IX86)) \ + && defined(SOUNDTOUCH_ALLOW_X86_OPTIMIZATIONS) + + if (_dwDisabledISA == 0xffffffff) return 0; + + uint res = 0; + +#if defined(__GNUC__) + // GCC version of cpuid. Requires GCC 4.3.0 or later for __cpuid intrinsic support. + uint eax, ebx, ecx, edx; // unsigned int is the standard type. uint is defined by the compiler and not guaranteed to be portable. + + // Check if no cpuid support. + if (!__get_cpuid (1, &eax, &ebx, &ecx, &edx)) return 0; // always disable extensions. + + if (edx & bit_MMX) res = res | SUPPORT_MMX; + if (edx & bit_SSE) res = res | SUPPORT_SSE; + if (edx & bit_SSE2) res = res | SUPPORT_SSE2; + +#else + // Window / VS version of cpuid. Notice that Visual Studio 2005 or later required + // for __cpuid intrinsic support. + int reg[4] = {-1}; + + // Check if no cpuid support. + __cpuid(reg,0); + if ((unsigned int)reg[0] == 0) return 0; // always disable extensions. + + __cpuid(reg,1); + if ((unsigned int)reg[3] & bit_MMX) res = res | SUPPORT_MMX; + if ((unsigned int)reg[3] & bit_SSE) res = res | SUPPORT_SSE; + if ((unsigned int)reg[3] & bit_SSE2) res = res | SUPPORT_SSE2; + +#endif + + return res & ~_dwDisabledISA; + +#else + +/// One of these is true: +/// 1) We don't want optimizations. +/// 2) Using an unsupported compiler. +/// 3) Running on a non-x86 platform. + return 0; + +#endif +} diff --git a/3rdparty/SoundTouch/cpu_detect_x86_gcc.cpp b/3rdparty/SoundTouch/cpu_detect_x86_gcc.cpp index 806de7f288..dbb79236bc 100644 --- a/3rdparty/SoundTouch/cpu_detect_x86_gcc.cpp +++ b/3rdparty/SoundTouch/cpu_detect_x86_gcc.cpp @@ -2,7 +2,7 @@ /// /// Generic version of the x86 CPU extension detection routine. /// -/// This file is for GNU & other non-Windows compilers, see 'cpu_detect_x86_win.cpp' +/// This file is for GNU & other non-Windows compilers, see 'cpu_detect_x86_win.cpp' /// for the Microsoft compiler version. /// /// Author : Copyright (c) Olli Parviainen @@ -11,10 +11,10 @@ /// //////////////////////////////////////////////////////////////////////////////// // -// Last changed : $Date: 2009-02-25 19:13:51 +0200 (Wed, 25 Feb 2009) $ +// Last changed : $Date: 2011-09-02 15:56:11 -0300 (sex, 02 set 2011) $ // File revision : $Revision: 4 $ // -// $Id: cpu_detect_x86_gcc.cpp 67 2009-02-25 17:13:51Z oparviai $ +// $Id: cpu_detect_x86_gcc.cpp 131 2011-09-02 18:56:11Z oparviai $ // //////////////////////////////////////////////////////////////////////////////// // @@ -39,15 +39,9 @@ // //////////////////////////////////////////////////////////////////////////////// -#include -#include #include "cpu_detect.h" #include "STTypes.h" -using namespace std; - -#include - ////////////////////////////////////////////////////////////////////////////// // // processor instructions extension detection routines @@ -68,7 +62,7 @@ void disableExtensions(uint dwDisableMask) /// Checks which instruction set extensions are supported by the CPU. uint detectCPUextensions(void) { -#if (!(ALLOW_X86_OPTIMIZATIONS) || !(__GNUC__)) +#if (!(SOUNDTOUCH_ALLOW_X86_OPTIMIZATIONS) || !(__GNUC__)) return 0; // always disable extensions on non-x86 platforms. @@ -78,8 +72,11 @@ uint detectCPUextensions(void) if (_dwDisabledISA == 0xffffffff) return 0; asm volatile( +#ifndef __x86_64__ + // Check if 'cpuid' instructions is available by toggling eflags bit 21. + // Skip this for x86-64 as they always have cpuid while stack manipulation + // differs from 16/32bit ISA. "\n\txor %%esi, %%esi" // clear %%esi = result register - // check if 'cpuid' instructions is available by toggling eflags bit 21 "\n\tpushf" // save eflags to stack "\n\tmovl (%%esp), %%eax" // load eax from stack (with eflags) @@ -93,6 +90,8 @@ uint detectCPUextensions(void) "\n\txor %%edx, %%edx" // clear edx for defaulting no mmx "\n\tcmp %%ecx, %%eax" // compare to original eflags values "\n\tjz end" // jumps to 'end' if cpuid not present +#endif // __x86_64__ + // cpuid instruction available, test for presence of mmx instructions "\n\tmovl $1, %%eax" @@ -129,7 +128,7 @@ uint detectCPUextensions(void) : "=r" (res) : /* no inputs */ : "%edx", "%eax", "%ecx", "%esi" ); - + return res & ~_dwDisabledISA; #endif } diff --git a/3rdparty/SoundTouch/cpu_detect_x86_win.cpp b/3rdparty/SoundTouch/cpu_detect_x86_win.cpp index 883a3accc0..666c7b0700 100644 --- a/3rdparty/SoundTouch/cpu_detect_x86_win.cpp +++ b/3rdparty/SoundTouch/cpu_detect_x86_win.cpp @@ -2,8 +2,8 @@ /// /// Win32 version of the x86 CPU detect routine. /// -/// This file is to be compiled in Windows platform with Microsoft Visual C++ -/// Compiler. Please see 'cpu_detect_x86_gcc.cpp' for the gcc compiler version +/// This file is to be compiled in Windows platform with Microsoft Visual C++ +/// Compiler. Please see 'cpu_detect_x86_gcc.cpp' for the gcc compiler version /// for all GNU platforms. /// /// Author : Copyright (c) Olli Parviainen @@ -12,10 +12,10 @@ /// //////////////////////////////////////////////////////////////////////////////// // -// Last changed : $Date: 2009-02-13 18:22:48 +0200 (Fri, 13 Feb 2009) $ +// Last changed : $Date: 2011-07-17 07:58:40 -0300 (dom, 17 jul 2011) $ // File revision : $Revision: 4 $ // -// $Id: cpu_detect_x86_win.cpp 62 2009-02-13 16:22:48Z oparviai $ +// $Id: cpu_detect_x86_win.cpp 127 2011-07-17 10:58:40Z oparviai $ // //////////////////////////////////////////////////////////////////////////////// // @@ -42,9 +42,7 @@ #include "cpu_detect.h" -#ifndef WIN32 -#error wrong platform - this source code file is exclusively for Win32 platform -#endif +#include "STTypes.h" ////////////////////////////////////////////////////////////////////////////// // @@ -71,7 +69,9 @@ uint detectCPUextensions(void) if (_dwDisabledISA == 0xffffffff) return 0; - _asm +#ifndef _M_X64 + // 32bit compilation, detect CPU capabilities with inline assembler. + __asm { ; check if 'cpuid' instructions is available by toggling eflags bit 21 ; @@ -92,7 +92,7 @@ uint detectCPUextensions(void) cmp eax, ecx ; compare to original eflags values jz end ; jumps to 'end' if cpuid not present - ; cpuid instruction available, test for presence of mmx instructions + ; cpuid instruction available, test for presence of mmx instructions mov eax, 1 cpuid test edx, 0x00800000 @@ -125,5 +125,13 @@ uint detectCPUextensions(void) mov res, esi } +#else + + // Visual C++ 64bit compilation doesn't support inline assembler. However, + // all x64 compatible CPUs support MMX & SSE extensions. + res = SUPPORT_MMX | SUPPORT_SSE | SUPPORT_SSE2; + +#endif + return res & ~_dwDisabledISA; } diff --git a/3rdparty/SoundTouch/mmx_optimized.cpp b/3rdparty/SoundTouch/mmx_optimized.cpp index 477119529a..15d8af1b76 100644 --- a/3rdparty/SoundTouch/mmx_optimized.cpp +++ b/3rdparty/SoundTouch/mmx_optimized.cpp @@ -1,15 +1,15 @@ //////////////////////////////////////////////////////////////////////////////// /// -/// MMX optimized routines. All MMX optimized functions have been gathered into -/// this single source code file, regardless to their class or original source -/// code file, in order to ease porting the library to other compiler and +/// MMX optimized routines. All MMX optimized functions have been gathered into +/// this single source code file, regardless to their class or original source +/// code file, in order to ease porting the library to other compiler and /// processor platforms. /// /// The MMX-optimizations are programmed using MMX compiler intrinsics that /// are supported both by Microsoft Visual C++ and GCC compilers, so this file /// should compile with both toolsets. /// -/// NOTICE: If using Visual Studio 6.0, you'll need to install the "Visual C++ +/// NOTICE: If using Visual Studio 6.0, you'll need to install the "Visual C++ /// 6.0 processor pack" update to support compiler intrinsic syntax. The update /// is available for download at Microsoft Developers Network, see here: /// http://msdn.microsoft.com/en-us/vstudio/aa718349.aspx @@ -20,10 +20,10 @@ /// //////////////////////////////////////////////////////////////////////////////// // -// Last changed : $Date: 2009-10-31 16:53:23 +0200 (Sat, 31 Oct 2009) $ +// Last changed : $Date: 2012-11-08 16:53:01 -0200 (qui, 08 nov 2012) $ // File revision : $Revision: 4 $ // -// $Id: mmx_optimized.cpp 75 2009-10-31 14:53:23Z oparviai $ +// $Id: mmx_optimized.cpp 160 2012-11-08 18:53:01Z oparviai $ // //////////////////////////////////////////////////////////////////////////////// // @@ -50,13 +50,9 @@ #include "STTypes.h" -#ifdef ALLOW_MMX +#ifdef SOUNDTOUCH_ALLOW_MMX // MMX routines available only with integer sample type -#if !(WIN32 || __i386__ || __x86_64__) -#error "wrong platform - this source code file is exclusively for x86 platforms" -#endif - using namespace soundtouch; ////////////////////////////////////////////////////////////////////////////// @@ -72,23 +68,23 @@ using namespace soundtouch; // Calculates cross correlation of two buffers -long TDStretchMMX::calcCrossCorrStereo(const short *pV1, const short *pV2) const +double TDStretchMMX::calcCrossCorr(const short *pV1, const short *pV2) const { const __m64 *pVec1, *pVec2; __m64 shifter; __m64 accu, normaccu; long corr, norm; int i; - + pVec1 = (__m64*)pV1; pVec2 = (__m64*)pV2; shifter = _m_from_int(overlapDividerBits); normaccu = accu = _mm_setzero_si64(); - // Process 4 parallel sets of 2 * stereo samples each during each - // round to improve CPU-level parallellization. - for (i = 0; i < overlapLength / 8; i ++) + // Process 4 parallel sets of 2 * stereo samples or 4 * mono samples + // during each round for improved CPU-level parallellization. + for (i = 0; i < channels * overlapLength / 16; i ++) { __m64 temp, temp2; @@ -127,10 +123,11 @@ long TDStretchMMX::calcCrossCorrStereo(const short *pV1, const short *pV2) const // Clear MMS state _m_empty(); - // Normalize result by dividing by sqrt(norm) - this step is easiest + // Normalize result by dividing by sqrt(norm) - this step is easiest // done using floating point operation if (norm == 0) norm = 1; // to avoid div by zero - return (long)((double)corr * USHRT_MAX / sqrt((double)norm)); + + return (double)corr / sqrt((double)norm); // Note: Warning about the missing EMMS instruction is harmless // as it'll be called elsewhere. } @@ -161,7 +158,7 @@ void TDStretchMMX::overlapStereo(short *output, const short *input) const // mix1 = mixer values for 1st stereo sample // mix1 = mixer values for 2nd stereo sample // adder = adder for updating mixer values after each round - + mix1 = _mm_set_pi16(0, overlapLength, 0, overlapLength); adder = _mm_set_pi16(1, -1, 1, -1); mix2 = _mm_add_pi16(mix1, adder); @@ -174,7 +171,7 @@ void TDStretchMMX::overlapStereo(short *output, const short *input) const for (i = 0; i < overlapLength / 4; i ++) { __m64 temp1, temp2; - + // load & shuffle data so that input & mixbuffer data samples are paired temp1 = _mm_unpacklo_pi16(pVMidBuf[0], pVinput[0]); // = i0l m0l i0r m0r temp2 = _mm_unpackhi_pi16(pVMidBuf[0], pVinput[0]); // = i1l m1l i1r m1r @@ -242,10 +239,10 @@ void FIRFilterMMX::setCoefficients(const short *coeffs, uint newLength, uint uRe // Ensure that filter coeffs array is aligned to 16-byte boundary delete[] filterCoeffsUnalign; filterCoeffsUnalign = new short[2 * newLength + 8]; - filterCoeffsAlign = (short *)(((ulong)filterCoeffsUnalign + 15) & -16); + filterCoeffsAlign = (short *)SOUNDTOUCH_ALIGN_POINTER_16(filterCoeffsUnalign); - // rearrange the filter coefficients for mmx routines - for (i = 0;i < length; i += 4) + // rearrange the filter coefficients for mmx routines + for (i = 0;i < length; i += 4) { filterCoeffsAlign[2 * i + 0] = coeffs[i + 0]; filterCoeffsAlign[2 * i + 1] = coeffs[i + 2]; @@ -317,4 +314,4 @@ uint FIRFilterMMX::evaluateFilterStereo(short *dest, const short *src, uint numS return (numSamples & 0xfffffffe) - length; } -#endif // ALLOW_MMX +#endif // SOUNDTOUCH_ALLOW_MMX diff --git a/3rdparty/SoundTouch/sse_optimized.cpp b/3rdparty/SoundTouch/sse_optimized.cpp index 7edd1cb79e..3566252cad 100644 --- a/3rdparty/SoundTouch/sse_optimized.cpp +++ b/3rdparty/SoundTouch/sse_optimized.cpp @@ -1,20 +1,20 @@ //////////////////////////////////////////////////////////////////////////////// /// -/// SSE optimized routines for Pentium-III, Athlon-XP and later CPUs. All SSE -/// optimized functions have been gathered into this single source -/// code file, regardless to their class or original source code file, in order +/// SSE optimized routines for Pentium-III, Athlon-XP and later CPUs. All SSE +/// optimized functions have been gathered into this single source +/// code file, regardless to their class or original source code file, in order /// to ease porting the library to other compiler and processor platforms. /// /// The SSE-optimizations are programmed using SSE compiler intrinsics that /// are supported both by Microsoft Visual C++ and GCC compilers, so this file /// should compile with both toolsets. /// -/// NOTICE: If using Visual Studio 6.0, you'll need to install the "Visual C++ -/// 6.0 processor pack" update to support SSE instruction set. The update is +/// NOTICE: If using Visual Studio 6.0, you'll need to install the "Visual C++ +/// 6.0 processor pack" update to support SSE instruction set. The update is /// available for download at Microsoft Developers Network, see here: /// http://msdn.microsoft.com/en-us/vstudio/aa718349.aspx /// -/// If the above URL is expired or removed, go to "http://msdn.microsoft.com" and +/// If the above URL is expired or removed, go to "http://msdn.microsoft.com" and /// perform a search with keywords "processor pack". /// /// Author : Copyright (c) Olli Parviainen @@ -23,10 +23,10 @@ /// //////////////////////////////////////////////////////////////////////////////// // -// Last changed : $Date: 2009-12-28 22:32:57 +0200 (Mon, 28 Dec 2009) $ +// Last changed : $Date: 2012-11-08 16:53:01 -0200 (qui, 08 nov 2012) $ // File revision : $Revision: 4 $ // -// $Id: sse_optimized.cpp 80 2009-12-28 20:32:57Z oparviai $ +// $Id: sse_optimized.cpp 160 2012-11-08 18:53:01Z oparviai $ // //////////////////////////////////////////////////////////////////////////////// // @@ -56,9 +56,9 @@ using namespace soundtouch; -#ifdef ALLOW_SSE +#ifdef SOUNDTOUCH_ALLOW_SSE -// SSE routines available only with float sample type +// SSE routines available only with float sample type ////////////////////////////////////////////////////////////////////////////// // @@ -71,35 +71,35 @@ using namespace soundtouch; #include // Calculates cross correlation of two buffers -double TDStretchSSE::calcCrossCorrStereo(const float *pV1, const float *pV2) const +double TDStretchSSE::calcCrossCorr(const float *pV1, const float *pV2) const { int i; const float *pVec1; const __m128 *pVec2; __m128 vSum, vNorm; - // Note. It means a major slow-down if the routine needs to tolerate - // unaligned __m128 memory accesses. It's way faster if we can skip + // Note. It means a major slow-down if the routine needs to tolerate + // unaligned __m128 memory accesses. It's way faster if we can skip // unaligned slots and use _mm_load_ps instruction instead of _mm_loadu_ps. // This can mean up to ~ 10-fold difference (incl. part of which is // due to skipping every second round for stereo sound though). // - // Compile-time define ALLOW_NONEXACT_SIMD_OPTIMIZATION is provided + // Compile-time define SOUNDTOUCH_ALLOW_NONEXACT_SIMD_OPTIMIZATION is provided // for choosing if this little cheating is allowed. -#ifdef ALLOW_NONEXACT_SIMD_OPTIMIZATION - // Little cheating allowed, return valid correlation only for +#ifdef SOUNDTOUCH_ALLOW_NONEXACT_SIMD_OPTIMIZATION + // Little cheating allowed, return valid correlation only for // aligned locations, meaning every second round for stereo sound. #define _MM_LOAD _mm_load_ps - if (((ulong)pV1) & 15) return -1e50; // skip unaligned locations + if (((ulongptr)pV1) & 15) return -1e50; // skip unaligned locations #else // No cheating allowed, use unaligned load & take the resulting // performance hit. #define _MM_LOAD _mm_loadu_ps -#endif +#endif // ensure overlapLength is divisible by 8 assert((overlapLength % 8) == 0); @@ -110,8 +110,9 @@ double TDStretchSSE::calcCrossCorrStereo(const float *pV1, const float *pV2) con pVec2 = (const __m128*)pV2; vSum = vNorm = _mm_setzero_ps(); - // Unroll the loop by factor of 4 * 4 operations - for (i = 0; i < overlapLength / 8; i ++) + // Unroll the loop by factor of 4 * 4 operations. Use same routine for + // stereo & mono, for mono it just means twice the amount of unrolling. + for (i = 0; i < channels * overlapLength / 16; i ++) { __m128 vTemp; // vSum += pV1[0..3] * pV2[0..3] @@ -152,7 +153,7 @@ double TDStretchSSE::calcCrossCorrStereo(const float *pV1, const float *pV2) con // Calculates the cross-correlation value between 'pV1' and 'pV2' vectors corr = norm = 0.0; - for (i = 0; i < overlapLength / 8; i ++) + for (i = 0; i < channels * overlapLength / 16; i ++) { corr += pV1[0] * pV2[0] + pV1[1] * pV2[1] + @@ -171,81 +172,13 @@ double TDStretchSSE::calcCrossCorrStereo(const float *pV1, const float *pV2) con pV1[14] * pV2[14] + pV1[15] * pV2[15]; - for (j = 0; j < 15; j ++) norm += pV1[j] * pV1[j]; + for (j = 0; j < 15; j ++) norm += pV1[j] * pV1[j]; pV1 += 16; pV2 += 16; } return corr / sqrt(norm); */ - - /* This is a bit outdated, corresponding routine in assembler. This may be teeny-weeny bit - faster than intrinsic version, but more difficult to maintain & get compiled on multiple - platforms. - - uint overlapLengthLocal = overlapLength; - float corr; - - _asm - { - // Very important note: data in 'pV2' _must_ be aligned to - // 16-byte boundary! - - // give prefetch hints to CPU of what data are to be needed soonish - // give more aggressive hints on pV1 as that changes while pV2 stays - // same between runs - prefetcht0 [pV1] - prefetcht0 [pV2] - prefetcht0 [pV1 + 32] - - mov eax, dword ptr pV1 - mov ebx, dword ptr pV2 - - xorps xmm0, xmm0 - - mov ecx, overlapLengthLocal - shr ecx, 3 // div by eight - - loop1: - prefetcht0 [eax + 64] // give a prefetch hint to CPU what data are to be needed soonish - prefetcht0 [ebx + 32] // give a prefetch hint to CPU what data are to be needed soonish - movups xmm1, [eax] - mulps xmm1, [ebx] - addps xmm0, xmm1 - - movups xmm2, [eax + 16] - mulps xmm2, [ebx + 16] - addps xmm0, xmm2 - - prefetcht0 [eax + 96] // give a prefetch hint to CPU what data are to be needed soonish - prefetcht0 [ebx + 64] // give a prefetch hint to CPU what data are to be needed soonish - - movups xmm3, [eax + 32] - mulps xmm3, [ebx + 32] - addps xmm0, xmm3 - - movups xmm4, [eax + 48] - mulps xmm4, [ebx + 48] - addps xmm0, xmm4 - - add eax, 64 - add ebx, 64 - - dec ecx - jnz loop1 - - // add the four floats of xmm0 together and return the result. - - movhlps xmm1, xmm0 // move 3 & 4 of xmm0 to 1 & 2 of xmm1 - addps xmm1, xmm0 - movaps xmm2, xmm1 - shufps xmm2, xmm2, 0x01 // move 2 of xmm2 as 1 of xmm2 - addss xmm2, xmm1 - movss corr, xmm2 - } - - return (double)corr; - */ } @@ -281,15 +214,15 @@ void FIRFilterSSE::setCoefficients(const float *coeffs, uint newLength, uint uRe FIRFilter::setCoefficients(coeffs, newLength, uResultDivFactor); // Scale the filter coefficients so that it won't be necessary to scale the filtering result - // also rearrange coefficients suitably for 3DNow! + // also rearrange coefficients suitably for SSE // Ensure that filter coeffs array is aligned to 16-byte boundary delete[] filterCoeffsUnalign; filterCoeffsUnalign = new float[2 * newLength + 4]; - filterCoeffsAlign = (float *)(((unsigned long)filterCoeffsUnalign + 15) & (ulong)-16); + filterCoeffsAlign = (float *)SOUNDTOUCH_ALIGN_POINTER_16(filterCoeffsUnalign); fDivider = (float)resultDivider; - // rearrange the filter coefficients for mmx routines + // rearrange the filter coefficients for mmx routines for (i = 0; i < newLength; i ++) { filterCoeffsAlign[2 * i + 0] = @@ -313,7 +246,7 @@ uint FIRFilterSSE::evaluateFilterStereo(float *dest, const float *source, uint n assert(dest != NULL); assert((length % 8) == 0); assert(filterCoeffsAlign != NULL); - assert(((ulong)filterCoeffsAlign) % 16 == 0); + assert(((ulongptr)filterCoeffsAlign) % 16 == 0); // filter is evaluated for two stereo samples with each iteration, thus use of 'j += 2' for (j = 0; j < count; j += 2) @@ -324,13 +257,13 @@ uint FIRFilterSSE::evaluateFilterStereo(float *dest, const float *source, uint n uint i; pSrc = (const float*)source; // source audio data - pFil = (const __m128*)filterCoeffsAlign; // filter coefficients. NOTE: Assumes coefficients + pFil = (const __m128*)filterCoeffsAlign; // filter coefficients. NOTE: Assumes coefficients // are aligned to 16-byte boundary sum1 = sum2 = _mm_setzero_ps(); - for (i = 0; i < length / 8; i ++) + for (i = 0; i < length / 8; i ++) { - // Unroll loop for efficiency & calculate filter for 2*2 stereo samples + // Unroll loop for efficiency & calculate filter for 2*2 stereo samples // at each pass // sum1 is accu for 2*2 filtered stereo sound data at the primary sound data offset @@ -365,14 +298,14 @@ uint FIRFilterSSE::evaluateFilterStereo(float *dest, const float *source, uint n } // Ideas for further improvement: - // 1. If it could be guaranteed that 'source' were always aligned to 16-byte + // 1. If it could be guaranteed that 'source' were always aligned to 16-byte // boundary, a faster aligned '_mm_load_ps' instruction could be used. - // 2. If it could be guaranteed that 'dest' were always aligned to 16-byte + // 2. If it could be guaranteed that 'dest' were always aligned to 16-byte // boundary, a faster '_mm_store_ps' instruction could be used. return (uint)count; - /* original routine in C-language. please notice the C-version has differently + /* original routine in C-language. please notice the C-version has differently organized coefficients though. double suml1, suml2; double sumr1, sumr2; @@ -387,26 +320,26 @@ uint FIRFilterSSE::evaluateFilterStereo(float *dest, const float *source, uint n suml2 = sumr2 = 0.0; ptr = src; pFil = filterCoeffs; - for (i = 0; i < lengthLocal; i ++) + for (i = 0; i < lengthLocal; i ++) { // unroll loop for efficiency. - suml1 += ptr[0] * pFil[0] + + suml1 += ptr[0] * pFil[0] + ptr[2] * pFil[2] + ptr[4] * pFil[4] + ptr[6] * pFil[6]; - sumr1 += ptr[1] * pFil[1] + + sumr1 += ptr[1] * pFil[1] + ptr[3] * pFil[3] + ptr[5] * pFil[5] + ptr[7] * pFil[7]; - suml2 += ptr[8] * pFil[0] + + suml2 += ptr[8] * pFil[0] + ptr[10] * pFil[2] + ptr[12] * pFil[4] + ptr[14] * pFil[6]; - sumr2 += ptr[9] * pFil[1] + + sumr2 += ptr[9] * pFil[1] + ptr[11] * pFil[3] + ptr[13] * pFil[5] + ptr[15] * pFil[7]; @@ -423,88 +356,6 @@ uint FIRFilterSSE::evaluateFilterStereo(float *dest, const float *source, uint n dest += 4; } */ - - - /* Similar routine in assembly, again obsoleted due to maintainability - _asm - { - // Very important note: data in 'src' _must_ be aligned to - // 16-byte boundary! - mov edx, count - mov ebx, dword ptr src - mov eax, dword ptr dest - shr edx, 1 - - loop1: - // "outer loop" : during each round 2*2 output samples are calculated - - // give prefetch hints to CPU of what data are to be needed soonish - prefetcht0 [ebx] - prefetcht0 [filterCoeffsLocal] - - mov esi, ebx - mov edi, filterCoeffsLocal - xorps xmm0, xmm0 - xorps xmm1, xmm1 - mov ecx, lengthLocal - - loop2: - // "inner loop" : during each round eight FIR filter taps are evaluated for 2*2 samples - prefetcht0 [esi + 32] // give a prefetch hint to CPU what data are to be needed soonish - prefetcht0 [edi + 32] // give a prefetch hint to CPU what data are to be needed soonish - - movups xmm2, [esi] // possibly unaligned load - movups xmm3, [esi + 8] // possibly unaligned load - mulps xmm2, [edi] - mulps xmm3, [edi] - addps xmm0, xmm2 - addps xmm1, xmm3 - - movups xmm4, [esi + 16] // possibly unaligned load - movups xmm5, [esi + 24] // possibly unaligned load - mulps xmm4, [edi + 16] - mulps xmm5, [edi + 16] - addps xmm0, xmm4 - addps xmm1, xmm5 - - prefetcht0 [esi + 64] // give a prefetch hint to CPU what data are to be needed soonish - prefetcht0 [edi + 64] // give a prefetch hint to CPU what data are to be needed soonish - - movups xmm6, [esi + 32] // possibly unaligned load - movups xmm7, [esi + 40] // possibly unaligned load - mulps xmm6, [edi + 32] - mulps xmm7, [edi + 32] - addps xmm0, xmm6 - addps xmm1, xmm7 - - movups xmm4, [esi + 48] // possibly unaligned load - movups xmm5, [esi + 56] // possibly unaligned load - mulps xmm4, [edi + 48] - mulps xmm5, [edi + 48] - addps xmm0, xmm4 - addps xmm1, xmm5 - - add esi, 64 - add edi, 64 - dec ecx - jnz loop2 - - // Now xmm0 and xmm1 both have a filtered 2-channel sample each, but we still need - // to sum the two hi- and lo-floats of these registers together. - - movhlps xmm2, xmm0 // xmm2 = xmm2_3 xmm2_2 xmm0_3 xmm0_2 - movlhps xmm2, xmm1 // xmm2 = xmm1_1 xmm1_0 xmm0_3 xmm0_2 - shufps xmm0, xmm1, 0xe4 // xmm0 = xmm1_3 xmm1_2 xmm0_1 xmm0_0 - addps xmm0, xmm2 - - movaps [eax], xmm0 - add ebx, 16 - add eax, 16 - - dec edx - jnz loop1 - } - */ } -#endif // ALLOW_SSE +#endif // SOUNDTOUCH_ALLOW_SSE diff --git a/3rdparty/w32pthreads/pthreads_lib_vs11.vcxproj b/3rdparty/w32pthreads/pthreads_lib_vs11.vcxproj index 89ee931f32..8ca75a68f3 100644 --- a/3rdparty/w32pthreads/pthreads_lib_vs11.vcxproj +++ b/3rdparty/w32pthreads/pthreads_lib_vs11.vcxproj @@ -641,7 +641,7 @@ - + {26511268-2902-4997-8421-ecd7055f9e28} false diff --git a/3rdparty/winpcap/include/Packet32.h b/3rdparty/winpcap/include/Packet32.h new file mode 100644 index 0000000000..1e0eacd77d --- /dev/null +++ b/3rdparty/winpcap/include/Packet32.h @@ -0,0 +1,359 @@ +/* + * Copyright (c) 1999 - 2005 NetGroup, Politecnico di Torino (Italy) + * Copyright (c) 2005 - 2007 CACE Technologies, Davis (California) + * 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. + * 3. Neither the name of the Politecnico di Torino, CACE Technologies + * 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. + * + */ + +/** @ingroup packetapi + * @{ + */ + +/** @defgroup packet32h Packet.dll definitions and data structures + * Packet32.h contains the data structures and the definitions used by packet.dll. + * The file is used both by the Win9x and the WinNTx versions of packet.dll, and can be included + * by the applications that use the functions of this library + * @{ + */ + +#ifndef __PACKET32 +#define __PACKET32 + +#include + +#ifdef HAVE_AIRPCAP_API +#include +#else +#if !defined(AIRPCAP_HANDLE__EAE405F5_0171_9592_B3C2_C19EC426AD34__DEFINED_) +#define AIRPCAP_HANDLE__EAE405F5_0171_9592_B3C2_C19EC426AD34__DEFINED_ +typedef struct _AirpcapHandle *PAirpcapHandle; +#endif /* AIRPCAP_HANDLE__EAE405F5_0171_9592_B3C2_C19EC426AD34__DEFINED_ */ +#endif /* HAVE_AIRPCAP_API */ + +#ifdef HAVE_DAG_API +#include +#endif /* HAVE_DAG_API */ + +// Working modes +#define PACKET_MODE_CAPT 0x0 ///< Capture mode +#define PACKET_MODE_STAT 0x1 ///< Statistical mode +#define PACKET_MODE_MON 0x2 ///< Monitoring mode +#define PACKET_MODE_DUMP 0x10 ///< Dump mode +#define PACKET_MODE_STAT_DUMP MODE_DUMP | MODE_STAT ///< Statistical dump Mode + + +/// Alignment macro. Defines the alignment size. +#define Packet_ALIGNMENT sizeof(int) +/// Alignment macro. Rounds up to the next even multiple of Packet_ALIGNMENT. +#define Packet_WORDALIGN(x) (((x)+(Packet_ALIGNMENT-1))&~(Packet_ALIGNMENT-1)) + +#define NdisMediumNull -1 ///< Custom linktype: NDIS doesn't provide an equivalent +#define NdisMediumCHDLC -2 ///< Custom linktype: NDIS doesn't provide an equivalent +#define NdisMediumPPPSerial -3 ///< Custom linktype: NDIS doesn't provide an equivalent +#define NdisMediumBare80211 -4 ///< Custom linktype: NDIS doesn't provide an equivalent +#define NdisMediumRadio80211 -5 ///< Custom linktype: NDIS doesn't provide an equivalent +#define NdisMediumPpi -6 ///< Custom linktype: NDIS doesn't provide an equivalent + +// Loopback behaviour definitions +#define NPF_DISABLE_LOOPBACK 1 ///< Drop the packets sent by the NPF driver +#define NPF_ENABLE_LOOPBACK 2 ///< Capture the packets sent by the NPF driver + +/*! + \brief Network type structure. + + This structure is used by the PacketGetNetType() function to return information on the current adapter's type and speed. +*/ +typedef struct NetType +{ + UINT LinkType; ///< The MAC of the current network adapter (see function PacketGetNetType() for more information) + ULONGLONG LinkSpeed; ///< The speed of the network in bits per second +}NetType; + + +//some definitions stolen from libpcap + +#ifndef BPF_MAJOR_VERSION + +/*! + \brief A BPF pseudo-assembly program. + + The program will be injected in the kernel by the PacketSetBPF() function and applied to every incoming packet. +*/ +struct bpf_program +{ + UINT bf_len; ///< Indicates the number of instructions of the program, i.e. the number of struct bpf_insn that will follow. + struct bpf_insn *bf_insns; ///< A pointer to the first instruction of the program. +}; + +/*! + \brief A single BPF pseudo-instruction. + + bpf_insn contains a single instruction for the BPF register-machine. It is used to send a filter program to the driver. +*/ +struct bpf_insn +{ + USHORT code; ///< Instruction type and addressing mode. + UCHAR jt; ///< Jump if true + UCHAR jf; ///< Jump if false + int k; ///< Generic field used for various purposes. +}; + +/*! + \brief Structure that contains a couple of statistics values on the current capture. + + It is used by packet.dll to return statistics about a capture session. +*/ +struct bpf_stat +{ + UINT bs_recv; ///< Number of packets that the driver received from the network adapter + ///< from the beginning of the current capture. This value includes the packets + ///< lost by the driver. + UINT bs_drop; ///< number of packets that the driver lost from the beginning of a capture. + ///< Basically, a packet is lost when the the buffer of the driver is full. + ///< In this situation the packet cannot be stored and the driver rejects it. + UINT ps_ifdrop; ///< drops by interface. XXX not yet supported + UINT bs_capt; ///< number of packets that pass the filter, find place in the kernel buffer and + ///< thus reach the application. +}; + +/*! + \brief Packet header. + + This structure defines the header associated with every packet delivered to the application. +*/ +struct bpf_hdr +{ + struct timeval bh_tstamp; ///< The timestamp associated with the captured packet. + ///< It is stored in a TimeVal structure. + UINT bh_caplen; ///< Length of captured portion. The captured portion can be different + ///< from the original packet, because it is possible (with a proper filter) + ///< to instruct the driver to capture only a portion of the packets. + UINT bh_datalen; ///< Original length of packet + USHORT bh_hdrlen; ///< Length of bpf header (this struct plus alignment padding). In some cases, + ///< a padding could be added between the end of this structure and the packet + ///< data for performance reasons. This filed can be used to retrieve the actual data + ///< of the packet. +}; + +/*! + \brief Dump packet header. + + This structure defines the header associated with the packets in a buffer to be used with PacketSendPackets(). + It is simpler than the bpf_hdr, because it corresponds to the header associated by WinPcap and libpcap to a + packet in a dump file. This makes straightforward sending WinPcap dump files to the network. +*/ +struct dump_bpf_hdr{ + struct timeval ts; ///< Time stamp of the packet + UINT caplen; ///< Length of captured portion. The captured portion can smaller than the + ///< the original packet, because it is possible (with a proper filter) to + ///< instruct the driver to capture only a portion of the packets. + UINT len; ///< Length of the original packet (off wire). +}; + + +#endif + +struct bpf_stat; + +#define DOSNAMEPREFIX TEXT("Packet_") ///< Prefix added to the adapters device names to create the WinPcap devices +#define MAX_LINK_NAME_LENGTH 64 //< Maximum length of the devices symbolic links +#define NMAX_PACKET 65535 + +/*! + \brief Addresses of a network adapter. + + This structure is used by the PacketGetNetInfoEx() function to return the IP addresses associated with + an adapter. +*/ +typedef struct npf_if_addr { + struct sockaddr_storage IPAddress; ///< IP address. + struct sockaddr_storage SubnetMask; ///< Netmask for that address. + struct sockaddr_storage Broadcast; ///< Broadcast address. +}npf_if_addr; + + +#define ADAPTER_NAME_LENGTH 256 + 12 ///< Maximum length for the name of an adapter. The value is the same used by the IP Helper API. +#define ADAPTER_DESC_LENGTH 128 ///< Maximum length for the description of an adapter. The value is the same used by the IP Helper API. +#define MAX_MAC_ADDR_LENGTH 8 ///< Maximum length for the link layer address of an adapter. The value is the same used by the IP Helper API. +#define MAX_NETWORK_ADDRESSES 16 ///< Maximum length for the link layer address of an adapter. The value is the same used by the IP Helper API. + + +typedef struct WAN_ADAPTER_INT WAN_ADAPTER; ///< Describes an opened wan (dialup, VPN...) network adapter using the NetMon API +typedef WAN_ADAPTER *PWAN_ADAPTER; ///< Describes an opened wan (dialup, VPN...) network adapter using the NetMon API + +#define INFO_FLAG_NDIS_ADAPTER 0 ///< Flag for ADAPTER_INFO: this is a traditional ndis adapter +#define INFO_FLAG_NDISWAN_ADAPTER 1 ///< Flag for ADAPTER_INFO: this is a NdisWan adapter, and it's managed by WANPACKET +#define INFO_FLAG_DAG_CARD 2 ///< Flag for ADAPTER_INFO: this is a DAG card +#define INFO_FLAG_DAG_FILE 6 ///< Flag for ADAPTER_INFO: this is a DAG file +#define INFO_FLAG_DONT_EXPORT 8 ///< Flag for ADAPTER_INFO: when this flag is set, the adapter will not be listed or openend by winpcap. This allows to prevent exporting broken network adapters, like for example FireWire ones. +#define INFO_FLAG_AIRPCAP_CARD 16 ///< Flag for ADAPTER_INFO: this is an airpcap card +#define INFO_FLAG_NPFIM_DEVICE 32 + +/*! + \brief Describes an opened network adapter. + + This structure is the most important for the functioning of packet.dll, but the great part of its fields + should be ignored by the user, since the library offers functions that avoid to cope with low-level parameters +*/ +typedef struct _ADAPTER { + HANDLE hFile; ///< \internal Handle to an open instance of the NPF driver. + CHAR SymbolicLink[MAX_LINK_NAME_LENGTH]; ///< \internal A string containing the name of the network adapter currently opened. + int NumWrites; ///< \internal Number of times a packets written on this adapter will be repeated + ///< on the wire. + HANDLE ReadEvent; ///< A notification event associated with the read calls on the adapter. + ///< It can be passed to standard Win32 functions (like WaitForSingleObject + ///< or WaitForMultipleObjects) to wait until the driver's buffer contains some + ///< data. It is particularly useful in GUI applications that need to wait + ///< concurrently on several events. In Windows NT/2000 the PacketSetMinToCopy() + ///< function can be used to define the minimum amount of data in the kernel buffer + ///< that will cause the event to be signalled. + + UINT ReadTimeOut; ///< \internal The amount of time after which a read on the driver will be released and + ///< ReadEvent will be signaled, also if no packets were captured + CHAR Name[ADAPTER_NAME_LENGTH]; + PWAN_ADAPTER pWanAdapter; + UINT Flags; ///< Adapter's flags. Tell if this adapter must be treated in a different way, using the Netmon API or the dagc API. + +#ifdef HAVE_AIRPCAP_API + PAirpcapHandle AirpcapAd; +#endif // HAVE_AIRPCAP_API + +#ifdef HAVE_NPFIM_API + void* NpfImHandle; +#endif // HAVE_NPFIM_API + +#ifdef HAVE_DAG_API + dagc_t *pDagCard; ///< Pointer to the dagc API adapter descriptor for this adapter + PCHAR DagBuffer; ///< Pointer to the buffer with the packets that is received from the DAG card + struct timeval DagReadTimeout; ///< Read timeout. The dagc API requires a timeval structure + unsigned DagFcsLen; ///< Length of the frame check sequence attached to any packet by the card. Obtained from the registry + DWORD DagFastProcess; ///< True if the user requests fast capture processing on this card. Higher level applications can use this value to provide a faster but possibly unprecise capture (for example, libpcap doesn't convert the timestamps). +#endif // HAVE_DAG_API +} ADAPTER, *LPADAPTER; + +/*! + \brief Structure that contains a group of packets coming from the driver. + + This structure defines the header associated with every packet delivered to the application. +*/ +typedef struct _PACKET { + HANDLE hEvent; ///< \deprecated Still present for compatibility with old applications. + OVERLAPPED OverLapped; ///< \deprecated Still present for compatibility with old applications. + PVOID Buffer; ///< Buffer with containing the packets. See the PacketReceivePacket() for + ///< details about the organization of the data in this buffer + UINT Length; ///< Length of the buffer + DWORD ulBytesReceived; ///< Number of valid bytes present in the buffer, i.e. amount of data + ///< received by the last call to PacketReceivePacket() + BOOLEAN bIoComplete; ///< \deprecated Still present for compatibility with old applications. +} PACKET, *LPPACKET; + +/*! + \brief Structure containing an OID request. + + It is used by the PacketRequest() function to send an OID to the interface card driver. + It can be used, for example, to retrieve the status of the error counters on the adapter, its MAC address, + the list of the multicast groups defined on it, and so on. +*/ +struct _PACKET_OID_DATA { + ULONG Oid; ///< OID code. See the Microsoft DDK documentation or the file ntddndis.h + ///< for a complete list of valid codes. + ULONG Length; ///< Length of the data field + UCHAR Data[1]; ///< variable-lenght field that contains the information passed to or received + ///< from the adapter. +}; +typedef struct _PACKET_OID_DATA PACKET_OID_DATA, *PPACKET_OID_DATA; + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @} + */ + +/* +BOOLEAN QueryWinPcapRegistryStringA(CHAR *SubKeyName, + CHAR *Value, + UINT *pValueLen, + CHAR *DefaultVal); + +BOOLEAN QueryWinPcapRegistryStringW(WCHAR *SubKeyName, + WCHAR *Value, + UINT *pValueLen, + WCHAR *DefaultVal); +*/ + +//--------------------------------------------------------------------------- +// EXPORTED FUNCTIONS +//--------------------------------------------------------------------------- + +PCHAR PacketGetVersion(); +PCHAR PacketGetDriverVersion(); +BOOLEAN PacketSetMinToCopy(LPADAPTER AdapterObject,int nbytes); +BOOLEAN PacketSetNumWrites(LPADAPTER AdapterObject,int nwrites); +BOOLEAN PacketSetMode(LPADAPTER AdapterObject,int mode); +BOOLEAN PacketSetReadTimeout(LPADAPTER AdapterObject,int timeout); +BOOLEAN PacketSetBpf(LPADAPTER AdapterObject,struct bpf_program *fp); +BOOLEAN PacketSetLoopbackBehavior(LPADAPTER AdapterObject, UINT LoopbackBehavior); +INT PacketSetSnapLen(LPADAPTER AdapterObject,int snaplen); +BOOLEAN PacketGetStats(LPADAPTER AdapterObject,struct bpf_stat *s); +BOOLEAN PacketGetStatsEx(LPADAPTER AdapterObject,struct bpf_stat *s); +BOOLEAN PacketSetBuff(LPADAPTER AdapterObject,int dim); +BOOLEAN PacketGetNetType (LPADAPTER AdapterObject,NetType *type); +LPADAPTER PacketOpenAdapter(PCHAR AdapterName); +BOOLEAN PacketSendPacket(LPADAPTER AdapterObject,LPPACKET pPacket,BOOLEAN Sync); +INT PacketSendPackets(LPADAPTER AdapterObject,PVOID PacketBuff,ULONG Size, BOOLEAN Sync); +LPPACKET PacketAllocatePacket(void); +VOID PacketInitPacket(LPPACKET lpPacket,PVOID Buffer,UINT Length); +VOID PacketFreePacket(LPPACKET lpPacket); +BOOLEAN PacketReceivePacket(LPADAPTER AdapterObject,LPPACKET lpPacket,BOOLEAN Sync); +BOOLEAN PacketSetHwFilter(LPADAPTER AdapterObject,ULONG Filter); +BOOLEAN PacketGetAdapterNames(PTSTR pStr,PULONG BufferSize); +BOOLEAN PacketGetNetInfoEx(PCHAR AdapterName, npf_if_addr* buffer, PLONG NEntries); +BOOLEAN PacketRequest(LPADAPTER AdapterObject,BOOLEAN Set,PPACKET_OID_DATA OidData); +HANDLE PacketGetReadEvent(LPADAPTER AdapterObject); +BOOLEAN PacketSetDumpName(LPADAPTER AdapterObject, void *name, int len); +BOOLEAN PacketSetDumpLimits(LPADAPTER AdapterObject, UINT maxfilesize, UINT maxnpacks); +BOOLEAN PacketIsDumpEnded(LPADAPTER AdapterObject, BOOLEAN sync); +BOOL PacketStopDriver(); +VOID PacketCloseAdapter(LPADAPTER lpAdapter); +BOOLEAN PacketStartOem(PCHAR errorString, UINT errorStringLength); +BOOLEAN PacketStartOemEx(PCHAR errorString, UINT errorStringLength, ULONG flags); +PAirpcapHandle PacketGetAirPcapHandle(LPADAPTER AdapterObject); + +// +// Used by PacketStartOemEx +// +#define PACKET_START_OEM_NO_NETMON 0x00000001 + +#ifdef __cplusplus +} +#endif + +#endif //__PACKET32 diff --git a/3rdparty/winpcap/include/Win32-Extensions.h b/3rdparty/winpcap/include/Win32-Extensions.h new file mode 100644 index 0000000000..d3b063b0fd --- /dev/null +++ b/3rdparty/winpcap/include/Win32-Extensions.h @@ -0,0 +1,113 @@ +/* + * Copyright (c) 1999 - 2005 NetGroup, Politecnico di Torino (Italy) + * Copyright (c) 2005 - 2006 CACE Technologies, Davis (California) + * 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. + * 3. Neither the name of the Politecnico di Torino, CACE Technologies + * nor the names of its contributors may be used to endorse or promote + * products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#ifndef __WIN32_EXTENSIONS_H__ +#define __WIN32_EXTENSIONS_H__ + +#ifdef __cplusplus +extern "C" { +#endif + +/* Definitions */ + +/*! + \brief A queue of raw packets that will be sent to the network with pcap_sendqueue_transmit(). +*/ +struct pcap_send_queue +{ + u_int maxlen; ///< Maximum size of the the queue, in bytes. This variable contains the size of the buffer field. + u_int len; ///< Current size of the queue, in bytes. + char *buffer; ///< Buffer containing the packets to be sent. +}; + +typedef struct pcap_send_queue pcap_send_queue; + +/*! + \brief This typedef is a support for the pcap_get_airpcap_handle() function +*/ +#if !defined(AIRPCAP_HANDLE__EAE405F5_0171_9592_B3C2_C19EC426AD34__DEFINED_) +#define AIRPCAP_HANDLE__EAE405F5_0171_9592_B3C2_C19EC426AD34__DEFINED_ +typedef struct _AirpcapHandle *PAirpcapHandle; +#endif + +#define BPF_MEM_EX_IMM 0xc0 +#define BPF_MEM_EX_IND 0xe0 + +/*used for ST*/ +#define BPF_MEM_EX 0xc0 +#define BPF_TME 0x08 + +#define BPF_LOOKUP 0x90 +#define BPF_EXECUTE 0xa0 +#define BPF_INIT 0xb0 +#define BPF_VALIDATE 0xc0 +#define BPF_SET_ACTIVE 0xd0 +#define BPF_RESET 0xe0 +#define BPF_SET_MEMORY 0x80 +#define BPF_GET_REGISTER_VALUE 0x70 +#define BPF_SET_REGISTER_VALUE 0x60 +#define BPF_SET_WORKING 0x50 +#define BPF_SET_ACTIVE_READ 0x40 +#define BPF_SET_AUTODELETION 0x30 +#define BPF_SEPARATION 0xff + +/* Prototypes */ +pcap_send_queue* pcap_sendqueue_alloc(u_int memsize); + +void pcap_sendqueue_destroy(pcap_send_queue* queue); + +int pcap_sendqueue_queue(pcap_send_queue* queue, const struct pcap_pkthdr *pkt_header, const u_char *pkt_data); + +u_int pcap_sendqueue_transmit(pcap_t *p, pcap_send_queue* queue, int sync); + +HANDLE pcap_getevent(pcap_t *p); + +struct pcap_stat *pcap_stats_ex(pcap_t *p, int *pcap_stat_size); + +int pcap_setuserbuffer(pcap_t *p, int size); + +int pcap_live_dump(pcap_t *p, char *filename, int maxsize, int maxpacks); + +int pcap_live_dump_ended(pcap_t *p, int sync); + +int pcap_offline_filter(struct bpf_program *prog, const struct pcap_pkthdr *header, const u_char *pkt_data); + +int pcap_start_oem(char* err_str, int flags); + +PAirpcapHandle pcap_get_airpcap_handle(pcap_t *p); + +#ifdef __cplusplus +} +#endif + +#endif //__WIN32_EXTENSIONS_H__ diff --git a/3rdparty/winpcap/include/bittypes.h b/3rdparty/winpcap/include/bittypes.h new file mode 100644 index 0000000000..558a0b5c0d --- /dev/null +++ b/3rdparty/winpcap/include/bittypes.h @@ -0,0 +1,137 @@ +/* + * Copyright (C) 1999 WIDE Project. + * 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. + * 3. Neither the name of the 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 PROJECT 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 PROJECT 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 _BITTYPES_H +#define _BITTYPES_H + +#ifndef HAVE_U_INT8_T + +#if SIZEOF_CHAR == 1 +typedef unsigned char u_int8_t; +typedef signed char int8_t; +#elif SIZEOF_INT == 1 +typedef unsigned int u_int8_t; +typedef signed int int8_t; +#else /* XXX */ +#error "there's no appropriate type for u_int8_t" +#endif +#define HAVE_U_INT8_T 1 +#define HAVE_INT8_T 1 + +#endif /* HAVE_U_INT8_T */ + +#ifndef HAVE_U_INT16_T + +#if SIZEOF_SHORT == 2 +typedef unsigned short u_int16_t; +typedef signed short int16_t; +#elif SIZEOF_INT == 2 +typedef unsigned int u_int16_t; +typedef signed int int16_t; +#elif SIZEOF_CHAR == 2 +typedef unsigned char u_int16_t; +typedef signed char int16_t; +#else /* XXX */ +#error "there's no appropriate type for u_int16_t" +#endif +#define HAVE_U_INT16_T 1 +#define HAVE_INT16_T 1 + +#endif /* HAVE_U_INT16_T */ + +#ifndef HAVE_U_INT32_T + +#if SIZEOF_INT == 4 +typedef unsigned int u_int32_t; +typedef signed int int32_t; +#elif SIZEOF_LONG == 4 +typedef unsigned long u_int32_t; +typedef signed long int32_t; +#elif SIZEOF_SHORT == 4 +typedef unsigned short u_int32_t; +typedef signed short int32_t; +#else /* XXX */ +#error "there's no appropriate type for u_int32_t" +#endif +#define HAVE_U_INT32_T 1 +#define HAVE_INT32_T 1 + +#endif /* HAVE_U_INT32_T */ + +#ifndef HAVE_U_INT64_T +#if SIZEOF_LONG_LONG == 8 +typedef unsigned long long u_int64_t; +typedef long long int64_t; +#elif defined(_MSC_EXTENSIONS) +typedef unsigned _int64 u_int64_t; +typedef _int64 int64_t; +#elif SIZEOF_INT == 8 +typedef unsigned int u_int64_t; +#elif SIZEOF_LONG == 8 +typedef unsigned long u_int64_t; +#elif SIZEOF_SHORT == 8 +typedef unsigned short u_int64_t; +#else /* XXX */ +#error "there's no appropriate type for u_int64_t" +#endif + +#endif /* HAVE_U_INT64_T */ + +#ifndef PRId64 +#ifdef _MSC_EXTENSIONS +#define PRId64 "I64d" +#else /* _MSC_EXTENSIONS */ +#define PRId64 "lld" +#endif /* _MSC_EXTENSIONS */ +#endif /* PRId64 */ + +#ifndef PRIo64 +#ifdef _MSC_EXTENSIONS +#define PRIo64 "I64o" +#else /* _MSC_EXTENSIONS */ +#define PRIo64 "llo" +#endif /* _MSC_EXTENSIONS */ +#endif /* PRIo64 */ + +#ifndef PRIx64 +#ifdef _MSC_EXTENSIONS +#define PRIx64 "I64x" +#else /* _MSC_EXTENSIONS */ +#define PRIx64 "llx" +#endif /* _MSC_EXTENSIONS */ +#endif /* PRIx64 */ + +#ifndef PRIu64 +#ifdef _MSC_EXTENSIONS +#define PRIu64 "I64u" +#else /* _MSC_EXTENSIONS */ +#define PRIu64 "llu" +#endif /* _MSC_EXTENSIONS */ +#endif /* PRIu64 */ + +#endif /* _BITTYPES_H */ diff --git a/3rdparty/winpcap/include/ip6_misc.h b/3rdparty/winpcap/include/ip6_misc.h new file mode 100644 index 0000000000..562fa6184e --- /dev/null +++ b/3rdparty/winpcap/include/ip6_misc.h @@ -0,0 +1,163 @@ +/* + * Copyright (c) 1993, 1994, 1997 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that: (1) source code distributions + * retain the above copyright notice and this paragraph in its entirety, (2) + * distributions including binary code include the above copyright notice and + * this paragraph in its entirety in the documentation or other materials + * provided with the distribution, and (3) all advertising materials mentioning + * features or use of this software display the following acknowledgement: + * ``This product includes software developed by the University of California, + * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of + * the University 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 ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. + * + * @(#) $Header: /tcpdump/master/libpcap/Win32/Include/ip6_misc.h,v 1.5 2006-01-22 18:02:18 gianluca Exp $ (LBL) + */ + +/* + * This file contains a collage of declarations for IPv6 from FreeBSD not present in Windows + */ + +#include + +#include + +#ifndef __MINGW32__ +#define IN_MULTICAST(a) IN_CLASSD(a) +#endif + +#define IN_EXPERIMENTAL(a) ((((u_int32_t) (a)) & 0xf0000000) == 0xf0000000) + +#define IN_LOOPBACKNET 127 + +#if defined(__MINGW32__) && defined(DEFINE_ADDITIONAL_IPV6_STUFF) +/* IPv6 address */ +struct in6_addr + { + union + { + u_int8_t u6_addr8[16]; + u_int16_t u6_addr16[8]; + u_int32_t u6_addr32[4]; + } in6_u; +#define s6_addr in6_u.u6_addr8 +#define s6_addr16 in6_u.u6_addr16 +#define s6_addr32 in6_u.u6_addr32 +#define s6_addr64 in6_u.u6_addr64 + }; + +#define IN6ADDR_ANY_INIT { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } +#define IN6ADDR_LOOPBACK_INIT { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1 } +#endif /* __MINGW32__ */ + + +#if (defined _MSC_VER) || (defined(__MINGW32__) && defined(DEFINE_ADDITIONAL_IPV6_STUFF)) +typedef unsigned short sa_family_t; +#endif + + +#if defined(__MINGW32__) && defined(DEFINE_ADDITIONAL_IPV6_STUFF) + +#define __SOCKADDR_COMMON(sa_prefix) \ + sa_family_t sa_prefix##family + +/* Ditto, for IPv6. */ +struct sockaddr_in6 + { + __SOCKADDR_COMMON (sin6_); + u_int16_t sin6_port; /* Transport layer port # */ + u_int32_t sin6_flowinfo; /* IPv6 flow information */ + struct in6_addr sin6_addr; /* IPv6 address */ + }; + +#define IN6_IS_ADDR_V4MAPPED(a) \ + ((((u_int32_t *) (a))[0] == 0) && (((u_int32_t *) (a))[1] == 0) && \ + (((u_int32_t *) (a))[2] == htonl (0xffff))) + +#define IN6_IS_ADDR_MULTICAST(a) (((u_int8_t *) (a))[0] == 0xff) + +#define IN6_IS_ADDR_LINKLOCAL(a) \ + ((((u_int32_t *) (a))[0] & htonl (0xffc00000)) == htonl (0xfe800000)) + +#define IN6_IS_ADDR_LOOPBACK(a) \ + (((u_int32_t *) (a))[0] == 0 && ((u_int32_t *) (a))[1] == 0 && \ + ((u_int32_t *) (a))[2] == 0 && ((u_int32_t *) (a))[3] == htonl (1)) +#endif /* __MINGW32__ */ + +#define ip6_vfc ip6_ctlun.ip6_un2_vfc +#define ip6_flow ip6_ctlun.ip6_un1.ip6_un1_flow +#define ip6_plen ip6_ctlun.ip6_un1.ip6_un1_plen +#define ip6_nxt ip6_ctlun.ip6_un1.ip6_un1_nxt +#define ip6_hlim ip6_ctlun.ip6_un1.ip6_un1_hlim +#define ip6_hops ip6_ctlun.ip6_un1.ip6_un1_hlim + +#define nd_rd_type nd_rd_hdr.icmp6_type +#define nd_rd_code nd_rd_hdr.icmp6_code +#define nd_rd_cksum nd_rd_hdr.icmp6_cksum +#define nd_rd_reserved nd_rd_hdr.icmp6_data32[0] + +/* + * IPV6 extension headers + */ +#define IPPROTO_HOPOPTS 0 /* IPv6 hop-by-hop options */ +#define IPPROTO_IPV6 41 /* IPv6 header. */ +#define IPPROTO_ROUTING 43 /* IPv6 routing header */ +#define IPPROTO_FRAGMENT 44 /* IPv6 fragmentation header */ +#define IPPROTO_ESP 50 /* encapsulating security payload */ +#define IPPROTO_AH 51 /* authentication header */ +#define IPPROTO_ICMPV6 58 /* ICMPv6 */ +#define IPPROTO_NONE 59 /* IPv6 no next header */ +#define IPPROTO_DSTOPTS 60 /* IPv6 destination options */ +#define IPPROTO_PIM 103 /* Protocol Independent Multicast. */ + +#define IPV6_RTHDR_TYPE_0 0 + +/* Option types and related macros */ +#define IP6OPT_PAD1 0x00 /* 00 0 00000 */ +#define IP6OPT_PADN 0x01 /* 00 0 00001 */ +#define IP6OPT_JUMBO 0xC2 /* 11 0 00010 = 194 */ +#define IP6OPT_JUMBO_LEN 6 +#define IP6OPT_ROUTER_ALERT 0x05 /* 00 0 00101 */ + +#define IP6OPT_RTALERT_LEN 4 +#define IP6OPT_RTALERT_MLD 0 /* Datagram contains an MLD message */ +#define IP6OPT_RTALERT_RSVP 1 /* Datagram contains an RSVP message */ +#define IP6OPT_RTALERT_ACTNET 2 /* contains an Active Networks msg */ +#define IP6OPT_MINLEN 2 + +#define IP6OPT_BINDING_UPDATE 0xc6 /* 11 0 00110 */ +#define IP6OPT_BINDING_ACK 0x07 /* 00 0 00111 */ +#define IP6OPT_BINDING_REQ 0x08 /* 00 0 01000 */ +#define IP6OPT_HOME_ADDRESS 0xc9 /* 11 0 01001 */ +#define IP6OPT_EID 0x8a /* 10 0 01010 */ + +#define IP6OPT_TYPE(o) ((o) & 0xC0) +#define IP6OPT_TYPE_SKIP 0x00 +#define IP6OPT_TYPE_DISCARD 0x40 +#define IP6OPT_TYPE_FORCEICMP 0x80 +#define IP6OPT_TYPE_ICMP 0xC0 + +#define IP6OPT_MUTABLE 0x20 + + +#if defined(__MINGW32__) && defined(DEFINE_ADDITIONAL_IPV6_STUFF) +#ifndef EAI_ADDRFAMILY +struct addrinfo { + int ai_flags; /* AI_PASSIVE, AI_CANONNAME */ + int ai_family; /* PF_xxx */ + int ai_socktype; /* SOCK_xxx */ + int ai_protocol; /* 0 or IPPROTO_xxx for IPv4 and IPv6 */ + size_t ai_addrlen; /* length of ai_addr */ + char *ai_canonname; /* canonical name for hostname */ + struct sockaddr *ai_addr; /* binary address */ + struct addrinfo *ai_next; /* next structure in linked list */ +}; +#endif +#endif /* __MINGW32__ */ diff --git a/3rdparty/winpcap/include/pcap-bpf.h b/3rdparty/winpcap/include/pcap-bpf.h new file mode 100644 index 0000000000..5fe129dbb4 --- /dev/null +++ b/3rdparty/winpcap/include/pcap-bpf.h @@ -0,0 +1,47 @@ +/*- + * Copyright (c) 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from the Stanford/CMU enet packet filter, + * (net/enet.c) distributed as part of 4.3BSD, and code contributed + * to Berkeley by Steven McCanne and Van Jacobson both of Lawrence + * Berkeley Laboratory. + * + * 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. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University 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 REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#) $Header: /tcpdump/master/libpcap/pcap-bpf.h,v 1.50 2007/04/01 21:43:55 guy Exp $ (LBL) + */ + +/* + * For backwards compatibility. + * + * Note to OS vendors: do NOT get rid of this file! Some applications + * might expect to be able to include . + */ +#include diff --git a/3rdparty/winpcap/include/pcap-namedb.h b/3rdparty/winpcap/include/pcap-namedb.h new file mode 100644 index 0000000000..80a2f00401 --- /dev/null +++ b/3rdparty/winpcap/include/pcap-namedb.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 1994, 1996 + * The Regents of the University of California. 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. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the Computer Systems + * Engineering Group at Lawrence Berkeley Laboratory. + * 4. Neither the name of the University nor of the Laboratory may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#) $Header: /tcpdump/master/libpcap/pcap-namedb.h,v 1.13 2006/10/04 18:13:32 guy Exp $ (LBL) + */ + +/* + * For backwards compatibility. + * + * Note to OS vendors: do NOT get rid of this file! Some applications + * might expect to be able to include . + */ +#include diff --git a/3rdparty/winpcap/include/pcap-stdinc.h b/3rdparty/winpcap/include/pcap-stdinc.h new file mode 100644 index 0000000000..6170a2344f --- /dev/null +++ b/3rdparty/winpcap/include/pcap-stdinc.h @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2002 - 2005 NetGroup, Politecnico di Torino (Italy) + * Copyright (c) 2005 - 2009 CACE Technologies, Inc. Davis (California) + * 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. + * 3. Neither the name of the Politecnico di Torino 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. + * + * @(#) $Header: /tcpdump/master/libpcap/pcap-stdinc.h,v 1.10.2.1 2008-10-06 15:38:39 gianluca Exp $ (LBL) + */ + +#define SIZEOF_CHAR 1 +#define SIZEOF_SHORT 2 +#define SIZEOF_INT 4 +#ifndef _MSC_EXTENSIONS +#define SIZEOF_LONG_LONG 8 +#endif + +/* + * Avoids a compiler warning in case this was already defined + * (someone defined _WINSOCKAPI_ when including 'windows.h', in order + * to prevent it from including 'winsock.h') + */ +#ifdef _WINSOCKAPI_ +#undef _WINSOCKAPI_ +#endif +#include + +#include + +#include "bittypes.h" +#include +#include + +#ifndef __MINGW32__ +#include "IP6_misc.h" +#endif + +#define caddr_t char* + +#if _MSC_VER < 1500 +#define snprintf _snprintf +#define vsnprintf _vsnprintf +#define strdup _strdup +#endif + +// PCSX2 note: MSVC2012 error with DEV9ghzdrk because of a macro redefinition here +//#define inline __inline + +#ifdef __MINGW32__ +#include +#else /*__MINGW32__*/ +/* MSVC compiler */ +#ifndef _UINTPTR_T_DEFINED +#ifdef _WIN64 +typedef unsigned __int64 uintptr_t; +#else +typedef _W64 unsigned int uintptr_t; +#endif +#define _UINTPTR_T_DEFINED +#endif + +#ifndef _INTPTR_T_DEFINED +#ifdef _WIN64 +typedef __int64 intptr_t; +#else +typedef _W64 int intptr_t; +#endif +#define _INTPTR_T_DEFINED +#endif + +#endif /*__MINGW32__*/ diff --git a/3rdparty/winpcap/include/pcap.h b/3rdparty/winpcap/include/pcap.h new file mode 100644 index 0000000000..935f9494c1 --- /dev/null +++ b/3rdparty/winpcap/include/pcap.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 1993, 1994, 1995, 1996, 1997 + * The Regents of the University of California. 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. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the Computer Systems + * Engineering Group at Lawrence Berkeley Laboratory. + * 4. Neither the name of the University nor of the Laboratory may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#) $Header: /tcpdump/master/libpcap/pcap.h,v 1.59 2006/10/04 18:09:22 guy Exp $ (LBL) + */ + +/* + * For backwards compatibility. + * + * Note to OS vendors: do NOT get rid of this file! Many applications + * expect to be able to include , and at least some of them + * go through contortions in their configure scripts to try to detect + * OSes that have "helpfully" moved pcap.h to without + * leaving behind a file. + */ +#include diff --git a/3rdparty/winpcap/include/pcap/bluetooth.h b/3rdparty/winpcap/include/pcap/bluetooth.h new file mode 100644 index 0000000000..7bf65df034 --- /dev/null +++ b/3rdparty/winpcap/include/pcap/bluetooth.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2006 Paolo Abeni (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. + * 3. The name of the author may not be used to endorse or promote + * products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE 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. + * + * bluetooth data struct + * By Paolo Abeni + * + * @(#) $Header: /tcpdump/master/libpcap/pcap/bluetooth.h,v 1.1 2007/09/22 02:10:17 guy Exp $ + */ + +#ifndef _PCAP_BLUETOOTH_STRUCTS_H__ +#define _PCAP_BLUETOOTH_STRUCTS_H__ + +/* + * Header prepended libpcap to each bluetooth h:4 frame. + * fields are in network byte order + */ +typedef struct _pcap_bluetooth_h4_header { + u_int32_t direction; /* if first bit is set direction is incoming */ +} pcap_bluetooth_h4_header; + + +#endif diff --git a/3rdparty/winpcap/include/pcap/bpf.h b/3rdparty/winpcap/include/pcap/bpf.h new file mode 100644 index 0000000000..9f4ca33e35 --- /dev/null +++ b/3rdparty/winpcap/include/pcap/bpf.h @@ -0,0 +1,934 @@ +/*- + * Copyright (c) 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from the Stanford/CMU enet packet filter, + * (net/enet.c) distributed as part of 4.3BSD, and code contributed + * to Berkeley by Steven McCanne and Van Jacobson both of Lawrence + * Berkeley Laboratory. + * + * 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. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University 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 REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#)bpf.h 7.1 (Berkeley) 5/7/91 + * + * @(#) $Header: /tcpdump/master/libpcap/pcap/bpf.h,v 1.19.2.8 2008-09-22 20:16:01 guy Exp $ (LBL) + */ + +/* + * This is libpcap's cut-down version of bpf.h; it includes only + * the stuff needed for the code generator and the userland BPF + * interpreter, and the libpcap APIs for setting filters, etc.. + * + * "pcap-bpf.c" will include the native OS version, as it deals with + * the OS's BPF implementation. + * + * XXX - should this all just be moved to "pcap.h"? + */ + +#ifndef BPF_MAJOR_VERSION + +#ifdef __cplusplus +extern "C" { +#endif + +/* BSD style release date */ +#define BPF_RELEASE 199606 + +#ifdef MSDOS /* must be 32-bit */ +typedef long bpf_int32; +typedef unsigned long bpf_u_int32; +#else +typedef int bpf_int32; +typedef u_int bpf_u_int32; +#endif + +/* + * Alignment macros. BPF_WORDALIGN rounds up to the next + * even multiple of BPF_ALIGNMENT. + */ +#ifndef __NetBSD__ +#define BPF_ALIGNMENT sizeof(bpf_int32) +#else +#define BPF_ALIGNMENT sizeof(long) +#endif +#define BPF_WORDALIGN(x) (((x)+(BPF_ALIGNMENT-1))&~(BPF_ALIGNMENT-1)) + +#define BPF_MAXBUFSIZE 0x8000 +#define BPF_MINBUFSIZE 32 + +/* + * Structure for "pcap_compile()", "pcap_setfilter()", etc.. + */ +struct bpf_program { + u_int bf_len; + struct bpf_insn *bf_insns; +}; + +/* + * Struct return by BIOCVERSION. This represents the version number of + * the filter language described by the instruction encodings below. + * bpf understands a program iff kernel_major == filter_major && + * kernel_minor >= filter_minor, that is, if the value returned by the + * running kernel has the same major number and a minor number equal + * equal to or less than the filter being downloaded. Otherwise, the + * results are undefined, meaning an error may be returned or packets + * may be accepted haphazardly. + * It has nothing to do with the source code version. + */ +struct bpf_version { + u_short bv_major; + u_short bv_minor; +}; +/* Current version number of filter architecture. */ +#define BPF_MAJOR_VERSION 1 +#define BPF_MINOR_VERSION 1 + +/* + * Data-link level type codes. + * + * Do *NOT* add new values to this list without asking + * "tcpdump-workers@lists.tcpdump.org" for a value. Otherwise, you run + * the risk of using a value that's already being used for some other + * purpose, and of having tools that read libpcap-format captures not + * being able to handle captures with your new DLT_ value, with no hope + * that they will ever be changed to do so (as that would destroy their + * ability to read captures using that value for that other purpose). + */ + +/* + * These are the types that are the same on all platforms, and that + * have been defined by for ages. + */ +#define DLT_NULL 0 /* BSD loopback encapsulation */ +#define DLT_EN10MB 1 /* Ethernet (10Mb) */ +#define DLT_EN3MB 2 /* Experimental Ethernet (3Mb) */ +#define DLT_AX25 3 /* Amateur Radio AX.25 */ +#define DLT_PRONET 4 /* Proteon ProNET Token Ring */ +#define DLT_CHAOS 5 /* Chaos */ +#define DLT_IEEE802 6 /* 802.5 Token Ring */ +#define DLT_ARCNET 7 /* ARCNET, with BSD-style header */ +#define DLT_SLIP 8 /* Serial Line IP */ +#define DLT_PPP 9 /* Point-to-point Protocol */ +#define DLT_FDDI 10 /* FDDI */ + +/* + * These are types that are different on some platforms, and that + * have been defined by for ages. We use #ifdefs to + * detect the BSDs that define them differently from the traditional + * libpcap + * + * XXX - DLT_ATM_RFC1483 is 13 in BSD/OS, and DLT_RAW is 14 in BSD/OS, + * but I don't know what the right #define is for BSD/OS. + */ +#define DLT_ATM_RFC1483 11 /* LLC-encapsulated ATM */ + +#ifdef __OpenBSD__ +#define DLT_RAW 14 /* raw IP */ +#else +#define DLT_RAW 12 /* raw IP */ +#endif + +/* + * Given that the only OS that currently generates BSD/OS SLIP or PPP + * is, well, BSD/OS, arguably everybody should have chosen its values + * for DLT_SLIP_BSDOS and DLT_PPP_BSDOS, which are 15 and 16, but they + * didn't. So it goes. + */ +#if defined(__NetBSD__) || defined(__FreeBSD__) +#ifndef DLT_SLIP_BSDOS +#define DLT_SLIP_BSDOS 13 /* BSD/OS Serial Line IP */ +#define DLT_PPP_BSDOS 14 /* BSD/OS Point-to-point Protocol */ +#endif +#else +#define DLT_SLIP_BSDOS 15 /* BSD/OS Serial Line IP */ +#define DLT_PPP_BSDOS 16 /* BSD/OS Point-to-point Protocol */ +#endif + +/* + * 17 is used for DLT_OLD_PFLOG in OpenBSD; + * OBSOLETE: DLT_PFLOG is 117 in OpenBSD now as well. See below. + * 18 is used for DLT_PFSYNC in OpenBSD; don't use it for anything else. + */ + +#define DLT_ATM_CLIP 19 /* Linux Classical-IP over ATM */ + +/* + * Apparently Redback uses this for its SmartEdge 400/800. I hope + * nobody else decided to use it, too. + */ +#define DLT_REDBACK_SMARTEDGE 32 + +/* + * These values are defined by NetBSD; other platforms should refrain from + * using them for other purposes, so that NetBSD savefiles with link + * types of 50 or 51 can be read as this type on all platforms. + */ +#define DLT_PPP_SERIAL 50 /* PPP over serial with HDLC encapsulation */ +#define DLT_PPP_ETHER 51 /* PPP over Ethernet */ + +/* + * The Axent Raptor firewall - now the Symantec Enterprise Firewall - uses + * a link-layer type of 99 for the tcpdump it supplies. The link-layer + * header has 6 bytes of unknown data, something that appears to be an + * Ethernet type, and 36 bytes that appear to be 0 in at least one capture + * I've seen. + */ +#define DLT_SYMANTEC_FIREWALL 99 + +/* + * Values between 100 and 103 are used in capture file headers as + * link-layer types corresponding to DLT_ types that differ + * between platforms; don't use those values for new DLT_ new types. + */ + +/* + * This value was defined by libpcap 0.5; platforms that have defined + * it with a different value should define it here with that value - + * a link type of 104 in a save file will be mapped to DLT_C_HDLC, + * whatever value that happens to be, so programs will correctly + * handle files with that link type regardless of the value of + * DLT_C_HDLC. + * + * The name DLT_C_HDLC was used by BSD/OS; we use that name for source + * compatibility with programs written for BSD/OS. + * + * libpcap 0.5 defined it as DLT_CHDLC; we define DLT_CHDLC as well, + * for source compatibility with programs written for libpcap 0.5. + */ +#define DLT_C_HDLC 104 /* Cisco HDLC */ +#define DLT_CHDLC DLT_C_HDLC + +#define DLT_IEEE802_11 105 /* IEEE 802.11 wireless */ + +/* + * 106 is reserved for Linux Classical IP over ATM; it's like DLT_RAW, + * except when it isn't. (I.e., sometimes it's just raw IP, and + * sometimes it isn't.) We currently handle it as DLT_LINUX_SLL, + * so that we don't have to worry about the link-layer header.) + */ + +/* + * Frame Relay; BSD/OS has a DLT_FR with a value of 11, but that collides + * with other values. + * DLT_FR and DLT_FRELAY packets start with the Q.922 Frame Relay header + * (DLCI, etc.). + */ +#define DLT_FRELAY 107 + +/* + * OpenBSD DLT_LOOP, for loopback devices; it's like DLT_NULL, except + * that the AF_ type in the link-layer header is in network byte order. + * + * DLT_LOOP is 12 in OpenBSD, but that's DLT_RAW in other OSes, so + * we don't use 12 for it in OSes other than OpenBSD. + */ +#ifdef __OpenBSD__ +#define DLT_LOOP 12 +#else +#define DLT_LOOP 108 +#endif + +/* + * Encapsulated packets for IPsec; DLT_ENC is 13 in OpenBSD, but that's + * DLT_SLIP_BSDOS in NetBSD, so we don't use 13 for it in OSes other + * than OpenBSD. + */ +#ifdef __OpenBSD__ +#define DLT_ENC 13 +#else +#define DLT_ENC 109 +#endif + +/* + * Values between 110 and 112 are reserved for use in capture file headers + * as link-layer types corresponding to DLT_ types that might differ + * between platforms; don't use those values for new DLT_ types + * other than the corresponding DLT_ types. + */ + +/* + * This is for Linux cooked sockets. + */ +#define DLT_LINUX_SLL 113 + +/* + * Apple LocalTalk hardware. + */ +#define DLT_LTALK 114 + +/* + * Acorn Econet. + */ +#define DLT_ECONET 115 + +/* + * Reserved for use with OpenBSD ipfilter. + */ +#define DLT_IPFILTER 116 + +/* + * OpenBSD DLT_PFLOG; DLT_PFLOG is 17 in OpenBSD, but that's DLT_LANE8023 + * in SuSE 6.3, so we can't use 17 for it in capture-file headers. + * + * XXX: is there a conflict with DLT_PFSYNC 18 as well? + */ +#ifdef __OpenBSD__ +#define DLT_OLD_PFLOG 17 +#define DLT_PFSYNC 18 +#endif +#define DLT_PFLOG 117 + +/* + * Registered for Cisco-internal use. + */ +#define DLT_CISCO_IOS 118 + +/* + * For 802.11 cards using the Prism II chips, with a link-layer + * header including Prism monitor mode information plus an 802.11 + * header. + */ +#define DLT_PRISM_HEADER 119 + +/* + * Reserved for Aironet 802.11 cards, with an Aironet link-layer header + * (see Doug Ambrisko's FreeBSD patches). + */ +#define DLT_AIRONET_HEADER 120 + +/* + * Reserved for Siemens HiPath HDLC. + */ +#define DLT_HHDLC 121 + +/* + * This is for RFC 2625 IP-over-Fibre Channel. + * + * This is not for use with raw Fibre Channel, where the link-layer + * header starts with a Fibre Channel frame header; it's for IP-over-FC, + * where the link-layer header starts with an RFC 2625 Network_Header + * field. + */ +#define DLT_IP_OVER_FC 122 + +/* + * This is for Full Frontal ATM on Solaris with SunATM, with a + * pseudo-header followed by an AALn PDU. + * + * There may be other forms of Full Frontal ATM on other OSes, + * with different pseudo-headers. + * + * If ATM software returns a pseudo-header with VPI/VCI information + * (and, ideally, packet type information, e.g. signalling, ILMI, + * LANE, LLC-multiplexed traffic, etc.), it should not use + * DLT_ATM_RFC1483, but should get a new DLT_ value, so tcpdump + * and the like don't have to infer the presence or absence of a + * pseudo-header and the form of the pseudo-header. + */ +#define DLT_SUNATM 123 /* Solaris+SunATM */ + +/* + * Reserved as per request from Kent Dahlgren + * for private use. + */ +#define DLT_RIO 124 /* RapidIO */ +#define DLT_PCI_EXP 125 /* PCI Express */ +#define DLT_AURORA 126 /* Xilinx Aurora link layer */ + +/* + * Header for 802.11 plus a number of bits of link-layer information + * including radio information, used by some recent BSD drivers as + * well as the madwifi Atheros driver for Linux. + */ +#define DLT_IEEE802_11_RADIO 127 /* 802.11 plus radiotap radio header */ + +/* + * Reserved for the TZSP encapsulation, as per request from + * Chris Waters + * TZSP is a generic encapsulation for any other link type, + * which includes a means to include meta-information + * with the packet, e.g. signal strength and channel + * for 802.11 packets. + */ +#define DLT_TZSP 128 /* Tazmen Sniffer Protocol */ + +/* + * BSD's ARCNET headers have the source host, destination host, + * and type at the beginning of the packet; that's what's handed + * up to userland via BPF. + * + * Linux's ARCNET headers, however, have a 2-byte offset field + * between the host IDs and the type; that's what's handed up + * to userland via PF_PACKET sockets. + * + * We therefore have to have separate DLT_ values for them. + */ +#define DLT_ARCNET_LINUX 129 /* ARCNET */ + +/* + * Juniper-private data link types, as per request from + * Hannes Gredler . The DLT_s are used + * for passing on chassis-internal metainformation such as + * QOS profiles, etc.. + */ +#define DLT_JUNIPER_MLPPP 130 +#define DLT_JUNIPER_MLFR 131 +#define DLT_JUNIPER_ES 132 +#define DLT_JUNIPER_GGSN 133 +#define DLT_JUNIPER_MFR 134 +#define DLT_JUNIPER_ATM2 135 +#define DLT_JUNIPER_SERVICES 136 +#define DLT_JUNIPER_ATM1 137 + +/* + * Apple IP-over-IEEE 1394, as per a request from Dieter Siegmund + * . The header that's presented is an Ethernet-like + * header: + * + * #define FIREWIRE_EUI64_LEN 8 + * struct firewire_header { + * u_char firewire_dhost[FIREWIRE_EUI64_LEN]; + * u_char firewire_shost[FIREWIRE_EUI64_LEN]; + * u_short firewire_type; + * }; + * + * with "firewire_type" being an Ethernet type value, rather than, + * for example, raw GASP frames being handed up. + */ +#define DLT_APPLE_IP_OVER_IEEE1394 138 + +/* + * Various SS7 encapsulations, as per a request from Jeff Morriss + * and subsequent discussions. + */ +#define DLT_MTP2_WITH_PHDR 139 /* pseudo-header with various info, followed by MTP2 */ +#define DLT_MTP2 140 /* MTP2, without pseudo-header */ +#define DLT_MTP3 141 /* MTP3, without pseudo-header or MTP2 */ +#define DLT_SCCP 142 /* SCCP, without pseudo-header or MTP2 or MTP3 */ + +/* + * DOCSIS MAC frames. + */ +#define DLT_DOCSIS 143 + +/* + * Linux-IrDA packets. Protocol defined at http://www.irda.org. + * Those packets include IrLAP headers and above (IrLMP...), but + * don't include Phy framing (SOF/EOF/CRC & byte stuffing), because Phy + * framing can be handled by the hardware and depend on the bitrate. + * This is exactly the format you would get capturing on a Linux-IrDA + * interface (irdaX), but not on a raw serial port. + * Note the capture is done in "Linux-cooked" mode, so each packet include + * a fake packet header (struct sll_header). This is because IrDA packet + * decoding is dependant on the direction of the packet (incomming or + * outgoing). + * When/if other platform implement IrDA capture, we may revisit the + * issue and define a real DLT_IRDA... + * Jean II + */ +#define DLT_LINUX_IRDA 144 + +/* + * Reserved for IBM SP switch and IBM Next Federation switch. + */ +#define DLT_IBM_SP 145 +#define DLT_IBM_SN 146 + +/* + * Reserved for private use. If you have some link-layer header type + * that you want to use within your organization, with the capture files + * using that link-layer header type not ever be sent outside your + * organization, you can use these values. + * + * No libpcap release will use these for any purpose, nor will any + * tcpdump release use them, either. + * + * Do *NOT* use these in capture files that you expect anybody not using + * your private versions of capture-file-reading tools to read; in + * particular, do *NOT* use them in products, otherwise you may find that + * people won't be able to use tcpdump, or snort, or Ethereal, or... to + * read capture files from your firewall/intrusion detection/traffic + * monitoring/etc. appliance, or whatever product uses that DLT_ value, + * and you may also find that the developers of those applications will + * not accept patches to let them read those files. + * + * Also, do not use them if somebody might send you a capture using them + * for *their* private type and tools using them for *your* private type + * would have to read them. + * + * Instead, ask "tcpdump-workers@lists.tcpdump.org" for a new DLT_ value, + * as per the comment above, and use the type you're given. + */ +#define DLT_USER0 147 +#define DLT_USER1 148 +#define DLT_USER2 149 +#define DLT_USER3 150 +#define DLT_USER4 151 +#define DLT_USER5 152 +#define DLT_USER6 153 +#define DLT_USER7 154 +#define DLT_USER8 155 +#define DLT_USER9 156 +#define DLT_USER10 157 +#define DLT_USER11 158 +#define DLT_USER12 159 +#define DLT_USER13 160 +#define DLT_USER14 161 +#define DLT_USER15 162 + +/* + * For future use with 802.11 captures - defined by AbsoluteValue + * Systems to store a number of bits of link-layer information + * including radio information: + * + * http://www.shaftnet.org/~pizza/software/capturefrm.txt + * + * but it might be used by some non-AVS drivers now or in the + * future. + */ +#define DLT_IEEE802_11_RADIO_AVS 163 /* 802.11 plus AVS radio header */ + +/* + * Juniper-private data link type, as per request from + * Hannes Gredler . The DLT_s are used + * for passing on chassis-internal metainformation such as + * QOS profiles, etc.. + */ +#define DLT_JUNIPER_MONITOR 164 + +/* + * Reserved for BACnet MS/TP. + */ +#define DLT_BACNET_MS_TP 165 + +/* + * Another PPP variant as per request from Karsten Keil . + * + * This is used in some OSes to allow a kernel socket filter to distinguish + * between incoming and outgoing packets, on a socket intended to + * supply pppd with outgoing packets so it can do dial-on-demand and + * hangup-on-lack-of-demand; incoming packets are filtered out so they + * don't cause pppd to hold the connection up (you don't want random + * input packets such as port scans, packets from old lost connections, + * etc. to force the connection to stay up). + * + * The first byte of the PPP header (0xff03) is modified to accomodate + * the direction - 0x00 = IN, 0x01 = OUT. + */ +#define DLT_PPP_PPPD 166 + +/* + * Names for backwards compatibility with older versions of some PPP + * software; new software should use DLT_PPP_PPPD. + */ +#define DLT_PPP_WITH_DIRECTION DLT_PPP_PPPD +#define DLT_LINUX_PPP_WITHDIRECTION DLT_PPP_PPPD + +/* + * Juniper-private data link type, as per request from + * Hannes Gredler . The DLT_s are used + * for passing on chassis-internal metainformation such as + * QOS profiles, cookies, etc.. + */ +#define DLT_JUNIPER_PPPOE 167 +#define DLT_JUNIPER_PPPOE_ATM 168 + +#define DLT_GPRS_LLC 169 /* GPRS LLC */ +#define DLT_GPF_T 170 /* GPF-T (ITU-T G.7041/Y.1303) */ +#define DLT_GPF_F 171 /* GPF-F (ITU-T G.7041/Y.1303) */ + +/* + * Requested by Oolan Zimmer for use in Gcom's T1/E1 line + * monitoring equipment. + */ +#define DLT_GCOM_T1E1 172 +#define DLT_GCOM_SERIAL 173 + +/* + * Juniper-private data link type, as per request from + * Hannes Gredler . The DLT_ is used + * for internal communication to Physical Interface Cards (PIC) + */ +#define DLT_JUNIPER_PIC_PEER 174 + +/* + * Link types requested by Gregor Maier of Endace + * Measurement Systems. They add an ERF header (see + * http://www.endace.com/support/EndaceRecordFormat.pdf) in front of + * the link-layer header. + */ +#define DLT_ERF_ETH 175 /* Ethernet */ +#define DLT_ERF_POS 176 /* Packet-over-SONET */ + +/* + * Requested by Daniele Orlandi for raw LAPD + * for vISDN (http://www.orlandi.com/visdn/). Its link-layer header + * includes additional information before the LAPD header, so it's + * not necessarily a generic LAPD header. + */ +#define DLT_LINUX_LAPD 177 + +/* + * Juniper-private data link type, as per request from + * Hannes Gredler . + * The DLT_ are used for prepending meta-information + * like interface index, interface name + * before standard Ethernet, PPP, Frelay & C-HDLC Frames + */ +#define DLT_JUNIPER_ETHER 178 +#define DLT_JUNIPER_PPP 179 +#define DLT_JUNIPER_FRELAY 180 +#define DLT_JUNIPER_CHDLC 181 + +/* + * Multi Link Frame Relay (FRF.16) + */ +#define DLT_MFR 182 + +/* + * Juniper-private data link type, as per request from + * Hannes Gredler . + * The DLT_ is used for internal communication with a + * voice Adapter Card (PIC) + */ +#define DLT_JUNIPER_VP 183 + +/* + * Arinc 429 frames. + * DLT_ requested by Gianluca Varenni . + * Every frame contains a 32bit A429 label. + * More documentation on Arinc 429 can be found at + * http://www.condoreng.com/support/downloads/tutorials/ARINCTutorial.pdf + */ +#define DLT_A429 184 + +/* + * Arinc 653 Interpartition Communication messages. + * DLT_ requested by Gianluca Varenni . + * Please refer to the A653-1 standard for more information. + */ +#define DLT_A653_ICM 185 + +/* + * USB packets, beginning with a USB setup header; requested by + * Paolo Abeni . + */ +#define DLT_USB 186 + +/* + * Bluetooth HCI UART transport layer (part H:4); requested by + * Paolo Abeni. + */ +#define DLT_BLUETOOTH_HCI_H4 187 + +/* + * IEEE 802.16 MAC Common Part Sublayer; requested by Maria Cruz + * . + */ +#define DLT_IEEE802_16_MAC_CPS 188 + +/* + * USB packets, beginning with a Linux USB header; requested by + * Paolo Abeni . + */ +#define DLT_USB_LINUX 189 + +/* + * Controller Area Network (CAN) v. 2.0B packets. + * DLT_ requested by Gianluca Varenni . + * Used to dump CAN packets coming from a CAN Vector board. + * More documentation on the CAN v2.0B frames can be found at + * http://www.can-cia.org/downloads/?269 + */ +#define DLT_CAN20B 190 + +/* + * IEEE 802.15.4, with address fields padded, as is done by Linux + * drivers; requested by Juergen Schimmer. + */ +#define DLT_IEEE802_15_4_LINUX 191 + +/* + * Per Packet Information encapsulated packets. + * DLT_ requested by Gianluca Varenni . + */ +#define DLT_PPI 192 + +/* + * Header for 802.16 MAC Common Part Sublayer plus a radiotap radio header; + * requested by Charles Clancy. + */ +#define DLT_IEEE802_16_MAC_CPS_RADIO 193 + +/* + * Juniper-private data link type, as per request from + * Hannes Gredler . + * The DLT_ is used for internal communication with a + * integrated service module (ISM). + */ +#define DLT_JUNIPER_ISM 194 + +/* + * IEEE 802.15.4, exactly as it appears in the spec (no padding, no + * nothing); requested by Mikko Saarnivala . + */ +#define DLT_IEEE802_15_4 195 + +/* + * Various link-layer types, with a pseudo-header, for SITA + * (http://www.sita.aero/); requested by Fulko Hew (fulko.hew@gmail.com). + */ +#define DLT_SITA 196 + +/* + * Various link-layer types, with a pseudo-header, for Endace DAG cards; + * encapsulates Endace ERF records. Requested by Stephen Donnelly + * . + */ +#define DLT_ERF 197 + +/* + * Special header prepended to Ethernet packets when capturing from a + * u10 Networks board. Requested by Phil Mulholland + * . + */ +#define DLT_RAIF1 198 + +/* + * IPMB packet for IPMI, beginning with the I2C slave address, followed + * by the netFn and LUN, etc.. Requested by Chanthy Toeung + * . + */ +#define DLT_IPMB 199 + +/* + * Juniper-private data link type, as per request from + * Hannes Gredler . + * The DLT_ is used for capturing data on a secure tunnel interface. + */ +#define DLT_JUNIPER_ST 200 + +/* + * Bluetooth HCI UART transport layer (part H:4), with pseudo-header + * that includes direction information; requested by Paolo Abeni. + */ +#define DLT_BLUETOOTH_HCI_H4_WITH_PHDR 201 + +/* + * AX.25 packet with a 1-byte KISS header; see + * + * http://www.ax25.net/kiss.htm + * + * as per Richard Stearn . + */ +#define DLT_AX25_KISS 202 + +/* + * LAPD packets from an ISDN channel, starting with the address field, + * with no pseudo-header. + * Requested by Varuna De Silva . + */ +#define DLT_LAPD 203 + +/* + * Variants of various link-layer headers, with a one-byte direction + * pseudo-header prepended - zero means "received by this host", + * non-zero (any non-zero value) means "sent by this host" - as per + * Will Barker . + */ +#define DLT_PPP_WITH_DIR 204 /* PPP - don't confuse with DLT_PPP_WITH_DIRECTION */ +#define DLT_C_HDLC_WITH_DIR 205 /* Cisco HDLC */ +#define DLT_FRELAY_WITH_DIR 206 /* Frame Relay */ +#define DLT_LAPB_WITH_DIR 207 /* LAPB */ + +/* + * 208 is reserved for an as-yet-unspecified proprietary link-layer + * type, as requested by Will Barker. + */ + +/* + * IPMB with a Linux-specific pseudo-header; as requested by Alexey Neyman + * . + */ +#define DLT_IPMB_LINUX 209 + +/* + * FlexRay automotive bus - http://www.flexray.com/ - as requested + * by Hannes Kaelber . + */ +#define DLT_FLEXRAY 210 + +/* + * Media Oriented Systems Transport (MOST) bus for multimedia + * transport - http://www.mostcooperation.com/ - as requested + * by Hannes Kaelber . + */ +#define DLT_MOST 211 + +/* + * Local Interconnect Network (LIN) bus for vehicle networks - + * http://www.lin-subbus.org/ - as requested by Hannes Kaelber + * . + */ +#define DLT_LIN 212 + +/* + * X2E-private data link type used for serial line capture, + * as requested by Hannes Kaelber . + */ +#define DLT_X2E_SERIAL 213 + +/* + * X2E-private data link type used for the Xoraya data logger + * family, as requested by Hannes Kaelber . + */ +#define DLT_X2E_XORAYA 214 + +/* + * IEEE 802.15.4, exactly as it appears in the spec (no padding, no + * nothing), but with the PHY-level data for non-ASK PHYs (4 octets + * of 0 as preamble, one octet of SFD, one octet of frame length+ + * reserved bit, and then the MAC-layer data, starting with the + * frame control field). + * + * Requested by Max Filippov . + */ +#define DLT_IEEE802_15_4_NONASK_PHY 215 + + +/* + * DLT and savefile link type values are split into a class and + * a member of that class. A class value of 0 indicates a regular + * DLT_/LINKTYPE_ value. + */ +#define DLT_CLASS(x) ((x) & 0x03ff0000) + +/* + * NetBSD-specific generic "raw" link type. The class value indicates + * that this is the generic raw type, and the lower 16 bits are the + * address family we're dealing with. Those values are NetBSD-specific; + * do not assume that they correspond to AF_ values for your operating + * system. + */ +#define DLT_CLASS_NETBSD_RAWAF 0x02240000 +#define DLT_NETBSD_RAWAF(af) (DLT_CLASS_NETBSD_RAWAF | (af)) +#define DLT_NETBSD_RAWAF_AF(x) ((x) & 0x0000ffff) +#define DLT_IS_NETBSD_RAWAF(x) (DLT_CLASS(x) == DLT_CLASS_NETBSD_RAWAF) + + +/* + * The instruction encodings. + */ +/* instruction classes */ +#define BPF_CLASS(code) ((code) & 0x07) +#define BPF_LD 0x00 +#define BPF_LDX 0x01 +#define BPF_ST 0x02 +#define BPF_STX 0x03 +#define BPF_ALU 0x04 +#define BPF_JMP 0x05 +#define BPF_RET 0x06 +#define BPF_MISC 0x07 + +/* ld/ldx fields */ +#define BPF_SIZE(code) ((code) & 0x18) +#define BPF_W 0x00 +#define BPF_H 0x08 +#define BPF_B 0x10 +#define BPF_MODE(code) ((code) & 0xe0) +#define BPF_IMM 0x00 +#define BPF_ABS 0x20 +#define BPF_IND 0x40 +#define BPF_MEM 0x60 +#define BPF_LEN 0x80 +#define BPF_MSH 0xa0 + +/* alu/jmp fields */ +#define BPF_OP(code) ((code) & 0xf0) +#define BPF_ADD 0x00 +#define BPF_SUB 0x10 +#define BPF_MUL 0x20 +#define BPF_DIV 0x30 +#define BPF_OR 0x40 +#define BPF_AND 0x50 +#define BPF_LSH 0x60 +#define BPF_RSH 0x70 +#define BPF_NEG 0x80 +#define BPF_JA 0x00 +#define BPF_JEQ 0x10 +#define BPF_JGT 0x20 +#define BPF_JGE 0x30 +#define BPF_JSET 0x40 +#define BPF_SRC(code) ((code) & 0x08) +#define BPF_K 0x00 +#define BPF_X 0x08 + +/* ret - BPF_K and BPF_X also apply */ +#define BPF_RVAL(code) ((code) & 0x18) +#define BPF_A 0x10 + +/* misc */ +#define BPF_MISCOP(code) ((code) & 0xf8) +#define BPF_TAX 0x00 +#define BPF_TXA 0x80 + +/* + * The instruction data structure. + */ +struct bpf_insn { + u_short code; + u_char jt; + u_char jf; + bpf_u_int32 k; +}; + +/* + * Macros for insn array initializers. + */ +#define BPF_STMT(code, k) { (u_short)(code), 0, 0, k } +#define BPF_JUMP(code, k, jt, jf) { (u_short)(code), jt, jf, k } + +#if __STDC__ || defined(__cplusplus) +extern int bpf_validate(const struct bpf_insn *, int); +extern u_int bpf_filter(const struct bpf_insn *, const u_char *, u_int, u_int); +#else +extern int bpf_validate(); +extern u_int bpf_filter(); +#endif + +/* + * Number of scratch memory words (for BPF_LD|BPF_MEM and BPF_ST). + */ +#define BPF_MEMWORDS 16 + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/3rdparty/winpcap/include/pcap/namedb.h b/3rdparty/winpcap/include/pcap/namedb.h new file mode 100644 index 0000000000..9002c75093 --- /dev/null +++ b/3rdparty/winpcap/include/pcap/namedb.h @@ -0,0 +1,89 @@ +/* + * Copyright (c) 1994, 1996 + * The Regents of the University of California. 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. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the Computer Systems + * Engineering Group at Lawrence Berkeley Laboratory. + * 4. Neither the name of the University nor of the Laboratory may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#) $Header: /tcpdump/master/libpcap/pcap/namedb.h,v 1.1 2006/10/04 18:09:22 guy Exp $ (LBL) + */ + +#ifndef lib_pcap_namedb_h +#define lib_pcap_namedb_h + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * As returned by the pcap_next_etherent() + * XXX this stuff doesn't belong in this interface, but this + * library already must do name to address translation, so + * on systems that don't have support for /etc/ethers, we + * export these hooks since they'll + */ +struct pcap_etherent { + u_char addr[6]; + char name[122]; +}; +#ifndef PCAP_ETHERS_FILE +#define PCAP_ETHERS_FILE "/etc/ethers" +#endif +struct pcap_etherent *pcap_next_etherent(FILE *); +u_char *pcap_ether_hostton(const char*); +u_char *pcap_ether_aton(const char *); + +bpf_u_int32 **pcap_nametoaddr(const char *); +#ifdef INET6 +struct addrinfo *pcap_nametoaddrinfo(const char *); +#endif +bpf_u_int32 pcap_nametonetaddr(const char *); + +int pcap_nametoport(const char *, int *, int *); +int pcap_nametoportrange(const char *, int *, int *, int *); +int pcap_nametoproto(const char *); +int pcap_nametoeproto(const char *); +int pcap_nametollc(const char *); +/* + * If a protocol is unknown, PROTO_UNDEF is returned. + * Also, pcap_nametoport() returns the protocol along with the port number. + * If there are ambiguous entried in /etc/services (i.e. domain + * can be either tcp or udp) PROTO_UNDEF is returned. + */ +#define PROTO_UNDEF -1 + +/* XXX move these to pcap-int.h? */ +int __pcap_atodn(const char *, bpf_u_int32 *); +int __pcap_atoin(const char *, bpf_u_int32 *); +u_short __pcap_nametodnaddr(const char *); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/3rdparty/winpcap/include/pcap/pcap.h b/3rdparty/winpcap/include/pcap/pcap.h new file mode 100644 index 0000000000..ad8fc40ac1 --- /dev/null +++ b/3rdparty/winpcap/include/pcap/pcap.h @@ -0,0 +1,407 @@ +/* -*- Mode: c; tab-width: 8; indent-tabs-mode: 1; c-basic-offset: 8; -*- */ +/* + * Copyright (c) 1993, 1994, 1995, 1996, 1997 + * The Regents of the University of California. 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. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the Computer Systems + * Engineering Group at Lawrence Berkeley Laboratory. + * 4. Neither the name of the University nor of the Laboratory may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#) $Header: /tcpdump/master/libpcap/pcap/pcap.h,v 1.4.2.11 2008-10-06 15:38:39 gianluca Exp $ (LBL) + */ + +#ifndef lib_pcap_pcap_h +#define lib_pcap_pcap_h + +#if defined(WIN32) + #include +#elif defined(MSDOS) + #include + #include /* u_int, u_char etc. */ +#else /* UN*X */ + #include + #include +#endif /* WIN32/MSDOS/UN*X */ + +#ifndef PCAP_DONT_INCLUDE_PCAP_BPF_H +#include +#endif + +#include + +#ifdef HAVE_REMOTE + // We have to define the SOCKET here, although it has been defined in sockutils.h + // This is to avoid the distribution of the 'sockutils.h' file around + // (for example in the WinPcap developer's pack) + #ifndef SOCKET + #ifdef WIN32 + #define SOCKET unsigned int + #else + #define SOCKET int + #endif + #endif +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +#define PCAP_VERSION_MAJOR 2 +#define PCAP_VERSION_MINOR 4 + +#define PCAP_ERRBUF_SIZE 256 + +/* + * Compatibility for systems that have a bpf.h that + * predates the bpf typedefs for 64-bit support. + */ +#if BPF_RELEASE - 0 < 199406 +typedef int bpf_int32; +typedef u_int bpf_u_int32; +#endif + +typedef struct pcap pcap_t; +typedef struct pcap_dumper pcap_dumper_t; +typedef struct pcap_if pcap_if_t; +typedef struct pcap_addr pcap_addr_t; + +/* + * The first record in the file contains saved values for some + * of the flags used in the printout phases of tcpdump. + * Many fields here are 32 bit ints so compilers won't insert unwanted + * padding; these files need to be interchangeable across architectures. + * + * Do not change the layout of this structure, in any way (this includes + * changes that only affect the length of fields in this structure). + * + * Also, do not change the interpretation of any of the members of this + * structure, in any way (this includes using values other than + * LINKTYPE_ values, as defined in "savefile.c", in the "linktype" + * field). + * + * Instead: + * + * introduce a new structure for the new format, if the layout + * of the structure changed; + * + * send mail to "tcpdump-workers@lists.tcpdump.org", requesting + * a new magic number for your new capture file format, and, when + * you get the new magic number, put it in "savefile.c"; + * + * use that magic number for save files with the changed file + * header; + * + * make the code in "savefile.c" capable of reading files with + * the old file header as well as files with the new file header + * (using the magic number to determine the header format). + * + * Then supply the changes as a patch at + * + * http://sourceforge.net/projects/libpcap/ + * + * so that future versions of libpcap and programs that use it (such as + * tcpdump) will be able to read your new capture file format. + */ +struct pcap_file_header { + bpf_u_int32 magic; + u_short version_major; + u_short version_minor; + bpf_int32 thiszone; /* gmt to local correction */ + bpf_u_int32 sigfigs; /* accuracy of timestamps */ + bpf_u_int32 snaplen; /* max length saved portion of each pkt */ + bpf_u_int32 linktype; /* data link type (LINKTYPE_*) */ +}; + +/* + * Macros for the value returned by pcap_datalink_ext(). + * + * If LT_FCS_LENGTH_PRESENT(x) is true, the LT_FCS_LENGTH(x) macro + * gives the FCS length of packets in the capture. + */ +#define LT_FCS_LENGTH_PRESENT(x) ((x) & 0x04000000) +#define LT_FCS_LENGTH(x) (((x) & 0xF0000000) >> 28) +#define LT_FCS_DATALINK_EXT(x) ((((x) & 0xF) << 28) | 0x04000000) + +typedef enum { + PCAP_D_INOUT = 0, + PCAP_D_IN, + PCAP_D_OUT +} pcap_direction_t; + +/* + * Generic per-packet information, as supplied by libpcap. + * + * The time stamp can and should be a "struct timeval", regardless of + * whether your system supports 32-bit tv_sec in "struct timeval", + * 64-bit tv_sec in "struct timeval", or both if it supports both 32-bit + * and 64-bit applications. The on-disk format of savefiles uses 32-bit + * tv_sec (and tv_usec); this structure is irrelevant to that. 32-bit + * and 64-bit versions of libpcap, even if they're on the same platform, + * should supply the appropriate version of "struct timeval", even if + * that's not what the underlying packet capture mechanism supplies. + */ +struct pcap_pkthdr { + struct timeval ts; /* time stamp */ + bpf_u_int32 caplen; /* length of portion present */ + bpf_u_int32 len; /* length this packet (off wire) */ +}; + +/* + * As returned by the pcap_stats() + */ +struct pcap_stat { + u_int ps_recv; /* number of packets received */ + u_int ps_drop; /* number of packets dropped */ + u_int ps_ifdrop; /* drops by interface XXX not yet supported */ +#ifdef HAVE_REMOTE + u_int ps_capt; /* number of packets that are received by the application; please get rid off the Win32 ifdef */ + u_int ps_sent; /* number of packets sent by the server on the network */ + u_int ps_netdrop; /* number of packets lost on the network */ +#endif /* HAVE_REMOTE */ +}; + +#ifdef MSDOS +/* + * As returned by the pcap_stats_ex() + */ +struct pcap_stat_ex { + u_long rx_packets; /* total packets received */ + u_long tx_packets; /* total packets transmitted */ + u_long rx_bytes; /* total bytes received */ + u_long tx_bytes; /* total bytes transmitted */ + u_long rx_errors; /* bad packets received */ + u_long tx_errors; /* packet transmit problems */ + u_long rx_dropped; /* no space in Rx buffers */ + u_long tx_dropped; /* no space available for Tx */ + u_long multicast; /* multicast packets received */ + u_long collisions; + + /* detailed rx_errors: */ + u_long rx_length_errors; + u_long rx_over_errors; /* receiver ring buff overflow */ + u_long rx_crc_errors; /* recv'd pkt with crc error */ + u_long rx_frame_errors; /* recv'd frame alignment error */ + u_long rx_fifo_errors; /* recv'r fifo overrun */ + u_long rx_missed_errors; /* recv'r missed packet */ + + /* detailed tx_errors */ + u_long tx_aborted_errors; + u_long tx_carrier_errors; + u_long tx_fifo_errors; + u_long tx_heartbeat_errors; + u_long tx_window_errors; + }; +#endif + +/* + * Item in a list of interfaces. + */ +struct pcap_if { + struct pcap_if *next; + char *name; /* name to hand to "pcap_open_live()" */ + char *description; /* textual description of interface, or NULL */ + struct pcap_addr *addresses; + bpf_u_int32 flags; /* PCAP_IF_ interface flags */ +}; + +#define PCAP_IF_LOOPBACK 0x00000001 /* interface is loopback */ + +/* + * Representation of an interface address. + */ +struct pcap_addr { + struct pcap_addr *next; + struct sockaddr *addr; /* address */ + struct sockaddr *netmask; /* netmask for that address */ + struct sockaddr *broadaddr; /* broadcast address for that address */ + struct sockaddr *dstaddr; /* P2P destination address for that address */ +}; + +typedef void (*pcap_handler)(u_char *, const struct pcap_pkthdr *, + const u_char *); + +/* + * Error codes for the pcap API. + * These will all be negative, so you can check for the success or + * failure of a call that returns these codes by checking for a + * negative value. + */ +#define PCAP_ERROR -1 /* generic error code */ +#define PCAP_ERROR_BREAK -2 /* loop terminated by pcap_breakloop */ +#define PCAP_ERROR_NOT_ACTIVATED -3 /* the capture needs to be activated */ +#define PCAP_ERROR_ACTIVATED -4 /* the operation can't be performed on already activated captures */ +#define PCAP_ERROR_NO_SUCH_DEVICE -5 /* no such device exists */ +#define PCAP_ERROR_RFMON_NOTSUP -6 /* this device doesn't support rfmon (monitor) mode */ +#define PCAP_ERROR_NOT_RFMON -7 /* operation supported only in monitor mode */ +#define PCAP_ERROR_PERM_DENIED -8 /* no permission to open the device */ +#define PCAP_ERROR_IFACE_NOT_UP -9 /* interface isn't up */ + +/* + * Warning codes for the pcap API. + * These will all be positive and non-zero, so they won't look like + * errors. + */ +#define PCAP_WARNING 1 /* generic warning code */ +#define PCAP_WARNING_PROMISC_NOTSUP 2 /* this device doesn't support promiscuous mode */ + +char *pcap_lookupdev(char *); +int pcap_lookupnet(const char *, bpf_u_int32 *, bpf_u_int32 *, char *); + +pcap_t *pcap_create(const char *, char *); +int pcap_set_snaplen(pcap_t *, int); +int pcap_set_promisc(pcap_t *, int); +int pcap_can_set_rfmon(pcap_t *); +int pcap_set_rfmon(pcap_t *, int); +int pcap_set_timeout(pcap_t *, int); +int pcap_set_buffer_size(pcap_t *, int); +int pcap_activate(pcap_t *); + +pcap_t *pcap_open_live(const char *, int, int, int, char *); +pcap_t *pcap_open_dead(int, int); +pcap_t *pcap_open_offline(const char *, char *); +#if defined(WIN32) +pcap_t *pcap_hopen_offline(intptr_t, char *); +#if !defined(LIBPCAP_EXPORTS) +#define pcap_fopen_offline(f,b) \ + pcap_hopen_offline(_get_osfhandle(_fileno(f)), b) +#else /*LIBPCAP_EXPORTS*/ +static pcap_t *pcap_fopen_offline(FILE *, char *); +#endif +#else /*WIN32*/ +pcap_t *pcap_fopen_offline(FILE *, char *); +#endif /*WIN32*/ + +void pcap_close(pcap_t *); +int pcap_loop(pcap_t *, int, pcap_handler, u_char *); +int pcap_dispatch(pcap_t *, int, pcap_handler, u_char *); +const u_char* + pcap_next(pcap_t *, struct pcap_pkthdr *); +int pcap_next_ex(pcap_t *, struct pcap_pkthdr **, const u_char **); +void pcap_breakloop(pcap_t *); +int pcap_stats(pcap_t *, struct pcap_stat *); +int pcap_setfilter(pcap_t *, struct bpf_program *); +int pcap_setdirection(pcap_t *, pcap_direction_t); +int pcap_getnonblock(pcap_t *, char *); +int pcap_setnonblock(pcap_t *, int, char *); +int pcap_inject(pcap_t *, const void *, size_t); +int pcap_sendpacket(pcap_t *, const u_char *, int); +const char *pcap_statustostr(int); +const char *pcap_strerror(int); +char *pcap_geterr(pcap_t *); +void pcap_perror(pcap_t *, char *); +int pcap_compile(pcap_t *, struct bpf_program *, const char *, int, + bpf_u_int32); +int pcap_compile_nopcap(int, int, struct bpf_program *, + const char *, int, bpf_u_int32); +void pcap_freecode(struct bpf_program *); +int pcap_offline_filter(struct bpf_program *, const struct pcap_pkthdr *, + const u_char *); +int pcap_datalink(pcap_t *); +int pcap_datalink_ext(pcap_t *); +int pcap_list_datalinks(pcap_t *, int **); +int pcap_set_datalink(pcap_t *, int); +void pcap_free_datalinks(int *); +int pcap_datalink_name_to_val(const char *); +const char *pcap_datalink_val_to_name(int); +const char *pcap_datalink_val_to_description(int); +int pcap_snapshot(pcap_t *); +int pcap_is_swapped(pcap_t *); +int pcap_major_version(pcap_t *); +int pcap_minor_version(pcap_t *); + +/* XXX */ +FILE *pcap_file(pcap_t *); +int pcap_fileno(pcap_t *); + +pcap_dumper_t *pcap_dump_open(pcap_t *, const char *); +pcap_dumper_t *pcap_dump_fopen(pcap_t *, FILE *fp); +FILE *pcap_dump_file(pcap_dumper_t *); +long pcap_dump_ftell(pcap_dumper_t *); +int pcap_dump_flush(pcap_dumper_t *); +void pcap_dump_close(pcap_dumper_t *); +void pcap_dump(u_char *, const struct pcap_pkthdr *, const u_char *); + +int pcap_findalldevs(pcap_if_t **, char *); +void pcap_freealldevs(pcap_if_t *); + +const char *pcap_lib_version(void); + +/* XXX this guy lives in the bpf tree */ +u_int bpf_filter(const struct bpf_insn *, const u_char *, u_int, u_int); +int bpf_validate(const struct bpf_insn *f, int len); +char *bpf_image(const struct bpf_insn *, int); +void bpf_dump(const struct bpf_program *, int); + +#if defined(WIN32) + +/* + * Win32 definitions + */ + +int pcap_setbuff(pcap_t *p, int dim); +int pcap_setmode(pcap_t *p, int mode); +int pcap_setmintocopy(pcap_t *p, int size); + +#ifdef WPCAP +/* Include file with the wpcap-specific extensions */ +#include +#endif /* WPCAP */ + +#define MODE_CAPT 0 +#define MODE_STAT 1 +#define MODE_MON 2 + +#elif defined(MSDOS) + +/* + * MS-DOS definitions + */ + +int pcap_stats_ex (pcap_t *, struct pcap_stat_ex *); +void pcap_set_wait (pcap_t *p, void (*yield)(void), int wait); +u_long pcap_mac_packets (void); + +#else /* UN*X */ + +/* + * UN*X definitions + */ + +int pcap_get_selectable_fd(pcap_t *); + +#endif /* WIN32/MSDOS/UN*X */ + +#ifdef HAVE_REMOTE +/* Includes most of the public stuff that is needed for the remote capture */ +#include +#endif /* HAVE_REMOTE */ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/3rdparty/winpcap/include/pcap/sll.h b/3rdparty/winpcap/include/pcap/sll.h new file mode 100644 index 0000000000..e9d5452af7 --- /dev/null +++ b/3rdparty/winpcap/include/pcap/sll.h @@ -0,0 +1,129 @@ +/*- + * Copyright (c) 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from the Stanford/CMU enet packet filter, + * (net/enet.c) distributed as part of 4.3BSD, and code contributed + * to Berkeley by Steven McCanne and Van Jacobson both of Lawrence + * Berkeley Laboratory. + * + * 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. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University 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 REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#) $Header: /tcpdump/master/libpcap/pcap/sll.h,v 1.2.2.1 2008-05-30 01:36:06 guy Exp $ (LBL) + */ + +/* + * For captures on Linux cooked sockets, we construct a fake header + * that includes: + * + * a 2-byte "packet type" which is one of: + * + * LINUX_SLL_HOST packet was sent to us + * LINUX_SLL_BROADCAST packet was broadcast + * LINUX_SLL_MULTICAST packet was multicast + * LINUX_SLL_OTHERHOST packet was sent to somebody else + * LINUX_SLL_OUTGOING packet was sent *by* us; + * + * a 2-byte Ethernet protocol field; + * + * a 2-byte link-layer type; + * + * a 2-byte link-layer address length; + * + * an 8-byte source link-layer address, whose actual length is + * specified by the previous value. + * + * All fields except for the link-layer address are in network byte order. + * + * DO NOT change the layout of this structure, or change any of the + * LINUX_SLL_ values below. If you must change the link-layer header + * for a "cooked" Linux capture, introduce a new DLT_ type (ask + * "tcpdump-workers@lists.tcpdump.org" for one, so that you don't give it + * a value that collides with a value already being used), and use the + * new header in captures of that type, so that programs that can + * handle DLT_LINUX_SLL captures will continue to handle them correctly + * without any change, and so that capture files with different headers + * can be told apart and programs that read them can dissect the + * packets in them. + */ + +#ifndef lib_pcap_sll_h +#define lib_pcap_sll_h + +/* + * A DLT_LINUX_SLL fake link-layer header. + */ +#define SLL_HDR_LEN 16 /* total header length */ +#define SLL_ADDRLEN 8 /* length of address field */ + +struct sll_header { + u_int16_t sll_pkttype; /* packet type */ + u_int16_t sll_hatype; /* link-layer address type */ + u_int16_t sll_halen; /* link-layer address length */ + u_int8_t sll_addr[SLL_ADDRLEN]; /* link-layer address */ + u_int16_t sll_protocol; /* protocol */ +}; + +/* + * The LINUX_SLL_ values for "sll_pkttype"; these correspond to the + * PACKET_ values on Linux, but are defined here so that they're + * available even on systems other than Linux, and so that they + * don't change even if the PACKET_ values change. + */ +#define LINUX_SLL_HOST 0 +#define LINUX_SLL_BROADCAST 1 +#define LINUX_SLL_MULTICAST 2 +#define LINUX_SLL_OTHERHOST 3 +#define LINUX_SLL_OUTGOING 4 + +/* + * The LINUX_SLL_ values for "sll_protocol"; these correspond to the + * ETH_P_ values on Linux, but are defined here so that they're + * available even on systems other than Linux. We assume, for now, + * that the ETH_P_ values won't change in Linux; if they do, then: + * + * if we don't translate them in "pcap-linux.c", capture files + * won't necessarily be readable if captured on a system that + * defines ETH_P_ values that don't match these values; + * + * if we do translate them in "pcap-linux.c", that makes life + * unpleasant for the BPF code generator, as the values you test + * for in the kernel aren't the values that you test for when + * reading a capture file, so the fixup code run on BPF programs + * handed to the kernel ends up having to do more work. + * + * Add other values here as necessary, for handling packet types that + * might show up on non-Ethernet, non-802.x networks. (Not all the ones + * in the Linux "if_ether.h" will, I suspect, actually show up in + * captures.) + */ +#define LINUX_SLL_P_802_3 0x0001 /* Novell 802.3 frames without 802.2 LLC header */ +#define LINUX_SLL_P_802_2 0x0004 /* 802.2 frames (not D/I/X Ethernet) */ + +#endif diff --git a/3rdparty/winpcap/include/pcap/usb.h b/3rdparty/winpcap/include/pcap/usb.h new file mode 100644 index 0000000000..adcd19c058 --- /dev/null +++ b/3rdparty/winpcap/include/pcap/usb.h @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2006 Paolo Abeni (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. + * 3. The name of the author may not be used to endorse or promote + * products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE 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. + * + * Basic USB data struct + * By Paolo Abeni + * + * @(#) $Header: /tcpdump/master/libpcap/pcap/usb.h,v 1.6 2007/09/22 02:06:08 guy Exp $ + */ + +#ifndef _PCAP_USB_STRUCTS_H__ +#define _PCAP_USB_STRUCTS_H__ + +/* + * possible transfer mode + */ +#define URB_TRANSFER_IN 0x80 +#define URB_ISOCHRONOUS 0x0 +#define URB_INTERRUPT 0x1 +#define URB_CONTROL 0x2 +#define URB_BULK 0x3 + +/* + * possible event type + */ +#define URB_SUBMIT 'S' +#define URB_COMPLETE 'C' +#define URB_ERROR 'E' + +/* + * USB setup header as defined in USB specification. + * Appears at the front of each packet in DLT_USB captures. + */ +typedef struct _usb_setup { + u_int8_t bmRequestType; + u_int8_t bRequest; + u_int16_t wValue; + u_int16_t wIndex; + u_int16_t wLength; +} pcap_usb_setup; + + +/* + * Header prepended by linux kernel to each event. + * Appears at the front of each packet in DLT_USB_LINUX captures. + */ +typedef struct _usb_header { + u_int64_t id; + u_int8_t event_type; + u_int8_t transfer_type; + u_int8_t endpoint_number; + u_int8_t device_address; + u_int16_t bus_id; + char setup_flag;/*if !=0 the urb setup header is not present*/ + char data_flag; /*if !=0 no urb data is present*/ + int64_t ts_sec; + int32_t ts_usec; + int32_t status; + u_int32_t urb_len; + u_int32_t data_len; /* amount of urb data really present in this event*/ + pcap_usb_setup setup; +} pcap_usb_header; + + +#endif diff --git a/3rdparty/winpcap/include/pcap/vlan.h b/3rdparty/winpcap/include/pcap/vlan.h new file mode 100644 index 0000000000..b0cb7949be --- /dev/null +++ b/3rdparty/winpcap/include/pcap/vlan.h @@ -0,0 +1,46 @@ +/*- + * Copyright (c) 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997 + * The Regents of the University of California. 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. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University 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 REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#) $Header: /tcpdump/master/libpcap/pcap/vlan.h,v 1.1.2.2 2008-08-06 07:45:59 guy Exp $ + */ + +#ifndef lib_pcap_vlan_h +#define lib_pcap_vlan_h + +struct vlan_tag { + u_int16_t vlan_tpid; /* ETH_P_8021Q */ + u_int16_t vlan_tci; /* VLAN TCI */ +}; + +#define VLAN_TAG_LEN 4 + +#endif diff --git a/3rdparty/winpcap/include/remote-ext.h b/3rdparty/winpcap/include/remote-ext.h new file mode 100644 index 0000000000..9f54d6974c --- /dev/null +++ b/3rdparty/winpcap/include/remote-ext.h @@ -0,0 +1,444 @@ +/* + * Copyright (c) 2002 - 2003 + * NetGroup, Politecnico di Torino (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. + * 3. Neither the name of the Politecnico di Torino nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + + +#ifndef __REMOTE_EXT_H__ +#define __REMOTE_EXT_H__ + + +#ifndef HAVE_REMOTE +#error Please do not include this file directly. Just define HAVE_REMOTE and then include pcap.h +#endif + +// Definition for Microsoft Visual Studio +#if _MSC_VER > 1000 +#pragma once +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/*! + \file remote-ext.h + + The goal of this file it to include most of the new definitions that should be + placed into the pcap.h file. + + It includes all new definitions (structures and functions like pcap_open(). + Some of the functions are not really a remote feature, but, right now, + they are placed here. +*/ + + + +// All this stuff is public +/*! \addtogroup remote_struct + \{ +*/ + + + + +/*! + \brief Defines the maximum buffer size in which address, port, interface names are kept. + + In case the adapter name or such is larger than this value, it is truncated. + This is not used by the user; however it must be aware that an hostname / interface + name longer than this value will be truncated. +*/ +#define PCAP_BUF_SIZE 1024 + + +/*! \addtogroup remote_source_ID + \{ +*/ + + +/*! + \brief Internal representation of the type of source in use (file, + remote/local interface). + + This indicates a file, i.e. the user want to open a capture from a local file. +*/ +#define PCAP_SRC_FILE 2 +/*! + \brief Internal representation of the type of source in use (file, + remote/local interface). + + This indicates a local interface, i.e. the user want to open a capture from + a local interface. This does not involve the RPCAP protocol. +*/ +#define PCAP_SRC_IFLOCAL 3 +/*! + \brief Internal representation of the type of source in use (file, + remote/local interface). + + This indicates a remote interface, i.e. the user want to open a capture from + an interface on a remote host. This does involve the RPCAP protocol. +*/ +#define PCAP_SRC_IFREMOTE 4 + +/*! + \} +*/ + + + +/*! \addtogroup remote_source_string + + The formats allowed by the pcap_open() are the following: + - file://path_and_filename [opens a local file] + - rpcap://devicename [opens the selected device devices available on the local host, without using the RPCAP protocol] + - rpcap://host/devicename [opens the selected device available on a remote host] + - rpcap://host:port/devicename [opens the selected device available on a remote host, using a non-standard port for RPCAP] + - adaptername [to open a local adapter; kept for compability, but it is strongly discouraged] + - (NULL) [to open the first local adapter; kept for compability, but it is strongly discouraged] + + The formats allowed by the pcap_findalldevs_ex() are the following: + - file://folder/ [lists all the files in the given folder] + - rpcap:// [lists all local adapters] + - rpcap://host:port/ [lists the devices available on a remote host] + + Referring to the 'host' and 'port' paramters, they can be either numeric or literal. Since + IPv6 is fully supported, these are the allowed formats: + + - host (literal): e.g. host.foo.bar + - host (numeric IPv4): e.g. 10.11.12.13 + - host (numeric IPv4, IPv6 style): e.g. [10.11.12.13] + - host (numeric IPv6): e.g. [1:2:3::4] + - port: can be either numeric (e.g. '80') or literal (e.g. 'http') + + Here you find some allowed examples: + - rpcap://host.foo.bar/devicename [everything literal, no port number] + - rpcap://host.foo.bar:1234/devicename [everything literal, with port number] + - rpcap://10.11.12.13/devicename [IPv4 numeric, no port number] + - rpcap://10.11.12.13:1234/devicename [IPv4 numeric, with port number] + - rpcap://[10.11.12.13]:1234/devicename [IPv4 numeric with IPv6 format, with port number] + - rpcap://[1:2:3::4]/devicename [IPv6 numeric, no port number] + - rpcap://[1:2:3::4]:1234/devicename [IPv6 numeric, with port number] + - rpcap://[1:2:3::4]:http/devicename [IPv6 numeric, with literal port number] + + \{ +*/ + + +/*! + \brief String that will be used to determine the type of source in use (file, + remote/local interface). + + This string will be prepended to the interface name in order to create a string + that contains all the information required to open the source. + + This string indicates that the user wants to open a capture from a local file. +*/ +#define PCAP_SRC_FILE_STRING "file://" +/*! + \brief String that will be used to determine the type of source in use (file, + remote/local interface). + + This string will be prepended to the interface name in order to create a string + that contains all the information required to open the source. + + This string indicates that the user wants to open a capture from a network interface. + This string does not necessarily involve the use of the RPCAP protocol. If the + interface required resides on the local host, the RPCAP protocol is not involved + and the local functions are used. +*/ +#define PCAP_SRC_IF_STRING "rpcap://" + +/*! + \} +*/ + + + + + +/*! + \addtogroup remote_open_flags + \{ +*/ + +/*! + \brief Defines if the adapter has to go in promiscuous mode. + + It is '1' if you have to open the adapter in promiscuous mode, '0' otherwise. + Note that even if this parameter is false, the interface could well be in promiscuous + mode for some other reason (for example because another capture process with + promiscuous mode enabled is currently using that interface). + On on Linux systems with 2.2 or later kernels (that have the "any" device), this + flag does not work on the "any" device; if an argument of "any" is supplied, + the 'promisc' flag is ignored. +*/ +#define PCAP_OPENFLAG_PROMISCUOUS 1 + +/*! + \brief Defines if the data trasfer (in case of a remote + capture) has to be done with UDP protocol. + + If it is '1' if you want a UDP data connection, '0' if you want + a TCP data connection; control connection is always TCP-based. + A UDP connection is much lighter, but it does not guarantee that all + the captured packets arrive to the client workstation. Moreover, + it could be harmful in case of network congestion. + This flag is meaningless if the source is not a remote interface. + In that case, it is simply ignored. +*/ +#define PCAP_OPENFLAG_DATATX_UDP 2 + + +/*! + \brief Defines if the remote probe will capture its own generated traffic. + + In case the remote probe uses the same interface to capture traffic and to send + data back to the caller, the captured traffic includes the RPCAP traffic as well. + If this flag is turned on, the RPCAP traffic is excluded from the capture, so that + the trace returned back to the collector is does not include this traffic. +*/ +#define PCAP_OPENFLAG_NOCAPTURE_RPCAP 4 + +/*! + \brief Defines if the local adapter will capture its own generated traffic. + + This flag tells the underlying capture driver to drop the packets that were sent by itself. + This is usefult when building applications like bridges, that should ignore the traffic + they just sent. +*/ +#define PCAP_OPENFLAG_NOCAPTURE_LOCAL 8 + +/*! + \brief This flag configures the adapter for maximum responsiveness. + + In presence of a large value for nbytes, WinPcap waits for the arrival of several packets before + copying the data to the user. This guarantees a low number of system calls, i.e. lower processor usage, + i.e. better performance, which is good for applications like sniffers. If the user sets the + PCAP_OPENFLAG_MAX_RESPONSIVENESS flag, the capture driver will copy the packets as soon as the application + is ready to receive them. This is suggested for real time applications (like, for example, a bridge) + that need the best responsiveness.*/ +#define PCAP_OPENFLAG_MAX_RESPONSIVENESS 16 + +/*! + \} +*/ + + +/*! + \addtogroup remote_samp_methods + \{ +*/ + +/*! + \brief No sampling has to be done on the current capture. + + In this case, no sampling algorithms are applied to the current capture. +*/ +#define PCAP_SAMP_NOSAMP 0 + +/*! + \brief It defines that only 1 out of N packets must be returned to the user. + + In this case, the 'value' field of the 'pcap_samp' structure indicates the + number of packets (minus 1) that must be discarded before one packet got accepted. + In other words, if 'value = 10', the first packet is returned to the caller, while + the following 9 are discarded. +*/ +#define PCAP_SAMP_1_EVERY_N 1 + +/*! + \brief It defines that we have to return 1 packet every N milliseconds. + + In this case, the 'value' field of the 'pcap_samp' structure indicates the 'waiting + time' in milliseconds before one packet got accepted. + In other words, if 'value = 10', the first packet is returned to the caller; the next + returned one will be the first packet that arrives when 10ms have elapsed. +*/ +#define PCAP_SAMP_FIRST_AFTER_N_MS 2 + +/*! + \} +*/ + + +/*! + \addtogroup remote_auth_methods + \{ +*/ + +/*! + \brief It defines the NULL authentication. + + This value has to be used within the 'type' member of the pcap_rmtauth structure. + The 'NULL' authentication has to be equal to 'zero', so that old applications + can just put every field of struct pcap_rmtauth to zero, and it does work. +*/ +#define RPCAP_RMTAUTH_NULL 0 +/*! + \brief It defines the username/password authentication. + + With this type of authentication, the RPCAP protocol will use the username/ + password provided to authenticate the user on the remote machine. If the + authentication is successful (and the user has the right to open network devices) + the RPCAP connection will continue; otherwise it will be dropped. + + This value has to be used within the 'type' member of the pcap_rmtauth structure. +*/ +#define RPCAP_RMTAUTH_PWD 1 + +/*! + \} +*/ + + + + +/*! + + \brief This structure keeps the information needed to autheticate + the user on a remote machine. + + The remote machine can either grant or refuse the access according + to the information provided. + In case the NULL authentication is required, both 'username' and + 'password' can be NULL pointers. + + This structure is meaningless if the source is not a remote interface; + in that case, the functions which requires such a structure can accept + a NULL pointer as well. +*/ +struct pcap_rmtauth +{ + /*! + \brief Type of the authentication required. + + In order to provide maximum flexibility, we can support different types + of authentication based on the value of this 'type' variable. The currently + supported authentication methods are defined into the + \link remote_auth_methods Remote Authentication Methods Section\endlink. + + */ + int type; + /*! + \brief Zero-terminated string containing the username that has to be + used on the remote machine for authentication. + + This field is meaningless in case of the RPCAP_RMTAUTH_NULL authentication + and it can be NULL. + */ + char *username; + /*! + \brief Zero-terminated string containing the password that has to be + used on the remote machine for authentication. + + This field is meaningless in case of the RPCAP_RMTAUTH_NULL authentication + and it can be NULL. + */ + char *password; +}; + + +/*! + \brief This structure defines the information related to sampling. + + In case the sampling is requested, the capturing device should read + only a subset of the packets coming from the source. The returned packets depend + on the sampling parameters. + + \warning The sampling process is applied after the filtering process. + In other words, packets are filtered first, then the sampling process selects a + subset of the 'filtered' packets and it returns them to the caller. +*/ +struct pcap_samp +{ + /*! + Method used for sampling. Currently, the supported methods are listed in the + \link remote_samp_methods Sampling Methods Section\endlink. + */ + int method; + + /*! + This value depends on the sampling method defined. For its meaning, please check + at the \link remote_samp_methods Sampling Methods Section\endlink. + */ + int value; +}; + + + + +//! Maximum lenght of an host name (needed for the RPCAP active mode) +#define RPCAP_HOSTLIST_SIZE 1024 + + +/*! + \} +*/ // end of public documentation + + +// Exported functions + + + +/** \name New WinPcap functions + + This section lists the new functions that are able to help considerably in writing + WinPcap programs because of their easiness of use. + */ +//\{ +pcap_t *pcap_open(const char *source, int snaplen, int flags, int read_timeout, struct pcap_rmtauth *auth, char *errbuf); +int pcap_createsrcstr(char *source, int type, const char *host, const char *port, const char *name, char *errbuf); +int pcap_parsesrcstr(const char *source, int *type, char *host, char *port, char *name, char *errbuf); +int pcap_findalldevs_ex(char *source, struct pcap_rmtauth *auth, pcap_if_t **alldevs, char *errbuf); +struct pcap_samp *pcap_setsampling(pcap_t *p); + +//\} +// End of new winpcap functions + + + +/** \name Remote Capture functions + */ +//\{ +SOCKET pcap_remoteact_accept(const char *address, const char *port, const char *hostlist, char *connectinghost, struct pcap_rmtauth *auth, char *errbuf); +int pcap_remoteact_list(char *hostlist, char sep, int size, char *errbuf); +int pcap_remoteact_close(const char *host, char *errbuf); +void pcap_remoteact_cleanup(); +//\} +// End of remote capture functions + +#ifdef __cplusplus +} +#endif + + +#endif + diff --git a/3rdparty/winpcap/lib/Packet.lib b/3rdparty/winpcap/lib/Packet.lib new file mode 100644 index 0000000000..81618bc8ca Binary files /dev/null and b/3rdparty/winpcap/lib/Packet.lib differ diff --git a/3rdparty/winpcap/lib/wpcap.lib b/3rdparty/winpcap/lib/wpcap.lib new file mode 100644 index 0000000000..f832e0445b Binary files /dev/null and b/3rdparty/winpcap/lib/wpcap.lib differ diff --git a/3rdparty/winpcap/lib/x64/Packet.lib b/3rdparty/winpcap/lib/x64/Packet.lib new file mode 100644 index 0000000000..30c1540503 Binary files /dev/null and b/3rdparty/winpcap/lib/x64/Packet.lib differ diff --git a/3rdparty/winpcap/lib/x64/wpcap.lib b/3rdparty/winpcap/lib/x64/wpcap.lib new file mode 100644 index 0000000000..d5559f802b Binary files /dev/null and b/3rdparty/winpcap/lib/x64/wpcap.lib differ diff --git a/3rdparty/winpcap/readme.txt b/3rdparty/winpcap/readme.txt new file mode 100644 index 0000000000..6239cecd1e --- /dev/null +++ b/3rdparty/winpcap/readme.txt @@ -0,0 +1,3 @@ +Winpcap is version 4.1.2 downloaded from +https://www.winpcap.org/install/bin/WpdPack_4_1_2.zip +Just the /include and /lib directories are included to keep the size small. \ No newline at end of file diff --git a/3rdparty/wxWidgets/build/msw/wx_adv_vs11.vcxproj b/3rdparty/wxWidgets/build/msw/wx_adv_vs11.vcxproj index 90b3f601fc..74a6515f32 100644 --- a/3rdparty/wxWidgets/build/msw/wx_adv_vs11.vcxproj +++ b/3rdparty/wxWidgets/build/msw/wx_adv_vs11.vcxproj @@ -221,7 +221,7 @@ - + {c34487af-228a-4d11-8e50-27803df76873} false diff --git a/3rdparty/wxWidgets/build/msw/wx_base_vs11.vcxproj b/3rdparty/wxWidgets/build/msw/wx_base_vs11.vcxproj index 6894f6120e..bdee3c6f57 100644 --- a/3rdparty/wxWidgets/build/msw/wx_base_vs11.vcxproj +++ b/3rdparty/wxWidgets/build/msw/wx_base_vs11.vcxproj @@ -379,7 +379,7 @@ - + {c34487af-228a-4d11-8e50-27803df76873} false diff --git a/3rdparty/wxWidgets/build/msw/wx_core_vs11.vcxproj b/3rdparty/wxWidgets/build/msw/wx_core_vs11.vcxproj index 9f8289f6c9..964b427cfc 100644 --- a/3rdparty/wxWidgets/build/msw/wx_core_vs11.vcxproj +++ b/3rdparty/wxWidgets/build/msw/wx_core_vs11.vcxproj @@ -1527,11 +1527,11 @@ - + {bc236261-77e8-4567-8d09-45cd02965eb6} false - + {c34487af-228a-4d11-8e50-27803df76873} false diff --git a/3rdparty/zlib/ChangeLog b/3rdparty/zlib/ChangeLog index 64d60661a8..c2c643a1a9 100644 --- a/3rdparty/zlib/ChangeLog +++ b/3rdparty/zlib/ChangeLog @@ -1,1130 +1,1409 @@ - - ChangeLog file for zlib - -Changes in 1.2.4 (14 Mar 2010) -- Fix VER3 extraction in configure for no fourth subversion -- Update zlib.3, add docs to Makefile.in to make .pdf out of it -- Add zlib.3.pdf to distribution -- Don't set error code in gzerror() if passed pointer is NULL -- Apply destination directory fixes to CMakeLists.txt [Lowman] -- Move #cmakedefine's to a new zconf.in.cmakein -- Restore zconf.h for builds that don't use configure or cmake -- Add distclean to dummy Makefile for convenience -- Update and improve INDEX, README, and FAQ -- Update CMakeLists.txt for the return of zconf.h [Lowman] -- Update contrib/vstudio/vc9 and vc10 [Vollant] -- Change libz.dll.a back to libzdll.a in win32/Makefile.gcc -- Apply license and readme changes to contrib/asm686 [Raiter] -- Check file name lengths and add -c option in minigzip.c [Li] -- Update contrib/amd64 and contrib/masmx86/ [Vollant] -- Avoid use of "eof" parameter in trees.c to not shadow library variable -- Update make_vms.com for removal of zlibdefs.h [Zinser] -- Update assembler code and vstudio projects in contrib [Vollant] -- Remove outdated assembler code contrib/masm686 and contrib/asm586 -- Remove old vc7 and vc8 from contrib/vstudio -- Update win32/Makefile.msc, add ZLIB_VER_SUBREVISION [Rowe] -- Fix memory leaks in gzclose_r() and gzclose_w(), file leak in gz_open() -- Add contrib/gcc_gvmat64 for longest_match and inflate_fast [Vollant] -- Remove *64 functions from win32/zlib.def (they're not 64-bit yet) -- Fix bug in void-returning vsprintf() case in gzwrite.c -- Fix name change from inflate.h in contrib/inflate86/inffas86.c -- Check if temporary file exists before removing in make_vms.com [Zinser] -- Fix make install and uninstall for --static option -- Fix usage of _MSC_VER in gzguts.h and zutil.h [Truta] -- Update readme.txt in contrib/masmx64 and masmx86 to assemble - -Changes in 1.2.3.9 (21 Feb 2010) -- Expunge gzio.c -- Move as400 build information to old -- Fix updates in contrib/minizip and contrib/vstudio -- Add const to vsnprintf test in configure to avoid warnings [Weigelt] -- Delete zconf.h (made by configure) [Weigelt] -- Change zconf.in.h to zconf.h.in per convention [Weigelt] -- Check for NULL buf in gzgets() -- Return empty string for gzgets() with len == 1 (like fgets()) -- Fix description of gzgets() in zlib.h for end-of-file, NULL return -- Update minizip to 1.1 [Vollant] -- Avoid MSVC loss of data warnings in gzread.c, gzwrite.c -- Note in zlib.h that gzerror() should be used to distinguish from EOF -- Remove use of snprintf() from gzlib.c -- Fix bug in gzseek() -- Update contrib/vstudio, adding vc9 and vc10 [Kuno, Vollant] -- Fix zconf.h generation in CMakeLists.txt [Lowman] -- Improve comments in zconf.h where modified by configure - -Changes in 1.2.3.8 (13 Feb 2010) -- Clean up text files (tabs, trailing whitespace, etc.) [Oberhumer] -- Use z_off64_t in gz_zero() and gz_skip() to match state->skip -- Avoid comparison problem when sizeof(int) == sizeof(z_off64_t) -- Revert to Makefile.in from 1.2.3.6 (live with the clutter) -- Fix missing error return in gzflush(), add zlib.h note -- Add *64 functions to zlib.map [Levin] -- Fix signed/unsigned comparison in gz_comp() -- Use SFLAGS when testing shared linking in configure -- Add --64 option to ./configure to use -m64 with gcc -- Fix ./configure --help to correctly name options -- Have make fail if a test fails [Levin] -- Avoid buffer overrun in contrib/masmx64/gvmat64.asm [Simpson] -- Remove assembler object files from contrib - -Changes in 1.2.3.7 (24 Jan 2010) -- Always gzopen() with O_LARGEFILE if available -- Fix gzdirect() to work immediately after gzopen() or gzdopen() -- Make gzdirect() more precise when the state changes while reading -- Improve zlib.h documentation in many places -- Catch memory allocation failure in gz_open() -- Complete close operation if seek forward in gzclose_w() fails -- Return Z_ERRNO from gzclose_r() if close() fails -- Return Z_STREAM_ERROR instead of EOF for gzclose() being passed NULL -- Return zero for gzwrite() errors to match zlib.h description -- Return -1 on gzputs() error to match zlib.h description -- Add zconf.in.h to allow recovery from configure modification [Weigelt] -- Fix static library permissions in Makefile.in [Weigelt] -- Avoid warnings in configure tests that hide functionality [Weigelt] -- Add *BSD and DragonFly to Linux case in configure [gentoo 123571] -- Change libzdll.a to libz.dll.a in win32/Makefile.gcc [gentoo 288212] -- Avoid access of uninitialized data for first inflateReset2 call [Gomes] -- Keep object files in subdirectories to reduce the clutter somewhat -- Remove default Makefile and zlibdefs.h, add dummy Makefile -- Add new external functions to Z_PREFIX, remove duplicates, z_z_ -> z_ -- Remove zlibdefs.h completely -- modify zconf.h instead - -Changes in 1.2.3.6 (17 Jan 2010) -- Avoid void * arithmetic in gzread.c and gzwrite.c -- Make compilers happier with const char * for gz_error message -- Avoid unused parameter warning in inflate.c -- Avoid signed-unsigned comparison warning in inflate.c -- Indent #pragma's for traditional C -- Fix usage of strwinerror() in glib.c, change to gz_strwinerror() -- Correct email address in configure for system options -- Update make_vms.com and add make_vms.com to contrib/minizip [Zinser] -- Update zlib.map [Brown] -- Fix Makefile.in for Solaris 10 make of example64 and minizip64 [Tšršk] -- Apply various fixes to CMakeLists.txt [Lowman] -- Add checks on len in gzread() and gzwrite() -- Add error message for no more room for gzungetc() -- Remove zlib version check in gzwrite() -- Defer compression of gzprintf() result until need to -- Use snprintf() in gzdopen() if available -- Remove USE_MMAP configuration determination (only used by minigzip) -- Remove examples/pigz.c (available separately) -- Update examples/gun.c to 1.6 - -Changes in 1.2.3.5 (8 Jan 2010) -- Add space after #if in zutil.h for some compilers -- Fix relatively harmless bug in deflate_fast() [Exarevsky] -- Fix same problem in deflate_slow() -- Add $(SHAREDLIBV) to LIBS in Makefile.in [Brown] -- Add deflate_rle() for faster Z_RLE strategy run-length encoding -- Add deflate_huff() for faster Z_HUFFMAN_ONLY encoding -- Change name of "write" variable in inffast.c to avoid library collisions -- Fix premature EOF from gzread() in gzio.c [Brown] -- Use zlib header window size if windowBits is 0 in inflateInit2() -- Remove compressBound() call in deflate.c to avoid linking compress.o -- Replace use of errno in gz* with functions, support WinCE [Alves] -- Provide alternative to perror() in minigzip.c for WinCE [Alves] -- Don't use _vsnprintf on later versions of MSVC [Lowman] -- Add CMake build script and input file [Lowman] -- Update contrib/minizip to 1.1 [Svensson, Vollant] -- Moved nintendods directory from contrib to . -- Replace gzio.c with a new set of routines with the same functionality -- Add gzbuffer(), gzoffset(), gzclose_r(), gzclose_w() as part of above -- Update contrib/minizip to 1.1b -- Change gzeof() to return 0 on error instead of -1 to agree with zlib.h - -Changes in 1.2.3.4 (21 Dec 2009) -- Use old school .SUFFIXES in Makefile.in for FreeBSD compatibility -- Update comments in configure and Makefile.in for default --shared -- Fix test -z's in configure [Marquess] -- Build examplesh and minigzipsh when not testing -- Change NULL's to Z_NULL's in deflate.c and in comments in zlib.h -- Import LDFLAGS from the environment in configure -- Fix configure to populate SFLAGS with discovered CFLAGS options -- Adapt make_vms.com to the new Makefile.in [Zinser] -- Add zlib2ansi script for C++ compilation [Marquess] -- Add _FILE_OFFSET_BITS=64 test to make test (when applicable) -- Add AMD64 assembler code for longest match to contrib [Teterin] -- Include options from $SFLAGS when doing $LDSHARED -- Simplify 64-bit file support by introducing z_off64_t type -- Make shared object files in objs directory to work around old Sun cc -- Use only three-part version number for Darwin shared compiles -- Add rc option to ar in Makefile.in for when ./configure not run -- Add -WI,-rpath,. to LDFLAGS for OSF 1 V4* -- Set LD_LIBRARYN32_PATH for SGI IRIX shared compile -- Protect against _FILE_OFFSET_BITS being defined when compiling zlib -- Rename Makefile.in targets allstatic to static and allshared to shared -- Fix static and shared Makefile.in targets to be independent -- Correct error return bug in gz_open() by setting state [Brown] -- Put spaces before ;;'s in configure for better sh compatibility -- Add pigz.c (parallel implementation of gzip) to examples/ -- Correct constant in crc32.c to UL [Leventhal] -- Reject negative lengths in crc32_combine() -- Add inflateReset2() function to work like inflateEnd()/inflateInit2() -- Include sys/types.h for _LARGEFILE64_SOURCE [Brown] -- Correct typo in doc/algorithm.txt [Janik] -- Fix bug in adler32_combine() [Zhu] -- Catch missing-end-of-block-code error in all inflates and in puff - Assures that random input to inflate eventually results in an error -- Added enough.c (calculation of ENOUGH for inftrees.h) to examples/ -- Update ENOUGH and its usage to reflect discovered bounds -- Fix gzerror() error report on empty input file [Brown] -- Add ush casts in trees.c to avoid pedantic runtime errors -- Fix typo in zlib.h uncompress() description [Reiss] -- Correct inflate() comments with regard to automatic header detection -- Remove deprecation comment on Z_PARTIAL_FLUSH (it stays) -- Put new version of gzlog (2.0) in examples with interruption recovery -- Add puff compile option to permit invalid distance-too-far streams -- Add puff TEST command options, ability to read piped input -- Prototype the *64 functions in zlib.h when _FILE_OFFSET_BITS == 64, but - _LARGEFILE64_SOURCE not defined -- Fix Z_FULL_FLUSH to truly erase the past by resetting s->strstart -- Fix deflateSetDictionary() to use all 32K for output consistency -- Remove extraneous #define MIN_LOOKAHEAD in deflate.c (in deflate.h) -- Clear bytes after deflate lookahead to avoid use of uninitialized data -- Change a limit in inftrees.c to be more transparent to Coverity Prevent -- Update win32/zlib.def with exported symbols from zlib.h -- Correct spelling error in zlib.h [Willem] -- Allow Z_BLOCK for deflate() to force a new block -- Allow negative bits in inflatePrime() to delete existing bit buffer -- Add Z_TREES flush option to inflate() to return at end of trees -- Add inflateMark() to return current state information for random access -- Add Makefile for NintendoDS to contrib [Costa] -- Add -w in configure compile tests to avoid spurious warnings [Beucler] -- Fix typos in zlib.h comments for deflateSetDictionary() -- Fix EOF detection in transparent gzread() [Maier] - -Changes in 1.2.3.3 (2 October 2006) -- Make --shared the default for configure, add a --static option -- Add compile option to permit invalid distance-too-far streams -- Add inflateUndermine() function which is required to enable above -- Remove use of "this" variable name for C++ compatibility [Marquess] -- Add testing of shared library in make test, if shared library built -- Use ftello() and fseeko() if available instead of ftell() and fseek() -- Provide two versions of all functions that use the z_off_t type for - binary compatibility -- a normal version and a 64-bit offset version, - per the Large File Support Extension when _LARGEFILE64_SOURCE is - defined; use the 64-bit versions by default when _FILE_OFFSET_BITS - is defined to be 64 -- Add a --uname= option to configure to perhaps help with cross-compiling - -Changes in 1.2.3.2 (3 September 2006) -- Turn off silly Borland warnings [Hay] -- Use off64_t and define _LARGEFILE64_SOURCE when present -- Fix missing dependency on inffixed.h in Makefile.in -- Rig configure --shared to build both shared and static [Teredesai, Truta] -- Remove zconf.in.h and instead create a new zlibdefs.h file -- Fix contrib/minizip/unzip.c non-encrypted after encrypted [Vollant] -- Add treebuild.xml (see http://treebuild.metux.de/) [Weigelt] - -Changes in 1.2.3.1 (16 August 2006) -- Add watcom directory with OpenWatcom make files [Daniel] -- Remove #undef of FAR in zconf.in.h for MVS [Fedtke] -- Update make_vms.com [Zinser] -- Use -fPIC for shared build in configure [Teredesai, Nicholson] -- Use only major version number for libz.so on IRIX and OSF1 [Reinholdtsen] -- Use fdopen() (not _fdopen()) for Interix in zutil.h [BŠck] -- Add some FAQ entries about the contrib directory -- Update the MVS question in the FAQ -- Avoid extraneous reads after EOF in gzio.c [Brown] -- Correct spelling of "successfully" in gzio.c [Randers-Pehrson] -- Add comments to zlib.h about gzerror() usage [Brown] -- Set extra flags in gzip header in gzopen() like deflate() does -- Make configure options more compatible with double-dash conventions - [Weigelt] -- Clean up compilation under Solaris SunStudio cc [Rowe, Reinholdtsen] -- Fix uninstall target in Makefile.in [Truta] -- Add pkgconfig support [Weigelt] -- Use $(DESTDIR) macro in Makefile.in [Reinholdtsen, Weigelt] -- Replace set_data_type() with a more accurate detect_data_type() in - trees.c, according to the txtvsbin.txt document [Truta] -- Swap the order of #include and #include "zlib.h" in - gzio.c, example.c and minigzip.c [Truta] -- Shut up annoying VS2005 warnings about standard C deprecation [Rowe, - Truta] (where?) -- Fix target "clean" from win32/Makefile.bor [Truta] -- Create .pdb and .manifest files in win32/makefile.msc [Ziegler, Rowe] -- Update zlib www home address in win32/DLL_FAQ.txt [Truta] -- Update contrib/masmx86/inffas32.asm for VS2005 [Vollant, Van Wassenhove] -- Enable browse info in the "Debug" and "ASM Debug" configurations in - the Visual C++ 6 project, and set (non-ASM) "Debug" as default [Truta] -- Add pkgconfig support [Weigelt] -- Add ZLIB_VER_MAJOR, ZLIB_VER_MINOR and ZLIB_VER_REVISION in zlib.h, - for use in win32/zlib1.rc [Polushin, Rowe, Truta] -- Add a document that explains the new text detection scheme to - doc/txtvsbin.txt [Truta] -- Add rfc1950.txt, rfc1951.txt and rfc1952.txt to doc/ [Truta] -- Move algorithm.txt into doc/ [Truta] -- Synchronize FAQ with website -- Fix compressBound(), was low for some pathological cases [Fearnley] -- Take into account wrapper variations in deflateBound() -- Set examples/zpipe.c input and output to binary mode for Windows -- Update examples/zlib_how.html with new zpipe.c (also web site) -- Fix some warnings in examples/gzlog.c and examples/zran.c (it seems - that gcc became pickier in 4.0) -- Add zlib.map for Linux: "All symbols from zlib-1.1.4 remain - un-versioned, the patch adds versioning only for symbols introduced in - zlib-1.2.0 or later. It also declares as local those symbols which are - not designed to be exported." [Levin] -- Update Z_PREFIX list in zconf.in.h, add --zprefix option to configure -- Do not initialize global static by default in trees.c, add a response - NO_INIT_GLOBAL_POINTERS to initialize them if needed [Marquess] -- Don't use strerror() in gzio.c under WinCE [Yakimov] -- Don't use errno.h in zutil.h under WinCE [Yakimov] -- Move arguments for AR to its usage to allow replacing ar [Marot] -- Add HAVE_VISIBILITY_PRAGMA in zconf.in.h for Mozilla [Randers-Pehrson] -- Improve inflateInit() and inflateInit2() documentation -- Fix structure size comment in inflate.h -- Change configure help option from --h* to --help [Santos] - -Changes in 1.2.3 (18 July 2005) -- Apply security vulnerability fixes to contrib/infback9 as well -- Clean up some text files (carriage returns, trailing space) -- Update testzlib, vstudio, masmx64, and masmx86 in contrib [Vollant] - -Changes in 1.2.2.4 (11 July 2005) -- Add inflatePrime() function for starting inflation at bit boundary -- Avoid some Visual C warnings in deflate.c -- Avoid more silly Visual C warnings in inflate.c and inftrees.c for 64-bit - compile -- Fix some spelling errors in comments [Betts] -- Correct inflateInit2() error return documentation in zlib.h -- Add zran.c example of compressed data random access to examples - directory, shows use of inflatePrime() -- Fix cast for assignments to strm->state in inflate.c and infback.c -- Fix zlibCompileFlags() in zutil.c to use 1L for long shifts [Oberhumer] -- Move declarations of gf2 functions to right place in crc32.c [Oberhumer] -- Add cast in trees.c t avoid a warning [Oberhumer] -- Avoid some warnings in fitblk.c, gun.c, gzjoin.c in examples [Oberhumer] -- Update make_vms.com [Zinser] -- Initialize state->write in inflateReset() since copied in inflate_fast() -- Be more strict on incomplete code sets in inflate_table() and increase - ENOUGH and MAXD -- this repairs a possible security vulnerability for - invalid inflate input. Thanks to Tavis Ormandy and Markus Oberhumer for - discovering the vulnerability and providing test cases. -- Add ia64 support to configure for HP-UX [Smith] -- Add error return to gzread() for format or i/o error [Levin] -- Use malloc.h for OS/2 [Necasek] - -Changes in 1.2.2.3 (27 May 2005) -- Replace 1U constants in inflate.c and inftrees.c for 64-bit compile -- Typecast fread() return values in gzio.c [Vollant] -- Remove trailing space in minigzip.c outmode (VC++ can't deal with it) -- Fix crc check bug in gzread() after gzungetc() [Heiner] -- Add the deflateTune() function to adjust internal compression parameters -- Add a fast gzip decompressor, gun.c, to examples (use of inflateBack) -- Remove an incorrect assertion in examples/zpipe.c -- Add C++ wrapper in infback9.h [Donais] -- Fix bug in inflateCopy() when decoding fixed codes -- Note in zlib.h how much deflateSetDictionary() actually uses -- Remove USE_DICT_HEAD in deflate.c (would mess up inflate if used) -- Add _WIN32_WCE to define WIN32 in zconf.in.h [Spencer] -- Don't include stderr.h or errno.h for _WIN32_WCE in zutil.h [Spencer] -- Add gzdirect() function to indicate transparent reads -- Update contrib/minizip [Vollant] -- Fix compilation of deflate.c when both ASMV and FASTEST [Oberhumer] -- Add casts in crc32.c to avoid warnings [Oberhumer] -- Add contrib/masmx64 [Vollant] -- Update contrib/asm586, asm686, masmx86, testzlib, vstudio [Vollant] - -Changes in 1.2.2.2 (30 December 2004) -- Replace structure assignments in deflate.c and inflate.c with zmemcpy to - avoid implicit memcpy calls (portability for no-library compilation) -- Increase sprintf() buffer size in gzdopen() to allow for large numbers -- Add INFLATE_STRICT to check distances against zlib header -- Improve WinCE errno handling and comments [Chang] -- Remove comment about no gzip header processing in FAQ -- Add Z_FIXED strategy option to deflateInit2() to force fixed trees -- Add updated make_vms.com [Coghlan], update README -- Create a new "examples" directory, move gzappend.c there, add zpipe.c, - fitblk.c, gzlog.[ch], gzjoin.c, and zlib_how.html. -- Add FAQ entry and comments in deflate.c on uninitialized memory access -- Add Solaris 9 make options in configure [Gilbert] -- Allow strerror() usage in gzio.c for STDC -- Fix DecompressBuf in contrib/delphi/ZLib.pas [ManChesTer] -- Update contrib/masmx86/inffas32.asm and gvmat32.asm [Vollant] -- Use z_off_t for adler32_combine() and crc32_combine() lengths -- Make adler32() much faster for small len -- Use OS_CODE in deflate() default gzip header - -Changes in 1.2.2.1 (31 October 2004) -- Allow inflateSetDictionary() call for raw inflate -- Fix inflate header crc check bug for file names and comments -- Add deflateSetHeader() and gz_header structure for custom gzip headers -- Add inflateGetheader() to retrieve gzip headers -- Add crc32_combine() and adler32_combine() functions -- Add alloc_func, free_func, in_func, out_func to Z_PREFIX list -- Use zstreamp consistently in zlib.h (inflate_back functions) -- Remove GUNZIP condition from definition of inflate_mode in inflate.h - and in contrib/inflate86/inffast.S [Truta, Anderson] -- Add support for AMD64 in contrib/inflate86/inffas86.c [Anderson] -- Update projects/README.projects and projects/visualc6 [Truta] -- Update win32/DLL_FAQ.txt [Truta] -- Avoid warning under NO_GZCOMPRESS in gzio.c; fix typo [Truta] -- Deprecate Z_ASCII; use Z_TEXT instead [Truta] -- Use a new algorithm for setting strm->data_type in trees.c [Truta] -- Do not define an exit() prototype in zutil.c unless DEBUG defined -- Remove prototype of exit() from zutil.c, example.c, minigzip.c [Truta] -- Add comment in zlib.h for Z_NO_FLUSH parameter to deflate() -- Fix Darwin build version identification [Peterson] - -Changes in 1.2.2 (3 October 2004) -- Update zlib.h comments on gzip in-memory processing -- Set adler to 1 in inflateReset() to support Java test suite [Walles] -- Add contrib/dotzlib [Ravn] -- Update win32/DLL_FAQ.txt [Truta] -- Update contrib/minizip [Vollant] -- Move contrib/visual-basic.txt to old/ [Truta] -- Fix assembler builds in projects/visualc6/ [Truta] - -Changes in 1.2.1.2 (9 September 2004) -- Update INDEX file -- Fix trees.c to update strm->data_type (no one ever noticed!) -- Fix bug in error case in inflate.c, infback.c, and infback9.c [Brown] -- Add "volatile" to crc table flag declaration (for DYNAMIC_CRC_TABLE) -- Add limited multitasking protection to DYNAMIC_CRC_TABLE -- Add NO_vsnprintf for VMS in zutil.h [Mozilla] -- Don't declare strerror() under VMS [Mozilla] -- Add comment to DYNAMIC_CRC_TABLE to use get_crc_table() to initialize -- Update contrib/ada [Anisimkov] -- Update contrib/minizip [Vollant] -- Fix configure to not hardcode directories for Darwin [Peterson] -- Fix gzio.c to not return error on empty files [Brown] -- Fix indentation; update version in contrib/delphi/ZLib.pas and - contrib/pascal/zlibpas.pas [Truta] -- Update mkasm.bat in contrib/masmx86 [Truta] -- Update contrib/untgz [Truta] -- Add projects/README.projects [Truta] -- Add project for MS Visual C++ 6.0 in projects/visualc6 [Cadieux, Truta] -- Update win32/DLL_FAQ.txt [Truta] -- Update list of Z_PREFIX symbols in zconf.h [Randers-Pehrson, Truta] -- Remove an unnecessary assignment to curr in inftrees.c [Truta] -- Add OS/2 to exe builds in configure [Poltorak] -- Remove err dummy parameter in zlib.h [Kientzle] - -Changes in 1.2.1.1 (9 January 2004) -- Update email address in README -- Several FAQ updates -- Fix a big fat bug in inftrees.c that prevented decoding valid - dynamic blocks with only literals and no distance codes -- - Thanks to "Hot Emu" for the bug report and sample file -- Add a note to puff.c on no distance codes case. - -Changes in 1.2.1 (17 November 2003) -- Remove a tab in contrib/gzappend/gzappend.c -- Update some interfaces in contrib for new zlib functions -- Update zlib version number in some contrib entries -- Add Windows CE definition for ptrdiff_t in zutil.h [Mai, Truta] -- Support shared libraries on Hurd and KFreeBSD [Brown] -- Fix error in NO_DIVIDE option of adler32.c - -Changes in 1.2.0.8 (4 November 2003) -- Update version in contrib/delphi/ZLib.pas and contrib/pascal/zlibpas.pas -- Add experimental NO_DIVIDE #define in adler32.c - - Possibly faster on some processors (let me know if it is) -- Correct Z_BLOCK to not return on first inflate call if no wrap -- Fix strm->data_type on inflate() return to correctly indicate EOB -- Add deflatePrime() function for appending in the middle of a byte -- Add contrib/gzappend for an example of appending to a stream -- Update win32/DLL_FAQ.txt [Truta] -- Delete Turbo C comment in README [Truta] -- Improve some indentation in zconf.h [Truta] -- Fix infinite loop on bad input in configure script [Church] -- Fix gzeof() for concatenated gzip files [Johnson] -- Add example to contrib/visual-basic.txt [Michael B.] -- Add -p to mkdir's in Makefile.in [vda] -- Fix configure to properly detect presence or lack of printf functions -- Add AS400 support [Monnerat] -- Add a little Cygwin support [Wilson] - -Changes in 1.2.0.7 (21 September 2003) -- Correct some debug formats in contrib/infback9 -- Cast a type in a debug statement in trees.c -- Change search and replace delimiter in configure from % to # [Beebe] -- Update contrib/untgz to 0.2 with various fixes [Truta] -- Add build support for Amiga [Nikl] -- Remove some directories in old that have been updated to 1.2 -- Add dylib building for Mac OS X in configure and Makefile.in -- Remove old distribution stuff from Makefile -- Update README to point to DLL_FAQ.txt, and add comment on Mac OS X -- Update links in README - -Changes in 1.2.0.6 (13 September 2003) -- Minor FAQ updates -- Update contrib/minizip to 1.00 [Vollant] -- Remove test of gz functions in example.c when GZ_COMPRESS defined [Truta] -- Update POSTINC comment for 68060 [Nikl] -- Add contrib/infback9 with deflate64 decoding (unsupported) -- For MVS define NO_vsnprintf and undefine FAR [van Burik] -- Add pragma for fdopen on MVS [van Burik] - -Changes in 1.2.0.5 (8 September 2003) -- Add OF to inflateBackEnd() declaration in zlib.h -- Remember start when using gzdopen in the middle of a file -- Use internal off_t counters in gz* functions to properly handle seeks -- Perform more rigorous check for distance-too-far in inffast.c -- Add Z_BLOCK flush option to return from inflate at block boundary -- Set strm->data_type on return from inflate - - Indicate bits unused, if at block boundary, and if in last block -- Replace size_t with ptrdiff_t in crc32.c, and check for correct size -- Add condition so old NO_DEFLATE define still works for compatibility -- FAQ update regarding the Windows DLL [Truta] -- INDEX update: add qnx entry, remove aix entry [Truta] -- Install zlib.3 into mandir [Wilson] -- Move contrib/zlib_dll_FAQ.txt to win32/DLL_FAQ.txt; update [Truta] -- Adapt the zlib interface to the new DLL convention guidelines [Truta] -- Introduce ZLIB_WINAPI macro to allow the export of functions using - the WINAPI calling convention, for Visual Basic [Vollant, Truta] -- Update msdos and win32 scripts and makefiles [Truta] -- Export symbols by name, not by ordinal, in win32/zlib.def [Truta] -- Add contrib/ada [Anisimkov] -- Move asm files from contrib/vstudio/vc70_32 to contrib/asm386 [Truta] -- Rename contrib/asm386 to contrib/masmx86 [Truta, Vollant] -- Add contrib/masm686 [Truta] -- Fix offsets in contrib/inflate86 and contrib/masmx86/inffas32.asm - [Truta, Vollant] -- Update contrib/delphi; rename to contrib/pascal; add example [Truta] -- Remove contrib/delphi2; add a new contrib/delphi [Truta] -- Avoid inclusion of the nonstandard in contrib/iostream, - and fix some method prototypes [Truta] -- Fix the ZCR_SEED2 constant to avoid warnings in contrib/minizip - [Truta] -- Avoid the use of backslash (\) in contrib/minizip [Vollant] -- Fix file time handling in contrib/untgz; update makefiles [Truta] -- Update contrib/vstudio/vc70_32 to comply with the new DLL guidelines - [Vollant] -- Remove contrib/vstudio/vc15_16 [Vollant] -- Rename contrib/vstudio/vc70_32 to contrib/vstudio/vc7 [Truta] -- Update README.contrib [Truta] -- Invert the assignment order of match_head and s->prev[...] in - INSERT_STRING [Truta] -- Compare TOO_FAR with 32767 instead of 32768, to avoid 16-bit warnings - [Truta] -- Compare function pointers with 0, not with NULL or Z_NULL [Truta] -- Fix prototype of syncsearch in inflate.c [Truta] -- Introduce ASMINF macro to be enabled when using an ASM implementation - of inflate_fast [Truta] -- Change NO_DEFLATE to NO_GZCOMPRESS [Truta] -- Modify test_gzio in example.c to take a single file name as a - parameter [Truta] -- Exit the example.c program if gzopen fails [Truta] -- Add type casts around strlen in example.c [Truta] -- Remove casting to sizeof in minigzip.c; give a proper type - to the variable compared with SUFFIX_LEN [Truta] -- Update definitions of STDC and STDC99 in zconf.h [Truta] -- Synchronize zconf.h with the new Windows DLL interface [Truta] -- Use SYS16BIT instead of __32BIT__ to distinguish between - 16- and 32-bit platforms [Truta] -- Use far memory allocators in small 16-bit memory models for - Turbo C [Truta] -- Add info about the use of ASMV, ASMINF and ZLIB_WINAPI in - zlibCompileFlags [Truta] -- Cygwin has vsnprintf [Wilson] -- In Windows16, OS_CODE is 0, as in MSDOS [Truta] -- In Cygwin, OS_CODE is 3 (Unix), not 11 (Windows32) [Wilson] - -Changes in 1.2.0.4 (10 August 2003) -- Minor FAQ updates -- Be more strict when checking inflateInit2's windowBits parameter -- Change NO_GUNZIP compile option to NO_GZIP to cover deflate as well -- Add gzip wrapper option to deflateInit2 using windowBits -- Add updated QNX rule in configure and qnx directory [Bonnefoy] -- Make inflate distance-too-far checks more rigorous -- Clean up FAR usage in inflate -- Add casting to sizeof() in gzio.c and minigzip.c - -Changes in 1.2.0.3 (19 July 2003) -- Fix silly error in gzungetc() implementation [Vollant] -- Update contrib/minizip and contrib/vstudio [Vollant] -- Fix printf format in example.c -- Correct cdecl support in zconf.in.h [Anisimkov] -- Minor FAQ updates - -Changes in 1.2.0.2 (13 July 2003) -- Add ZLIB_VERNUM in zlib.h for numerical preprocessor comparisons -- Attempt to avoid warnings in crc32.c for pointer-int conversion -- Add AIX to configure, remove aix directory [Bakker] -- Add some casts to minigzip.c -- Improve checking after insecure sprintf() or vsprintf() calls -- Remove #elif's from crc32.c -- Change leave label to inf_leave in inflate.c and infback.c to avoid - library conflicts -- Remove inflate gzip decoding by default--only enable gzip decoding by - special request for stricter backward compatibility -- Add zlibCompileFlags() function to return compilation information -- More typecasting in deflate.c to avoid warnings -- Remove leading underscore from _Capital #defines [Truta] -- Fix configure to link shared library when testing -- Add some Windows CE target adjustments [Mai] -- Remove #define ZLIB_DLL in zconf.h [Vollant] -- Add zlib.3 [Rodgers] -- Update RFC URL in deflate.c and algorithm.txt [Mai] -- Add zlib_dll_FAQ.txt to contrib [Truta] -- Add UL to some constants [Truta] -- Update minizip and vstudio [Vollant] -- Remove vestigial NEED_DUMMY_RETURN from zconf.in.h -- Expand use of NO_DUMMY_DECL to avoid all dummy structures -- Added iostream3 to contrib [Schwardt] -- Replace rewind() with fseek() for WinCE [Truta] -- Improve setting of zlib format compression level flags - - Report 0 for huffman and rle strategies and for level == 0 or 1 - - Report 2 only for level == 6 -- Only deal with 64K limit when necessary at compile time [Truta] -- Allow TOO_FAR check to be turned off at compile time [Truta] -- Add gzclearerr() function [Souza] -- Add gzungetc() function - -Changes in 1.2.0.1 (17 March 2003) -- Add Z_RLE strategy for run-length encoding [Truta] - - When Z_RLE requested, restrict matches to distance one - - Update zlib.h, minigzip.c, gzopen(), gzdopen() for Z_RLE -- Correct FASTEST compilation to allow level == 0 -- Clean up what gets compiled for FASTEST -- Incorporate changes to zconf.in.h [Vollant] - - Refine detection of Turbo C need for dummy returns - - Refine ZLIB_DLL compilation - - Include additional header file on VMS for off_t typedef -- Try to use _vsnprintf where it supplants vsprintf [Vollant] -- Add some casts in inffast.c -- Enchance comments in zlib.h on what happens if gzprintf() tries to - write more than 4095 bytes before compression -- Remove unused state from inflateBackEnd() -- Remove exit(0) from minigzip.c, example.c -- Get rid of all those darn tabs -- Add "check" target to Makefile.in that does the same thing as "test" -- Add "mostlyclean" and "maintainer-clean" targets to Makefile.in -- Update contrib/inflate86 [Anderson] -- Update contrib/testzlib, contrib/vstudio, contrib/minizip [Vollant] -- Add msdos and win32 directories with makefiles [Truta] -- More additions and improvements to the FAQ - -Changes in 1.2.0 (9 March 2003) -- New and improved inflate code - - About 20% faster - - Does not allocate 32K window unless and until needed - - Automatically detects and decompresses gzip streams - - Raw inflate no longer needs an extra dummy byte at end - - Added inflateBack functions using a callback interface--even faster - than inflate, useful for file utilities (gzip, zip) - - Added inflateCopy() function to record state for random access on - externally generated deflate streams (e.g. in gzip files) - - More readable code (I hope) -- New and improved crc32() - - About 50% faster, thanks to suggestions from Rodney Brown -- Add deflateBound() and compressBound() functions -- Fix memory leak in deflateInit2() -- Permit setting dictionary for raw deflate (for parallel deflate) -- Fix const declaration for gzwrite() -- Check for some malloc() failures in gzio.c -- Fix bug in gzopen() on single-byte file 0x1f -- Fix bug in gzread() on concatenated file with 0x1f at end of buffer - and next buffer doesn't start with 0x8b -- Fix uncompress() to return Z_DATA_ERROR on truncated input -- Free memory at end of example.c -- Remove MAX #define in trees.c (conflicted with some libraries) -- Fix static const's in deflate.c, gzio.c, and zutil.[ch] -- Declare malloc() and free() in gzio.c if STDC not defined -- Use malloc() instead of calloc() in zutil.c if int big enough -- Define STDC for AIX -- Add aix/ with approach for compiling shared library on AIX -- Add HP-UX support for shared libraries in configure -- Add OpenUNIX support for shared libraries in configure -- Use $cc instead of gcc to build shared library -- Make prefix directory if needed when installing -- Correct Macintosh avoidance of typedef Byte in zconf.h -- Correct Turbo C memory allocation when under Linux -- Use libz.a instead of -lz in Makefile (assure use of compiled library) -- Update configure to check for snprintf or vsnprintf functions and their - return value, warn during make if using an insecure function -- Fix configure problem with compile-time knowledge of HAVE_UNISTD_H that - is lost when library is used--resolution is to build new zconf.h -- Documentation improvements (in zlib.h): - - Document raw deflate and inflate - - Update RFCs URL - - Point out that zlib and gzip formats are different - - Note that Z_BUF_ERROR is not fatal - - Document string limit for gzprintf() and possible buffer overflow - - Note requirement on avail_out when flushing - - Note permitted values of flush parameter of inflate() -- Add some FAQs (and even answers) to the FAQ -- Add contrib/inflate86/ for x86 faster inflate -- Add contrib/blast/ for PKWare Data Compression Library decompression -- Add contrib/puff/ simple inflate for deflate format description - -Changes in 1.1.4 (11 March 2002) -- ZFREE was repeated on same allocation on some error conditions. - This creates a security problem described in - http://www.zlib.org/advisory-2002-03-11.txt -- Returned incorrect error (Z_MEM_ERROR) on some invalid data -- Avoid accesses before window for invalid distances with inflate window - less than 32K. -- force windowBits > 8 to avoid a bug in the encoder for a window size - of 256 bytes. (A complete fix will be available in 1.1.5). - -Changes in 1.1.3 (9 July 1998) -- fix "an inflate input buffer bug that shows up on rare but persistent - occasions" (Mark) -- fix gzread and gztell for concatenated .gz files (Didier Le Botlan) -- fix gzseek(..., SEEK_SET) in write mode -- fix crc check after a gzeek (Frank Faubert) -- fix miniunzip when the last entry in a zip file is itself a zip file - (J Lillge) -- add contrib/asm586 and contrib/asm686 (Brian Raiter) - See http://www.muppetlabs.com/~breadbox/software/assembly.html -- add support for Delphi 3 in contrib/delphi (Bob Dellaca) -- add support for C++Builder 3 and Delphi 3 in contrib/delphi2 (Davide Moretti) -- do not exit prematurely in untgz if 0 at start of block (Magnus Holmgren) -- use macro EXTERN instead of extern to support DLL for BeOS (Sander Stoks) -- added a FAQ file - -- Support gzdopen on Mac with Metrowerks (Jason Linhart) -- Do not redefine Byte on Mac (Brad Pettit & Jason Linhart) -- define SEEK_END too if SEEK_SET is not defined (Albert Chin-A-Young) -- avoid some warnings with Borland C (Tom Tanner) -- fix a problem in contrib/minizip/zip.c for 16-bit MSDOS (Gilles Vollant) -- emulate utime() for WIN32 in contrib/untgz (Gilles Vollant) -- allow several arguments to configure (Tim Mooney, Frodo Looijaard) -- use libdir and includedir in Makefile.in (Tim Mooney) -- support shared libraries on OSF1 V4 (Tim Mooney) -- remove so_locations in "make clean" (Tim Mooney) -- fix maketree.c compilation error (Glenn, Mark) -- Python interface to zlib now in Python 1.5 (Jeremy Hylton) -- new Makefile.riscos (Rich Walker) -- initialize static descriptors in trees.c for embedded targets (Nick Smith) -- use "foo-gz" in example.c for RISCOS and VMS (Nick Smith) -- add the OS/2 files in Makefile.in too (Andrew Zabolotny) -- fix fdopen and halloc macros for Microsoft C 6.0 (Tom Lane) -- fix maketree.c to allow clean compilation of inffixed.h (Mark) -- fix parameter check in deflateCopy (Gunther Nikl) -- cleanup trees.c, use compressed_len only in debug mode (Christian Spieler) -- Many portability patches by Christian Spieler: - . zutil.c, zutil.h: added "const" for zmem* - . Make_vms.com: fixed some typos - . Make_vms.com: msdos/Makefile.*: removed zutil.h from some dependency lists - . msdos/Makefile.msc: remove "default rtl link library" info from obj files - . msdos/Makefile.*: use model-dependent name for the built zlib library - . msdos/Makefile.emx, nt/Makefile.emx, nt/Makefile.gcc: - new makefiles, for emx (DOS/OS2), emx&rsxnt and mingw32 (Windows 9x / NT) -- use define instead of typedef for Bytef also for MSC small/medium (Tom Lane) -- replace __far with _far for better portability (Christian Spieler, Tom Lane) -- fix test for errno.h in configure (Tim Newsham) - -Changes in 1.1.2 (19 March 98) -- added contrib/minzip, mini zip and unzip based on zlib (Gilles Vollant) - See http://www.winimage.com/zLibDll/unzip.html -- preinitialize the inflate tables for fixed codes, to make the code - completely thread safe (Mark) -- some simplifications and slight speed-up to the inflate code (Mark) -- fix gzeof on non-compressed files (Allan Schrum) -- add -std1 option in configure for OSF1 to fix gzprintf (Martin Mokrejs) -- use default value of 4K for Z_BUFSIZE for 16-bit MSDOS (Tim Wegner + Glenn) -- added os2/Makefile.def and os2/zlib.def (Andrew Zabolotny) -- add shared lib support for UNIX_SV4.2MP (MATSUURA Takanori) -- do not wrap extern "C" around system includes (Tom Lane) -- mention zlib binding for TCL in README (Andreas Kupries) -- added amiga/Makefile.pup for Amiga powerUP SAS/C PPC (Andreas Kleinert) -- allow "make install prefix=..." even after configure (Glenn Randers-Pehrson) -- allow "configure --prefix $HOME" (Tim Mooney) -- remove warnings in example.c and gzio.c (Glenn Randers-Pehrson) -- move Makefile.sas to amiga/Makefile.sas - -Changes in 1.1.1 (27 Feb 98) -- fix macros _tr_tally_* in deflate.h for debug mode (Glenn Randers-Pehrson) -- remove block truncation heuristic which had very marginal effect for zlib - (smaller lit_bufsize than in gzip 1.2.4) and degraded a little the - compression ratio on some files. This also allows inlining _tr_tally for - matches in deflate_slow. -- added msdos/Makefile.w32 for WIN32 Microsoft Visual C++ (Bob Frazier) - -Changes in 1.1.0 (24 Feb 98) -- do not return STREAM_END prematurely in inflate (John Bowler) -- revert to the zlib 1.0.8 inflate to avoid the gcc 2.8.0 bug (Jeremy Buhler) -- compile with -DFASTEST to get compression code optimized for speed only -- in minigzip, try mmap'ing the input file first (Miguel Albrecht) -- increase size of I/O buffers in minigzip.c and gzio.c (not a big gain - on Sun but significant on HP) - -- add a pointer to experimental unzip library in README (Gilles Vollant) -- initialize variable gcc in configure (Chris Herborth) - -Changes in 1.0.9 (17 Feb 1998) -- added gzputs and gzgets functions -- do not clear eof flag in gzseek (Mark Diekhans) -- fix gzseek for files in transparent mode (Mark Diekhans) -- do not assume that vsprintf returns the number of bytes written (Jens Krinke) -- replace EXPORT with ZEXPORT to avoid conflict with other programs -- added compress2 in zconf.h, zlib.def, zlib.dnt -- new asm code from Gilles Vollant in contrib/asm386 -- simplify the inflate code (Mark): - . Replace ZALLOC's in huft_build() with single ZALLOC in inflate_blocks_new() - . ZALLOC the length list in inflate_trees_fixed() instead of using stack - . ZALLOC the value area for huft_build() instead of using stack - . Simplify Z_FINISH check in inflate() - -- Avoid gcc 2.8.0 comparison bug a little differently than zlib 1.0.8 -- in inftrees.c, avoid cc -O bug on HP (Farshid Elahi) -- in zconf.h move the ZLIB_DLL stuff earlier to avoid problems with - the declaration of FAR (Gilles VOllant) -- install libz.so* with mode 755 (executable) instead of 644 (Marc Lehmann) -- read_buf buf parameter of type Bytef* instead of charf* -- zmemcpy parameters are of type Bytef*, not charf* (Joseph Strout) -- do not redeclare unlink in minigzip.c for WIN32 (John Bowler) -- fix check for presence of directories in "make install" (Ian Willis) - -Changes in 1.0.8 (27 Jan 1998) -- fixed offsets in contrib/asm386/gvmat32.asm (Gilles Vollant) -- fix gzgetc and gzputc for big endian systems (Markus Oberhumer) -- added compress2() to allow setting the compression level -- include sys/types.h to get off_t on some systems (Marc Lehmann & QingLong) -- use constant arrays for the static trees in trees.c instead of computing - them at run time (thanks to Ken Raeburn for this suggestion). To create - trees.h, compile with GEN_TREES_H and run "make test". -- check return code of example in "make test" and display result -- pass minigzip command line options to file_compress -- simplifying code of inflateSync to avoid gcc 2.8 bug - -- support CC="gcc -Wall" in configure -s (QingLong) -- avoid a flush caused by ftell in gzopen for write mode (Ken Raeburn) -- fix test for shared library support to avoid compiler warnings -- zlib.lib -> zlib.dll in msdos/zlib.rc (Gilles Vollant) -- check for TARGET_OS_MAC in addition to MACOS (Brad Pettit) -- do not use fdopen for Metrowerks on Mac (Brad Pettit)) -- add checks for gzputc and gzputc in example.c -- avoid warnings in gzio.c and deflate.c (Andreas Kleinert) -- use const for the CRC table (Ken Raeburn) -- fixed "make uninstall" for shared libraries -- use Tracev instead of Trace in infblock.c -- in example.c use correct compressed length for test_sync -- suppress +vnocompatwarnings in configure for HPUX (not always supported) - -Changes in 1.0.7 (20 Jan 1998) -- fix gzseek which was broken in write mode -- return error for gzseek to negative absolute position -- fix configure for Linux (Chun-Chung Chen) -- increase stack space for MSC (Tim Wegner) -- get_crc_table and inflateSyncPoint are EXPORTed (Gilles Vollant) -- define EXPORTVA for gzprintf (Gilles Vollant) -- added man page zlib.3 (Rick Rodgers) -- for contrib/untgz, fix makedir() and improve Makefile - -- check gzseek in write mode in example.c -- allocate extra buffer for seeks only if gzseek is actually called -- avoid signed/unsigned comparisons (Tim Wegner, Gilles Vollant) -- add inflateSyncPoint in zconf.h -- fix list of exported functions in nt/zlib.dnt and mdsos/zlib.def - -Changes in 1.0.6 (19 Jan 1998) -- add functions gzprintf, gzputc, gzgetc, gztell, gzeof, gzseek, gzrewind and - gzsetparams (thanks to Roland Giersig and Kevin Ruland for some of this code) -- Fix a deflate bug occurring only with compression level 0 (thanks to - Andy Buckler for finding this one). -- In minigzip, pass transparently also the first byte for .Z files. -- return Z_BUF_ERROR instead of Z_OK if output buffer full in uncompress() -- check Z_FINISH in inflate (thanks to Marc Schluper) -- Implement deflateCopy (thanks to Adam Costello) -- make static libraries by default in configure, add --shared option. -- move MSDOS or Windows specific files to directory msdos -- suppress the notion of partial flush to simplify the interface - (but the symbol Z_PARTIAL_FLUSH is kept for compatibility with 1.0.4) -- suppress history buffer provided by application to simplify the interface - (this feature was not implemented anyway in 1.0.4) -- next_in and avail_in must be initialized before calling inflateInit or - inflateInit2 -- add EXPORT in all exported functions (for Windows DLL) -- added Makefile.nt (thanks to Stephen Williams) -- added the unsupported "contrib" directory: - contrib/asm386/ by Gilles Vollant - 386 asm code replacing longest_match(). - contrib/iostream/ by Kevin Ruland - A C++ I/O streams interface to the zlib gz* functions - contrib/iostream2/ by Tyge Løvset - Another C++ I/O streams interface - contrib/untgz/ by "Pedro A. Aranda Guti\irrez" - A very simple tar.gz file extractor using zlib - contrib/visual-basic.txt by Carlos Rios - How to use compress(), uncompress() and the gz* functions from VB. -- pass params -f (filtered data), -h (huffman only), -1 to -9 (compression - level) in minigzip (thanks to Tom Lane) - -- use const for rommable constants in deflate -- added test for gzseek and gztell in example.c -- add undocumented function inflateSyncPoint() (hack for Paul Mackerras) -- add undocumented function zError to convert error code to string - (for Tim Smithers) -- Allow compilation of gzio with -DNO_DEFLATE to avoid the compression code. -- Use default memcpy for Symantec MSDOS compiler. -- Add EXPORT keyword for check_func (needed for Windows DLL) -- add current directory to LD_LIBRARY_PATH for "make test" -- create also a link for libz.so.1 -- added support for FUJITSU UXP/DS (thanks to Toshiaki Nomura) -- use $(SHAREDLIB) instead of libz.so in Makefile.in (for HPUX) -- added -soname for Linux in configure (Chun-Chung Chen, -- assign numbers to the exported functions in zlib.def (for Windows DLL) -- add advice in zlib.h for best usage of deflateSetDictionary -- work around compiler bug on Atari (cast Z_NULL in call of s->checkfn) -- allow compilation with ANSI keywords only enabled for TurboC in large model -- avoid "versionString"[0] (Borland bug) -- add NEED_DUMMY_RETURN for Borland -- use variable z_verbose for tracing in debug mode (L. Peter Deutsch). -- allow compilation with CC -- defined STDC for OS/2 (David Charlap) -- limit external names to 8 chars for MVS (Thomas Lund) -- in minigzip.c, use static buffers only for 16-bit systems -- fix suffix check for "minigzip -d foo.gz" -- do not return an error for the 2nd of two consecutive gzflush() (Felix Lee) -- use _fdopen instead of fdopen for MSC >= 6.0 (Thomas Fanslau) -- added makelcc.bat for lcc-win32 (Tom St Denis) -- in Makefile.dj2, use copy and del instead of install and rm (Frank Donahoe) -- Avoid expanded $Id$. Use "rcs -kb" or "cvs admin -kb" to avoid Id expansion. -- check for unistd.h in configure (for off_t) -- remove useless check parameter in inflate_blocks_free -- avoid useless assignment of s->check to itself in inflate_blocks_new -- do not flush twice in gzclose (thanks to Ken Raeburn) -- rename FOPEN as F_OPEN to avoid clash with /usr/include/sys/file.h -- use NO_ERRNO_H instead of enumeration of operating systems with errno.h -- work around buggy fclose on pipes for HP/UX -- support zlib DLL with BORLAND C++ 5.0 (thanks to Glenn Randers-Pehrson) -- fix configure if CC is already equal to gcc - -Changes in 1.0.5 (3 Jan 98) -- Fix inflate to terminate gracefully when fed corrupted or invalid data -- Use const for rommable constants in inflate -- Eliminate memory leaks on error conditions in inflate -- Removed some vestigial code in inflate -- Update web address in README - -Changes in 1.0.4 (24 Jul 96) -- In very rare conditions, deflate(s, Z_FINISH) could fail to produce an EOF - bit, so the decompressor could decompress all the correct data but went - on to attempt decompressing extra garbage data. This affected minigzip too. -- zlibVersion and gzerror return const char* (needed for DLL) -- port to RISCOS (no fdopen, no multiple dots, no unlink, no fileno) -- use z_error only for DEBUG (avoid problem with DLLs) - -Changes in 1.0.3 (2 Jul 96) -- use z_streamp instead of z_stream *, which is now a far pointer in MSDOS - small and medium models; this makes the library incompatible with previous - versions for these models. (No effect in large model or on other systems.) -- return OK instead of BUF_ERROR if previous deflate call returned with - avail_out as zero but there is nothing to do -- added memcmp for non STDC compilers -- define NO_DUMMY_DECL for more Mac compilers (.h files merged incorrectly) -- define __32BIT__ if __386__ or i386 is defined (pb. with Watcom and SCO) -- better check for 16-bit mode MSC (avoids problem with Symantec) - -Changes in 1.0.2 (23 May 96) -- added Windows DLL support -- added a function zlibVersion (for the DLL support) -- fixed declarations using Bytef in infutil.c (pb with MSDOS medium model) -- Bytef is define's instead of typedef'd only for Borland C -- avoid reading uninitialized memory in example.c -- mention in README that the zlib format is now RFC1950 -- updated Makefile.dj2 -- added algorithm.doc - -Changes in 1.0.1 (20 May 96) [1.0 skipped to avoid confusion] -- fix array overlay in deflate.c which sometimes caused bad compressed data -- fix inflate bug with empty stored block -- fix MSDOS medium model which was broken in 0.99 -- fix deflateParams() which could generated bad compressed data. -- Bytef is define'd instead of typedef'ed (work around Borland bug) -- added an INDEX file -- new makefiles for DJGPP (Makefile.dj2), 32-bit Borland (Makefile.b32), - Watcom (Makefile.wat), Amiga SAS/C (Makefile.sas) -- speed up adler32 for modern machines without auto-increment -- added -ansi for IRIX in configure -- static_init_done in trees.c is an int -- define unlink as delete for VMS -- fix configure for QNX -- add configure branch for SCO and HPUX -- avoid many warnings (unused variables, dead assignments, etc...) -- no fdopen for BeOS -- fix the Watcom fix for 32 bit mode (define FAR as empty) -- removed redefinition of Byte for MKWERKS -- work around an MWKERKS bug (incorrect merge of all .h files) - -Changes in 0.99 (27 Jan 96) -- allow preset dictionary shared between compressor and decompressor -- allow compression level 0 (no compression) -- add deflateParams in zlib.h: allow dynamic change of compression level - and compression strategy. -- test large buffers and deflateParams in example.c -- add optional "configure" to build zlib as a shared library -- suppress Makefile.qnx, use configure instead -- fixed deflate for 64-bit systems (detected on Cray) -- fixed inflate_blocks for 64-bit systems (detected on Alpha) -- declare Z_DEFLATED in zlib.h (possible parameter for deflateInit2) -- always return Z_BUF_ERROR when deflate() has nothing to do -- deflateInit and inflateInit are now macros to allow version checking -- prefix all global functions and types with z_ with -DZ_PREFIX -- make falloc completely reentrant (inftrees.c) -- fixed very unlikely race condition in ct_static_init -- free in reverse order of allocation to help memory manager -- use zlib-1.0/* instead of zlib/* inside the tar.gz -- make zlib warning-free with "gcc -O3 -Wall -Wwrite-strings -Wpointer-arith - -Wconversion -Wstrict-prototypes -Wmissing-prototypes" -- allow gzread on concatenated .gz files -- deflateEnd now returns Z_DATA_ERROR if it was premature -- deflate is finally (?) fully deterministic (no matches beyond end of input) -- Document Z_SYNC_FLUSH -- add uninstall in Makefile -- Check for __cpluplus in zlib.h -- Better test in ct_align for partial flush -- avoid harmless warnings for Borland C++ -- initialize hash_head in deflate.c -- avoid warning on fdopen (gzio.c) for HP cc -Aa -- include stdlib.h for STDC compilers -- include errno.h for Cray -- ignore error if ranlib doesn't exist -- call ranlib twice for NeXTSTEP -- use exec_prefix instead of prefix for libz.a -- renamed ct_* as _tr_* to avoid conflict with applications -- clear z->msg in inflateInit2 before any error return -- initialize opaque in example.c, gzio.c, deflate.c and inflate.c -- fixed typo in zconf.h (_GNUC__ => __GNUC__) -- check for WIN32 in zconf.h and zutil.c (avoid farmalloc in 32-bit mode) -- fix typo in Make_vms.com (f$trnlnm -> f$getsyi) -- in fcalloc, normalize pointer if size > 65520 bytes -- don't use special fcalloc for 32 bit Borland C++ -- use STDC instead of __GO32__ to avoid redeclaring exit, calloc, etc... -- use Z_BINARY instead of BINARY -- document that gzclose after gzdopen will close the file -- allow "a" as mode in gzopen. -- fix error checking in gzread -- allow skipping .gz extra-field on pipes -- added reference to Perl interface in README -- put the crc table in FAR data (I dislike more and more the medium model :) -- added get_crc_table -- added a dimension to all arrays (Borland C can't count). -- workaround Borland C bug in declaration of inflate_codes_new & inflate_fast -- guard against multiple inclusion of *.h (for precompiled header on Mac) -- Watcom C pretends to be Microsoft C small model even in 32 bit mode. -- don't use unsized arrays to avoid silly warnings by Visual C++: - warning C4746: 'inflate_mask' : unsized array treated as '__far' - (what's wrong with far data in far model?). -- define enum out of inflate_blocks_state to allow compilation with C++ - -Changes in 0.95 (16 Aug 95) -- fix MSDOS small and medium model (now easier to adapt to any compiler) -- inlined send_bits -- fix the final (:-) bug for deflate with flush (output was correct but - not completely flushed in rare occasions). -- default window size is same for compression and decompression - (it's now sufficient to set MAX_WBITS in zconf.h). -- voidp -> voidpf and voidnp -> voidp (for consistency with other - typedefs and because voidnp was not near in large model). - -Changes in 0.94 (13 Aug 95) -- support MSDOS medium model -- fix deflate with flush (could sometimes generate bad output) -- fix deflateReset (zlib header was incorrectly suppressed) -- added support for VMS -- allow a compression level in gzopen() -- gzflush now calls fflush -- For deflate with flush, flush even if no more input is provided. -- rename libgz.a as libz.a -- avoid complex expression in infcodes.c triggering Turbo C bug -- work around a problem with gcc on Alpha (in INSERT_STRING) -- don't use inline functions (problem with some gcc versions) -- allow renaming of Byte, uInt, etc... with #define. -- avoid warning about (unused) pointer before start of array in deflate.c -- avoid various warnings in gzio.c, example.c, infblock.c, adler32.c, zutil.c -- avoid reserved word 'new' in trees.c - -Changes in 0.93 (25 June 95) -- temporarily disable inline functions -- make deflate deterministic -- give enough lookahead for PARTIAL_FLUSH -- Set binary mode for stdin/stdout in minigzip.c for OS/2 -- don't even use signed char in inflate (not portable enough) -- fix inflate memory leak for segmented architectures - -Changes in 0.92 (3 May 95) -- don't assume that char is signed (problem on SGI) -- Clear bit buffer when starting a stored block -- no memcpy on Pyramid -- suppressed inftest.c -- optimized fill_window, put longest_match inline for gcc -- optimized inflate on stored blocks. -- untabify all sources to simplify patches - -Changes in 0.91 (2 May 95) -- Default MEM_LEVEL is 8 (not 9 for Unix) as documented in zlib.h -- Document the memory requirements in zconf.h -- added "make install" -- fix sync search logic in inflateSync -- deflate(Z_FULL_FLUSH) now works even if output buffer too short -- after inflateSync, don't scare people with just "lo world" -- added support for DJGPP - -Changes in 0.9 (1 May 95) -- don't assume that zalloc clears the allocated memory (the TurboC bug - was Mark's bug after all :) -- let again gzread copy uncompressed data unchanged (was working in 0.71) -- deflate(Z_FULL_FLUSH), inflateReset and inflateSync are now fully implemented -- added a test of inflateSync in example.c -- moved MAX_WBITS to zconf.h because users might want to change that. -- document explicitly that zalloc(64K) on MSDOS must return a normalized - pointer (zero offset) -- added Makefiles for Microsoft C, Turbo C, Borland C++ -- faster crc32() - -Changes in 0.8 (29 April 95) -- added fast inflate (inffast.c) -- deflate(Z_FINISH) now returns Z_STREAM_END when done. Warning: this - is incompatible with previous versions of zlib which returned Z_OK. -- work around a TurboC compiler bug (bad code for b << 0, see infutil.h) - (actually that was not a compiler bug, see 0.81 above) -- gzread no longer reads one extra byte in certain cases -- In gzio destroy(), don't reference a freed structure -- avoid many warnings for MSDOS -- avoid the ERROR symbol which is used by MS Windows - -Changes in 0.71 (14 April 95) -- Fixed more MSDOS compilation problems :( There is still a bug with - TurboC large model. - -Changes in 0.7 (14 April 95) -- Added full inflate support. -- Simplified the crc32() interface. The pre- and post-conditioning - (one's complement) is now done inside crc32(). WARNING: this is - incompatible with previous versions; see zlib.h for the new usage. - -Changes in 0.61 (12 April 95) -- workaround for a bug in TurboC. example and minigzip now work on MSDOS. - -Changes in 0.6 (11 April 95) -- added minigzip.c -- added gzdopen to reopen a file descriptor as gzFile -- added transparent reading of non-gziped files in gzread. -- fixed bug in gzread (don't read crc as data) -- fixed bug in destroy (gzio.c) (don't return Z_STREAM_END for gzclose). -- don't allocate big arrays in the stack (for MSDOS) -- fix some MSDOS compilation problems - -Changes in 0.5: -- do real compression in deflate.c. Z_PARTIAL_FLUSH is supported but - not yet Z_FULL_FLUSH. -- support decompression but only in a single step (forced Z_FINISH) -- added opaque object for zalloc and zfree. -- added deflateReset and inflateReset -- added a variable zlib_version for consistency checking. -- renamed the 'filter' parameter of deflateInit2 as 'strategy'. - Added Z_FILTERED and Z_HUFFMAN_ONLY constants. - -Changes in 0.4: -- avoid "zip" everywhere, use zlib instead of ziplib. -- suppress Z_BLOCK_FLUSH, interpret Z_PARTIAL_FLUSH as block flush - if compression method == 8. -- added adler32 and crc32 -- renamed deflateOptions as deflateInit2, call one or the other but not both -- added the method parameter for deflateInit2. -- added inflateInit2 -- simplied considerably deflateInit and inflateInit by not supporting - user-provided history buffer. This is supported only in deflateInit2 - and inflateInit2. - -Changes in 0.3: -- prefix all macro names with Z_ -- use Z_FINISH instead of deflateEnd to finish compression. -- added Z_HUFFMAN_ONLY -- added gzerror() + + ChangeLog file for zlib + +Changes in 1.2.7 (2 May 2012) +- Replace use of memmove() with a simple copy for portability +- Test for existence of strerror +- Restore gzgetc_ for backward compatibility with 1.2.6 +- Fix build with non-GNU make on Solaris +- Require gcc 4.0 or later on Mac OS X to use the hidden attribute +- Include unistd.h for Watcom C +- Use __WATCOMC__ instead of __WATCOM__ +- Do not use the visibility attribute if NO_VIZ defined +- Improve the detection of no hidden visibility attribute +- Avoid using __int64 for gcc or solo compilation +- Cast to char * in gzprintf to avoid warnings [Zinser] +- Fix make_vms.com for VAX [Zinser] +- Don't use library or built-in byte swaps +- Simplify test and use of gcc hidden attribute +- Fix bug in gzclose_w() when gzwrite() fails to allocate memory +- Add "x" (O_EXCL) and "e" (O_CLOEXEC) modes support to gzopen() +- Fix bug in test/minigzip.c for configure --solo +- Fix contrib/vstudio project link errors [Mohanathas] +- Add ability to choose the builder in make_vms.com [Schweda] +- Add DESTDIR support to mingw32 win32/Makefile.gcc +- Fix comments in win32/Makefile.gcc for proper usage +- Allow overriding the default install locations for cmake +- Generate and install the pkg-config file with cmake +- Build both a static and a shared version of zlib with cmake +- Include version symbols for cmake builds +- If using cmake with MSVC, add the source directory to the includes +- Remove unneeded EXTRA_CFLAGS from win32/Makefile.gcc [Truta] +- Move obsolete emx makefile to old [Truta] +- Allow the use of -Wundef when compiling or using zlib +- Avoid the use of the -u option with mktemp +- Improve inflate() documentation on the use of Z_FINISH +- Recognize clang as gcc +- Add gzopen_w() in Windows for wide character path names +- Rename zconf.h in CMakeLists.txt to move it out of the way +- Add source directory in CMakeLists.txt for building examples +- Look in build directory for zlib.pc in CMakeLists.txt +- Remove gzflags from zlibvc.def in vc9 and vc10 +- Fix contrib/minizip compilation in the MinGW environment +- Update ./configure for Solaris, support --64 [Mooney] +- Remove -R. from Solaris shared build (possible security issue) +- Avoid race condition for parallel make (-j) running example +- Fix type mismatch between get_crc_table() and crc_table +- Fix parsing of version with "-" in CMakeLists.txt [Snider, Ziegler] +- Fix the path to zlib.map in CMakeLists.txt +- Force the native libtool in Mac OS X to avoid GNU libtool [Beebe] +- Add instructions to win32/Makefile.gcc for shared install [Torri] + +Changes in 1.2.6.1 (12 Feb 2012) +- Avoid the use of the Objective-C reserved name "id" +- Include io.h in gzguts.h for Microsoft compilers +- Fix problem with ./configure --prefix and gzgetc macro +- Include gz_header definition when compiling zlib solo +- Put gzflags() functionality back in zutil.c +- Avoid library header include in crc32.c for Z_SOLO +- Use name in GCC_CLASSIC as C compiler for coverage testing, if set +- Minor cleanup in contrib/minizip/zip.c [Vollant] +- Update make_vms.com [Zinser] +- Remove unnecessary gzgetc_ function +- Use optimized byte swap operations for Microsoft and GNU [Snyder] +- Fix minor typo in zlib.h comments [Rzesniowiecki] + +Changes in 1.2.6 (29 Jan 2012) +- Update the Pascal interface in contrib/pascal +- Fix function numbers for gzgetc_ in zlibvc.def files +- Fix configure.ac for contrib/minizip [Schiffer] +- Fix large-entry detection in minizip on 64-bit systems [Schiffer] +- Have ./configure use the compiler return code for error indication +- Fix CMakeLists.txt for cross compilation [McClure] +- Fix contrib/minizip/zip.c for 64-bit architectures [Dalsnes] +- Fix compilation of contrib/minizip on FreeBSD [Marquez] +- Correct suggested usages in win32/Makefile.msc [Shachar, Horvath] +- Include io.h for Turbo C / Borland C on all platforms [Truta] +- Make version explicit in contrib/minizip/configure.ac [Bosmans] +- Avoid warning for no encryption in contrib/minizip/zip.c [Vollant] +- Minor cleanup up contrib/minizip/unzip.c [Vollant] +- Fix bug when compiling minizip with C++ [Vollant] +- Protect for long name and extra fields in contrib/minizip [Vollant] +- Avoid some warnings in contrib/minizip [Vollant] +- Add -I../.. -L../.. to CFLAGS for minizip and miniunzip +- Add missing libs to minizip linker command +- Add support for VPATH builds in contrib/minizip +- Add an --enable-demos option to contrib/minizip/configure +- Add the generation of configure.log by ./configure +- Exit when required parameters not provided to win32/Makefile.gcc +- Have gzputc return the character written instead of the argument +- Use the -m option on ldconfig for BSD systems [Tobias] +- Correct in zlib.map when deflateResetKeep was added + +Changes in 1.2.5.3 (15 Jan 2012) +- Restore gzgetc function for binary compatibility +- Do not use _lseeki64 under Borland C++ [Truta] +- Update win32/Makefile.msc to build test/*.c [Truta] +- Remove old/visualc6 given CMakefile and other alternatives +- Update AS400 build files and documentation [Monnerat] +- Update win32/Makefile.gcc to build test/*.c [Truta] +- Permit stronger flushes after Z_BLOCK flushes +- Avoid extraneous empty blocks when doing empty flushes +- Permit Z_NULL arguments to deflatePending +- Allow deflatePrime() to insert bits in the middle of a stream +- Remove second empty static block for Z_PARTIAL_FLUSH +- Write out all of the available bits when using Z_BLOCK +- Insert the first two strings in the hash table after a flush + +Changes in 1.2.5.2 (17 Dec 2011) +- fix ld error: unable to find version dependency 'ZLIB_1.2.5' +- use relative symlinks for shared libs +- Avoid searching past window for Z_RLE strategy +- Assure that high-water mark initialization is always applied in deflate +- Add assertions to fill_window() in deflate.c to match comments +- Update python link in README +- Correct spelling error in gzread.c +- Fix bug in gzgets() for a concatenated empty gzip stream +- Correct error in comment for gz_make() +- Change gzread() and related to ignore junk after gzip streams +- Allow gzread() and related to continue after gzclearerr() +- Allow gzrewind() and gzseek() after a premature end-of-file +- Simplify gzseek() now that raw after gzip is ignored +- Change gzgetc() to a macro for speed (~40% speedup in testing) +- Fix gzclose() to return the actual error last encountered +- Always add large file support for windows +- Include zconf.h for windows large file support +- Include zconf.h.cmakein for windows large file support +- Update zconf.h.cmakein on make distclean +- Merge vestigial vsnprintf determination from zutil.h to gzguts.h +- Clarify how gzopen() appends in zlib.h comments +- Correct documentation of gzdirect() since junk at end now ignored +- Add a transparent write mode to gzopen() when 'T' is in the mode +- Update python link in zlib man page +- Get inffixed.h and MAKEFIXED result to match +- Add a ./config --solo option to make zlib subset with no libary use +- Add undocumented inflateResetKeep() function for CAB file decoding +- Add --cover option to ./configure for gcc coverage testing +- Add #define ZLIB_CONST option to use const in the z_stream interface +- Add comment to gzdopen() in zlib.h to use dup() when using fileno() +- Note behavior of uncompress() to provide as much data as it can +- Add files in contrib/minizip to aid in building libminizip +- Split off AR options in Makefile.in and configure +- Change ON macro to Z_ARG to avoid application conflicts +- Facilitate compilation with Borland C++ for pragmas and vsnprintf +- Include io.h for Turbo C / Borland C++ +- Move example.c and minigzip.c to test/ +- Simplify incomplete code table filling in inflate_table() +- Remove code from inflate.c and infback.c that is impossible to execute +- Test the inflate code with full coverage +- Allow deflateSetDictionary, inflateSetDictionary at any time (in raw) +- Add deflateResetKeep and fix inflateResetKeep to retain dictionary +- Fix gzwrite.c to accommodate reduced memory zlib compilation +- Have inflate() with Z_FINISH avoid the allocation of a window +- Do not set strm->adler when doing raw inflate +- Fix gzeof() to behave just like feof() when read is not past end of file +- Fix bug in gzread.c when end-of-file is reached +- Avoid use of Z_BUF_ERROR in gz* functions except for premature EOF +- Document gzread() capability to read concurrently written files +- Remove hard-coding of resource compiler in CMakeLists.txt [Blammo] + +Changes in 1.2.5.1 (10 Sep 2011) +- Update FAQ entry on shared builds (#13) +- Avoid symbolic argument to chmod in Makefile.in +- Fix bug and add consts in contrib/puff [Oberhumer] +- Update contrib/puff/zeros.raw test file to have all block types +- Add full coverage test for puff in contrib/puff/Makefile +- Fix static-only-build install in Makefile.in +- Fix bug in unzGetCurrentFileInfo() in contrib/minizip [Kuno] +- Add libz.a dependency to shared in Makefile.in for parallel builds +- Spell out "number" (instead of "nb") in zlib.h for total_in, total_out +- Replace $(...) with `...` in configure for non-bash sh [Bowler] +- Add darwin* to Darwin* and solaris* to SunOS\ 5* in configure [Groffen] +- Add solaris* to Linux* in configure to allow gcc use [Groffen] +- Add *bsd* to Linux* case in configure [Bar-Lev] +- Add inffast.obj to dependencies in win32/Makefile.msc +- Correct spelling error in deflate.h [Kohler] +- Change libzdll.a again to libz.dll.a (!) in win32/Makefile.gcc +- Add test to configure for GNU C looking for gcc in output of $cc -v +- Add zlib.pc generation to win32/Makefile.gcc [Weigelt] +- Fix bug in zlib.h for _FILE_OFFSET_BITS set and _LARGEFILE64_SOURCE not +- Add comment in zlib.h that adler32_combine with len2 < 0 makes no sense +- Make NO_DIVIDE option in adler32.c much faster (thanks to John Reiser) +- Make stronger test in zconf.h to include unistd.h for LFS +- Apply Darwin patches for 64-bit file offsets to contrib/minizip [Slack] +- Fix zlib.h LFS support when Z_PREFIX used +- Add updated as400 support (removed from old) [Monnerat] +- Avoid deflate sensitivity to volatile input data +- Avoid division in adler32_combine for NO_DIVIDE +- Clarify the use of Z_FINISH with deflateBound() amount of space +- Set binary for output file in puff.c +- Use u4 type for crc_table to avoid conversion warnings +- Apply casts in zlib.h to avoid conversion warnings +- Add OF to prototypes for adler32_combine_ and crc32_combine_ [Miller] +- Improve inflateSync() documentation to note indeterminancy +- Add deflatePending() function to return the amount of pending output +- Correct the spelling of "specification" in FAQ [Randers-Pehrson] +- Add a check in configure for stdarg.h, use for gzprintf() +- Check that pointers fit in ints when gzprint() compiled old style +- Add dummy name before $(SHAREDLIBV) in Makefile [Bar-Lev, Bowler] +- Delete line in configure that adds -L. libz.a to LDFLAGS [Weigelt] +- Add debug records in assmebler code [Londer] +- Update RFC references to use http://tools.ietf.org/html/... [Li] +- Add --archs option, use of libtool to configure for Mac OS X [Borstel] + +Changes in 1.2.5 (19 Apr 2010) +- Disable visibility attribute in win32/Makefile.gcc [Bar-Lev] +- Default to libdir as sharedlibdir in configure [Nieder] +- Update copyright dates on modified source files +- Update trees.c to be able to generate modified trees.h +- Exit configure for MinGW, suggesting win32/Makefile.gcc +- Check for NULL path in gz_open [Homurlu] + +Changes in 1.2.4.5 (18 Apr 2010) +- Set sharedlibdir in configure [Torok] +- Set LDFLAGS in Makefile.in [Bar-Lev] +- Avoid mkdir objs race condition in Makefile.in [Bowler] +- Add ZLIB_INTERNAL in front of internal inter-module functions and arrays +- Define ZLIB_INTERNAL to hide internal functions and arrays for GNU C +- Don't use hidden attribute when it is a warning generator (e.g. Solaris) + +Changes in 1.2.4.4 (18 Apr 2010) +- Fix CROSS_PREFIX executable testing, CHOST extract, mingw* [Torok] +- Undefine _LARGEFILE64_SOURCE in zconf.h if it is zero, but not if empty +- Try to use bash or ksh regardless of functionality of /bin/sh +- Fix configure incompatibility with NetBSD sh +- Remove attempt to run under bash or ksh since have better NetBSD fix +- Fix win32/Makefile.gcc for MinGW [Bar-Lev] +- Add diagnostic messages when using CROSS_PREFIX in configure +- Added --sharedlibdir option to configure [Weigelt] +- Use hidden visibility attribute when available [Frysinger] + +Changes in 1.2.4.3 (10 Apr 2010) +- Only use CROSS_PREFIX in configure for ar and ranlib if they exist +- Use CROSS_PREFIX for nm [Bar-Lev] +- Assume _LARGEFILE64_SOURCE defined is equivalent to true +- Avoid use of undefined symbols in #if with && and || +- Make *64 prototypes in gzguts.h consistent with functions +- Add -shared load option for MinGW in configure [Bowler] +- Move z_off64_t to public interface, use instead of off64_t +- Remove ! from shell test in configure (not portable to Solaris) +- Change +0 macro tests to -0 for possibly increased portability + +Changes in 1.2.4.2 (9 Apr 2010) +- Add consistent carriage returns to readme.txt's in masmx86 and masmx64 +- Really provide prototypes for *64 functions when building without LFS +- Only define unlink() in minigzip.c if unistd.h not included +- Update README to point to contrib/vstudio project files +- Move projects/vc6 to old/ and remove projects/ +- Include stdlib.h in minigzip.c for setmode() definition under WinCE +- Clean up assembler builds in win32/Makefile.msc [Rowe] +- Include sys/types.h for Microsoft for off_t definition +- Fix memory leak on error in gz_open() +- Symbolize nm as $NM in configure [Weigelt] +- Use TEST_LDSHARED instead of LDSHARED to link test programs [Weigelt] +- Add +0 to _FILE_OFFSET_BITS and _LFS64_LARGEFILE in case not defined +- Fix bug in gzeof() to take into account unused input data +- Avoid initialization of structures with variables in puff.c +- Updated win32/README-WIN32.txt [Rowe] + +Changes in 1.2.4.1 (28 Mar 2010) +- Remove the use of [a-z] constructs for sed in configure [gentoo 310225] +- Remove $(SHAREDLIB) from LIBS in Makefile.in [Creech] +- Restore "for debugging" comment on sprintf() in gzlib.c +- Remove fdopen for MVS from gzguts.h +- Put new README-WIN32.txt in win32 [Rowe] +- Add check for shell to configure and invoke another shell if needed +- Fix big fat stinking bug in gzseek() on uncompressed files +- Remove vestigial F_OPEN64 define in zutil.h +- Set and check the value of _LARGEFILE_SOURCE and _LARGEFILE64_SOURCE +- Avoid errors on non-LFS systems when applications define LFS macros +- Set EXE to ".exe" in configure for MINGW [Kahle] +- Match crc32() in crc32.c exactly to the prototype in zlib.h [Sherrill] +- Add prefix for cross-compilation in win32/makefile.gcc [Bar-Lev] +- Add DLL install in win32/makefile.gcc [Bar-Lev] +- Allow Linux* or linux* from uname in configure [Bar-Lev] +- Allow ldconfig to be redefined in configure and Makefile.in [Bar-Lev] +- Add cross-compilation prefixes to configure [Bar-Lev] +- Match type exactly in gz_load() invocation in gzread.c +- Match type exactly of zcalloc() in zutil.c to zlib.h alloc_func +- Provide prototypes for *64 functions when building zlib without LFS +- Don't use -lc when linking shared library on MinGW +- Remove errno.h check in configure and vestigial errno code in zutil.h + +Changes in 1.2.4 (14 Mar 2010) +- Fix VER3 extraction in configure for no fourth subversion +- Update zlib.3, add docs to Makefile.in to make .pdf out of it +- Add zlib.3.pdf to distribution +- Don't set error code in gzerror() if passed pointer is NULL +- Apply destination directory fixes to CMakeLists.txt [Lowman] +- Move #cmakedefine's to a new zconf.in.cmakein +- Restore zconf.h for builds that don't use configure or cmake +- Add distclean to dummy Makefile for convenience +- Update and improve INDEX, README, and FAQ +- Update CMakeLists.txt for the return of zconf.h [Lowman] +- Update contrib/vstudio/vc9 and vc10 [Vollant] +- Change libz.dll.a back to libzdll.a in win32/Makefile.gcc +- Apply license and readme changes to contrib/asm686 [Raiter] +- Check file name lengths and add -c option in minigzip.c [Li] +- Update contrib/amd64 and contrib/masmx86/ [Vollant] +- Avoid use of "eof" parameter in trees.c to not shadow library variable +- Update make_vms.com for removal of zlibdefs.h [Zinser] +- Update assembler code and vstudio projects in contrib [Vollant] +- Remove outdated assembler code contrib/masm686 and contrib/asm586 +- Remove old vc7 and vc8 from contrib/vstudio +- Update win32/Makefile.msc, add ZLIB_VER_SUBREVISION [Rowe] +- Fix memory leaks in gzclose_r() and gzclose_w(), file leak in gz_open() +- Add contrib/gcc_gvmat64 for longest_match and inflate_fast [Vollant] +- Remove *64 functions from win32/zlib.def (they're not 64-bit yet) +- Fix bug in void-returning vsprintf() case in gzwrite.c +- Fix name change from inflate.h in contrib/inflate86/inffas86.c +- Check if temporary file exists before removing in make_vms.com [Zinser] +- Fix make install and uninstall for --static option +- Fix usage of _MSC_VER in gzguts.h and zutil.h [Truta] +- Update readme.txt in contrib/masmx64 and masmx86 to assemble + +Changes in 1.2.3.9 (21 Feb 2010) +- Expunge gzio.c +- Move as400 build information to old +- Fix updates in contrib/minizip and contrib/vstudio +- Add const to vsnprintf test in configure to avoid warnings [Weigelt] +- Delete zconf.h (made by configure) [Weigelt] +- Change zconf.in.h to zconf.h.in per convention [Weigelt] +- Check for NULL buf in gzgets() +- Return empty string for gzgets() with len == 1 (like fgets()) +- Fix description of gzgets() in zlib.h for end-of-file, NULL return +- Update minizip to 1.1 [Vollant] +- Avoid MSVC loss of data warnings in gzread.c, gzwrite.c +- Note in zlib.h that gzerror() should be used to distinguish from EOF +- Remove use of snprintf() from gzlib.c +- Fix bug in gzseek() +- Update contrib/vstudio, adding vc9 and vc10 [Kuno, Vollant] +- Fix zconf.h generation in CMakeLists.txt [Lowman] +- Improve comments in zconf.h where modified by configure + +Changes in 1.2.3.8 (13 Feb 2010) +- Clean up text files (tabs, trailing whitespace, etc.) [Oberhumer] +- Use z_off64_t in gz_zero() and gz_skip() to match state->skip +- Avoid comparison problem when sizeof(int) == sizeof(z_off64_t) +- Revert to Makefile.in from 1.2.3.6 (live with the clutter) +- Fix missing error return in gzflush(), add zlib.h note +- Add *64 functions to zlib.map [Levin] +- Fix signed/unsigned comparison in gz_comp() +- Use SFLAGS when testing shared linking in configure +- Add --64 option to ./configure to use -m64 with gcc +- Fix ./configure --help to correctly name options +- Have make fail if a test fails [Levin] +- Avoid buffer overrun in contrib/masmx64/gvmat64.asm [Simpson] +- Remove assembler object files from contrib + +Changes in 1.2.3.7 (24 Jan 2010) +- Always gzopen() with O_LARGEFILE if available +- Fix gzdirect() to work immediately after gzopen() or gzdopen() +- Make gzdirect() more precise when the state changes while reading +- Improve zlib.h documentation in many places +- Catch memory allocation failure in gz_open() +- Complete close operation if seek forward in gzclose_w() fails +- Return Z_ERRNO from gzclose_r() if close() fails +- Return Z_STREAM_ERROR instead of EOF for gzclose() being passed NULL +- Return zero for gzwrite() errors to match zlib.h description +- Return -1 on gzputs() error to match zlib.h description +- Add zconf.in.h to allow recovery from configure modification [Weigelt] +- Fix static library permissions in Makefile.in [Weigelt] +- Avoid warnings in configure tests that hide functionality [Weigelt] +- Add *BSD and DragonFly to Linux case in configure [gentoo 123571] +- Change libzdll.a to libz.dll.a in win32/Makefile.gcc [gentoo 288212] +- Avoid access of uninitialized data for first inflateReset2 call [Gomes] +- Keep object files in subdirectories to reduce the clutter somewhat +- Remove default Makefile and zlibdefs.h, add dummy Makefile +- Add new external functions to Z_PREFIX, remove duplicates, z_z_ -> z_ +- Remove zlibdefs.h completely -- modify zconf.h instead + +Changes in 1.2.3.6 (17 Jan 2010) +- Avoid void * arithmetic in gzread.c and gzwrite.c +- Make compilers happier with const char * for gz_error message +- Avoid unused parameter warning in inflate.c +- Avoid signed-unsigned comparison warning in inflate.c +- Indent #pragma's for traditional C +- Fix usage of strwinerror() in glib.c, change to gz_strwinerror() +- Correct email address in configure for system options +- Update make_vms.com and add make_vms.com to contrib/minizip [Zinser] +- Update zlib.map [Brown] +- Fix Makefile.in for Solaris 10 make of example64 and minizip64 [Torok] +- Apply various fixes to CMakeLists.txt [Lowman] +- Add checks on len in gzread() and gzwrite() +- Add error message for no more room for gzungetc() +- Remove zlib version check in gzwrite() +- Defer compression of gzprintf() result until need to +- Use snprintf() in gzdopen() if available +- Remove USE_MMAP configuration determination (only used by minigzip) +- Remove examples/pigz.c (available separately) +- Update examples/gun.c to 1.6 + +Changes in 1.2.3.5 (8 Jan 2010) +- Add space after #if in zutil.h for some compilers +- Fix relatively harmless bug in deflate_fast() [Exarevsky] +- Fix same problem in deflate_slow() +- Add $(SHAREDLIBV) to LIBS in Makefile.in [Brown] +- Add deflate_rle() for faster Z_RLE strategy run-length encoding +- Add deflate_huff() for faster Z_HUFFMAN_ONLY encoding +- Change name of "write" variable in inffast.c to avoid library collisions +- Fix premature EOF from gzread() in gzio.c [Brown] +- Use zlib header window size if windowBits is 0 in inflateInit2() +- Remove compressBound() call in deflate.c to avoid linking compress.o +- Replace use of errno in gz* with functions, support WinCE [Alves] +- Provide alternative to perror() in minigzip.c for WinCE [Alves] +- Don't use _vsnprintf on later versions of MSVC [Lowman] +- Add CMake build script and input file [Lowman] +- Update contrib/minizip to 1.1 [Svensson, Vollant] +- Moved nintendods directory from contrib to . +- Replace gzio.c with a new set of routines with the same functionality +- Add gzbuffer(), gzoffset(), gzclose_r(), gzclose_w() as part of above +- Update contrib/minizip to 1.1b +- Change gzeof() to return 0 on error instead of -1 to agree with zlib.h + +Changes in 1.2.3.4 (21 Dec 2009) +- Use old school .SUFFIXES in Makefile.in for FreeBSD compatibility +- Update comments in configure and Makefile.in for default --shared +- Fix test -z's in configure [Marquess] +- Build examplesh and minigzipsh when not testing +- Change NULL's to Z_NULL's in deflate.c and in comments in zlib.h +- Import LDFLAGS from the environment in configure +- Fix configure to populate SFLAGS with discovered CFLAGS options +- Adapt make_vms.com to the new Makefile.in [Zinser] +- Add zlib2ansi script for C++ compilation [Marquess] +- Add _FILE_OFFSET_BITS=64 test to make test (when applicable) +- Add AMD64 assembler code for longest match to contrib [Teterin] +- Include options from $SFLAGS when doing $LDSHARED +- Simplify 64-bit file support by introducing z_off64_t type +- Make shared object files in objs directory to work around old Sun cc +- Use only three-part version number for Darwin shared compiles +- Add rc option to ar in Makefile.in for when ./configure not run +- Add -WI,-rpath,. to LDFLAGS for OSF 1 V4* +- Set LD_LIBRARYN32_PATH for SGI IRIX shared compile +- Protect against _FILE_OFFSET_BITS being defined when compiling zlib +- Rename Makefile.in targets allstatic to static and allshared to shared +- Fix static and shared Makefile.in targets to be independent +- Correct error return bug in gz_open() by setting state [Brown] +- Put spaces before ;;'s in configure for better sh compatibility +- Add pigz.c (parallel implementation of gzip) to examples/ +- Correct constant in crc32.c to UL [Leventhal] +- Reject negative lengths in crc32_combine() +- Add inflateReset2() function to work like inflateEnd()/inflateInit2() +- Include sys/types.h for _LARGEFILE64_SOURCE [Brown] +- Correct typo in doc/algorithm.txt [Janik] +- Fix bug in adler32_combine() [Zhu] +- Catch missing-end-of-block-code error in all inflates and in puff + Assures that random input to inflate eventually results in an error +- Added enough.c (calculation of ENOUGH for inftrees.h) to examples/ +- Update ENOUGH and its usage to reflect discovered bounds +- Fix gzerror() error report on empty input file [Brown] +- Add ush casts in trees.c to avoid pedantic runtime errors +- Fix typo in zlib.h uncompress() description [Reiss] +- Correct inflate() comments with regard to automatic header detection +- Remove deprecation comment on Z_PARTIAL_FLUSH (it stays) +- Put new version of gzlog (2.0) in examples with interruption recovery +- Add puff compile option to permit invalid distance-too-far streams +- Add puff TEST command options, ability to read piped input +- Prototype the *64 functions in zlib.h when _FILE_OFFSET_BITS == 64, but + _LARGEFILE64_SOURCE not defined +- Fix Z_FULL_FLUSH to truly erase the past by resetting s->strstart +- Fix deflateSetDictionary() to use all 32K for output consistency +- Remove extraneous #define MIN_LOOKAHEAD in deflate.c (in deflate.h) +- Clear bytes after deflate lookahead to avoid use of uninitialized data +- Change a limit in inftrees.c to be more transparent to Coverity Prevent +- Update win32/zlib.def with exported symbols from zlib.h +- Correct spelling errors in zlib.h [Willem, Sobrado] +- Allow Z_BLOCK for deflate() to force a new block +- Allow negative bits in inflatePrime() to delete existing bit buffer +- Add Z_TREES flush option to inflate() to return at end of trees +- Add inflateMark() to return current state information for random access +- Add Makefile for NintendoDS to contrib [Costa] +- Add -w in configure compile tests to avoid spurious warnings [Beucler] +- Fix typos in zlib.h comments for deflateSetDictionary() +- Fix EOF detection in transparent gzread() [Maier] + +Changes in 1.2.3.3 (2 October 2006) +- Make --shared the default for configure, add a --static option +- Add compile option to permit invalid distance-too-far streams +- Add inflateUndermine() function which is required to enable above +- Remove use of "this" variable name for C++ compatibility [Marquess] +- Add testing of shared library in make test, if shared library built +- Use ftello() and fseeko() if available instead of ftell() and fseek() +- Provide two versions of all functions that use the z_off_t type for + binary compatibility -- a normal version and a 64-bit offset version, + per the Large File Support Extension when _LARGEFILE64_SOURCE is + defined; use the 64-bit versions by default when _FILE_OFFSET_BITS + is defined to be 64 +- Add a --uname= option to configure to perhaps help with cross-compiling + +Changes in 1.2.3.2 (3 September 2006) +- Turn off silly Borland warnings [Hay] +- Use off64_t and define _LARGEFILE64_SOURCE when present +- Fix missing dependency on inffixed.h in Makefile.in +- Rig configure --shared to build both shared and static [Teredesai, Truta] +- Remove zconf.in.h and instead create a new zlibdefs.h file +- Fix contrib/minizip/unzip.c non-encrypted after encrypted [Vollant] +- Add treebuild.xml (see http://treebuild.metux.de/) [Weigelt] + +Changes in 1.2.3.1 (16 August 2006) +- Add watcom directory with OpenWatcom make files [Daniel] +- Remove #undef of FAR in zconf.in.h for MVS [Fedtke] +- Update make_vms.com [Zinser] +- Use -fPIC for shared build in configure [Teredesai, Nicholson] +- Use only major version number for libz.so on IRIX and OSF1 [Reinholdtsen] +- Use fdopen() (not _fdopen()) for Interix in zutil.h [BŠck] +- Add some FAQ entries about the contrib directory +- Update the MVS question in the FAQ +- Avoid extraneous reads after EOF in gzio.c [Brown] +- Correct spelling of "successfully" in gzio.c [Randers-Pehrson] +- Add comments to zlib.h about gzerror() usage [Brown] +- Set extra flags in gzip header in gzopen() like deflate() does +- Make configure options more compatible with double-dash conventions + [Weigelt] +- Clean up compilation under Solaris SunStudio cc [Rowe, Reinholdtsen] +- Fix uninstall target in Makefile.in [Truta] +- Add pkgconfig support [Weigelt] +- Use $(DESTDIR) macro in Makefile.in [Reinholdtsen, Weigelt] +- Replace set_data_type() with a more accurate detect_data_type() in + trees.c, according to the txtvsbin.txt document [Truta] +- Swap the order of #include and #include "zlib.h" in + gzio.c, example.c and minigzip.c [Truta] +- Shut up annoying VS2005 warnings about standard C deprecation [Rowe, + Truta] (where?) +- Fix target "clean" from win32/Makefile.bor [Truta] +- Create .pdb and .manifest files in win32/makefile.msc [Ziegler, Rowe] +- Update zlib www home address in win32/DLL_FAQ.txt [Truta] +- Update contrib/masmx86/inffas32.asm for VS2005 [Vollant, Van Wassenhove] +- Enable browse info in the "Debug" and "ASM Debug" configurations in + the Visual C++ 6 project, and set (non-ASM) "Debug" as default [Truta] +- Add pkgconfig support [Weigelt] +- Add ZLIB_VER_MAJOR, ZLIB_VER_MINOR and ZLIB_VER_REVISION in zlib.h, + for use in win32/zlib1.rc [Polushin, Rowe, Truta] +- Add a document that explains the new text detection scheme to + doc/txtvsbin.txt [Truta] +- Add rfc1950.txt, rfc1951.txt and rfc1952.txt to doc/ [Truta] +- Move algorithm.txt into doc/ [Truta] +- Synchronize FAQ with website +- Fix compressBound(), was low for some pathological cases [Fearnley] +- Take into account wrapper variations in deflateBound() +- Set examples/zpipe.c input and output to binary mode for Windows +- Update examples/zlib_how.html with new zpipe.c (also web site) +- Fix some warnings in examples/gzlog.c and examples/zran.c (it seems + that gcc became pickier in 4.0) +- Add zlib.map for Linux: "All symbols from zlib-1.1.4 remain + un-versioned, the patch adds versioning only for symbols introduced in + zlib-1.2.0 or later. It also declares as local those symbols which are + not designed to be exported." [Levin] +- Update Z_PREFIX list in zconf.in.h, add --zprefix option to configure +- Do not initialize global static by default in trees.c, add a response + NO_INIT_GLOBAL_POINTERS to initialize them if needed [Marquess] +- Don't use strerror() in gzio.c under WinCE [Yakimov] +- Don't use errno.h in zutil.h under WinCE [Yakimov] +- Move arguments for AR to its usage to allow replacing ar [Marot] +- Add HAVE_VISIBILITY_PRAGMA in zconf.in.h for Mozilla [Randers-Pehrson] +- Improve inflateInit() and inflateInit2() documentation +- Fix structure size comment in inflate.h +- Change configure help option from --h* to --help [Santos] + +Changes in 1.2.3 (18 July 2005) +- Apply security vulnerability fixes to contrib/infback9 as well +- Clean up some text files (carriage returns, trailing space) +- Update testzlib, vstudio, masmx64, and masmx86 in contrib [Vollant] + +Changes in 1.2.2.4 (11 July 2005) +- Add inflatePrime() function for starting inflation at bit boundary +- Avoid some Visual C warnings in deflate.c +- Avoid more silly Visual C warnings in inflate.c and inftrees.c for 64-bit + compile +- Fix some spelling errors in comments [Betts] +- Correct inflateInit2() error return documentation in zlib.h +- Add zran.c example of compressed data random access to examples + directory, shows use of inflatePrime() +- Fix cast for assignments to strm->state in inflate.c and infback.c +- Fix zlibCompileFlags() in zutil.c to use 1L for long shifts [Oberhumer] +- Move declarations of gf2 functions to right place in crc32.c [Oberhumer] +- Add cast in trees.c t avoid a warning [Oberhumer] +- Avoid some warnings in fitblk.c, gun.c, gzjoin.c in examples [Oberhumer] +- Update make_vms.com [Zinser] +- Initialize state->write in inflateReset() since copied in inflate_fast() +- Be more strict on incomplete code sets in inflate_table() and increase + ENOUGH and MAXD -- this repairs a possible security vulnerability for + invalid inflate input. Thanks to Tavis Ormandy and Markus Oberhumer for + discovering the vulnerability and providing test cases. +- Add ia64 support to configure for HP-UX [Smith] +- Add error return to gzread() for format or i/o error [Levin] +- Use malloc.h for OS/2 [Necasek] + +Changes in 1.2.2.3 (27 May 2005) +- Replace 1U constants in inflate.c and inftrees.c for 64-bit compile +- Typecast fread() return values in gzio.c [Vollant] +- Remove trailing space in minigzip.c outmode (VC++ can't deal with it) +- Fix crc check bug in gzread() after gzungetc() [Heiner] +- Add the deflateTune() function to adjust internal compression parameters +- Add a fast gzip decompressor, gun.c, to examples (use of inflateBack) +- Remove an incorrect assertion in examples/zpipe.c +- Add C++ wrapper in infback9.h [Donais] +- Fix bug in inflateCopy() when decoding fixed codes +- Note in zlib.h how much deflateSetDictionary() actually uses +- Remove USE_DICT_HEAD in deflate.c (would mess up inflate if used) +- Add _WIN32_WCE to define WIN32 in zconf.in.h [Spencer] +- Don't include stderr.h or errno.h for _WIN32_WCE in zutil.h [Spencer] +- Add gzdirect() function to indicate transparent reads +- Update contrib/minizip [Vollant] +- Fix compilation of deflate.c when both ASMV and FASTEST [Oberhumer] +- Add casts in crc32.c to avoid warnings [Oberhumer] +- Add contrib/masmx64 [Vollant] +- Update contrib/asm586, asm686, masmx86, testzlib, vstudio [Vollant] + +Changes in 1.2.2.2 (30 December 2004) +- Replace structure assignments in deflate.c and inflate.c with zmemcpy to + avoid implicit memcpy calls (portability for no-library compilation) +- Increase sprintf() buffer size in gzdopen() to allow for large numbers +- Add INFLATE_STRICT to check distances against zlib header +- Improve WinCE errno handling and comments [Chang] +- Remove comment about no gzip header processing in FAQ +- Add Z_FIXED strategy option to deflateInit2() to force fixed trees +- Add updated make_vms.com [Coghlan], update README +- Create a new "examples" directory, move gzappend.c there, add zpipe.c, + fitblk.c, gzlog.[ch], gzjoin.c, and zlib_how.html. +- Add FAQ entry and comments in deflate.c on uninitialized memory access +- Add Solaris 9 make options in configure [Gilbert] +- Allow strerror() usage in gzio.c for STDC +- Fix DecompressBuf in contrib/delphi/ZLib.pas [ManChesTer] +- Update contrib/masmx86/inffas32.asm and gvmat32.asm [Vollant] +- Use z_off_t for adler32_combine() and crc32_combine() lengths +- Make adler32() much faster for small len +- Use OS_CODE in deflate() default gzip header + +Changes in 1.2.2.1 (31 October 2004) +- Allow inflateSetDictionary() call for raw inflate +- Fix inflate header crc check bug for file names and comments +- Add deflateSetHeader() and gz_header structure for custom gzip headers +- Add inflateGetheader() to retrieve gzip headers +- Add crc32_combine() and adler32_combine() functions +- Add alloc_func, free_func, in_func, out_func to Z_PREFIX list +- Use zstreamp consistently in zlib.h (inflate_back functions) +- Remove GUNZIP condition from definition of inflate_mode in inflate.h + and in contrib/inflate86/inffast.S [Truta, Anderson] +- Add support for AMD64 in contrib/inflate86/inffas86.c [Anderson] +- Update projects/README.projects and projects/visualc6 [Truta] +- Update win32/DLL_FAQ.txt [Truta] +- Avoid warning under NO_GZCOMPRESS in gzio.c; fix typo [Truta] +- Deprecate Z_ASCII; use Z_TEXT instead [Truta] +- Use a new algorithm for setting strm->data_type in trees.c [Truta] +- Do not define an exit() prototype in zutil.c unless DEBUG defined +- Remove prototype of exit() from zutil.c, example.c, minigzip.c [Truta] +- Add comment in zlib.h for Z_NO_FLUSH parameter to deflate() +- Fix Darwin build version identification [Peterson] + +Changes in 1.2.2 (3 October 2004) +- Update zlib.h comments on gzip in-memory processing +- Set adler to 1 in inflateReset() to support Java test suite [Walles] +- Add contrib/dotzlib [Ravn] +- Update win32/DLL_FAQ.txt [Truta] +- Update contrib/minizip [Vollant] +- Move contrib/visual-basic.txt to old/ [Truta] +- Fix assembler builds in projects/visualc6/ [Truta] + +Changes in 1.2.1.2 (9 September 2004) +- Update INDEX file +- Fix trees.c to update strm->data_type (no one ever noticed!) +- Fix bug in error case in inflate.c, infback.c, and infback9.c [Brown] +- Add "volatile" to crc table flag declaration (for DYNAMIC_CRC_TABLE) +- Add limited multitasking protection to DYNAMIC_CRC_TABLE +- Add NO_vsnprintf for VMS in zutil.h [Mozilla] +- Don't declare strerror() under VMS [Mozilla] +- Add comment to DYNAMIC_CRC_TABLE to use get_crc_table() to initialize +- Update contrib/ada [Anisimkov] +- Update contrib/minizip [Vollant] +- Fix configure to not hardcode directories for Darwin [Peterson] +- Fix gzio.c to not return error on empty files [Brown] +- Fix indentation; update version in contrib/delphi/ZLib.pas and + contrib/pascal/zlibpas.pas [Truta] +- Update mkasm.bat in contrib/masmx86 [Truta] +- Update contrib/untgz [Truta] +- Add projects/README.projects [Truta] +- Add project for MS Visual C++ 6.0 in projects/visualc6 [Cadieux, Truta] +- Update win32/DLL_FAQ.txt [Truta] +- Update list of Z_PREFIX symbols in zconf.h [Randers-Pehrson, Truta] +- Remove an unnecessary assignment to curr in inftrees.c [Truta] +- Add OS/2 to exe builds in configure [Poltorak] +- Remove err dummy parameter in zlib.h [Kientzle] + +Changes in 1.2.1.1 (9 January 2004) +- Update email address in README +- Several FAQ updates +- Fix a big fat bug in inftrees.c that prevented decoding valid + dynamic blocks with only literals and no distance codes -- + Thanks to "Hot Emu" for the bug report and sample file +- Add a note to puff.c on no distance codes case. + +Changes in 1.2.1 (17 November 2003) +- Remove a tab in contrib/gzappend/gzappend.c +- Update some interfaces in contrib for new zlib functions +- Update zlib version number in some contrib entries +- Add Windows CE definition for ptrdiff_t in zutil.h [Mai, Truta] +- Support shared libraries on Hurd and KFreeBSD [Brown] +- Fix error in NO_DIVIDE option of adler32.c + +Changes in 1.2.0.8 (4 November 2003) +- Update version in contrib/delphi/ZLib.pas and contrib/pascal/zlibpas.pas +- Add experimental NO_DIVIDE #define in adler32.c + - Possibly faster on some processors (let me know if it is) +- Correct Z_BLOCK to not return on first inflate call if no wrap +- Fix strm->data_type on inflate() return to correctly indicate EOB +- Add deflatePrime() function for appending in the middle of a byte +- Add contrib/gzappend for an example of appending to a stream +- Update win32/DLL_FAQ.txt [Truta] +- Delete Turbo C comment in README [Truta] +- Improve some indentation in zconf.h [Truta] +- Fix infinite loop on bad input in configure script [Church] +- Fix gzeof() for concatenated gzip files [Johnson] +- Add example to contrib/visual-basic.txt [Michael B.] +- Add -p to mkdir's in Makefile.in [vda] +- Fix configure to properly detect presence or lack of printf functions +- Add AS400 support [Monnerat] +- Add a little Cygwin support [Wilson] + +Changes in 1.2.0.7 (21 September 2003) +- Correct some debug formats in contrib/infback9 +- Cast a type in a debug statement in trees.c +- Change search and replace delimiter in configure from % to # [Beebe] +- Update contrib/untgz to 0.2 with various fixes [Truta] +- Add build support for Amiga [Nikl] +- Remove some directories in old that have been updated to 1.2 +- Add dylib building for Mac OS X in configure and Makefile.in +- Remove old distribution stuff from Makefile +- Update README to point to DLL_FAQ.txt, and add comment on Mac OS X +- Update links in README + +Changes in 1.2.0.6 (13 September 2003) +- Minor FAQ updates +- Update contrib/minizip to 1.00 [Vollant] +- Remove test of gz functions in example.c when GZ_COMPRESS defined [Truta] +- Update POSTINC comment for 68060 [Nikl] +- Add contrib/infback9 with deflate64 decoding (unsupported) +- For MVS define NO_vsnprintf and undefine FAR [van Burik] +- Add pragma for fdopen on MVS [van Burik] + +Changes in 1.2.0.5 (8 September 2003) +- Add OF to inflateBackEnd() declaration in zlib.h +- Remember start when using gzdopen in the middle of a file +- Use internal off_t counters in gz* functions to properly handle seeks +- Perform more rigorous check for distance-too-far in inffast.c +- Add Z_BLOCK flush option to return from inflate at block boundary +- Set strm->data_type on return from inflate + - Indicate bits unused, if at block boundary, and if in last block +- Replace size_t with ptrdiff_t in crc32.c, and check for correct size +- Add condition so old NO_DEFLATE define still works for compatibility +- FAQ update regarding the Windows DLL [Truta] +- INDEX update: add qnx entry, remove aix entry [Truta] +- Install zlib.3 into mandir [Wilson] +- Move contrib/zlib_dll_FAQ.txt to win32/DLL_FAQ.txt; update [Truta] +- Adapt the zlib interface to the new DLL convention guidelines [Truta] +- Introduce ZLIB_WINAPI macro to allow the export of functions using + the WINAPI calling convention, for Visual Basic [Vollant, Truta] +- Update msdos and win32 scripts and makefiles [Truta] +- Export symbols by name, not by ordinal, in win32/zlib.def [Truta] +- Add contrib/ada [Anisimkov] +- Move asm files from contrib/vstudio/vc70_32 to contrib/asm386 [Truta] +- Rename contrib/asm386 to contrib/masmx86 [Truta, Vollant] +- Add contrib/masm686 [Truta] +- Fix offsets in contrib/inflate86 and contrib/masmx86/inffas32.asm + [Truta, Vollant] +- Update contrib/delphi; rename to contrib/pascal; add example [Truta] +- Remove contrib/delphi2; add a new contrib/delphi [Truta] +- Avoid inclusion of the nonstandard in contrib/iostream, + and fix some method prototypes [Truta] +- Fix the ZCR_SEED2 constant to avoid warnings in contrib/minizip + [Truta] +- Avoid the use of backslash (\) in contrib/minizip [Vollant] +- Fix file time handling in contrib/untgz; update makefiles [Truta] +- Update contrib/vstudio/vc70_32 to comply with the new DLL guidelines + [Vollant] +- Remove contrib/vstudio/vc15_16 [Vollant] +- Rename contrib/vstudio/vc70_32 to contrib/vstudio/vc7 [Truta] +- Update README.contrib [Truta] +- Invert the assignment order of match_head and s->prev[...] in + INSERT_STRING [Truta] +- Compare TOO_FAR with 32767 instead of 32768, to avoid 16-bit warnings + [Truta] +- Compare function pointers with 0, not with NULL or Z_NULL [Truta] +- Fix prototype of syncsearch in inflate.c [Truta] +- Introduce ASMINF macro to be enabled when using an ASM implementation + of inflate_fast [Truta] +- Change NO_DEFLATE to NO_GZCOMPRESS [Truta] +- Modify test_gzio in example.c to take a single file name as a + parameter [Truta] +- Exit the example.c program if gzopen fails [Truta] +- Add type casts around strlen in example.c [Truta] +- Remove casting to sizeof in minigzip.c; give a proper type + to the variable compared with SUFFIX_LEN [Truta] +- Update definitions of STDC and STDC99 in zconf.h [Truta] +- Synchronize zconf.h with the new Windows DLL interface [Truta] +- Use SYS16BIT instead of __32BIT__ to distinguish between + 16- and 32-bit platforms [Truta] +- Use far memory allocators in small 16-bit memory models for + Turbo C [Truta] +- Add info about the use of ASMV, ASMINF and ZLIB_WINAPI in + zlibCompileFlags [Truta] +- Cygwin has vsnprintf [Wilson] +- In Windows16, OS_CODE is 0, as in MSDOS [Truta] +- In Cygwin, OS_CODE is 3 (Unix), not 11 (Windows32) [Wilson] + +Changes in 1.2.0.4 (10 August 2003) +- Minor FAQ updates +- Be more strict when checking inflateInit2's windowBits parameter +- Change NO_GUNZIP compile option to NO_GZIP to cover deflate as well +- Add gzip wrapper option to deflateInit2 using windowBits +- Add updated QNX rule in configure and qnx directory [Bonnefoy] +- Make inflate distance-too-far checks more rigorous +- Clean up FAR usage in inflate +- Add casting to sizeof() in gzio.c and minigzip.c + +Changes in 1.2.0.3 (19 July 2003) +- Fix silly error in gzungetc() implementation [Vollant] +- Update contrib/minizip and contrib/vstudio [Vollant] +- Fix printf format in example.c +- Correct cdecl support in zconf.in.h [Anisimkov] +- Minor FAQ updates + +Changes in 1.2.0.2 (13 July 2003) +- Add ZLIB_VERNUM in zlib.h for numerical preprocessor comparisons +- Attempt to avoid warnings in crc32.c for pointer-int conversion +- Add AIX to configure, remove aix directory [Bakker] +- Add some casts to minigzip.c +- Improve checking after insecure sprintf() or vsprintf() calls +- Remove #elif's from crc32.c +- Change leave label to inf_leave in inflate.c and infback.c to avoid + library conflicts +- Remove inflate gzip decoding by default--only enable gzip decoding by + special request for stricter backward compatibility +- Add zlibCompileFlags() function to return compilation information +- More typecasting in deflate.c to avoid warnings +- Remove leading underscore from _Capital #defines [Truta] +- Fix configure to link shared library when testing +- Add some Windows CE target adjustments [Mai] +- Remove #define ZLIB_DLL in zconf.h [Vollant] +- Add zlib.3 [Rodgers] +- Update RFC URL in deflate.c and algorithm.txt [Mai] +- Add zlib_dll_FAQ.txt to contrib [Truta] +- Add UL to some constants [Truta] +- Update minizip and vstudio [Vollant] +- Remove vestigial NEED_DUMMY_RETURN from zconf.in.h +- Expand use of NO_DUMMY_DECL to avoid all dummy structures +- Added iostream3 to contrib [Schwardt] +- Replace rewind() with fseek() for WinCE [Truta] +- Improve setting of zlib format compression level flags + - Report 0 for huffman and rle strategies and for level == 0 or 1 + - Report 2 only for level == 6 +- Only deal with 64K limit when necessary at compile time [Truta] +- Allow TOO_FAR check to be turned off at compile time [Truta] +- Add gzclearerr() function [Souza] +- Add gzungetc() function + +Changes in 1.2.0.1 (17 March 2003) +- Add Z_RLE strategy for run-length encoding [Truta] + - When Z_RLE requested, restrict matches to distance one + - Update zlib.h, minigzip.c, gzopen(), gzdopen() for Z_RLE +- Correct FASTEST compilation to allow level == 0 +- Clean up what gets compiled for FASTEST +- Incorporate changes to zconf.in.h [Vollant] + - Refine detection of Turbo C need for dummy returns + - Refine ZLIB_DLL compilation + - Include additional header file on VMS for off_t typedef +- Try to use _vsnprintf where it supplants vsprintf [Vollant] +- Add some casts in inffast.c +- Enchance comments in zlib.h on what happens if gzprintf() tries to + write more than 4095 bytes before compression +- Remove unused state from inflateBackEnd() +- Remove exit(0) from minigzip.c, example.c +- Get rid of all those darn tabs +- Add "check" target to Makefile.in that does the same thing as "test" +- Add "mostlyclean" and "maintainer-clean" targets to Makefile.in +- Update contrib/inflate86 [Anderson] +- Update contrib/testzlib, contrib/vstudio, contrib/minizip [Vollant] +- Add msdos and win32 directories with makefiles [Truta] +- More additions and improvements to the FAQ + +Changes in 1.2.0 (9 March 2003) +- New and improved inflate code + - About 20% faster + - Does not allocate 32K window unless and until needed + - Automatically detects and decompresses gzip streams + - Raw inflate no longer needs an extra dummy byte at end + - Added inflateBack functions using a callback interface--even faster + than inflate, useful for file utilities (gzip, zip) + - Added inflateCopy() function to record state for random access on + externally generated deflate streams (e.g. in gzip files) + - More readable code (I hope) +- New and improved crc32() + - About 50% faster, thanks to suggestions from Rodney Brown +- Add deflateBound() and compressBound() functions +- Fix memory leak in deflateInit2() +- Permit setting dictionary for raw deflate (for parallel deflate) +- Fix const declaration for gzwrite() +- Check for some malloc() failures in gzio.c +- Fix bug in gzopen() on single-byte file 0x1f +- Fix bug in gzread() on concatenated file with 0x1f at end of buffer + and next buffer doesn't start with 0x8b +- Fix uncompress() to return Z_DATA_ERROR on truncated input +- Free memory at end of example.c +- Remove MAX #define in trees.c (conflicted with some libraries) +- Fix static const's in deflate.c, gzio.c, and zutil.[ch] +- Declare malloc() and free() in gzio.c if STDC not defined +- Use malloc() instead of calloc() in zutil.c if int big enough +- Define STDC for AIX +- Add aix/ with approach for compiling shared library on AIX +- Add HP-UX support for shared libraries in configure +- Add OpenUNIX support for shared libraries in configure +- Use $cc instead of gcc to build shared library +- Make prefix directory if needed when installing +- Correct Macintosh avoidance of typedef Byte in zconf.h +- Correct Turbo C memory allocation when under Linux +- Use libz.a instead of -lz in Makefile (assure use of compiled library) +- Update configure to check for snprintf or vsnprintf functions and their + return value, warn during make if using an insecure function +- Fix configure problem with compile-time knowledge of HAVE_UNISTD_H that + is lost when library is used--resolution is to build new zconf.h +- Documentation improvements (in zlib.h): + - Document raw deflate and inflate + - Update RFCs URL + - Point out that zlib and gzip formats are different + - Note that Z_BUF_ERROR is not fatal + - Document string limit for gzprintf() and possible buffer overflow + - Note requirement on avail_out when flushing + - Note permitted values of flush parameter of inflate() +- Add some FAQs (and even answers) to the FAQ +- Add contrib/inflate86/ for x86 faster inflate +- Add contrib/blast/ for PKWare Data Compression Library decompression +- Add contrib/puff/ simple inflate for deflate format description + +Changes in 1.1.4 (11 March 2002) +- ZFREE was repeated on same allocation on some error conditions. + This creates a security problem described in + http://www.zlib.org/advisory-2002-03-11.txt +- Returned incorrect error (Z_MEM_ERROR) on some invalid data +- Avoid accesses before window for invalid distances with inflate window + less than 32K. +- force windowBits > 8 to avoid a bug in the encoder for a window size + of 256 bytes. (A complete fix will be available in 1.1.5). + +Changes in 1.1.3 (9 July 1998) +- fix "an inflate input buffer bug that shows up on rare but persistent + occasions" (Mark) +- fix gzread and gztell for concatenated .gz files (Didier Le Botlan) +- fix gzseek(..., SEEK_SET) in write mode +- fix crc check after a gzeek (Frank Faubert) +- fix miniunzip when the last entry in a zip file is itself a zip file + (J Lillge) +- add contrib/asm586 and contrib/asm686 (Brian Raiter) + See http://www.muppetlabs.com/~breadbox/software/assembly.html +- add support for Delphi 3 in contrib/delphi (Bob Dellaca) +- add support for C++Builder 3 and Delphi 3 in contrib/delphi2 (Davide Moretti) +- do not exit prematurely in untgz if 0 at start of block (Magnus Holmgren) +- use macro EXTERN instead of extern to support DLL for BeOS (Sander Stoks) +- added a FAQ file + +- Support gzdopen on Mac with Metrowerks (Jason Linhart) +- Do not redefine Byte on Mac (Brad Pettit & Jason Linhart) +- define SEEK_END too if SEEK_SET is not defined (Albert Chin-A-Young) +- avoid some warnings with Borland C (Tom Tanner) +- fix a problem in contrib/minizip/zip.c for 16-bit MSDOS (Gilles Vollant) +- emulate utime() for WIN32 in contrib/untgz (Gilles Vollant) +- allow several arguments to configure (Tim Mooney, Frodo Looijaard) +- use libdir and includedir in Makefile.in (Tim Mooney) +- support shared libraries on OSF1 V4 (Tim Mooney) +- remove so_locations in "make clean" (Tim Mooney) +- fix maketree.c compilation error (Glenn, Mark) +- Python interface to zlib now in Python 1.5 (Jeremy Hylton) +- new Makefile.riscos (Rich Walker) +- initialize static descriptors in trees.c for embedded targets (Nick Smith) +- use "foo-gz" in example.c for RISCOS and VMS (Nick Smith) +- add the OS/2 files in Makefile.in too (Andrew Zabolotny) +- fix fdopen and halloc macros for Microsoft C 6.0 (Tom Lane) +- fix maketree.c to allow clean compilation of inffixed.h (Mark) +- fix parameter check in deflateCopy (Gunther Nikl) +- cleanup trees.c, use compressed_len only in debug mode (Christian Spieler) +- Many portability patches by Christian Spieler: + . zutil.c, zutil.h: added "const" for zmem* + . Make_vms.com: fixed some typos + . Make_vms.com: msdos/Makefile.*: removed zutil.h from some dependency lists + . msdos/Makefile.msc: remove "default rtl link library" info from obj files + . msdos/Makefile.*: use model-dependent name for the built zlib library + . msdos/Makefile.emx, nt/Makefile.emx, nt/Makefile.gcc: + new makefiles, for emx (DOS/OS2), emx&rsxnt and mingw32 (Windows 9x / NT) +- use define instead of typedef for Bytef also for MSC small/medium (Tom Lane) +- replace __far with _far for better portability (Christian Spieler, Tom Lane) +- fix test for errno.h in configure (Tim Newsham) + +Changes in 1.1.2 (19 March 98) +- added contrib/minzip, mini zip and unzip based on zlib (Gilles Vollant) + See http://www.winimage.com/zLibDll/unzip.html +- preinitialize the inflate tables for fixed codes, to make the code + completely thread safe (Mark) +- some simplifications and slight speed-up to the inflate code (Mark) +- fix gzeof on non-compressed files (Allan Schrum) +- add -std1 option in configure for OSF1 to fix gzprintf (Martin Mokrejs) +- use default value of 4K for Z_BUFSIZE for 16-bit MSDOS (Tim Wegner + Glenn) +- added os2/Makefile.def and os2/zlib.def (Andrew Zabolotny) +- add shared lib support for UNIX_SV4.2MP (MATSUURA Takanori) +- do not wrap extern "C" around system includes (Tom Lane) +- mention zlib binding for TCL in README (Andreas Kupries) +- added amiga/Makefile.pup for Amiga powerUP SAS/C PPC (Andreas Kleinert) +- allow "make install prefix=..." even after configure (Glenn Randers-Pehrson) +- allow "configure --prefix $HOME" (Tim Mooney) +- remove warnings in example.c and gzio.c (Glenn Randers-Pehrson) +- move Makefile.sas to amiga/Makefile.sas + +Changes in 1.1.1 (27 Feb 98) +- fix macros _tr_tally_* in deflate.h for debug mode (Glenn Randers-Pehrson) +- remove block truncation heuristic which had very marginal effect for zlib + (smaller lit_bufsize than in gzip 1.2.4) and degraded a little the + compression ratio on some files. This also allows inlining _tr_tally for + matches in deflate_slow. +- added msdos/Makefile.w32 for WIN32 Microsoft Visual C++ (Bob Frazier) + +Changes in 1.1.0 (24 Feb 98) +- do not return STREAM_END prematurely in inflate (John Bowler) +- revert to the zlib 1.0.8 inflate to avoid the gcc 2.8.0 bug (Jeremy Buhler) +- compile with -DFASTEST to get compression code optimized for speed only +- in minigzip, try mmap'ing the input file first (Miguel Albrecht) +- increase size of I/O buffers in minigzip.c and gzio.c (not a big gain + on Sun but significant on HP) + +- add a pointer to experimental unzip library in README (Gilles Vollant) +- initialize variable gcc in configure (Chris Herborth) + +Changes in 1.0.9 (17 Feb 1998) +- added gzputs and gzgets functions +- do not clear eof flag in gzseek (Mark Diekhans) +- fix gzseek for files in transparent mode (Mark Diekhans) +- do not assume that vsprintf returns the number of bytes written (Jens Krinke) +- replace EXPORT with ZEXPORT to avoid conflict with other programs +- added compress2 in zconf.h, zlib.def, zlib.dnt +- new asm code from Gilles Vollant in contrib/asm386 +- simplify the inflate code (Mark): + . Replace ZALLOC's in huft_build() with single ZALLOC in inflate_blocks_new() + . ZALLOC the length list in inflate_trees_fixed() instead of using stack + . ZALLOC the value area for huft_build() instead of using stack + . Simplify Z_FINISH check in inflate() + +- Avoid gcc 2.8.0 comparison bug a little differently than zlib 1.0.8 +- in inftrees.c, avoid cc -O bug on HP (Farshid Elahi) +- in zconf.h move the ZLIB_DLL stuff earlier to avoid problems with + the declaration of FAR (Gilles VOllant) +- install libz.so* with mode 755 (executable) instead of 644 (Marc Lehmann) +- read_buf buf parameter of type Bytef* instead of charf* +- zmemcpy parameters are of type Bytef*, not charf* (Joseph Strout) +- do not redeclare unlink in minigzip.c for WIN32 (John Bowler) +- fix check for presence of directories in "make install" (Ian Willis) + +Changes in 1.0.8 (27 Jan 1998) +- fixed offsets in contrib/asm386/gvmat32.asm (Gilles Vollant) +- fix gzgetc and gzputc for big endian systems (Markus Oberhumer) +- added compress2() to allow setting the compression level +- include sys/types.h to get off_t on some systems (Marc Lehmann & QingLong) +- use constant arrays for the static trees in trees.c instead of computing + them at run time (thanks to Ken Raeburn for this suggestion). To create + trees.h, compile with GEN_TREES_H and run "make test". +- check return code of example in "make test" and display result +- pass minigzip command line options to file_compress +- simplifying code of inflateSync to avoid gcc 2.8 bug + +- support CC="gcc -Wall" in configure -s (QingLong) +- avoid a flush caused by ftell in gzopen for write mode (Ken Raeburn) +- fix test for shared library support to avoid compiler warnings +- zlib.lib -> zlib.dll in msdos/zlib.rc (Gilles Vollant) +- check for TARGET_OS_MAC in addition to MACOS (Brad Pettit) +- do not use fdopen for Metrowerks on Mac (Brad Pettit)) +- add checks for gzputc and gzputc in example.c +- avoid warnings in gzio.c and deflate.c (Andreas Kleinert) +- use const for the CRC table (Ken Raeburn) +- fixed "make uninstall" for shared libraries +- use Tracev instead of Trace in infblock.c +- in example.c use correct compressed length for test_sync +- suppress +vnocompatwarnings in configure for HPUX (not always supported) + +Changes in 1.0.7 (20 Jan 1998) +- fix gzseek which was broken in write mode +- return error for gzseek to negative absolute position +- fix configure for Linux (Chun-Chung Chen) +- increase stack space for MSC (Tim Wegner) +- get_crc_table and inflateSyncPoint are EXPORTed (Gilles Vollant) +- define EXPORTVA for gzprintf (Gilles Vollant) +- added man page zlib.3 (Rick Rodgers) +- for contrib/untgz, fix makedir() and improve Makefile + +- check gzseek in write mode in example.c +- allocate extra buffer for seeks only if gzseek is actually called +- avoid signed/unsigned comparisons (Tim Wegner, Gilles Vollant) +- add inflateSyncPoint in zconf.h +- fix list of exported functions in nt/zlib.dnt and mdsos/zlib.def + +Changes in 1.0.6 (19 Jan 1998) +- add functions gzprintf, gzputc, gzgetc, gztell, gzeof, gzseek, gzrewind and + gzsetparams (thanks to Roland Giersig and Kevin Ruland for some of this code) +- Fix a deflate bug occurring only with compression level 0 (thanks to + Andy Buckler for finding this one). +- In minigzip, pass transparently also the first byte for .Z files. +- return Z_BUF_ERROR instead of Z_OK if output buffer full in uncompress() +- check Z_FINISH in inflate (thanks to Marc Schluper) +- Implement deflateCopy (thanks to Adam Costello) +- make static libraries by default in configure, add --shared option. +- move MSDOS or Windows specific files to directory msdos +- suppress the notion of partial flush to simplify the interface + (but the symbol Z_PARTIAL_FLUSH is kept for compatibility with 1.0.4) +- suppress history buffer provided by application to simplify the interface + (this feature was not implemented anyway in 1.0.4) +- next_in and avail_in must be initialized before calling inflateInit or + inflateInit2 +- add EXPORT in all exported functions (for Windows DLL) +- added Makefile.nt (thanks to Stephen Williams) +- added the unsupported "contrib" directory: + contrib/asm386/ by Gilles Vollant + 386 asm code replacing longest_match(). + contrib/iostream/ by Kevin Ruland + A C++ I/O streams interface to the zlib gz* functions + contrib/iostream2/ by Tyge Løvset + Another C++ I/O streams interface + contrib/untgz/ by "Pedro A. Aranda Guti\irrez" + A very simple tar.gz file extractor using zlib + contrib/visual-basic.txt by Carlos Rios + How to use compress(), uncompress() and the gz* functions from VB. +- pass params -f (filtered data), -h (huffman only), -1 to -9 (compression + level) in minigzip (thanks to Tom Lane) + +- use const for rommable constants in deflate +- added test for gzseek and gztell in example.c +- add undocumented function inflateSyncPoint() (hack for Paul Mackerras) +- add undocumented function zError to convert error code to string + (for Tim Smithers) +- Allow compilation of gzio with -DNO_DEFLATE to avoid the compression code. +- Use default memcpy for Symantec MSDOS compiler. +- Add EXPORT keyword for check_func (needed for Windows DLL) +- add current directory to LD_LIBRARY_PATH for "make test" +- create also a link for libz.so.1 +- added support for FUJITSU UXP/DS (thanks to Toshiaki Nomura) +- use $(SHAREDLIB) instead of libz.so in Makefile.in (for HPUX) +- added -soname for Linux in configure (Chun-Chung Chen, +- assign numbers to the exported functions in zlib.def (for Windows DLL) +- add advice in zlib.h for best usage of deflateSetDictionary +- work around compiler bug on Atari (cast Z_NULL in call of s->checkfn) +- allow compilation with ANSI keywords only enabled for TurboC in large model +- avoid "versionString"[0] (Borland bug) +- add NEED_DUMMY_RETURN for Borland +- use variable z_verbose for tracing in debug mode (L. Peter Deutsch). +- allow compilation with CC +- defined STDC for OS/2 (David Charlap) +- limit external names to 8 chars for MVS (Thomas Lund) +- in minigzip.c, use static buffers only for 16-bit systems +- fix suffix check for "minigzip -d foo.gz" +- do not return an error for the 2nd of two consecutive gzflush() (Felix Lee) +- use _fdopen instead of fdopen for MSC >= 6.0 (Thomas Fanslau) +- added makelcc.bat for lcc-win32 (Tom St Denis) +- in Makefile.dj2, use copy and del instead of install and rm (Frank Donahoe) +- Avoid expanded $Id$. Use "rcs -kb" or "cvs admin -kb" to avoid Id expansion. +- check for unistd.h in configure (for off_t) +- remove useless check parameter in inflate_blocks_free +- avoid useless assignment of s->check to itself in inflate_blocks_new +- do not flush twice in gzclose (thanks to Ken Raeburn) +- rename FOPEN as F_OPEN to avoid clash with /usr/include/sys/file.h +- use NO_ERRNO_H instead of enumeration of operating systems with errno.h +- work around buggy fclose on pipes for HP/UX +- support zlib DLL with BORLAND C++ 5.0 (thanks to Glenn Randers-Pehrson) +- fix configure if CC is already equal to gcc + +Changes in 1.0.5 (3 Jan 98) +- Fix inflate to terminate gracefully when fed corrupted or invalid data +- Use const for rommable constants in inflate +- Eliminate memory leaks on error conditions in inflate +- Removed some vestigial code in inflate +- Update web address in README + +Changes in 1.0.4 (24 Jul 96) +- In very rare conditions, deflate(s, Z_FINISH) could fail to produce an EOF + bit, so the decompressor could decompress all the correct data but went + on to attempt decompressing extra garbage data. This affected minigzip too. +- zlibVersion and gzerror return const char* (needed for DLL) +- port to RISCOS (no fdopen, no multiple dots, no unlink, no fileno) +- use z_error only for DEBUG (avoid problem with DLLs) + +Changes in 1.0.3 (2 Jul 96) +- use z_streamp instead of z_stream *, which is now a far pointer in MSDOS + small and medium models; this makes the library incompatible with previous + versions for these models. (No effect in large model or on other systems.) +- return OK instead of BUF_ERROR if previous deflate call returned with + avail_out as zero but there is nothing to do +- added memcmp for non STDC compilers +- define NO_DUMMY_DECL for more Mac compilers (.h files merged incorrectly) +- define __32BIT__ if __386__ or i386 is defined (pb. with Watcom and SCO) +- better check for 16-bit mode MSC (avoids problem with Symantec) + +Changes in 1.0.2 (23 May 96) +- added Windows DLL support +- added a function zlibVersion (for the DLL support) +- fixed declarations using Bytef in infutil.c (pb with MSDOS medium model) +- Bytef is define's instead of typedef'd only for Borland C +- avoid reading uninitialized memory in example.c +- mention in README that the zlib format is now RFC1950 +- updated Makefile.dj2 +- added algorithm.doc + +Changes in 1.0.1 (20 May 96) [1.0 skipped to avoid confusion] +- fix array overlay in deflate.c which sometimes caused bad compressed data +- fix inflate bug with empty stored block +- fix MSDOS medium model which was broken in 0.99 +- fix deflateParams() which could generated bad compressed data. +- Bytef is define'd instead of typedef'ed (work around Borland bug) +- added an INDEX file +- new makefiles for DJGPP (Makefile.dj2), 32-bit Borland (Makefile.b32), + Watcom (Makefile.wat), Amiga SAS/C (Makefile.sas) +- speed up adler32 for modern machines without auto-increment +- added -ansi for IRIX in configure +- static_init_done in trees.c is an int +- define unlink as delete for VMS +- fix configure for QNX +- add configure branch for SCO and HPUX +- avoid many warnings (unused variables, dead assignments, etc...) +- no fdopen for BeOS +- fix the Watcom fix for 32 bit mode (define FAR as empty) +- removed redefinition of Byte for MKWERKS +- work around an MWKERKS bug (incorrect merge of all .h files) + +Changes in 0.99 (27 Jan 96) +- allow preset dictionary shared between compressor and decompressor +- allow compression level 0 (no compression) +- add deflateParams in zlib.h: allow dynamic change of compression level + and compression strategy. +- test large buffers and deflateParams in example.c +- add optional "configure" to build zlib as a shared library +- suppress Makefile.qnx, use configure instead +- fixed deflate for 64-bit systems (detected on Cray) +- fixed inflate_blocks for 64-bit systems (detected on Alpha) +- declare Z_DEFLATED in zlib.h (possible parameter for deflateInit2) +- always return Z_BUF_ERROR when deflate() has nothing to do +- deflateInit and inflateInit are now macros to allow version checking +- prefix all global functions and types with z_ with -DZ_PREFIX +- make falloc completely reentrant (inftrees.c) +- fixed very unlikely race condition in ct_static_init +- free in reverse order of allocation to help memory manager +- use zlib-1.0/* instead of zlib/* inside the tar.gz +- make zlib warning-free with "gcc -O3 -Wall -Wwrite-strings -Wpointer-arith + -Wconversion -Wstrict-prototypes -Wmissing-prototypes" +- allow gzread on concatenated .gz files +- deflateEnd now returns Z_DATA_ERROR if it was premature +- deflate is finally (?) fully deterministic (no matches beyond end of input) +- Document Z_SYNC_FLUSH +- add uninstall in Makefile +- Check for __cpluplus in zlib.h +- Better test in ct_align for partial flush +- avoid harmless warnings for Borland C++ +- initialize hash_head in deflate.c +- avoid warning on fdopen (gzio.c) for HP cc -Aa +- include stdlib.h for STDC compilers +- include errno.h for Cray +- ignore error if ranlib doesn't exist +- call ranlib twice for NeXTSTEP +- use exec_prefix instead of prefix for libz.a +- renamed ct_* as _tr_* to avoid conflict with applications +- clear z->msg in inflateInit2 before any error return +- initialize opaque in example.c, gzio.c, deflate.c and inflate.c +- fixed typo in zconf.h (_GNUC__ => __GNUC__) +- check for WIN32 in zconf.h and zutil.c (avoid farmalloc in 32-bit mode) +- fix typo in Make_vms.com (f$trnlnm -> f$getsyi) +- in fcalloc, normalize pointer if size > 65520 bytes +- don't use special fcalloc for 32 bit Borland C++ +- use STDC instead of __GO32__ to avoid redeclaring exit, calloc, etc... +- use Z_BINARY instead of BINARY +- document that gzclose after gzdopen will close the file +- allow "a" as mode in gzopen. +- fix error checking in gzread +- allow skipping .gz extra-field on pipes +- added reference to Perl interface in README +- put the crc table in FAR data (I dislike more and more the medium model :) +- added get_crc_table +- added a dimension to all arrays (Borland C can't count). +- workaround Borland C bug in declaration of inflate_codes_new & inflate_fast +- guard against multiple inclusion of *.h (for precompiled header on Mac) +- Watcom C pretends to be Microsoft C small model even in 32 bit mode. +- don't use unsized arrays to avoid silly warnings by Visual C++: + warning C4746: 'inflate_mask' : unsized array treated as '__far' + (what's wrong with far data in far model?). +- define enum out of inflate_blocks_state to allow compilation with C++ + +Changes in 0.95 (16 Aug 95) +- fix MSDOS small and medium model (now easier to adapt to any compiler) +- inlined send_bits +- fix the final (:-) bug for deflate with flush (output was correct but + not completely flushed in rare occasions). +- default window size is same for compression and decompression + (it's now sufficient to set MAX_WBITS in zconf.h). +- voidp -> voidpf and voidnp -> voidp (for consistency with other + typedefs and because voidnp was not near in large model). + +Changes in 0.94 (13 Aug 95) +- support MSDOS medium model +- fix deflate with flush (could sometimes generate bad output) +- fix deflateReset (zlib header was incorrectly suppressed) +- added support for VMS +- allow a compression level in gzopen() +- gzflush now calls fflush +- For deflate with flush, flush even if no more input is provided. +- rename libgz.a as libz.a +- avoid complex expression in infcodes.c triggering Turbo C bug +- work around a problem with gcc on Alpha (in INSERT_STRING) +- don't use inline functions (problem with some gcc versions) +- allow renaming of Byte, uInt, etc... with #define. +- avoid warning about (unused) pointer before start of array in deflate.c +- avoid various warnings in gzio.c, example.c, infblock.c, adler32.c, zutil.c +- avoid reserved word 'new' in trees.c + +Changes in 0.93 (25 June 95) +- temporarily disable inline functions +- make deflate deterministic +- give enough lookahead for PARTIAL_FLUSH +- Set binary mode for stdin/stdout in minigzip.c for OS/2 +- don't even use signed char in inflate (not portable enough) +- fix inflate memory leak for segmented architectures + +Changes in 0.92 (3 May 95) +- don't assume that char is signed (problem on SGI) +- Clear bit buffer when starting a stored block +- no memcpy on Pyramid +- suppressed inftest.c +- optimized fill_window, put longest_match inline for gcc +- optimized inflate on stored blocks. +- untabify all sources to simplify patches + +Changes in 0.91 (2 May 95) +- Default MEM_LEVEL is 8 (not 9 for Unix) as documented in zlib.h +- Document the memory requirements in zconf.h +- added "make install" +- fix sync search logic in inflateSync +- deflate(Z_FULL_FLUSH) now works even if output buffer too short +- after inflateSync, don't scare people with just "lo world" +- added support for DJGPP + +Changes in 0.9 (1 May 95) +- don't assume that zalloc clears the allocated memory (the TurboC bug + was Mark's bug after all :) +- let again gzread copy uncompressed data unchanged (was working in 0.71) +- deflate(Z_FULL_FLUSH), inflateReset and inflateSync are now fully implemented +- added a test of inflateSync in example.c +- moved MAX_WBITS to zconf.h because users might want to change that. +- document explicitly that zalloc(64K) on MSDOS must return a normalized + pointer (zero offset) +- added Makefiles for Microsoft C, Turbo C, Borland C++ +- faster crc32() + +Changes in 0.8 (29 April 95) +- added fast inflate (inffast.c) +- deflate(Z_FINISH) now returns Z_STREAM_END when done. Warning: this + is incompatible with previous versions of zlib which returned Z_OK. +- work around a TurboC compiler bug (bad code for b << 0, see infutil.h) + (actually that was not a compiler bug, see 0.81 above) +- gzread no longer reads one extra byte in certain cases +- In gzio destroy(), don't reference a freed structure +- avoid many warnings for MSDOS +- avoid the ERROR symbol which is used by MS Windows + +Changes in 0.71 (14 April 95) +- Fixed more MSDOS compilation problems :( There is still a bug with + TurboC large model. + +Changes in 0.7 (14 April 95) +- Added full inflate support. +- Simplified the crc32() interface. The pre- and post-conditioning + (one's complement) is now done inside crc32(). WARNING: this is + incompatible with previous versions; see zlib.h for the new usage. + +Changes in 0.61 (12 April 95) +- workaround for a bug in TurboC. example and minigzip now work on MSDOS. + +Changes in 0.6 (11 April 95) +- added minigzip.c +- added gzdopen to reopen a file descriptor as gzFile +- added transparent reading of non-gziped files in gzread. +- fixed bug in gzread (don't read crc as data) +- fixed bug in destroy (gzio.c) (don't return Z_STREAM_END for gzclose). +- don't allocate big arrays in the stack (for MSDOS) +- fix some MSDOS compilation problems + +Changes in 0.5: +- do real compression in deflate.c. Z_PARTIAL_FLUSH is supported but + not yet Z_FULL_FLUSH. +- support decompression but only in a single step (forced Z_FINISH) +- added opaque object for zalloc and zfree. +- added deflateReset and inflateReset +- added a variable zlib_version for consistency checking. +- renamed the 'filter' parameter of deflateInit2 as 'strategy'. + Added Z_FILTERED and Z_HUFFMAN_ONLY constants. + +Changes in 0.4: +- avoid "zip" everywhere, use zlib instead of ziplib. +- suppress Z_BLOCK_FLUSH, interpret Z_PARTIAL_FLUSH as block flush + if compression method == 8. +- added adler32 and crc32 +- renamed deflateOptions as deflateInit2, call one or the other but not both +- added the method parameter for deflateInit2. +- added inflateInit2 +- simplied considerably deflateInit and inflateInit by not supporting + user-provided history buffer. This is supported only in deflateInit2 + and inflateInit2. + +Changes in 0.3: +- prefix all macro names with Z_ +- use Z_FINISH instead of deflateEnd to finish compression. +- added Z_HUFFMAN_ONLY +- added gzerror() diff --git a/3rdparty/zlib/FAQ b/3rdparty/zlib/FAQ index c154978f10..99b7cf92e4 100644 --- a/3rdparty/zlib/FAQ +++ b/3rdparty/zlib/FAQ @@ -1,366 +1,368 @@ - - Frequently Asked Questions about zlib - - -If your question is not there, please check the zlib home page -http://zlib.net/ which may have more recent information. -The lastest zlib FAQ is at http://zlib.net/zlib_faq.html - - - 1. Is zlib Y2K-compliant? - - Yes. zlib doesn't handle dates. - - 2. Where can I get a Windows DLL version? - - The zlib sources can be compiled without change to produce a DLL. See the - file win32/DLL_FAQ.txt in the zlib distribution. Pointers to the - precompiled DLL are found in the zlib web site at http://zlib.net/ . - - 3. Where can I get a Visual Basic interface to zlib? - - See - * http://marknelson.us/1997/01/01/zlib-engine/ - * win32/DLL_FAQ.txt in the zlib distribution - - 4. compress() returns Z_BUF_ERROR. - - Make sure that before the call of compress(), the length of the compressed - buffer is equal to the available size of the compressed buffer and not - zero. For Visual Basic, check that this parameter is passed by reference - ("as any"), not by value ("as long"). - - 5. deflate() or inflate() returns Z_BUF_ERROR. - - Before making the call, make sure that avail_in and avail_out are not zero. - When setting the parameter flush equal to Z_FINISH, also make sure that - avail_out is big enough to allow processing all pending input. Note that a - Z_BUF_ERROR is not fatal--another call to deflate() or inflate() can be - made with more input or output space. A Z_BUF_ERROR may in fact be - unavoidable depending on how the functions are used, since it is not - possible to tell whether or not there is more output pending when - strm.avail_out returns with zero. See http://zlib.net/zlib_how.html for a - heavily annotated example. - - 6. Where's the zlib documentation (man pages, etc.)? - - It's in zlib.h . Examples of zlib usage are in the files example.c and - minigzip.c, with more in examples/ . - - 7. Why don't you use GNU autoconf or libtool or ...? - - Because we would like to keep zlib as a very small and simple package. - zlib is rather portable and doesn't need much configuration. - - 8. I found a bug in zlib. - - Most of the time, such problems are due to an incorrect usage of zlib. - Please try to reproduce the problem with a small program and send the - corresponding source to us at zlib@gzip.org . Do not send multi-megabyte - data files without prior agreement. - - 9. Why do I get "undefined reference to gzputc"? - - If "make test" produces something like - - example.o(.text+0x154): undefined reference to `gzputc' - - check that you don't have old files libz.* in /usr/lib, /usr/local/lib or - /usr/X11R6/lib. Remove any old versions, then do "make install". - -10. I need a Delphi interface to zlib. - - See the contrib/delphi directory in the zlib distribution. - -11. Can zlib handle .zip archives? - - Not by itself, no. See the directory contrib/minizip in the zlib - distribution. - -12. Can zlib handle .Z files? - - No, sorry. You have to spawn an uncompress or gunzip subprocess, or adapt - the code of uncompress on your own. - -13. How can I make a Unix shared library? - - make clean - ./configure -s - make - -14. How do I install a shared zlib library on Unix? - - After the above, then: - - make install - - However, many flavors of Unix come with a shared zlib already installed. - Before going to the trouble of compiling a shared version of zlib and - trying to install it, you may want to check if it's already there! If you - can #include , it's there. The -lz option will probably link to - it. You can check the version at the top of zlib.h or with the - ZLIB_VERSION symbol defined in zlib.h . - -15. I have a question about OttoPDF. - - We are not the authors of OttoPDF. The real author is on the OttoPDF web - site: Joel Hainley, jhainley@myndkryme.com. - -16. Can zlib decode Flate data in an Adobe PDF file? - - Yes. See http://www.pdflib.com/ . To modify PDF forms, see - http://sourceforge.net/projects/acroformtool/ . - -17. Why am I getting this "register_frame_info not found" error on Solaris? - - After installing zlib 1.1.4 on Solaris 2.6, running applications using zlib - generates an error such as: - - ld.so.1: rpm: fatal: relocation error: file /usr/local/lib/libz.so: - symbol __register_frame_info: referenced symbol not found - - The symbol __register_frame_info is not part of zlib, it is generated by - the C compiler (cc or gcc). You must recompile applications using zlib - which have this problem. This problem is specific to Solaris. See - http://www.sunfreeware.com for Solaris versions of zlib and applications - using zlib. - -18. Why does gzip give an error on a file I make with compress/deflate? - - The compress and deflate functions produce data in the zlib format, which - is different and incompatible with the gzip format. The gz* functions in - zlib on the other hand use the gzip format. Both the zlib and gzip formats - use the same compressed data format internally, but have different headers - and trailers around the compressed data. - -19. Ok, so why are there two different formats? - - The gzip format was designed to retain the directory information about a - single file, such as the name and last modification date. The zlib format - on the other hand was designed for in-memory and communication channel - applications, and has a much more compact header and trailer and uses a - faster integrity check than gzip. - -20. Well that's nice, but how do I make a gzip file in memory? - - You can request that deflate write the gzip format instead of the zlib - format using deflateInit2(). You can also request that inflate decode the - gzip format using inflateInit2(). Read zlib.h for more details. - -21. Is zlib thread-safe? - - Yes. However any library routines that zlib uses and any application- - provided memory allocation routines must also be thread-safe. zlib's gz* - functions use stdio library routines, and most of zlib's functions use the - library memory allocation routines by default. zlib's *Init* functions - allow for the application to provide custom memory allocation routines. - - Of course, you should only operate on any given zlib or gzip stream from a - single thread at a time. - -22. Can I use zlib in my commercial application? - - Yes. Please read the license in zlib.h. - -23. Is zlib under the GNU license? - - No. Please read the license in zlib.h. - -24. The license says that altered source versions must be "plainly marked". So - what exactly do I need to do to meet that requirement? - - You need to change the ZLIB_VERSION and ZLIB_VERNUM #defines in zlib.h. In - particular, the final version number needs to be changed to "f", and an - identification string should be appended to ZLIB_VERSION. Version numbers - x.x.x.f are reserved for modifications to zlib by others than the zlib - maintainers. For example, if the version of the base zlib you are altering - is "1.2.3.4", then in zlib.h you should change ZLIB_VERNUM to 0x123f, and - ZLIB_VERSION to something like "1.2.3.f-zachary-mods-v3". You can also - update the version strings in deflate.c and inftrees.c. - - For altered source distributions, you should also note the origin and - nature of the changes in zlib.h, as well as in ChangeLog and README, along - with the dates of the alterations. The origin should include at least your - name (or your company's name), and an email address to contact for help or - issues with the library. - - Note that distributing a compiled zlib library along with zlib.h and - zconf.h is also a source distribution, and so you should change - ZLIB_VERSION and ZLIB_VERNUM and note the origin and nature of the changes - in zlib.h as you would for a full source distribution. - -25. Will zlib work on a big-endian or little-endian architecture, and can I - exchange compressed data between them? - - Yes and yes. - -26. Will zlib work on a 64-bit machine? - - Yes. It has been tested on 64-bit machines, and has no dependence on any - data types being limited to 32-bits in length. If you have any - difficulties, please provide a complete problem report to zlib@gzip.org - -27. Will zlib decompress data from the PKWare Data Compression Library? - - No. The PKWare DCL uses a completely different compressed data format than - does PKZIP and zlib. However, you can look in zlib's contrib/blast - directory for a possible solution to your problem. - -28. Can I access data randomly in a compressed stream? - - No, not without some preparation. If when compressing you periodically use - Z_FULL_FLUSH, carefully write all the pending data at those points, and - keep an index of those locations, then you can start decompression at those - points. You have to be careful to not use Z_FULL_FLUSH too often, since it - can significantly degrade compression. Alternatively, you can scan a - deflate stream once to generate an index, and then use that index for - random access. See examples/zran.c . - -29. Does zlib work on MVS, OS/390, CICS, etc.? - - It has in the past, but we have not heard of any recent evidence. There - were working ports of zlib 1.1.4 to MVS, but those links no longer work. - If you know of recent, successful applications of zlib on these operating - systems, please let us know. Thanks. - -30. Is there some simpler, easier to read version of inflate I can look at to - understand the deflate format? - - First off, you should read RFC 1951. Second, yes. Look in zlib's - contrib/puff directory. - -31. Does zlib infringe on any patents? - - As far as we know, no. In fact, that was originally the whole point behind - zlib. Look here for some more information: - - http://www.gzip.org/#faq11 - -32. Can zlib work with greater than 4 GB of data? - - Yes. inflate() and deflate() will process any amount of data correctly. - Each call of inflate() or deflate() is limited to input and output chunks - of the maximum value that can be stored in the compiler's "unsigned int" - type, but there is no limit to the number of chunks. Note however that the - strm.total_in and strm_total_out counters may be limited to 4 GB. These - counters are provided as a convenience and are not used internally by - inflate() or deflate(). The application can easily set up its own counters - updated after each call of inflate() or deflate() to count beyond 4 GB. - compress() and uncompress() may be limited to 4 GB, since they operate in a - single call. gzseek() and gztell() may be limited to 4 GB depending on how - zlib is compiled. See the zlibCompileFlags() function in zlib.h. - - The word "may" appears several times above since there is a 4 GB limit only - if the compiler's "long" type is 32 bits. If the compiler's "long" type is - 64 bits, then the limit is 16 exabytes. - -33. Does zlib have any security vulnerabilities? - - The only one that we are aware of is potentially in gzprintf(). If zlib is - compiled to use sprintf() or vsprintf(), then there is no protection - against a buffer overflow of an 8K string space (or other value as set by - gzbuffer()), other than the caller of gzprintf() assuring that the output - will not exceed 8K. On the other hand, if zlib is compiled to use - snprintf() or vsnprintf(), which should normally be the case, then there is - no vulnerability. The ./configure script will display warnings if an - insecure variation of sprintf() will be used by gzprintf(). Also the - zlibCompileFlags() function will return information on what variant of - sprintf() is used by gzprintf(). - - If you don't have snprintf() or vsnprintf() and would like one, you can - find a portable implementation here: - - http://www.ijs.si/software/snprintf/ - - Note that you should be using the most recent version of zlib. Versions - 1.1.3 and before were subject to a double-free vulnerability, and versions - 1.2.1 and 1.2.2 were subject to an access exception when decompressing - invalid compressed data. - -34. Is there a Java version of zlib? - - Probably what you want is to use zlib in Java. zlib is already included - as part of the Java SDK in the java.util.zip package. If you really want - a version of zlib written in the Java language, look on the zlib home - page for links: http://zlib.net/ . - -35. I get this or that compiler or source-code scanner warning when I crank it - up to maximally-pedantic. Can't you guys write proper code? - - Many years ago, we gave up attempting to avoid warnings on every compiler - in the universe. It just got to be a waste of time, and some compilers - were downright silly as well as contradicted each other. So now, we simply - make sure that the code always works. - -36. Valgrind (or some similar memory access checker) says that deflate is - performing a conditional jump that depends on an uninitialized value. - Isn't that a bug? - - No. That is intentional for performance reasons, and the output of deflate - is not affected. This only started showing up recently since zlib 1.2.x - uses malloc() by default for allocations, whereas earlier versions used - calloc(), which zeros out the allocated memory. Even though the code was - correct, versions 1.2.4 and later was changed to not stimulate these - checkers. - -37. Will zlib read the (insert any ancient or arcane format here) compressed - data format? - - Probably not. Look in the comp.compression FAQ for pointers to various - formats and associated software. - -38. How can I encrypt/decrypt zip files with zlib? - - zlib doesn't support encryption. The original PKZIP encryption is very - weak and can be broken with freely available programs. To get strong - encryption, use GnuPG, http://www.gnupg.org/ , which already includes zlib - compression. For PKZIP compatible "encryption", look at - http://www.info-zip.org/ - -39. What's the difference between the "gzip" and "deflate" HTTP 1.1 encodings? - - "gzip" is the gzip format, and "deflate" is the zlib format. They should - probably have called the second one "zlib" instead to avoid confusion with - the raw deflate compressed data format. While the HTTP 1.1 RFC 2616 - correctly points to the zlib specification in RFC 1950 for the "deflate" - transfer encoding, there have been reports of servers and browsers that - incorrectly produce or expect raw deflate data per the deflate - specficiation in RFC 1951, most notably Microsoft. So even though the - "deflate" transfer encoding using the zlib format would be the more - efficient approach (and in fact exactly what the zlib format was designed - for), using the "gzip" transfer encoding is probably more reliable due to - an unfortunate choice of name on the part of the HTTP 1.1 authors. - - Bottom line: use the gzip format for HTTP 1.1 encoding. - -40. Does zlib support the new "Deflate64" format introduced by PKWare? - - No. PKWare has apparently decided to keep that format proprietary, since - they have not documented it as they have previous compression formats. In - any case, the compression improvements are so modest compared to other more - modern approaches, that it's not worth the effort to implement. - -41. I'm having a problem with the zip functions in zlib, can you help? - - There are no zip functions in zlib. You are probably using minizip by - Giles Vollant, which is found in the contrib directory of zlib. It is not - part of zlib. In fact none of the stuff in contrib is part of zlib. The - files in there are not supported by the zlib authors. You need to contact - the authors of the respective contribution for help. - -42. The match.asm code in contrib is under the GNU General Public License. - Since it's part of zlib, doesn't that mean that all of zlib falls under the - GNU GPL? - - No. The files in contrib are not part of zlib. They were contributed by - other authors and are provided as a convenience to the user within the zlib - distribution. Each item in contrib has its own license. - -43. Is zlib subject to export controls? What is its ECCN? - - zlib is not subject to export controls, and so is classified as EAR99. - -44. Can you please sign these lengthy legal documents and fax them back to us - so that we can use your software in our product? - - No. Go away. Shoo. + + Frequently Asked Questions about zlib + + +If your question is not there, please check the zlib home page +http://zlib.net/ which may have more recent information. +The lastest zlib FAQ is at http://zlib.net/zlib_faq.html + + + 1. Is zlib Y2K-compliant? + + Yes. zlib doesn't handle dates. + + 2. Where can I get a Windows DLL version? + + The zlib sources can be compiled without change to produce a DLL. See the + file win32/DLL_FAQ.txt in the zlib distribution. Pointers to the + precompiled DLL are found in the zlib web site at http://zlib.net/ . + + 3. Where can I get a Visual Basic interface to zlib? + + See + * http://marknelson.us/1997/01/01/zlib-engine/ + * win32/DLL_FAQ.txt in the zlib distribution + + 4. compress() returns Z_BUF_ERROR. + + Make sure that before the call of compress(), the length of the compressed + buffer is equal to the available size of the compressed buffer and not + zero. For Visual Basic, check that this parameter is passed by reference + ("as any"), not by value ("as long"). + + 5. deflate() or inflate() returns Z_BUF_ERROR. + + Before making the call, make sure that avail_in and avail_out are not zero. + When setting the parameter flush equal to Z_FINISH, also make sure that + avail_out is big enough to allow processing all pending input. Note that a + Z_BUF_ERROR is not fatal--another call to deflate() or inflate() can be + made with more input or output space. A Z_BUF_ERROR may in fact be + unavoidable depending on how the functions are used, since it is not + possible to tell whether or not there is more output pending when + strm.avail_out returns with zero. See http://zlib.net/zlib_how.html for a + heavily annotated example. + + 6. Where's the zlib documentation (man pages, etc.)? + + It's in zlib.h . Examples of zlib usage are in the files test/example.c + and test/minigzip.c, with more in examples/ . + + 7. Why don't you use GNU autoconf or libtool or ...? + + Because we would like to keep zlib as a very small and simple package. + zlib is rather portable and doesn't need much configuration. + + 8. I found a bug in zlib. + + Most of the time, such problems are due to an incorrect usage of zlib. + Please try to reproduce the problem with a small program and send the + corresponding source to us at zlib@gzip.org . Do not send multi-megabyte + data files without prior agreement. + + 9. Why do I get "undefined reference to gzputc"? + + If "make test" produces something like + + example.o(.text+0x154): undefined reference to `gzputc' + + check that you don't have old files libz.* in /usr/lib, /usr/local/lib or + /usr/X11R6/lib. Remove any old versions, then do "make install". + +10. I need a Delphi interface to zlib. + + See the contrib/delphi directory in the zlib distribution. + +11. Can zlib handle .zip archives? + + Not by itself, no. See the directory contrib/minizip in the zlib + distribution. + +12. Can zlib handle .Z files? + + No, sorry. You have to spawn an uncompress or gunzip subprocess, or adapt + the code of uncompress on your own. + +13. How can I make a Unix shared library? + + By default a shared (and a static) library is built for Unix. So: + + make distclean + ./configure + make + +14. How do I install a shared zlib library on Unix? + + After the above, then: + + make install + + However, many flavors of Unix come with a shared zlib already installed. + Before going to the trouble of compiling a shared version of zlib and + trying to install it, you may want to check if it's already there! If you + can #include , it's there. The -lz option will probably link to + it. You can check the version at the top of zlib.h or with the + ZLIB_VERSION symbol defined in zlib.h . + +15. I have a question about OttoPDF. + + We are not the authors of OttoPDF. The real author is on the OttoPDF web + site: Joel Hainley, jhainley@myndkryme.com. + +16. Can zlib decode Flate data in an Adobe PDF file? + + Yes. See http://www.pdflib.com/ . To modify PDF forms, see + http://sourceforge.net/projects/acroformtool/ . + +17. Why am I getting this "register_frame_info not found" error on Solaris? + + After installing zlib 1.1.4 on Solaris 2.6, running applications using zlib + generates an error such as: + + ld.so.1: rpm: fatal: relocation error: file /usr/local/lib/libz.so: + symbol __register_frame_info: referenced symbol not found + + The symbol __register_frame_info is not part of zlib, it is generated by + the C compiler (cc or gcc). You must recompile applications using zlib + which have this problem. This problem is specific to Solaris. See + http://www.sunfreeware.com for Solaris versions of zlib and applications + using zlib. + +18. Why does gzip give an error on a file I make with compress/deflate? + + The compress and deflate functions produce data in the zlib format, which + is different and incompatible with the gzip format. The gz* functions in + zlib on the other hand use the gzip format. Both the zlib and gzip formats + use the same compressed data format internally, but have different headers + and trailers around the compressed data. + +19. Ok, so why are there two different formats? + + The gzip format was designed to retain the directory information about a + single file, such as the name and last modification date. The zlib format + on the other hand was designed for in-memory and communication channel + applications, and has a much more compact header and trailer and uses a + faster integrity check than gzip. + +20. Well that's nice, but how do I make a gzip file in memory? + + You can request that deflate write the gzip format instead of the zlib + format using deflateInit2(). You can also request that inflate decode the + gzip format using inflateInit2(). Read zlib.h for more details. + +21. Is zlib thread-safe? + + Yes. However any library routines that zlib uses and any application- + provided memory allocation routines must also be thread-safe. zlib's gz* + functions use stdio library routines, and most of zlib's functions use the + library memory allocation routines by default. zlib's *Init* functions + allow for the application to provide custom memory allocation routines. + + Of course, you should only operate on any given zlib or gzip stream from a + single thread at a time. + +22. Can I use zlib in my commercial application? + + Yes. Please read the license in zlib.h. + +23. Is zlib under the GNU license? + + No. Please read the license in zlib.h. + +24. The license says that altered source versions must be "plainly marked". So + what exactly do I need to do to meet that requirement? + + You need to change the ZLIB_VERSION and ZLIB_VERNUM #defines in zlib.h. In + particular, the final version number needs to be changed to "f", and an + identification string should be appended to ZLIB_VERSION. Version numbers + x.x.x.f are reserved for modifications to zlib by others than the zlib + maintainers. For example, if the version of the base zlib you are altering + is "1.2.3.4", then in zlib.h you should change ZLIB_VERNUM to 0x123f, and + ZLIB_VERSION to something like "1.2.3.f-zachary-mods-v3". You can also + update the version strings in deflate.c and inftrees.c. + + For altered source distributions, you should also note the origin and + nature of the changes in zlib.h, as well as in ChangeLog and README, along + with the dates of the alterations. The origin should include at least your + name (or your company's name), and an email address to contact for help or + issues with the library. + + Note that distributing a compiled zlib library along with zlib.h and + zconf.h is also a source distribution, and so you should change + ZLIB_VERSION and ZLIB_VERNUM and note the origin and nature of the changes + in zlib.h as you would for a full source distribution. + +25. Will zlib work on a big-endian or little-endian architecture, and can I + exchange compressed data between them? + + Yes and yes. + +26. Will zlib work on a 64-bit machine? + + Yes. It has been tested on 64-bit machines, and has no dependence on any + data types being limited to 32-bits in length. If you have any + difficulties, please provide a complete problem report to zlib@gzip.org + +27. Will zlib decompress data from the PKWare Data Compression Library? + + No. The PKWare DCL uses a completely different compressed data format than + does PKZIP and zlib. However, you can look in zlib's contrib/blast + directory for a possible solution to your problem. + +28. Can I access data randomly in a compressed stream? + + No, not without some preparation. If when compressing you periodically use + Z_FULL_FLUSH, carefully write all the pending data at those points, and + keep an index of those locations, then you can start decompression at those + points. You have to be careful to not use Z_FULL_FLUSH too often, since it + can significantly degrade compression. Alternatively, you can scan a + deflate stream once to generate an index, and then use that index for + random access. See examples/zran.c . + +29. Does zlib work on MVS, OS/390, CICS, etc.? + + It has in the past, but we have not heard of any recent evidence. There + were working ports of zlib 1.1.4 to MVS, but those links no longer work. + If you know of recent, successful applications of zlib on these operating + systems, please let us know. Thanks. + +30. Is there some simpler, easier to read version of inflate I can look at to + understand the deflate format? + + First off, you should read RFC 1951. Second, yes. Look in zlib's + contrib/puff directory. + +31. Does zlib infringe on any patents? + + As far as we know, no. In fact, that was originally the whole point behind + zlib. Look here for some more information: + + http://www.gzip.org/#faq11 + +32. Can zlib work with greater than 4 GB of data? + + Yes. inflate() and deflate() will process any amount of data correctly. + Each call of inflate() or deflate() is limited to input and output chunks + of the maximum value that can be stored in the compiler's "unsigned int" + type, but there is no limit to the number of chunks. Note however that the + strm.total_in and strm_total_out counters may be limited to 4 GB. These + counters are provided as a convenience and are not used internally by + inflate() or deflate(). The application can easily set up its own counters + updated after each call of inflate() or deflate() to count beyond 4 GB. + compress() and uncompress() may be limited to 4 GB, since they operate in a + single call. gzseek() and gztell() may be limited to 4 GB depending on how + zlib is compiled. See the zlibCompileFlags() function in zlib.h. + + The word "may" appears several times above since there is a 4 GB limit only + if the compiler's "long" type is 32 bits. If the compiler's "long" type is + 64 bits, then the limit is 16 exabytes. + +33. Does zlib have any security vulnerabilities? + + The only one that we are aware of is potentially in gzprintf(). If zlib is + compiled to use sprintf() or vsprintf(), then there is no protection + against a buffer overflow of an 8K string space (or other value as set by + gzbuffer()), other than the caller of gzprintf() assuring that the output + will not exceed 8K. On the other hand, if zlib is compiled to use + snprintf() or vsnprintf(), which should normally be the case, then there is + no vulnerability. The ./configure script will display warnings if an + insecure variation of sprintf() will be used by gzprintf(). Also the + zlibCompileFlags() function will return information on what variant of + sprintf() is used by gzprintf(). + + If you don't have snprintf() or vsnprintf() and would like one, you can + find a portable implementation here: + + http://www.ijs.si/software/snprintf/ + + Note that you should be using the most recent version of zlib. Versions + 1.1.3 and before were subject to a double-free vulnerability, and versions + 1.2.1 and 1.2.2 were subject to an access exception when decompressing + invalid compressed data. + +34. Is there a Java version of zlib? + + Probably what you want is to use zlib in Java. zlib is already included + as part of the Java SDK in the java.util.zip package. If you really want + a version of zlib written in the Java language, look on the zlib home + page for links: http://zlib.net/ . + +35. I get this or that compiler or source-code scanner warning when I crank it + up to maximally-pedantic. Can't you guys write proper code? + + Many years ago, we gave up attempting to avoid warnings on every compiler + in the universe. It just got to be a waste of time, and some compilers + were downright silly as well as contradicted each other. So now, we simply + make sure that the code always works. + +36. Valgrind (or some similar memory access checker) says that deflate is + performing a conditional jump that depends on an uninitialized value. + Isn't that a bug? + + No. That is intentional for performance reasons, and the output of deflate + is not affected. This only started showing up recently since zlib 1.2.x + uses malloc() by default for allocations, whereas earlier versions used + calloc(), which zeros out the allocated memory. Even though the code was + correct, versions 1.2.4 and later was changed to not stimulate these + checkers. + +37. Will zlib read the (insert any ancient or arcane format here) compressed + data format? + + Probably not. Look in the comp.compression FAQ for pointers to various + formats and associated software. + +38. How can I encrypt/decrypt zip files with zlib? + + zlib doesn't support encryption. The original PKZIP encryption is very + weak and can be broken with freely available programs. To get strong + encryption, use GnuPG, http://www.gnupg.org/ , which already includes zlib + compression. For PKZIP compatible "encryption", look at + http://www.info-zip.org/ + +39. What's the difference between the "gzip" and "deflate" HTTP 1.1 encodings? + + "gzip" is the gzip format, and "deflate" is the zlib format. They should + probably have called the second one "zlib" instead to avoid confusion with + the raw deflate compressed data format. While the HTTP 1.1 RFC 2616 + correctly points to the zlib specification in RFC 1950 for the "deflate" + transfer encoding, there have been reports of servers and browsers that + incorrectly produce or expect raw deflate data per the deflate + specification in RFC 1951, most notably Microsoft. So even though the + "deflate" transfer encoding using the zlib format would be the more + efficient approach (and in fact exactly what the zlib format was designed + for), using the "gzip" transfer encoding is probably more reliable due to + an unfortunate choice of name on the part of the HTTP 1.1 authors. + + Bottom line: use the gzip format for HTTP 1.1 encoding. + +40. Does zlib support the new "Deflate64" format introduced by PKWare? + + No. PKWare has apparently decided to keep that format proprietary, since + they have not documented it as they have previous compression formats. In + any case, the compression improvements are so modest compared to other more + modern approaches, that it's not worth the effort to implement. + +41. I'm having a problem with the zip functions in zlib, can you help? + + There are no zip functions in zlib. You are probably using minizip by + Giles Vollant, which is found in the contrib directory of zlib. It is not + part of zlib. In fact none of the stuff in contrib is part of zlib. The + files in there are not supported by the zlib authors. You need to contact + the authors of the respective contribution for help. + +42. The match.asm code in contrib is under the GNU General Public License. + Since it's part of zlib, doesn't that mean that all of zlib falls under the + GNU GPL? + + No. The files in contrib are not part of zlib. They were contributed by + other authors and are provided as a convenience to the user within the zlib + distribution. Each item in contrib has its own license. + +43. Is zlib subject to export controls? What is its ECCN? + + zlib is not subject to export controls, and so is classified as EAR99. + +44. Can you please sign these lengthy legal documents and fax them back to us + so that we can use your software in our product? + + No. Go away. Shoo. diff --git a/3rdparty/zlib/README b/3rdparty/zlib/README index 5fb367d0a8..6f1255ffe4 100644 --- a/3rdparty/zlib/README +++ b/3rdparty/zlib/README @@ -1,114 +1,115 @@ -ZLIB DATA COMPRESSION LIBRARY - -zlib 1.2.4 is a general purpose data compression library. All the code is -thread safe. The data format used by the zlib library is described by RFCs -(Request for Comments) 1950 to 1952 in the files -http://www.ietf.org/rfc/rfc1950.txt (zlib format), rfc1951.txt (deflate format) -and rfc1952.txt (gzip format). - -All functions of the compression library are documented in the file zlib.h -(volunteer to write man pages welcome, contact zlib@gzip.org). A usage example -of the library is given in the file example.c which also tests that the library -is working correctly. Another example is given in the file minigzip.c. The -compression library itself is composed of all source files except example.c and -minigzip.c. - -To compile all files and run the test program, follow the instructions given at -the top of Makefile.in. In short "./configure; make test", and if that goes -well, "make install" should work for most flavors of Unix. For Windows, use one -of the special makefiles in win32/ or projects/ . For VMS, use make_vms.com. - -Questions about zlib should be sent to , or to Gilles Vollant - for the Windows DLL version. The zlib home page is -http://zlib.net/ . Before reporting a problem, please check this site to -verify that you have the latest version of zlib; otherwise get the latest -version and check whether the problem still exists or not. - -PLEASE read the zlib FAQ http://zlib.net/zlib_faq.html before asking for help. - -Mark Nelson wrote an article about zlib for the Jan. 1997 -issue of Dr. Dobb's Journal; a copy of the article is available at -http://marknelson.us/1997/01/01/zlib-engine/ . - -The changes made in version 1.2.4 are documented in the file ChangeLog. - -Unsupported third party contributions are provided in directory contrib/ . - -zlib is available in Java using the java.util.zip package, documented at -http://java.sun.com/developer/technicalArticles/Programming/compression/ . - -A Perl interface to zlib written by Paul Marquess is available -at CPAN (Comprehensive Perl Archive Network) sites, including -http://search.cpan.org/~pmqs/IO-Compress-Zlib/ . - -A Python interface to zlib written by A.M. Kuchling is -available in Python 1.5 and later versions, see -http://www.python.org/doc/lib/module-zlib.html . - -zlib is built into tcl: http://wiki.tcl.tk/4610 . - -An experimental package to read and write files in .zip format, written on top -of zlib by Gilles Vollant , is available in the -contrib/minizip directory of zlib. - - -Notes for some targets: - -- For Windows DLL versions, please see win32/DLL_FAQ.txt - -- For 64-bit Irix, deflate.c must be compiled without any optimization. With - -O, one libpng test fails. The test works in 32 bit mode (with the -n32 - compiler flag). The compiler bug has been reported to SGI. - -- zlib doesn't work with gcc 2.6.3 on a DEC 3000/300LX under OSF/1 2.1 it works - when compiled with cc. - -- On Digital Unix 4.0D (formely OSF/1) on AlphaServer, the cc option -std1 is - necessary to get gzprintf working correctly. This is done by configure. - -- zlib doesn't work on HP-UX 9.05 with some versions of /bin/cc. It works with - other compilers. Use "make test" to check your compiler. - -- gzdopen is not supported on RISCOS or BEOS. - -- For PalmOs, see http://palmzlib.sourceforge.net/ - - -Acknowledgments: - - The deflate format used by zlib was defined by Phil Katz. The deflate and - zlib specifications were written by L. Peter Deutsch. Thanks to all the - people who reported problems and suggested various improvements in zlib; they - are too numerous to cite here. - -Copyright notice: - - (C) 1995-2010 Jean-loup Gailly and Mark Adler - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jean-loup Gailly Mark Adler - jloup@gzip.org madler@alumni.caltech.edu - -If you use the zlib library in a product, we would appreciate *not* receiving -lengthy legal documents to sign. The sources are provided for free but without -warranty of any kind. The library has been entirely written by Jean-loup -Gailly and Mark Adler; it does not include third-party code. - -If you redistribute modified sources, we would appreciate that you include in -the file ChangeLog history information documenting your changes. Please read -the FAQ for more information on the distribution of modified source versions. +ZLIB DATA COMPRESSION LIBRARY + +zlib 1.2.7 is a general purpose data compression library. All the code is +thread safe. The data format used by the zlib library is described by RFCs +(Request for Comments) 1950 to 1952 in the files +http://tools.ietf.org/html/rfc1950 (zlib format), rfc1951 (deflate format) and +rfc1952 (gzip format). + +All functions of the compression library are documented in the file zlib.h +(volunteer to write man pages welcome, contact zlib@gzip.org). A usage example +of the library is given in the file test/example.c which also tests that +the library is working correctly. Another example is given in the file +test/minigzip.c. The compression library itself is composed of all source +files in the root directory. + +To compile all files and run the test program, follow the instructions given at +the top of Makefile.in. In short "./configure; make test", and if that goes +well, "make install" should work for most flavors of Unix. For Windows, use +one of the special makefiles in win32/ or contrib/vstudio/ . For VMS, use +make_vms.com. + +Questions about zlib should be sent to , or to Gilles Vollant + for the Windows DLL version. The zlib home page is +http://zlib.net/ . Before reporting a problem, please check this site to +verify that you have the latest version of zlib; otherwise get the latest +version and check whether the problem still exists or not. + +PLEASE read the zlib FAQ http://zlib.net/zlib_faq.html before asking for help. + +Mark Nelson wrote an article about zlib for the Jan. 1997 +issue of Dr. Dobb's Journal; a copy of the article is available at +http://marknelson.us/1997/01/01/zlib-engine/ . + +The changes made in version 1.2.7 are documented in the file ChangeLog. + +Unsupported third party contributions are provided in directory contrib/ . + +zlib is available in Java using the java.util.zip package, documented at +http://java.sun.com/developer/technicalArticles/Programming/compression/ . + +A Perl interface to zlib written by Paul Marquess is available +at CPAN (Comprehensive Perl Archive Network) sites, including +http://search.cpan.org/~pmqs/IO-Compress-Zlib/ . + +A Python interface to zlib written by A.M. Kuchling is +available in Python 1.5 and later versions, see +http://docs.python.org/library/zlib.html . + +zlib is built into tcl: http://wiki.tcl.tk/4610 . + +An experimental package to read and write files in .zip format, written on top +of zlib by Gilles Vollant , is available in the +contrib/minizip directory of zlib. + + +Notes for some targets: + +- For Windows DLL versions, please see win32/DLL_FAQ.txt + +- For 64-bit Irix, deflate.c must be compiled without any optimization. With + -O, one libpng test fails. The test works in 32 bit mode (with the -n32 + compiler flag). The compiler bug has been reported to SGI. + +- zlib doesn't work with gcc 2.6.3 on a DEC 3000/300LX under OSF/1 2.1 it works + when compiled with cc. + +- On Digital Unix 4.0D (formely OSF/1) on AlphaServer, the cc option -std1 is + necessary to get gzprintf working correctly. This is done by configure. + +- zlib doesn't work on HP-UX 9.05 with some versions of /bin/cc. It works with + other compilers. Use "make test" to check your compiler. + +- gzdopen is not supported on RISCOS or BEOS. + +- For PalmOs, see http://palmzlib.sourceforge.net/ + + +Acknowledgments: + + The deflate format used by zlib was defined by Phil Katz. The deflate and + zlib specifications were written by L. Peter Deutsch. Thanks to all the + people who reported problems and suggested various improvements in zlib; they + are too numerous to cite here. + +Copyright notice: + + (C) 1995-2012 Jean-loup Gailly and Mark Adler + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + Jean-loup Gailly Mark Adler + jloup@gzip.org madler@alumni.caltech.edu + +If you use the zlib library in a product, we would appreciate *not* receiving +lengthy legal documents to sign. The sources are provided for free but without +warranty of any kind. The library has been entirely written by Jean-loup +Gailly and Mark Adler; it does not include third-party code. + +If you redistribute modified sources, we would appreciate that you include in +the file ChangeLog history information documenting your changes. Please read +the FAQ for more information on the distribution of modified source versions. diff --git a/3rdparty/zlib/adler32.c b/3rdparty/zlib/adler32.c index 65ad6a5adc..a868f073d8 100644 --- a/3rdparty/zlib/adler32.c +++ b/3rdparty/zlib/adler32.c @@ -1,5 +1,5 @@ /* adler32.c -- compute the Adler-32 checksum of a data stream - * Copyright (C) 1995-2007 Mark Adler + * Copyright (C) 1995-2011 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ @@ -9,9 +9,9 @@ #define local static -local uLong adler32_combine_(uLong adler1, uLong adler2, z_off64_t len2); +local uLong adler32_combine_ OF((uLong adler1, uLong adler2, z_off64_t len2)); -#define BASE 65521UL /* largest prime smaller than 65536 */ +#define BASE 65521 /* largest prime smaller than 65536 */ #define NMAX 5552 /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */ @@ -21,39 +21,44 @@ local uLong adler32_combine_(uLong adler1, uLong adler2, z_off64_t len2); #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4); #define DO16(buf) DO8(buf,0); DO8(buf,8); -/* use NO_DIVIDE if your processor does not do division in hardware */ +/* use NO_DIVIDE if your processor does not do division in hardware -- + try it both ways to see which is faster */ #ifdef NO_DIVIDE -# define MOD(a) \ +/* note that this assumes BASE is 65521, where 65536 % 65521 == 15 + (thank you to John Reiser for pointing this out) */ +# define CHOP(a) \ do { \ - if (a >= (BASE << 16)) a -= (BASE << 16); \ - if (a >= (BASE << 15)) a -= (BASE << 15); \ - if (a >= (BASE << 14)) a -= (BASE << 14); \ - if (a >= (BASE << 13)) a -= (BASE << 13); \ - if (a >= (BASE << 12)) a -= (BASE << 12); \ - if (a >= (BASE << 11)) a -= (BASE << 11); \ - if (a >= (BASE << 10)) a -= (BASE << 10); \ - if (a >= (BASE << 9)) a -= (BASE << 9); \ - if (a >= (BASE << 8)) a -= (BASE << 8); \ - if (a >= (BASE << 7)) a -= (BASE << 7); \ - if (a >= (BASE << 6)) a -= (BASE << 6); \ - if (a >= (BASE << 5)) a -= (BASE << 5); \ - if (a >= (BASE << 4)) a -= (BASE << 4); \ - if (a >= (BASE << 3)) a -= (BASE << 3); \ - if (a >= (BASE << 2)) a -= (BASE << 2); \ - if (a >= (BASE << 1)) a -= (BASE << 1); \ + unsigned long tmp = a >> 16; \ + a &= 0xffffUL; \ + a += (tmp << 4) - tmp; \ + } while (0) +# define MOD28(a) \ + do { \ + CHOP(a); \ if (a >= BASE) a -= BASE; \ } while (0) -# define MOD4(a) \ +# define MOD(a) \ do { \ - if (a >= (BASE << 4)) a -= (BASE << 4); \ - if (a >= (BASE << 3)) a -= (BASE << 3); \ - if (a >= (BASE << 2)) a -= (BASE << 2); \ - if (a >= (BASE << 1)) a -= (BASE << 1); \ + CHOP(a); \ + MOD28(a); \ + } while (0) +# define MOD63(a) \ + do { /* this assumes a is not negative */ \ + z_off64_t tmp = a >> 32; \ + a &= 0xffffffffL; \ + a += (tmp << 8) - (tmp << 5) + tmp; \ + tmp = a >> 16; \ + a &= 0xffffL; \ + a += (tmp << 4) - tmp; \ + tmp = a >> 16; \ + a &= 0xffffL; \ + a += (tmp << 4) - tmp; \ if (a >= BASE) a -= BASE; \ } while (0) #else # define MOD(a) a %= BASE -# define MOD4(a) a %= BASE +# define MOD28(a) a %= BASE +# define MOD63(a) a %= BASE #endif /* ========================================================================= */ @@ -92,7 +97,7 @@ uLong ZEXPORT adler32(adler, buf, len) } if (adler >= BASE) adler -= BASE; - MOD4(sum2); /* only added so many BASE's */ + MOD28(sum2); /* only added so many BASE's */ return adler | (sum2 << 16); } @@ -137,8 +142,13 @@ local uLong adler32_combine_(adler1, adler2, len2) unsigned long sum2; unsigned rem; + /* for negative len, return invalid adler32 as a clue for debugging */ + if (len2 < 0) + return 0xffffffffUL; + /* the derivation of this formula is left as an exercise for the reader */ - rem = (unsigned)(len2 % BASE); + MOD63(len2); /* assumes len2 >= 0 */ + rem = (unsigned)len2; sum1 = adler1 & 0xffff; sum2 = rem * sum1; MOD(sum2); diff --git a/3rdparty/zlib/crc32.c b/3rdparty/zlib/crc32.c index 1acc7ed8e4..979a7190a3 100644 --- a/3rdparty/zlib/crc32.c +++ b/3rdparty/zlib/crc32.c @@ -1,5 +1,5 @@ /* crc32.c -- compute the CRC-32 of a data stream - * Copyright (C) 1995-2006 Mark Adler + * Copyright (C) 1995-2006, 2010, 2011, 2012 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h * * Thanks to Rodney Brown for his contribution of faster @@ -17,6 +17,8 @@ of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should first call get_crc_table() to initialize the tables before allowing more than one thread to use crc32(). + + DYNAMIC_CRC_TABLE and MAKECRCH can be #defined to write out crc32.h. */ #ifdef MAKECRCH @@ -30,31 +32,11 @@ #define local static -/* Find a four-byte integer type for crc32_little() and crc32_big(). */ -#ifndef NOBYFOUR -# ifdef STDC /* need ANSI C limits.h to determine sizes */ -# include -# define BYFOUR -# if (UINT_MAX == 0xffffffffUL) - typedef unsigned int u4; -# else -# if (ULONG_MAX == 0xffffffffUL) - typedef unsigned long u4; -# else -# if (USHRT_MAX == 0xffffffffUL) - typedef unsigned short u4; -# else -# undef BYFOUR /* can't find a four-byte integer type! */ -# endif -# endif -# endif -# endif /* STDC */ -#endif /* !NOBYFOUR */ - /* Definitions for doing the crc four data bytes at a time. */ +#if !defined(NOBYFOUR) && defined(Z_U4) +# define BYFOUR +#endif #ifdef BYFOUR -# define REV(w) ((((w)>>24)&0xff)+(((w)>>8)&0xff00)+ \ - (((w)&0xff00)<<8)+(((w)&0xff)<<24)) local unsigned long crc32_little OF((unsigned long, const unsigned char FAR *, unsigned)); local unsigned long crc32_big OF((unsigned long, @@ -68,16 +50,16 @@ local unsigned long gf2_matrix_times OF((unsigned long *mat, unsigned long vec)); local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat)); -local uLong crc32_combine_(uLong crc1, uLong crc2, z_off64_t len2); +local uLong crc32_combine_ OF((uLong crc1, uLong crc2, z_off64_t len2)); #ifdef DYNAMIC_CRC_TABLE local volatile int crc_table_empty = 1; -local unsigned long FAR crc_table[TBLS][256]; +local z_crc_t FAR crc_table[TBLS][256]; local void make_crc_table OF((void)); #ifdef MAKECRCH - local void write_table OF((FILE *, const unsigned long FAR *)); + local void write_table OF((FILE *, const z_crc_t FAR *)); #endif /* MAKECRCH */ /* Generate tables for a byte-wise 32-bit CRC calculation on the polynomial: @@ -107,9 +89,9 @@ local void make_crc_table OF((void)); */ local void make_crc_table() { - unsigned long c; + z_crc_t c; int n, k; - unsigned long poly; /* polynomial exclusive-or pattern */ + z_crc_t poly; /* polynomial exclusive-or pattern */ /* terms of polynomial defining this crc (except x^32): */ static volatile int first = 1; /* flag to limit concurrent making */ static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26}; @@ -121,13 +103,13 @@ local void make_crc_table() first = 0; /* make exclusive-or pattern from polynomial (0xedb88320UL) */ - poly = 0UL; - for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++) - poly |= 1UL << (31 - p[n]); + poly = 0; + for (n = 0; n < (int)(sizeof(p)/sizeof(unsigned char)); n++) + poly |= (z_crc_t)1 << (31 - p[n]); /* generate a crc for every 8-bit value */ for (n = 0; n < 256; n++) { - c = (unsigned long)n; + c = (z_crc_t)n; for (k = 0; k < 8; k++) c = c & 1 ? poly ^ (c >> 1) : c >> 1; crc_table[0][n] = c; @@ -138,11 +120,11 @@ local void make_crc_table() and then the byte reversal of those as well as the first table */ for (n = 0; n < 256; n++) { c = crc_table[0][n]; - crc_table[4][n] = REV(c); + crc_table[4][n] = ZSWAP32(c); for (k = 1; k < 4; k++) { c = crc_table[0][c & 0xff] ^ (c >> 8); crc_table[k][n] = c; - crc_table[k + 4][n] = REV(c); + crc_table[k + 4][n] = ZSWAP32(c); } } #endif /* BYFOUR */ @@ -164,7 +146,7 @@ local void make_crc_table() if (out == NULL) return; fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n"); fprintf(out, " * Generated automatically by crc32.c\n */\n\n"); - fprintf(out, "local const unsigned long FAR "); + fprintf(out, "local const z_crc_t FAR "); fprintf(out, "crc_table[TBLS][256] =\n{\n {\n"); write_table(out, crc_table[0]); # ifdef BYFOUR @@ -184,12 +166,13 @@ local void make_crc_table() #ifdef MAKECRCH local void write_table(out, table) FILE *out; - const unsigned long FAR *table; + const z_crc_t FAR *table; { int n; for (n = 0; n < 256; n++) - fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n], + fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", + (unsigned long)(table[n]), n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", ")); } #endif /* MAKECRCH */ @@ -204,13 +187,13 @@ local void write_table(out, table) /* ========================================================================= * This function can be used by asm versions of crc32() */ -const unsigned long FAR * ZEXPORT get_crc_table() +const z_crc_t FAR * ZEXPORT get_crc_table() { #ifdef DYNAMIC_CRC_TABLE if (crc_table_empty) make_crc_table(); #endif /* DYNAMIC_CRC_TABLE */ - return (const unsigned long FAR *)crc_table; + return (const z_crc_t FAR *)crc_table; } /* ========================================================================= */ @@ -221,7 +204,7 @@ const unsigned long FAR * ZEXPORT get_crc_table() unsigned long ZEXPORT crc32(crc, buf, len) unsigned long crc; const unsigned char FAR *buf; - unsigned len; + uInt len; { if (buf == Z_NULL) return 0UL; @@ -232,7 +215,7 @@ unsigned long ZEXPORT crc32(crc, buf, len) #ifdef BYFOUR if (sizeof(void *) == sizeof(ptrdiff_t)) { - u4 endian; + z_crc_t endian; endian = 1; if (*((unsigned char *)(&endian))) @@ -266,17 +249,17 @@ local unsigned long crc32_little(crc, buf, len) const unsigned char FAR *buf; unsigned len; { - register u4 c; - register const u4 FAR *buf4; + register z_crc_t c; + register const z_crc_t FAR *buf4; - c = (u4)crc; + c = (z_crc_t)crc; c = ~c; while (len && ((ptrdiff_t)buf & 3)) { c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8); len--; } - buf4 = (const u4 FAR *)(const void FAR *)buf; + buf4 = (const z_crc_t FAR *)(const void FAR *)buf; while (len >= 32) { DOLIT32; len -= 32; @@ -306,17 +289,17 @@ local unsigned long crc32_big(crc, buf, len) const unsigned char FAR *buf; unsigned len; { - register u4 c; - register const u4 FAR *buf4; + register z_crc_t c; + register const z_crc_t FAR *buf4; - c = REV((u4)crc); + c = ZSWAP32((z_crc_t)crc); c = ~c; while (len && ((ptrdiff_t)buf & 3)) { c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8); len--; } - buf4 = (const u4 FAR *)(const void FAR *)buf; + buf4 = (const z_crc_t FAR *)(const void FAR *)buf; buf4--; while (len >= 32) { DOBIG32; @@ -333,7 +316,7 @@ local unsigned long crc32_big(crc, buf, len) c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8); } while (--len); c = ~c; - return (unsigned long)(REV(c)); + return (unsigned long)(ZSWAP32(c)); } #endif /* BYFOUR */ diff --git a/3rdparty/zlib/crc32.h b/3rdparty/zlib/crc32.h index 8053b6117c..9e0c778102 100644 --- a/3rdparty/zlib/crc32.h +++ b/3rdparty/zlib/crc32.h @@ -2,7 +2,7 @@ * Generated automatically by crc32.c */ -local const unsigned long FAR crc_table[TBLS][256] = +local const z_crc_t FAR crc_table[TBLS][256] = { { 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL, diff --git a/3rdparty/zlib/deflate.c b/3rdparty/zlib/deflate.c index fcd698cc62..9e4c2cbc8a 100644 --- a/3rdparty/zlib/deflate.c +++ b/3rdparty/zlib/deflate.c @@ -1,5 +1,5 @@ /* deflate.c -- compress data using the deflation algorithm - * Copyright (C) 1995-2010 Jean-loup Gailly and Mark Adler + * Copyright (C) 1995-2012 Jean-loup Gailly and Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ @@ -37,7 +37,7 @@ * REFERENCES * * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification". - * Available in http://www.ietf.org/rfc/rfc1951.txt + * Available in http://tools.ietf.org/html/rfc1951 * * A description of the Rabin and Karp algorithm is given in the book * "Algorithms" by R. Sedgewick, Addison-Wesley, p252. @@ -52,7 +52,7 @@ #include "deflate.h" const char deflate_copyright[] = - " deflate 1.2.4 Copyright 1995-2010 Jean-loup Gailly and Mark Adler "; + " deflate 1.2.7 Copyright 1995-2012 Jean-loup Gailly and Mark Adler "; /* If you use the zlib library in a product, an acknowledgment is welcome in the documentation of your product. If for some reason you cannot @@ -155,6 +155,9 @@ local const config configuration_table[10] = { struct static_tree_desc_s {int dummy;}; /* for buggy compilers */ #endif +/* rank Z_BLOCK between Z_NO_FLUSH and Z_PARTIAL_FLUSH */ +#define RANK(f) (((f) << 1) - ((f) > 4 ? 9 : 0)) + /* =========================================================================== * Update a hash value with the given input byte * IN assertion: all calls to to UPDATE_HASH are made with consecutive @@ -235,10 +238,19 @@ int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy, strm->msg = Z_NULL; if (strm->zalloc == (alloc_func)0) { +#ifdef Z_SOLO + return Z_STREAM_ERROR; +#else strm->zalloc = zcalloc; strm->opaque = (voidpf)0; +#endif } - if (strm->zfree == (free_func)0) strm->zfree = zcfree; + if (strm->zfree == (free_func)0) +#ifdef Z_SOLO + return Z_STREAM_ERROR; +#else + strm->zfree = zcfree; +#endif #ifdef FASTEST if (level != 0) level = 1; @@ -314,43 +326,70 @@ int ZEXPORT deflateSetDictionary (strm, dictionary, dictLength) uInt dictLength; { deflate_state *s; - uInt length = dictLength; - uInt n; - IPos hash_head = 0; + uInt str, n; + int wrap; + unsigned avail; + unsigned char *next; - if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL || - strm->state->wrap == 2 || - (strm->state->wrap == 1 && strm->state->status != INIT_STATE)) + if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL) + return Z_STREAM_ERROR; + s = strm->state; + wrap = s->wrap; + if (wrap == 2 || (wrap == 1 && s->status != INIT_STATE) || s->lookahead) return Z_STREAM_ERROR; - s = strm->state; - if (s->wrap) + /* when using zlib wrappers, compute Adler-32 for provided dictionary */ + if (wrap == 1) strm->adler = adler32(strm->adler, dictionary, dictLength); + s->wrap = 0; /* avoid computing Adler-32 in read_buf */ - if (length < MIN_MATCH) return Z_OK; - if (length > s->w_size) { - length = s->w_size; - dictionary += dictLength - length; /* use the tail of the dictionary */ + /* if dictionary would fill window, just replace the history */ + if (dictLength >= s->w_size) { + if (wrap == 0) { /* already empty otherwise */ + CLEAR_HASH(s); + s->strstart = 0; + s->block_start = 0L; + s->insert = 0; + } + dictionary += dictLength - s->w_size; /* use the tail */ + dictLength = s->w_size; } - zmemcpy(s->window, dictionary, length); - s->strstart = length; - s->block_start = (long)length; - /* Insert all strings in the hash table (except for the last two bytes). - * s->lookahead stays null, so s->ins_h will be recomputed at the next - * call of fill_window. - */ - s->ins_h = s->window[0]; - UPDATE_HASH(s, s->ins_h, s->window[1]); - for (n = 0; n <= length - MIN_MATCH; n++) { - INSERT_STRING(s, n, hash_head); + /* insert dictionary into window and hash */ + avail = strm->avail_in; + next = strm->next_in; + strm->avail_in = dictLength; + strm->next_in = (Bytef *)dictionary; + fill_window(s); + while (s->lookahead >= MIN_MATCH) { + str = s->strstart; + n = s->lookahead - (MIN_MATCH-1); + do { + UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); +#ifndef FASTEST + s->prev[str & s->w_mask] = s->head[s->ins_h]; +#endif + s->head[s->ins_h] = (Pos)str; + str++; + } while (--n); + s->strstart = str; + s->lookahead = MIN_MATCH-1; + fill_window(s); } - if (hash_head) hash_head = 0; /* to make compiler happy */ + s->strstart += s->lookahead; + s->block_start = (long)s->strstart; + s->insert = s->lookahead; + s->lookahead = 0; + s->match_length = s->prev_length = MIN_MATCH-1; + s->match_available = 0; + strm->next_in = next; + strm->avail_in = avail; + s->wrap = wrap; return Z_OK; } /* ========================================================================= */ -int ZEXPORT deflateReset (strm) +int ZEXPORT deflateResetKeep (strm) z_streamp strm; { deflate_state *s; @@ -380,11 +419,22 @@ int ZEXPORT deflateReset (strm) s->last_flush = Z_NO_FLUSH; _tr_init(s); - lm_init(s); return Z_OK; } +/* ========================================================================= */ +int ZEXPORT deflateReset (strm) + z_streamp strm; +{ + int ret; + + ret = deflateResetKeep(strm); + if (ret == Z_OK) + lm_init(strm->state); + return ret; +} + /* ========================================================================= */ int ZEXPORT deflateSetHeader (strm, head) z_streamp strm; @@ -396,15 +446,43 @@ int ZEXPORT deflateSetHeader (strm, head) return Z_OK; } +/* ========================================================================= */ +int ZEXPORT deflatePending (strm, pending, bits) + unsigned *pending; + int *bits; + z_streamp strm; +{ + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + if (pending != Z_NULL) + *pending = strm->state->pending; + if (bits != Z_NULL) + *bits = strm->state->bi_valid; + return Z_OK; +} + /* ========================================================================= */ int ZEXPORT deflatePrime (strm, bits, value) z_streamp strm; int bits; int value; { + deflate_state *s; + int put; + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; - strm->state->bi_valid = bits; - strm->state->bi_buf = (ush)(value & ((1 << bits) - 1)); + s = strm->state; + if ((Bytef *)(s->d_buf) < s->pending_out + ((Buf_size + 7) >> 3)) + return Z_BUF_ERROR; + do { + put = Buf_size - s->bi_valid; + if (put > bits) + put = bits; + s->bi_buf |= (ush)((value & ((1 << put) - 1)) << s->bi_valid); + s->bi_valid += put; + _tr_flush_bits(s); + value >>= put; + bits -= put; + } while (bits); return Z_OK; } @@ -562,19 +640,22 @@ local void putShortMSB (s, b) local void flush_pending(strm) z_streamp strm; { - unsigned len = strm->state->pending; + unsigned len; + deflate_state *s = strm->state; + _tr_flush_bits(s); + len = s->pending; if (len > strm->avail_out) len = strm->avail_out; if (len == 0) return; - zmemcpy(strm->next_out, strm->state->pending_out, len); + zmemcpy(strm->next_out, s->pending_out, len); strm->next_out += len; - strm->state->pending_out += len; + s->pending_out += len; strm->total_out += len; strm->avail_out -= len; - strm->state->pending -= len; - if (strm->state->pending == 0) { - strm->state->pending_out = strm->state->pending_buf; + s->pending -= len; + if (s->pending == 0) { + s->pending_out = s->pending_buf; } } @@ -801,7 +882,7 @@ int ZEXPORT deflate (strm, flush) * flushes. For repeated and useless calls with Z_FINISH, we keep * returning Z_STREAM_END instead of Z_BUF_ERROR. */ - } else if (strm->avail_in == 0 && flush <= old_flush && + } else if (strm->avail_in == 0 && RANK(flush) <= RANK(old_flush) && flush != Z_FINISH) { ERR_RETURN(strm, Z_BUF_ERROR); } @@ -850,6 +931,7 @@ int ZEXPORT deflate (strm, flush) if (s->lookahead == 0) { s->strstart = 0; s->block_start = 0L; + s->insert = 0; } } } @@ -945,12 +1027,12 @@ int ZEXPORT deflateCopy (dest, source) ss = source->state; - zmemcpy(dest, source, sizeof(z_stream)); + zmemcpy((voidpf)dest, (voidpf)source, sizeof(z_stream)); ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state)); if (ds == Z_NULL) return Z_MEM_ERROR; dest->state = (struct internal_state FAR *) ds; - zmemcpy(ds, ss, sizeof(deflate_state)); + zmemcpy((voidpf)ds, (voidpf)ss, sizeof(deflate_state)); ds->strm = dest; ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte)); @@ -966,8 +1048,8 @@ int ZEXPORT deflateCopy (dest, source) } /* following zmemcpy do not work for 16-bit MSDOS */ zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte)); - zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos)); - zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos)); + zmemcpy((voidpf)ds->prev, (voidpf)ss->prev, ds->w_size * sizeof(Pos)); + zmemcpy((voidpf)ds->head, (voidpf)ss->head, ds->hash_size * sizeof(Pos)); zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size); ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf); @@ -1001,15 +1083,15 @@ local int read_buf(strm, buf, size) strm->avail_in -= len; + zmemcpy(buf, strm->next_in, len); if (strm->state->wrap == 1) { - strm->adler = adler32(strm->adler, strm->next_in, len); + strm->adler = adler32(strm->adler, buf, len); } #ifdef GZIP else if (strm->state->wrap == 2) { - strm->adler = crc32(strm->adler, strm->next_in, len); + strm->adler = crc32(strm->adler, buf, len); } #endif - zmemcpy(buf, strm->next_in, len); strm->next_in += len; strm->total_in += len; @@ -1036,6 +1118,7 @@ local void lm_init (s) s->strstart = 0; s->block_start = 0L; s->lookahead = 0; + s->insert = 0; s->match_length = s->prev_length = MIN_MATCH-1; s->match_available = 0; s->ins_h = 0; @@ -1310,6 +1393,8 @@ local void fill_window(s) unsigned more; /* Amount of free space at the end of the window. */ uInt wsize = s->w_size; + Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); + do { more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart); @@ -1362,7 +1447,7 @@ local void fill_window(s) #endif more += wsize; } - if (s->strm->avail_in == 0) return; + if (s->strm->avail_in == 0) break; /* If there was no sliding: * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && @@ -1381,12 +1466,24 @@ local void fill_window(s) s->lookahead += n; /* Initialize the hash value now that we have some input: */ - if (s->lookahead >= MIN_MATCH) { - s->ins_h = s->window[s->strstart]; - UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]); + if (s->lookahead + s->insert >= MIN_MATCH) { + uInt str = s->strstart - s->insert; + s->ins_h = s->window[str]; + UPDATE_HASH(s, s->ins_h, s->window[str + 1]); #if MIN_MATCH != 3 Call UPDATE_HASH() MIN_MATCH-3 more times #endif + while (s->insert) { + UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); +#ifndef FASTEST + s->prev[str & s->w_mask] = s->head[s->ins_h]; +#endif + s->head[s->ins_h] = (Pos)str; + str++; + s->insert--; + if (s->lookahead + s->insert < MIN_MATCH) + break; + } } /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, * but this is not important since only literal bytes will be emitted. @@ -1427,6 +1524,9 @@ local void fill_window(s) s->high_water += init; } } + + Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, + "not enough room for search"); } /* =========================================================================== @@ -1506,8 +1606,14 @@ local block_state deflate_stored(s, flush) FLUSH_BLOCK(s, 0); } } - FLUSH_BLOCK(s, flush == Z_FINISH); - return flush == Z_FINISH ? finish_done : block_done; + s->insert = 0; + if (flush == Z_FINISH) { + FLUSH_BLOCK(s, 1); + return finish_done; + } + if ((long)s->strstart > s->block_start) + FLUSH_BLOCK(s, 0); + return block_done; } /* =========================================================================== @@ -1603,8 +1709,14 @@ local block_state deflate_fast(s, flush) } if (bflush) FLUSH_BLOCK(s, 0); } - FLUSH_BLOCK(s, flush == Z_FINISH); - return flush == Z_FINISH ? finish_done : block_done; + s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1; + if (flush == Z_FINISH) { + FLUSH_BLOCK(s, 1); + return finish_done; + } + if (s->last_lit) + FLUSH_BLOCK(s, 0); + return block_done; } #ifndef FASTEST @@ -1728,8 +1840,14 @@ local block_state deflate_slow(s, flush) _tr_tally_lit(s, s->window[s->strstart-1], bflush); s->match_available = 0; } - FLUSH_BLOCK(s, flush == Z_FINISH); - return flush == Z_FINISH ? finish_done : block_done; + s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1; + if (flush == Z_FINISH) { + FLUSH_BLOCK(s, 1); + return finish_done; + } + if (s->last_lit) + FLUSH_BLOCK(s, 0); + return block_done; } #endif /* FASTEST */ @@ -1749,11 +1867,11 @@ local block_state deflate_rle(s, flush) for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes - * for the longest encodable run. + * for the longest run, plus one for the unrolled loop. */ - if (s->lookahead < MAX_MATCH) { + if (s->lookahead <= MAX_MATCH) { fill_window(s); - if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) { + if (s->lookahead <= MAX_MATCH && flush == Z_NO_FLUSH) { return need_more; } if (s->lookahead == 0) break; /* flush the current block */ @@ -1776,6 +1894,7 @@ local block_state deflate_rle(s, flush) if (s->match_length > s->lookahead) s->match_length = s->lookahead; } + Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); } /* Emit match if have run of MIN_MATCH or longer, else emit literal */ @@ -1796,8 +1915,14 @@ local block_state deflate_rle(s, flush) } if (bflush) FLUSH_BLOCK(s, 0); } - FLUSH_BLOCK(s, flush == Z_FINISH); - return flush == Z_FINISH ? finish_done : block_done; + s->insert = 0; + if (flush == Z_FINISH) { + FLUSH_BLOCK(s, 1); + return finish_done; + } + if (s->last_lit) + FLUSH_BLOCK(s, 0); + return block_done; } /* =========================================================================== @@ -1829,6 +1954,12 @@ local block_state deflate_huff(s, flush) s->strstart++; if (bflush) FLUSH_BLOCK(s, 0); } - FLUSH_BLOCK(s, flush == Z_FINISH); - return flush == Z_FINISH ? finish_done : block_done; + s->insert = 0; + if (flush == Z_FINISH) { + FLUSH_BLOCK(s, 1); + return finish_done; + } + if (s->last_lit) + FLUSH_BLOCK(s, 0); + return block_done; } diff --git a/3rdparty/zlib/deflate.h b/3rdparty/zlib/deflate.h index f53deba852..fbac44d908 100644 --- a/3rdparty/zlib/deflate.h +++ b/3rdparty/zlib/deflate.h @@ -1,5 +1,5 @@ /* deflate.h -- internal compression state - * Copyright (C) 1995-2009 Jean-loup Gailly + * Copyright (C) 1995-2012 Jean-loup Gailly * For conditions of distribution and use, see copyright notice in zlib.h */ @@ -48,6 +48,9 @@ #define MAX_BITS 15 /* All codes must not exceed MAX_BITS bits */ +#define Buf_size 16 +/* size of bit buffer in bi_buf */ + #define INIT_STATE 42 #define EXTRA_STATE 69 #define NAME_STATE 73 @@ -188,7 +191,7 @@ typedef struct internal_state { int nice_match; /* Stop searching when current match exceeds this */ /* used by trees.c: */ - /* Didn't use ct_data typedef below to supress compiler warning */ + /* Didn't use ct_data typedef below to suppress compiler warning */ struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ @@ -244,7 +247,7 @@ typedef struct internal_state { ulg opt_len; /* bit length of current block with optimal trees */ ulg static_len; /* bit length of current block with static trees */ uInt matches; /* number of string matches in current block */ - int last_eob_len; /* bit length of EOB code for last block */ + uInt insert; /* bytes at end of window left to insert */ #ifdef DEBUG ulg compressed_len; /* total bit length of compressed file mod 2^32 */ @@ -290,13 +293,14 @@ typedef struct internal_state { memory checker errors from longest match routines */ /* in trees.c */ -void _tr_init OF((deflate_state *s)); -int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc)); -void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len, - int last)); -void _tr_align OF((deflate_state *s)); -void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len, - int last)); +void ZLIB_INTERNAL _tr_init OF((deflate_state *s)); +int ZLIB_INTERNAL _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc)); +void ZLIB_INTERNAL _tr_flush_block OF((deflate_state *s, charf *buf, + ulg stored_len, int last)); +void ZLIB_INTERNAL _tr_flush_bits OF((deflate_state *s)); +void ZLIB_INTERNAL _tr_align OF((deflate_state *s)); +void ZLIB_INTERNAL _tr_stored_block OF((deflate_state *s, charf *buf, + ulg stored_len, int last)); #define d_code(dist) \ ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)]) @@ -309,11 +313,11 @@ void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len, /* Inline versions of _tr_tally for speed: */ #if defined(GEN_TREES_H) || !defined(STDC) - extern uch _length_code[]; - extern uch _dist_code[]; + extern uch ZLIB_INTERNAL _length_code[]; + extern uch ZLIB_INTERNAL _dist_code[]; #else - extern const uch _length_code[]; - extern const uch _dist_code[]; + extern const uch ZLIB_INTERNAL _length_code[]; + extern const uch ZLIB_INTERNAL _dist_code[]; #endif # define _tr_tally_lit(s, c, flush) \ diff --git a/3rdparty/zlib/gzguts.h b/3rdparty/zlib/gzguts.h index 0e7ed4330a..ee3f281aa5 100644 --- a/3rdparty/zlib/gzguts.h +++ b/3rdparty/zlib/gzguts.h @@ -1,18 +1,22 @@ /* gzguts.h -- zlib internal header definitions for gz* operations - * Copyright (C) 2004, 2005, 2010 Mark Adler + * Copyright (C) 2004, 2005, 2010, 2011, 2012 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ #ifdef _LARGEFILE64_SOURCE # ifndef _LARGEFILE_SOURCE -# define _LARGEFILE_SOURCE +# define _LARGEFILE_SOURCE 1 # endif # ifdef _FILE_OFFSET_BITS # undef _FILE_OFFSET_BITS # endif #endif -#define ZLIB_INTERNAL +#ifdef HAVE_HIDDEN +# define ZLIB_INTERNAL __attribute__((visibility ("hidden"))) +#else +# define ZLIB_INTERNAL +#endif #include #include "zlib.h" @@ -23,13 +27,65 @@ #endif #include +#ifdef _WIN32 +# include +#endif + +#if defined(__TURBOC__) || defined(_MSC_VER) || defined(_WIN32) +# include +#endif + #ifdef NO_DEFLATE /* for compatibility with old definition */ # define NO_GZCOMPRESS #endif -#ifdef _MSC_VER -# include -# define vsnprintf _vsnprintf +#if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550) +# ifndef HAVE_VSNPRINTF +# define HAVE_VSNPRINTF +# endif +#endif + +#if defined(__CYGWIN__) +# ifndef HAVE_VSNPRINTF +# define HAVE_VSNPRINTF +# endif +#endif + +#if defined(MSDOS) && defined(__BORLANDC__) && (BORLANDC > 0x410) +# ifndef HAVE_VSNPRINTF +# define HAVE_VSNPRINTF +# endif +#endif + +#ifndef HAVE_VSNPRINTF +# ifdef MSDOS +/* vsnprintf may exist on some MS-DOS compilers (DJGPP?), + but for now we just assume it doesn't. */ +# define NO_vsnprintf +# endif +# ifdef __TURBOC__ +# define NO_vsnprintf +# endif +# ifdef WIN32 +/* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */ +# if !defined(vsnprintf) && !defined(NO_vsnprintf) +# if !defined(_MSC_VER) || ( defined(_MSC_VER) && _MSC_VER < 1500 ) +# define vsnprintf _vsnprintf +# endif +# endif +# endif +# ifdef __SASC +# define NO_vsnprintf +# endif +# ifdef VMS +# define NO_vsnprintf +# endif +# ifdef __OS400__ +# define NO_vsnprintf +# endif +# ifdef __MVS__ +# define NO_vsnprintf +# endif #endif #ifndef local @@ -44,11 +100,11 @@ #endif /* get errno and strerror definition */ -#if defined UNDER_CE && defined NO_ERRNO_H +#if defined UNDER_CE # include # define zstrerror() gz_strwinerror((DWORD)GetLastError()) #else -# ifdef STDC +# ifndef NO_STRERROR # include # define zstrerror() strerror(errno) # else @@ -56,16 +112,19 @@ # endif #endif -/* MVS fdopen() */ -#ifdef __MVS__ - #pragma map (fdopen , "\174\174FDOPEN") - FILE *fdopen(int, const char *); +/* provide prototypes for these when building zlib without LFS */ +#if !defined(_LARGEFILE64_SOURCE) || _LFS64_LARGEFILE-0 == 0 + ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); + ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int)); + ZEXTERN z_off64_t ZEXPORT gztell64 OF((gzFile)); + ZEXTERN z_off64_t ZEXPORT gzoffset64 OF((gzFile)); #endif -#ifdef _LARGEFILE64_SOURCE -# define z_off64_t off64_t +/* default memLevel */ +#if MAX_MEM_LEVEL >= 8 +# define DEF_MEM_LEVEL 8 #else -# define z_off64_t z_off_t +# define DEF_MEM_LEVEL MAX_MEM_LEVEL #endif /* default i/o buffer size -- double this for output when reading */ @@ -84,23 +143,25 @@ /* internal gzip file state data structure */ typedef struct { + /* exposed contents for gzgetc() macro */ + struct gzFile_s x; /* "x" for exposed */ + /* x.have: number of bytes available at x.next */ + /* x.next: next output data to deliver or write */ + /* x.pos: current position in uncompressed data */ /* used for both reading and writing */ int mode; /* see gzip modes above */ int fd; /* file descriptor */ char *path; /* path or fd for error messages */ - z_off64_t pos; /* current position in uncompressed data */ unsigned size; /* buffer size, zero if not allocated yet */ unsigned want; /* requested buffer size, default is GZBUFSIZE */ unsigned char *in; /* input buffer */ unsigned char *out; /* output buffer (double-sized when reading) */ - unsigned char *next; /* next output data to deliver or write */ + int direct; /* 0 if processing gzip, 1 if transparent */ /* just for reading */ - unsigned have; /* amount of output data unused at next */ - int eof; /* true if end of input file reached */ - z_off64_t start; /* where the gzip data started, for rewinding */ - z_off64_t raw; /* where the raw data started, for seeking */ int how; /* 0: get header, 1: copy, 2: decompress */ - int direct; /* true if last read direct, false if gzip */ + z_off64_t start; /* where the gzip data started, for rewinding */ + int eof; /* true if end of input file reached */ + int past; /* true if read requested past end */ /* just for writing */ int level; /* compression level */ int strategy; /* compression strategy */ @@ -116,9 +177,9 @@ typedef struct { typedef gz_state FAR *gz_statep; /* shared functions */ -ZEXTERN void ZEXPORT gz_error OF((gz_statep, int, const char *)); -#if defined UNDER_CE && defined NO_ERRNO_H -ZEXTERN char ZEXPORT *gz_strwinerror OF((DWORD error)); +void ZLIB_INTERNAL gz_error OF((gz_statep, int, const char *)); +#if defined UNDER_CE +char ZLIB_INTERNAL *gz_strwinerror OF((DWORD error)); #endif /* GT_OFF(x), where x is an unsigned value, is true if x > maximum z_off64_t @@ -127,6 +188,6 @@ ZEXTERN char ZEXPORT *gz_strwinerror OF((DWORD error)); #ifdef INT_MAX # define GT_OFF(x) (sizeof(int) == sizeof(z_off64_t) && (x) > INT_MAX) #else -ZEXTERN unsigned ZEXPORT gz_intmax OF((void)); +unsigned ZLIB_INTERNAL gz_intmax OF((void)); # define GT_OFF(x) (sizeof(int) == sizeof(z_off64_t) && (x) > gz_intmax()) #endif diff --git a/3rdparty/zlib/gzlib.c b/3rdparty/zlib/gzlib.c index 6fdb08a814..ca55c6ea92 100644 --- a/3rdparty/zlib/gzlib.c +++ b/3rdparty/zlib/gzlib.c @@ -1,21 +1,25 @@ /* gzlib.c -- zlib functions common to reading and writing gzip files - * Copyright (C) 2004, 2010 Mark Adler + * Copyright (C) 2004, 2010, 2011, 2012 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ #include "gzguts.h" -#ifdef _LARGEFILE64_SOURCE +#if defined(_WIN32) && !defined(__BORLANDC__) +# define LSEEK _lseeki64 +#else +#if defined(_LARGEFILE64_SOURCE) && _LFS64_LARGEFILE-0 # define LSEEK lseek64 #else # define LSEEK lseek #endif +#endif /* Local functions */ local void gz_reset OF((gz_statep)); -local gzFile gz_open OF((const char *, int, const char *)); +local gzFile gz_open OF((const void *, int, const char *)); -#if defined UNDER_CE && defined NO_ERRNO_H +#if defined UNDER_CE /* Map the Windows error number in ERROR to a locale-dependent error message string and return a pointer to it. Typically, the values for ERROR come @@ -26,7 +30,7 @@ local gzFile gz_open OF((const char *, int, const char *)); The gz_strwinerror function does not change the current setting of GetLastError. */ -char ZEXPORT *gz_strwinerror (error) +char ZLIB_INTERNAL *gz_strwinerror (error) DWORD error; { static char buf[1024]; @@ -65,31 +69,43 @@ char ZEXPORT *gz_strwinerror (error) return buf; } -#endif /* UNDER_CE && NO_ERRNO_H */ +#endif /* UNDER_CE */ /* Reset gzip file state */ local void gz_reset(state) gz_statep state; { + state->x.have = 0; /* no output data available */ if (state->mode == GZ_READ) { /* for reading ... */ - state->have = 0; /* no output data available */ state->eof = 0; /* not at end of file */ + state->past = 0; /* have not read past end yet */ state->how = LOOK; /* look for gzip header */ - state->direct = 1; /* default for empty file */ } state->seek = 0; /* no seek request pending */ gz_error(state, Z_OK, NULL); /* clear error */ - state->pos = 0; /* no uncompressed data yet */ + state->x.pos = 0; /* no uncompressed data yet */ state->strm.avail_in = 0; /* no input data yet */ } /* Open a gzip file either by name or file descriptor. */ local gzFile gz_open(path, fd, mode) - const char *path; + const void *path; int fd; const char *mode; { gz_statep state; + size_t len; + int oflag; +#ifdef O_CLOEXEC + int cloexec = 0; +#endif +#ifdef O_EXCL + int exclusive = 0; +#endif + + /* check input */ + if (path == NULL) + return NULL; /* allocate gzFile structure to return */ state = malloc(sizeof(gz_state)); @@ -103,6 +119,7 @@ local gzFile gz_open(path, fd, mode) state->mode = GZ_NONE; state->level = Z_DEFAULT_COMPRESSION; state->strategy = Z_DEFAULT_STRATEGY; + state->direct = 0; while (*mode) { if (*mode >= '0' && *mode <= '9') state->level = *mode - '0'; @@ -124,6 +141,16 @@ local gzFile gz_open(path, fd, mode) return NULL; case 'b': /* ignore -- will request binary anyway */ break; +#ifdef O_CLOEXEC + case 'e': + cloexec = 1; + break; +#endif +#ifdef O_EXCL + case 'x': + exclusive = 1; + break; +#endif case 'f': state->strategy = Z_FILTERED; break; @@ -135,6 +162,8 @@ local gzFile gz_open(path, fd, mode) break; case 'F': state->strategy = Z_FIXED; + case 'T': + state->direct = 1; default: /* could consider as an error, but just ignore */ ; } @@ -147,31 +176,69 @@ local gzFile gz_open(path, fd, mode) return NULL; } + /* can't force transparent read */ + if (state->mode == GZ_READ) { + if (state->direct) { + free(state); + return NULL; + } + state->direct = 1; /* for empty file */ + } + /* save the path name for error messages */ - state->path = malloc(strlen(path) + 1); +#ifdef _WIN32 + if (fd == -2) { + len = wcstombs(NULL, path, 0); + if (len == (size_t)-1) + len = 0; + } + else +#endif + len = strlen(path); + state->path = malloc(len + 1); if (state->path == NULL) { free(state); return NULL; } - strcpy(state->path, path); +#ifdef _WIN32 + if (fd == -2) + if (len) + wcstombs(state->path, path, len + 1); + else + *(state->path) = 0; + else +#endif + strcpy(state->path, path); - /* open the file with the appropriate mode (or just use fd) */ - state->fd = fd != -1 ? fd : - open(path, + /* compute the flags for open() */ + oflag = #ifdef O_LARGEFILE - O_LARGEFILE | + O_LARGEFILE | #endif #ifdef O_BINARY - O_BINARY | + O_BINARY | #endif - (state->mode == GZ_READ ? - O_RDONLY : - (O_WRONLY | O_CREAT | ( - state->mode == GZ_WRITE ? - O_TRUNC : - O_APPEND))), - 0666); +#ifdef O_CLOEXEC + (cloexec ? O_CLOEXEC : 0) | +#endif + (state->mode == GZ_READ ? + O_RDONLY : + (O_WRONLY | O_CREAT | +#ifdef O_EXCL + (exclusive ? O_EXCL : 0) | +#endif + (state->mode == GZ_WRITE ? + O_TRUNC : + O_APPEND))); + + /* open the file with the appropriate flags (or just use fd) */ + state->fd = fd > -1 ? fd : ( +#ifdef _WIN32 + fd == -2 ? _wopen(path, oflag, 0666) : +#endif + open(path, oflag, 0666)); if (state->fd == -1) { + free(state->path); free(state); return NULL; } @@ -217,12 +284,22 @@ gzFile ZEXPORT gzdopen(fd, mode) if (fd == -1 || (path = malloc(7 + 3 * sizeof(int))) == NULL) return NULL; - sprintf(path, "", fd); + sprintf(path, "", fd); /* for debugging */ gz = gz_open(path, fd, mode); free(path); return gz; } +/* -- see zlib.h -- */ +#ifdef _WIN32 +gzFile ZEXPORT gzopen_w(path, mode) + const wchar_t *path; + const char *mode; +{ + return gz_open(path, -2, mode); +} +#endif + /* -- see zlib.h -- */ int ZEXPORT gzbuffer(file, size) gzFile file; @@ -242,8 +319,8 @@ int ZEXPORT gzbuffer(file, size) return -1; /* check and set requested size */ - if (size == 0) - return -1; + if (size < 2) + size = 2; /* need two bytes to check magic header */ state->want = size; return 0; } @@ -260,7 +337,8 @@ int ZEXPORT gzrewind(file) state = (gz_statep)file; /* check that we're reading and that there's no error */ - if (state->mode != GZ_READ || state->err != Z_OK) + if (state->mode != GZ_READ || + (state->err != Z_OK && state->err != Z_BUF_ERROR)) return -1; /* back up and start over */ @@ -288,7 +366,7 @@ z_off64_t ZEXPORT gzseek64(file, offset, whence) return -1; /* check that there's no error */ - if (state->err != Z_OK) + if (state->err != Z_OK && state->err != Z_BUF_ERROR) return -1; /* can only seek from start or relative to current position */ @@ -297,31 +375,32 @@ z_off64_t ZEXPORT gzseek64(file, offset, whence) /* normalize offset to a SEEK_CUR specification */ if (whence == SEEK_SET) - offset -= state->pos; + offset -= state->x.pos; else if (state->seek) offset += state->skip; state->seek = 0; /* if within raw area while reading, just go there */ if (state->mode == GZ_READ && state->how == COPY && - state->pos + offset >= state->raw) { - ret = LSEEK(state->fd, offset, SEEK_CUR); + state->x.pos + offset >= 0) { + ret = LSEEK(state->fd, offset - state->x.have, SEEK_CUR); if (ret == -1) return -1; - state->have = 0; + state->x.have = 0; state->eof = 0; + state->past = 0; state->seek = 0; gz_error(state, Z_OK, NULL); state->strm.avail_in = 0; - state->pos += offset; - return state->pos; + state->x.pos += offset; + return state->x.pos; } /* calculate skip amount, rewinding if needed for back seek when reading */ if (offset < 0) { if (state->mode != GZ_READ) /* writing -- can't go backwards */ return -1; - offset += state->pos; + offset += state->x.pos; if (offset < 0) /* before start of file! */ return -1; if (gzrewind(file) == -1) /* rewind, then skip to offset */ @@ -330,11 +409,11 @@ z_off64_t ZEXPORT gzseek64(file, offset, whence) /* if reading, skip what's in output buffer (one less gzgetc() check) */ if (state->mode == GZ_READ) { - n = GT_OFF(state->have) || (z_off64_t)state->have > offset ? - (unsigned)offset : state->have; - state->have -= n; - state->next += n; - state->pos += n; + n = GT_OFF(state->x.have) || (z_off64_t)state->x.have > offset ? + (unsigned)offset : state->x.have; + state->x.have -= n; + state->x.next += n; + state->x.pos += n; offset -= n; } @@ -343,7 +422,7 @@ z_off64_t ZEXPORT gzseek64(file, offset, whence) state->seek = 1; state->skip = offset; } - return state->pos + offset; + return state->x.pos + offset; } /* -- see zlib.h -- */ @@ -372,7 +451,7 @@ z_off64_t ZEXPORT gztell64(file) return -1; /* return position */ - return state->pos + (state->seek ? state->skip : 0); + return state->x.pos + (state->seek ? state->skip : 0); } /* -- see zlib.h -- */ @@ -432,7 +511,7 @@ int ZEXPORT gzeof(file) return 0; /* return end-of-file state */ - return state->mode == GZ_READ ? (state->eof && state->have == 0) : 0; + return state->mode == GZ_READ ? state->past : 0; } /* -- see zlib.h -- */ @@ -469,8 +548,10 @@ void ZEXPORT gzclearerr(file) return; /* clear error and end-of-file */ - if (state->mode == GZ_READ) + if (state->mode == GZ_READ) { state->eof = 0; + state->past = 0; + } gz_error(state, Z_OK, NULL); } @@ -480,7 +561,7 @@ void ZEXPORT gzclearerr(file) memory). Simply save the error message as a static string. If there is an allocation failure constructing the error message, then convert the error to out of memory. */ -void ZEXPORT gz_error(state, err, msg) +void ZLIB_INTERNAL gz_error(state, err, msg) gz_statep state; int err; const char *msg; @@ -492,6 +573,10 @@ void ZEXPORT gz_error(state, err, msg) state->msg = NULL; } + /* if fatal, set state->x.have to 0 so that the gzgetc() macro fails */ + if (err != Z_OK && err != Z_BUF_ERROR) + state->x.have = 0; + /* set error code, and if no message, then done */ state->err = err; if (msg == NULL) @@ -520,7 +605,7 @@ void ZEXPORT gz_error(state, err, msg) available) -- we need to do this to cover cases where 2's complement not used, since C standard permits 1's complement and sign-bit representations, otherwise we could just use ((unsigned)-1) >> 1 */ -unsigned ZEXPORT gz_intmax() +unsigned ZLIB_INTERNAL gz_intmax() { unsigned p, q; diff --git a/3rdparty/zlib/gzread.c b/3rdparty/zlib/gzread.c index 434ef023e0..3493d34d4e 100644 --- a/3rdparty/zlib/gzread.c +++ b/3rdparty/zlib/gzread.c @@ -1,5 +1,5 @@ /* gzread.c -- zlib functions for reading gzip files - * Copyright (C) 2004, 2005, 2010 Mark Adler + * Copyright (C) 2004, 2005, 2010, 2011, 2012 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ @@ -8,10 +8,9 @@ /* Local functions */ local int gz_load OF((gz_statep, unsigned char *, unsigned, unsigned *)); local int gz_avail OF((gz_statep)); -local int gz_next4 OF((gz_statep, unsigned long *)); -local int gz_head OF((gz_statep)); +local int gz_look OF((gz_statep)); local int gz_decomp OF((gz_statep)); -local int gz_make OF((gz_statep)); +local int gz_fetch OF((gz_statep)); local int gz_skip OF((gz_statep, z_off64_t)); /* Use read() to load a buffer -- return -1 on error, otherwise 0. Read from @@ -46,66 +45,47 @@ local int gz_load(state, buf, len, have) error, 0 otherwise. Note that the eof flag is set when the end of the input file is reached, even though there may be unused data in the buffer. Once that data has been used, no more attempts will be made to read the file. - gz_avail() assumes that strm->avail_in == 0. */ + If strm->avail_in != 0, then the current data is moved to the beginning of + the input buffer, and then the remainder of the buffer is loaded with the + available data from the input file. */ local int gz_avail(state) gz_statep state; { + unsigned got; z_streamp strm = &(state->strm); - if (state->err != Z_OK) + if (state->err != Z_OK && state->err != Z_BUF_ERROR) return -1; if (state->eof == 0) { - if (gz_load(state, state->in, state->size, &(strm->avail_in)) == -1) + if (strm->avail_in) { /* copy what's there to the start */ + unsigned char *p = state->in, *q = strm->next_in; + unsigned n = strm->avail_in; + do { + *p++ = *q++; + } while (--n); + } + if (gz_load(state, state->in + strm->avail_in, + state->size - strm->avail_in, &got) == -1) return -1; + strm->avail_in += got; strm->next_in = state->in; } return 0; } -/* Get next byte from input, or -1 if end or error. */ -#define NEXT() ((strm->avail_in == 0 && gz_avail(state) == -1) ? -1 : \ - (strm->avail_in == 0 ? -1 : \ - (strm->avail_in--, *(strm->next_in)++))) - -/* Get a four-byte little-endian integer and return 0 on success and the value - in *ret. Otherwise -1 is returned and *ret is not modified. */ -local int gz_next4(state, ret) - gz_statep state; - unsigned long *ret; -{ - int ch; - unsigned long val; - z_streamp strm = &(state->strm); - - val = NEXT(); - val += (unsigned)NEXT() << 8; - val += (unsigned long)NEXT() << 16; - ch = NEXT(); - if (ch == -1) - return -1; - val += (unsigned long)ch << 24; - *ret = val; - return 0; -} - -/* Look for gzip header, set up for inflate or copy. state->have must be zero. +/* Look for gzip header, set up for inflate or copy. state->x.have must be 0. If this is the first time in, allocate required memory. state->how will be left unchanged if there is no more input data available, will be set to COPY if there is no gzip header and direct copying will be performed, or it will - be set to GZIP for decompression, and the gzip header will be skipped so - that the next available input data is the raw deflate stream. If direct - copying, then leftover input data from the input buffer will be copied to - the output buffer. In that case, all further file reads will be directly to - either the output buffer or a user buffer. If decompressing, the inflate - state and the check value will be initialized. gz_head() will return 0 on - success or -1 on failure. Failures may include read errors or gzip header - errors. */ -local int gz_head(state) + be set to GZIP for decompression. If direct copying, then leftover input + data from the input buffer will be copied to the output buffer. In that + case, all further file reads will be directly to either the output buffer or + a user buffer. If decompressing, the inflate state will be initialized. + gz_look() will return 0 on success or -1 on failure. */ +local int gz_look(state) gz_statep state; { z_streamp strm = &(state->strm); - int flags; - unsigned len; /* allocate read buffers and inflate memory */ if (state->size == 0) { @@ -128,7 +108,7 @@ local int gz_head(state) state->strm.opaque = Z_NULL; state->strm.avail_in = 0; state->strm.next_in = Z_NULL; - if (inflateInit2(&(state->strm), -15) != Z_OK) { /* raw inflate */ + if (inflateInit2(&(state->strm), 15 + 16) != Z_OK) { /* gunzip */ free(state->out); free(state->in); state->size = 0; @@ -137,83 +117,45 @@ local int gz_head(state) } } - /* get some data in the input buffer */ - if (strm->avail_in == 0) { + /* get at least the magic bytes in the input buffer */ + if (strm->avail_in < 2) { if (gz_avail(state) == -1) return -1; if (strm->avail_in == 0) return 0; } - /* look for the gzip magic header bytes 31 and 139 */ - if (strm->next_in[0] == 31) { - strm->avail_in--; - strm->next_in++; - if (strm->avail_in == 0 && gz_avail(state) == -1) - return -1; - if (strm->avail_in && strm->next_in[0] == 139) { - /* we have a gzip header, woo hoo! */ - strm->avail_in--; - strm->next_in++; - - /* skip rest of header */ - if (NEXT() != 8) { /* compression method */ - gz_error(state, Z_DATA_ERROR, "unknown compression method"); - return -1; - } - flags = NEXT(); - if (flags & 0xe0) { /* reserved flag bits */ - gz_error(state, Z_DATA_ERROR, "unknown header flags set"); - return -1; - } - NEXT(); /* modification time */ - NEXT(); - NEXT(); - NEXT(); - NEXT(); /* extra flags */ - NEXT(); /* operating system */ - if (flags & 4) { /* extra field */ - len = (unsigned)NEXT(); - len += (unsigned)NEXT() << 8; - while (len--) - if (NEXT() < 0) - break; - } - if (flags & 8) /* file name */ - while (NEXT() > 0) - ; - if (flags & 16) /* comment */ - while (NEXT() > 0) - ; - if (flags & 2) { /* header crc */ - NEXT(); - NEXT(); - } - /* an unexpected end of file is not checked for here -- it will be - noticed on the first request for uncompressed data */ - - /* set up for decompression */ - inflateReset(strm); - strm->adler = crc32(0L, Z_NULL, 0); - state->how = GZIP; - state->direct = 0; - return 0; - } - else { - /* not a gzip file -- save first byte (31) and fall to raw i/o */ - state->out[0] = 31; - state->have = 1; - } + /* look for gzip magic bytes -- if there, do gzip decoding (note: there is + a logical dilemma here when considering the case of a partially written + gzip file, to wit, if a single 31 byte is written, then we cannot tell + whether this is a single-byte file, or just a partially written gzip + file -- for here we assume that if a gzip file is being written, then + the header will be written in a single operation, so that reading a + single byte is sufficient indication that it is not a gzip file) */ + if (strm->avail_in > 1 && + strm->next_in[0] == 31 && strm->next_in[1] == 139) { + inflateReset(strm); + state->how = GZIP; + state->direct = 0; + return 0; } - /* doing raw i/o, save start of raw data for seeking, copy any leftover - input to output -- this assumes that the output buffer is larger than - the input buffer, which also assures space for gzungetc() */ - state->raw = state->pos; - state->next = state->out; + /* no gzip header -- if we were decoding gzip before, then this is trailing + garbage. Ignore the trailing garbage and finish. */ + if (state->direct == 0) { + strm->avail_in = 0; + state->eof = 1; + state->x.have = 0; + return 0; + } + + /* doing raw i/o, copy any leftover input to output -- this assumes that + the output buffer is larger than the input buffer, which also assures + space for gzungetc() */ + state->x.next = state->out; if (strm->avail_in) { - memcpy(state->next + state->have, strm->next_in, strm->avail_in); - state->have += strm->avail_in; + memcpy(state->x.next, strm->next_in, strm->avail_in); + state->x.have = strm->avail_in; strm->avail_in = 0; } state->how = COPY; @@ -222,19 +164,15 @@ local int gz_head(state) } /* Decompress from input to the provided next_out and avail_out in the state. - If the end of the compressed data is reached, then verify the gzip trailer - check value and length (modulo 2^32). state->have and state->next are set - to point to the just decompressed data, and the crc is updated. If the - trailer is verified, state->how is reset to LOOK to look for the next gzip - stream or raw data, once state->have is depleted. Returns 0 on success, -1 - on failure. Failures may include invalid compressed data or a failed gzip - trailer verification. */ + On return, state->x.have and state->x.next point to the just decompressed + data. If the gzip stream completes, state->how is reset to LOOK to look for + the next gzip stream or raw data, once state->x.have is depleted. Returns 0 + on success, -1 on failure. */ local int gz_decomp(state) gz_statep state; { - int ret; + int ret = Z_OK; unsigned had; - unsigned long crc, len; z_streamp strm = &(state->strm); /* fill output buffer up to end of deflate stream */ @@ -244,15 +182,15 @@ local int gz_decomp(state) if (strm->avail_in == 0 && gz_avail(state) == -1) return -1; if (strm->avail_in == 0) { - gz_error(state, Z_DATA_ERROR, "unexpected end of file"); - return -1; + gz_error(state, Z_BUF_ERROR, "unexpected end of file"); + break; } /* decompress and handle errors */ ret = inflate(strm, Z_NO_FLUSH); if (ret == Z_STREAM_ERROR || ret == Z_NEED_DICT) { gz_error(state, Z_STREAM_ERROR, - "internal error: inflate stream corrupt"); + "internal error: inflate stream corrupt"); return -1; } if (ret == Z_MEM_ERROR) { @@ -261,67 +199,55 @@ local int gz_decomp(state) } if (ret == Z_DATA_ERROR) { /* deflate stream invalid */ gz_error(state, Z_DATA_ERROR, - strm->msg == NULL ? "compressed data error" : strm->msg); + strm->msg == NULL ? "compressed data error" : strm->msg); return -1; } } while (strm->avail_out && ret != Z_STREAM_END); - /* update available output and crc check value */ - state->have = had - strm->avail_out; - state->next = strm->next_out - state->have; - strm->adler = crc32(strm->adler, state->next, state->have); + /* update available output */ + state->x.have = had - strm->avail_out; + state->x.next = strm->next_out - state->x.have; - /* check gzip trailer if at end of deflate stream */ - if (ret == Z_STREAM_END) { - if (gz_next4(state, &crc) == -1 || gz_next4(state, &len) == -1) { - gz_error(state, Z_DATA_ERROR, "unexpected end of file"); - return -1; - } - if (crc != strm->adler) { - gz_error(state, Z_DATA_ERROR, "incorrect data check"); - return -1; - } - if (len != (strm->total_out & 0xffffffffL)) { - gz_error(state, Z_DATA_ERROR, "incorrect length check"); - return -1; - } - state->how = LOOK; /* ready for next stream, once have is 0 (leave - state->direct unchanged to remember how) */ - } + /* if the gzip stream completed successfully, look for another */ + if (ret == Z_STREAM_END) + state->how = LOOK; /* good decompression */ return 0; } -/* Make data and put in the output buffer. Assumes that state->have == 0. +/* Fetch data and put it in the output buffer. Assumes state->x.have is 0. Data is either copied from the input file or decompressed from the input file depending on state->how. If state->how is LOOK, then a gzip header is - looked for (and skipped if found) to determine wither to copy or decompress. - Returns -1 on error, otherwise 0. gz_make() will leave state->have as COPY - or GZIP unless the end of the input file has been reached and all data has - been processed. */ -local int gz_make(state) + looked for to determine whether to copy or decompress. Returns -1 on error, + otherwise 0. gz_fetch() will leave state->how as COPY or GZIP unless the + end of the input file has been reached and all data has been processed. */ +local int gz_fetch(state) gz_statep state; { z_streamp strm = &(state->strm); - if (state->how == LOOK) { /* look for gzip header */ - if (gz_head(state) == -1) - return -1; - if (state->have) /* got some data from gz_head() */ + do { + switch(state->how) { + case LOOK: /* -> LOOK, COPY (only if never GZIP), or GZIP */ + if (gz_look(state) == -1) + return -1; + if (state->how == LOOK) + return 0; + break; + case COPY: /* -> COPY */ + if (gz_load(state, state->out, state->size << 1, &(state->x.have)) + == -1) + return -1; + state->x.next = state->out; return 0; - } - if (state->how == COPY) { /* straight copy */ - if (gz_load(state, state->out, state->size << 1, &(state->have)) == -1) - return -1; - state->next = state->out; - } - else if (state->how == GZIP) { /* decompress */ - strm->avail_out = state->size << 1; - strm->next_out = state->out; - if (gz_decomp(state) == -1) - return -1; - } + case GZIP: /* -> GZIP or LOOK (if end of gzip stream) */ + strm->avail_out = state->size << 1; + strm->next_out = state->out; + if (gz_decomp(state) == -1) + return -1; + } + } while (state->x.have == 0 && (!state->eof || strm->avail_in)); return 0; } @@ -335,12 +261,12 @@ local int gz_skip(state, len) /* skip over len bytes or reach end-of-file, whichever comes first */ while (len) /* skip over whatever is in output buffer */ - if (state->have) { - n = GT_OFF(state->have) || (z_off64_t)state->have > len ? - (unsigned)len : state->have; - state->have -= n; - state->next += n; - state->pos += n; + if (state->x.have) { + n = GT_OFF(state->x.have) || (z_off64_t)state->x.have > len ? + (unsigned)len : state->x.have; + state->x.have -= n; + state->x.next += n; + state->x.pos += n; len -= n; } @@ -351,7 +277,7 @@ local int gz_skip(state, len) /* need more data to skip -- load up output buffer */ else { /* get more output, looking for header if required */ - if (gz_make(state) == -1) + if (gz_fetch(state) == -1) return -1; } return 0; @@ -373,14 +299,15 @@ int ZEXPORT gzread(file, buf, len) state = (gz_statep)file; strm = &(state->strm); - /* check that we're reading and that there's no error */ - if (state->mode != GZ_READ || state->err != Z_OK) + /* check that we're reading and that there's no (serious) error */ + if (state->mode != GZ_READ || + (state->err != Z_OK && state->err != Z_BUF_ERROR)) return -1; /* since an int is returned, make sure len fits in one, otherwise return with an error (this avoids the flaw in the interface) */ if ((int)len < 0) { - gz_error(state, Z_BUF_ERROR, "requested length does not fit in int"); + gz_error(state, Z_DATA_ERROR, "requested length does not fit in int"); return -1; } @@ -399,24 +326,26 @@ int ZEXPORT gzread(file, buf, len) got = 0; do { /* first just try copying data from the output buffer */ - if (state->have) { - n = state->have > len ? len : state->have; - memcpy(buf, state->next, n); - state->next += n; - state->have -= n; + if (state->x.have) { + n = state->x.have > len ? len : state->x.have; + memcpy(buf, state->x.next, n); + state->x.next += n; + state->x.have -= n; } /* output buffer empty -- return if we're at the end of the input */ - else if (state->eof && strm->avail_in == 0) + else if (state->eof && strm->avail_in == 0) { + state->past = 1; /* tried to read past end */ break; + } /* need output data -- for small len or new stream load up our output buffer */ else if (state->how == LOOK || len < (state->size << 1)) { /* get more output, looking for header if required */ - if (gz_make(state) == -1) + if (gz_fetch(state) == -1) return -1; - continue; /* no progress yet -- go back to memcpy() above */ + continue; /* no progress yet -- go back to copy above */ /* the copy above assures that we will leave with space in the output buffer, allowing at least one gzungetc() to succeed */ } @@ -433,15 +362,15 @@ int ZEXPORT gzread(file, buf, len) strm->next_out = buf; if (gz_decomp(state) == -1) return -1; - n = state->have; - state->have = 0; + n = state->x.have; + state->x.have = 0; } /* update progress */ len -= n; buf = (char *)buf + n; got += n; - state->pos += n; + state->x.pos += n; } while (len); /* return number of bytes read into user buffer (will fit in int) */ @@ -449,6 +378,7 @@ int ZEXPORT gzread(file, buf, len) } /* -- see zlib.h -- */ +#undef gzgetc int ZEXPORT gzgetc(file) gzFile file; { @@ -461,15 +391,16 @@ int ZEXPORT gzgetc(file) return -1; state = (gz_statep)file; - /* check that we're reading and that there's no error */ - if (state->mode != GZ_READ || state->err != Z_OK) + /* check that we're reading and that there's no (serious) error */ + if (state->mode != GZ_READ || + (state->err != Z_OK && state->err != Z_BUF_ERROR)) return -1; /* try output buffer (no need to check for skip request) */ - if (state->have) { - state->have--; - state->pos++; - return *(state->next)++; + if (state->x.have) { + state->x.have--; + state->x.pos++; + return *(state->x.next)++; } /* nothing there -- try gzread() */ @@ -477,6 +408,12 @@ int ZEXPORT gzgetc(file) return ret < 1 ? -1 : buf[0]; } +int ZEXPORT gzgetc_(file) +gzFile file; +{ + return gzgetc(file); +} + /* -- see zlib.h -- */ int ZEXPORT gzungetc(c, file) int c; @@ -489,8 +426,9 @@ int ZEXPORT gzungetc(c, file) return -1; state = (gz_statep)file; - /* check that we're reading and that there's no error */ - if (state->mode != GZ_READ || state->err != Z_OK) + /* check that we're reading and that there's no (serious) error */ + if (state->mode != GZ_READ || + (state->err != Z_OK && state->err != Z_BUF_ERROR)) return -1; /* process a skip request */ @@ -505,32 +443,34 @@ int ZEXPORT gzungetc(c, file) return -1; /* if output buffer empty, put byte at end (allows more pushing) */ - if (state->have == 0) { - state->have = 1; - state->next = state->out + (state->size << 1) - 1; - state->next[0] = c; - state->pos--; + if (state->x.have == 0) { + state->x.have = 1; + state->x.next = state->out + (state->size << 1) - 1; + state->x.next[0] = c; + state->x.pos--; + state->past = 0; return c; } /* if no room, give up (must have already done a gzungetc()) */ - if (state->have == (state->size << 1)) { - gz_error(state, Z_BUF_ERROR, "out of room to push characters"); + if (state->x.have == (state->size << 1)) { + gz_error(state, Z_DATA_ERROR, "out of room to push characters"); return -1; } /* slide output data if needed and insert byte before existing data */ - if (state->next == state->out) { - unsigned char *src = state->out + state->have; + if (state->x.next == state->out) { + unsigned char *src = state->out + state->x.have; unsigned char *dest = state->out + (state->size << 1); while (src > state->out) *--dest = *--src; - state->next = dest; + state->x.next = dest; } - state->have++; - state->next--; - state->next[0] = c; - state->pos--; + state->x.have++; + state->x.next--; + state->x.next[0] = c; + state->x.pos--; + state->past = 0; return c; } @@ -550,8 +490,9 @@ char * ZEXPORT gzgets(file, buf, len) return NULL; state = (gz_statep)file; - /* check that we're reading and that there's no error */ - if (state->mode != GZ_READ || state->err != Z_OK) + /* check that we're reading and that there's no (serious) error */ + if (state->mode != GZ_READ || + (state->err != Z_OK && state->err != Z_BUF_ERROR)) return NULL; /* process a skip request */ @@ -568,32 +509,31 @@ char * ZEXPORT gzgets(file, buf, len) left = (unsigned)len - 1; if (left) do { /* assure that something is in the output buffer */ - if (state->have == 0) { - if (gz_make(state) == -1) - return NULL; /* error */ - if (state->have == 0) { /* end of file */ - if (buf == str) /* got bupkus */ - return NULL; - break; /* got something -- return it */ - } + if (state->x.have == 0 && gz_fetch(state) == -1) + return NULL; /* error */ + if (state->x.have == 0) { /* end of file */ + state->past = 1; /* read past end */ + break; /* return what we have */ } /* look for end-of-line in current output buffer */ - n = state->have > left ? left : state->have; - eol = memchr(state->next, '\n', n); + n = state->x.have > left ? left : state->x.have; + eol = memchr(state->x.next, '\n', n); if (eol != NULL) - n = (unsigned)(eol - state->next) + 1; + n = (unsigned)(eol - state->x.next) + 1; /* copy through end-of-line, or remainder if not found */ - memcpy(buf, state->next, n); - state->have -= n; - state->next += n; - state->pos += n; + memcpy(buf, state->x.next, n); + state->x.have -= n; + state->x.next += n; + state->x.pos += n; left -= n; buf += n; } while (left && eol == NULL); - /* found end-of-line or out of space -- terminate string and return it */ + /* return terminated string, or if nothing, end of file */ + if (buf == str) + return NULL; buf[0] = 0; return str; } @@ -609,16 +549,12 @@ int ZEXPORT gzdirect(file) return 0; state = (gz_statep)file; - /* check that we're reading */ - if (state->mode != GZ_READ) - return 0; - /* if the state is not known, but we can find out, then do so (this is mainly for right after a gzopen() or gzdopen()) */ - if (state->how == LOOK && state->have == 0) - (void)gz_head(state); + if (state->mode == GZ_READ && state->how == LOOK && state->x.have == 0) + (void)gz_look(state); - /* return 1 if reading direct, 0 if decompressing a gzip stream */ + /* return 1 if transparent, 0 if processing a gzip stream */ return state->direct; } @@ -626,7 +562,7 @@ int ZEXPORT gzdirect(file) int ZEXPORT gzclose_r(file) gzFile file; { - int ret; + int ret, err; gz_statep state; /* get internal structure */ @@ -644,9 +580,10 @@ int ZEXPORT gzclose_r(file) free(state->out); free(state->in); } + err = state->err == Z_BUF_ERROR ? Z_BUF_ERROR : Z_OK; gz_error(state, Z_OK, NULL); free(state->path); ret = close(state->fd); free(state); - return ret ? Z_ERRNO : Z_OK; + return ret ? Z_ERRNO : err; } diff --git a/3rdparty/zlib/gzwrite.c b/3rdparty/zlib/gzwrite.c index e8defc6887..27cb3428e3 100644 --- a/3rdparty/zlib/gzwrite.c +++ b/3rdparty/zlib/gzwrite.c @@ -1,5 +1,5 @@ /* gzwrite.c -- zlib functions for writing gzip files - * Copyright (C) 2004, 2005, 2010 Mark Adler + * Copyright (C) 2004, 2005, 2010, 2011, 2012 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ @@ -18,44 +18,55 @@ local int gz_init(state) int ret; z_streamp strm = &(state->strm); - /* allocate input and output buffers */ + /* allocate input buffer */ state->in = malloc(state->want); - state->out = malloc(state->want); - if (state->in == NULL || state->out == NULL) { - if (state->out != NULL) - free(state->out); - if (state->in != NULL) - free(state->in); + if (state->in == NULL) { gz_error(state, Z_MEM_ERROR, "out of memory"); return -1; } - /* allocate deflate memory, set up for gzip compression */ - strm->zalloc = Z_NULL; - strm->zfree = Z_NULL; - strm->opaque = Z_NULL; - ret = deflateInit2(strm, state->level, Z_DEFLATED, - 15 + 16, 8, state->strategy); - if (ret != Z_OK) { - free(state->in); - gz_error(state, Z_MEM_ERROR, "out of memory"); - return -1; + /* only need output buffer and deflate state if compressing */ + if (!state->direct) { + /* allocate output buffer */ + state->out = malloc(state->want); + if (state->out == NULL) { + free(state->in); + gz_error(state, Z_MEM_ERROR, "out of memory"); + return -1; + } + + /* allocate deflate memory, set up for gzip compression */ + strm->zalloc = Z_NULL; + strm->zfree = Z_NULL; + strm->opaque = Z_NULL; + ret = deflateInit2(strm, state->level, Z_DEFLATED, + MAX_WBITS + 16, DEF_MEM_LEVEL, state->strategy); + if (ret != Z_OK) { + free(state->out); + free(state->in); + gz_error(state, Z_MEM_ERROR, "out of memory"); + return -1; + } } /* mark state as initialized */ state->size = state->want; - /* initialize write buffer */ - strm->avail_out = state->size; - strm->next_out = state->out; - state->next = strm->next_out; + /* initialize write buffer if compressing */ + if (!state->direct) { + strm->avail_out = state->size; + strm->next_out = state->out; + state->x.next = strm->next_out; + } return 0; } /* Compress whatever is at avail_in and next_in and write to the output file. Return -1 if there is an error writing to the output file, otherwise 0. flush is assumed to be a valid deflate() flush value. If flush is Z_FINISH, - then the deflate() state is reset to start a new gzip stream. */ + then the deflate() state is reset to start a new gzip stream. If gz->direct + is true, then simply write to the output file without compressing, and + ignore flush. */ local int gz_comp(state, flush) gz_statep state; int flush; @@ -68,6 +79,17 @@ local int gz_comp(state, flush) if (state->size == 0 && gz_init(state) == -1) return -1; + /* write directly if requested */ + if (state->direct) { + got = write(state->fd, strm->next_in, strm->avail_in); + if (got < 0 || (unsigned)got != strm->avail_in) { + gz_error(state, Z_ERRNO, zstrerror()); + return -1; + } + strm->avail_in = 0; + return 0; + } + /* run deflate() on provided input until it produces no more output */ ret = Z_OK; do { @@ -75,8 +97,8 @@ local int gz_comp(state, flush) doing Z_FINISH then don't write until we get to Z_STREAM_END */ if (strm->avail_out == 0 || (flush != Z_NO_FLUSH && (flush != Z_FINISH || ret == Z_STREAM_END))) { - have = (unsigned)(strm->next_out - state->next); - if (have && ((got = write(state->fd, state->next, have)) < 0 || + have = (unsigned)(strm->next_out - state->x.next); + if (have && ((got = write(state->fd, state->x.next, have)) < 0 || (unsigned)got != have)) { gz_error(state, Z_ERRNO, zstrerror()); return -1; @@ -85,7 +107,7 @@ local int gz_comp(state, flush) strm->avail_out = state->size; strm->next_out = state->out; } - state->next = strm->next_out; + state->x.next = strm->next_out; } /* compress */ @@ -131,7 +153,7 @@ local int gz_zero(state, len) } strm->avail_in = n; strm->next_in = state->in; - state->pos += n; + state->x.pos += n; if (gz_comp(state, Z_NO_FLUSH) == -1) return -1; len -= n; @@ -163,7 +185,7 @@ int ZEXPORT gzwrite(file, buf, len) /* since an int is returned, make sure len fits in one, otherwise return with an error (this avoids the flaw in the interface) */ if ((int)len < 0) { - gz_error(state, Z_BUF_ERROR, "requested length does not fit in int"); + gz_error(state, Z_DATA_ERROR, "requested length does not fit in int"); return 0; } @@ -193,7 +215,7 @@ int ZEXPORT gzwrite(file, buf, len) n = len; memcpy(strm->next_in + strm->avail_in, buf, n); strm->avail_in += n; - state->pos += n; + state->x.pos += n; buf = (char *)buf + n; len -= n; if (len && gz_comp(state, Z_NO_FLUSH) == -1) @@ -208,7 +230,7 @@ int ZEXPORT gzwrite(file, buf, len) /* directly compress user buffer to file */ strm->avail_in = len; strm->next_in = (voidp)buf; - state->pos += len; + state->x.pos += len; if (gz_comp(state, Z_NO_FLUSH) == -1) return 0; } @@ -249,15 +271,15 @@ int ZEXPORT gzputc(file, c) if (strm->avail_in == 0) strm->next_in = state->in; strm->next_in[strm->avail_in++] = c; - state->pos++; - return c; + state->x.pos++; + return c & 0xff; } /* no room in buffer or not initialized, use gz_write() */ buf[0] = c; if (gzwrite(file, buf, 1) != 1) return -1; - return c; + return c & 0xff; } /* -- see zlib.h -- */ @@ -274,7 +296,7 @@ int ZEXPORT gzputs(file, str) return ret == 0 && len != 0 ? -1 : ret; } -#ifdef STDC +#if defined(STDC) || defined(Z_HAVE_STDARG_H) #include /* -- see zlib.h -- */ @@ -316,19 +338,19 @@ int ZEXPORTVA gzprintf (gzFile file, const char *format, ...) va_start(va, format); #ifdef NO_vsnprintf # ifdef HAS_vsprintf_void - (void)vsprintf(state->in, format, va); + (void)vsprintf((char *)(state->in), format, va); va_end(va); for (len = 0; len < size; len++) if (state->in[len] == 0) break; # else - len = vsprintf(state->in, format, va); + len = vsprintf((char *)(state->in), format, va); va_end(va); # endif #else # ifdef HAS_vsnprintf_void - (void)vsnprintf(state->in, size, format, va); + (void)vsnprintf((char *)(state->in), size, format, va); va_end(va); - len = strlen(state->in); + len = strlen((char *)(state->in)); # else len = vsnprintf((char *)(state->in), size, format, va); va_end(va); @@ -342,11 +364,11 @@ int ZEXPORTVA gzprintf (gzFile file, const char *format, ...) /* update buffer and position, defer compression until needed */ strm->avail_in = (unsigned)len; strm->next_in = state->in; - state->pos += len; + state->x.pos += len; return len; } -#else /* !STDC */ +#else /* !STDC && !Z_HAVE_STDARG_H */ /* -- see zlib.h -- */ int ZEXPORTVA gzprintf (file, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, @@ -366,6 +388,10 @@ int ZEXPORTVA gzprintf (file, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, state = (gz_statep)file; strm = &(state->strm); + /* check that can really pass pointer in ints */ + if (sizeof(int) != sizeof(void *)) + return 0; + /* check that we're writing and that there's no error */ if (state->mode != GZ_WRITE || state->err != Z_OK) return 0; @@ -390,22 +416,23 @@ int ZEXPORTVA gzprintf (file, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, state->in[size - 1] = 0; #ifdef NO_snprintf # ifdef HAS_sprintf_void - sprintf(state->in, format, a1, a2, a3, a4, a5, a6, a7, a8, + sprintf((char *)(state->in), format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); for (len = 0; len < size; len++) if (state->in[len] == 0) break; # else - len = sprintf(state->in, format, a1, a2, a3, a4, a5, a6, a7, a8, - a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); + len = sprintf((char *)(state->in), format, a1, a2, a3, a4, a5, a6, a7, a8, + a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); # endif #else # ifdef HAS_snprintf_void - snprintf(state->in, size, format, a1, a2, a3, a4, a5, a6, a7, a8, + snprintf((char *)(state->in), size, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); - len = strlen(state->in); + len = strlen((char *)(state->in)); # else - len = snprintf(state->in, size, format, a1, a2, a3, a4, a5, a6, a7, a8, - a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); + len = snprintf((char *)(state->in), size, format, a1, a2, a3, a4, a5, a6, + a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, + a19, a20); # endif #endif @@ -416,7 +443,7 @@ int ZEXPORTVA gzprintf (file, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, /* update buffer and position, defer compression until needed */ strm->avail_in = (unsigned)len; strm->next_in = state->in; - state->pos += len; + state->x.pos += len; return len; } @@ -500,7 +527,7 @@ int ZEXPORT gzsetparams(file, level, strategy) int ZEXPORT gzclose_w(file) gzFile file; { - int ret = 0; + int ret = Z_OK; gz_statep state; /* get internal structure */ @@ -515,17 +542,24 @@ int ZEXPORT gzclose_w(file) /* check for seek request */ if (state->seek) { state->seek = 0; - ret += gz_zero(state, state->skip); + if (gz_zero(state, state->skip) == -1) + ret = state->err; } /* flush, free memory, and close file */ - ret += gz_comp(state, Z_FINISH); - (void)deflateEnd(&(state->strm)); - free(state->out); - free(state->in); + if (state->size) { + if (gz_comp(state, Z_FINISH) == -1) + ret = state->err; + if (!state->direct) { + (void)deflateEnd(&(state->strm)); + free(state->out); + } + free(state->in); + } gz_error(state, Z_OK, NULL); free(state->path); - ret += close(state->fd); + if (close(state->fd) == -1) + ret = Z_ERRNO; free(state); - return ret ? Z_ERRNO : Z_OK; + return ret; } diff --git a/3rdparty/zlib/infback.c b/3rdparty/zlib/infback.c index af3a8c965d..981aff17c2 100644 --- a/3rdparty/zlib/infback.c +++ b/3rdparty/zlib/infback.c @@ -1,5 +1,5 @@ /* infback.c -- inflate using a call-back interface - * Copyright (C) 1995-2009 Mark Adler + * Copyright (C) 1995-2011 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ @@ -42,10 +42,19 @@ int stream_size; return Z_STREAM_ERROR; strm->msg = Z_NULL; /* in case we return an error */ if (strm->zalloc == (alloc_func)0) { +#ifdef Z_SOLO + return Z_STREAM_ERROR; +#else strm->zalloc = zcalloc; strm->opaque = (voidpf)0; +#endif } - if (strm->zfree == (free_func)0) strm->zfree = zcfree; + if (strm->zfree == (free_func)0) +#ifdef Z_SOLO + return Z_STREAM_ERROR; +#else + strm->zfree = zcfree; +#endif state = (struct inflate_state FAR *)ZALLOC(strm, 1, sizeof(struct inflate_state)); if (state == Z_NULL) return Z_MEM_ERROR; @@ -394,7 +403,6 @@ void FAR *out_desc; PULLBYTE(); } if (here.val < 16) { - NEEDBITS(here.bits); DROPBITS(here.bits); state->lens[state->have++] = here.val; } diff --git a/3rdparty/zlib/inffast.c b/3rdparty/zlib/inffast.c index 0a0761f3de..2f1d60b43b 100644 --- a/3rdparty/zlib/inffast.c +++ b/3rdparty/zlib/inffast.c @@ -1,5 +1,5 @@ /* inffast.c -- fast decoding - * Copyright (C) 1995-2008 Mark Adler + * Copyright (C) 1995-2008, 2010 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ @@ -64,7 +64,7 @@ requires strm->avail_out >= 258 for each loop to avoid checking for output space. */ -void inflate_fast(strm, start) +void ZLIB_INTERNAL inflate_fast(strm, start) z_streamp strm; unsigned start; /* inflate()'s starting value for strm->avail_out */ { diff --git a/3rdparty/zlib/inffast.h b/3rdparty/zlib/inffast.h index 1e88d2d97b..e5c1aa4ca8 100644 --- a/3rdparty/zlib/inffast.h +++ b/3rdparty/zlib/inffast.h @@ -1,5 +1,5 @@ /* inffast.h -- header to use inffast.c - * Copyright (C) 1995-2003 Mark Adler + * Copyright (C) 1995-2003, 2010 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ @@ -8,4 +8,4 @@ subject to change. Applications should only use zlib.h. */ -void inflate_fast OF((z_streamp strm, unsigned start)); +void ZLIB_INTERNAL inflate_fast OF((z_streamp strm, unsigned start)); diff --git a/3rdparty/zlib/inffixed.h b/3rdparty/zlib/inffixed.h index 75ed4b5978..d628327769 100644 --- a/3rdparty/zlib/inffixed.h +++ b/3rdparty/zlib/inffixed.h @@ -2,9 +2,9 @@ * Generated automatically by makefixed(). */ - /* WARNING: this file should *not* be used by applications. It - is part of the implementation of the compression library and - is subject to change. Applications should only use zlib.h. + /* WARNING: this file should *not* be used by applications. + It is part of the implementation of this library and is + subject to change. Applications should only use zlib.h. */ static const code lenfix[512] = { diff --git a/3rdparty/zlib/inflate.c b/3rdparty/zlib/inflate.c index a8431abeac..47418a1e1e 100644 --- a/3rdparty/zlib/inflate.c +++ b/3rdparty/zlib/inflate.c @@ -1,5 +1,5 @@ /* inflate.c -- zlib decompression - * Copyright (C) 1995-2010 Mark Adler + * Copyright (C) 1995-2012 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ @@ -100,7 +100,7 @@ local int updatewindow OF((z_streamp strm, unsigned out)); local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf, unsigned len)); -int ZEXPORT inflateReset(strm) +int ZEXPORT inflateResetKeep(strm) z_streamp strm; { struct inflate_state FAR *state; @@ -109,15 +109,13 @@ z_streamp strm; state = (struct inflate_state FAR *)strm->state; strm->total_in = strm->total_out = state->total = 0; strm->msg = Z_NULL; - strm->adler = 1; /* to support ill-conceived Java test suite */ + if (state->wrap) /* to support ill-conceived Java test suite */ + strm->adler = state->wrap & 1; state->mode = HEAD; state->last = 0; state->havedict = 0; state->dmax = 32768U; state->head = Z_NULL; - state->wsize = 0; - state->whave = 0; - state->wnext = 0; state->hold = 0; state->bits = 0; state->lencode = state->distcode = state->next = state->codes; @@ -127,6 +125,19 @@ z_streamp strm; return Z_OK; } +int ZEXPORT inflateReset(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + state->wsize = 0; + state->whave = 0; + state->wnext = 0; + return inflateResetKeep(strm); +} + int ZEXPORT inflateReset2(strm, windowBits) z_streamp strm; int windowBits; @@ -180,10 +191,19 @@ int stream_size; if (strm == Z_NULL) return Z_STREAM_ERROR; strm->msg = Z_NULL; /* in case we return an error */ if (strm->zalloc == (alloc_func)0) { +#ifdef Z_SOLO + return Z_STREAM_ERROR; +#else strm->zalloc = zcalloc; strm->opaque = (voidpf)0; +#endif } - if (strm->zfree == (free_func)0) strm->zfree = zcfree; + if (strm->zfree == (free_func)0) +#ifdef Z_SOLO + return Z_STREAM_ERROR; +#else + strm->zfree = zcfree; +#endif state = (struct inflate_state FAR *) ZALLOC(strm, 1, sizeof(struct inflate_state)); if (state == Z_NULL) return Z_MEM_ERROR; @@ -321,8 +341,8 @@ void makefixed() low = 0; for (;;) { if ((low % 7) == 0) printf("\n "); - printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits, - state.lencode[low].val); + printf("{%u,%u,%d}", (low & 127) == 99 ? 64 : state.lencode[low].op, + state.lencode[low].bits, state.lencode[low].val); if (++low == size) break; putchar(','); } @@ -499,11 +519,6 @@ unsigned out; bits -= bits & 7; \ } while (0) -/* Reverse the bytes in a 32-bit value */ -#define REVERSE(q) \ - ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \ - (((q) & 0xff00) << 8) + (((q) & 0xff) << 24)) - /* inflate() uses a state machine to process as much input data and generate as much output data as possible before returning. The state machine is @@ -797,7 +812,7 @@ int flush; #endif case DICTID: NEEDBITS(32); - strm->adler = state->check = REVERSE(hold); + strm->adler = state->check = ZSWAP32(hold); INITBITS(); state->mode = DICT; case DICT: @@ -925,7 +940,6 @@ int flush; PULLBYTE(); } if (here.val < 16) { - NEEDBITS(here.bits); DROPBITS(here.bits); state->lens[state->have++] = here.val; } @@ -1170,7 +1184,7 @@ int flush; #ifdef GUNZIP state->flags ? hold : #endif - REVERSE(hold)) != state->check) { + ZSWAP32(hold)) != state->check) { strm->msg = (char *)"incorrect data check"; state->mode = BAD; break; @@ -1214,7 +1228,8 @@ int flush; */ inf_leave: RESTORE(); - if (state->wsize || (state->mode < CHECK && out != strm->avail_out)) + if (state->wsize || (out != strm->avail_out && state->mode < BAD && + (state->mode < CHECK || flush != Z_FINISH))) if (updatewindow(strm, out)) { state->mode = MEM; return Z_MEM_ERROR; @@ -1255,7 +1270,10 @@ const Bytef *dictionary; uInt dictLength; { struct inflate_state FAR *state; - unsigned long id; + unsigned long dictid; + unsigned char *next; + unsigned avail; + int ret; /* check state */ if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; @@ -1263,29 +1281,27 @@ uInt dictLength; if (state->wrap != 0 && state->mode != DICT) return Z_STREAM_ERROR; - /* check for correct dictionary id */ + /* check for correct dictionary identifier */ if (state->mode == DICT) { - id = adler32(0L, Z_NULL, 0); - id = adler32(id, dictionary, dictLength); - if (id != state->check) + dictid = adler32(0L, Z_NULL, 0); + dictid = adler32(dictid, dictionary, dictLength); + if (dictid != state->check) return Z_DATA_ERROR; } - /* copy dictionary to window */ - if (updatewindow(strm, strm->avail_out)) { + /* copy dictionary to window using updatewindow(), which will amend the + existing dictionary if appropriate */ + next = strm->next_out; + avail = strm->avail_out; + strm->next_out = (Bytef *)dictionary + dictLength; + strm->avail_out = 0; + ret = updatewindow(strm, dictLength); + strm->avail_out = avail; + strm->next_out = next; + if (ret) { state->mode = MEM; return Z_MEM_ERROR; } - if (dictLength > state->wsize) { - zmemcpy(state->window, dictionary + dictLength - state->wsize, - state->wsize); - state->whave = state->wsize; - } - else { - zmemcpy(state->window + state->wsize - dictLength, dictionary, - dictLength); - state->whave = dictLength; - } state->havedict = 1; Tracev((stderr, "inflate: dictionary set\n")); return Z_OK; @@ -1433,8 +1449,8 @@ z_streamp source; } /* copy state */ - zmemcpy(dest, source, sizeof(z_stream)); - zmemcpy(copy, state, sizeof(struct inflate_state)); + zmemcpy((voidpf)dest, (voidpf)source, sizeof(z_stream)); + zmemcpy((voidpf)copy, (voidpf)state, sizeof(struct inflate_state)); if (state->lencode >= state->codes && state->lencode <= state->codes + ENOUGH - 1) { copy->lencode = copy->codes + (state->lencode - state->codes); diff --git a/3rdparty/zlib/inftrees.c b/3rdparty/zlib/inftrees.c index ccf7fa965f..abcd7c45ed 100644 --- a/3rdparty/zlib/inftrees.c +++ b/3rdparty/zlib/inftrees.c @@ -1,5 +1,5 @@ /* inftrees.c -- generate Huffman trees for efficient decoding - * Copyright (C) 1995-2010 Mark Adler + * Copyright (C) 1995-2012 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ @@ -9,7 +9,7 @@ #define MAXBITS 15 const char inflate_copyright[] = - " inflate 1.2.4 Copyright 1995-2010 Mark Adler "; + " inflate 1.2.7 Copyright 1995-2012 Mark Adler "; /* If you use the zlib library in a product, an acknowledgment is welcome in the documentation of your product. If for some reason you cannot @@ -29,7 +29,7 @@ const char inflate_copyright[] = table index bits. It will differ if the request is greater than the longest code or if it is less than the shortest code. */ -int inflate_table(type, lens, codes, table, bits, work) +int ZLIB_INTERNAL inflate_table(type, lens, codes, table, bits, work) codetype type; unsigned short FAR *lens; unsigned codes; @@ -62,7 +62,7 @@ unsigned short FAR *work; 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0}; static const unsigned short lext[31] = { /* Length codes 257..285 extra */ 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, - 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 64, 195}; + 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 78, 68}; static const unsigned short dbase[32] = { /* Distance codes 0..29 base */ 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, @@ -289,38 +289,14 @@ unsigned short FAR *work; } } - /* - Fill in rest of table for incomplete codes. This loop is similar to the - loop above in incrementing huff for table indices. It is assumed that - len is equal to curr + drop, so there is no loop needed to increment - through high index bits. When the current sub-table is filled, the loop - drops back to the root table to fill in any remaining entries there. - */ - here.op = (unsigned char)64; /* invalid code marker */ - here.bits = (unsigned char)(len - drop); - here.val = (unsigned short)0; - while (huff != 0) { - /* when done with sub-table, drop back to root table */ - if (drop != 0 && (huff & mask) != low) { - drop = 0; - len = root; - next = *table; - here.bits = (unsigned char)len; - } - - /* put invalid code marker in table */ - next[huff >> drop] = here; - - /* backwards increment the len-bit code huff */ - incr = 1U << (len - 1); - while (huff & incr) - incr >>= 1; - if (incr != 0) { - huff &= incr - 1; - huff += incr; - } - else - huff = 0; + /* fill in remaining table entry if code is incomplete (guaranteed to have + at most one remaining entry, since if the code is incomplete, the + maximum code length that was allowed to get this far is one bit) */ + if (huff != 0) { + here.op = (unsigned char)64; /* invalid code marker */ + here.bits = (unsigned char)(len - drop); + here.val = (unsigned short)0; + next[huff] = here; } /* set return parameters */ diff --git a/3rdparty/zlib/inftrees.h b/3rdparty/zlib/inftrees.h index 67461da034..baa53a0b1a 100644 --- a/3rdparty/zlib/inftrees.h +++ b/3rdparty/zlib/inftrees.h @@ -1,5 +1,5 @@ /* inftrees.h -- header to use inftrees.c - * Copyright (C) 1995-2005 Mark Adler + * Copyright (C) 1995-2005, 2010 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ @@ -57,6 +57,6 @@ typedef enum { DISTS } codetype; -extern int inflate_table OF((codetype type, unsigned short FAR *lens, +int ZLIB_INTERNAL inflate_table OF((codetype type, unsigned short FAR *lens, unsigned codes, code FAR * FAR *table, unsigned FAR *bits, unsigned short FAR *work)); diff --git a/3rdparty/zlib/trees.c b/3rdparty/zlib/trees.c index 1a6e997ac0..8c32b214b1 100644 --- a/3rdparty/zlib/trees.c +++ b/3rdparty/zlib/trees.c @@ -1,5 +1,5 @@ /* trees.c -- output deflated data using Huffman coding - * Copyright (C) 1995-2009 Jean-loup Gailly + * Copyright (C) 1995-2012 Jean-loup Gailly * detect_data_type() function provided freely by Cosmin Truta, 2006 * For conditions of distribution and use, see copyright notice in zlib.h */ @@ -74,11 +74,6 @@ local const uch bl_order[BL_CODES] * probability, to avoid transmitting the lengths for unused bit length codes. */ -#define Buf_size (8 * 2*sizeof(char)) -/* Number of bits used within bi_buf. (bi_buf might be implemented on - * more than 16 bits on some systems.) - */ - /* =========================================================================== * Local data. These are initialized only once. */ @@ -351,13 +346,14 @@ void gen_trees_header() static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5)); } - fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n"); + fprintf(header, "const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = {\n"); for (i = 0; i < DIST_CODE_LEN; i++) { fprintf(header, "%2u%s", _dist_code[i], SEPARATOR(i, DIST_CODE_LEN-1, 20)); } - fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n"); + fprintf(header, + "const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= {\n"); for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) { fprintf(header, "%2u%s", _length_code[i], SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20)); @@ -382,7 +378,7 @@ void gen_trees_header() /* =========================================================================== * Initialize the tree data structures for a new zlib stream. */ -void _tr_init(s) +void ZLIB_INTERNAL _tr_init(s) deflate_state *s; { tr_static_init(); @@ -398,7 +394,6 @@ void _tr_init(s) s->bi_buf = 0; s->bi_valid = 0; - s->last_eob_len = 8; /* enough lookahead for inflate */ #ifdef DEBUG s->compressed_len = 0L; s->bits_sent = 0L; @@ -867,7 +862,7 @@ local void send_all_trees(s, lcodes, dcodes, blcodes) /* =========================================================================== * Send a stored block */ -void _tr_stored_block(s, buf, stored_len, last) +void ZLIB_INTERNAL _tr_stored_block(s, buf, stored_len, last) deflate_state *s; charf *buf; /* input block */ ulg stored_len; /* length of input block */ @@ -881,18 +876,20 @@ void _tr_stored_block(s, buf, stored_len, last) copy_block(s, buf, (unsigned)stored_len, 1); /* with header */ } +/* =========================================================================== + * Flush the bits in the bit buffer to pending output (leaves at most 7 bits) + */ +void ZLIB_INTERNAL _tr_flush_bits(s) + deflate_state *s; +{ + bi_flush(s); +} + /* =========================================================================== * Send one empty static block to give enough lookahead for inflate. * This takes 10 bits, of which 7 may remain in the bit buffer. - * The current inflate code requires 9 bits of lookahead. If the - * last two codes for the previous block (real code plus EOB) were coded - * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode - * the last real code. In this case we send two empty static blocks instead - * of one. (There are no problems if the previous block is stored or fixed.) - * To simplify the code, we assume the worst case of last real code encoded - * on one bit only. */ -void _tr_align(s) +void ZLIB_INTERNAL _tr_align(s) deflate_state *s; { send_bits(s, STATIC_TREES<<1, 3); @@ -901,27 +898,13 @@ void _tr_align(s) s->compressed_len += 10L; /* 3 for block type, 7 for EOB */ #endif bi_flush(s); - /* Of the 10 bits for the empty block, we have already sent - * (10 - bi_valid) bits. The lookahead for the last real code (before - * the EOB of the previous block) was thus at least one plus the length - * of the EOB plus what we have just sent of the empty static block. - */ - if (1 + s->last_eob_len + 10 - s->bi_valid < 9) { - send_bits(s, STATIC_TREES<<1, 3); - send_code(s, END_BLOCK, static_ltree); -#ifdef DEBUG - s->compressed_len += 10L; -#endif - bi_flush(s); - } - s->last_eob_len = 7; } /* =========================================================================== * Determine the best encoding for the current block: dynamic trees, static * trees or store, and output the encoded block to the zip file. */ -void _tr_flush_block(s, buf, stored_len, last) +void ZLIB_INTERNAL _tr_flush_block(s, buf, stored_len, last) deflate_state *s; charf *buf; /* input block, or NULL if too old */ ulg stored_len; /* length of input block */ @@ -1022,7 +1005,7 @@ void _tr_flush_block(s, buf, stored_len, last) * Save the match info and tally the frequency counts. Return true if * the current block must be flushed. */ -int _tr_tally (s, dist, lc) +int ZLIB_INTERNAL _tr_tally (s, dist, lc) deflate_state *s; unsigned dist; /* distance of matched string */ unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ @@ -1117,7 +1100,6 @@ local void compress_block(s, ltree, dtree) } while (lx < s->last_lit); send_code(s, END_BLOCK, ltree); - s->last_eob_len = ltree[END_BLOCK].Len; } /* =========================================================================== @@ -1225,7 +1207,6 @@ local void copy_block(s, buf, len, header) int header; /* true if block header must be written */ { bi_windup(s); /* align on byte boundary */ - s->last_eob_len = 8; /* enough lookahead for inflate */ if (header) { put_short(s, (ush)len); diff --git a/3rdparty/zlib/trees.h b/3rdparty/zlib/trees.h index 72facf900f..d35639d82a 100644 --- a/3rdparty/zlib/trees.h +++ b/3rdparty/zlib/trees.h @@ -70,7 +70,7 @@ local const ct_data static_dtree[D_CODES] = { {{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}} }; -const uch _dist_code[DIST_CODE_LEN] = { +const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = { 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, @@ -99,7 +99,7 @@ const uch _dist_code[DIST_CODE_LEN] = { 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29 }; -const uch _length_code[MAX_MATCH-MIN_MATCH+1]= { +const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= { 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, diff --git a/3rdparty/zlib/zconf.h b/3rdparty/zlib/zconf.h index 58880245c1..8a46a58b30 100644 --- a/3rdparty/zlib/zconf.h +++ b/3rdparty/zlib/zconf.h @@ -1,5 +1,5 @@ /* zconf.h -- configuration of the zlib compression library - * Copyright (C) 1995-2010 Jean-loup Gailly. + * Copyright (C) 1995-2012 Jean-loup Gailly. * For conditions of distribution and use, see copyright notice in zlib.h */ @@ -15,6 +15,7 @@ * this permanently in zconf.h using "./configure --zprefix". */ #ifdef Z_PREFIX /* may be set to #if 1 by ./configure */ +# define Z_PREFIX_SET /* all linked symbols */ # define _dist_code z__dist_code @@ -27,9 +28,11 @@ # define adler32 z_adler32 # define adler32_combine z_adler32_combine # define adler32_combine64 z_adler32_combine64 -# define compress z_compress -# define compress2 z_compress2 -# define compressBound z_compressBound +# ifndef Z_SOLO +# define compress z_compress +# define compress2 z_compress2 +# define compressBound z_compressBound +# endif # define crc32 z_crc32 # define crc32_combine z_crc32_combine # define crc32_combine64 z_crc32_combine64 @@ -40,44 +43,52 @@ # define deflateInit2_ z_deflateInit2_ # define deflateInit_ z_deflateInit_ # define deflateParams z_deflateParams +# define deflatePending z_deflatePending # define deflatePrime z_deflatePrime # define deflateReset z_deflateReset +# define deflateResetKeep z_deflateResetKeep # define deflateSetDictionary z_deflateSetDictionary # define deflateSetHeader z_deflateSetHeader # define deflateTune z_deflateTune # define deflate_copyright z_deflate_copyright # define get_crc_table z_get_crc_table -# define gz_error z_gz_error -# define gz_intmax z_gz_intmax -# define gz_strwinerror z_gz_strwinerror -# define gzbuffer z_gzbuffer -# define gzclearerr z_gzclearerr -# define gzclose z_gzclose -# define gzclose_r z_gzclose_r -# define gzclose_w z_gzclose_w -# define gzdirect z_gzdirect -# define gzdopen z_gzdopen -# define gzeof z_gzeof -# define gzerror z_gzerror -# define gzflush z_gzflush -# define gzgetc z_gzgetc -# define gzgets z_gzgets -# define gzoffset z_gzoffset -# define gzoffset64 z_gzoffset64 -# define gzopen z_gzopen -# define gzopen64 z_gzopen64 -# define gzprintf z_gzprintf -# define gzputc z_gzputc -# define gzputs z_gzputs -# define gzread z_gzread -# define gzrewind z_gzrewind -# define gzseek z_gzseek -# define gzseek64 z_gzseek64 -# define gzsetparams z_gzsetparams -# define gztell z_gztell -# define gztell64 z_gztell64 -# define gzungetc z_gzungetc -# define gzwrite z_gzwrite +# ifndef Z_SOLO +# define gz_error z_gz_error +# define gz_intmax z_gz_intmax +# define gz_strwinerror z_gz_strwinerror +# define gzbuffer z_gzbuffer +# define gzclearerr z_gzclearerr +# define gzclose z_gzclose +# define gzclose_r z_gzclose_r +# define gzclose_w z_gzclose_w +# define gzdirect z_gzdirect +# define gzdopen z_gzdopen +# define gzeof z_gzeof +# define gzerror z_gzerror +# define gzflush z_gzflush +# define gzgetc z_gzgetc +# define gzgetc_ z_gzgetc_ +# define gzgets z_gzgets +# define gzoffset z_gzoffset +# define gzoffset64 z_gzoffset64 +# define gzopen z_gzopen +# define gzopen64 z_gzopen64 +# ifdef _WIN32 +# define gzopen_w z_gzopen_w +# endif +# define gzprintf z_gzprintf +# define gzputc z_gzputc +# define gzputs z_gzputs +# define gzread z_gzread +# define gzrewind z_gzrewind +# define gzseek z_gzseek +# define gzseek64 z_gzseek64 +# define gzsetparams z_gzsetparams +# define gztell z_gztell +# define gztell64 z_gztell64 +# define gzungetc z_gzungetc +# define gzwrite z_gzwrite +# endif # define inflate z_inflate # define inflateBack z_inflateBack # define inflateBackEnd z_inflateBackEnd @@ -95,13 +106,18 @@ # define inflateSync z_inflateSync # define inflateSyncPoint z_inflateSyncPoint # define inflateUndermine z_inflateUndermine +# define inflateResetKeep z_inflateResetKeep # define inflate_copyright z_inflate_copyright # define inflate_fast z_inflate_fast # define inflate_table z_inflate_table -# define uncompress z_uncompress +# ifndef Z_SOLO +# define uncompress z_uncompress +# endif # define zError z_zError -# define zcalloc z_zcalloc -# define zcfree z_zcfree +# ifndef Z_SOLO +# define zcalloc z_zcalloc +# define zcfree z_zcfree +# endif # define zlibCompileFlags z_zlibCompileFlags # define zlibVersion z_zlibVersion @@ -111,7 +127,9 @@ # define alloc_func z_alloc_func # define charf z_charf # define free_func z_free_func -# define gzFile z_gzFile +# ifndef Z_SOLO +# define gzFile z_gzFile +# endif # define gz_header z_gz_header # define gz_headerp z_gz_headerp # define in_func z_in_func @@ -197,6 +215,12 @@ # endif #endif +#if defined(ZLIB_CONST) && !defined(z_const) +# define z_const const +#else +# define z_const +#endif + /* Some Mac compilers merge all .h files incorrectly: */ #if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__) # define NO_DUMMY_DECL @@ -243,6 +267,14 @@ # endif #endif +#ifndef Z_ARG /* function prototypes for stdarg */ +# if defined(STDC) || defined(Z_HAVE_STDARG_H) +# define Z_ARG(args) args +# else +# define Z_ARG(args) () +# endif +#endif + /* The following definitions for FAR are needed only for MSDOS mixed * model programming (small or medium model with some far allocations). * This was tested only with MSC; for other MSDOS compilers you may have @@ -315,10 +347,6 @@ # endif #endif -#ifdef HAVE_VISIBILITY_PRAGMA -# define ZEXTERN __attribute__((visibility ("default"))) extern -#endif - #ifndef ZEXTERN # define ZEXTERN extern #endif @@ -360,40 +388,102 @@ typedef uLong FAR uLongf; typedef Byte *voidp; #endif +/* ./configure may #define Z_U4 here */ + +#if !defined(Z_U4) && !defined(Z_SOLO) && defined(STDC) +# include +# if (UINT_MAX == 0xffffffffUL) +# define Z_U4 unsigned +# else +# if (ULONG_MAX == 0xffffffffUL) +# define Z_U4 unsigned long +# else +# if (USHRT_MAX == 0xffffffffUL) +# define Z_U4 unsigned short +# endif +# endif +# endif +#endif + +#ifdef Z_U4 + typedef Z_U4 z_crc_t; +#else + typedef unsigned long z_crc_t; +#endif + #ifdef HAVE_UNISTD_H /* may be set to #if 1 by ./configure */ # define Z_HAVE_UNISTD_H #endif -#ifdef Z_HAVE_UNISTD_H -# include /* for off_t */ -# include /* for SEEK_* and off_t */ -# ifdef VMS -# include /* for off_t */ -# endif -# ifndef z_off_t -# define z_off_t off_t +#ifdef HAVE_STDARG_H /* may be set to #if 1 by ./configure */ +# define Z_HAVE_STDARG_H +#endif + +#ifdef STDC +# ifndef Z_SOLO +# include /* for off_t */ # endif #endif -#ifdef _LARGEFILE64_SOURCE -# include +#ifdef _WIN32 +# include /* for wchar_t */ #endif -#ifndef SEEK_SET +/* a little trick to accommodate both "#define _LARGEFILE64_SOURCE" and + * "#define _LARGEFILE64_SOURCE 1" as requesting 64-bit operations, (even + * though the former does not conform to the LFS document), but considering + * both "#undef _LARGEFILE64_SOURCE" and "#define _LARGEFILE64_SOURCE 0" as + * equivalently requesting no 64-bit operations + */ +#if defined(LARGEFILE64_SOURCE) && -_LARGEFILE64_SOURCE - -1 == 1 +# undef _LARGEFILE64_SOURCE +#endif + +#if defined(__WATCOMC__) && !defined(Z_HAVE_UNISTD_H) +# define Z_HAVE_UNISTD_H +#endif +#ifndef Z_SOLO +# if defined(Z_HAVE_UNISTD_H) || defined(LARGEFILE64_SOURCE) +# include /* for SEEK_*, off_t, and _LFS64_LARGEFILE */ +# ifdef VMS +# include /* for off_t */ +# endif +# ifndef z_off_t +# define z_off_t off_t +# endif +# endif +#endif + +#if defined(_LFS64_LARGEFILE) && _LFS64_LARGEFILE-0 +# define Z_LFS64 +#endif + +#if defined(_LARGEFILE64_SOURCE) && defined(Z_LFS64) +# define Z_LARGE64 +#endif + +#if defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS-0 == 64 && defined(Z_LFS64) +# define Z_WANT64 +#endif + +#if !defined(SEEK_SET) && !defined(Z_SOLO) # define SEEK_SET 0 /* Seek from beginning of file. */ # define SEEK_CUR 1 /* Seek from current position. */ # define SEEK_END 2 /* Set file pointer to EOF plus "offset" */ #endif + #ifndef z_off_t # define z_off_t long #endif -#if defined(__OS400__) -# define NO_vsnprintf -#endif - -#if defined(__MVS__) -# define NO_vsnprintf +#if !defined(_WIN32) && defined(Z_LARGE64) +# define z_off64_t off64_t +#else +# if defined(_WIN32) && !defined(__GNUC__) && !defined(Z_SOLO) +# define z_off64_t __int64 +# else +# define z_off64_t z_off_t +# endif #endif /* MVS linker does not support external names larger than 8 bytes */ diff --git a/3rdparty/zlib/zlib.h b/3rdparty/zlib/zlib.h index f5785be7e0..3edf3acdb5 100644 --- a/3rdparty/zlib/zlib.h +++ b/3rdparty/zlib/zlib.h @@ -1,7 +1,7 @@ /* zlib.h -- interface of the 'zlib' general purpose compression library - version 1.2.4, Mar 14th, 2010 + version 1.2.7, May 2nd, 2012 - Copyright (C) 1995-2010 Jean-loup Gailly and Mark Adler + Copyright (C) 1995-2012 Jean-loup Gailly and Mark Adler This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages @@ -24,8 +24,8 @@ The data format used by the zlib library is described by RFCs (Request for - Comments) 1950 to 1952 in the files http://www.ietf.org/rfc/rfc1950.txt - (zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format). + Comments) 1950 to 1952 in the files http://tools.ietf.org/html/rfc1950 + (zlib format), rfc1951 (deflate format) and rfc1952 (gzip format). */ #ifndef ZLIB_H @@ -37,11 +37,11 @@ extern "C" { #endif -#define ZLIB_VERSION "1.2.4" -#define ZLIB_VERNUM 0x1240 +#define ZLIB_VERSION "1.2.7" +#define ZLIB_VERNUM 0x1270 #define ZLIB_VER_MAJOR 1 #define ZLIB_VER_MINOR 2 -#define ZLIB_VER_REVISION 4 +#define ZLIB_VER_REVISION 7 #define ZLIB_VER_SUBREVISION 0 /* @@ -83,15 +83,15 @@ typedef void (*free_func) OF((voidpf opaque, voidpf address)); struct internal_state; typedef struct z_stream_s { - Bytef *next_in; /* next input byte */ + z_const Bytef *next_in; /* next input byte */ uInt avail_in; /* number of bytes available at next_in */ - uLong total_in; /* total nb of input bytes read so far */ + uLong total_in; /* total number of input bytes read so far */ Bytef *next_out; /* next output byte should be put there */ uInt avail_out; /* remaining free space at next_out */ - uLong total_out; /* total nb of bytes output so far */ + uLong total_out; /* total number of bytes output so far */ - char *msg; /* last error message, NULL if no error */ + z_const char *msg; /* last error message, NULL if no error */ struct internal_state FAR *state; /* not visible by applications */ alloc_func zalloc; /* used to allocate the internal state */ @@ -327,8 +327,9 @@ ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush)); Z_FINISH can be used immediately after deflateInit if all the compression is to be done in a single step. In this case, avail_out must be at least the - value returned by deflateBound (see below). If deflate does not return - Z_STREAM_END, then it must be called again as described above. + value returned by deflateBound (see below). Then deflate is guaranteed to + return Z_STREAM_END. If not enough output space is provided, deflate will + not return Z_STREAM_END, and it must be called again as described above. deflate() sets strm->adler to the adler32 checksum of all input read so far (that is, total_in bytes). @@ -451,23 +452,29 @@ ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush)); error. However if all decompression is to be performed in a single step (a single call of inflate), the parameter flush should be set to Z_FINISH. In this case all pending input is processed and all pending output is flushed; - avail_out must be large enough to hold all the uncompressed data. (The size - of the uncompressed data may have been saved by the compressor for this - purpose.) The next operation on this stream must be inflateEnd to deallocate - the decompression state. The use of Z_FINISH is never required, but can be - used to inform inflate that a faster approach may be used for the single - inflate() call. + avail_out must be large enough to hold all of the uncompressed data for the + operation to complete. (The size of the uncompressed data may have been + saved by the compressor for this purpose.) The use of Z_FINISH is not + required to perform an inflation in one step. However it may be used to + inform inflate that a faster approach can be used for the single inflate() + call. Z_FINISH also informs inflate to not maintain a sliding window if the + stream completes, which reduces inflate's memory footprint. If the stream + does not complete, either because not all of the stream is provided or not + enough output space is provided, then a sliding window will be allocated and + inflate() can be called again to continue the operation as if Z_NO_FLUSH had + been used. In this implementation, inflate() always flushes as much output as possible to the output buffer, and always uses the faster approach on the - first call. So the only effect of the flush parameter in this implementation - is on the return value of inflate(), as noted below, or when it returns early - because Z_BLOCK or Z_TREES is used. + first call. So the effects of the flush parameter in this implementation are + on the return value of inflate() as noted below, when inflate() returns early + when Z_BLOCK or Z_TREES is used, and when inflate() avoids the allocation of + memory for a sliding window when Z_FINISH is used. If a preset dictionary is needed after this call (see inflateSetDictionary - below), inflate sets strm->adler to the adler32 checksum of the dictionary + below), inflate sets strm->adler to the Adler-32 checksum of the dictionary chosen by the compressor and returns Z_NEED_DICT; otherwise it sets - strm->adler to the adler32 checksum of all output produced so far (that is, + strm->adler to the Adler-32 checksum of all output produced so far (that is, total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described below. At the end of the stream, inflate() checks that its computed adler32 checksum is equal to that saved by the compressor and returns Z_STREAM_END @@ -478,7 +485,9 @@ ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush)); initializing with inflateInit2(). Any information contained in the gzip header is not retained, so applications that need that information should instead use raw inflate, see inflateInit2() below, or inflateBack() and - perform their own processing of the gzip header and trailer. + perform their own processing of the gzip header and trailer. When processing + gzip-wrapped deflate data, strm->adler32 is set to the CRC-32 of the output + producted so far. The CRC-32 is checked against the gzip trailer. inflate() returns Z_OK if some progress has been made (more input processed or more output produced), Z_STREAM_END if the end of the compressed data has @@ -580,10 +589,15 @@ ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm, uInt dictLength)); /* Initializes the compression dictionary from the given byte sequence - without producing any compressed output. This function must be called - immediately after deflateInit, deflateInit2 or deflateReset, before any call - of deflate. The compressor and decompressor must use exactly the same - dictionary (see inflateSetDictionary). + without producing any compressed output. When using the zlib format, this + function must be called immediately after deflateInit, deflateInit2 or + deflateReset, and before any call of deflate. When doing raw deflate, this + function must be called either before any call of deflate, or immediately + after the completion of a deflate block, i.e. after all input has been + consumed and all output has been delivered when using any of the flush + options Z_BLOCK, Z_PARTIAL_FLUSH, Z_SYNC_FLUSH, or Z_FULL_FLUSH. The + compressor and decompressor must use exactly the same dictionary (see + inflateSetDictionary). The dictionary should consist of strings (byte sequences) that are likely to be encountered later in the data to be compressed, with the most commonly @@ -610,8 +624,8 @@ ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm, deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is inconsistent (for example if deflate has already been called for this stream - or if the compression method is bsort). deflateSetDictionary does not - perform any compression: this will be done by deflate(). + or if not at a block boundary for raw deflate). deflateSetDictionary does + not perform any compression: this will be done by deflate(). */ ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest, @@ -688,9 +702,29 @@ ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm, deflation of sourceLen bytes. It must be called after deflateInit() or deflateInit2(), and after deflateSetHeader(), if used. This would be used to allocate an output buffer for deflation in a single pass, and so would be - called before deflate(). + called before deflate(). If that first deflate() call is provided the + sourceLen input bytes, an output buffer allocated to the size returned by + deflateBound(), and the flush value Z_FINISH, then deflate() is guaranteed + to return Z_STREAM_END. Note that it is possible for the compressed size to + be larger than the value returned by deflateBound() if flush options other + than Z_FINISH or Z_NO_FLUSH are used. */ +ZEXTERN int ZEXPORT deflatePending OF((z_streamp strm, + unsigned *pending, + int *bits)); +/* + deflatePending() returns the number of bytes and bits of output that have + been generated, but not yet provided in the available output. The bytes not + provided would be due to the available output space having being consumed. + The number of bits of output not provided are between 0 and 7, where they + await more bits to join them in order to fill out a full byte. If pending + or bits are Z_NULL, then those values are not set. + + deflatePending returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. + */ + ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm, int bits, int value)); @@ -703,8 +737,9 @@ ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm, than or equal to 16, and that many of the least significant bits of value will be inserted in the output. - deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent. + deflatePrime returns Z_OK if success, Z_BUF_ERROR if there was not enough + room in the internal buffer to insert the bits, or Z_STREAM_ERROR if the + source stream state was inconsistent. */ ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm, @@ -790,10 +825,11 @@ ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm, if that call returned Z_NEED_DICT. The dictionary chosen by the compressor can be determined from the adler32 value returned by that call of inflate. The compressor and decompressor must use exactly the same dictionary (see - deflateSetDictionary). For raw inflate, this function can be called - immediately after inflateInit2() or inflateReset() and before any call of - inflate() to set the dictionary. The application must insure that the - dictionary that was used for compression is provided. + deflateSetDictionary). For raw inflate, this function can be called at any + time to set the dictionary. If the provided dictionary is smaller than the + window and there is already data in the window, then the provided dictionary + will amend what's there. The application must insure that the dictionary + that was used for compression is provided. inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is @@ -805,17 +841,21 @@ ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm, ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm)); /* - Skips invalid compressed data until a full flush point (see above the - description of deflate with Z_FULL_FLUSH) can be found, or until all + Skips invalid compressed data until a possible full flush point (see above + for the description of deflate with Z_FULL_FLUSH) can be found, or until all available input is skipped. No output is provided. - inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR - if no more input was provided, Z_DATA_ERROR if no flush point has been - found, or Z_STREAM_ERROR if the stream structure was inconsistent. In the - success case, the application may save the current current value of total_in - which indicates where valid compressed data was found. In the error case, - the application may repeatedly call inflateSync, providing more input each - time, until success or end of the input data. + inflateSync searches for a 00 00 FF FF pattern in the compressed data. + All full flush points have this pattern, but not all occurences of this + pattern are full flush points. + + inflateSync returns Z_OK if a possible full flush point has been found, + Z_BUF_ERROR if no more input was provided, Z_DATA_ERROR if no flush point + has been found, or Z_STREAM_ERROR if the stream structure was inconsistent. + In the success case, the application may save the current current value of + total_in which indicates where valid compressed data was found. In the + error case, the application may repeatedly call inflateSync, providing more + input each time, until success or end of the input data. */ ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest, @@ -962,7 +1002,7 @@ ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits, See inflateBack() for the usage of these routines. inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of - the paramaters are invalid, Z_MEM_ERROR if the internal state could not be + the parameters are invalid, Z_MEM_ERROR if the internal state could not be allocated, or Z_VERSION_ERROR if the version of the library does not match the version of the header file. */ @@ -1088,6 +1128,7 @@ ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void)); 27-31: 0 (reserved) */ +#ifndef Z_SOLO /* utility functions */ @@ -1149,10 +1190,11 @@ ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen, uncompress returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR if there was not enough room in the output - buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete. + buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete. In + the case where there is not enough room, uncompress() will fill the output + buffer with the uncompressed data up to that point. */ - /* gzip file access functions */ /* @@ -1162,7 +1204,7 @@ ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen, wrapper, documented in RFC 1952, wrapped around a deflate stream. */ -typedef voidp gzFile; /* opaque gzip file descriptor */ +typedef struct gzFile_s *gzFile; /* semi-opaque gzip file descriptor */ /* ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode)); @@ -1172,13 +1214,28 @@ ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode)); a strategy: 'f' for filtered data as in "wb6f", 'h' for Huffman-only compression as in "wb1h", 'R' for run-length encoding as in "wb1R", or 'F' for fixed code compression as in "wb9F". (See the description of - deflateInit2 for more information about the strategy parameter.) Also "a" - can be used instead of "w" to request that the gzip stream that will be - written be appended to the file. "+" will result in an error, since reading - and writing to the same gzip file is not supported. + deflateInit2 for more information about the strategy parameter.) 'T' will + request transparent writing or appending with no compression and not using + the gzip format. + + "a" can be used instead of "w" to request that the gzip stream that will + be written be appended to the file. "+" will result in an error, since + reading and writing to the same gzip file is not supported. The addition of + "x" when writing will create the file exclusively, which fails if the file + already exists. On systems that support it, the addition of "e" when + reading or writing will set the flag to close the file on an execve() call. + + These functions, as well as gzip, will read and decode a sequence of gzip + streams in a file. The append function of gzopen() can be used to create + such a file. (Also see gzflush() for another way to do this.) When + appending, gzopen does not test whether the file begins with a gzip stream, + nor does it look for the end of the gzip streams to begin appending. gzopen + will simply append a gzip stream to the existing file. gzopen can be used to read a file which is not in gzip format; in this - case gzread will directly read from the file without decompression. + case gzread will directly read from the file without decompression. When + reading, this will be detected automatically by looking for the magic two- + byte gzip header. gzopen returns NULL if the file could not be opened, if there was insufficient memory to allocate the gzFile state, or if an invalid mode was @@ -1197,7 +1254,11 @@ ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode)); descriptor fd, just like fclose(fdopen(fd, mode)) closes the file descriptor fd. If you want to keep fd open, use fd = dup(fd_keep); gz = gzdopen(fd, mode);. The duplicated descriptor should be saved to avoid a leak, since - gzdopen does not close fd if it fails. + gzdopen does not close fd if it fails. If you are using fileno() to get the + file descriptor from a FILE *, then you will have to use dup() to avoid + double-close()ing the file descriptor. Both gzclose() and fclose() will + close the associated file descriptor, so they need to have different file + descriptors. gzdopen returns NULL if there was insufficient memory to allocate the gzFile state, if an invalid mode was specified (an 'r', 'w', or 'a' was not @@ -1235,14 +1296,26 @@ ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy)); ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len)); /* Reads the given number of uncompressed bytes from the compressed file. If - the input file was not in gzip format, gzread copies the given number of - bytes into the buffer. + the input file is not in gzip format, gzread copies the given number of + bytes into the buffer directly from the file. After reaching the end of a gzip stream in the input, gzread will continue - to read, looking for another gzip stream, or failing that, reading the rest - of the input file directly without decompression. The entire input file - will be read if gzread is called until it returns less than the requested - len. + to read, looking for another gzip stream. Any number of gzip streams may be + concatenated in the input file, and will all be decompressed by gzread(). + If something other than a gzip stream is encountered after a gzip stream, + that remaining trailing garbage is ignored (and no error is returned). + + gzread can be used to read a gzip file that is being concurrently written. + Upon reaching the end of the input, gzread will return with the available + data. If the error code returned by gzerror is Z_OK or Z_BUF_ERROR, then + gzclearerr can be used to clear the end of file indicator in order to permit + gzread to be tried again. Z_OK indicates that a gzip stream was completed + on the last gzread. Z_BUF_ERROR indicates that the input file ended in the + middle of a gzip stream. Note that gzread does not return -1 in the event + of an incomplete gzip stream. This error is deferred until gzclose(), which + will return Z_BUF_ERROR if the last gzread ended in the middle of a gzip + stream. Alternatively, gzerror can be used before gzclose to detect this + case. gzread returns the number of uncompressed bytes actually read, less than len for end of file, or -1 for error. @@ -1256,7 +1329,7 @@ ZEXTERN int ZEXPORT gzwrite OF((gzFile file, error. */ -ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...)); +ZEXTERN int ZEXPORTVA gzprintf Z_ARG((gzFile file, const char *format, ...)); /* Converts, formats, and writes the arguments to the compressed file under control of the format string, as in fprintf. gzprintf returns the number of @@ -1301,7 +1374,10 @@ ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c)); ZEXTERN int ZEXPORT gzgetc OF((gzFile file)); /* Reads one byte from the compressed file. gzgetc returns this byte or -1 - in case of end of file or error. + in case of end of file or error. This is implemented as a macro for speed. + As such, it does not do all of the checking the other functions do. I.e. + it does not check to see if file is NULL, nor whether the structure file + points to has been clobbered or not. */ ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file)); @@ -1397,9 +1473,7 @@ ZEXTERN int ZEXPORT gzeof OF((gzFile file)); ZEXTERN int ZEXPORT gzdirect OF((gzFile file)); /* Returns true (1) if file is being copied directly while reading, or false - (0) if file is a gzip stream being decompressed. This state can change from - false to true while reading the input file if the end of a gzip stream is - reached, but is followed by data that is not another gzip stream. + (0) if file is a gzip stream being decompressed. If the input file is empty, gzdirect() will return true, since the input does not contain a gzip stream. @@ -1408,6 +1482,13 @@ ZEXTERN int ZEXPORT gzdirect OF((gzFile file)); cause buffers to be allocated to allow reading the file to determine if it is a gzip file. Therefore if gzbuffer() is used, it should be called before gzdirect(). + + When writing, gzdirect() returns true (1) if transparent writing was + requested ("wT" for the gzopen() mode), or false (0) otherwise. (Note: + gzdirect() is not needed when writing. Transparent writing must be + explicitly requested, so the application already knows the answer. When + linking statically, using gzdirect() will include all of the zlib code for + gzip file reading and decompression, which may not be desired.) */ ZEXTERN int ZEXPORT gzclose OF((gzFile file)); @@ -1419,7 +1500,8 @@ ZEXTERN int ZEXPORT gzclose OF((gzFile file)); must not be called more than once on the same allocation. gzclose will return Z_STREAM_ERROR if file is not valid, Z_ERRNO on a - file operation error, or Z_OK on success. + file operation error, Z_MEM_ERROR if out of memory, Z_BUF_ERROR if the + last read ended in the middle of a gzip stream, or Z_OK on success. */ ZEXTERN int ZEXPORT gzclose_r OF((gzFile file)); @@ -1457,6 +1539,7 @@ ZEXTERN void ZEXPORT gzclearerr OF((gzFile file)); file that is being written concurrently. */ +#endif /* !Z_SOLO */ /* checksum functions */ @@ -1492,16 +1575,17 @@ ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2, Combine two Adler-32 checksums into one. For two sequences of bytes, seq1 and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of - seq1 and seq2 concatenated, requiring only adler1, adler2, and len2. + seq1 and seq2 concatenated, requiring only adler1, adler2, and len2. Note + that the z_off_t type (like off_t) is a signed integer. If len2 is + negative, the result has no meaning or utility. */ ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len)); /* Update a running CRC-32 with the bytes buf[0..len-1] and return the updated CRC-32. If buf is Z_NULL, this function returns the required - initial value for the for the crc. Pre- and post-conditioning (one's - complement) is performed within this function so it shouldn't be done by the - application. + initial value for the crc. Pre- and post-conditioning (one's complement) is + performed within this function so it shouldn't be done by the application. Usage example: @@ -1544,41 +1628,81 @@ ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits, const char *version, int stream_size)); #define deflateInit(strm, level) \ - deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream)) + deflateInit_((strm), (level), ZLIB_VERSION, (int)sizeof(z_stream)) #define inflateInit(strm) \ - inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream)) + inflateInit_((strm), ZLIB_VERSION, (int)sizeof(z_stream)) #define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \ deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\ - (strategy), ZLIB_VERSION, sizeof(z_stream)) + (strategy), ZLIB_VERSION, (int)sizeof(z_stream)) #define inflateInit2(strm, windowBits) \ - inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream)) + inflateInit2_((strm), (windowBits), ZLIB_VERSION, \ + (int)sizeof(z_stream)) #define inflateBackInit(strm, windowBits, window) \ inflateBackInit_((strm), (windowBits), (window), \ - ZLIB_VERSION, sizeof(z_stream)) + ZLIB_VERSION, (int)sizeof(z_stream)) -#ifdef _LARGEFILE64_SOURCE - ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); - ZEXTERN off64_t ZEXPORT gzseek64 OF((gzFile, off64_t, int)); - ZEXTERN off64_t ZEXPORT gztell64 OF((gzFile)); - ZEXTERN off64_t ZEXPORT gzoffset64 OF((gzFile)); - ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, off64_t)); - ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, off64_t)); +#ifndef Z_SOLO + +/* gzgetc() macro and its supporting function and exposed data structure. Note + * that the real internal state is much larger than the exposed structure. + * This abbreviated structure exposes just enough for the gzgetc() macro. The + * user should not mess with these exposed elements, since their names or + * behavior could change in the future, perhaps even capriciously. They can + * only be used by the gzgetc() macro. You have been warned. + */ +struct gzFile_s { + unsigned have; + unsigned char *next; + z_off64_t pos; +}; +ZEXTERN int ZEXPORT gzgetc_ OF((gzFile file)); /* backward compatibility */ +#ifdef Z_PREFIX_SET +# undef z_gzgetc +# define z_gzgetc(g) \ + ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : gzgetc(g)) +#else +# define gzgetc(g) \ + ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : gzgetc(g)) #endif -#if !defined(ZLIB_INTERNAL) && _FILE_OFFSET_BITS == 64 -# define gzopen gzopen64 -# define gzseek gzseek64 -# define gztell gztell64 -# define gzoffset gzoffset64 -# define adler32_combine adler32_combine64 -# define crc32_combine crc32_combine64 -# ifndef _LARGEFILE64_SOURCE +/* provide 64-bit offset functions if _LARGEFILE64_SOURCE defined, and/or + * change the regular functions to 64 bits if _FILE_OFFSET_BITS is 64 (if + * both are true, the application gets the *64 functions, and the regular + * functions are changed to 64 bits) -- in case these are set on systems + * without large file support, _LFS64_LARGEFILE must also be true + */ +#ifdef Z_LARGE64 + ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); + ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int)); + ZEXTERN z_off64_t ZEXPORT gztell64 OF((gzFile)); + ZEXTERN z_off64_t ZEXPORT gzoffset64 OF((gzFile)); + ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off64_t)); + ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off64_t)); +#endif + +#if !defined(ZLIB_INTERNAL) && defined(Z_WANT64) +# ifdef Z_PREFIX_SET +# define z_gzopen z_gzopen64 +# define z_gzseek z_gzseek64 +# define z_gztell z_gztell64 +# define z_gzoffset z_gzoffset64 +# define z_adler32_combine z_adler32_combine64 +# define z_crc32_combine z_crc32_combine64 +# else +# define gzopen gzopen64 +# define gzseek gzseek64 +# define gztell gztell64 +# define gzoffset gzoffset64 +# define adler32_combine adler32_combine64 +# define crc32_combine crc32_combine64 +# endif +# ifndef Z_LARGE64 ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); - ZEXTERN off_t ZEXPORT gzseek64 OF((gzFile, off_t, int)); - ZEXTERN off_t ZEXPORT gztell64 OF((gzFile)); - ZEXTERN off_t ZEXPORT gzoffset64 OF((gzFile)); - ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, off_t)); - ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, off_t)); + ZEXTERN z_off_t ZEXPORT gzseek64 OF((gzFile, z_off_t, int)); + ZEXTERN z_off_t ZEXPORT gztell64 OF((gzFile)); + ZEXTERN z_off_t ZEXPORT gzoffset64 OF((gzFile)); + ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t)); + ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t)); # endif #else ZEXTERN gzFile ZEXPORT gzopen OF((const char *, const char *)); @@ -1589,14 +1713,29 @@ ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits, ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t)); #endif +#else /* Z_SOLO */ + + ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t)); + ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t)); + +#endif /* !Z_SOLO */ + +/* hack for buggy compilers */ #if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL) - struct internal_state {int dummy;}; /* hack for buggy compilers */ + struct internal_state {int dummy;}; #endif +/* undocumented functions */ ZEXTERN const char * ZEXPORT zError OF((int)); ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp)); -ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void)); +ZEXTERN const z_crc_t FAR * ZEXPORT get_crc_table OF((void)); ZEXTERN int ZEXPORT inflateUndermine OF((z_streamp, int)); +ZEXTERN int ZEXPORT inflateResetKeep OF((z_streamp)); +ZEXTERN int ZEXPORT deflateResetKeep OF((z_streamp)); +#if defined(_WIN32) && !defined(Z_SOLO) +ZEXTERN gzFile ZEXPORT gzopen_w OF((const wchar_t *path, + const char *mode)); +#endif #ifdef __cplusplus } diff --git a/3rdparty/zlib/zutil.c b/3rdparty/zlib/zutil.c index 98a55a8838..65e0d3b72b 100644 --- a/3rdparty/zlib/zutil.c +++ b/3rdparty/zlib/zutil.c @@ -1,11 +1,14 @@ /* zutil.c -- target dependent utility functions for the compression library - * Copyright (C) 1995-2005 Jean-loup Gailly. + * Copyright (C) 1995-2005, 2010, 2011, 2012 Jean-loup Gailly. * For conditions of distribution and use, see copyright notice in zlib.h */ /* @(#) $Id$ */ #include "zutil.h" +#ifndef Z_SOLO +# include "gzguts.h" +#endif #ifndef NO_DUMMY_DECL struct internal_state {int dummy;}; /* for buggy compilers */ @@ -85,27 +88,27 @@ uLong ZEXPORT zlibCompileFlags() #ifdef FASTEST flags += 1L << 21; #endif -#ifdef STDC +#if defined(STDC) || defined(Z_HAVE_STDARG_H) # ifdef NO_vsnprintf - flags += 1L << 25; + flags += 1L << 25; # ifdef HAS_vsprintf_void - flags += 1L << 26; + flags += 1L << 26; # endif # else # ifdef HAS_vsnprintf_void - flags += 1L << 26; + flags += 1L << 26; # endif # endif #else - flags += 1L << 24; + flags += 1L << 24; # ifdef NO_snprintf - flags += 1L << 25; + flags += 1L << 25; # ifdef HAS_sprintf_void - flags += 1L << 26; + flags += 1L << 26; # endif # else # ifdef HAS_snprintf_void - flags += 1L << 26; + flags += 1L << 26; # endif # endif #endif @@ -117,9 +120,9 @@ uLong ZEXPORT zlibCompileFlags() # ifndef verbose # define verbose 0 # endif -int z_verbose = verbose; +int ZLIB_INTERNAL z_verbose = verbose; -void z_error (m) +void ZLIB_INTERNAL z_error (m) char *m; { fprintf(stderr, "%s\n", m); @@ -146,7 +149,7 @@ const char * ZEXPORT zError(err) #ifndef HAVE_MEMCPY -void zmemcpy(dest, source, len) +void ZLIB_INTERNAL zmemcpy(dest, source, len) Bytef* dest; const Bytef* source; uInt len; @@ -157,7 +160,7 @@ void zmemcpy(dest, source, len) } while (--len != 0); } -int zmemcmp(s1, s2, len) +int ZLIB_INTERNAL zmemcmp(s1, s2, len) const Bytef* s1; const Bytef* s2; uInt len; @@ -170,7 +173,7 @@ int zmemcmp(s1, s2, len) return 0; } -void zmemzero(dest, len) +void ZLIB_INTERNAL zmemzero(dest, len) Bytef* dest; uInt len; { @@ -181,6 +184,7 @@ void zmemzero(dest, len) } #endif +#ifndef Z_SOLO #ifdef SYS16BIT @@ -213,7 +217,7 @@ local ptr_table table[MAX_PTR]; * a protected system like OS/2. Use Microsoft C instead. */ -voidpf zcalloc (voidpf opaque, unsigned items, unsigned size) +voidpf ZLIB_INTERNAL zcalloc (voidpf opaque, unsigned items, unsigned size) { voidpf buf = opaque; /* just to make some compilers happy */ ulg bsize = (ulg)items*size; @@ -237,7 +241,7 @@ voidpf zcalloc (voidpf opaque, unsigned items, unsigned size) return buf; } -void zcfree (voidpf opaque, voidpf ptr) +void ZLIB_INTERNAL zcfree (voidpf opaque, voidpf ptr) { int n; if (*(ush*)&ptr != 0) { /* object < 64K */ @@ -272,13 +276,13 @@ void zcfree (voidpf opaque, voidpf ptr) # define _hfree hfree #endif -voidpf zcalloc (voidpf opaque, unsigned items, unsigned size) +voidpf ZLIB_INTERNAL zcalloc (voidpf opaque, uInt items, uInt size) { if (opaque) opaque = 0; /* to make compiler happy */ return _halloc((long)items, size); } -void zcfree (voidpf opaque, voidpf ptr) +void ZLIB_INTERNAL zcfree (voidpf opaque, voidpf ptr) { if (opaque) opaque = 0; /* to make compiler happy */ _hfree(ptr); @@ -297,7 +301,7 @@ extern voidp calloc OF((uInt items, uInt size)); extern void free OF((voidpf ptr)); #endif -voidpf zcalloc (opaque, items, size) +voidpf ZLIB_INTERNAL zcalloc (opaque, items, size) voidpf opaque; unsigned items; unsigned size; @@ -307,7 +311,7 @@ voidpf zcalloc (opaque, items, size) (voidpf)calloc(items, size); } -void zcfree (opaque, ptr) +void ZLIB_INTERNAL zcfree (opaque, ptr) voidpf opaque; voidpf ptr; { @@ -316,3 +320,5 @@ void zcfree (opaque, ptr) } #endif /* MY_ZCALLOC */ + +#endif /* !Z_SOLO */ diff --git a/3rdparty/zlib/zutil.h b/3rdparty/zlib/zutil.h index 025035dbe9..4e3dcc6ae9 100644 --- a/3rdparty/zlib/zutil.h +++ b/3rdparty/zlib/zutil.h @@ -1,5 +1,5 @@ /* zutil.h -- internal interface and configuration of the compression library - * Copyright (C) 1995-2010 Jean-loup Gailly. + * Copyright (C) 1995-2012 Jean-loup Gailly. * For conditions of distribution and use, see copyright notice in zlib.h */ @@ -13,10 +13,15 @@ #ifndef ZUTIL_H #define ZUTIL_H -#define ZLIB_INTERNAL +#ifdef HAVE_HIDDEN +# define ZLIB_INTERNAL __attribute__((visibility ("hidden"))) +#else +# define ZLIB_INTERNAL +#endif + #include "zlib.h" -#ifdef STDC +#if defined(STDC) && !defined(Z_SOLO) # if !(defined(_WIN32_WCE) && defined(_MSC_VER)) # include # endif @@ -24,17 +29,8 @@ # include #endif -#if defined(UNDER_CE) && defined(NO_ERRNO_H) -# define zseterrno(ERR) SetLastError((DWORD)(ERR)) -# define zerrno() ((int)GetLastError()) -#else -# ifdef NO_ERRNO_H - extern int errno; -# else -# include -# endif -# define zseterrno(ERR) do { errno = (ERR); } while (0) -# define zerrno() errno +#ifdef Z_SOLO + typedef long ptrdiff_t; /* guess -- will be caught if guess is wrong */ #endif #ifndef local @@ -86,16 +82,18 @@ extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */ #if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32)) # define OS_CODE 0x00 -# if defined(__TURBOC__) || defined(__BORLANDC__) -# if (__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__)) - /* Allow compilation with ANSI keywords only enabled */ - void _Cdecl farfree( void *block ); - void *_Cdecl farmalloc( unsigned long nbytes ); -# else -# include +# ifndef Z_SOLO +# if defined(__TURBOC__) || defined(__BORLANDC__) +# if (__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__)) + /* Allow compilation with ANSI keywords only enabled */ + void _Cdecl farfree( void *block ); + void *_Cdecl farmalloc( unsigned long nbytes ); +# else +# include +# endif +# else /* MSC or DJGPP */ +# include # endif -# else /* MSC or DJGPP */ -# include # endif #endif @@ -115,18 +113,20 @@ extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */ #ifdef OS2 # define OS_CODE 0x06 -# ifdef M_I86 +# if defined(M_I86) && !defined(Z_SOLO) # include # endif #endif #if defined(MACOS) || defined(TARGET_OS_MAC) # define OS_CODE 0x07 -# if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os -# include /* for fdopen */ -# else -# ifndef fdopen -# define fdopen(fd,mode) NULL /* No fdopen() */ +# ifndef Z_SOLO +# if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os +# include /* for fdopen */ +# else +# ifndef fdopen +# define fdopen(fd,mode) NULL /* No fdopen() */ +# endif # endif # endif #endif @@ -161,16 +161,16 @@ extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */ # endif #endif -#if defined(__BORLANDC__) +#if defined(__BORLANDC__) && !defined(MSDOS) #pragma warn -8004 #pragma warn -8008 #pragma warn -8066 #endif -#ifdef _LARGEFILE64_SOURCE -# define z_off64_t off64_t -#else -# define z_off64_t z_off_t +/* provide prototypes for these when building zlib without LFS */ +#if !defined(_WIN32) && (!defined(_LARGEFILE64_SOURCE) || _LFS64_LARGEFILE-0 == 0) + ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t)); + ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t)); #endif /* common defaults */ @@ -181,52 +181,11 @@ extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */ #ifndef F_OPEN # define F_OPEN(name, mode) fopen((name), (mode)) -#endif - -#ifdef _LARGEFILE64_SOURCE -# define F_OPEN64(name, mode) fopen64((name), (mode)) -#else -# define F_OPEN64(name, mode) fopen((name), (mode)) #endif /* functions */ -#if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550) -# ifndef HAVE_VSNPRINTF -# define HAVE_VSNPRINTF -# endif -#endif -#if defined(__CYGWIN__) -# ifndef HAVE_VSNPRINTF -# define HAVE_VSNPRINTF -# endif -#endif -#ifndef HAVE_VSNPRINTF -# ifdef MSDOS - /* vsnprintf may exist on some MS-DOS compilers (DJGPP?), - but for now we just assume it doesn't. */ -# define NO_vsnprintf -# endif -# ifdef __TURBOC__ -# define NO_vsnprintf -# endif -# ifdef WIN32 - /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */ -# if !defined(vsnprintf) && !defined(NO_vsnprintf) -# if !defined(_MSC_VER) || ( defined(_MSC_VER) && _MSC_VER < 1500 ) -# define vsnprintf _vsnprintf -# endif -# endif -# endif -# ifdef __SASC -# define NO_vsnprintf -# endif -#endif -#ifdef VMS -# define NO_vsnprintf -#endif - -#if defined(pyr) +#if defined(pyr) || defined(Z_SOLO) # define NO_MEMCPY #endif #if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__) @@ -250,16 +209,16 @@ extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */ # define zmemzero(dest, len) memset(dest, 0, len) # endif #else - extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len)); - extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len)); - extern void zmemzero OF((Bytef* dest, uInt len)); + void ZLIB_INTERNAL zmemcpy OF((Bytef* dest, const Bytef* source, uInt len)); + int ZLIB_INTERNAL zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len)); + void ZLIB_INTERNAL zmemzero OF((Bytef* dest, uInt len)); #endif /* Diagnostic functions */ #ifdef DEBUG # include - extern int z_verbose; - extern void z_error OF((char *m)); + extern int ZLIB_INTERNAL z_verbose; + extern void ZLIB_INTERNAL z_error OF((char *m)); # define Assert(cond,msg) {if(!(cond)) z_error(msg);} # define Trace(x) {if (z_verbose>=0) fprintf x ;} # define Tracev(x) {if (z_verbose>0) fprintf x ;} @@ -275,13 +234,19 @@ extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */ # define Tracecv(c,x) #endif - -voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size)); -void zcfree OF((voidpf opaque, voidpf ptr)); +#ifndef Z_SOLO + voidpf ZLIB_INTERNAL zcalloc OF((voidpf opaque, unsigned items, + unsigned size)); + void ZLIB_INTERNAL zcfree OF((voidpf opaque, voidpf ptr)); +#endif #define ZALLOC(strm, items, size) \ (*((strm)->zalloc))((strm)->opaque, (items), (size)) #define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr)) #define TRY_FREE(s, p) {if (p) ZFREE(s, p);} +/* Reverse the bytes in a 32-bit value */ +#define ZSWAP32(q) ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \ + (((q) & 0xff00) << 8) + (((q) & 0xff) << 24)) + #endif /* ZUTIL_H */ diff --git a/bin/GameIndex.dbf b/bin/GameIndex.dbf index 9391966406..cb32a49e80 100644 --- a/bin/GameIndex.dbf +++ b/bin/GameIndex.dbf @@ -214,10 +214,10 @@ Name = Kiosk Demo Disc 2.02 Region = NTSC-U --------------------------------------------- Serial = SCUS-97128 -Name = Drakan - The Ancients' Gates +Name = Drakan - The Ancients' Gates // aka "Drakan 2" Region = NTSC-U Compat = 5 -EETimingHack = 1 //flickery textures +EETimingHack = 1 // flickery textures --------------------------------------------- Serial = SCUS-97129 Name = Okage - Shadow King @@ -349,7 +349,7 @@ Region = NTSC-U Compat = 5 --------------------------------------------- Serial = SCUS-97169 -Name = Drakan - The Ancients' Gates [Demo] +Name = Drakan - The Ancients' Gates [Demo] // aka "Drakan 2 [Demo]" Region = NTSC-U --------------------------------------------- Serial = SCUS-97170 @@ -840,7 +840,7 @@ Serial = SCUS-97328 Name = Gran Turismo 4 Region = NTSC-U Compat = 5 -eeClampMode = 3 // Text in races works +//eeClampMode = 3 // Text in races works vuClampMode = 2 // Text in GT mode works --------------------------------------------- Serial = SCUS-97329 @@ -1169,7 +1169,7 @@ Region = NTSC-U Serial = SCUS-97436 Name = Gran Turismo 4 [Online Public Beta] Region = NTSC-U -eeClampMode = 3 // Text in races works +//eeClampMode = 3 // Text in races works vuClampMode = 2 // Text in GT mode works --------------------------------------------- Serial = SCUS-97437 @@ -3670,7 +3670,7 @@ Name = Gravenville - Ghost Master Region = NTSC-U --------------------------------------------- Serial = SLUS-20467 -Name = Tomb Raider - The Angel of Darkness +Name = Tomb Raider - The Angel of Darkness // aka "TRAOD" Region = NTSC-U Compat = 5 OPHFlagHack = 1 @@ -3755,6 +3755,9 @@ Serial = SLUS-20484 Name = Devil May Cry 2 [Disc1of2] Region = NTSC-U Compat = 5 +[patches] + comment=Note that this disc has the same CRC as SLPM-65232, the NTSC-J disc. +[/patches] --------------------------------------------- Serial = SLUS-20485 Name = Dino Stalker @@ -5887,8 +5890,8 @@ Compat = 4 //patch=0,EE,003a9538,word,03e00008 //patch=0,EE,003a953c,word,00000000 - //patch=0,EE,003a9460,word,03e00008 - //patch=0,EE,003a9464,word,00000000 + patch=0,EE,003a9460,word,03e00008 + patch=0,EE,003a9464,word,00000000 [/patches] --------------------------------------------- @@ -5949,7 +5952,7 @@ Name = Samurai Showdown V Region = NTSC-U --------------------------------------------- Serial = SLUS-20973 -Name = Champions - Return to Arms +Name = Champions - Return to Arms // aka "Champions of Norrath 2" Region = NTSC-U Compat = 4 --------------------------------------------- @@ -9559,6 +9562,12 @@ Region = NTSC-U Compat = 5 VuClipFlagHack = 1 --------------------------------------------- +Serial = SLUS-21782B +Name = Shin Megami Tensei - Persona 4 +Region = NTSC-U +Compat = 5 +VuClipFlagHack = 1 +--------------------------------------------- Serial = SLUS-21783 Name = Space Chimps Region = NTSC-U @@ -10658,6 +10667,7 @@ Region = NTSC-U Serial = SLUS-29101 Name = Crash Twinsanity & Spyro - A Hero's Tail [Demo] Region = NTSC-U +XgKickHack = 1 //Fixes bad Geometry --------------------------------------------- Serial = SLUS-29104 Name = Galactic Wrestling - Featuring Ultimate Muscle [Demo] @@ -10708,7 +10718,7 @@ Name = Konami Preview Disc Region = NTSC-U --------------------------------------------- Serial = SLUS-29126 -Name = Champions - Return to Arms [Demo] +Name = Champions - Return to Arms [Demo] // aka "Champions of Norrath 2 [Demo]" Region = NTSC-U Compat = 4 --------------------------------------------- @@ -10908,7 +10918,7 @@ Region = NTSC-U Serial = PAPX-90512 Name = Gran Turismo 4 - Toyota Prius [Trial] Region = NTSC-J -eeClampMode = 3 // Text in races works +//eeClampMode = 3 // Text in races works vuClampMode = 2 // Text in GT mode works --------------------------------------------- Serial = PBPX-95503 @@ -10932,39 +10942,39 @@ Serial = PBPX-95524 Name = Gran Turismo 4 - Prologue Region = NTSC-Unk Compat = 5 -eeClampMode = 3 // Text in races works +//eeClampMode = 3 // Text in races works vuClampMode = 2 // Text in GT mode works -[patches = CA6243B9] +//[patches = CA6243B9] +// +// comment=patches by Nachbrenner - comment=patches by Nachbrenner - - //fix IPU DMA - patch=1,EE,00166814,word,00000000 - patch=1,EE,003a36b8,word,00000000 - patch=1,EE,003a36f4,word,00000000 - //Skip Videos - patch=1,EE,001e3718,word,03e00008 - patch=1,EE,001e371c,word,00000000 - -[/patches] +// //fix IPU DMA +// patch=1,EE,00166814,word,00000000 +// patch=1,EE,003a36b8,word,00000000 +// patch=1,EE,003a36f4,word,00000000 +// //Skip Videos +// patch=1,EE,001e3718,word,03e00008 +// patch=1,EE,001e371c,word,00000000 +// +//[/patches] --------------------------------------------- Serial = PCPX-96649 Name = Gran Turismo 4 [Demo] Region = NTSC-J Compat = 4 -eeClampMode = 3 // Text in races works +//eeClampMode = 3 // Text in races works vuClampMode = 2 // Text in GT mode works -[patches = E906EA37] - - comment=patches by mdr61 - - //Timelimit counter stop - patch=0,EE,002EF740,word,00000000 - //Pause counter stop - patch=0,EE,002C7394,word,00000000 - patch=0,EE,002F1F40,word,00000000 - -[/patches] +//[patches = E906EA37] +// +// comment=patches by mdr61 +// +// //Timelimit counter stop +// patch=0,EE,002EF740,word,00000000 +// //Pause counter stop +// patch=0,EE,002C7394,word,00000000 +// patch=0,EE,002F1F40,word,00000000 +// +//[/patches] --------------------------------------------- Serial = SCAJ-10001 Name = Makai Senki Disgaea @@ -11178,7 +11188,7 @@ Name = Chain Drive Region = NTSC-Unk --------------------------------------------- Serial = SCAJ-20044 -Name = Tomb Raider - The Angel of Darkness +Name = Tomb Raider - The Angel of Darkness // aka "TRAOD" Region = NTSC-Unk OPHFlagHack = 1 --------------------------------------------- @@ -11249,7 +11259,7 @@ Region = NTSC-Unk Serial = SCAJ-20066 Name = Gran Turismo 4 - Prologue Region = NTSC-Unk -eeClampMode = 3 // Text in races works +//eeClampMode = 3 // Text in races works vuClampMode = 2 // Text in GT mode works --------------------------------------------- Serial = SCAJ-20067 @@ -11619,6 +11629,7 @@ Region = NTSC-Unk Serial = SCAJ-20161 Name = Siren 2 Region = NTSC-J +XgKickHack = 1 //SPS. --------------------------------------------- Serial = SCAJ-20162 Name = Rogue Galaxy @@ -11643,6 +11654,7 @@ Region = NTSC-Unk Serial = SCAJ-20167 Name = Siren 2 Region = NTSC-Ch-J +XgKickHack = 1 //SPS. --------------------------------------------- Serial = SCAJ-20168 Name = Rule of Rose @@ -11825,28 +11837,28 @@ Region = NTSC-Unk Serial = SCAJ-30006 Name = Gran Turismo 4 Region = NTSC-Unk -eeClampMode = 3 // Text in races works +//eeClampMode = 3 // Text in races works vuClampMode = 2 // Text in GT mode works --------------------------------------------- Serial = SCAJ-30007 Name = Gran Turismo 4 Region = NTSC-Unk Compat = 5 -eeClampMode = 3 // Text in races works +//eeClampMode = 3 // Text in races works vuClampMode = 2 // Text in GT mode works -[patches = 7ABDBB5E] - - comment=patches by nachbrenner - - //skip Videos - patch=1,EE,00100D84,word,24100001 - -[/patches] +//[patches = 7ABDBB5E] +// +// comment=patches by nachbrenner +// +// //skip Videos +// patch=1,EE,00100D84,word,24100001 +// +//[/patches] --------------------------------------------- Serial = SCAJ-30008 Name = Gran Turismo 4 [PlayStation 2 The Best] Region = NTSC-Unk -eeClampMode = 3 // Text in races works +//eeClampMode = 3 // Text in races works vuClampMode = 2 // Text in GT mode works --------------------------------------------- Serial = SCAJ-30010 @@ -11923,7 +11935,7 @@ VIF1StallHack = 1 //HUD Serial = SCKA-20022 Name = Gran Turismo 4 Prologue Region = NTSC-K -eeClampMode = 3 // Text in races works +//eeClampMode = 3 // Text in races works vuClampMode = 2 // Text in GT mode works --------------------------------------------- Serial = SCKA-20023 @@ -12075,6 +12087,7 @@ Region = NTSC-K Serial = SCKA-20069 Name = Siren 2 Region = NTSC-K +XgKickHack = 1 //SPS. --------------------------------------------- Serial = SCKA-20070 Name = Ace Combat Zero - The Belkan War @@ -12172,7 +12185,7 @@ Region = NTSC-K Serial = SCKA-30001 Name = Gran Turismo 4 Region = NTSC-K -eeClampMode = 3 // Text in races works +//eeClampMode = 3 // Text in races works vuClampMode = 2 // Text in GT mode works --------------------------------------------- Serial = SCKA-30002 @@ -12584,7 +12597,7 @@ Region = NTSC-J Serial = SCPS-15055 Name = Gran Turismo 4 - Prologue Region = NTSC-J -eeClampMode = 3 // Text in races works +//eeClampMode = 3 // Text in races works vuClampMode = 2 // Text in GT mode works --------------------------------------------- Serial = SCPS-15056 @@ -12797,6 +12810,7 @@ Serial = SCPS-15106 Name = Siren 2 Region = NTSC-J Compat = 4 +XgKickHack = 1 //SPS. --------------------------------------------- Serial = SCPS-15107 Name = Gunparade Orchestra - Midori no Shou [Limited Edition] @@ -12863,7 +12877,7 @@ Serial = SCPS-17001 Name = Gran Turismo 4 Region = NTSC-J Compat = 5 -eeClampMode = 3 // Text in races works +//eeClampMode = 3 // Text in races works vuClampMode = 2 // Text in GT mode works --------------------------------------------- Serial = SCPS-17002 @@ -12991,7 +13005,7 @@ Region = NTSC-J Serial = SCPS-19252 Name = Gran Turismo 4 [PlayStation 2 The Best] Region = NTSC-J -eeClampMode = 3 // Text in races works +//eeClampMode = 3 // Text in races works vuClampMode = 2 // Text in GT mode works --------------------------------------------- Serial = SCPS-19253 @@ -13013,7 +13027,7 @@ Region = NTSC-J Serial = SCPS-19304 Name = Gran Turismo 4 - Prologue [PlayStation 2 The Best] Region = NTSC-J -eeClampMode = 3 // Text in races works +//eeClampMode = 3 // Text in races works vuClampMode = 2 // Text in GT mode works --------------------------------------------- Serial = SCPS-19305 @@ -13099,6 +13113,7 @@ Region = NTSC-J Serial = SCPS-19326 Name = Siren 2 [PlayStation 2 The Best] Region = NTSC-J +XgKickHack = 1 //SPS. --------------------------------------------- Serial = SCPS-19327 Name = Ape Escape 3 [PlayStation 2 the Best - Reprint] @@ -16447,7 +16462,7 @@ Serial = SLPM-62623 Name = Elemental Gerad Region = NTSC-J Compat = 5 -XgKickHack = 1 +XgKickHack = 1 //Fixes chocolate coloured characters --------------------------------------------- Serial = SLPM-62624 Name = Indoor Helicopter Adventure 2 @@ -16997,10 +17012,6 @@ Name = Guilty Gear X Plus "By Your Side" Region = NTSC-K Compat = 5 --------------------------------------------- -Serial = SLPM-64549 -Name = Shikigame no Shiro -Region = NTSC-K ---------------------------------------------- Serial = SLPM-65001 Name = Kessen Region = NTSC-J @@ -17701,6 +17712,9 @@ Serial = SLPM-65232 Name = Devil May Cry 2 [Dante Disc] Region = NTSC-J Compat = 5 +[patches] + comment=Note that this disc has the same CRC as SLUS-20484, the NTSC-U disc. +[/patches] --------------------------------------------- Serial = SLPM-65233 Name = Devil May Cry 2 [Lucia Disc] @@ -19908,11 +19922,6 @@ Serial = SLPM-65844 Name = Air [Best] Region = NTSC-J --------------------------------------------- -Serial = SLPM-65845 -Name = Baldur's Gate - Dark Alliance II -Region = NTSC-J -Compat = 4 ---------------------------------------------- Serial = SLPM-65846 Name = Lord of the Rings, The - Uchitsu Kuni Daisanki Region = NTSC-J @@ -26568,7 +26577,7 @@ Name = True Love Story - Summer Days and Yet Region = NTSC-J --------------------------------------------- Serial = SLPS-25246 -Name = Tomb Raider - The Angel of Darkness +Name = Tomb Raider - The Angel of Darkness // aka "TRAOD" Region = NTSC-J OPHFlagHack = 1 --------------------------------------------- @@ -29397,7 +29406,7 @@ Region = NTSC-J Serial = TCPS-10111 Name = Eremental Gerad Region = NTSC-J -XgKickHack = 1 +XgKickHack = 1 //Fixes chocolate coloured characters --------------------------------------------- Serial = TCPS-10113 Name = Mushihime-sama @@ -29571,9 +29580,19 @@ Region = PAL-E Compat = 5 --------------------------------------------- Serial = SCES-50006 -Name = Drakan - The Ancients' Gates -Region = PAL-Unk -EETimingHack = 1 //flickery textures +Name = Drakan - The Ancients' Gates // aka "Drakan 2" +Region = PAL-M5 +Compat = 5 +EETimingHack = 1 // flickery textures +[patches] + comment=This gamedisc supports multiple languages. + comment=Language selection is done through the BIOS configuration. + comment=Implementation requires full boot - "Boot CDVD (full)". + + patch=1,EE,001C2274,word,3C013F7F // 3C013F80 + // Fix by pgert that reduces displaycrap which arises with Resolution Scaling + // around the Health & Mana bars. Improvement someone? +[/patches] --------------------------------------------- Serial = SCES-50009 Name = Wild Wild Racing @@ -30105,7 +30124,7 @@ Serial = SCES-51719 Name = Gran Turismo 4 Region = PAL-Unk Compat = 5 -eeClampMode = 3 // Text in races works +//eeClampMode = 3 // Text in races works vuClampMode = 2 // Text in GT mode works --------------------------------------------- Serial = SCES-51725 @@ -30288,7 +30307,7 @@ Serial = SCES-52438 Name = Gran Turismo 4 - Prologue Region = PAL-Unk Compat = 5 -eeClampMode = 3 // Text in races works +//eeClampMode = 3 // Text in races works vuClampMode = 2 // Text in GT mode works --------------------------------------------- Serial = SCES-52456 @@ -30336,8 +30355,17 @@ Region = PAL-Unk --------------------------------------------- Serial = SCES-52677 Name = Network Access Disc & Hardware - Online Arena -Region = PAL-Unk -Compat = 4 +Region = PAL-Unk // Portuguese * Dutch * Italian * German * Spanish * French * English * Japanese +Compat = 5 +[patches] + comment=- This gamedisc supports multiple languages and widescreen. + comment=- Language & widescreen selection is done through the BIOS configuration. + comment=- Implementation requires full boot - "Boot CDVD (full)". + comment=- + comment=- Using GSdx, this gamedisc crashes in gamemenu with SW-mode, + comment=- and have no 3D display with HW-mode. + comment=- Playable by toggling between HW-mode (in menu) and SW-mode (in game). +[/patches] --------------------------------------------- Serial = SCES-52748 Name = EyeToy - Play 2 @@ -30468,7 +30496,7 @@ Serial = SCES-53247 Name = WRC - World Rally Championship - Rally Evolved Region = PAL-Unk Compat = 4 -XgKickHack = 1 //Most of the ingame SPS gets fixed with it. +XgKickHack = 1 //SPS. [patches = cbbc2e7f] comment=patches by Nachbrenner //fix delay slot violation @@ -30639,6 +30667,7 @@ Serial = SCES-53851 Name = Forbidden Siren 2 Region = PAL-M5 Compat = 4 +XgKickHack = 1 //SPS. --------------------------------------------- Serial = SCES-53879 Name = Buzz! The Big Quiz @@ -31145,14 +31174,6 @@ Serial = SLED-53745 Name = Total Overdose [Demo] Region = PAL-M5 --------------------------------------------- -Serial = SLED-53745 -Name = Total Overdose [Demo] -Region = PAL-M5 ---------------------------------------------- -Serial = SLED-53745 -Name = Total Overdose [Demo] -Region = PAL-M5 ---------------------------------------------- Serial = SLED-53845 Name = Matrix - Path of Neo [Demo] Region = PAL-E @@ -31697,8 +31718,13 @@ Compat = 4 --------------------------------------------- Serial = SLES-50211 Name = Gauntlet - Dark Legacy -Region = PAL-Unk +Region = PAL-Unk // English * French * German Compat = 5 +[patches] + comment=- This gamedisc supports multiple languages. + comment=- Language selection is done through the BIOS configuration. + comment=- Implementation requires full boot - "Boot CDVD (full)". +[/patches] --------------------------------------------- Serial = SLES-50212 Name = Paris-Dakar Rally @@ -32926,6 +32952,12 @@ Serial = SLES-50821 Name = Project Zero Region = PAL-M5 Compat = 5 +[patches] + comment=- This gamedisc only lets you choose language once, + comment=- whereafter it stores that setting in the memcard. + comment=- To change the language you actually have to erase + comment=- the memcard content for the game. +[/patches] --------------------------------------------- Serial = SLES-50822 Name = Shadow Hearts @@ -33801,10 +33833,16 @@ Region = PAL-Unk Compat = 5 --------------------------------------------- Serial = SLES-51227 -Name = Tomb Raider - Angel of Darkness +Name = Tomb Raider - Angel of Darkness // aka "TRAOD" Region = PAL-Unk Compat = 5 OPHFlagHack = 1 +[patches] + comment=- This gamedisc supports multiple languages and widescreen. + comment=- Language & widescreen selection is done through the BIOS configuration. + comment=- Implementation requires full boot - "Boot CDVD (full)". + comment=- Full boot is recommended anyway for this gamedisc to avoid textproblems. +[/patches] --------------------------------------------- Serial = SLES-51229 Name = Virtua Cop - Elite Edition @@ -35655,6 +35693,12 @@ Compat = 3 Serial = SLES-52149 Name = Tom Clancy's Splinter Cell - Pandora Tomorrow Region = PAL-Unk +Compat = 5 +[patches] + comment=- This gamedisc supports multiple languages. + comment=- Language selection is done through the BIOS configuration. + comment=- Implementation requires full boot - "Boot CDVD (full)". +[/patches] --------------------------------------------- Serial = SLES-52150 Name = Legacy of Kain - Defiance @@ -35720,6 +35764,11 @@ Name = Baldur's Gate - Dark Alliance 2 Region = PAL-Unk Compat = 4 --------------------------------------------- +Serial = SLPM-65845 +Name = Baldur's Gate - Dark Alliance II +Region = NTSC-J +Compat = 4 +--------------------------------------------- Serial = SLES-52190 Name = RPM Tuning Region = PAL-Unk @@ -35849,14 +35898,17 @@ Compat = 4 Serial = SLES-52278 Name = Mafia Region = PAL-Unk +EETimingHack = 1 --------------------------------------------- Serial = SLES-52279 Name = Mafia Region = PAL-Unk +EETimingHack = 1 --------------------------------------------- Serial = SLES-52280 Name = Mafia Region = PAL-Unk +EETimingHack = 1 --------------------------------------------- Serial = SLES-52282 Name = Mafia @@ -35949,7 +36001,7 @@ Region = PAL-Unk --------------------------------------------- Serial = SLES-52325 Name = Champions of Norrath - Realms of EverQuest -Region = PAL-Unk +Region = PAL-Unk // English * French * German --------------------------------------------- Serial = SLES-52326 Name = Spawn - Armageddon @@ -36305,10 +36357,10 @@ Compat = 4 //comment=Patches By Nachbrenner //fix IPU busy! ingame - //patch=0,EE,003a9a88,word,03e00008 - //patch=0,EE,003a9a8c,word,00000000 - //patch=0,EE,003a9b60,word,03e00008 - //patch=0,EE,003a9b64,word,00000000 + patch=0,EE,003a9a88,word,03e00008 + patch=0,EE,003a9a8c,word,00000000 + patch=0,EE,003a9b60,word,03e00008 + patch=0,EE,003a9b64,word,00000000 [/patches] --------------------------------------------- @@ -36472,6 +36524,7 @@ Serial = SLES-52568 Name = Crash Twinsanity Region = PAL-Unk Compat = 5 +XgKickHack = 1 //Fixes bad Geometry --------------------------------------------- Serial = SLES-52569 Name = Spyro - A Hero's Tail @@ -37525,8 +37578,13 @@ Region = PAL-Unk --------------------------------------------- Serial = SLES-53007 Name = Tom Clancy's Splinter Cell - Chaos Theory -Region = PAL-M5 +Region = PAL-Unk Compat = 5 +[patches] + comment=- This gamedisc supports multiple languages. + comment=- Language selection is done through the BIOS configuration. + comment=- Implementation requires full boot - "Boot CDVD (full)". +[/patches] --------------------------------------------- Serial = SLES-53011 Name = Gallop Racer 2 @@ -37632,7 +37690,7 @@ Compat = 5 eeRoundMode = 0 --------------------------------------------- Serial = SLES-53039 -Name = Champions - Return to Arms +Name = Champions - Return to Arms // aka "Champions of Norrath 2" Region = PAL-Unk Compat = 4 --------------------------------------------- @@ -37910,7 +37968,12 @@ Region = PAL-Unk --------------------------------------------- Serial = SLES-53154 Name = Bard's Tale -Region = PAL-Unk +Region = PAL-Unk // English * Spanish * Italian * French * German * Japanese * Korean * Chinese +[patches] + comment=- This gamedisc supports multiple languages. + comment=- Language selection is done through the BIOS configuration. + comment=- Implementation requires full boot - "Boot CDVD (full)". +[/patches] --------------------------------------------- Serial = SLES-53155 Name = Star Wars - Episode III - Revenge of the Sith @@ -38887,7 +38950,13 @@ Region = PAL-E --------------------------------------------- Serial = SLES-53667 Name = Gauntlet - Seven Sorrows -Region = PAL-Unk +Region = PAL-M5 +Compat = 5 +[patches] + comment=- This gamedisc supports multiple languages. + comment=- Language selection is done through the BIOS configuration. + comment=- Implementation requires full boot - "Boot CDVD (full)". +[/patches] --------------------------------------------- Serial = SLES-53668 Name = Micro Machines v4 @@ -39224,6 +39293,12 @@ Compat = 5 Serial = SLES-53826 Name = Tom Clancy's Splinter Cell - Double Agent Region = PAL-Unk +Compat = 5 +[patches] + comment=- This gamedisc supports multiple languages. + comment=- Language selection is done through the BIOS configuration. + comment=- Implementation requires full boot - "Boot CDVD (full)". +[/patches] --------------------------------------------- Serial = SLES-53827 Name = Tom Clancy's Splinter Cell - Double Agent @@ -39308,7 +39383,7 @@ Serial = SLES-53866 Name = Over the Hedge Region = PAL-Unk --------------------------------------------- -Serial = SLES-53866 +Serial = SLES-53867 Name = Ski Alpin 2006 Region = PAL-Unk vuClampMode = 2 @@ -39385,9 +39460,14 @@ Name = 50cent - Bulletproof Region = PAL-Unk --------------------------------------------- Serial = SLES-53908 -Name = Tomb Raider - Legends -Region = PAL-Unk +Name = Tomb Raider - Legend +Region = PAL-Unk // English * French * German * Italian * Spanish * Japanese * Portugese * Polish Compat = 5 +[patches] + comment=- This gamedisc supports multiple languages. + comment=- Language selection is done through the BIOS configuration. + comment=- Implementation requires full boot - "Boot CDVD (full)". +[/patches] --------------------------------------------- Serial = SLES-53909 Name = Full Spectrum Warrior - Ten Hammers @@ -39957,17 +40037,17 @@ Region = PAL-R --------------------------------------------- Serial = SLES-54185 Name = Dirge of Cerberus - Final Fantasy VII -Region = PAL-E +Region = PAL-Unk Compat = 5 [patches = 33F7D21A] - - //comment=patches by nachbrenner - - //override sceScfGetLanguage - //patch=0,EE,002486d8,word,24020000 //japanese - //patch=0,EE,002486d8,word,24020001 //english - //patch=0,EE,002486d8,word,24020004 //german - + comment=- This gamedisc supports multiple languages. + comment=- Language selection is done through the BIOS configuration. + comment=- Implementation requires full boot - "Boot CDVD (full)". + + // Override sceScfGetLanguage patches by nachbrenner: + // patch=0,EE,002486d8,word,24020000 // japanese + // patch=0,EE,002486d8,word,24020001 // english + // patch=0,EE,002486d8,word,24020004 // german [/patches] --------------------------------------------- Serial = SLES-54186 @@ -40861,7 +40941,13 @@ Region = PAL-M11 --------------------------------------------- Serial = SLES-54674 Name = Lara Croft Tomb Raider - Anniversary -Region = PAL-M5 +Region = PAL-Unk // English * French * German * Italian * Spanish * Japanese * Portugese * Polish * Russian * Czech +Compat = 5 +[patches] + comment=- This gamedisc supports multiple languages. + comment=- Language selection is done through the BIOS configuration. + comment=- Implementation requires full boot - "Boot CDVD (full)". +[/patches] --------------------------------------------- Serial = SLES-54675 Name = Street Warrior @@ -41694,8 +41780,13 @@ Region = PAL-M5 --------------------------------------------- Serial = SLES-55442 Name = Tomb Raider Underworld -Region = PAL-M5 +Region = PAL-Unk // English * French * German * Italian * Spanish * Japanese * Portugese * Polish * Russian * Czech * Dutch Compat = 5 +[patches] + comment=- This gamedisc supports multiple languages. + comment=- Language selection is done through the BIOS configuration. + comment=- Implementation requires full boot - "Boot CDVD (full)". +[/patches] --------------------------------------------- Serial = SLES-55443 Name = Mana Khemia - Alchemists of Al-Revis diff --git a/bin/launch_pcsx2_linux.sh b/bin/launch_pcsx2_linux.sh index f18241ea83..6a3681dbbd 100755 --- a/bin/launch_pcsx2_linux.sh +++ b/bin/launch_pcsx2_linux.sh @@ -72,9 +72,15 @@ then fi # Launch PCSX2 -if [ -x pcsx2 ] +if [ -x "pcsx2" ] then ./pcsx2 $@ +elif [ -x "pcsx2-dev" ] +then + ./pcsx2-dev $@ +elif [ -x "pcsx2-dbg" ] +then + ./pcsx2-dbg $@ else echo "Error PCSX2 not found" echo "Maybe the script was directly 'called'" diff --git a/cmake/FindAio.cmake b/cmake/FindAio.cmake index 9aad0020a7..c3e8f69935 100644 --- a/cmake/FindAio.cmake +++ b/cmake/FindAio.cmake @@ -9,8 +9,6 @@ if(AIO_INCLUDE_DIR AND AIO_LIBRARIES) set(AIO_FIND_QUIETLY TRUE) endif(AIO_INCLUDE_DIR AND AIO_LIBRARIES) -INCLUDE(CheckCXXSymbolExists) - # include dir find_path(AIO_INCLUDE_DIR libaio.h) diff --git a/cmake/SearchForStuff.cmake b/cmake/SearchForStuff.cmake index e96395fee4..a39d1858f2 100644 --- a/cmake/SearchForStuff.cmake +++ b/cmake/SearchForStuff.cmake @@ -40,9 +40,9 @@ find_package(Subversion) # Warning do not put any double-quote for the argument... # set(wxWidgets_CONFIG_OPTIONS --unicode=yes --debug=yes) # In case someone want to debug inside wx # -# Fedora uses an extra non-standard option ... +# Fedora uses an extra non-standard option ... Arch must be the first option. if(Fedora) - set(wxWidgets_CONFIG_OPTIONS --unicode=yes --arch i686) + set(wxWidgets_CONFIG_OPTIONS --arch i686 --unicode=yes) else() set(wxWidgets_CONFIG_OPTIONS --unicode=yes) endif() diff --git a/cmake/SelectPcsx2Plugins.cmake b/cmake/SelectPcsx2Plugins.cmake index a097c60c9e..101c49356a 100644 --- a/cmake/SelectPcsx2Plugins.cmake +++ b/cmake/SelectPcsx2Plugins.cmake @@ -1,7 +1,7 @@ #------------------------------------------------------------------------------- # Dependency message print #------------------------------------------------------------------------------- -set(msg_dep_common_libs "check these libraries -> wxWidgets (>=2.8.10), sparsehash (>=1.5)") +set(msg_dep_common_libs "check these libraries -> wxWidgets (>=2.8.10), sparsehash (>=1.5), aio") set(msg_dep_pcsx2 "check these libraries -> wxWidgets (>=2.8.10), gtk2 (>=2.16), zlib (>=1.2.4), pcsx2 common libs") set(msg_dep_cdvdiso "check these libraries -> bzip2 (>=1.0.5), gtk2 (>=2.16)") set(msg_dep_zerogs "check these libraries -> glew (>=1.6), opengl, X11, nvidia-cg-toolkit (>=2.1)") diff --git a/common/build/Utilities/utilities_vs11.vcxproj b/common/build/Utilities/utilities_vs11.vcxproj index 1a08e88d8f..81d2555c18 100644 --- a/common/build/Utilities/utilities_vs11.vcxproj +++ b/common/build/Utilities/utilities_vs11.vcxproj @@ -192,7 +192,7 @@ - + {48ad7e0a-25b1-4974-a1e3-03f8c438d34f} false diff --git a/common/include/PS2Eext.h b/common/include/PS2Eext.h index 6a6c3dcce2..e6d6fedcb5 100644 --- a/common/include/PS2Eext.h +++ b/common/include/PS2Eext.h @@ -144,20 +144,18 @@ struct PluginConf int ReadInt(const std::string& item, int defval) { int value = defval; - int err = 0; std::string buf = item + " = %d\n"; - if (ConfFile) err=fscanf(ConfFile, buf.c_str(), &value); + if (ConfFile) fscanf(ConfFile, buf.c_str(), &value); return value; } void WriteInt(std::string item, int value) { - int err = 0; std::string buf = item + " = %d\n"; - if (ConfFile) err=fprintf(ConfFile, buf.c_str(), value); + if (ConfFile) fprintf(ConfFile, buf.c_str(), value); } }; diff --git a/common/include/PluginCallbacks.h b/common/include/PluginCallbacks.h index ccb3159b3a..c2049e376b 100644 --- a/common/include/PluginCallbacks.h +++ b/common/include/PluginCallbacks.h @@ -1058,6 +1058,14 @@ typedef struct _PS2E_ComponentAPI_Mcd // void (PS2E_CALLBACK* McdGetSizeInfo)( PS2E_THISPTR thisptr, uint port, uint slot, PS2E_McdSizeInfo* outways ); + // McdIsPSX + // Checks if the memorycard is a PSX one from the Mcd provider. + // + // Returns: + // False: PS2, True: PSX + // + bool (PS2E_CALLBACK* McdIsPSX)( PS2E_THISPTR thisptr, uint port, uint slot ); + // McdRead // Requests that a block of data be loaded from the memorycard into the specified dest // buffer (which is allocated by the caller). Bytes read should match the requested diff --git a/debian-unstable-upstream/create_pcsx2_tarball_from_svn_repository.sh b/debian-unstable-upstream/create_pcsx2_tarball_from_svn_repository.sh index 6f81365ebf..3f8aab00cf 100755 --- a/debian-unstable-upstream/create_pcsx2_tarball_from_svn_repository.sh +++ b/debian-unstable-upstream/create_pcsx2_tarball_from_svn_repository.sh @@ -136,6 +136,8 @@ echo "Copy the subversion repository to a temporary directory" rm -fr $NEW_DIR cp -r $ROOT_DIR $NEW_DIR +echo "Remove .svn directories" +find $NEW_DIR -name ".svn" -type d -exec rm -fr {} \; 2> /dev/null echo "Remove windows files (useless & potential copyright issues)" # => pcsx2/windows # Copyright header must be updated diff --git a/linux_various/glsl2h.pl b/linux_various/glsl2h.pl new file mode 100755 index 0000000000..b5d96c805f --- /dev/null +++ b/linux_various/glsl2h.pl @@ -0,0 +1,61 @@ +#!/usr/bin/perl + +use strict; +use warnings; + +my @res = qw/convert interlace merge shadeboost tfx/; +my $path = "plugins/GSdx/res"; + +foreach my $r (@res) { + glsl2h($path, $r); +} + +sub glsl2h { + my $path = shift; + my $glsl = shift; + + open(my $GLSL, "<$path/${glsl}.glsl"); + open(my $H, ">$path/${glsl}.h"); + + my $header = <)) { + chomp $line; + $line =~ s/%/\\%/g; + $line =~ s/"/\\"/g; + print $H "\t\"$line\\n\"\n"; + } + print $H "\t;\n"; +} diff --git a/pcsx2/CDVD/CDVD.cpp b/pcsx2/CDVD/CDVD.cpp index f0b531d42a..3647c6733b 100644 --- a/pcsx2/CDVD/CDVD.cpp +++ b/pcsx2/CDVD/CDVD.cpp @@ -1209,12 +1209,12 @@ static void cdvdWrite04(u8 rt) { // NCOMMAND default: cdvd.ReadMode = CDVD_MODE_2048; cdvd.BlockSize = 2048; break; } - CDVD_LOG( "CdRead > startSector=%d, nSectors=%d, RetryCnt=%x, Speed=%x(%x), ReadMode=%x(%x) (1074=%x)", - cdvd.Sector, cdvd.nSectors, cdvd.RetryCnt, cdvd.Speed, cdvd.Param[9], cdvd.ReadMode, cdvd.Param[10], psxHu32(0x1074)); + CDVD_LOG( "CdRead > startSector=%d, seekTo=%d, nSectors=%d, RetryCnt=%x, Speed=%x(%x), ReadMode=%x(%x) (1074=%x)", + cdvd.Sector, cdvd.SeekToSector, cdvd.nSectors, cdvd.RetryCnt, cdvd.Speed, cdvd.Param[9], cdvd.ReadMode, cdvd.Param[10], psxHu32(0x1074)); if( EmuConfig.CdvdVerboseReads ) Console.WriteLn( Color_Gray, L"CdRead: Reading Sector %d(%d Blocks of Size %d) at Speed=%dx", - cdvd.Sector, cdvd.nSectors,cdvd.BlockSize,cdvd.Speed); + cdvd.SeekToSector, cdvd.nSectors,cdvd.BlockSize,cdvd.Speed); cdvd.ReadTime = cdvdBlockReadTime( MODE_CDROM ); CDVDREAD_INT( cdvdStartSeek( cdvd.SeekToSector,MODE_CDROM ) ); @@ -1293,12 +1293,12 @@ static void cdvdWrite04(u8 rt) { // NCOMMAND cdvd.ReadMode = CDVD_MODE_2048; cdvd.BlockSize = 2064; // Why oh why was it 2064 - CDVD_LOG( "DvdRead > startSector=%d, nSectors=%d, RetryCnt=%x, Speed=%x(%x), ReadMode=%x(%x) (1074=%x)", - cdvd.Sector, cdvd.nSectors, cdvd.RetryCnt, cdvd.Speed, cdvd.Param[9], cdvd.ReadMode, cdvd.Param[10], psxHu32(0x1074)); + CDVD_LOG( "DvdRead > startSector=%d, seekTo=%d nSectors=%d, RetryCnt=%x, Speed=%x(%x), ReadMode=%x(%x) (1074=%x)", + cdvd.Sector, cdvd.SeekToSector, cdvd.nSectors, cdvd.RetryCnt, cdvd.Speed, cdvd.Param[9], cdvd.ReadMode, cdvd.Param[10], psxHu32(0x1074)); if( EmuConfig.CdvdVerboseReads ) Console.WriteLn( Color_Gray, L"DvdRead: Reading Sector %d(%d Blocks of Size %d) at Speed=%dx", - cdvd.Sector, cdvd.nSectors,cdvd.BlockSize,cdvd.Speed); + cdvd.SeekToSector, cdvd.nSectors,cdvd.BlockSize,cdvd.Speed); cdvd.ReadTime = cdvdBlockReadTime( MODE_DVDROM ); CDVDREAD_INT( cdvdStartSeek( cdvd.SeekToSector, MODE_DVDROM ) ); diff --git a/pcsx2/CDVD/CDVDaccess.cpp b/pcsx2/CDVD/CDVDaccess.cpp index cf71955a22..1352794ab9 100644 --- a/pcsx2/CDVD/CDVDaccess.cpp +++ b/pcsx2/CDVD/CDVDaccess.cpp @@ -113,6 +113,9 @@ static int CheckDiskTypeFS(int baseType) { } +#ifdef PCSX2_DEVBUILD + return CDVD_TYPE_PS2DVD; // need this hack for some homebrew (SMS) +#endif return CDVD_TYPE_ILLEGAL; // << Only for discs which aren't ps2 at all. } @@ -145,7 +148,11 @@ static int FindDiskType(int mType) { //const cdVolDesc& volDesc = (cdVolDesc&)bleh; //if(volDesc.rootToc.tocSize == 2048) - if(*(u16*)(bleh+166) == 2048) + + //Horrible hack! in CD images position 166 and 171 have block size but not DVD's + //It's not always 2048 however (can be 4096) + //Test Impossible Mission if thia is changed. + if(*(u16*)(bleh+166) == *(u16*)(bleh+171)) iCDType = CDVD_TYPE_DETCTCD; else iCDType = CDVD_TYPE_DETCTDVDS; diff --git a/pcsx2/FiFo.cpp b/pcsx2/FiFo.cpp index a4d57b0032..5f0317ff29 100644 --- a/pcsx2/FiFo.cpp +++ b/pcsx2/FiFo.cpp @@ -109,6 +109,15 @@ void __fastcall WriteFIFO_VIF1(const mem128_t *value) } else vif1Regs.stat.VPS = VPS_IDLE; + if( gifRegs.stat.APATH == 2 && gifUnit.gifPath[1].isDone()) + { + gifRegs.stat.APATH = 0; + gifRegs.stat.OPH = 0; + vif1Regs.stat.VGW = false; //Let vif continue if it's stuck on a flush + + if(gifUnit.checkPaths(1,0,1)) gifUnit.Execute(false, true); + } + pxAssertDev( ret, "vif stall code not implemented" ); } @@ -119,4 +128,16 @@ void __fastcall WriteFIFO_GIF(const mem128_t *value) if(gifUnit.gifPath[GIF_PATH_3].state == GIF_PATH_WAIT) gifUnit.gifPath[GIF_PATH_3].state = GIF_PATH_IDLE; + + if( gifRegs.stat.APATH == 3 ) + { + gifRegs.stat.APATH = 0; + gifRegs.stat.OPH = 0; + + if(gifUnit.gifPath[GIF_PATH_3].state == GIF_PATH_IDLE || gifUnit.gifPath[GIF_PATH_3].state == GIF_PATH_WAIT) + { + if(gifUnit.checkPaths(1,1,0)) gifUnit.Execute(false, true); + } + + } } diff --git a/pcsx2/GS.cpp b/pcsx2/GS.cpp index 2731da3301..82960d2c8e 100644 --- a/pcsx2/GS.cpp +++ b/pcsx2/GS.cpp @@ -110,7 +110,7 @@ static __fi void gsCSRwrite( const tGS_CSR& csr ) } else CSRreg.SIGNAL = false; gifUnit.gsSIGNAL.queued = false; - gifUnit.Execute(false); // Resume paused transfers + gifUnit.Execute(false, true); // Resume paused transfers } if(csr.FINISH) CSRreg.FINISH = false; diff --git a/pcsx2/Gif.cpp b/pcsx2/Gif.cpp index 3ede5edf57..5d7c26bfae 100644 --- a/pcsx2/Gif.cpp +++ b/pcsx2/Gif.cpp @@ -50,7 +50,17 @@ void incGifChAddr(u32 qwc) { __fi void gifInterrupt() { GIF_LOG("gifInterrupt caught!"); - //Required for Path3 Masking timing! + if( gifRegs.stat.APATH == 3 ) + { + gifRegs.stat.APATH = 0; + gifRegs.stat.OPH = 0; + if(gifUnit.gifPath[GIF_PATH_3].state == GIF_PATH_IDLE || gifUnit.gifPath[GIF_PATH_3].state == GIF_PATH_WAIT) + { + if(gifUnit.checkPaths(1,1,0)) gifUnit.Execute(false, true); + } + + } + //Required for Path3 Masking timing! if(gifUnit.gifPath[GIF_PATH_3].state == GIF_PATH_WAIT) { gifUnit.gifPath[GIF_PATH_3].state = GIF_PATH_IDLE; @@ -102,7 +112,7 @@ __fi void gifInterrupt() } static u32 WRITERING_DMA(u32 *pMem, u32 qwc) { - //qwc = min(qwc, 1024u); + if(gifRegs.stat.IMT) qwc = std::min(qwc, 1024u); uint size = gifUnit.TransferGSPacketData(GIF_TRANS_DMA, (u8*)pMem, qwc*16) / 16; incGifChAddr(size); return size; @@ -350,7 +360,7 @@ static __fi bool mfifoGIFchain() if (gifch.qwc == 0) return true; if (gifch.madr >= dmacRegs.rbor.ADDR && - gifch.madr <=(dmacRegs.rbor.ADDR + dmacRegs.rbsr.RMSK + 16)) + gifch.madr <= (dmacRegs.rbor.ADDR + dmacRegs.rbsr.RMSK + 16)) { bool ret = true; // if(gifch.madr == (dmacRegs.rbor.ADDR + dmacRegs.rbsr.RMSK + 16)) DevCon.Warning("Edge GIF"); @@ -380,6 +390,32 @@ static u32 qwctag(u32 mask) { return (dmacRegs.rbor.ADDR + (mask & dmacRegs.rbsr.RMSK)); } +void mfifoGifMaskMem(int id) +{ + switch (id) { + //These five transfer data following the tag, need to check its within the buffer (Front Mission 4) + case TAG_CNT: + case TAG_NEXT: + case TAG_CALL: + case TAG_RET: + case TAG_END: + if(gifch.madr < dmacRegs.rbor.ADDR) //probably not needed but we will check anyway. + { + //DevCon.Warning("GIF MFIFO MADR below bottom of ring buffer, wrapping GIF MADR = %x Ring Bottom %x", gifch.madr, dmacRegs.rbor.ADDR); + gifch.madr = qwctag(gifch.madr); + } + if(gifch.madr > (dmacRegs.rbor.ADDR + dmacRegs.rbsr.RMSK)) //Usual scenario is the tag is near the end (Front Mission 4) + { + //DevCon.Warning("GIF MFIFO MADR outside top of ring buffer, wrapping GIF MADR = %x Ring Top %x", gifch.madr, (dmacRegs.rbor.ADDR + dmacRegs.rbsr.RMSK)+16); + gifch.madr = qwctag(gifch.madr); + } + break; + default: + //Do nothing as the MADR could be outside + break; + } +} + void mfifoGIFtransfer(int qwc) { tDMA_TAG *ptag; @@ -416,6 +452,8 @@ void mfifoGIFtransfer(int qwc) gspath3done = hwDmacSrcChainWithStack(gifch, ptag->ID); + mfifoGifMaskMem(ptag->ID); + if(gspath3done == true) gifstate = GIF_STATE_DONE; else gifstate = GIF_STATE_READY; @@ -456,6 +494,17 @@ void gifMFIFOInterrupt() GIF_LOG("gifMFIFOInterrupt"); mfifocycles = 0; + if( gifRegs.stat.APATH == 3 ) + { + gifRegs.stat.APATH = 0; + gifRegs.stat.OPH = 0; + if(gifUnit.gifPath[GIF_PATH_3].state == GIF_PATH_IDLE || gifUnit.gifPath[GIF_PATH_3].state == GIF_PATH_WAIT) + { + if(gifUnit.checkPaths(1,1,0)) gifUnit.Execute(false, true); + } + + } + if(gifUnit.gifPath[GIF_PATH_3].state == GIF_PATH_WAIT) { gifUnit.gifPath[GIF_PATH_3].state = GIF_PATH_IDLE; diff --git a/pcsx2/Gif_Unit.h b/pcsx2/Gif_Unit.h index 84e30e035f..7bc1ac4419 100644 --- a/pcsx2/Gif_Unit.h +++ b/pcsx2/Gif_Unit.h @@ -473,7 +473,7 @@ struct Gif_Unit { } if (tranType == GIF_TRANS_MTVU) { // This is on the EE thread path1.mtvu.fakePackets++; - if (CanDoGif()) Execute(false); + if (CanDoGif()) Execute(false, true); return 0; } } @@ -481,7 +481,7 @@ struct Gif_Unit { GUNIT_LOG("%s - [path=%d][size=%d]", Gif_TransferStr[(tranType>>8)&0xf], (tranType&3)+1, size); if (size == 0) { GUNIT_WARN("Gif Unit - Size == 0"); return 0; } if(!CanDoGif()) { GUNIT_WARN("Gif Unit - Signal or PSE Set or Dir = GS to EE"); } - pxAssertDev((stat.APATH==0) || checkPaths(1,1,1), "Gif Unit - APATH wasn't cleared?"); + //pxAssertDev((stat.APATH==0) || checkPaths(1,1,1), "Gif Unit - APATH wasn't cleared?"); lastTranType = tranType; if (tranType == GIF_TRANS_FIFO) { @@ -502,7 +502,7 @@ struct Gif_Unit { } gifPath[tranType&3].CopyGSPacketData(pMem, size, aligned); - size -= Execute(tranType == GIF_TRANS_DMA); + size -= Execute(tranType == GIF_TRANS_DMA, false); return size; } @@ -540,7 +540,7 @@ struct Gif_Unit { // Processes gif packets and performs path arbitration // on EOPs or on Path 3 Images when IMT is set. - int Execute(bool isPath3) { + int Execute(bool isPath3, bool isResume) { if (!CanDoGif()) { DevCon.Error("Gif Unit - Signal or PSE Set or Dir = GS to EE"); return 0; } bool didPath3 = false; int curPath = stat.APATH > 0 ? stat.APATH-1 : 0; //Init to zero if no path is already set. @@ -584,7 +584,7 @@ struct Gif_Unit { elif (!gsSIGNAL.queued && !gifPath[1].isDone()) { stat.APATH = 2; stat.P2Q = 0; curPath = 1; } elif (!gsSIGNAL.queued && !gifPath[2].isDone() && !Path3Masked() /*&& !stat.P2Q*/) { stat.APATH = 3; stat.P3Q = 0; stat.IP3 = 0; curPath = 2; } - else { stat.APATH = 0; stat.OPH = 0; break; } + else { if(isResume) { stat.APATH = 0; stat.OPH = 0; } break; } } //Some loaders/Refresh Rate selectors and things dont issue "End of Packet" commands diff --git a/pcsx2/HwRead.cpp b/pcsx2/HwRead.cpp index f6b34a02d5..42f58a3aa1 100644 --- a/pcsx2/HwRead.cpp +++ b/pcsx2/HwRead.cpp @@ -142,6 +142,14 @@ mem32_t __fastcall _hwRead32(u32 mem) if(mem == (D1_CHCR + 0x10) && CHECK_VIFFIFOHACK) return psHu32(mem) + (vif1ch.qwc * 16); + if((mem == GIF_CHCR) && !vif1ch.chcr.STR && gifRegs.stat.M3P && gifRegs.stat.APATH != 3) + { + //Hack for Wallace and Gromit Curse Project Zoo - Enabled the mask, then starts a new + //GIF DMA, the mask never comes off and it won't proceed until this is unset. + //Unsetting it works too but messes up other PATH3 games. + //If STR is already unset, it won't make the slightest difference. + return (psHu32(mem) & ~0x100); + } return psHu32(mem); } diff --git a/pcsx2/IPU/IPUdma.cpp b/pcsx2/IPU/IPUdma.cpp index 4fbbd99d67..af49d83213 100644 --- a/pcsx2/IPU/IPUdma.cpp +++ b/pcsx2/IPU/IPUdma.cpp @@ -279,15 +279,15 @@ void IPU0dma() case NO_STD: break; case STD_GIF: // GIF - Console.Warning("GIFSTALL"); + DevCon.Warning("GIFSTALL"); g_nDMATransfer.GIFSTALL = true; break; case STD_VIF1: // VIF - Console.Warning("VIFSTALL"); + DevCon.Warning("VIFSTALL"); g_nDMATransfer.VIFSTALL = true; break; case STD_SIF1: - Console.Warning("SIFSTALL"); + DevCon.Warning("SIFSTALL"); g_nDMATransfer.SIFSTALL = true; break; } @@ -402,7 +402,7 @@ void ipu0Interrupt() if (g_nDMATransfer.GIFSTALL) { // gif - Console.Warning("IPU GIF Stall"); + DevCon.Warning("IPU GIF Stall"); g_nDMATransfer.GIFSTALL = false; //if (gif->chcr.STR) GIFdma(); } @@ -410,7 +410,7 @@ void ipu0Interrupt() if (g_nDMATransfer.VIFSTALL) { // vif - Console.Warning("IPU VIF Stall"); + DevCon.Warning("IPU VIF Stall"); g_nDMATransfer.VIFSTALL = false; //if (vif1ch.chcr.STR) dmaVIF1(); } @@ -418,7 +418,7 @@ void ipu0Interrupt() if (g_nDMATransfer.SIFSTALL) { // sif - Console.Warning("IPU SIF Stall"); + DevCon.Warning("IPU SIF Stall"); g_nDMATransfer.SIFSTALL = false; // Not totally sure whether this needs to be done or not, so I'm diff --git a/pcsx2/Memory.cpp b/pcsx2/Memory.cpp index 1ad1469d6d..e188643f57 100644 --- a/pcsx2/Memory.cpp +++ b/pcsx2/Memory.cpp @@ -446,24 +446,28 @@ template static __fi void ClearVuFunc(u32 addr, u32 size) { template static mem8_t __fc vuMicroRead8(u32 addr) { VURegs* vu = vunum ? &VU1 : &VU0; addr &= vunum ? 0x3fff: 0xfff; + if (vunum && THREAD_VU1) vu1Thread.WaitVU(); return vu->Micro[addr]; } template static mem16_t __fc vuMicroRead16(u32 addr) { VURegs* vu = vunum ? &VU1 : &VU0; addr &= vunum ? 0x3fff: 0xfff; + if (vunum && THREAD_VU1) vu1Thread.WaitVU(); return *(u16*)&vu->Micro[addr]; } template static mem32_t __fc vuMicroRead32(u32 addr) { VURegs* vu = vunum ? &VU1 : &VU0; addr &= vunum ? 0x3fff: 0xfff; + if (vunum && THREAD_VU1) vu1Thread.WaitVU(); return *(u32*)&vu->Micro[addr]; } template static void __fc vuMicroRead64(u32 addr,mem64_t* data) { VURegs* vu = vunum ? &VU1 : &VU0; addr &= vunum ? 0x3fff: 0xfff; + if (vunum && THREAD_VU1) vu1Thread.WaitVU(); *data=*(u64*)&vu->Micro[addr]; } @@ -471,6 +475,7 @@ template static void __fc vuMicroRead128(u32 addr,mem128_t* data) { VURegs* vu = vunum ? &VU1 : &VU0; addr &= vunum ? 0x3fff: 0xfff; if (vunum && THREAD_VU1) vu1Thread.WaitVU(); + CopyQWC(data,&vu->Micro[addr]); } @@ -479,6 +484,7 @@ template static void __fc vuMicroRead128(u32 addr,mem128_t* data) { template static void __fc vuMicroWrite8(u32 addr,mem8_t data) { VURegs* vu = vunum ? &VU1 : &VU0; addr &= vunum ? 0x3fff: 0xfff; + if (vunum && THREAD_VU1) { vu1Thread.WriteMicroMem(addr, &data, sizeof(u8)); return; @@ -491,6 +497,7 @@ template static void __fc vuMicroWrite8(u32 addr,mem8_t data) { template static void __fc vuMicroWrite16(u32 addr, mem16_t data) { VURegs* vu = vunum ? &VU1 : &VU0; addr &= vunum ? 0x3fff: 0xfff; + if (vunum && THREAD_VU1) { vu1Thread.WriteMicroMem(addr, &data, sizeof(u16)); return; @@ -503,6 +510,7 @@ template static void __fc vuMicroWrite16(u32 addr, mem16_t data) { template static void __fc vuMicroWrite32(u32 addr, mem32_t data) { VURegs* vu = vunum ? &VU1 : &VU0; addr &= vunum ? 0x3fff: 0xfff; + if (vunum && THREAD_VU1) { vu1Thread.WriteMicroMem(addr, &data, sizeof(u32)); return; @@ -515,10 +523,12 @@ template static void __fc vuMicroWrite32(u32 addr, mem32_t data) { template static void __fc vuMicroWrite64(u32 addr, const mem64_t* data) { VURegs* vu = vunum ? &VU1 : &VU0; addr &= vunum ? 0x3fff: 0xfff; + if (vunum && THREAD_VU1) { vu1Thread.WriteMicroMem(addr, (void*)data, sizeof(u64)); return; } + if (*(u64*)&vu->Micro[addr]!=data[0]) { ClearVuFunc(addr, 8); *(u64*)&vu->Micro[addr] =data[0]; @@ -527,6 +537,7 @@ template static void __fc vuMicroWrite64(u32 addr, const mem64_t* dat template static void __fc vuMicroWrite128(u32 addr, const mem128_t* data) { VURegs* vu = vunum ? &VU1 : &VU0; addr &= vunum ? 0x3fff: 0xfff; + if (vunum && THREAD_VU1) { vu1Thread.WriteMicroMem(addr, (void*)data, sizeof(u128)); return; diff --git a/pcsx2/Patch.cpp b/pcsx2/Patch.cpp index b6fbae5a5e..faf1b57ec8 100644 --- a/pcsx2/Patch.cpp +++ b/pcsx2/Patch.cpp @@ -21,6 +21,7 @@ #include "Patch.h" #include "GameDatabase.h" #include +#include IniPatch Patch[ MAX_PATCH ]; IniPatch Cheat[ MAX_CHEAT ]; @@ -165,35 +166,60 @@ void inifile_process(wxTextFile &f1 ) } } +void ResetCheatsCount() +{ + cheatnumber = 0; +} + +static int LoadCheatsFiles(const wxString& folderName, wxString& fileSpec, const wxString& friendlyName) +{ + if (!wxDir::Exists(folderName)) { + Console.WriteLn(Color_Red, L"The %s folder ('%s') is inaccessible. Skipping...", friendlyName.c_str(), folderName.c_str()); + return 0; + } + wxDir dir(folderName); + + int before = cheatnumber; + wxString buffer; + wxTextFile f; + bool found = dir.GetFirst(&buffer, fileSpec, wxDIR_FILES); + while (found) { + Console.WriteLn(Color_Gray, L"Found %s file: '%s'", friendlyName.c_str(), buffer.c_str()); + int before = cheatnumber; + f.Open(Path::Combine(dir.GetName(), buffer)); + inifile_process(f); + f.Close(); + int loaded = cheatnumber - before; + Console.WriteLn((loaded ? Color_Green : Color_Gray), L"Loaded %d %s from '%s'", loaded, friendlyName.c_str(), buffer.c_str()); + found = dir.GetNext(&buffer); + } + + return cheatnumber - before; +} + // This routine loads cheats from *.pnach files // Returns number of cheats loaded // Note: Should be called after InitPatches() -int InitCheats(const wxString& name) +int LoadCheats(wxString name, const wxString& folderName, const wxString& friendlyName) { - wxTextFile f1; - wxString buffer; - cheatnumber = 0; + if (!name.Length()) { + Console.WriteLn(Color_Gray, "Cheats: No CRC, using 00000000 instead."); + name = L"00000000"; + } - // FIXME : We need to add a 'cheats' folder to the AppConfig, and use that instead. --air + int loaded = 0; - buffer = Path::Combine(L"cheats", name + L".pnach"); + wxString filespec = name + L"*.pnach"; + loaded += LoadCheatsFiles(folderName, filespec, friendlyName); - if(!f1.Open(buffer) && wxFileName::IsCaseSensitive()) - { - f1.Open( Path::Combine(L"cheats", name.Upper() + L".pnach") ); - } + wxString nameUpper = name; nameUpper.Upper(); + if (wxFileName::IsCaseSensitive() && name != nameUpper) { + filespec = nameUpper + L"*.pnach"; + loaded += LoadCheatsFiles(folderName, filespec, friendlyName); + } - if(!f1.IsOpened()) - { - Console.WriteLn( Color_Gray, "No cheats found. Resuming execution without cheats..." ); - return 0; - } - - Console.WriteLn( Color_Green, "Cheats found!"); - inifile_process( f1 ); - - Console.WriteLn("Cheats Loaded: %d", cheatnumber); - return cheatnumber; + Console.WriteLn((loaded ? Color_Green : Color_Gray), L"Overall %d %s loaded", loaded, friendlyName.c_str()); + return loaded; } static u32 StrToU32(const wxString& str, int base = 10) diff --git a/pcsx2/Patch.h b/pcsx2/Patch.h index a4db00831d..a62f8692b4 100644 --- a/pcsx2/Patch.h +++ b/pcsx2/Patch.h @@ -57,7 +57,8 @@ namespace PatchFunc PATCHTABLEFUNC cheat; } -extern int InitCheats(const wxString& name); +extern void ResetCheatsCount(); +extern int LoadCheats(wxString name, const wxString& folderName, const wxString& friendlyName); extern void inifile_command(bool isCheat, const wxString& cmd); extern void inifile_trim(wxString& buffer); diff --git a/pcsx2/PluginManager.cpp b/pcsx2/PluginManager.cpp index 1166fca2cd..5a76a0aa85 100644 --- a/pcsx2/PluginManager.cpp +++ b/pcsx2/PluginManager.cpp @@ -43,6 +43,11 @@ void SysPluginBindings::McdGetSizeInfo( uint port, uint slot, PS2E_McdSizeInfo& Mcd->McdGetSizeInfo( (PS2E_THISPTR) Mcd, port, slot, &outways ); } +bool SysPluginBindings::McdIsPSX( uint port, uint slot ) +{ + return Mcd->McdIsPSX( (PS2E_THISPTR) Mcd, port, slot ); +} + void SysPluginBindings::McdRead( uint port, uint slot, u8 *dest, u32 adr, int size ) { Mcd->McdRead( (PS2E_THISPTR) Mcd, port, slot, dest, adr, size ); diff --git a/pcsx2/Plugins.h b/pcsx2/Plugins.h index 6781989097..87f9505f34 100644 --- a/pcsx2/Plugins.h +++ b/pcsx2/Plugins.h @@ -236,6 +236,7 @@ public: bool McdIsPresent( uint port, uint slot ); void McdGetSizeInfo( uint port, uint slot, PS2E_McdSizeInfo& outways ); + bool McdIsPSX( uint port, uint slot ); void McdRead( uint port, uint slot, u8 *dest, u32 adr, int size ); void McdSave( uint port, uint slot, const u8 *src, u32 adr, int size ); void McdEraseBlock( uint port, uint slot, u32 adr ); diff --git a/pcsx2/VU.h b/pcsx2/VU.h index af87cd16b6..360c4ac738 100644 --- a/pcsx2/VU.h +++ b/pcsx2/VU.h @@ -82,7 +82,7 @@ struct REG_VI { //#define VUFLAG_BREAKONMFLAG 0x00000001 #define VUFLAG_MFLAGSET 0x00000002 - +#define VUFLAG_INTCINTERRUPT 0x00000004 struct fdivPipe { int enable; REG_VI reg; @@ -154,6 +154,10 @@ struct __aligned16 VURegs { u32 ebit; + u8 VIBackupCycles; + u32 VIOldValue; + u32 VIRegNumber; + fmacPipe fmac[8]; fdivPipe fdiv; efuPipe efu; diff --git a/pcsx2/VU0microInterp.cpp b/pcsx2/VU0microInterp.cpp index c4aca7aa71..de0432d2a8 100644 --- a/pcsx2/VU0microInterp.cpp +++ b/pcsx2/VU0microInterp.cpp @@ -61,13 +61,17 @@ static void _vu0Exec(VURegs* VU) if (VU0.VI[REG_FBRST].UL & 0x4) { VU0.VI[REG_VPU_STAT].UL|= 0x2; hwIntcIrq(INTC_VU0); + VU->ebit = 1; } + } if (ptr[1] & 0x08000000) { /* T flag */ if (VU0.VI[REG_FBRST].UL & 0x8) { VU0.VI[REG_VPU_STAT].UL|= 0x4; hwIntcIrq(INTC_VU0); + VU->ebit = 1; } + } VU->code = ptr[1]; @@ -144,6 +148,9 @@ static void _vu0Exec(VURegs* VU) _vuTestPipes(VU); + if(VU->VIBackupCycles > 0) + VU->VIBackupCycles--; + if (VU->branch > 0) { if (VU->branch-- == 1) { VU->VI[REG_TPC].UL = VU->branchpc; @@ -161,6 +168,7 @@ static void _vu0Exec(VURegs* VU) if( VU->ebit > 0 ) { if( VU->ebit-- == 1 ) { + VU->VIBackupCycles = 0; _vuFlushAll(VU); VU0.VI[REG_VPU_STAT].UL&= ~0x1; /* E flag */ vif0Regs.stat.VEW = false; diff --git a/pcsx2/VU1microInterp.cpp b/pcsx2/VU1microInterp.cpp index 85ce8ff550..c440ac33c4 100644 --- a/pcsx2/VU1microInterp.cpp +++ b/pcsx2/VU1microInterp.cpp @@ -59,13 +59,17 @@ static void _vu1Exec(VURegs* VU) if (VU0.VI[REG_FBRST].UL & 0x400) { VU0.VI[REG_VPU_STAT].UL|= 0x200; hwIntcIrq(INTC_VU1); + VU->ebit = 1; } + } if (ptr[1] & 0x08000000) { /* T flag */ if (VU0.VI[REG_FBRST].UL & 0x800) { VU0.VI[REG_VPU_STAT].UL|= 0x400; hwIntcIrq(INTC_VU1); + VU->ebit = 1; } + } //VUM_LOG("VU->cycle = %d (flags st=%x;mac=%x;clip=%x,q=%f)", VU->cycle, VU->statusflag, VU->macflag, VU->clipflag, VU->q.F); @@ -141,6 +145,9 @@ static void _vu1Exec(VURegs* VU) _vuTestPipes(VU); + if(VU->VIBackupCycles > 0) + VU->VIBackupCycles--; + if (VU->branch > 0) { if (VU->branch-- == 1) { VU->VI[REG_TPC].UL = VU->branchpc; @@ -158,6 +165,7 @@ static void _vu1Exec(VURegs* VU) if( VU->ebit > 0 ) { if( VU->ebit-- == 1 ) { + VU->VIBackupCycles = 0; _vuFlushAll(VU); VU0.VI[REG_VPU_STAT].UL &= ~0x100; vif1Regs.stat.VEW = false; diff --git a/pcsx2/VUops.cpp b/pcsx2/VUops.cpp index f619927311..b3601335ad 100644 --- a/pcsx2/VUops.cpp +++ b/pcsx2/VUops.cpp @@ -43,6 +43,7 @@ #define _Imm11_ (s32)(VU->code & 0x400 ? 0xfffffc00 | (VU->code & 0x3ff) : VU->code & 0x3ff) #define _UImm11_ (s32)(VU->code & 0x7ff) +#define VI_BACKUP static __aligned16 VECTOR RDzero; @@ -1456,7 +1457,7 @@ static __fi void _vuCLIP(VURegs * VU) { if ( vuDouble(VU->VF[_Fs_].i.z) > +value ) VU->clipflag|= 0x10; if ( vuDouble(VU->VF[_Fs_].i.z) < -value ) VU->clipflag|= 0x20; VU->clipflag = VU->clipflag & 0xFFFFFF; - VU->VI[REG_CLIP_FLAG].UL = VU->clipflag; + //VU->VI[REG_CLIP_FLAG].UL = VU->clipflag; //Shouldn't need to do this, let the pipes sort it out. }/*last update 16/07/05 refraction - Needs checking */ @@ -1546,36 +1547,81 @@ static __fi void _vuIADDI(VURegs * VU) { s16 imm = ((VU->code >> 6) & 0x1f); imm = ((imm & 0x10 ? 0xfff0 : 0) | (imm & 0xf)); if(_It_ == 0) return; + +#ifdef VI_BACKUP + VU->VIBackupCycles = 2; + VU->VIRegNumber = _It_; + VU->VIOldValue = VU->VI[_It_].US[0]; +#endif + VU->VI[_It_].SS[0] = VU->VI[_Is_].SS[0] + imm; }//last checked 17/05/03 shadow NOTE: not quite sure about that static __fi void _vuIADDIU(VURegs * VU) { if(_It_ == 0) return; + +#ifdef VI_BACKUP + VU->VIBackupCycles = 2; + VU->VIRegNumber = _It_; + VU->VIOldValue = VU->VI[_It_].US[0]; +#endif + VU->VI[_It_].SS[0] = VU->VI[_Is_].SS[0] + (((VU->code >> 10) & 0x7800) | (VU->code & 0x7ff)); }//last checked 17/05/03 shadow static __fi void _vuIADD(VURegs * VU) { if(_Id_ == 0) return; + +#ifdef VI_BACKUP + VU->VIBackupCycles = 2; + VU->VIRegNumber = _It_; + VU->VIOldValue = VU->VI[_Id_].US[0]; +#endif + VU->VI[_Id_].SS[0] = VU->VI[_Is_].SS[0] + VU->VI[_It_].SS[0]; }//last checked 17/05/03 shadow static __fi void _vuIAND(VURegs * VU) { if(_Id_ == 0) return; + +#ifdef VI_BACKUP + VU->VIBackupCycles = 2; + VU->VIRegNumber = _It_; + VU->VIOldValue = VU->VI[_Id_].US[0]; +#endif + VU->VI[_Id_].US[0] = VU->VI[_Is_].US[0] & VU->VI[_It_].US[0]; }//last checked 17/05/03 shadow static __fi void _vuIOR(VURegs * VU) { if(_Id_ == 0) return; + +#ifdef VI_BACKUP + VU->VIBackupCycles = 2; + VU->VIRegNumber = _It_; + VU->VIOldValue = VU->VI[_Id_].US[0]; +#endif + VU->VI[_Id_].US[0] = VU->VI[_Is_].US[0] | VU->VI[_It_].US[0]; } static __fi void _vuISUB(VURegs * VU) { if(_Id_ == 0) return; +#ifdef VI_BACKUP + VU->VIBackupCycles = 2; + VU->VIRegNumber = _It_; + VU->VIOldValue = VU->VI[_Id_].US[0]; +#endif VU->VI[_Id_].SS[0] = VU->VI[_Is_].SS[0] - VU->VI[_It_].SS[0]; } static __fi void _vuISUBIU(VURegs * VU) { if(_It_ == 0) return; +#ifdef VI_BACKUP + VU->VIBackupCycles = 2; + VU->VIRegNumber = _It_; + VU->VIOldValue = VU->VI[_It_].US[0]; +#endif VU->VI[_It_].SS[0] = VU->VI[_Is_].SS[0] - (((VU->code >> 10) & 0x7800) | (VU->code & 0x7ff)); } @@ -1600,6 +1646,11 @@ static __fi void _vuMFIR(VURegs * VU) { // Big bug!!! mov from fs to ft not ft to fs. asadr static __fi void _vuMTIR(VURegs * VU) { if(_It_ == 0) return; +#ifdef VI_BACKUP + VU->VIBackupCycles = 2; + VU->VIRegNumber = _It_; + VU->VIOldValue = VU->VI[_It_].US[0]; +#endif VU->VI[_It_].US[0] = *(u16*)&VU->VF[_Fs_].F[_Fsf_]; } @@ -1703,6 +1754,13 @@ static __ri void _vuILW(VURegs * VU) { s16 imm = (VU->code & 0x400) ? (VU->code & 0x3ff) | 0xfc00 : (VU->code & 0x3ff); u16 addr = ((imm + VU->VI[_Is_].SS[0]) * 16); u16* ptr = (u16*)GET_VU_MEM(VU, addr); + +#ifdef VI_BACKUP + VU->VIBackupCycles = 2; + VU->VIRegNumber = _It_; + VU->VIOldValue = VU->VI[_It_].US[0]; +#endif + if (_X) VU->VI[_It_].US[0] = ptr[0]; if (_Y) VU->VI[_It_].US[0] = ptr[2]; if (_Z) VU->VI[_It_].US[0] = ptr[4]; @@ -1724,6 +1782,13 @@ static __ri void _vuILWR(VURegs * VU) { u32 addr = (VU->VI[_Is_].US[0] * 16); u16* ptr = (u16*)GET_VU_MEM(VU, addr); + +#ifdef VI_BACKUP + VU->VIBackupCycles = 2; + VU->VIRegNumber = _It_; + VU->VIOldValue = VU->VI[_It_].US[0]; +#endif + if (_X) VU->VI[_It_].US[0] = ptr[0]; if (_Y) VU->VI[_It_].US[0] = ptr[2]; if (_Z) VU->VI[_It_].US[0] = ptr[4]; @@ -1888,42 +1953,113 @@ static __fi void _setBranch(VURegs * VU, u32 bpc) { } static __ri void _vuIBEQ(VURegs * VU) { - if (VU->VI[_It_].US[0] == VU->VI[_Is_].US[0]) { + s16 dest = VU->VI[_It_].US[0] ; + s16 src = VU->VI[_Is_].US[0]; +#ifdef VI_BACKUP + if(VU->VIBackupCycles > 0) + { + if(VU->VIRegNumber == _It_) + { + dest = VU->VIOldValue; + } + if(VU->VIRegNumber == _Is_) + { + src = VU->VIOldValue; + } + } +#endif + if (dest == src) { s32 bpc = _branchAddr(VU); _setBranch(VU, bpc); } } static __ri void _vuIBGEZ(VURegs * VU) { - if (VU->VI[_Is_].SS[0] >= 0) { + s16 src = VU->VI[_Is_].US[0]; +#ifdef VI_BACKUP + if(VU->VIBackupCycles > 0) + { + if(VU->VIRegNumber == _Is_) + { + src = VU->VIOldValue; + } + } +#endif + if (src >= 0) { s32 bpc = _branchAddr(VU); _setBranch(VU, bpc); } } static __ri void _vuIBGTZ(VURegs * VU) { - if (VU->VI[_Is_].SS[0] > 0) { + s16 src = VU->VI[_Is_].US[0]; +#ifdef VI_BACKUP + if(VU->VIBackupCycles > 0) + { + if(VU->VIRegNumber == _Is_) + { + src = VU->VIOldValue; + } + } +#endif + + if (src > 0) { s32 bpc = _branchAddr(VU); _setBranch(VU, bpc); } } static __ri void _vuIBLEZ(VURegs * VU) { - if (VU->VI[_Is_].SS[0] <= 0) { + s16 src = VU->VI[_Is_].US[0]; +#ifdef VI_BACKUP + if(VU->VIBackupCycles > 0) + { + if(VU->VIRegNumber == _Is_) + { + src = VU->VIOldValue; + } + } +#endif + if (src <= 0) { s32 bpc = _branchAddr(VU); _setBranch(VU, bpc); } } static __ri void _vuIBLTZ(VURegs * VU) { - if (VU->VI[_Is_].SS[0] < 0) { + s16 src = VU->VI[_Is_].US[0]; +#ifdef VI_BACKUP + if(VU->VIBackupCycles > 0) + { + if(VU->VIRegNumber == _Is_) + { + src = VU->VIOldValue; + } + } +#endif + if (src < 0) { s32 bpc = _branchAddr(VU); _setBranch(VU, bpc); } } static __ri void _vuIBNE(VURegs * VU) { - if (VU->VI[_It_].US[0] != VU->VI[_Is_].US[0]) { + s16 dest = VU->VI[_It_].US[0] ; + s16 src = VU->VI[_Is_].US[0]; +#ifdef VI_BACKUP + if(VU->VIBackupCycles > 0) + { + if(VU->VIRegNumber == _It_) + { + dest = VU->VIOldValue; + } + if(VU->VIRegNumber == _Is_) + { + src = VU->VIOldValue; + } + } +#endif + if (dest != src) { s32 bpc = _branchAddr(VU); _setBranch(VU, bpc); } diff --git a/pcsx2/Vif.cpp b/pcsx2/Vif.cpp index 7df6e56924..07dc6ea7f4 100644 --- a/pcsx2/Vif.cpp +++ b/pcsx2/Vif.cpp @@ -21,6 +21,7 @@ #include "GS.h" #include "Gif.h" #include "MTVU.h" +#include "Gif_Unit.h" __aligned16 vifStruct vif0, vif1; @@ -124,7 +125,7 @@ __fi void vif0FBRST(u32 value) { // just stoppin the VIF (linuz). vif0Regs.stat.VSS = true; vif0Regs.stat.VPS = VPS_IDLE; - vif0.vifstalled.enabled = true; + vif0.vifstalled.enabled = VifStallEnable(vif0ch); vif0.vifstalled.value = VIF_IRQ_STALL; } @@ -178,6 +179,27 @@ __fi void vif1FBRST(u32 value) { psHu64(VIF1_FIFO + 8) = 0; vif1.done = true; vif1ch.chcr.STR = false; + + //HACK!! Dynasty Warriors 5 Empires has some sort of wierd packet alignment thing going off, meaning + //the packet ends before the DirectHL in progress has finished. Not sure what causes that, but the GIF + //Unit is still waiting for more data, so we have to "pretend" it is finished when the game issues a reset + //which it does without causing any pauses. + //In most cases, this will never ever happen, so doing the following won't matter. + if(!gifUnit.gifPath[GIF_PATH_2].isDone()) + { + DevCon.Warning("VIF1 FBRST While GIF Path2 is waiting for data!"); + gifUnit.gifPath[GIF_PATH_2].state = GIF_PATH_IDLE; + gifUnit.gifPath[GIF_PATH_2].curSize = gifUnit.gifPath[GIF_PATH_2].curOffset; + + if( gifRegs.stat.APATH == 2) + { + gifRegs.stat.APATH = 0; + gifRegs.stat.OPH = 0; + vif1Regs.stat.VGW = false; //Let vif continue if it's stuck on a flush + + if(gifUnit.checkPaths(1,0,1)) gifUnit.Execute(false, true); + } + } #if USE_OLD_GIF == 1 // ... if(vif1Regs.mskpath3 == 1 && GSTransferStatus.PTH3 == STOPPED_MODE && gifch.chcr.STR == true) { @@ -209,7 +231,7 @@ __fi void vif1FBRST(u32 value) { vif1Regs.stat.VFS = true; vif1Regs.stat.VPS = VPS_IDLE; cpuRegs.interrupt &= ~((1 << 1) | (1 << 10)); //Stop all vif1 DMA's - vif1.vifstalled.enabled = true; + vif1.vifstalled.enabled = VifStallEnable(vif1ch); vif1.vifstalled.value = VIF_IRQ_STALL; Console.WriteLn("vif1 force break"); } @@ -221,7 +243,7 @@ __fi void vif1FBRST(u32 value) { vif1Regs.stat.VSS = true; vif1Regs.stat.VPS = VPS_IDLE; cpuRegs.interrupt &= ~((1 << 1) | (1 << 10)); //Stop all vif1 DMA's - vif1.vifstalled.enabled = true; + vif1.vifstalled.enabled = VifStallEnable(vif1ch); vif1.vifstalled.value = VIF_IRQ_STALL; } diff --git a/pcsx2/Vif.h b/pcsx2/Vif.h index 235e232482..32825aa267 100644 --- a/pcsx2/Vif.h +++ b/pcsx2/Vif.h @@ -241,6 +241,8 @@ static VIFregisters& vif1Regs = (VIFregisters&)eeHw[0x3C00]; #define MTVU_VifX (idx ? ((THREAD_VU1) ? vu1Thread.vif : vif1) : (vif0)) #define MTVU_VifXRegs (idx ? ((THREAD_VU1) ? vu1Thread.vifRegs : vif1Regs) : (vif0Regs)) +#define VifStallEnable(vif) vif.chcr.STR ? true : false; + extern void dmaVIF0(); extern void dmaVIF1(); extern void mfifoVIF1transfer(int qwc); diff --git a/pcsx2/Vif0_Dma.cpp b/pcsx2/Vif0_Dma.cpp index ecd8a4978c..909c88a446 100644 --- a/pcsx2/Vif0_Dma.cpp +++ b/pcsx2/Vif0_Dma.cpp @@ -28,7 +28,7 @@ __fi void vif0FLUSH() if(vif0Regs.stat.VEW == true) { vif0.waitforvu = true; - vif0.vifstalled.enabled = true; + vif0.vifstalled.enabled = VifStallEnable(vif0ch); vif0.vifstalled.value = VIF_TIMING_BREAK; } return; diff --git a/pcsx2/Vif1_Dma.cpp b/pcsx2/Vif1_Dma.cpp index 0b3724af9b..08b2c2d286 100644 --- a/pcsx2/Vif1_Dma.cpp +++ b/pcsx2/Vif1_Dma.cpp @@ -28,7 +28,7 @@ __fi void vif1FLUSH() if(vif1Regs.stat.VEW == true) { vif1.waitforvu = true; - vif1.vifstalled.enabled = true; + vif1.vifstalled.enabled = VifStallEnable(vif1ch); vif1.vifstalled.value = VIF_TIMING_BREAK; } } @@ -230,6 +230,20 @@ __fi void vif1VUFinish() vif1Regs.stat.VEW = false; VIF_LOG("VU1 finished"); + + if( gifRegs.stat.APATH == 1 ) + { + VIF_LOG("Clear APATH1"); + gifRegs.stat.APATH = 0; + gifRegs.stat.OPH = 0; + vif1Regs.stat.VGW = false; //Let vif continue if it's stuck on a flush + + if(!vif1.waitforvu) + { + if(gifUnit.checkPaths(0,1,1)) gifUnit.Execute(false, true); + } + + } if(vif1.waitforvu == true) { vif1.waitforvu = false; @@ -253,6 +267,14 @@ __fi void vif1Interrupt() g_vif1Cycles = 0; + if( gifRegs.stat.APATH == 2 && gifUnit.gifPath[GIF_PATH_2].isDone()) + { + gifRegs.stat.APATH = 0; + gifRegs.stat.OPH = 0; + vif1Regs.stat.VGW = false; //Let vif continue if it's stuck on a flush + + if(gifUnit.checkPaths(1,0,1)) gifUnit.Execute(false, true); + } //Some games (Fahrenheit being one) start vif first, let it loop through blankness while it sets MFIFO mode, so we need to check it here. if (dmacRegs.ctrl.MFD == MFD_VIF1) { //Console.WriteLn("VIFMFIFO\n"); diff --git a/pcsx2/Vif1_MFIFO.cpp b/pcsx2/Vif1_MFIFO.cpp index 5daa3ffaca..65eb9d5f12 100644 --- a/pcsx2/Vif1_MFIFO.cpp +++ b/pcsx2/Vif1_MFIFO.cpp @@ -116,7 +116,7 @@ static __fi void mfifo_VIF1chain() } if (vif1ch.madr >= dmacRegs.rbor.ADDR && - vif1ch.madr <= (dmacRegs.rbor.ADDR + dmacRegs.rbsr.RMSK + 16)) + vif1ch.madr < (dmacRegs.rbor.ADDR + dmacRegs.rbsr.RMSK + 16)) { //if(vif1ch.madr == (dmacRegs.rbor.ADDR + dmacRegs.rbsr.RMSK + 16)) DevCon.Warning("Edge VIF1"); @@ -145,6 +145,32 @@ static __fi void mfifo_VIF1chain() } } +void mfifoVifMaskMem(int id) +{ + switch (id) { + //These five transfer data following the tag, need to check its within the buffer (Front Mission 4) + case TAG_CNT: + case TAG_NEXT: + case TAG_CALL: + case TAG_RET: + case TAG_END: + if(vif1ch.madr < dmacRegs.rbor.ADDR) //probably not needed but we will check anyway. + { + //DevCon.Warning("VIF MFIFO MADR below bottom of ring buffer, wrapping VIF MADR = %x Ring Bottom %x", vif1ch.madr, dmacRegs.rbor.ADDR); + vif1ch.madr = qwctag(vif1ch.madr); + } + if(vif1ch.madr > (dmacRegs.rbor.ADDR + dmacRegs.rbsr.RMSK)) //Usual scenario is the tag is near the end (Front Mission 4) + { + //DevCon.Warning("VIF MFIFO MADR outside top of ring buffer, wrapping VIF MADR = %x Ring Top %x", vif1ch.madr, (dmacRegs.rbor.ADDR + dmacRegs.rbsr.RMSK)+16); + vif1ch.madr = qwctag(vif1ch.madr); + } + break; + default: + //Do nothing as the MADR could be outside + break; + } +} + void mfifoVIF1transfer(int qwc) { tDMA_TAG *ptag; @@ -223,6 +249,8 @@ void mfifoVIF1transfer(int qwc) vif1.done |= hwDmacSrcChainWithStack(vif1ch, ptag->ID); + mfifoVifMaskMem(ptag->ID); + if (vif1ch.chcr.TIE && ptag->IRQ) { VIF_LOG("dmaIrq Set"); @@ -250,6 +278,14 @@ void vifMFIFOInterrupt() g_vif1Cycles = 0; VIF_LOG("vif mfifo interrupt"); + if( gifRegs.stat.APATH == 2 && gifUnit.gifPath[1].isDone()) + { + gifRegs.stat.APATH = 0; + gifRegs.stat.OPH = 0; + + if(gifUnit.checkPaths(1,0,1)) gifUnit.Execute(false, true); + } + if (dmacRegs.ctrl.MFD != MFD_VIF1) { DevCon.Warning("Not in VIF MFIFO mode! Stopping VIF MFIFO"); return; diff --git a/pcsx2/Vif_Codes.cpp b/pcsx2/Vif_Codes.cpp index 38d2ee55a4..0750026bbe 100644 --- a/pcsx2/Vif_Codes.cpp +++ b/pcsx2/Vif_Codes.cpp @@ -54,7 +54,7 @@ __ri void vifExecQueue(int idx) else { startcycles = ((VU1.cycle-startcycles) + ( vif1ch.qwc - (vif1.vifpacketsize >> 2) )); CPU_INT(VIF_VU1_FINISH, 1/*startcycles * BIAS*/); } //DevCon.Warning("Ran VU%x, VU0 Cycles %x, VU1 Cycles %x, start %x cycle %x", idx, g_vu0Cycles, g_vu1Cycles, startcycles, VU1.cycle); - //GetVifX.vifstalled.enabled = true; + //GetVifX.vifstalled.enabled = VifStallEnable(vifXch); //GetVifX.vifstalled.value = VIF_TIMING_BREAK; } @@ -153,7 +153,7 @@ template __fi int _vifCode_Direct(int pass, const u8* data, bool isDire if (size != ret) { // Stall if gif didn't process all the data (path2 queued) GUNIT_WARN("Vif %s: Stall! [size=%d][ret=%d]", name, size, ret); //gifUnit.PrintInfo(); - vif1.vifstalled.enabled = true; + vif1.vifstalled.enabled = VifStallEnable(vif1ch); vif1.vifstalled.value = VIF_TIMING_BREAK; vif1Regs.stat.VGW = true; return 0; @@ -161,6 +161,8 @@ template __fi int _vifCode_Direct(int pass, const u8* data, bool isDire if (vif1.tag.size == 0) { vif1.cmd = 0; vif1.pass = 0; + vif1.vifstalled.enabled = VifStallEnable(vif1ch); + vif1.vifstalled.value = VIF_TIMING_BREAK; } return ret / 4; } @@ -181,18 +183,19 @@ vifOp(vifCode_Flush) { vif1Only(); vifStruct& vifX = GetVifX; pass1or2 { + bool p1or2 = (gifRegs.stat.APATH != 0 && gifRegs.stat.APATH != 3); vif1Regs.stat.VGW = false; vifFlush(idx); - if (gifUnit.checkPaths(1,1,0)) { + if (gifUnit.checkPaths(1,1,0) || p1or2) { GUNIT_WARN("Vif Flush: Stall!"); //gifUnit.PrintInfo(); vif1Regs.stat.VGW = true; - vifX.vifstalled.enabled = true; - vifX.vifstalled.value = VIF_TIMING_BREAK; + vif1.vifstalled.enabled = VifStallEnable(vif1ch); + vif1.vifstalled.value = VIF_TIMING_BREAK; return 0; } - else vifX.cmd = 0; - vifX.pass = 0; + else vif1.cmd = 0; + vif1.pass = 0; } pass3 { VifCodeLog("Flush"); } return 1; @@ -202,15 +205,22 @@ vifOp(vifCode_FlushA) { vif1Only(); vifStruct& vifX = GetVifX; pass1or2 { - Gif_Path& p3 = gifUnit.gifPath[GIF_PATH_3]; - u32 p1or2 = gifUnit.checkPaths(1,1,0); - bool doStall = false; + //Gif_Path& p3 = gifUnit.gifPath[GIF_PATH_3]; + u32 gifBusy = gifUnit.checkPaths(1,1,1) || (gifRegs.stat.APATH != 0); + //bool doStall = false; vif1Regs.stat.VGW = false; vifFlush(idx); - if (p3.state != GIF_PATH_IDLE || p1or2) { + + if (gifBusy) + { GUNIT_WARN("Vif FlushA: Stall!"); + vif1Regs.stat.VGW = true; + vif1.vifstalled.enabled = VifStallEnable(vif1ch); + vif1.vifstalled.value = VIF_TIMING_BREAK; + return 0; + //gifUnit.PrintInfo(); - if (p3.state != GIF_PATH_IDLE && !p1or2) { // Only path 3 left... + /*if (p3.state != GIF_PATH_IDLE && !p1or2) { // Only path 3 left... GUNIT_WARN("Vif FlushA - Getting path3 to finish!"); if (gifUnit.lastTranType == GIF_TRANS_FIFO && p3.state != GIF_PATH_IDLE && !p3.hasDataRemaining()) { @@ -222,16 +232,18 @@ vifOp(vifCode_FlushA) { doStall = true; // If path3 still isn't finished... } } - else doStall = true; + else doStall = true;*/ } - if (doStall) { + /*if (doStall) { vif1Regs.stat.VGW = true; - vifX.vifstalled.enabled = true; + vifX.vifstalled.enabled = VifStallEnable(vifXch); vifX.vifstalled.value = VIF_TIMING_BREAK; return 0; } - else vifX.cmd = 0; - vifX.pass = 0; + else*/ + //Didn't need to stall! + vif1.cmd = 0; + vif1.pass = 0; } pass3 { VifCodeLog("FlushA"); } return 1; @@ -368,7 +380,7 @@ vifOp(vifCode_MSCALF) { if (u32 a = gifUnit.checkPaths(1,1,0)) { GUNIT_WARN("Vif MSCALF: Stall! [%d,%d]", !!(a&1), !!(a&2)); vif1Regs.stat.VGW = true; - vifX.vifstalled.enabled = true; + vifX.vifstalled.enabled = VifStallEnable(vifXch); vifX.vifstalled.value = VIF_TIMING_BREAK; } if(vifX.waitforvu == false) @@ -422,6 +434,14 @@ vifOp(vifCode_Nop) { GetVifX.cmd = 0; GetVifX.pass = 0; vifExecQueue(idx); + if(GetVifX.vifpacketsize > 1) + { + if(((data[1] >> 24) & 0x7f) == 0x6) //is mskpath3 next + { + GetVifX.vifstalled.enabled = VifStallEnable(vifXch); + GetVifX.vifstalled.value = VIF_TIMING_BREAK; + } + } } pass3 { VifCodeLog("Nop"); } return 1; @@ -435,7 +455,7 @@ vifOp(vifCode_Null) { if (!(vifXRegs.err.ME1)) { // Ignore vifcode and tag mismatch error Console.WriteLn("Vif%d: Unknown VifCmd! [%x]", idx, vifX.cmd); vifXRegs.stat.ER1 = true; - vifX.vifstalled.enabled = true; + vifX.vifstalled.enabled = VifStallEnable(vifXch); vifX.vifstalled.value = VIF_IRQ_STALL; //vifX.irq++; } diff --git a/pcsx2/Vif_Transfer.cpp b/pcsx2/Vif_Transfer.cpp index 4b4361a70e..93f189f810 100644 --- a/pcsx2/Vif_Transfer.cpp +++ b/pcsx2/Vif_Transfer.cpp @@ -86,7 +86,7 @@ _vifT static __fi bool vifTransfer(u32 *data, int size, bool TTE) { vifXRegs.stat.VIS = true; // Note: commenting this out fixes WALL-E? } //Always needs to be set to return to the correct offset if there is data left. - vifX.vifstalled.enabled = true; + vifX.vifstalled.enabled = VifStallEnable(vifXch); vifX.vifstalled.value = VIF_IRQ_STALL; } @@ -107,9 +107,9 @@ _vifT static __fi bool vifTransfer(u32 *data, int size, bool TTE) { } else { - if(vifX.irqoffset.value > 1) + if(vifX.irqoffset.value != 0){ vifX.irqoffset.enabled = true; - else + }else vifX.irqoffset.enabled = false; } diff --git a/pcsx2/gui/AppCoreThread.cpp b/pcsx2/gui/AppCoreThread.cpp index cf02c7e826..dab97ce2e1 100644 --- a/pcsx2/gui/AppCoreThread.cpp +++ b/pcsx2/gui/AppCoreThread.cpp @@ -305,6 +305,7 @@ void AppCoreThread::ApplySettings( const Pcsx2Config& src ) wxString gamePatch; wxString gameFixes; wxString gameCheats; + wxString gameWsHacks; wxString gameName; wxString gameCompat; @@ -349,13 +350,21 @@ void AppCoreThread::ApplySettings( const Pcsx2Config& src ) gameName = L"Booting PS2 BIOS... "; } + ResetCheatsCount(); if (EmuConfig.EnableCheats) { - if (int cheats = InitCheats(gameCRC)) { + if (int cheats = LoadCheats(gameCRC, L"cheats", L"Cheats")) { gameCheats.Printf(L" [%d Cheats]", cheats); } } - Console.SetTitle(gameName+gameSerial+gameCompat+gameFixes+gamePatch+gameCheats); + // FIXME: we should have a widescreen hacks config + if (EmuConfig.EnableCheats) { + if (int cheats = LoadCheats(gameCRC, L"cheats_ws", L"Widescreen hacks")) { + gameWsHacks.Printf(L" [%d WS hacks]", cheats); + } + } + + Console.SetTitle(gameName+gameSerial+gameCompat+gameFixes+gamePatch+gameCheats+gameWsHacks); // Re-entry guard protects against cases where code wants to manually set core settings // which are not part of g_Conf. The subsequent call to apply g_Conf settings (which is diff --git a/pcsx2/gui/MemoryCardFile.cpp b/pcsx2/gui/MemoryCardFile.cpp index 57662bddfd..a5908934a7 100644 --- a/pcsx2/gui/MemoryCardFile.cpp +++ b/pcsx2/gui/MemoryCardFile.cpp @@ -64,6 +64,7 @@ public: s32 IsPresent ( uint slot ); void GetSizeInfo( uint slot, PS2E_McdSizeInfo& outways ); + bool IsPSX ( uint slot ); s32 Read ( uint slot, u8 *dest, u32 adr, int size ); s32 Save ( uint slot, const u8 *src, u32 adr, int size ); s32 EraseBlock ( uint slot, u32 adr ); @@ -266,6 +267,11 @@ void FileMemoryCard::GetSizeInfo( uint slot, PS2E_McdSizeInfo& outways ) outways.McdSizeInSectors = 0x4000; } +bool FileMemoryCard::IsPSX( uint slot ) +{ + return m_file[slot].Length() == 0x20000; +} + s32 FileMemoryCard::Read( uint slot, u8 *dest, u32 adr, int size ) { wxFFile& mcfp( m_file[slot] ); @@ -379,6 +385,11 @@ static void PS2E_CALLBACK FileMcd_GetSizeInfo( PS2E_THISPTR thisptr, uint port, thisptr->impl.GetSizeInfo( FileMcd_ConvertToSlot( port, slot ), *outways ); } +static bool PS2E_CALLBACK FileMcd_IsPSX( PS2E_THISPTR thisptr, uint port, uint slot ) +{ + return thisptr->impl.IsPSX( FileMcd_ConvertToSlot( port, slot ) ); +} + static s32 PS2E_CALLBACK FileMcd_Read( PS2E_THISPTR thisptr, uint port, uint slot, u8 *dest, u32 adr, int size ) { return thisptr->impl.Read( FileMcd_ConvertToSlot( port, slot ), dest, adr, size ); @@ -408,6 +419,7 @@ Component_FileMcd::Component_FileMcd() api.McdIsPresent = FileMcd_IsPresent; api.McdGetSizeInfo = FileMcd_GetSizeInfo; + api.McdIsPSX = FileMcd_IsPSX; api.McdRead = FileMcd_Read; api.McdSave = FileMcd_Save; api.McdEraseBlock = FileMcd_EraseBlock; diff --git a/pcsx2/gui/Panels/MemoryCardListPanel.cpp b/pcsx2/gui/Panels/MemoryCardListPanel.cpp index 3269ab4dd6..728285abf7 100644 --- a/pcsx2/gui/Panels/MemoryCardListPanel.cpp +++ b/pcsx2/gui/Panels/MemoryCardListPanel.cpp @@ -35,13 +35,18 @@ using namespace Panels; static bool IsMcdFormatted( wxFFile& fhand ) { + static const char formatted_psx[] = "MC"; static const char formatted_string[] = "Sony PS2 Memory Card Format"; static const int fmtstrlen = sizeof( formatted_string )-1; char dest[fmtstrlen]; fhand.Read( dest, fmtstrlen ); - return memcmp( formatted_string, dest, fmtstrlen ) == 0; + + bool formatted = memcmp( formatted_string, dest, fmtstrlen ) == 0; + if(!formatted) formatted = memcmp( formatted_psx, dest, 2 ) == 0; + + return formatted; } //sets IsPresent if the file is valid, and derived properties (filename, formatted, size, etc) @@ -56,7 +61,10 @@ bool EnumerateMemoryCard( McdSlotItem& dest, const wxFileName& filename, const w //DevCon.WriteLn( fullpath ); wxFFile mcdFile( fullpath ); if( !mcdFile.IsOpened() ) return false; // wx should log the error for us. - if( mcdFile.Length() < (1024*528) ) + + wxFileOffset length = mcdFile.Length(); + + if( length < (1024*528) && length != 0x20000 ) { Console.Warning( "... MemoryCard appears to be truncated. Ignoring." ); return false; @@ -67,7 +75,14 @@ bool EnumerateMemoryCard( McdSlotItem& dest, const wxFileName& filename, const w if( filename.GetFullPath() == (basePath+filename.GetFullName()).GetFullPath() ) dest.Filename = filename.GetFullName(); - dest.SizeInMB = (uint)(mcdFile.Length() / (1024 * 528 * 2)); + dest.SizeInMB = (uint)(length / (1024 * 528 * 2)); + + if(length == 0x20000) + { + dest.IsPSX = true; // PSX memcard; + dest.SizeInMB = 1; // MegaBIT + } + dest.IsFormatted = IsMcdFormatted( mcdFile ); filename.GetTimes( NULL, &dest.DateModified, &dest.DateCreated ); @@ -1082,6 +1097,8 @@ void Panels::MemoryCardListPanel_Simple::ReadFilesAtMcdFolder(){ wxArrayString memcardList; wxDir::GetAllFiles(m_FolderPicker->GetPath().ToString(), &memcardList, L"*.ps2", wxDIR_FILES); + wxDir::GetAllFiles(m_FolderPicker->GetPath().ToString(), &memcardList, L"*.mcd", wxDIR_FILES); + wxDir::GetAllFiles(m_FolderPicker->GetPath().ToString(), &memcardList, L"*.mcr", wxDIR_FILES); for(uint i = 0; i < memcardList.size(); i++) { McdSlotItem currentCardFile; diff --git a/pcsx2/gui/Panels/MemoryCardListView.cpp b/pcsx2/gui/Panels/MemoryCardListView.cpp index 0590ab616e..40edf7ffba 100644 --- a/pcsx2/gui/Panels/MemoryCardListView.cpp +++ b/pcsx2/gui/Panels/MemoryCardListView.cpp @@ -76,6 +76,7 @@ enum McdColumnType_Simple McdColS_Filename, McdColS_Size, McdColS_Formatted, + McdColS_Type, McdColS_DateModified, McdColS_DateCreated, McdColS_Count @@ -102,13 +103,14 @@ const ListViewColumnInfo& MemoryCardListView_Simple::GetDefaultColumnInfo( uint { static const ListViewColumnInfo columns[] = { - { _("PS2 Port") , 154 , wxLIST_FORMAT_LEFT }, + { _("PS2 Port") , 170 , wxLIST_FORMAT_LEFT }, //{ _("Port status") , 80 , wxLIST_FORMAT_LEFT }, - { _("Card (file) name") , 126 , wxLIST_FORMAT_LEFT }, - { _("Card size") , 60 , wxLIST_FORMAT_LEFT }, + { _("Card (file) name") , 145 , wxLIST_FORMAT_LEFT }, + { _("Card size") , 65 , wxLIST_FORMAT_LEFT }, { _("Formatted") , 80 , wxLIST_FORMAT_LEFT }, - { _("Last Modified"), 85 , wxLIST_FORMAT_LEFT }, - { _("Created on") , 85 , wxLIST_FORMAT_LEFT }, + { _("Type") , 60 , wxLIST_FORMAT_LEFT }, + { _("Last Modified"), 90 , wxLIST_FORMAT_LEFT }, + { _("Created on") , 90 , wxLIST_FORMAT_LEFT }, }; pxAssertDev( idx < ArraySize(columns), "ListView column index is out of bounds." ); @@ -152,8 +154,9 @@ wxString MemoryCardListView_Simple::OnGetItemText(long item, long column) const return prefix + res; } */ - case McdColS_Size: return prefix + ( !it.IsPresent ? L"" : pxsFmt( L"%u MB", it.SizeInMB ) ); + case McdColS_Size: return prefix + ( !it.IsPresent ? L"" : (it.IsPSX? pxsFmt( L"%u MBit", it.SizeInMB ) : pxsFmt( L"%u MiB", it.SizeInMB )) ); case McdColS_Formatted: return prefix + ( !it.IsPresent ? L"" : ( it.IsFormatted ? _("Yes") : _("No")) ); + case McdColS_Type: return prefix + ( !it.IsPresent ? L"" : ( it.IsPSX? _("PSX") : _("PS2")) ); case McdColS_DateModified: return prefix + ( !it.IsPresent ? L"" : it.DateModified.FormatDate() ); case McdColS_DateCreated: return prefix + ( !it.IsPresent ? L"" : it.DateCreated.FormatDate() ); diff --git a/pcsx2/gui/Panels/MemoryCardPanels.h b/pcsx2/gui/Panels/MemoryCardPanels.h index f462007286..826ae38945 100644 --- a/pcsx2/gui/Panels/MemoryCardPanels.h +++ b/pcsx2/gui/Panels/MemoryCardPanels.h @@ -44,6 +44,7 @@ struct McdSlotItem //Only meaningful when IsPresent==true (a file exists for this item): wxFileName Filename; // full pathname bool IsFormatted; + bool IsPSX; // False: PS2 memory card, True: PSX memory card uint SizeInMB; // size, in megabytes! wxDateTime DateCreated; wxDateTime DateModified; @@ -62,6 +63,7 @@ struct McdSlotItem { Slot = -1; + IsPSX = false; IsPresent = false; IsEnabled = false; } diff --git a/pcsx2/windows/VCprojects/pcsx2_vs11.vcxproj b/pcsx2/windows/VCprojects/pcsx2_vs11.vcxproj index dbd787ddf0..0ca74c6f0f 100644 --- a/pcsx2/windows/VCprojects/pcsx2_vs11.vcxproj +++ b/pcsx2/windows/VCprojects/pcsx2_vs11.vcxproj @@ -868,39 +868,39 @@ - + {26511268-2902-4997-8421-ecd7055f9e28} false - + {7e9b2be7-cec3-4f14-847b-0ab8d562fb86} false - + {0e231fb1-f3c9-4724-accb-de8bcb3c089e} false - + {48ad7e0a-25b1-4974-a1e3-03f8c438d34f} false - + {0318ba30-ef48-441a-9e10-dc85efae39f0} false - + {2f6c0388-20cb-4242-9f6c-a6ebb6a83f47} false - + {4639972e-424e-4e13-8b07-ca403c481346} false - + {a51123f5-9505-4eae-85e7-d320290a272c} false - + {677b7d11-d5e1-40b3-88b1-9a4df83d2213} false diff --git a/pcsx2/x86/microVU.cpp b/pcsx2/x86/microVU.cpp index 8ec9b1f0fa..f88c6be5b9 100644 --- a/pcsx2/x86/microVU.cpp +++ b/pcsx2/x86/microVU.cpp @@ -327,6 +327,12 @@ void recMicroVU0::Execute(u32 cycles) { // woody hangs if too high on sVU (untested on mVU) // Edit: Need to test this again, if anyone ever has a "Woody" game :p ((mVUrecCall)microVU0.startFunct)(VU0.VI[REG_TPC].UL, cycles); + + if(microVU0.regs().flags & 0x4) + { + microVU0.regs().flags &= ~0x4; + hwIntcIrq(6); + } } void recMicroVU1::Execute(u32 cycles) { pxAssert(m_Reserved); // please allocate me first! :| @@ -335,6 +341,12 @@ void recMicroVU1::Execute(u32 cycles) { if(!(VU0.VI[REG_VPU_STAT].UL & 0x100)) return; } ((mVUrecCall)microVU1.startFunct)(VU1.VI[REG_TPC].UL, cycles); + + if(microVU1.regs().flags & 0x4) + { + microVU1.regs().flags &= ~0x4; + hwIntcIrq(7); + } } void recMicroVU0::Clear(u32 addr, u32 size) { diff --git a/pcsx2/x86/microVU_Analyze.inl b/pcsx2/x86/microVU_Analyze.inl index 7fd22f544e..ed32f3f359 100644 --- a/pcsx2/x86/microVU_Analyze.inl +++ b/pcsx2/x86/microVU_Analyze.inl @@ -460,12 +460,21 @@ __ri int mVUbranchCheck(mV) { mVUlow.badBranch = 1; incPC(2); mVUlow.evilBranch = 1; - mVUregs.blockType = 2; + + if(mVUlow.branch == 2 || mVUlow.branch == 10) //Needs linking, we can only guess this if the next is not conditional + { + if(branchType <= 2 && branchType >= 9) //First branch is not conditional so we know what the link will be + { //So we can let the existing evil block do its thing! We know where to get the addr :) + mVUregs.blockType = 2; + } //Else it is conditional, so we need to do some nasty processing later in microVU_Branch.inl + } + else mVUregs.blockType = 2; //Second branch doesn't need linking, so can let it run its evil block course (MGS2 for testing) + mVUregs.needExactMatch |= 7; // This might not be necessary, but w/e... mVUregs.flagInfo = 0; mVUregs.fullFlags0 = 0; mVUregs.fullFlags1 = 0; - DevCon.Warning("microVU%d: %s in %s delay slot! [%04x]", mVU.index, + DevCon.Warning("microVU%d: %s in %s delay slot! [%04x] - If game broken report to PCSX2 Team", mVU.index, branchSTR[mVUlow.branch&0xf], branchSTR[branchType&0xf], xPC); return 1; } diff --git a/pcsx2/x86/microVU_Branch.inl b/pcsx2/x86/microVU_Branch.inl index f784d01f8e..b6e2a2e99b 100644 --- a/pcsx2/x86/microVU_Branch.inl +++ b/pcsx2/x86/microVU_Branch.inl @@ -18,7 +18,7 @@ extern bool doEarlyExit (microVU& mVU); extern void mVUincCycles(microVU& mVU, int x); extern void* mVUcompile (microVU& mVU, u32 startPC, uptr pState); - +extern void* mVUcompileSingleInstruction(microVU& mVU, u32 startPC, uptr pState, microFlagCycles& mFC); __fi int getLastFlagInst(microRegInfo& pState, int* xFlag, int flagType, int isEbit) { if (isEbit) return findFlagInst(xFlag, 0x7fffffff); if (pState.needExactMatch & (1<pState, mFC->xStatus, 0, isEbit); + int fMac = getLastFlagInst(mVUpBlock->pState, mFC->xMac, 1, isEbit); + int fClip = getLastFlagInst(mVUpBlock->pState, mFC->xClip, 2, isEbit); + int qInst = 0; + int pInst = 0; + microBlock stateBackup; + memcpy(&stateBackup, &mVUregs, sizeof(mVUregs)); //backup the state, it's about to get screwed with. + + mVU.regAlloc->TDwritebackAll(); //Writing back ok, invalidating early kills the rec, so don't do it :P + + if (isEbit) { + /*memzero(mVUinfo); + memzero(mVUregsTemp);*/ + mVUincCycles(mVU, 100); // Ensures Valid P/Q instances (And sets all cycle data to 0) + mVUcycles -= 100; + qInst = mVU.q; + pInst = mVU.p; + if (mVUinfo.doDivFlag) { + sFLAG.doFlag = 1; + sFLAG.write = fStatus; + mVUdivSet(mVU); + } + //Run any pending XGKick, providing we've got to it. + if (mVUinfo.doXGKICK && xPC >= mVUinfo.XGKICKPC) { mVU_XGKICK_DELAY(mVU, 1); } + if (doEarlyExit(mVU)) { + if (!isVU1) xCALL(mVU0clearlpStateJIT); + else xCALL(mVU1clearlpStateJIT); + } + } + + // Save P/Q Regs + if (qInst) { xPSHUF.D(xmmPQ, xmmPQ, 0xe5); } + xMOVSS(ptr32[&mVU.regs().VI[REG_Q].UL], xmmPQ); + if (isVU1) { + xPSHUF.D(xmmPQ, xmmPQ, pInst ? 3 : 2); + xMOVSS(ptr32[&mVU.regs().VI[REG_P].UL], xmmPQ); + } + + // Save Flag Instances + xMOV(ptr32[&mVU.regs().VI[REG_STATUS_FLAG].UL], getFlagReg(fStatus)); + mVUallocMFLAGa(mVU, gprT1, fMac); + mVUallocCFLAGa(mVU, gprT2, fClip); + xMOV(ptr32[&mVU.regs().VI[REG_MAC_FLAG].UL], gprT1); + xMOV(ptr32[&mVU.regs().VI[REG_CLIP_FLAG].UL], gprT2); + + if (isEbit || isVU1) { // Clear 'is busy' Flags + if (!mVU.index || !THREAD_VU1) { + xAND(ptr32[&VU0.VI[REG_VPU_STAT].UL], (isVU1 ? ~0x100 : ~0x001)); // VBS0/VBS1 flag + xAND(ptr32[&mVU.getVifRegs().stat], ~VIF1_STAT_VEW); // Clear VU 'is busy' signal for vif + } + } + + if (isEbit != 2) { // Save PC, and Jump to Exit Point + xMOV(ptr32[&mVU.regs().VI[REG_TPC].UL], xPC); + xJMP(mVU.exitFunct); + } + memcpy(&mVUregs, &stateBackup, sizeof(mVUregs)); //Restore the state for the rest of the recompile +} + void mVUendProgram(mV, microFlagCycles* mFC, int isEbit) { int fStatus = getLastFlagInst(mVUpBlock->pState, mFC->xStatus, 0, isEbit); @@ -116,6 +177,15 @@ void normJumpCompile(mV, microFlagCycles& mFC, bool isEvilJump) { if (doJumpCaching) xMOV(gprT3, (uptr)mVUpBlock); else xMOV(gprT3, (uptr)&mVUpBlock->pStateEnd); + if(mVUup.eBit && isEvilJump)// E-bit EvilJump + { + //Xtreme G 3 does 2 conditional jumps, the first contains an E Bit on the first instruction + //So if it is taken, you need to end the program, else you get infinite loops. + mVUendProgram(mVU, &mFC, 2); + xMOV(ptr32[&mVU.regs().VI[REG_TPC].UL], gprT2); + xJMP(mVU.exitFunct); + } + if (!mVU.index) xCALL(mVUcompileJIT<0>); //(u32 startPC, uptr pState) else xCALL(mVUcompileJIT<1>); @@ -125,19 +195,144 @@ void normJumpCompile(mV, microFlagCycles& mFC, bool isEvilJump) { void normBranch(mV, microFlagCycles& mFC) { - // E-bit Branch - if (mVUup.eBit) { iPC = branchAddr/4; mVUendProgram(mVU, &mFC, 1); return; } + // E-bit or T-Bit or D-Bit Branch + if (mVUup.dBit && doDBitHandling) + { + u32 tempPC = iPC; + xTEST(ptr32[&VU0.VI[REG_FBRST].UL], (isVU1 ? 0x400 : 0x4)); + xForwardJump32 eJMP(Jcc_Zero); + xOR(ptr32[&VU0.VI[REG_VPU_STAT].UL], (isVU1 ? 0x200 : 0x2)); + xOR(ptr32[&mVU.regs().flags], VUFLAG_INTCINTERRUPT); + iPC = branchAddr/4; + mVUDTendProgram(mVU, &mFC, 1); + eJMP.SetTarget(); + iPC = tempPC; + } + if (mVUup.tBit) + { + u32 tempPC = iPC; + xTEST(ptr32[&VU0.VI[REG_FBRST].UL], (isVU1 ? 0x800 : 0x8)); + xForwardJump32 eJMP(Jcc_Zero); + xOR(ptr32[&VU0.VI[REG_VPU_STAT].UL], (isVU1 ? 0x400 : 0x4)); + xOR(ptr32[&mVU.regs().flags], VUFLAG_INTCINTERRUPT); + iPC = branchAddr/4; + mVUDTendProgram(mVU, &mFC, 1); + eJMP.SetTarget(); + iPC = tempPC; + } + if (mVUup.eBit) { if(mVUlow.badBranch) DevCon.Warning("End on evil Unconditional branch! - Not implemented! - If game broken report to PCSX2 Team"); iPC = branchAddr/4; mVUendProgram(mVU, &mFC, 1); return; } + + if(mVUlow.badBranch) + { + u32 badBranchAddr = branchAddr+8; + incPC(3); + if(mVUlow.branch == 2 || mVUlow.branch == 10) //Delay slot branch needs linking + { + DevCon.Warning("Found %s in delay slot, linking - If game broken report to PCSX2 Team", mVUlow.branch == 2 ? "BAL" : "JALR"); + xMOV(gprT3, badBranchAddr); + xSHR(gprT3, 3); + mVUallocVIb(mVU, gprT3, _It_); + + } + incPC(-3); + } // Normal Branch mVUsetupBranch(mVU, mFC); normBranchCompile(mVU, branchAddr); } +//Messy handler warning!! +//This handles JALR/BAL in the delay slot of a conditional branch. We do this because the normal handling +//Doesn't seem to work properly, even if the link is made to the correct address, so we do it manually instead. +//Normally EvilBlock handles all this stuff, but something to do with conditionals and links don't quite work right :/ +void condJumpProcessingEvil(mV, microFlagCycles& mFC, int JMPcc) { + + u32 bPC = iPC-1; // mVUcompile can modify iPC, mVUpBlock, and mVUregs so back them up + microBlock* pBlock = mVUpBlock; + u32 badBranchAddr; + iPC = bPC-2; + setCode(); + badBranchAddr = branchAddr; + + xCMP(ptr16[&mVU.branch], 0); + + xForwardJump32 eJMP(xInvertCond((JccComparisonType)JMPcc)); + + mVUcompileSingleInstruction(mVU, badBranchAddr, (uptr)&mVUregs, mFC); + + xMOV(gprT3, badBranchAddr+8); + iPC = bPC; + setCode(); + xSHR(gprT3, 3); + mVUallocVIb(mVU, gprT3, _It_); //Link to branch addr + 8 + + normJumpCompile(mVU, mFC, true); //Compile evil branch, just in time! + + eJMP.SetTarget(); + + incPC(2); // Point to delay slot of evil Branch (as the original branch isn't taken) + mVUcompileSingleInstruction(mVU, xPC, (uptr)&mVUregs, mFC); + + xMOV(gprT3, xPC); + iPC = bPC; + setCode(); + xSHR(gprT3, 3); + mVUallocVIb(mVU, gprT3, _It_); + + normJumpCompile(mVU, mFC, true); //Compile evil branch, just in time! + +} void condBranch(mV, microFlagCycles& mFC, int JMPcc) { mVUsetupBranch(mVU, mFC); + + if (mVUup.tBit) + { + u32 tempPC = iPC; + xTEST(ptr32[&VU0.VI[REG_FBRST].UL], (isVU1 ? 0x800 : 0x8)); + xForwardJump32 eJMP(Jcc_Zero); + xOR(ptr32[&VU0.VI[REG_VPU_STAT].UL], (isVU1 ? 0x400 : 0x4)); + xOR(ptr32[&mVU.regs().flags], VUFLAG_INTCINTERRUPT); + mVUDTendProgram(mVU, &mFC, 2); + xCMP(ptr16[&mVU.branch], 0); + xForwardJump8 tJMP((JccComparisonType)JMPcc); + incPC(4); // Set PC to First instruction of Non-Taken Side + xMOV(ptr32[&mVU.regs().VI[REG_TPC].UL], xPC); + xJMP(mVU.exitFunct); + eJMP.SetTarget(); + incPC(-4); // Go Back to Branch Opcode to get branchAddr + iPC = branchAddr/4; + xMOV(ptr32[&mVU.regs().VI[REG_TPC].UL], xPC); + xJMP(mVU.exitFunct); + tJMP.SetTarget(); + iPC = tempPC; + } + if (mVUup.dBit && doDBitHandling) + { + u32 tempPC = iPC; + xTEST(ptr32[&VU0.VI[REG_FBRST].UL], (isVU1 ? 0x400 : 0x4)); + xForwardJump32 eJMP(Jcc_Zero); + xOR(ptr32[&VU0.VI[REG_VPU_STAT].UL], (isVU1 ? 0x200 : 0x2)); + xOR(ptr32[&mVU.regs().flags], VUFLAG_INTCINTERRUPT); + mVUDTendProgram(mVU, &mFC, 2); + xCMP(ptr16[&mVU.branch], 0); + xForwardJump8 dJMP((JccComparisonType)JMPcc); + incPC(4); // Set PC to First instruction of Non-Taken Side + xMOV(ptr32[&mVU.regs().VI[REG_TPC].UL], xPC); + xJMP(mVU.exitFunct); + dJMP.SetTarget(); + incPC(-4); // Go Back to Branch Opcode to get branchAddr + iPC = branchAddr/4; + xMOV(ptr32[&mVU.regs().VI[REG_TPC].UL], xPC); + xJMP(mVU.exitFunct); + eJMP.SetTarget(); + iPC = tempPC; + } xCMP(ptr16[&mVU.branch], 0); incPC(3); if (mVUup.eBit) { // Conditional Branch With E-Bit Set + if(mVUlow.evilBranch) DevCon.Warning("End on evil branch! - Not implemented! - If game broken report to PCSX2 Team"); + mVUendProgram(mVU, &mFC, 2); xForwardJump8 eJMP((JccComparisonType)JMPcc); incPC(1); // Set PC to First instruction of Non-Taken Side @@ -151,6 +346,17 @@ void condBranch(mV, microFlagCycles& mFC, int JMPcc) { return; } else { // Normal Conditional Branch + + if(mVUlow.evilBranch) //We are dealing with an evil evil block, so we need to process this slightly differently + { + + if(mVUlow.branch == 10 || mVUlow.branch == 2) //Evil branch is a jump of some measure + { + //Because of how it is linked, we need to make sure the target is recompiled if taken + condJumpProcessingEvil(mVU, mFC, JMPcc); + return; + } + } microBlock* bBlock; incPC2(1); // Check if Branch Non-Taken Side has already been recompiled blockCreate(iPC/2); @@ -190,7 +396,46 @@ void normJump(mV, microFlagCycles& mFC) { normBranchCompile(mVU, jumpAddr); return; } + if(mVUlow.badBranch) + { + incPC(3); + if(mVUlow.branch == 2 || mVUlow.branch == 10) //Delay slot BAL needs linking, only need to do BAL here, JALR done earlier + { + DevCon.Warning("Found %x in delay slot, linking - If game broken report to PCSX2 Team", mVUlow.branch == 2 ? "BAL" : "JALR"); + incPC(-2); + mVUallocVIa(mVU, gprT1, _Is_); + xADD(gprT1, 8); + xSHR(gprT1, 3); + incPC(2); + mVUallocVIb(mVU, gprT1, _It_); + } + incPC(-3); + } + if (mVUup.dBit && doDBitHandling) + { + xTEST(ptr32[&VU0.VI[REG_FBRST].UL], (isVU1 ? 0x400 : 0x4)); + xForwardJump32 eJMP(Jcc_Zero); + xOR(ptr32[&VU0.VI[REG_VPU_STAT].UL], (isVU1 ? 0x200 : 0x2)); + xOR(ptr32[&mVU.regs().flags], VUFLAG_INTCINTERRUPT); + mVUDTendProgram(mVU, &mFC, 2); + xMOV(gprT1, ptr32[&mVU.branch]); + xMOV(ptr32[&mVU.regs().VI[REG_TPC].UL], gprT1); + xJMP(mVU.exitFunct); + eJMP.SetTarget(); + } + if (mVUup.tBit) + { + xTEST(ptr32[&VU0.VI[REG_FBRST].UL], (isVU1 ? 0x800 : 0x8)); + xForwardJump32 eJMP(Jcc_Zero); + xOR(ptr32[&VU0.VI[REG_VPU_STAT].UL], (isVU1 ? 0x400 : 0x4)); + xOR(ptr32[&mVU.regs().flags], VUFLAG_INTCINTERRUPT); + mVUDTendProgram(mVU, &mFC, 2); + xMOV(gprT1, ptr32[&mVU.branch]); + xMOV(ptr32[&mVU.regs().VI[REG_TPC].UL], gprT1); + xJMP(mVU.exitFunct); + eJMP.SetTarget(); + } if (mVUup.eBit) { // E-bit Jump mVUendProgram(mVU, &mFC, 2); xMOV(gprT1, ptr32[&mVU.branch]); diff --git a/pcsx2/x86/microVU_Compile.inl b/pcsx2/x86/microVU_Compile.inl index ba4ba6133c..0191e4193a 100644 --- a/pcsx2/x86/microVU_Compile.inl +++ b/pcsx2/x86/microVU_Compile.inl @@ -19,8 +19,8 @@ // Messages Called at Execution Time... //------------------------------------------------------------------ -static void __fc mVUbadOp0 (u32 prog, u32 pc) { Console.Error("microVU0 Warning: Exiting... Block started with illegal opcode. [%04x] [%03d]", pc, prog); } -static void __fc mVUbadOp1 (u32 prog, u32 pc) { Console.Error("microVU1 Warning: Exiting... Block started with illegal opcode. [%04x] [%03d]", pc, prog); } +static void __fc mVUbadOp0 (u32 prog, u32 pc) { Console.Error("microVU0 Warning: Exiting... Block contains an illegal opcode. [%04x] [%03d]", pc, prog); } +static void __fc mVUbadOp1 (u32 prog, u32 pc) { Console.Error("microVU1 Warning: Exiting... Block contains an illegal opcode. [%04x] [%03d]", pc, prog); } static void __fc mVUwarning0(u32 prog, u32 pc) { Console.Error("microVU0 Warning: Exiting from Possible Infinite Loop [%04x] [%03d]", pc, prog); } static void __fc mVUwarning1(u32 prog, u32 pc) { Console.Error("microVU1 Warning: Exiting from Possible Infinite Loop [%04x] [%03d]", pc, prog); } static void __fc mVUprintPC1(u32 pc) { Console.WriteLn("Block Start PC = 0x%04x", pc); } @@ -160,15 +160,21 @@ void mVUexecuteInstruction(mV) { // If 1st op in block is a bad opcode, then don't compile rest of block (Dawn of Mana Level 2) __fi void mVUcheckBadOp(mV) { - if (mVUinfo.isBadOp && mVUcount == 0) { + + // The BIOS writes upper and lower NOPs in reversed slots (bug) + //So to prevent spamming we ignore these, however its possible the real VU will bomb out if + //this happens, so we will bomb out without warning. + if (mVUinfo.isBadOp && mVU.code != 0x8000033c) { + mVUinfo.isEOB = true; - Console.Warning("microVU Warning: First Instruction of block contains illegal opcode..."); + DevCon.Warning("microVU Warning: Block contains an illegal opcode..."); + } } // Prints msg when exiting block early if 1st op was a bad opcode (Dawn of Mana Level 2) __fi void handleBadOp(mV, int count) { - if (mVUinfo.isBadOp && count == 0) { + if (mVUinfo.isBadOp) { mVUbackupRegs(mVU, true); xMOV(gprT2, mVU.prog.cur->idx); xMOV(gprT3, xPC); @@ -186,7 +192,8 @@ __ri void branchWarning(mV) { mVUlow.isNOP = 1; } else incPC(2); - if (mVUinfo.isBdelay) { // Check if VI Reg Written to on Branch Delay Slot Instruction + + if (mVUinfo.isBdelay && !mVUlow.evilBranch) { // Check if VI Reg Written to on Branch Delay Slot Instruction if (mVUlow.VI_write.reg && mVUlow.VI_write.used && !mVUlow.readFlags) { mVUlow.backupVI = 1; mVUregs.viBackUp = mVUlow.VI_write.reg; @@ -262,7 +269,7 @@ void mVUincCycles(mV, int x) { } if (mVUregs.xgkick) { calcCycles(mVUregs.xgkick, x); - if (!mVUregs.xgkick) { mVUinfo.doXGKICK = 1; } + if (!mVUregs.xgkick) { mVUinfo.doXGKICK = 1; mVUinfo.XGKICKPC = xPC;} } calcCycles(mVUregs.r, x); } @@ -373,9 +380,9 @@ void mVUtestCycles(microVU& mVU) { // This gets run at the start of every loop of mVU's first pass __fi void startLoop(mV) { - if (curI & _Mbit_) { DevCon.WriteLn (Color_Green, "microVU%d: M-bit set!", getIndex); } - if (curI & _Dbit_) { DevCon.WriteLn (Color_Green, "microVU%d: D-bit set!", getIndex); } - if (curI & _Tbit_) { DevCon.WriteLn (Color_Green, "microVU%d: T-bit set!", getIndex); } + if (curI & _Mbit_) { DevCon.WriteLn (Color_Green, "microVU%d: M-bit set! PC = %x", getIndex, xPC); } + if (curI & _Dbit_) { DevCon.WriteLn (Color_Green, "microVU%d: D-bit set! PC = %x", getIndex, xPC); } + if (curI & _Tbit_) { DevCon.WriteLn (Color_Green, "microVU%d: T-bit set! PC = %x", getIndex, xPC); } memzero(mVUinfo); memzero(mVUregsTemp); } @@ -406,7 +413,7 @@ __fi void mVUinitFirstPass(microVU& mVU, uptr pState, u8* thisPtr) { } mVUblock.x86ptrStart = thisPtr; mVUpBlock = mVUblocks[mVUstartPC/2]->add(&mVUblock); // Add this block to block manager - mVUregs.needExactMatch = /*(mVUregs.blockType||noFlagOpts)?7:*/0; // ToDo: Fix 1-Op block flag linking (MGS2:Demo/Sly Cooper) + mVUregs.needExactMatch = (mVUpBlock->pState.blockType)?7:0; // ToDo: Fix 1-Op block flag linking (MGS2:Demo/Sly Cooper) mVUregs.blockType = 0; mVUregs.viBackUp = 0; mVUregs.flagInfo = 0; @@ -420,6 +427,87 @@ __fi void mVUinitFirstPass(microVU& mVU, uptr pState, u8* thisPtr) { // Recompiler //------------------------------------------------------------------ +//This bastardized function is used when a linked branch is in a conditional delay slot. It's messy, it's horrible, but it works. +//Unfortunately linking the reg manually and using the normal evil block method seems to suck at this :/ +//If this is removed, test Evil Dead: Fistful of Boomstick (hangs going ingame), Mark of Kri (collision detection) +//and Tony Hawks Project 8 (graphics are half missing, requires Negative rounding when working) +void* mVUcompileSingleInstruction(microVU& mVU, u32 startPC, uptr pState, microFlagCycles& mFC) { + + u8* thisPtr = x86Ptr; + + // First Pass + iPC = startPC / 4; + + mVUbranch = 0; + incPC(1); + startLoop(mVU); + + mVUincCycles(mVU, 1); + mVUopU(mVU, 0); + mVUcheckBadOp(mVU); + if (curI & _Ebit_) { eBitPass1(mVU, branch); DevCon.Warning("E Bit on single instruction");} + if (curI & _DTbit_) { branch = 4; DevCon.Warning("D Bit on single instruction");} + if (curI & _Mbit_) { mVUup.mBit = 1; DevCon.Warning("M Bit on single instruction");} + if (curI & _Ibit_) { mVUlow.isNOP = 1; mVUup.iBit = 1; DevCon.Warning("I Bit on single instruction");} + else { incPC(-1); mVUopL(mVU, 0); incPC(1); } + mVUsetCycles(mVU); + mVUinfo.readQ = mVU.q; + mVUinfo.writeQ = !mVU.q; + mVUinfo.readP = mVU.p; + mVUinfo.writeP = !mVU.p; + mVUcount++; + mVUsetFlagInfo(mVU); + incPC(1); + + + mVUsetFlags(mVU, mFC); // Sets Up Flag instances + mVUoptimizePipeState(mVU); // Optimize the End Pipeline State for nicer Block Linking + mVUdebugPrintBlocks(mVU,0);// Prints Start/End PC of blocks executed, for debugging... + mVUtestCycles(mVU); // Update VU Cycles and Exit Early if Necessary + + // Second Pass + iPC = startPC / 4; + setCode(); + + if (mVUup.mBit) { xOR(ptr32[&mVU.regs().flags], VUFLAG_MFLAGSET); } + mVUexecuteInstruction(mVU); + + mVUincCycles(mVU, 1); //Just incase the is XGKick + if (mVUinfo.doXGKICK) { mVU_XGKICK_DELAY(mVU, 1); } + + return thisPtr; +} + +void mVUDoDBit(microVU& mVU, microFlagCycles* mFC) +{ + xTEST(ptr32[&VU0.VI[REG_FBRST].UL], (isVU1 ? 0x400 : 0x4)); + xForwardJump32 eJMP(Jcc_Zero); + xOR(ptr32[&VU0.VI[REG_VPU_STAT].UL], (isVU1 ? 0x200 : 0x2)); + xOR(ptr32[&mVU.regs().flags], VUFLAG_INTCINTERRUPT); + incPC(1); + mVUDTendProgram(mVU, mFC, 1); + incPC(-1); + eJMP.SetTarget(); +} + +void mVUDoTBit(microVU& mVU, microFlagCycles* mFC) +{ + xTEST(ptr32[&VU0.VI[REG_FBRST].UL], (isVU1 ? 0x800 : 0x8)); + xForwardJump32 eJMP(Jcc_Zero); + xOR(ptr32[&VU0.VI[REG_VPU_STAT].UL], (isVU1 ? 0x400 : 0x4)); + xOR(ptr32[&mVU.regs().flags], VUFLAG_INTCINTERRUPT); + incPC(1); + mVUDTendProgram(mVU, mFC, 1); + incPC(-1); + + eJMP.SetTarget(); +} + +void mVUSaveFlags(microVU& mVU,microFlagCycles &mFC, microFlagCycles &mFCBackup) +{ + memcpy_fast(&mFCBackup, &mFC, sizeof(microFlagCycles)); + mVUsetFlags(mVU, mFCBackup); // Sets Up Flag instances +} void* mVUcompile(microVU& mVU, u32 startPC, uptr pState) { microFlagCycles mFC; @@ -431,25 +519,31 @@ void* mVUcompile(microVU& mVU, u32 startPC, uptr pState) { mVUsetupRange(mVU, startPC, 1); // Setup Program Bounds/Range mVU.regAlloc->reset(); // Reset regAlloc mVUinitFirstPass(mVU, pState, thisPtr); - for(int branch = 0; mVUcount < endCount; mVUcount++) { + mVUbranch = 0; + for(int branch = 0; mVUcount < endCount;) { incPC(1); startLoop(mVU); mVUincCycles(mVU, 1); mVUopU(mVU, 0); mVUcheckBadOp(mVU); if (curI & _Ebit_) { eBitPass1(mVU, branch); } - if (curI & _DTbit_) { branch = 4; } + if (curI & _Mbit_) { mVUup.mBit = 1; } + if (curI & _Ibit_) { mVUlow.isNOP = 1; mVUup.iBit = 1; } else { incPC(-1); mVUopL(mVU, 0); incPC(1); } + if (curI & _Dbit_) { mVUup.dBit = 1; } + if (curI & _Tbit_) { mVUup.tBit = 1; } mVUsetCycles(mVU); mVUinfo.readQ = mVU.q; mVUinfo.writeQ = !mVU.q; mVUinfo.readP = mVU.p; mVUinfo.writeP = !mVU.p; - if (branch >= 2) { mVUinfo.isEOB = 1; if (branch == 3) { mVUinfo.isBdelay = 1; } mVUcount++; branchWarning(mVU); break; } + mVUcount++; + if (branch >= 2) { mVUinfo.isEOB = 1; if (branch == 3) { mVUinfo.isBdelay = 1; } branchWarning(mVU); break; } elif (branch == 1) { branch = 2; } if (mVUbranch) { mVUsetFlagInfo(mVU); eBitWarning(mVU); branch = 3; mVUbranch = 0; } + if (mVUinfo.isEOB) break; incPC(1); } @@ -471,6 +565,11 @@ void* mVUcompile(microVU& mVU, u32 startPC, uptr pState) { if (mVUinfo.isEOB) { handleBadOp(mVU, x); x = 0xffff; } if (mVUup.mBit) { xOR(ptr32[&mVU.regs().flags], VUFLAG_MFLAGSET); } mVUexecuteInstruction(mVU); + if(!mVUinfo.isBdelay && !mVUlow.branch) //T/D Bit on branch is handled after the branch, branch delay slots are executed. + { + if(mVUup.tBit) { mVUDoTBit(mVU, &mFC); } + else if(mVUup.dBit && doDBitHandling) { mVUDoDBit(mVU, &mFC); } + } if (mVUinfo.doXGKICK) { mVU_XGKICK_DELAY(mVU, 1); } if (isEvilBlock) { mVUsetupRange(mVU, xPC, 0); normJumpCompile(mVU, mFC, 1); return thisPtr; } else if (!mVUinfo.isBdelay) { incPC(1); } @@ -478,6 +577,7 @@ void* mVUcompile(microVU& mVU, u32 startPC, uptr pState) { mVUsetupRange(mVU, xPC, 0); mVUdebugPrintBlocks(mVU,1); incPC(-3); // Go back to branch opcode + switch (mVUlow.branch) { case 1: case 2: normBranch(mVU, mFC); return thisPtr; // B/BAL case 9: case 10: normJump (mVU, mFC); return thisPtr; // JR/JALR @@ -488,10 +588,11 @@ void* mVUcompile(microVU& mVU, u32 startPC, uptr pState) { case 7: condBranch(mVU, mFC, Jcc_Less); return thisPtr; // IBLTZ case 8: condBranch(mVU, mFC, Jcc_NotEqual); return thisPtr; // IBNEQ } + } } if ((x == endCount) && (x!=1)) { Console.Error("microVU%d: Possible infinite compiling loop!", mVU.index); } - + // E-bit End mVUsetupRange(mVU, xPC-8, 0); mVUendProgram(mVU, &mFC, 1); @@ -502,7 +603,7 @@ void* mVUcompile(microVU& mVU, u32 startPC, uptr pState) { __fi void* mVUentryGet(microVU& mVU, microBlockManager* block, u32 startPC, uptr pState) { microBlock* pBlock = block->search((microRegInfo*)pState); if (pBlock) return pBlock->x86ptrStart; - else return mVUcompile(mVU, startPC, pState); + else { return mVUcompile(mVU, startPC, pState);} } // Search for Existing Compiled Block (if found, return x86ptr; else, compile and return x86ptr) diff --git a/pcsx2/x86/microVU_IR.h b/pcsx2/x86/microVU_IR.h index ef7c24fef0..3f77da4504 100644 --- a/pcsx2/x86/microVU_IR.h +++ b/pcsx2/x86/microVU_IR.h @@ -112,6 +112,8 @@ struct microUpperOp { bool eBit; // Has E-bit set bool iBit; // Has I-bit set bool mBit; // Has M-bit set + bool tBit; // Has T-bit set + bool dBit; // Has D-bit set microVFreg VF_write; // VF Vectors written to by this instruction microVFreg VF_read[2]; // VF Vectors read by this instruction }; @@ -157,6 +159,7 @@ struct microOp { bool swapOps; // Run Lower Instruction before Upper Instruction bool backupVF; // Backup mVUlow.VF_write.reg, and restore it before the Upper Instruction is called bool doXGKICK; // Do XGKICK transfer on this instruction + u32 XGKICKPC; // The PC in which the XGKick has taken place, so if we break early (before it) we don run it. bool doDivFlag; // Transfer Div flag to Status Flag on this instruction int readQ; // Q instance for reading int writeQ; // Q instance for writing @@ -257,6 +260,18 @@ public: } } + void TDwritebackAll(bool clearState = 0) { + for(int i = 0; i < xmmTotal; i++) { + microMapXMM& mapX = xmmMap[xmm(i).Id]; + + if ((mapX.VFreg > 0) && mapX.xyzw) { // Reg was modified and not Temp or vf0 + if (mapX.VFreg == 33) xMOVSS(ptr32[&getVI(REG_I)], xmm(i)); + elif (mapX.VFreg == 32) mVUsaveReg(xmm(i), ptr[®s().ACC], mapX.xyzw, 1); + else mVUsaveReg(xmm(i), ptr[&getVF(mapX.VFreg)], mapX.xyzw, 1); + } + } + } + void clearReg(const xmm& reg) { clearReg(reg.Id); } void clearReg(int regId) { microMapXMM& clear = xmmMap[regId]; diff --git a/pcsx2/x86/microVU_Lower.inl b/pcsx2/x86/microVU_Lower.inl index d816b11fa3..f44e11501a 100644 --- a/pcsx2/x86/microVU_Lower.inl +++ b/pcsx2/x86/microVU_Lower.inl @@ -1246,6 +1246,7 @@ void condEvilBranch(mV, int JMPcc) { if (mVUlow.badBranch) { xMOV(ptr32[&mVU.branch], gprT1); xMOV(ptr32[&mVU.badBranch], branchAddrN); + xCMP(gprT1b, 0); xForwardJump8 cJMP((JccComparisonType)JMPcc); incPC(6); // Branch Not Taken Addr + 8 @@ -1260,6 +1261,9 @@ void condEvilBranch(mV, int JMPcc) { xMOV(gprT1, ptr32[&mVU.badBranch]); // Branch Not Taken xMOV(ptr32[&mVU.evilBranch], gprT1); cJMP.SetTarget(); + incPC(-2); + if(mVUlow.branch >= 9) DevCon.Warning("Conditional in JALR/JR delay slot - If game broken report to PCSX2 Team"); + incPC(2); } mVUop(mVU_B) { @@ -1277,10 +1281,14 @@ mVUop(mVU_BAL) { setBranchA(mX, 2, _It_); pass1 { mVUanalyzeNormBranch(mVU, _It_, 1); } pass2 { - xMOV(gprT1, bSaveAddr); - mVUallocVIb(mVU, gprT1, _It_); + if(!mVUlow.evilBranch) + { + xMOV(gprT1, bSaveAddr); + mVUallocVIb(mVU, gprT1, _It_); + } + if (mVUlow.badBranch) { xMOV(ptr32[&mVU.badBranch], branchAddrN); } - if (mVUlow.evilBranch) { xMOV(ptr32[&mVU.evilBranch], branchAddr); } + if (mVUlow.evilBranch) { xMOV(ptr32[&mVU.evilBranch], branchAddr);} mVU.profiler.EmitOp(opBAL); } pass3 { mVUlog("BAL vi%02d [%04x]", _Ft_, branchAddr, branchAddr); } @@ -1377,13 +1385,11 @@ void normJumpPass2(mV) { mVUallocVIa(mVU, gprT1, _Is_); xSHL(gprT1, 3); xAND(gprT1, mVU.microMemSize - 8); - if (!mVUlow.evilBranch) xMOV(ptr32[&mVU.branch], gprT1); - else xMOV(ptr32[&mVU.evilBranch], gprT1); - if (mVUlow.badBranch) { - xADD(gprT1, 8); - xAND(gprT1, mVU.microMemSize - 8); - xMOV(ptr32[&mVU.badBranch], gprT1); - } + + if (!mVUlow.evilBranch) { xMOV(ptr32[&mVU.branch], gprT1 ); } + else { xMOV(ptr32[&mVU.evilBranch], gprT1 ); } + //If delay slot is conditional, it uses badBranch to go to its target + if (mVUlow.badBranch) { xADD(gprT1, 8); xMOV(ptr32[&mVU.badBranch], gprT1); } } } @@ -1399,8 +1405,27 @@ mVUop(mVU_JALR) { pass1 { mVUanalyzeJump(mVU, _Is_, _It_, 1); } pass2 { normJumpPass2(mVU); - xMOV(gprT1, bSaveAddr); - mVUallocVIb(mVU, gprT1, _It_); + if(!mVUlow.evilBranch) + { + xMOV(gprT1, bSaveAddr); + mVUallocVIb(mVU, gprT1, _It_); + } + if(mVUlow.evilBranch) + { + incPC(-2); + if(mVUlow.branch >= 9) //Previous branch is a jump of some type so + //we need to take the branch address from the register it uses. + { + DevCon.Warning("Linking JALR from JALR/JR branch target! - If game broken report to PCSX2 Team"); + mVUallocVIa(mVU, gprT1, _Is_); + xADD(gprT1, 8); + xSHR(gprT1, 3); + incPC(2); + mVUallocVIb(mVU, gprT1, _It_); + } + else incPC(2); + } + mVU.profiler.EmitOp(opJALR); } pass3 { mVUlog("JALR vi%02d, [vi%02d]", _Ft_, _Fs_); } diff --git a/pcsx2/x86/microVU_Misc.h b/pcsx2/x86/microVU_Misc.h index bc05ddc53a..47886bf4fb 100644 --- a/pcsx2/x86/microVU_Misc.h +++ b/pcsx2/x86/microVU_Misc.h @@ -350,6 +350,12 @@ static const bool doJumpAsSameProgram = 0; // Set to 1 to treat jumps as same pr // constant recompilation problems in certain games. // Note: You MUST disable doJumpCaching if you enable this option. +// Handling of D-Bit in Micro Programs +static const bool doDBitHandling = 0; +// This flag shouldn't be enabled in released versions of games. Any games which +// need this method of pausing the VU should be using the T-Bit instead, however +// this could prove useful for VU debugging. + //------------------------------------------------------------------ // Speed Hacks (can cause infinite loops, SPS, Black Screens, etc...) //------------------------------------------------------------------ @@ -370,7 +376,7 @@ static const bool doJumpAsSameProgram = 0; // Set to 1 to treat jumps as same pr //------------------------------------------------------------------ // XG Kick Transfer Delay Amount -#define mVU_XGKICK_CYCLES ((CHECK_XGKICKHACK) ? 3 : 1) +#define mVU_XGKICK_CYCLES ((CHECK_XGKICKHACK) ? 6 : 1) // Its unknown at recompile time how long the xgkick transfer will take // so give it a value that makes games happy :) (SO3 is fine at 1 cycle delay) diff --git a/pcsx2/x86/microVU_Tables.inl b/pcsx2/x86/microVU_Tables.inl index 983af8332f..fdca6d772f 100644 --- a/pcsx2/x86/microVU_Tables.inl +++ b/pcsx2/x86/microVU_Tables.inl @@ -212,7 +212,7 @@ mVUop(mVUopU) { mVU_UPPER_OPCODE [ (mVU.code & 0x3f) ](mX); } // Gets Upper mVUop(mVUopL) { mVULOWER_OPCODE [ (mVU.code >> 25) ](mX); } // Gets Lower Opcode mVUop(mVUunknown) { pass1 { mVUinfo.isBadOp = true; } - pass2 { Console.Error("microVU%d: Unknown Micro VU opcode called (%x) [%04x]\n", getIndex, mVU.code, xPC); } + pass2 { if(mVU.code != 0x8000033c) Console.Error("microVU%d: Unknown Micro VU opcode called (%x) [%04x]\n", getIndex, mVU.code, xPC); } pass3 { mVUlog("Unknown", mVU.code); } } diff --git a/pcsx2_suite_2010.sln b/pcsx2_suite_2010.sln index 059889a74d..ec7cc5d3d7 100644 --- a/pcsx2_suite_2010.sln +++ b/pcsx2_suite_2010.sln @@ -114,6 +114,8 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "USBqemu", "plugins\USBqemu\ EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ZZOgl-cg", "plugins\zzogl-pg-cg\opengl\Win32\zerogsogl-cg.vcxproj", "{019773FA-2DAA-4C12-9511-BD2D4EB2A718}" EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "DEV9ghzdrk", "plugins\dev9ghzdrk\Win32\DEV9ghzdrk.vcxproj", "{BBE4E5FB-530A-4D18-A633-35AF0577B7F3}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug AVX|Win32 = Debug AVX|Win32 @@ -1221,6 +1223,39 @@ Global {019773FA-2DAA-4C12-9511-BD2D4EB2A718}.Release|Win32.ActiveCfg = Release|Win32 {019773FA-2DAA-4C12-9511-BD2D4EB2A718}.Release|Win32.Build.0 = Release|Win32 {019773FA-2DAA-4C12-9511-BD2D4EB2A718}.Release|x64.ActiveCfg = Release|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Debug AVX|Win32.ActiveCfg = Debug|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Debug AVX|Win32.Build.0 = Debug|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Debug AVX|x64.ActiveCfg = Debug|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Debug SSE2|Win32.ActiveCfg = Debug|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Debug SSE2|Win32.Build.0 = Debug|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Debug SSE2|x64.ActiveCfg = Debug|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Debug SSE4|Win32.ActiveCfg = Debug|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Debug SSE4|Win32.Build.0 = Debug|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Debug SSE4|x64.ActiveCfg = Debug|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Debug SSSE3|Win32.ActiveCfg = Debug|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Debug SSSE3|Win32.Build.0 = Debug|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Debug SSSE3|x64.ActiveCfg = Debug|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Debug|Win32.ActiveCfg = Debug|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Debug|Win32.Build.0 = Debug|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Debug|x64.ActiveCfg = Debug|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Devel|Win32.ActiveCfg = Debug|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Devel|Win32.Build.0 = Debug|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Devel|x64.ActiveCfg = Debug|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Release AVX|Win32.ActiveCfg = Release|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Release AVX|Win32.Build.0 = Release|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Release AVX|x64.ActiveCfg = Release|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Release SSE2|Win32.ActiveCfg = Release|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Release SSE2|Win32.Build.0 = Release|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Release SSE2|x64.ActiveCfg = Release|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Release SSE4|Win32.ActiveCfg = Release|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Release SSE4|Win32.Build.0 = Release|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Release SSE4|x64.ActiveCfg = Release|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Release SSSE3|Win32.ActiveCfg = Release|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Release SSSE3|Win32.Build.0 = Release|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Release SSSE3|x64.ActiveCfg = Release|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Release|Win32.ActiveCfg = Release|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Release|Win32.Build.0 = Release|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Release|x64.ActiveCfg = Release|Win32 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -1240,6 +1275,7 @@ Global {2D4E85B2-F47F-4D65-B091-701E5C031DAC} = {703FD00B-D7A0-41E3-BD03-CEC86B385DAF} {E613DA9F-41B4-4613-9911-E418EF5533BC} = {703FD00B-D7A0-41E3-BD03-CEC86B385DAF} {019773FA-2DAA-4C12-9511-BD2D4EB2A718} = {703FD00B-D7A0-41E3-BD03-CEC86B385DAF} + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3} = {703FD00B-D7A0-41E3-BD03-CEC86B385DAF} {E9B51944-7E6D-4BCD-83F2-7BBD5A46182D} = {78EBE642-7A4D-4EA7-86BE-5639C6646C38} {2F6C0388-20CB-4242-9F6C-A6EBB6A83F47} = {78EBE642-7A4D-4EA7-86BE-5639C6646C38} {F4EB4AB2-C595-4B05-8BC0-059024BC796C} = {78EBE642-7A4D-4EA7-86BE-5639C6646C38} diff --git a/pcsx2_suite_2012.sln b/pcsx2_suite_2012.sln index 6bfe50433f..a5f519a7ff 100644 --- a/pcsx2_suite_2012.sln +++ b/pcsx2_suite_2012.sln @@ -114,6 +114,8 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "USBqemu", "plugins\USBqemu\ EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ZZOgl-cg", "plugins\zzogl-pg-cg\opengl\Win32\zerogsogl-cg_vs11.vcxproj", "{019773FA-2DAA-4C12-9511-BD2D4EB2A718}" EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "DEV9ghzdrk", "plugins\dev9ghzdrk\Win32\DEV9ghzdrk_vs11.vcxproj", "{BBE4E5FB-530A-4D18-A633-35AF0577B7F3}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug AVX|Win32 = Debug AVX|Win32 @@ -1221,6 +1223,39 @@ Global {019773FA-2DAA-4C12-9511-BD2D4EB2A718}.Release|Win32.ActiveCfg = Release|Win32 {019773FA-2DAA-4C12-9511-BD2D4EB2A718}.Release|Win32.Build.0 = Release|Win32 {019773FA-2DAA-4C12-9511-BD2D4EB2A718}.Release|x64.ActiveCfg = Release|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Debug AVX|Win32.ActiveCfg = Debug|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Debug AVX|Win32.Build.0 = Debug|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Debug AVX|x64.ActiveCfg = Debug|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Debug SSE2|Win32.ActiveCfg = Debug|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Debug SSE2|Win32.Build.0 = Debug|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Debug SSE2|x64.ActiveCfg = Debug|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Debug SSE4|Win32.ActiveCfg = Debug|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Debug SSE4|Win32.Build.0 = Debug|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Debug SSE4|x64.ActiveCfg = Debug|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Debug SSSE3|Win32.ActiveCfg = Debug|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Debug SSSE3|Win32.Build.0 = Debug|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Debug SSSE3|x64.ActiveCfg = Debug|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Debug|Win32.ActiveCfg = Debug|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Debug|Win32.Build.0 = Debug|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Debug|x64.ActiveCfg = Debug|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Devel|Win32.ActiveCfg = Debug|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Devel|Win32.Build.0 = Debug|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Devel|x64.ActiveCfg = Debug|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Release AVX|Win32.ActiveCfg = Release|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Release AVX|Win32.Build.0 = Release|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Release AVX|x64.ActiveCfg = Release|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Release SSE2|Win32.ActiveCfg = Release|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Release SSE2|Win32.Build.0 = Release|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Release SSE2|x64.ActiveCfg = Release|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Release SSE4|Win32.ActiveCfg = Release|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Release SSE4|Win32.Build.0 = Release|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Release SSE4|x64.ActiveCfg = Release|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Release SSSE3|Win32.ActiveCfg = Release|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Release SSSE3|Win32.Build.0 = Release|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Release SSSE3|x64.ActiveCfg = Release|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Release|Win32.ActiveCfg = Release|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Release|Win32.Build.0 = Release|Win32 + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3}.Release|x64.ActiveCfg = Release|Win32 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -1240,6 +1275,7 @@ Global {2D4E85B2-F47F-4D65-B091-701E5C031DAC} = {703FD00B-D7A0-41E3-BD03-CEC86B385DAF} {E613DA9F-41B4-4613-9911-E418EF5533BC} = {703FD00B-D7A0-41E3-BD03-CEC86B385DAF} {019773FA-2DAA-4C12-9511-BD2D4EB2A718} = {703FD00B-D7A0-41E3-BD03-CEC86B385DAF} + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3} = {703FD00B-D7A0-41E3-BD03-CEC86B385DAF} {E9B51944-7E6D-4BCD-83F2-7BBD5A46182D} = {78EBE642-7A4D-4EA7-86BE-5639C6646C38} {2F6C0388-20CB-4242-9F6C-A6EBB6A83F47} = {78EBE642-7A4D-4EA7-86BE-5639C6646C38} {F4EB4AB2-C595-4B05-8BC0-059024BC796C} = {78EBE642-7A4D-4EA7-86BE-5639C6646C38} diff --git a/plugins/CDVDiso/src/Windows/CDVDiso_vs11.vcxproj b/plugins/CDVDiso/src/Windows/CDVDiso_vs11.vcxproj index 222ecfcfa4..e2ac007bfb 100644 --- a/plugins/CDVDiso/src/Windows/CDVDiso_vs11.vcxproj +++ b/plugins/CDVDiso/src/Windows/CDVDiso_vs11.vcxproj @@ -154,11 +154,11 @@ - + {f4eb4ab2-c595-4b05-8bc0-059024bc796c} false - + {2f6c0388-20cb-4242-9f6c-a6ebb6a83f47} false diff --git a/plugins/GSdx/GS.h b/plugins/GSdx/GS.h index abfdcdf2b2..ec414a3ac3 100644 --- a/plugins/GSdx/GS.h +++ b/plugins/GSdx/GS.h @@ -807,7 +807,8 @@ REG_END2 if(PSM == PSM_PSMT4) return TW > 7 || TH > 7; } - return (TBW << 6) < (1u << TW); + // The recast of TBW seems useless but it avoid tons of warning from GCC... + return ((uint32)TBW << 6u) < (1u << TW); } REG_END2 diff --git a/plugins/GSdx/GSClut.cpp b/plugins/GSdx/GSClut.cpp index f61dabcfe6..6c76c56d9f 100644 --- a/plugins/GSdx/GSClut.cpp +++ b/plugins/GSdx/GSClut.cpp @@ -30,7 +30,7 @@ GSClut::GSClut(GSLocalMemory* mem) { uint8* p = (uint8*)vmalloc(CLUT_ALLOC_SIZE, false); - m_clut = (uint16*)&p[0]; // 1k + 1k for buffer overruns (TODO: wrap CSM2 writes, too) + m_clut = (uint16*)&p[0]; // 1k + 1k for mirrored area simulating wrapping memory m_buff32 = (uint32*)&p[2048]; // 1k m_buff64 = (uint64*)&p[4096]; // 2k m_write.dirty = true; @@ -124,31 +124,43 @@ void GSClut::Write(const GIFRegTEX0& TEX0, const GIFRegTEXCLUT& TEXCLUT) m_read.dirty = true; (this->*m_wc[TEX0.CSM][TEX0.CPSM][TEX0.PSM])(TEX0, TEXCLUT); + + // Mirror write to other half of buffer to simulate wrapping memory + int offset = (TEX0.CSA & (TEX0.CPSM < PSM_PSMCT16 ? 15 : 31)) * 16; + if (TEX0.PSM == PSM_PSMT8 || TEX0.PSM == PSM_PSMT8H) + { + int size = TEX0.CPSM < PSM_PSMCT16 ? 512 : 256; + + memcpy(m_clut + 512 + offset, m_clut + offset, sizeof *m_clut * min(size, 512 - offset)); + memcpy(m_clut, m_clut + 512, sizeof *m_clut * max(0, size + offset - 512)); + } + else + { + int size = 16; + + memcpy(m_clut + 512 + offset, m_clut + offset, sizeof *m_clut * size); + if (TEX0.CPSM < PSM_PSMCT16) + memcpy(m_clut + 512 + 256 + offset, m_clut + 256 + offset, sizeof *m_clut * size); + } } void GSClut::WriteCLUT32_I8_CSM1(const GIFRegTEX0& TEX0, const GIFRegTEXCLUT& TEXCLUT) { ALIGN_STACK(32); - // ASSERT(TEX0.CSA == 0); // sfex - - WriteCLUT_T32_I8_CSM1((uint32*)m_mem->BlockPtr32(0, 0, TEX0.CBP, 1), m_clut); + WriteCLUT_T32_I8_CSM1((uint32*)m_mem->BlockPtr32(0, 0, TEX0.CBP, 1), m_clut + ((TEX0.CSA & 15) << 4)); } void GSClut::WriteCLUT32_I4_CSM1(const GIFRegTEX0& TEX0, const GIFRegTEXCLUT& TEXCLUT) { ALIGN_STACK(32); - ASSERT(TEX0.CSA < 16); - WriteCLUT_T32_I4_CSM1((uint32*)m_mem->BlockPtr32(0, 0, TEX0.CBP, 1), m_clut + ((TEX0.CSA & 15) << 4)); } void GSClut::WriteCLUT16_I8_CSM1(const GIFRegTEX0& TEX0, const GIFRegTEXCLUT& TEXCLUT) { - ASSERT(TEX0.CSA < 16); - - WriteCLUT_T16_I8_CSM1((uint16*)m_mem->BlockPtr16(0, 0, TEX0.CBP, 1), m_clut + ((TEX0.CSA & 15) << 4)); + WriteCLUT_T16_I8_CSM1((uint16*)m_mem->BlockPtr16(0, 0, TEX0.CBP, 1), m_clut + (TEX0.CSA << 4)); } void GSClut::WriteCLUT16_I4_CSM1(const GIFRegTEX0& TEX0, const GIFRegTEXCLUT& TEXCLUT) @@ -158,9 +170,7 @@ void GSClut::WriteCLUT16_I4_CSM1(const GIFRegTEX0& TEX0, const GIFRegTEXCLUT& TE void GSClut::WriteCLUT16S_I8_CSM1(const GIFRegTEX0& TEX0, const GIFRegTEXCLUT& TEXCLUT) { - ASSERT(TEX0.CSA < 16); - - WriteCLUT_T16_I8_CSM1((uint16*)m_mem->BlockPtr16S(0, 0, TEX0.CBP, 1), m_clut + ((TEX0.CSA & 15) << 4)); + WriteCLUT_T16_I8_CSM1((uint16*)m_mem->BlockPtr16S(0, 0, TEX0.CBP, 1), m_clut + (TEX0.CSA << 4)); } void GSClut::WriteCLUT16S_I4_CSM1(const GIFRegTEX0& TEX0, const GIFRegTEXCLUT& TEXCLUT) @@ -175,7 +185,7 @@ template void GSClut::WriteCLUT32_CSM2(const GIFRegTEX0& TEX0, const GIFR uint32* RESTRICT s = &m_mem->m_vm32[o->pixel.row[TEXCLUT.COV]]; int* RESTRICT col = &o->pixel.col[0][TEXCLUT.COU << 4]; - uint16* RESTRICT clut = m_clut + (TEX0.CSA << 4); + uint16* RESTRICT clut = m_clut + ((TEX0.CSA & 15) << 4); for(int i = 0; i < n; i++) { @@ -231,13 +241,12 @@ void GSClut::Read(const GIFRegTEX0& TEX0) { case PSM_PSMT8: case PSM_PSMT8H: - ASSERT(TEX0.CSA == 0); + clut += (TEX0.CSA & 15) << 4; ReadCLUT_T32_I8(clut, m_buff32); break; case PSM_PSMT4: case PSM_PSMT4HL: case PSM_PSMT4HH: - //ASSERT(TEX0.CSA < 16); clut += (TEX0.CSA & 15) << 4; ReadCLUT_T32_I4(clut, m_buff32, m_buff64); break; @@ -249,8 +258,7 @@ void GSClut::Read(const GIFRegTEX0& TEX0) { case PSM_PSMT8: case PSM_PSMT8H: - ASSERT(TEX0.CSA < 16); - clut += (TEX0.CSA & 15) << 4; + clut += TEX0.CSA << 4; ReadCLUT_T16_I8(clut, m_buff32); break; case PSM_PSMT4: @@ -281,13 +289,12 @@ void GSClut::Read32(const GIFRegTEX0& TEX0, const GIFRegTEXA& TEXA) { case PSM_PSMT8: case PSM_PSMT8H: - // ASSERT(TEX0.CSA == 0); // sfex + clut += (TEX0.CSA & 15) << 4; ReadCLUT_T32_I8(clut, m_buff32); break; case PSM_PSMT4: case PSM_PSMT4HL: case PSM_PSMT4HH: - //ASSERT(TEX0.CSA < 16); // Idol Janshi Suchie-Pai IV (highlighted menu item, mahjong tiles) clut += (TEX0.CSA & 15) << 4; // TODO: merge these functions ReadCLUT_T32_I4(clut, m_buff32); @@ -301,8 +308,7 @@ void GSClut::Read32(const GIFRegTEX0& TEX0, const GIFRegTEXA& TEXA) { case PSM_PSMT8: case PSM_PSMT8H: - ASSERT(TEX0.CSA < 16); - clut += (TEX0.CSA & 15) << 4; + clut += TEX0.CSA << 4; Expand16(clut, m_buff32, 256, TEXA); break; case PSM_PSMT4: diff --git a/plugins/GSdx/GSCrc.cpp b/plugins/GSdx/GSCrc.cpp index 960374d566..54356966ff 100644 --- a/plugins/GSdx/GSCrc.cpp +++ b/plugins/GSdx/GSCrc.cpp @@ -500,6 +500,7 @@ CRC::Game CRC::m_games[] = {0x0098F740, SeintoSeiya, NoRegion, 0}, // cutie comment {0xBDD9BAAD, UrbanReign, US, 0}, // cutie comment {0xAE4BEBD3, UrbanReign, EU, 0}, + {0x9F391882, SteambotChronicles, US, 0}, }; hash_map CRC::m_map; diff --git a/plugins/GSdx/GSCrc.h b/plugins/GSdx/GSCrc.h index 77b3c55fcb..8669f70c30 100644 --- a/plugins/GSdx/GSCrc.h +++ b/plugins/GSdx/GSCrc.h @@ -173,6 +173,7 @@ public: Simple2000Vol114, SeintoSeiya, UrbanReign, + SteambotChronicles, TitleCount, }; diff --git a/plugins/GSdx/GSDevice9.cpp b/plugins/GSdx/GSDevice9.cpp index 6102c0c2e3..24e6af94f6 100644 --- a/plugins/GSdx/GSDevice9.cpp +++ b/plugins/GSdx/GSDevice9.cpp @@ -136,7 +136,7 @@ static D3DFORMAT BestD3dFormat(IDirect3D9* d3d, UINT adapter, D3DDEVTYPE devtype if(1 == msaaCount) msaaCount = 0; - for(int i = 0; i < sizeof(fmts); i++) + for(int i = 0; i < countof(fmts); i++) { if(TestDepthFormat(d3d, adapter, devtype, fmts[i]) && (!msaaCount || IsMsaaSupported(d3d, adapter, devtype, fmts[i], msaaCount, msaa_desc))) { diff --git a/plugins/GSdx/GSDeviceDX.h b/plugins/GSdx/GSDeviceDX.h index 76f2911f8a..e49a4d2e31 100644 --- a/plugins/GSdx/GSDeviceDX.h +++ b/plugins/GSdx/GSDeviceDX.h @@ -96,6 +96,8 @@ public: GSVector4 MinF_TA; GSVector4i MskFix; + GSVector4 TC_OffsetHack; + struct PSConstantBuffer() { FogColor_AREF = GSVector4::zero(); @@ -175,6 +177,7 @@ public: uint32 colclip:2; uint32 date:2; uint32 spritehack:1; + uint32 tcoffsethack:1; uint32 point_sampler:1; }; diff --git a/plugins/GSdx/GSDeviceOGL.cpp b/plugins/GSdx/GSDeviceOGL.cpp index df72e57c3f..1526a8c361 100644 --- a/plugins/GSdx/GSDeviceOGL.cpp +++ b/plugins/GSdx/GSDeviceOGL.cpp @@ -22,6 +22,11 @@ #include "stdafx.h" #include "GSDeviceOGL.h" +#include "res/convert.h" +#include "res/interlace.h" +#include "res/merge.h" +#include "res/shadeboost.h" + // TODO performance cost to investigate // Texture attachment/glDrawBuffer. For the moment it set every draw and potentially multiple time (first time in clear, second time in rendering) // Attachment 1 is only used with the GL_16UI format @@ -33,6 +38,11 @@ static uint32 g_draw_count = 0; static uint32 g_frame_count = 1; +static const uint32 g_merge_cb_index = 10; +static const uint32 g_interlace_cb_index = 11; +static const uint32 g_shadeboost_cb_index = 12; +static const uint32 g_fxaa_cb_index = 13; + GSDeviceOGL::GSDeviceOGL() : m_free_window(false) , m_window(NULL) @@ -65,19 +75,33 @@ GSDeviceOGL::~GSDeviceOGL() // Clean m_merge_obj for (uint32 i = 0; i < 2; i++) +#ifndef DISABLE_GL41_SSO glDeleteProgram(m_merge_obj.ps[i]); +#else + glDeleteShader(m_merge_obj.ps[i]); +#endif delete (m_merge_obj.cb); delete (m_merge_obj.bs); // Clean m_interlace for (uint32 i = 0; i < 2; i++) +#ifndef DISABLE_GL41_SSO glDeleteProgram(m_interlace.ps[i]); +#else + glDeleteShader(m_interlace.ps[i]); +#endif delete (m_interlace.cb); // Clean m_convert +#ifndef DISABLE_GL41_SSO glDeleteProgram(m_convert.vs); for (uint32 i = 0; i < 2; i++) glDeleteProgram(m_convert.ps[i]); +#else + glDeleteShader(m_convert.vs); + for (uint i = 0; i < 2; i++) + glDeleteShader(m_convert.ps[i]); +#endif glDeleteSamplers(1, &m_convert.ln); glDeleteSamplers(1, &m_convert.pt); delete m_convert.dss; @@ -88,7 +112,9 @@ GSDeviceOGL::~GSDeviceOGL() delete m_date.bs; // Clean various opengl allocation +#ifndef DISABLE_GL41_SSO glDeleteProgramPipelines(1, &m_pipeline); +#endif glDeleteFramebuffers(1, &m_fbo); glDeleteFramebuffers(1, &m_fbo_read); @@ -98,9 +124,18 @@ GSDeviceOGL::~GSDeviceOGL() glDeleteSamplers(1, &m_rt_ss); delete m_vb; +#ifndef DISABLE_GL41_SSO for (auto it = m_vs.begin(); it != m_vs.end() ; it++) glDeleteProgram(it->second); for (auto it = m_gs.begin(); it != m_gs.end() ; it++) glDeleteProgram(it->second); for (auto it = m_ps.begin(); it != m_ps.end() ; it++) glDeleteProgram(it->second); +#else + for (auto it = m_vs.begin(); it != m_vs.end() ; it++) glDeleteShader(it->second); + for (auto it = m_gs.begin(); it != m_gs.end() ; it++) glDeleteShader(it->second); + for (auto it = m_ps.begin(); it != m_ps.end() ; it++) glDeleteShader(it->second); + + for (auto it = m_single_prog.begin(); it != m_single_prog.end() ; it++) glDeleteProgram(it->second); + m_single_prog.clear(); +#endif for (auto it = m_ps_ss.begin(); it != m_ps_ss.end() ; it++) glDeleteSamplers(1, &it->second); m_vs.clear(); m_gs.clear(); @@ -161,8 +196,10 @@ bool GSDeviceOGL::Create(GSWnd* wnd) // **************************************************************** // Various object // **************************************************************** +#ifndef DISABLE_GL41_SSO glGenProgramPipelines(1, &m_pipeline); glBindProgramPipeline(m_pipeline); +#endif glGenFramebuffers(1, &m_fbo); glGenFramebuffers(1, &m_fbo_read); @@ -180,10 +217,10 @@ bool GSDeviceOGL::Create(GSWnd* wnd) // **************************************************************** // convert // **************************************************************** - CompileShaderFromSource("convert.glsl", "vs_main", GL_VERTEX_SHADER, &m_convert.vs); - CompileShaderFromSource("convert.glsl", "gs_main", GL_GEOMETRY_SHADER, &m_convert.gs); + CompileShaderFromSource("convert.glsl", "vs_main", GL_VERTEX_SHADER, &m_convert.vs, convert_glsl); + CompileShaderFromSource("convert.glsl", "gs_main", GL_GEOMETRY_SHADER, &m_convert.gs, convert_glsl); for(uint32 i = 0; i < countof(m_convert.ps); i++) - CompileShaderFromSource("convert.glsl", format("ps_main%d", i), GL_FRAGMENT_SHADER, &m_convert.ps[i]); + CompileShaderFromSource("convert.glsl", format("ps_main%d", i), GL_FRAGMENT_SHADER, &m_convert.ps[i], convert_glsl); // Note the following object are initialized to 0 so disabled. // Note: maybe enable blend with a factor of 1 @@ -240,10 +277,10 @@ bool GSDeviceOGL::Create(GSWnd* wnd) // **************************************************************** // merge // **************************************************************** - m_merge_obj.cb = new GSUniformBufferOGL(1, sizeof(MergeConstantBuffer)); + m_merge_obj.cb = new GSUniformBufferOGL(g_merge_cb_index, sizeof(MergeConstantBuffer)); for(uint32 i = 0; i < countof(m_merge_obj.ps); i++) - CompileShaderFromSource("merge.glsl", format("ps_main%d", i), GL_FRAGMENT_SHADER, &m_merge_obj.ps[i]); + CompileShaderFromSource("merge.glsl", format("ps_main%d", i), GL_FRAGMENT_SHADER, &m_merge_obj.ps[i], merge_glsl); m_merge_obj.bs = new GSBlendStateOGL(); m_merge_obj.bs->EnableBlend(); @@ -252,14 +289,14 @@ bool GSDeviceOGL::Create(GSWnd* wnd) // **************************************************************** // interlace // **************************************************************** - m_interlace.cb = new GSUniformBufferOGL(2, sizeof(InterlaceConstantBuffer)); + m_interlace.cb = new GSUniformBufferOGL(g_interlace_cb_index, sizeof(InterlaceConstantBuffer)); for(uint32 i = 0; i < countof(m_interlace.ps); i++) - CompileShaderFromSource("interlace.glsl", format("ps_main%d", i), GL_FRAGMENT_SHADER, &m_interlace.ps[i]); + CompileShaderFromSource("interlace.glsl", format("ps_main%d", i), GL_FRAGMENT_SHADER, &m_interlace.ps[i], interlace_glsl); // **************************************************************** // Shade boost // **************************************************************** - m_shadeboost.cb = new GSUniformBufferOGL(6, sizeof(ShadeBoostConstantBuffer)); + m_shadeboost.cb = new GSUniformBufferOGL(g_shadeboost_cb_index, sizeof(ShadeBoostConstantBuffer)); int ShadeBoost_Contrast = theApp.GetConfig("ShadeBoost_Contrast", 50); int ShadeBoost_Brightness = theApp.GetConfig("ShadeBoost_Brightness", 50); @@ -268,7 +305,7 @@ bool GSDeviceOGL::Create(GSWnd* wnd) + format("#define SB_BRIGHTNESS %d\n", ShadeBoost_Brightness) + format("#define SB_CONTRAST %d\n", ShadeBoost_Contrast); - CompileShaderFromSource("shadeboost.glsl", "ps_main", GL_FRAGMENT_SHADER, &m_shadeboost.ps, macro); + CompileShaderFromSource("shadeboost.glsl", "ps_main", GL_FRAGMENT_SHADER, &m_shadeboost.ps, shadeboost_glsl, macro); // **************************************************************** // rasterization configuration @@ -300,8 +337,8 @@ bool GSDeviceOGL::Create(GSWnd* wnd) // FIXME need to define FXAA_GLSL_130 for the shader // FIXME need to manually set the index... // FIXME need dofxaa interface too - // m_fxaa.cb = new GSUniformBufferOGL(3, sizeof(FXAAConstantBuffer)); - //CompileShaderFromSource("fxaa.fx", format("ps_main", i), GL_FRAGMENT_SHADER, &m_fxaa.ps); + // m_fxaa.cb = new GSUniformBufferOGL(g_fxaa_cb_index, sizeof(FXAAConstantBuffer)); + //CompileShaderFromSource("fxaa.fx", format("ps_main", i), GL_FRAGMENT_SHADER, &m_fxaa.ps, fxaa_glsl); // **************************************************************** // date @@ -471,9 +508,8 @@ void GSDeviceOGL::Flip() #ifdef PRINT_FRAME_NUMBER fprintf(stderr, "Draw %d (Frame %d)\n", g_draw_count, g_frame_count); #endif -#ifdef ENABLE_OGL_DEBUG - if (theApp.GetConfig("debug_ogl_dump", 0) != 0) - g_frame_count++; +#if defined(ENABLE_OGL_DEBUG) || defined(PRINT_FRAME_NUMBER) + g_frame_count++; #endif } @@ -550,47 +586,112 @@ void GSDeviceOGL::DebugOutput() //DebugBB(); } -void GSDeviceOGL::DrawPrimitive() +#ifdef DISABLE_GL42 +static void set_uniform_buffer_binding(GLuint prog, GLchar* name, GLuint binding) { + GLuint index; + index = glGetUniformBlockIndex(prog, name); + if (index != GL_INVALID_INDEX) { + glUniformBlockBinding(prog, index, binding); + } +} +#endif + +#ifdef DISABLE_GL41_SSO +GLuint GSDeviceOGL::link_prog() +{ + GLuint single_prog = glCreateProgram(); + if (m_state.vs) glAttachShader(single_prog, m_state.vs); + if (m_state.ps) glAttachShader(single_prog, m_state.ps); + if (m_state.gs) glAttachShader(single_prog, m_state.gs); + + glLinkProgram(single_prog); + + GLint status; + glGetProgramiv(single_prog, GL_LINK_STATUS, &status); + if (!status) { + GLint log_length = 0; + glGetProgramiv(single_prog, GL_INFO_LOG_LENGTH, &log_length); + if (log_length > 0) { + char* log = new char[log_length]; + glGetProgramInfoLog(single_prog, log_length, NULL, log); + fprintf(stderr, "%s", log); + delete[] log; + } + fprintf(stderr, "\n"); + } + +#if 0 + if (m_state.vs) glDetachShader(single_prog, m_state.vs); + if (m_state.ps) glDetachShader(single_prog, m_state.ps); + if (m_state.gs) glDetachShader(single_prog, m_state.gs); +#endif + + return single_prog; +} +#endif + +void GSDeviceOGL::BeforeDraw() { #ifdef ENABLE_OGL_DEBUG DebugInput(); #endif - m_state.vb->DrawPrimitive(); +#ifdef DISABLE_GL41_SSO + // Note: shader are integer lookup pointer. They start from 1 and incr + // every time you create a new shader OR a new program. + uint64 sel = (uint64)m_state.vs << 40 | (uint64)m_state.gs << 20 | m_state.ps; + auto single_prog = m_single_prog.find(sel); + if (single_prog == m_single_prog.end()) { + m_single_prog[sel] = link_prog(); + single_prog = m_single_prog.find(sel); + } + glUseProgram(single_prog->second); + +#endif + +#ifdef DISABLE_GL42 + set_uniform_buffer_binding(m_state.vs, "cb20", 20); + set_uniform_buffer_binding(m_state.ps, "cb21", 21); + + set_uniform_buffer_binding(m_state.ps, "cb10", 10); + set_uniform_buffer_binding(m_state.ps, "cb11", 11); + set_uniform_buffer_binding(m_state.ps, "cb12", 12); + set_uniform_buffer_binding(m_state.ps, "cb13", 13); +#endif +} + +void GSDeviceOGL::AfterDraw() +{ #ifdef ENABLE_OGL_DEBUG DebugOutput(); +#endif +#if defined(ENABLE_OGL_DEBUG) || defined(PRINT_FRAME_NUMBER) g_draw_count++; #endif } +void GSDeviceOGL::DrawPrimitive() +{ + BeforeDraw(); + m_state.vb->DrawPrimitive(); + AfterDraw(); +} + void GSDeviceOGL::DrawIndexedPrimitive() { -#ifdef ENABLE_OGL_DEBUG - DebugInput(); -#endif - + BeforeDraw(); m_state.vb->DrawIndexedPrimitive(); - -#ifdef ENABLE_OGL_DEBUG - DebugOutput(); - g_draw_count++; -#endif + AfterDraw(); } void GSDeviceOGL::DrawIndexedPrimitive(int offset, int count) { ASSERT(offset + count <= m_index.count); -#ifdef ENABLE_OGL_DEBUG - DebugInput(); -#endif + BeforeDraw(); m_state.vb->DrawIndexedPrimitive(offset, count); - -#ifdef ENABLE_OGL_DEBUG - DebugOutput(); - g_draw_count++; -#endif + AfterDraw(); } void GSDeviceOGL::ClearRenderTarget(GSTexture* t, const GSVector4& c) @@ -686,7 +787,7 @@ GSTexture* GSDeviceOGL::CopyOffscreen(GSTexture* src, const GSVector4& sr, int w { ASSERT(0); - return false; + return NULL; } // FIXME: It is possible to bypass completely offscreen-buffer on opengl but it needs some re-thinking of the code. @@ -1038,7 +1139,9 @@ void GSDeviceOGL::VSSetShader(GLuint vs) if(m_state.vs != vs) { m_state.vs = vs; +#ifndef DISABLE_GL41_SSO glUseProgramStages(m_pipeline, GL_VERTEX_SHADER_BIT, vs); +#endif } } @@ -1047,7 +1150,9 @@ void GSDeviceOGL::GSSetShader(GLuint gs) if(m_state.gs != gs) { m_state.gs = gs; +#ifndef DISABLE_GL41_SSO glUseProgramStages(m_pipeline, GL_GEOMETRY_SHADER_BIT, gs); +#endif } } @@ -1088,7 +1193,9 @@ void GSDeviceOGL::PSSetShader(GLuint ps) if(m_state.ps != ps) { m_state.ps = ps; +#ifndef DISABLE_GL41_SSO glUseProgramStages(m_pipeline, GL_FRAGMENT_SHADER_BIT, ps); +#endif } // Sampler and texture must be set at the same time @@ -1196,47 +1303,25 @@ void GSDeviceOGL::OMSetRenderTargets(GSTexture* rt, GSTexture* ds, const GSVecto } } -// AMD drivers fail to support correctly the setting of index in fragment shader (layout statement in glsl)... -// So instead to use directly glCreateShaderProgramv, you need to emulate the function and manually set -// the index in the fragment shader. -GLuint GSDeviceOGL::glCreateShaderProgramv_AMD_BUG_WORKAROUND(GLenum type, GLsizei count, const char ** strings) -{ - const GLuint shader = glCreateShader(type); - if (shader) { - glShaderSource(shader, count, strings, NULL); - glCompileShader(shader); - const GLuint program = glCreateProgram(); - if (program) { - GLint compiled = GL_FALSE; - glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled); - glProgramParameteri(program, GL_PROGRAM_SEPARABLE, GL_TRUE); - if (compiled) { - glAttachShader(program, shader); - // HACK TO SET CORRECTLY THE INDEX - if (type == GL_FRAGMENT_SHADER) { - glBindFragDataLocationIndexed(program, 0, 0, "SV_Target0"); - glBindFragDataLocationIndexed(program, 0, 1, "SV_Target1"); - } - // END OF HACK - glLinkProgram(program); - glDetachShader(program, shader); - } - /* append-shader-info-log-to-program-info-log */ - } - glDeleteShader(shader); - return program; - } else { - return 0; - } -} - -void GSDeviceOGL::CompileShaderFromSource(const std::string& glsl_file, const std::string& entry, GLenum type, GLuint* program, const std::string& macro_sel) +void GSDeviceOGL::CompileShaderFromSource(const std::string& glsl_file, const std::string& entry, GLenum type, GLuint* program, const char* glsl_h_code, const std::string& macro_sel) { // ***************************************************** // Build a header string // ***************************************************** // First select the version (must be the first line so we need to generate it +#ifdef DISABLE_GL41_SSO + #ifdef DISABLE_GL42 + std::string version = "#version 330\n#define DISABLE_GL42\n"; + #else + std::string version = "#version 330\n#extension GL_ARB_shading_language_420pack: require\n"; + #endif +#else + #ifdef DISABLE_GL42 + std::string version = "#version 330\n#extension GL_ARB_separate_shader_objects : require\n#define DISABLE_GL42\n"; + #else std::string version = "#version 330\n#extension GL_ARB_shading_language_420pack: require\n#extension GL_ARB_separate_shader_objects : require\n"; + #endif +#endif //std::string version = "#version 420\n"; // Allow to puts several shader in 1 files @@ -1274,6 +1359,7 @@ void GSDeviceOGL::CompileShaderFromSource(const std::string& glsl_file, const st const std::string shader_file = string("plugins/") + glsl_file; #endif std::ifstream myfile(shader_file.c_str()); + bool failed_to_open_glsl = true; if (myfile.is_open()) { while ( myfile.good() ) { @@ -1282,26 +1368,30 @@ void GSDeviceOGL::CompileShaderFromSource(const std::string& glsl_file, const st source += '\n'; } myfile.close(); - } else { - fprintf(stderr, "Error opening %s: ", shader_file.c_str()); - *program = 0; - return; + failed_to_open_glsl = false; } // Note it is better to separate header and source file to have the good line number // in the glsl compiler report const char** sources_array = (const char**)malloc(2*sizeof(char*)); - char* source_str = (char*)malloc(source.size() + 1); + char* header_str = (char*)malloc(header.size() + 1); sources_array[0] = header_str; - sources_array[1] = source_str; - - source.copy(source_str, source.size(), 0); - source_str[source.size()] = '\0'; header.copy(header_str, header.size(), 0); header_str[header.size()] = '\0'; + char* source_str = (char*)malloc(source.size() + 1); + if (failed_to_open_glsl) { + sources_array[1] = glsl_h_code; + } else { + sources_array[1] = source_str; + source.copy(source_str, source.size(), 0); + source_str[source.size()] = '\0'; + } + + +#ifndef DISABLE_GL41_SSO #if 0 // Could be useful one day const GLchar* ShaderSource[1]; @@ -1310,20 +1400,11 @@ void GSDeviceOGL::CompileShaderFromSource(const std::string& glsl_file, const st #else *program = glCreateShaderProgramv(type, 2, sources_array); #endif - - // Check the correctness of the (AMD) driver - // Note: glGetFragDataLocation crash too!!! Catalyst 12.10 (and later) => HD 5XXX,6XXX !!! - if (theApp.GetConfig("renderer", 0) == 12) { - GLint slot = glGetFragDataLocation(*program, "SV_Target1"); - if (slot == 0) { // <=> SV_Target1 used same slot as SV_Target0 - GLint index = glGetFragDataIndex(*program, "SV_Target1"); - if (index != 1) { - fprintf(stderr, "Driver bug: failed to set the index, program will be recompiled\n"); - glDeleteProgram(*program); - *program = glCreateShaderProgramv_AMD_BUG_WORKAROUND(type, 2, sources_array); - } - } - } +#else + *program = glCreateShader(type); + glShaderSource(*program, 2, sources_array, NULL); + glCompileShader(*program); +#endif free(source_str); free(header_str); @@ -1335,15 +1416,22 @@ void GSDeviceOGL::CompileShaderFromSource(const std::string& glsl_file, const st fprintf(stderr, "\n%s", macro_sel.c_str()); GLint log_length = 0; +#ifndef DISABLE_GL41_SSO glGetProgramiv(*program, GL_INFO_LOG_LENGTH, &log_length); +#else + glGetShaderiv(*program, GL_INFO_LOG_LENGTH, &log_length); +#endif if (log_length > 0) { - char* log = (char*)malloc(log_length); - glGetProgramInfoLog(*program, log_length, NULL, log); + char* log = new char[log_length]; +#ifndef DISABLE_GL41_SSO + glGetProgramInfoLog(*program, log_length, NULL, log); +#else + glGetShaderInfoLog(*program, log_length, NULL, log); +#endif fprintf(stderr, "%s", log); - free(log); + delete[] log; } fprintf(stderr, "\n"); - } } diff --git a/plugins/GSdx/GSDeviceOGL.h b/plugins/GSdx/GSDeviceOGL.h index a1de636dc1..6856bc032a 100644 --- a/plugins/GSdx/GSDeviceOGL.h +++ b/plugins/GSdx/GSDeviceOGL.h @@ -301,6 +301,8 @@ class GSDeviceOGL : public GSDevice GSVector4 MinF_TA; GSVector4i MskFix; + GSVector4 TC_OffsetHack; + PSConstantBuffer() { FogColor_AREF = GSVector4::zero(); @@ -380,6 +382,7 @@ class GSDeviceOGL : public GSDevice uint32 colclip:2; uint32 date:2; uint32 spritehack:1; + uint32 tcoffsethack:1; uint32 point_sampler:1; }; @@ -596,6 +599,8 @@ class GSDeviceOGL : public GSDevice void DrawPrimitive(); void DrawIndexedPrimitive(); void DrawIndexedPrimitive(int offset, int count); + void BeforeDraw(); + void AfterDraw(); void ClearRenderTarget(GSTexture* t, const GSVector4& c); void ClearRenderTarget(GSTexture* t, uint32 c); @@ -618,7 +623,7 @@ class GSDeviceOGL : public GSDevice GSTexture* Resolve(GSTexture* t); - void CompileShaderFromSource(const std::string& glsl_file, const std::string& entry, GLenum type, GLuint* program, const std::string& macro_sel = ""); + void CompileShaderFromSource(const std::string& glsl_file, const std::string& entry, GLenum type, GLuint* program, const char* glsl_h_code, const std::string& macro_sel = ""); void EndScene(); @@ -652,5 +657,9 @@ class GSDeviceOGL : public GSDevice void SetupPS(PSSelector sel, const PSConstantBuffer* cb, PSSamplerSelector ssel); void SetupOM(OMDepthStencilSelector dssel, OMBlendSelector bsel, uint8 afix); - GLuint glCreateShaderProgramv_AMD_BUG_WORKAROUND(GLenum type, GLsizei count, const char ** strings); +#ifdef DISABLE_GL41_SSO + hash_map m_single_prog; + GLuint link_prog(); +#endif + }; diff --git a/plugins/GSdx/GSDeviceSW.cpp b/plugins/GSdx/GSDeviceSW.cpp index e0acc51254..a56c96ad1c 100644 --- a/plugins/GSdx/GSDeviceSW.cpp +++ b/plugins/GSdx/GSDeviceSW.cpp @@ -50,7 +50,7 @@ bool GSDeviceSW::Reset(int w, int h) GSTexture* GSDeviceSW::CreateSurface(int type, int w, int h, bool msaa, int format) { - if(format != 0) return false; // there is only one format + if(format != 0) return NULL; // there is only one format return new GSTextureSW(type, w, h); } diff --git a/plugins/GSdx/GSLinuxDialog.cpp b/plugins/GSdx/GSLinuxDialog.cpp index 65ecbd1b72..c74b0cc823 100644 --- a/plugins/GSdx/GSLinuxDialog.cpp +++ b/plugins/GSdx/GSLinuxDialog.cpp @@ -29,8 +29,6 @@ GtkWidget *shadeboost_check, *paltex_check, *fba_check, *aa_check, *native_res_ GtkWidget *sb_contrast, *sb_brightness, *sb_saturation; GtkWidget *resx_spin, *resy_spin; -GtkWidget *hack_alpha_check, *hack_offset_check, *hack_skipdraw_spin, *hack_msaa_check, *hack_sprite_check, * hack_wild_check, *hack_enble_check; - static void SysMessage(const char *fmt, ...) { va_list list; @@ -212,6 +210,21 @@ void toggle_widget_states( GtkWidget *widget, gpointer callback_data ) } } +void set_hex_entry(GtkWidget *text_box, int hex_value) { + gchar* data=(gchar *)g_malloc(sizeof(gchar)*40); + sprintf(data,"%X", hex_value); + gtk_entry_set_text(GTK_ENTRY(text_box),data); +} + +int get_hex_entry(GtkWidget *text_box) { + int hex_value = 0; + const gchar *data = gtk_entry_get_text(GTK_ENTRY(text_box)); + + sscanf(data,"%X",&hex_value); + + return hex_value; +} + bool RunLinuxDialog() { GtkWidget *dialog; @@ -222,6 +235,9 @@ bool RunLinuxDialog() GtkWidget *interlace_label, *threads_label, *native_label, *msaa_label, *rexy_label, *render_label, *filter_label; GtkWidget *hack_table, *hack_skipdraw_label, *hack_box, *hack_frame; + GtkWidget *hack_alpha_check, *hack_offset_check, *hack_skipdraw_spin, *hack_msaa_check, *hack_sprite_check, * hack_wild_check, *hack_enble_check; + GtkWidget *hack_tco_label, *hack_tco_entry; + int return_value; GdkPixbuf* logo_pixmap; @@ -324,15 +340,20 @@ bool RunLinuxDialog() gtk_box_pack_start(GTK_BOX(resxy_box), resy_spin, false, false, 5); // Create our hack settings. - hack_alpha_check = gtk_check_button_new_with_label("Alpha Hack"); - hack_offset_check = gtk_check_button_new_with_label("Offset Hack"); + hack_alpha_check = gtk_check_button_new_with_label("Alpha Hack"); + hack_offset_check = gtk_check_button_new_with_label("Offset Hack"); hack_skipdraw_label = gtk_label_new("Skipdraw:"); - hack_skipdraw_spin = gtk_spin_button_new_with_range(0,1000,1); - hack_enble_check = gtk_check_button_new_with_label("Enable User Hacks"); - hack_wild_check = gtk_check_button_new_with_label("Wild arm Hack"); - hack_sprite_check = gtk_check_button_new_with_label("Sprite Hack"); - hack_msaa_check = gtk_check_button_new_with_label("Msaa Hack"); + hack_skipdraw_spin = gtk_spin_button_new_with_range(0,1000,1); + hack_enble_check = gtk_check_button_new_with_label("Enable User Hacks"); + hack_wild_check = gtk_check_button_new_with_label("Wild arm Hack"); + hack_sprite_check = gtk_check_button_new_with_label("Sprite Hack"); + hack_msaa_check = gtk_check_button_new_with_label("Msaa Hack"); + hack_tco_label = gtk_label_new("Texture offset: 0x"); + hack_tco_entry = gtk_entry_new(); + gtk_spin_button_set_value(GTK_SPIN_BUTTON(hack_skipdraw_spin), theApp.GetConfig("UserHacks_SkipDraw", 0)); + set_hex_entry(hack_tco_entry, theApp.GetConfig("UserHacks_TCOffset", 0)); + // Tables are strange. The numbers are for their position: left, right, top, bottom. gtk_table_attach_defaults(GTK_TABLE(hack_table), hack_alpha_check, 0, 1, 0, 1); gtk_table_attach_defaults(GTK_TABLE(hack_table), hack_offset_check, 1, 2, 0, 1); @@ -342,6 +363,8 @@ bool RunLinuxDialog() //gtk_table_attach_defaults(GTK_TABLE(hack_table), hack_msaa_check, 2, 3, 1, 2); gtk_table_attach_defaults(GTK_TABLE(hack_table), hack_skipdraw_label, 0, 1, 2, 3); gtk_table_attach_defaults(GTK_TABLE(hack_table), hack_skipdraw_spin, 1, 2, 2, 3); + gtk_table_attach_defaults(GTK_TABLE(hack_table), hack_tco_label, 0, 1, 3, 4); + gtk_table_attach_defaults(GTK_TABLE(hack_table), hack_tco_entry, 1, 2, 3, 4); // Create our checkboxes. shadeboost_check = gtk_check_button_new_with_label("Shade boost"); @@ -473,6 +496,7 @@ bool RunLinuxDialog() theApp.SetConfig("UserHacks_WildHack", (int)gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(hack_wild_check))); theApp.SetConfig("UserHacks_SpriteHack", (int)gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(hack_sprite_check))); theApp.SetConfig("UserHacks", (int)gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(hack_enble_check))); + theApp.SetConfig("UserHacks_TCOffset", get_hex_entry(hack_tco_entry)); // Let's just be windowed for the moment. theApp.SetConfig("windowed", 1); diff --git a/plugins/GSdx/GSRendererDX.cpp b/plugins/GSdx/GSRendererDX.cpp index 1349e76c41..36713b6ee6 100644 --- a/plugins/GSdx/GSRendererDX.cpp +++ b/plugins/GSdx/GSRendererDX.cpp @@ -31,8 +31,12 @@ GSRendererDX::GSRendererDX(GSTextureCache* tc, const GSVector2& pixelcenter) m_fba = !!theApp.GetConfig("fba", 1); UserHacks_AlphaHack = !!theApp.GetConfig("UserHacks_AlphaHack", 0) && !!theApp.GetConfig("UserHacks", 0); - UserHacks_WildHack = !!theApp.GetConfig("UserHacks", 0) ? theApp.GetConfig("UserHacks_WildHack", 0) : 0; + UserHacks_WildHack = !!theApp.GetConfig("UserHacks", 0) ? theApp.GetConfig("UserHacks_WildHack", 0) : 0; UserHacks_AlphaStencil = !!theApp.GetConfig("UserHacks_AlphaStencil", 0) && !!theApp.GetConfig("UserHacks", 0); + + UserHacks_TCOffset = !!theApp.GetConfig("UserHacks", 0) ? theApp.GetConfig("UserHacks_TCOffset", 0) : 0; + UserHacks_TCO_x = (UserHacks_TCOffset & 0xFFFF) / -1000.0f; + UserHacks_TCO_y = ((UserHacks_TCOffset >> 16) & 0xFFFF) / -1000.0f; } GSRendererDX::~GSRendererDX() @@ -287,10 +291,7 @@ void GSRendererDX::DrawPrims(GSTexture* rt, GSTexture* ds, GSTextureCache::Sourc ps_sel.wms = context->CLAMP.WMS; ps_sel.wmt = context->CLAMP.WMT; - if (tex->m_palette) - ps_sel.fmt = cpsm.fmt | 4; - else - ps_sel.fmt = cpsm.fmt; + ps_sel.fmt = tex->m_palette? cpsm.fmt | 4 : cpsm.fmt; ps_sel.aem = env.TEXA.AEM; ps_sel.tfx = context->TEX0.TFX; ps_sel.tcc = context->TEX0.TCC; @@ -319,6 +320,10 @@ void GSRendererDX::DrawPrims(GSTexture* rt, GSTexture* ds, GSTextureCache::Sourc ps_cb.HalfTexel = GSVector4(-0.5f, 0.5f).xxyy() / WH.zwzw(); ps_cb.MskFix = GSVector4i(context->CLAMP.MINU, context->CLAMP.MINV, context->CLAMP.MAXU, context->CLAMP.MAXV); + // TC Offset Hack + ps_sel.tcoffsethack = !!UserHacks_TCOffset; + ps_cb.TC_OffsetHack = GSVector4(UserHacks_TCO_x, UserHacks_TCO_y).xyxy() / WH.xyxy(); + GSVector4 clamp(ps_cb.MskFix); GSVector4 ta(env.TEXA & GSVector4i::x000000ff()); diff --git a/plugins/GSdx/GSRendererDX.h b/plugins/GSdx/GSRendererDX.h index cd1587c806..5325433ee4 100644 --- a/plugins/GSdx/GSRendererDX.h +++ b/plugins/GSdx/GSRendererDX.h @@ -37,7 +37,9 @@ protected: virtual void SetupIA() = 0; virtual void UpdateFBA(GSTexture* rt) {} - int UserHacks_WildHack; + unsigned int UserHacks_WildHack; + unsigned int UserHacks_TCOffset; + float UserHacks_TCO_x, UserHacks_TCO_y; public: GSRendererDX(GSTextureCache* tc, const GSVector2& pixelcenter = GSVector2(0, 0)); diff --git a/plugins/GSdx/GSRendererDX11.cpp b/plugins/GSdx/GSRendererDX11.cpp index 380956ac89..cd44665eb2 100644 --- a/plugins/GSdx/GSRendererDX11.cpp +++ b/plugins/GSdx/GSRendererDX11.cpp @@ -45,17 +45,16 @@ void GSRendererDX11::SetupIA() if(dev->IAMapVertexBuffer(&ptr, sizeof(GSVertex), m_vertex.next)) { - GSVector4i::storent(ptr, m_vertex.buff, sizeof(GSVertex) * m_vertex.next); - - if(UserHacks_WildHack && !isPackedUV_HackFlag) - { - GSVertex* RESTRICT d = (GSVertex*)ptr; - - for(unsigned int i = 0; i < m_vertex.next; i++, d++) - if(PRIM->TME && PRIM->FST) - d->UV &= UserHacks_WildHack == 1 ? 0x3FEF3FEF : 0x3FF73FF7; - } - + GSVector4i::storent(ptr, m_vertex.buff, sizeof(GSVertex) * m_vertex.next); + + if(UserHacks_WildHack && !isPackedUV_HackFlag) + { + GSVertex* RESTRICT d = (GSVertex*)ptr; + + for(unsigned int i = 0; i < m_vertex.next; i++, d++) + if(PRIM->TME && PRIM->FST) d->UV &= 0x3FEF3FEF; + } + dev->IAUnmapVertexBuffer(); } diff --git a/plugins/GSdx/GSRendererDX9.cpp b/plugins/GSdx/GSRendererDX9.cpp index 437a526e14..c56218bef4 100644 --- a/plugins/GSdx/GSRendererDX9.cpp +++ b/plugins/GSdx/GSRendererDX9.cpp @@ -199,15 +199,13 @@ void GSRendererDX9::SetupIA() { if(PRIM->FST) { - if(UserHacks_WildHack && !isPackedUV_HackFlag) - { - t = GSVector4(GSVector4i::load(UserHacks_WildHack == 1? - s->UV & 0x3FEF3FEF : s->UV & 0x3FF73FF7).upl16()); - - //printf("GSDX: %08X | D3D9(%d) %s\n", s->UV & 0x3FEF3FEF, m_vertex.next, i == 0 ? "*" : ""); - } - else - t = GSVector4(GSVector4i::load(s->UV).upl16()); + if(UserHacks_WildHack && !isPackedUV_HackFlag) + { + t = GSVector4(GSVector4i::load(s->UV & 0x3FEF3FEF).upl16()); + //printf("GSDX: %08X | D3D9(%d) %s\n", s->UV & 0x3FEF3FEF, m_vertex.next, i == 0 ? "*" : ""); + } + else + t = GSVector4(GSVector4i::load(s->UV).upl16()); } else { diff --git a/plugins/GSdx/GSRendererOGL.cpp b/plugins/GSdx/GSRendererOGL.cpp index a3ec58065d..7cbcdad607 100644 --- a/plugins/GSdx/GSRendererOGL.cpp +++ b/plugins/GSdx/GSRendererOGL.cpp @@ -33,6 +33,10 @@ GSRendererOGL::GSRendererOGL() UserHacks_WildHack = !!theApp.GetConfig("UserHacks", 0) ? theApp.GetConfig("UserHacks_WildHack", 0) : 0; UserHacks_AlphaStencil = !!theApp.GetConfig("UserHacks_AlphaStencil", 0) && !!theApp.GetConfig("UserHacks", 0); m_pixelcenter = GSVector2(-0.5f, -0.5f); + + UserHacks_TCOffset = !!theApp.GetConfig("UserHacks", 0) ? theApp.GetConfig("UserHacks_TCOffset", 0) : 0; + UserHacks_TCO_x = (UserHacks_TCOffset & 0xFFFF) / -1000.0f; + UserHacks_TCO_y = ((UserHacks_TCOffset >> 16) & 0xFFFF) / -1000.0f; } bool GSRendererOGL::CreateDevice(GSDevice* dev) @@ -61,7 +65,7 @@ void GSRendererOGL::SetupIA() for(unsigned int i = 0; i < m_vertex.next; i++, d++) if(PRIM->TME && PRIM->FST) - d->UV &= UserHacks_WildHack == 1 ? 0x3FEF3FEF : 0x3FF73FF7; + d->UV &= 0x3FEF3FEF; } dev->IAUnmapVertexBuffer(); @@ -354,10 +358,7 @@ void GSRendererOGL::DrawPrims(GSTexture* rt, GSTexture* ds, GSTextureCache::Sour ps_sel.wms = context->CLAMP.WMS; ps_sel.wmt = context->CLAMP.WMT; - if (tex->m_palette) - ps_sel.fmt = cpsm.fmt | 4; - else - ps_sel.fmt = cpsm.fmt; + ps_sel.fmt = tex->m_palette ? cpsm.fmt | 4 : cpsm.fmt; ps_sel.aem = env.TEXA.AEM; ps_sel.tfx = context->TEX0.TFX; ps_sel.tcc = context->TEX0.TCC; @@ -386,6 +387,10 @@ void GSRendererOGL::DrawPrims(GSTexture* rt, GSTexture* ds, GSTextureCache::Sour ps_cb.HalfTexel = GSVector4(-0.5f, 0.5f).xxyy() / WH.zwzw(); ps_cb.MskFix = GSVector4i(context->CLAMP.MINU, context->CLAMP.MINV, context->CLAMP.MAXU, context->CLAMP.MAXV); + // TC Offset Hack + ps_sel.tcoffsethack = !!UserHacks_TCOffset; + ps_cb.TC_OffsetHack = GSVector4(UserHacks_TCO_x, UserHacks_TCO_y).xyxy() / WH.xyxy(); + GSVector4 clamp(ps_cb.MskFix); GSVector4 ta(env.TEXA & GSVector4i::x000000ff()); diff --git a/plugins/GSdx/GSRendererOGL.h b/plugins/GSdx/GSRendererOGL.h index fe815d1999..502f699d8e 100644 --- a/plugins/GSdx/GSRendererOGL.h +++ b/plugins/GSdx/GSRendererOGL.h @@ -39,7 +39,9 @@ class GSRendererOGL : public GSRendererHW bool m_fba; bool UserHacks_AlphaHack; bool UserHacks_AlphaStencil; - int UserHacks_WildHack; + unsigned int UserHacks_WildHack; + unsigned int UserHacks_TCOffset; + float UserHacks_TCO_x, UserHacks_TCO_y; protected: void SetupIA(); diff --git a/plugins/GSdx/GSSettingsDlg.cpp b/plugins/GSdx/GSSettingsDlg.cpp index 65588c797a..64ec3ecaaa 100644 --- a/plugins/GSdx/GSSettingsDlg.cpp +++ b/plugins/GSdx/GSSettingsDlg.cpp @@ -105,7 +105,7 @@ void GSSettingsDlg::OnInit() buf, size, NULL, NULL); adapters.push_back(Adapter(buf, GSAdapter(desc), level)); - delete buf; + delete [] buf; #else adapters.push_back(Adapter(desc.Description, GSAdapter(desc), level)); #endif @@ -522,6 +522,11 @@ void GSHacksDlg::OnInit() SendMessage(GetDlgItem(m_hWnd, IDC_SKIPDRAWHACK), UDM_SETRANGE, 0, MAKELPARAM(1000, 0)); SendMessage(GetDlgItem(m_hWnd, IDC_SKIPDRAWHACK), UDM_SETPOS, 0, MAKELPARAM(theApp.GetConfig("UserHacks_SkipDraw", 0), 0)); + SendMessage(GetDlgItem(m_hWnd, IDC_TCOFFSETX), UDM_SETRANGE, 0, MAKELPARAM(10000, 0)); + SendMessage(GetDlgItem(m_hWnd, IDC_TCOFFSETX), UDM_SETPOS, 0, MAKELPARAM(theApp.GetConfig("UserHacks_TCOffset", 0) & 0xFFFF, 0)); + + SendMessage(GetDlgItem(m_hWnd, IDC_TCOFFSETY), UDM_SETRANGE, 0, MAKELPARAM(10000, 0)); + SendMessage(GetDlgItem(m_hWnd, IDC_TCOFFSETY), UDM_SETPOS, 0, MAKELPARAM((theApp.GetConfig("UserHacks_TCOffset", 0) >> 16) & 0xFFFF, 0)); // Hacks descriptions SetWindowText(GetDlgItem(m_hWnd, IDC_HACK_DESCRIPTION), "Hover over an item to get a description."); @@ -537,6 +542,7 @@ bool GSHacksDlg::OnMessage(UINT message, WPARAM wParam, LPARAM lParam) case WM_SETCURSOR: { const char *helpstr = ""; + bool updateText = true; POINT pos; GetCursorPos(&pos); @@ -582,7 +588,8 @@ bool GSHacksDlg::OnMessage(UINT message, WPARAM wParam, LPARAM lParam) case IDC_AGGRESSIVECRC: helpstr = "Use more aggressive CRC hacks on some games\n\n" "Only affects few games, removing some effects which might make the image sharper/clearer.\n" - "Affected games: FFX, FFX2, FFXII, GOW2, ICO, SoTC, SSX3."; + "Affected games: FFX, FFX2, FFXII, GOW2, ICO, SoTC, SSX3.\n" + "Works as a speedhack for: Steambot Chronicles."; break; case IDC_ALPHASTENCIL: helpstr = "Extend stencil based emulation of destination alpha to perform stencil operations while drawing.\n\n" @@ -597,12 +604,26 @@ bool GSHacksDlg::OnMessage(UINT message, WPARAM wParam, LPARAM lParam) "CrcHacksExclusions=all\n" "CrcHacksExclusions=0x0F0C4A9C, 0x0EE5646B, 0x7ACF7E03"; break; + + case IDC_TCOFFSETX: + case IDC_TCOFFSETX2: + case IDC_STATIC_TCOFFSETX: + case IDC_TCOFFSETY: + case IDC_TCOFFSETY2: + case IDC_STATIC_TCOFFSETY: + helpstr = "Texture Coordinates Offset Hack\n\n" + "Offset for the ST/UV texture coordinates. Fixes some odd texture issues and might fix some post processing alignment too.\n\n" + " 0500 0500, fixes Persona 3 minimap, helps Haunting Ground.\n" + " 0000 1000, fixes Xenosaga hair edges (DX10+ Issue)\n"; + break; + default: - helpstr = "Hover over an item to get a description."; + updateText = false; break; } - SetWindowText(GetDlgItem(m_hWnd, IDC_HACK_DESCRIPTION), helpstr); + if(updateText) + SetWindowText(GetDlgItem(m_hWnd, IDC_HACK_DESCRIPTION), helpstr); } break; @@ -623,6 +644,12 @@ bool GSHacksDlg::OnMessage(UINT message, WPARAM wParam, LPARAM lParam) theApp.SetConfig("UserHacks_AggressiveCRC", (int)IsDlgButtonChecked(m_hWnd, IDC_AGGRESSIVECRC)); theApp.SetConfig("UserHacks_AlphaStencil", (int)IsDlgButtonChecked(m_hWnd, IDC_ALPHASTENCIL)); theApp.SetConfig("UserHacks_DisableCrcHacks", (int)IsDlgButtonChecked(m_hWnd, IDC_CHECK_DISABLE_ALL_HACKS)); + + unsigned int TCOFFSET = SendMessage(GetDlgItem(m_hWnd, IDC_TCOFFSETX), UDM_GETPOS, 0, 0) & 0xFFFF; + TCOFFSET |= (SendMessage(GetDlgItem(m_hWnd, IDC_TCOFFSETY), UDM_GETPOS, 0, 0) & 0xFFFF) << 16; + + theApp.SetConfig("UserHacks_TCOffset", TCOFFSET); + EndDialog(m_hWnd, id); } break; } diff --git a/plugins/GSdx/GSState.cpp b/plugins/GSdx/GSState.cpp index 94e7113e60..2283d24e32 100644 --- a/plugins/GSdx/GSState.cpp +++ b/plugins/GSdx/GSState.cpp @@ -2562,7 +2562,7 @@ void GSState::GetTextureMinMax(GSVector4i& r, const GIFRegTEX0& TEX0, const GIFR __assume(0); } - if(wms + wmt < 6) + if(wms != CLAMP_REGION_REPEAT || wmt != CLAMP_REGION_REPEAT) { GSVector4 st = m_vt.m_min.t.xyxy(m_vt.m_max.t); @@ -2577,6 +2577,7 @@ void GSState::GetTextureMinMax(GSVector4i& r, const GIFRegTEX0& TEX0, const GIFR int mask = 0; + // See commented code below for the meaning of mask if(wms == CLAMP_REPEAT || wmt == CLAMP_REPEAT) { u = uv & GSVector4i::xffffffff().srl32(32 - tw); @@ -2588,11 +2589,17 @@ void GSState::GetTextureMinMax(GSVector4i& r, const GIFRegTEX0& TEX0, const GIFR mask = (uu.upl32(vv) == uu.uph32(vv)).mask(); } - uv = uv.rintersect(tr); + uv = uv.rintersect(vr - GSVector4i(0,0,1,1)); switch(wms) { case CLAMP_REPEAT: + // This commented code cannot be used directly because it needs uv before the intersection + /*if (uv_.x >> tw == uv_.z >> tw) + { + vr.x = max(vr.x, (uv_.x & ((1 << tw) - 1))); + vr.z = min(vr.z, (uv_.z & ((1 << tw) - 1)) + 1); + }*/ if(mask & 0x000f) {if(vr.x < u.x) vr.x = u.x; if(vr.z > u.z + 1) vr.z = u.z + 1;} break; case CLAMP_CLAMP: @@ -2609,6 +2616,11 @@ void GSState::GetTextureMinMax(GSVector4i& r, const GIFRegTEX0& TEX0, const GIFR switch(wmt) { case CLAMP_REPEAT: + /*if (uv_.y >> th == uv_.w >> th) + { + vr.y = max(vr.y, (uv_.y & ((1 << th) - 1))); + vr.w = min(vr.w, (uv_.w & ((1 << th) - 1)) + 1); + }*/ if(mask & 0xf000) {if(vr.y < v.y) vr.y = v.y; if(vr.w > v.w + 1) vr.w = v.w + 1;} break; case CLAMP_CLAMP: @@ -2625,12 +2637,13 @@ void GSState::GetTextureMinMax(GSVector4i& r, const GIFRegTEX0& TEX0, const GIFR vr = vr.rintersect(tr); + // This really shouldn't happen now except with the clamping region set entirely outside the texture, + // special handling should be written for that case. if(vr.rempty()) { // NOTE: this can happen when texcoords are all outside the texture or clamping area is zero, but we can't // let the texture cache update nothing, the sampler will still need a single texel from the border somewhere // examples: - // - ICO opening menu (texture looks like the miniature silhouette of everything except the sky) // - THPS (no visible problems) // - NFSMW (strange rectangles on screen, might be unrelated) @@ -5040,6 +5053,30 @@ bool GSC_UrbanReign(const GSFrameInfo& fi, int& skip) return true; } +bool GSC_SteambotChronicles(const GSFrameInfo& fi, int& skip) +{ + if(skip == 0) + { + // Author: miseru99 on forums.pcsx2.net + if(fi.TME && fi.TPSM == PSM_PSMCT16S) + { + if(fi.FBP == 0x1180) + { + skip=1;//1 deletes some of the glitched effects + } + else if(fi.FBP == 0) + { + skip=100;//deletes most others(too high deletes the buggy sea completely;c, too low causes glitches to be visible) + } + else if(g_aggressive && fi.FBP != 0)//Agressive CRC + { + skip=19;//"speedhack", makes the game very light, vaporized water can disappear when not looked at directly, possibly some interface still, other value to try: 6 breaks menu background, possibly nothing(?) during gameplay, but it's slower, hence not much of a speedhack anymore + } + } + } + return true; +} + #ifdef ENABLE_DYNAMIC_CRC_HACK #include @@ -5311,6 +5348,7 @@ bool GSState::IsBadFrame(int& skip, int UserHacks_SkipDraw) map[CRC::SoulCalibur3] = GSC_SoulCalibur3; map[CRC::Simple2000Vol114] = GSC_Simple2000Vol114; map[CRC::UrbanReign] = GSC_UrbanReign; + map[CRC::SteambotChronicles] = GSC_SteambotChronicles; } // TODO: just set gsc in SetGameCRC once diff --git a/plugins/GSdx/GSTextureCache.cpp b/plugins/GSdx/GSTextureCache.cpp index d82ed1242f..9831fa5309 100644 --- a/plugins/GSdx/GSTextureCache.cpp +++ b/plugins/GSdx/GSTextureCache.cpp @@ -196,24 +196,7 @@ GSTextureCache::Target* GSTextureCache::LookupTarget(const GIFRegTEX0& TEX0, int if(multiplier > 1) // it's limited to a maximum of 4 on reading the config { - -#if 0 //#ifdef ENABLE_UPSCALE_HACKS //not happy with this yet.. - - float x = 1.0f; - float y = 1.0f; - - switch(multiplier) - { - case 2: x = 1.9375; y = 2.0f; break; // x res get's rid of vertical lines in many games - case 3: x = 2.9375f; y = 2.9375f; break; // not helping much - case 4: x = 3.875f; y = 3.875f; break; // not helping much - default: __assume(0); - } - - dst->m_texture->SetScale(GSVector2::_(x, y)); -#else dst->m_texture->SetScale(GSVector2((float)multiplier, (float)multiplier)); -#endif } else { diff --git a/plugins/GSdx/GSTextureFX11.cpp b/plugins/GSdx/GSTextureFX11.cpp index 689248c13b..d51ec6ec0d 100644 --- a/plugins/GSdx/GSTextureFX11.cpp +++ b/plugins/GSdx/GSTextureFX11.cpp @@ -177,7 +177,7 @@ void GSDevice11::SetupPS(PSSelector sel, const PSConstantBuffer* cb, PSSamplerSe if(i == m_ps.end()) { - string str[17]; + string str[18]; str[0] = format("%d", sel.fst); str[1] = format("%d", sel.wms); @@ -195,7 +195,8 @@ void GSDevice11::SetupPS(PSSelector sel, const PSConstantBuffer* cb, PSSamplerSe str[13] = format("%d", sel.colclip); str[14] = format("%d", sel.date); str[15] = format("%d", sel.spritehack); - str[16] = format("%d", sel.point_sampler); + str[16] = format("%d", sel.tcoffsethack); + str[17] = format("%d", sel.point_sampler); D3D11_SHADER_MACRO macro[] = { @@ -215,7 +216,8 @@ void GSDevice11::SetupPS(PSSelector sel, const PSConstantBuffer* cb, PSSamplerSe {"PS_COLCLIP", str[13].c_str()}, {"PS_DATE", str[14].c_str()}, {"PS_SPRITEHACK", str[15].c_str()}, - {"PS_POINT_SAMPLER", str[16].c_str()}, + {"PS_TCOFFSETHACK", str[16].c_str()}, + {"PS_POINT_SAMPLER", str[17].c_str()}, {NULL, NULL}, }; diff --git a/plugins/GSdx/GSTextureFX9.cpp b/plugins/GSdx/GSTextureFX9.cpp index 132228ff89..a929458a82 100644 --- a/plugins/GSdx/GSTextureFX9.cpp +++ b/plugins/GSdx/GSTextureFX9.cpp @@ -135,7 +135,7 @@ void GSDevice9::SetupPS(PSSelector sel, const PSConstantBuffer* cb, PSSamplerSel if(i == m_ps.end()) { - string str[16]; + string str[17]; str[0] = format("%d", sel.fst); str[1] = format("%d", sel.wms); @@ -152,7 +152,8 @@ void GSDevice9::SetupPS(PSSelector sel, const PSConstantBuffer* cb, PSSamplerSel str[12] = format("%d", sel.colclip); str[13] = format("%d", sel.date); str[14] = format("%d", sel.spritehack); - str[15] = format("%d", sel.point_sampler); + str[15] = format("%d", sel.tcoffsethack); + str[16] = format("%d", sel.point_sampler); D3DXMACRO macro[] = { @@ -171,7 +172,8 @@ void GSDevice9::SetupPS(PSSelector sel, const PSConstantBuffer* cb, PSSamplerSel {"PS_COLCLIP", str[12].c_str()}, {"PS_DATE", str[13].c_str()}, {"PS_SPRITEHACK", str[14].c_str()}, - {"PS_POINT_SAMPLER", str[15].c_str()}, + {"PS_TCOFFSETHACK", str[15].c_str()}, + {"PS_POINT_SAMPLER", str[16].c_str()}, {NULL, NULL}, }; diff --git a/plugins/GSdx/GSTextureFXOGL.cpp b/plugins/GSdx/GSTextureFXOGL.cpp index 5594147575..dbf8ae46ed 100644 --- a/plugins/GSdx/GSTextureFXOGL.cpp +++ b/plugins/GSdx/GSTextureFXOGL.cpp @@ -23,10 +23,15 @@ #include "GSDeviceOGL.h" #include "GSTables.h" +#include "res/tfx.h" + +static const uint32 g_vs_cb_index = 20; +static const uint32 g_ps_cb_index = 21; + void GSDeviceOGL::CreateTextureFX() { - m_vs_cb = new GSUniformBufferOGL(4, sizeof(VSConstantBuffer)); - m_ps_cb = new GSUniformBufferOGL(5, sizeof(PSConstantBuffer)); + m_vs_cb = new GSUniformBufferOGL(g_vs_cb_index, sizeof(VSConstantBuffer)); + m_ps_cb = new GSUniformBufferOGL(g_ps_cb_index, sizeof(PSConstantBuffer)); glGenSamplers(1, &m_rt_ss); // FIXME, seem to have no difference between sampler !!! @@ -64,9 +69,9 @@ void GSDeviceOGL::CreateTextureFX() #ifdef _LINUX GLuint dummy; std::string macro = "\n"; - CompileShaderFromSource("tfx.glsl", "vs_main", GL_VERTEX_SHADER, &dummy, macro); - CompileShaderFromSource("tfx.glsl", "gs_main", GL_GEOMETRY_SHADER, &dummy, macro); - CompileShaderFromSource("tfx.glsl", "ps_main", GL_FRAGMENT_SHADER, &dummy, macro); + CompileShaderFromSource("tfx.glsl", "vs_main", GL_VERTEX_SHADER, &dummy, tfx_glsl, macro); + CompileShaderFromSource("tfx.glsl", "gs_main", GL_GEOMETRY_SHADER, &dummy, tfx_glsl, macro); + CompileShaderFromSource("tfx.glsl", "ps_main", GL_FRAGMENT_SHADER, &dummy, tfx_glsl, macro); #endif } @@ -86,7 +91,7 @@ void GSDeviceOGL::SetupVS(VSSelector sel, const VSConstantBuffer* cb) + format("#define VS_RTCOPY %d\n", sel.rtcopy); GLuint vs; - CompileShaderFromSource("tfx.glsl", "vs_main", GL_VERTEX_SHADER, &vs, macro); + CompileShaderFromSource("tfx.glsl", "vs_main", GL_VERTEX_SHADER, &vs, tfx_glsl, macro); m_vs[sel] = vs; i = m_vs.find(sel); @@ -117,7 +122,7 @@ void GSDeviceOGL::SetupGS(GSSelector sel) std::string macro = format("#define GS_IIP %d\n", sel.iip) + format("#define GS_PRIM %d\n", sel.prim); - CompileShaderFromSource("tfx.glsl", "gs_main", GL_GEOMETRY_SHADER, &gs, macro); + CompileShaderFromSource("tfx.glsl", "gs_main", GL_GEOMETRY_SHADER, &gs, tfx_glsl, macro); m_gs[sel] = gs; } else { @@ -155,9 +160,11 @@ void GSDeviceOGL::SetupPS(PSSelector sel, const PSConstantBuffer* cb, PSSamplerS + format("#define PS_LTF %d\n", sel.ltf) + format("#define PS_COLCLIP %d\n", sel.colclip) + format("#define PS_DATE %d\n", sel.date) - + format("#define PS_SPRITEHACK %d\n", sel.spritehack); + + format("#define PS_SPRITEHACK %d\n", sel.spritehack) + + format("#define PS_TCOFFSETHACK %d\n", sel.tcoffsethack) + + format("#define PS_POINT_SAMPLER %d\n", sel.point_sampler); - CompileShaderFromSource("tfx.glsl", "ps_main", GL_FRAGMENT_SHADER, &ps, macro); + CompileShaderFromSource("tfx.glsl", "ps_main", GL_FRAGMENT_SHADER, &ps, tfx_glsl, macro); m_ps[sel] = ps; i = m_ps.find(sel); diff --git a/plugins/GSdx/GSTextureOGL.cpp b/plugins/GSdx/GSTextureOGL.cpp index 1a845875ff..89a654bd4f 100644 --- a/plugins/GSdx/GSTextureOGL.cpp +++ b/plugins/GSdx/GSTextureOGL.cpp @@ -19,8 +19,6 @@ * */ -#pragma once - #include "stdafx.h" #include #include "GSTextureOGL.h" @@ -66,7 +64,7 @@ GSTextureOGL::GSTextureOGL(int type, int w, int h, bool msaa, int format, GLuint //FIXME I not sure we need a pixel buffer object. It seems more a texture // glGenBuffers(1, &m_texture_id); // m_texture_target = GL_PIXEL_UNPACK_BUFFER; - // assert(0); + // ASSERT(0); // Note there is also a buffer texture!!! // http://www.opengl.org/wiki/Buffer_Texture // Note: in this case it must use in GLSL @@ -81,6 +79,7 @@ GSTextureOGL::GSTextureOGL(int type, int w, int h, bool msaa, int format, GLuint case GSTexture::Backbuffer: m_texture_target = 0; m_texture_id = 0; + break; default: break; } @@ -97,11 +96,6 @@ GSTextureOGL::GSTextureOGL(int type, int w, int h, bool msaa, int format, GLuint // Allocate the buffer switch (m_type) { - case GSTexture::DepthStencil: - EnableUnit(0); - glTexImage2D(m_texture_target, 0, m_format, m_size.x, m_size.y, 0, GL_DEPTH_STENCIL, GL_FLOAT_32_UNSIGNED_INT_24_8_REV, NULL); - break; - case GSTexture::Offscreen: // Allocate a pbo with the texture if (m_format == GL_RGBA8) m_pbo_size = m_size.x * m_size.y * 4; @@ -114,28 +108,22 @@ GSTextureOGL::GSTextureOGL(int type, int w, int h, bool msaa, int format, GLuint glBindBuffer(GL_PIXEL_PACK_BUFFER, m_pbo_id); glBufferData(GL_PIXEL_PACK_BUFFER, m_pbo_size, NULL, GL_STREAM_DRAW); glBindBuffer(GL_PIXEL_PACK_BUFFER, 0); + ASSERT(!m_msaa); + case GSTexture::DepthStencil: case GSTexture::RenderTarget: case GSTexture::Texture: - // FIXME + // FIXME: check the opensource driver // Howto allocate the texture unit !!! // In worst case the HW renderer seems to use 3 texture unit // For the moment SW renderer only use 1 so don't bother EnableUnit(0); - // Did we need to setup a default sampler of the texture now? - // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); - // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); - // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); - if (m_format == GL_RGBA8) - glTexImage2D(m_texture_target, 0, m_format, m_size.x, m_size.y, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); - else if (m_format == GL_R16UI) - glTexImage2D(m_texture_target, 0, m_format, m_size.x, m_size.y, 0, GL_RED_INTEGER, GL_UNSIGNED_SHORT, NULL); - else if (m_format == GL_R8) - glTexImage2D(m_texture_target, 0, m_format, m_size.x, m_size.y, 0, GL_RED, GL_UNSIGNED_BYTE, NULL); - else { - fprintf(stderr, "wrong texture pixel format :%x\n", m_format); - ASSERT(0); // TODO Later + if (m_msaa) { + ASSERT(m_texture_target == GL_TEXTURE_2D_MULTISAMPLE); + // Require a recent GLEW and GL4.3 + //glTexStorage2DMultisample(m_texture_target, msaa_level, m_format, m_size.x, m_size.y, false); + } else { + glTexStorage2D(m_texture_target, 1, m_format, m_size.x, m_size.y); } break; default: break; diff --git a/plugins/GSdx/GSWndOGL.cpp b/plugins/GSdx/GSWndOGL.cpp index 0b79a16e6b..83e6c1ebc7 100644 --- a/plugins/GSdx/GSWndOGL.cpp +++ b/plugins/GSdx/GSWndOGL.cpp @@ -28,6 +28,13 @@ GSWndOGL::GSWndOGL() { } +static bool ctxError = false; +static int ctxErrorHandler(Display *dpy, XErrorEvent *ev) +{ + ctxError = true; + return 0; +} + bool GSWndOGL::CreateContext(int major, int minor) { if ( !m_NativeDisplay || !m_NativeWindow ) @@ -58,6 +65,11 @@ bool GSWndOGL::CreateContext(int major, int minor) PFNGLXCREATECONTEXTATTRIBSARBPROC glXCreateContextAttribsARB = (PFNGLXCREATECONTEXTATTRIBSARBPROC)glXGetProcAddress((const GLubyte*) "glXCreateContextAttribsARB"); if (!glXCreateContextAttribsARB) return false; + // Install a dummy handler to handle gracefully (aka not segfault) the support of GL version + int (*oldHandler)(Display*, XErrorEvent*) = XSetErrorHandler(&ctxErrorHandler); + // Be sure the handler is installed + XSync( m_XDisplay, false); + // Create a context int context_attribs[] = { @@ -71,9 +83,18 @@ bool GSWndOGL::CreateContext(int major, int minor) }; m_context = glXCreateContextAttribsARB(m_NativeDisplay, fbc[0], 0, true, context_attribs); - if (!m_context) return false; - XSync( m_NativeDisplay, false); + // Don't forget to reinstall the older Handler + XSetErrorHandler(oldHandler); + + // Get latest error + XSync( m_XDisplay, false); + + if (!m_context || ctxError) { + fprintf(stderr, "Failed to create the opengl context. Check your drivers support openGL %d.%d. Hint: opensource drivers don't\n", major, minor ); + return false; + } + return true; } diff --git a/plugins/GSdx/GSdx.rc b/plugins/GSdx/GSdx.rc index a5b602546f..0b293f825e 100644 --- a/plugins/GSdx/GSdx.rc +++ b/plugins/GSdx/GSdx.rc @@ -74,28 +74,34 @@ IDB_LOGO10 BITMAP "res\\logo10.bmp" // Dialog // -IDD_HACKS DIALOGEX 0, 0, 315, 203 +IDD_HACKS DIALOGEX 0, 0, 315, 236 STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_POPUP | WS_CAPTION | WS_SYSMENU CAPTION "Hacks Configuration" FONT 8, "MS Shell Dlg", 400, 0, 0x1 BEGIN - DEFPUSHBUTTON "OK",IDOK,258,182,50,14 - GROUPBOX "Hack",IDC_STATIC,7,7,76,165,0,WS_EX_TRANSPARENT - GROUPBOX "Description",IDC_STATIC,85,7,223,165 + DEFPUSHBUTTON "OK",IDOK,258,215,50,14 + GROUPBOX "Hack",IDC_STATIC,7,7,86,201,0,WS_EX_TRANSPARENT + GROUPBOX "Description",IDC_STATIC,96,7,212,201 LTEXT "MSAA",IDC_STATIC_MSAA,14,20,20,8 LTEXT "Skipdraw",IDC_STATIC_SKIPDRAW,14,37,30,8 - EDITTEXT IDC_SKIPDRAWHACKEDIT,45,35,24,14,ES_RIGHT | ES_AUTOHSCROLL - CONTROL "",IDC_SKIPDRAWHACK,"msctls_updown32",UDS_SETBUDDYINT | UDS_AUTOBUDDY | UDS_ARROWKEYS,68,35,10,14 + EDITTEXT IDC_SKIPDRAWHACKEDIT,53,35,35,14,ES_RIGHT | ES_AUTOHSCROLL + CONTROL "",IDC_SKIPDRAWHACK,"msctls_updown32",UDS_SETBUDDYINT | UDS_ALIGNRIGHT | UDS_AUTOBUDDY | UDS_ARROWKEYS | UDS_NOTHOUSANDS,88,35,10,14 CONTROL "Alpha",IDC_ALPHAHACK,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,14,54,34,10 CONTROL "Half-pixel Offset",IDC_OFFSETHACK,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,14,71,65,10 CONTROL "Sprite",IDC_SPRITEHACK,"Button",BS_AUTO3STATE | WS_TABSTOP,14,88,35,10 - LTEXT "USE AT YOUR OWN RISK!",IDC_STATIC,7,182,84,8,WS_DISABLED - COMBOBOX IDC_MSAACB,35,18,44,63,CBS_DROPDOWNLIST | WS_VSCROLL | WS_TABSTOP + LTEXT "USE AT YOUR OWN RISK!",IDC_STATIC,7,218,84,11,WS_DISABLED + COMBOBOX IDC_MSAACB,35,18,54,63,CBS_DROPDOWNLIST | WS_VSCROLL | WS_TABSTOP CONTROL "WildArmsOffset",IDC_WILDHACK,"Button",BS_AUTO3STATE | WS_TABSTOP,14,105,64,10 - LTEXT "TEXT_GOES_HERE",IDC_HACK_DESCRIPTION,92,20,209,145 + LTEXT "TEXT_GOES_HERE",IDC_HACK_DESCRIPTION,102,20,199,183 CONTROL "Aggressive-CRC",IDC_AGGRESSIVECRC,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,14,122,66,10 CONTROL "Alpha Stencil",IDC_ALPHASTENCIL,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,14,139,66,10 CONTROL "Disable CRCs",IDC_CHECK_DISABLE_ALL_HACKS,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,14,156,58,10 + LTEXT "TC Offset X",IDC_STATIC_TCOFFSETX,14,173,37,8 + EDITTEXT IDC_TCOFFSETX2,53,171,35,14,ES_RIGHT | ES_AUTOHSCROLL + CONTROL "",IDC_TCOFFSETX,"msctls_updown32",UDS_SETBUDDYINT | UDS_ALIGNRIGHT | UDS_AUTOBUDDY | UDS_ARROWKEYS | UDS_NOTHOUSANDS,87,171,11,14 + EDITTEXT IDC_TCOFFSETY2,53,188,35,14,ES_RIGHT | ES_AUTOHSCROLL + CONTROL "",IDC_TCOFFSETY,"msctls_updown32",UDS_SETBUDDYINT | UDS_ALIGNRIGHT | UDS_AUTOBUDDY | UDS_ARROWKEYS | UDS_NOTHOUSANDS,86,188,11,14 + LTEXT "TC Offset Y",IDC_STATIC_TCOFFSETY,14,190,37,8 END IDD_SHADEBOOST DIALOGEX 0, 0, 316, 129 @@ -262,7 +268,7 @@ BEGIN LEFTMARGIN, 7 RIGHTMARGIN, 308 TOPMARGIN, 7 - BOTTOMMARGIN, 196 + BOTTOMMARGIN, 229 END IDD_SHADEBOOST, DIALOG diff --git a/plugins/GSdx/config.h b/plugins/GSdx/config.h index 3dec9a7b97..ab1fd551de 100644 --- a/plugins/GSdx/config.h +++ b/plugins/GSdx/config.h @@ -28,8 +28,6 @@ //#define ENABLE_DYNAMIC_CRC_HACK #define DYNA_DLL_PATH "c:/dev/pcsx2/trunk/tools/dynacrchack/DynaCrcHack.dll" -#define ENABLE_UPSCALE_HACKS // Hacks intended to fix upscaling / rendering glitches in HW renderers - //#define DISABLE_HW_TEXTURE_CACHE // Slow but fixes a lot of bugs //#define DISABLE_BITMASKING @@ -42,3 +40,9 @@ #ifdef _DEBUG #define ENABLE_OGL_DEBUG // Create a debug context and check opengl command status. Allow also to dump various textures/states. #endif + +// Set manually uniform buffer index +//#define DISABLE_GL42 + +// Debug: use single program for all shaders. +//#define DISABLE_GL41_SSO diff --git a/plugins/GSdx/res/convert.h b/plugins/GSdx/res/convert.h new file mode 100644 index 0000000000..66379bd16d --- /dev/null +++ b/plugins/GSdx/res/convert.h @@ -0,0 +1,196 @@ +/* + * Copyright (C) 2011-2013 Gregory hainaut + * Copyright (C) 2007-2009 Gabest + * + * This file was generated by glsl2h.pl script + * + * This Program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2, or (at your option) + * any later version. + * + * This Program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with GNU Make; see the file COPYING. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA USA. + * http://www.gnu.org/copyleft/gpl.html + * + */ + +#pragma once + +#include "stdafx.h" + +extern const char* convert_glsl = + "//#version 420 // Keep it for editor detection\n" + "\n" + "struct vertex_basic\n" + "{\n" + " vec4 p;\n" + " vec2 t;\n" + "};\n" + "\n" + "\n" + "#ifdef VERTEX_SHADER\n" + "\n" + "out gl_PerVertex {\n" + " vec4 gl_Position;\n" + " float gl_PointSize;\n" + " float gl_ClipDistance[];\n" + "};\n" + "\n" + "layout(location = 0) in vec4 POSITION;\n" + "layout(location = 1) in vec2 TEXCOORD0;\n" + "\n" + "// FIXME set the interpolation (don't know what dx do)\n" + "// flat means that there is no interpolation. The value given to the fragment shader is based on the provoking vertex conventions.\n" + "//\n" + "// noperspective means that there will be linear interpolation in window-space. This is usually not what you want, but it can have its uses.\n" + "//\n" + "// smooth, the default, means to do perspective-correct interpolation.\n" + "//\n" + "// The centroid qualifier only matters when multisampling. If this qualifier is not present, then the value is interpolated to the pixel's center, anywhere in the pixel, or to one of the pixel's samples. This sample may lie outside of the actual primitive being rendered, since a primitive can cover only part of a pixel's area. The centroid qualifier is used to prevent this; the interpolation point must fall within both the pixel's area and the primitive's area.\n" + "layout(location = 0) out vertex_basic VSout;\n" + "\n" + "void vs_main()\n" + "{\n" + " VSout.p = POSITION;\n" + " VSout.t = TEXCOORD0;\n" + " gl_Position = POSITION; // NOTE I don't know if it is possible to merge POSITION_OUT and gl_Position\n" + "}\n" + "\n" + "#endif\n" + "\n" + "#ifdef GEOMETRY_SHADER\n" + "in gl_PerVertex {\n" + " vec4 gl_Position;\n" + " float gl_PointSize;\n" + " float gl_ClipDistance[];\n" + "} gl_in[];\n" + "\n" + "out gl_PerVertex {\n" + " vec4 gl_Position;\n" + " float gl_PointSize;\n" + " float gl_ClipDistance[];\n" + "};\n" + "\n" + "// FIXME\n" + "// AMD Driver bug again !!!!\n" + "//layout(location = 0) in vertex GSin[];\n" + "in vertex_basic GSin[];\n" + "\n" + "layout(location = 0) out vertex_basic GSout;\n" + "layout(triangles) in;\n" + "layout(triangle_strip, max_vertices = 3) out;\n" + "\n" + "void gs_main()\n" + "{\n" + " for(int i = 0; i < gl_in.length(); i++) {\n" + " gl_Position = gl_in[i].gl_Position;\n" + " GSout = GSin[i];\n" + " EmitVertex();\n" + " }\n" + " EndPrimitive();\n" + "}\n" + "#endif\n" + "\n" + "#ifdef FRAGMENT_SHADER\n" + "// NOTE: pixel can be clip with \"discard\"\n" + "\n" + "layout(location = 0) in vertex_basic PSin;\n" + "\n" + "layout(location = 0) out vec4 SV_Target0;\n" + "layout(location = 1) out uint SV_Target1;\n" + "\n" + "layout(binding = 0) uniform sampler2D TextureSampler;\n" + "\n" + "vec4 sample_c()\n" + "{\n" + " return texture(TextureSampler, PSin.t );\n" + "}\n" + "\n" + "vec4 ps_crt(uint i)\n" + "{\n" + " vec4 mask[4] =\n" + " {\n" + " vec4(1, 0, 0, 0),\n" + " vec4(0, 1, 0, 0),\n" + " vec4(0, 0, 1, 0),\n" + " vec4(1, 1, 1, 0)\n" + " };\n" + "\n" + " return sample_c() * clamp((mask[i] + 0.5f), 0.0f, 1.0f);\n" + "}\n" + "\n" + "void ps_main0()\n" + "{\n" + " SV_Target0 = sample_c();\n" + "}\n" + "\n" + "void ps_main1()\n" + "{\n" + " vec4 c = sample_c();\n" + "\n" + " c.a *= 256.0f / 127.0f; // hm, 0.5 won't give us 1.0 if we just multiply with 2\n" + "\n" + " highp uvec4 i = uvec4(c * vec4(uint(0x001f), uint(0x03e0), uint(0x7c00), uint(0x8000)));\n" + "\n" + " SV_Target1 = (i.x & uint(0x001f)) | (i.y & uint(0x03e0)) | (i.z & uint(0x7c00)) | (i.w & uint(0x8000));\n" + "}\n" + "\n" + "void ps_main7()\n" + "{\n" + " vec4 c = sample_c();\n" + "\n" + " c.a = dot(c.rgb, vec3(0.299, 0.587, 0.114));\n" + "\n" + " SV_Target0 = c;\n" + "}\n" + "\n" + "void ps_main5() // triangular\n" + "{\n" + " highp uvec4 p = uvec4(PSin.p);\n" + "\n" + " vec4 c = ps_crt(((p.x + ((p.y >> 1u) & 1u) * 3u) >> 1u) \% 3u);\n" + "\n" + " SV_Target0 = c;\n" + "}\n" + "\n" + "void ps_main6() // diagonal\n" + "{\n" + " uvec4 p = uvec4(PSin.p);\n" + "\n" + " vec4 c = ps_crt((p.x + (p.y \% 3u)) \% 3u);\n" + "\n" + " SV_Target0 = c;\n" + "}\n" + "\n" + "void ps_main2()\n" + "{\n" + " if((sample_c().a - 128.0f / 255) < 0) // >= 0x80 pass\n" + " discard;\n" + "\n" + " SV_Target0 = vec4(0.0f, 0.0f, 0.0f, 0.0f);\n" + "}\n" + "void ps_main3()\n" + "{\n" + " if((127.95f / 255 - sample_c().a) <0) // < 0x80 pass (== 0x80 should not pass)\n" + " discard;\n" + "\n" + " SV_Target0 = vec4(0.0f, 0.0f, 0.0f, 0.0f);\n" + "}\n" + "void ps_main4()\n" + "{\n" + " // FIXME mod and fmod are different when value are negative\n" + " // output.c = fmod(sample_c(input.t) * 255 + 0.5f, 256) / 255;\n" + " vec4 c = mod(sample_c() * 255 + 0.5f, 256) / 255;\n" + "\n" + " SV_Target0 = c;\n" + "}\n" + "\n" + "#endif\n" + ; diff --git a/plugins/GSdx/res/interlace.glsl b/plugins/GSdx/res/interlace.glsl index 97e567fa1b..21b81af113 100644 --- a/plugins/GSdx/res/interlace.glsl +++ b/plugins/GSdx/res/interlace.glsl @@ -11,7 +11,11 @@ layout(location = 0) in vertex_basic PSin; layout(location = 0) out vec4 SV_Target0; -layout(std140, binding = 2) uniform cb0 +#ifdef DISABLE_GL42 +layout(std140) uniform cb11 +#else +layout(std140, binding = 11) uniform cb11 +#endif { vec2 ZrH; float hH; diff --git a/plugins/GSdx/res/interlace.h b/plugins/GSdx/res/interlace.h new file mode 100644 index 0000000000..ed21d59fe8 --- /dev/null +++ b/plugins/GSdx/res/interlace.h @@ -0,0 +1,92 @@ +/* + * Copyright (C) 2011-2013 Gregory hainaut + * Copyright (C) 2007-2009 Gabest + * + * This file was generated by glsl2h.pl script + * + * This Program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2, or (at your option) + * any later version. + * + * This Program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with GNU Make; see the file COPYING. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA USA. + * http://www.gnu.org/copyleft/gpl.html + * + */ + +#pragma once + +#include "stdafx.h" + +extern const char* interlace_glsl = + "//#version 420 // Keep it for editor detection\n" + "\n" + "struct vertex_basic\n" + "{\n" + " vec4 p;\n" + " vec2 t;\n" + "};\n" + "\n" + "#ifdef FRAGMENT_SHADER\n" + "layout(location = 0) in vertex_basic PSin;\n" + "\n" + "layout(location = 0) out vec4 SV_Target0;\n" + "\n" + "#ifdef DISABLE_GL42\n" + "layout(std140) uniform cb11\n" + "#else\n" + "layout(std140, binding = 11) uniform cb11\n" + "#endif\n" + "{\n" + " vec2 ZrH;\n" + " float hH;\n" + "};\n" + "\n" + "layout(binding = 0) uniform sampler2D TextureSampler;\n" + "\n" + "// TODO ensure that clip (discard) is < 0 and not <= 0 ???\n" + "void ps_main0()\n" + "{\n" + " // I'm not sure it impact us but be safe to lookup texture before conditional if\n" + " // see: http://www.opengl.org/wiki/GLSL_Sampler#Non-uniform_flow_control\n" + " vec4 c = texture(TextureSampler, PSin.t);\n" + " if (fract(PSin.t.y * hH) - 0.5 < 0.0)\n" + " discard;\n" + "\n" + " SV_Target0 = c;\n" + "}\n" + "\n" + "void ps_main1()\n" + "{\n" + " // I'm not sure it impact us but be safe to lookup texture before conditional if\n" + " // see: http://www.opengl.org/wiki/GLSL_Sampler#Non-uniform_flow_control\n" + " vec4 c = texture(TextureSampler, PSin.t);\n" + " if (0.5 - fract(PSin.t.y * hH) < 0.0)\n" + " discard;\n" + "\n" + " SV_Target0 = c;\n" + "}\n" + "\n" + "void ps_main2()\n" + "{\n" + " vec4 c0 = texture(TextureSampler, PSin.t - ZrH);\n" + " vec4 c1 = texture(TextureSampler, PSin.t);\n" + " vec4 c2 = texture(TextureSampler, PSin.t + ZrH);\n" + "\n" + " SV_Target0 = (c0 + c1 * 2 + c2) / 4;\n" + "}\n" + "\n" + "void ps_main3()\n" + "{\n" + " SV_Target0 = texture(TextureSampler, PSin.t);\n" + "}\n" + "\n" + "#endif\n" + ; diff --git a/plugins/GSdx/res/merge.glsl b/plugins/GSdx/res/merge.glsl index e9a93bdc88..ed3ca36062 100644 --- a/plugins/GSdx/res/merge.glsl +++ b/plugins/GSdx/res/merge.glsl @@ -11,7 +11,11 @@ layout(location = 0) in vertex_basic PSin; layout(location = 0) out vec4 SV_Target0; -layout(std140, binding = 1) uniform cb0 +#ifdef DISABLE_GL42 +layout(std140) uniform cb10 +#else +layout(std140, binding = 10) uniform cb10 +#endif { vec4 BGColor; }; diff --git a/plugins/GSdx/res/merge.h b/plugins/GSdx/res/merge.h new file mode 100644 index 0000000000..a3012684bf --- /dev/null +++ b/plugins/GSdx/res/merge.h @@ -0,0 +1,68 @@ +/* + * Copyright (C) 2011-2013 Gregory hainaut + * Copyright (C) 2007-2009 Gabest + * + * This file was generated by glsl2h.pl script + * + * This Program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2, or (at your option) + * any later version. + * + * This Program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with GNU Make; see the file COPYING. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA USA. + * http://www.gnu.org/copyleft/gpl.html + * + */ + +#pragma once + +#include "stdafx.h" + +extern const char* merge_glsl = + "//#version 420 // Keep it for editor detection\n" + "\n" + "struct vertex_basic\n" + "{\n" + " vec4 p;\n" + " vec2 t;\n" + "};\n" + "\n" + "#ifdef FRAGMENT_SHADER\n" + "layout(location = 0) in vertex_basic PSin;\n" + "\n" + "layout(location = 0) out vec4 SV_Target0;\n" + "\n" + "#ifdef DISABLE_GL42\n" + "layout(std140) uniform cb10\n" + "#else\n" + "layout(std140, binding = 10) uniform cb10\n" + "#endif\n" + "{\n" + " vec4 BGColor;\n" + "};\n" + "\n" + "layout(binding = 0) uniform sampler2D TextureSampler;\n" + "\n" + "void ps_main0()\n" + "{\n" + " vec4 c = texture(TextureSampler, PSin.t);\n" + " c.a = min(c.a * 2, 1.0);\n" + " SV_Target0 = c;\n" + "}\n" + "\n" + "void ps_main1()\n" + "{\n" + " vec4 c = texture(TextureSampler, PSin.t);\n" + " c.a = BGColor.a;\n" + " SV_Target0 = c;\n" + "}\n" + "\n" + "#endif\n" + ; diff --git a/plugins/GSdx/res/shadeboost.glsl b/plugins/GSdx/res/shadeboost.glsl index c98222d80a..006329ae80 100644 --- a/plugins/GSdx/res/shadeboost.glsl +++ b/plugins/GSdx/res/shadeboost.glsl @@ -18,7 +18,11 @@ layout(location = 0) in vertex_basic PSin; layout(location = 0) out vec4 SV_Target0; -layout(std140, binding = 6) uniform cb0 +#ifdef DISABLE_GL42 +layout(std140) uniform cb12 +#else +layout(std140, binding = 12) uniform cb12 +#endif { vec4 BGColor; }; diff --git a/plugins/GSdx/res/shadeboost.h b/plugins/GSdx/res/shadeboost.h new file mode 100644 index 0000000000..172175c349 --- /dev/null +++ b/plugins/GSdx/res/shadeboost.h @@ -0,0 +1,94 @@ +/* + * Copyright (C) 2011-2013 Gregory hainaut + * Copyright (C) 2007-2009 Gabest + * + * This file was generated by glsl2h.pl script + * + * This Program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2, or (at your option) + * any later version. + * + * This Program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with GNU Make; see the file COPYING. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA USA. + * http://www.gnu.org/copyleft/gpl.html + * + */ + +#pragma once + +#include "stdafx.h" + +extern const char* shadeboost_glsl = + "//#version 420 // Keep it for editor detection\n" + "\n" + "/*\n" + "** Contrast, saturation, brightness\n" + "** Code of this function is from TGM's shader pack\n" + "** http://irrlicht.sourceforge.net/phpBB2/viewtopic.php?t=21057\n" + "*/\n" + "\n" + "struct vertex_basic\n" + "{\n" + " vec4 p;\n" + " vec2 t;\n" + "};\n" + "\n" + "#ifdef FRAGMENT_SHADER\n" + "\n" + "layout(location = 0) in vertex_basic PSin;\n" + "\n" + "layout(location = 0) out vec4 SV_Target0;\n" + "\n" + "#ifdef DISABLE_GL42\n" + "layout(std140) uniform cb12\n" + "#else\n" + "layout(std140, binding = 12) uniform cb12\n" + "#endif\n" + "{\n" + " vec4 BGColor;\n" + "};\n" + "\n" + "layout(binding = 0) uniform sampler2D TextureSampler;\n" + "\n" + "// For all settings: 1.0 = 100\% 0.5=50\% 1.5 = 150\% \n" + "vec4 ContrastSaturationBrightness(vec4 color)\n" + "{\n" + " const float sat = SB_SATURATION / 50.0;\n" + " const float brt = SB_BRIGHTNESS / 50.0;\n" + " const float con = SB_CONTRAST / 50.0;\n" + " \n" + " // Increase or decrease theese values to adjust r, g and b color channels seperately\n" + " const float AvgLumR = 0.5;\n" + " const float AvgLumG = 0.5;\n" + " const float AvgLumB = 0.5;\n" + " \n" + " const vec3 LumCoeff = vec3(0.2125, 0.7154, 0.0721);\n" + " \n" + " vec3 AvgLumin = vec3(AvgLumR, AvgLumG, AvgLumB);\n" + " vec3 brtColor = color.rgb * brt;\n" + " float dot_intensity = dot(brtColor, LumCoeff);\n" + " vec3 intensity = vec3(dot_intensity, dot_intensity, dot_intensity);\n" + " vec3 satColor = mix(intensity, brtColor, sat);\n" + " vec3 conColor = mix(AvgLumin, satColor, con);\n" + "\n" + " color.rgb = conColor; \n" + " return color;\n" + "}\n" + "\n" + "\n" + "void ps_main()\n" + "{\n" + " vec4 c = texture(TextureSampler, PSin.t);\n" + " SV_Target0 = ContrastSaturationBrightness(c);\n" + "}\n" + "\n" + "\n" + "#endif\n" + ; diff --git a/plugins/GSdx/res/tfx.fx b/plugins/GSdx/res/tfx.fx index 7d56b29866..ef48db6f37 100644 --- a/plugins/GSdx/res/tfx.fx +++ b/plugins/GSdx/res/tfx.fx @@ -37,6 +37,7 @@ #define PS_COLCLIP 0 #define PS_DATE 0 #define PS_SPRITEHACK 0 +#define PS_TCOFFSETHACK 0 #define PS_POINT_SAMPLER 0 #endif @@ -101,6 +102,7 @@ cbuffer cb1 float2 MinF; float2 TA; uint4 MskFix; + float4 TC_OffsetHack; }; float4 sample_c(float2 uv) @@ -202,6 +204,8 @@ float4 ps_params[7]; #define MinF ps_params[4].xy #define TA ps_params[4].zw +#define TC_OffsetHack ps_params[6] + float4 sample_c(float2 uv) { return tex2D(Texture, uv); @@ -365,10 +369,11 @@ float4x4 sample_4p(float4 u) float4 sample(float2 st, float q) { - if(!PS_FST) - { - st /= q; - } + if(!PS_FST) st /= q; + + #if PS_TCOFFSETHACK + st += TC_OffsetHack.xy; + #endif float4 t; float4x4 c; diff --git a/plugins/GSdx/res/tfx.glsl b/plugins/GSdx/res/tfx.glsl index 127014ca42..e6f87aff26 100644 --- a/plugins/GSdx/res/tfx.glsl +++ b/plugins/GSdx/res/tfx.glsl @@ -7,6 +7,10 @@ #define FMT_16 2 #define FMT_PAL 4 /* flag bit */ +// Not sure we have same issue on opengl. Doesn't work anyway on ATI card +// And I say this as an ATI user. +#define ATI_SUCKS 0 + #ifndef VS_BPPZ #define VS_BPPZ 0 #define VS_TME 1 @@ -36,6 +40,8 @@ #define PS_COLCLIP 0 #define PS_DATE 0 #define PS_SPRITEHACK 0 +#define PS_POINT_SAMPLER 0 +#define PS_TCOFFSETHACK 0 #endif struct vertex @@ -63,7 +69,11 @@ out gl_PerVertex { float gl_ClipDistance[]; }; -layout(std140, binding = 4) uniform cb0 +#ifdef DISABLE_GL42 +layout(std140) uniform cb20 +#else +layout(std140, binding = 20) uniform cb20 +#endif { vec4 VertexScale; vec4 VertexOffset; @@ -143,10 +153,7 @@ out gl_PerVertex { float gl_ClipDistance[]; }; -// FIXME -// AMD Driver bug again !!!! -//layout(location = 0) in vertex GSin[]; -in vertex GSin[]; +layout(location = 0) in vertex GSin[]; layout(location = 0) out vertex GSout; @@ -272,7 +279,11 @@ layout(binding = 0) uniform sampler2D TextureSampler; layout(binding = 1) uniform sampler2D PaletteSampler; layout(binding = 2) uniform sampler2D RTCopySampler; -layout(std140, binding = 5) uniform cb1 +#ifdef DISABLE_GL42 +layout(std140) uniform cb21 +#else +layout(std140, binding = 21) uniform cb21 +#endif { vec3 FogColor; float AREF; @@ -282,10 +293,22 @@ layout(std140, binding = 5) uniform cb1 vec2 MinF; vec2 TA; uvec4 MskFix; + vec4 TC_OffsetHack; }; vec4 sample_c(vec2 uv) { + // FIXME: check the issue on openGL + if (ATI_SUCKS == 1 && PS_POINT_SAMPLER == 1) + { + // Weird issue with ATI cards (happens on at least HD 4xxx and 5xxx), + // it looks like they add 127/128 of a texel to sampling coordinates + // occasionally causing point sampling to erroneously round up. + // I'm manually adjusting coordinates to the centre of texels here, + // though the centre is just paranoia, the top left corner works fine. + uv = (trunc(uv * WH.zw) + vec2(0.5, 0.5)) / WH.zw; + } + // FIXME I'm not sure it is a good solution to flip texture return texture(TextureSampler, uv); //FIXME another way to FLIP vertically @@ -403,10 +426,9 @@ mat4 sample_4p(vec4 u) vec4 sample_color(vec2 st, float q) { - if(PS_FST == 0) - { - st /= q; - } + if(PS_FST == 0) st /= q; + + if(PS_TCOFFSETHACK == 1) st += TC_OffsetHack.xy; vec4 t; mat4 c; diff --git a/plugins/GSdx/res/tfx.h b/plugins/GSdx/res/tfx.h new file mode 100644 index 0000000000..8f38c2c3e2 --- /dev/null +++ b/plugins/GSdx/res/tfx.h @@ -0,0 +1,697 @@ +/* + * Copyright (C) 2011-2013 Gregory hainaut + * Copyright (C) 2007-2009 Gabest + * + * This file was generated by glsl2h.pl script + * + * This Program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2, or (at your option) + * any later version. + * + * This Program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with GNU Make; see the file COPYING. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA USA. + * http://www.gnu.org/copyleft/gpl.html + * + */ + +#pragma once + +#include "stdafx.h" + +extern const char* tfx_glsl = + "//#version 420 // Keep it for text editor detection\n" + "\n" + "// note lerp => mix\n" + "\n" + "#define FMT_32 0\n" + "#define FMT_24 1\n" + "#define FMT_16 2\n" + "#define FMT_PAL 4 /* flag bit */\n" + "\n" + "// Not sure we have same issue on opengl. Doesn't work anyway on ATI card\n" + "// And I say this as an ATI user.\n" + "#define ATI_SUCKS 0\n" + "\n" + "#ifndef VS_BPPZ\n" + "#define VS_BPPZ 0\n" + "#define VS_TME 1\n" + "#define VS_FST 1\n" + "#define VS_LOGZ 0\n" + "#endif\n" + "\n" + "#ifndef GS_IIP\n" + "#define GS_IIP 0\n" + "#define GS_PRIM 3\n" + "#endif\n" + "\n" + "#ifndef PS_FST\n" + "#define PS_FST 0\n" + "#define PS_WMS 0\n" + "#define PS_WMT 0\n" + "#define PS_FMT FMT_32\n" + "#define PS_AEM 0\n" + "#define PS_TFX 0\n" + "#define PS_TCC 1\n" + "#define PS_ATST 1\n" + "#define PS_FOG 0\n" + "#define PS_CLR1 0\n" + "#define PS_FBA 0\n" + "#define PS_AOUT 0\n" + "#define PS_LTF 1\n" + "#define PS_COLCLIP 0\n" + "#define PS_DATE 0\n" + "#define PS_SPRITEHACK 0\n" + "#define PS_POINT_SAMPLER 0\n" + "#define PS_TCOFFSETHACK 0\n" + "#endif\n" + "\n" + "struct vertex\n" + "{\n" + " vec4 p;\n" + " vec4 t;\n" + " vec4 tp;\n" + " vec4 c;\n" + "};\n" + "\n" + "#ifdef VERTEX_SHADER\n" + "layout(location = 0) in vec2 i_st;\n" + "layout(location = 1) in vec4 i_c;\n" + "layout(location = 2) in float i_q;\n" + "layout(location = 3) in uvec2 i_p;\n" + "layout(location = 4) in uint i_z;\n" + "layout(location = 5) in uvec2 i_uv;\n" + "layout(location = 6) in vec4 i_f;\n" + "\n" + "layout(location = 0) out vertex VSout;\n" + "\n" + "out gl_PerVertex {\n" + " invariant vec4 gl_Position;\n" + " float gl_PointSize;\n" + " float gl_ClipDistance[];\n" + "};\n" + "\n" + "#ifdef DISABLE_GL42\n" + "layout(std140) uniform cb20\n" + "#else\n" + "layout(std140, binding = 20) uniform cb20\n" + "#endif\n" + "{\n" + " vec4 VertexScale;\n" + " vec4 VertexOffset;\n" + " vec2 TextureScale;\n" + "};\n" + "\n" + "void vs_main()\n" + "{\n" + " uint z;\n" + " if(VS_BPPZ == 1) // 24\n" + " z = i_z & uint(0xffffff);\n" + " else if(VS_BPPZ == 2) // 16\n" + " z = i_z & uint(0xffff);\n" + " else\n" + " z = i_z;\n" + "\n" + " // pos -= 0.05 (1/320 pixel) helps avoiding rounding problems (integral part of pos is usually 5 digits, 0.05 is about as low as we can go)\n" + " // example: ceil(afterseveralvertextransformations(y = 133)) => 134 => line 133 stays empty\n" + " // input granularity is 1/16 pixel, anything smaller than that won't step drawing up/left by one pixel\n" + " // example: 133.0625 (133 + 1/16) should start from line 134, ceil(133.0625 - 0.05) still above 133\n" + "\n" + " vec4 p = vec4(i_p, z, 0) - vec4(0.05f, 0.05f, 0, 0); \n" + " vec4 final_p = p * VertexScale - VertexOffset;\n" + " // FIXME\n" + " // FLIP vertically\n" + " final_p.y *= -1.0f;\n" + "\n" + " if(VS_LOGZ == 1)\n" + " {\n" + " final_p.z = log2(1.0f + float(z)) / 32.0f;\n" + " }\n" + "\n" + " VSout.p = final_p;\n" + " gl_Position = final_p; // NOTE I don't know if it is possible to merge POSITION_OUT and gl_Position\n" + "#if VS_RTCOPY\n" + " VSout.tp = final_p * vec4(0.5, -0.5, 0, 0) + 0.5;\n" + "#endif\n" + "\n" + "\n" + " if(VS_TME != 0)\n" + " {\n" + " if(VS_FST != 0)\n" + " {\n" + " //VSout.t.xy = i_t * TextureScale;\n" + " VSout.t.xy = i_uv * TextureScale;\n" + " VSout.t.w = 1.0f;\n" + " }\n" + " else\n" + " {\n" + " //VSout.t.xy = i_t;\n" + " VSout.t.xy = i_st;\n" + " VSout.t.w = i_q;\n" + " }\n" + " }\n" + " else\n" + " {\n" + " VSout.t.xy = vec2(0.0f, 0.0f);\n" + " VSout.t.w = 1.0f;\n" + " }\n" + "\n" + " VSout.c = i_c;\n" + " VSout.t.z = i_f.r;\n" + "}\n" + "\n" + "#endif\n" + "\n" + "#ifdef GEOMETRY_SHADER\n" + "in gl_PerVertex {\n" + " vec4 gl_Position;\n" + " float gl_PointSize;\n" + " float gl_ClipDistance[];\n" + "} gl_in[];\n" + "\n" + "out gl_PerVertex {\n" + " vec4 gl_Position;\n" + " float gl_PointSize;\n" + " float gl_ClipDistance[];\n" + "};\n" + "\n" + "layout(location = 0) in vertex GSin[];\n" + "\n" + "layout(location = 0) out vertex GSout;\n" + "\n" + "#if GS_PRIM == 0\n" + "layout(points) in;\n" + "layout(points, max_vertices = 1) out;\n" + "\n" + "void gs_main()\n" + "{\n" + " for(int i = 0; i < gl_in.length(); i++) {\n" + " gl_Position = gl_in[i].gl_Position; // FIXME is it useful\n" + " GSout = GSin[i];\n" + " EmitVertex();\n" + " }\n" + " EndPrimitive();\n" + "}\n" + "\n" + "#elif GS_PRIM == 1\n" + "layout(lines) in;\n" + "layout(line_strip, max_vertices = 2) out;\n" + "\n" + "void gs_main()\n" + "{\n" + " for(int i = 0; i < gl_in.length(); i++) {\n" + " gl_Position = gl_in[i].gl_Position; // FIXME is it useful\n" + " GSout = GSin[i];\n" + "#if GS_IIP == 0\n" + " if (i == 0)\n" + " GSout.c = GSin[1].c;\n" + "#endif\n" + " EmitVertex();\n" + " }\n" + " EndPrimitive();\n" + "}\n" + "\n" + "#elif GS_PRIM == 2\n" + "layout(triangles) in;\n" + "layout(triangle_strip, max_vertices = 3) out;\n" + "\n" + "void gs_main()\n" + "{\n" + " for(int i = 0; i < gl_in.length(); i++) {\n" + " gl_Position = gl_in[i].gl_Position; // FIXME is it useful\n" + " GSout = GSin[i];\n" + "#if GS_IIP == 0\n" + " if (i == 0 || i == 1)\n" + " GSout.c = GSin[2].c;\n" + "#endif\n" + " EmitVertex();\n" + " }\n" + " EndPrimitive();\n" + "}\n" + "\n" + "#elif GS_PRIM == 3\n" + "layout(lines) in;\n" + "layout(triangle_strip, max_vertices = 6) out;\n" + "\n" + "void gs_main()\n" + "{\n" + " // left top => GSin[0];\n" + " // right bottom => GSin[1];\n" + " vertex rb = GSin[1];\n" + " vertex lt = GSin[0];\n" + "\n" + " lt.p.z = rb.p.z;\n" + " lt.t.zw = rb.t.zw;\n" + "#if GS_IIP == 0\n" + " lt.c = rb.c;\n" + "#endif\n" + "\n" + " vertex lb = rb;\n" + " lb.p.x = lt.p.x;\n" + " lb.t.x = lt.t.x;\n" + "\n" + " vertex rt = rb;\n" + " rt.p.y = lt.p.y;\n" + " rt.t.y = lt.t.y;\n" + "\n" + " // Triangle 1\n" + " gl_Position = lt.p;\n" + " GSout = lt;\n" + " EmitVertex();\n" + "\n" + " gl_Position = lb.p;\n" + " GSout = lb;\n" + " EmitVertex();\n" + "\n" + " gl_Position = rt.p;\n" + " GSout = rt;\n" + " EmitVertex();\n" + "\n" + " EndPrimitive();\n" + "\n" + " // Triangle 2\n" + " gl_Position = lb.p;\n" + " GSout = lb;\n" + " EmitVertex();\n" + "\n" + " gl_Position = rt.p;\n" + " GSout = rt;\n" + " EmitVertex();\n" + "\n" + " gl_Position = rb.p;\n" + " GSout = rb;\n" + " EmitVertex();\n" + "\n" + " EndPrimitive();\n" + "\n" + "}\n" + "\n" + "#endif\n" + "\n" + "#endif\n" + "\n" + "#ifdef FRAGMENT_SHADER\n" + "layout(location = 0) in vertex PSin;\n" + "\n" + "// Same buffer but 2 colors for dual source blending\n" + "layout(location = 0, index = 0) out vec4 SV_Target0;\n" + "layout(location = 0, index = 1) out vec4 SV_Target1;\n" + "\n" + "layout(binding = 0) uniform sampler2D TextureSampler;\n" + "layout(binding = 1) uniform sampler2D PaletteSampler;\n" + "layout(binding = 2) uniform sampler2D RTCopySampler;\n" + "\n" + "#ifdef DISABLE_GL42\n" + "layout(std140) uniform cb21\n" + "#else\n" + "layout(std140, binding = 21) uniform cb21\n" + "#endif\n" + "{\n" + " vec3 FogColor;\n" + " float AREF;\n" + " vec4 HalfTexel;\n" + " vec4 WH;\n" + " vec4 MinMax;\n" + " vec2 MinF;\n" + " vec2 TA;\n" + " uvec4 MskFix;\n" + " vec4 TC_OffsetHack;\n" + "};\n" + "\n" + "vec4 sample_c(vec2 uv)\n" + "{\n" + " // FIXME: check the issue on openGL\n" + " if (ATI_SUCKS == 1 && PS_POINT_SAMPLER == 1)\n" + " {\n" + " // Weird issue with ATI cards (happens on at least HD 4xxx and 5xxx),\n" + " // it looks like they add 127/128 of a texel to sampling coordinates\n" + " // occasionally causing point sampling to erroneously round up.\n" + " // I'm manually adjusting coordinates to the centre of texels here,\n" + " // though the centre is just paranoia, the top left corner works fine.\n" + " uv = (trunc(uv * WH.zw) + vec2(0.5, 0.5)) / WH.zw;\n" + " }\n" + "\n" + " // FIXME I'm not sure it is a good solution to flip texture\n" + " return texture(TextureSampler, uv);\n" + " //FIXME another way to FLIP vertically\n" + " //return texture(TextureSampler, vec2(uv.x, 1.0f-uv.y) );\n" + "}\n" + "\n" + "vec4 sample_p(float u)\n" + "{\n" + " //FIXME do we need a 1D sampler. Big impact on opengl to find 1 dim\n" + " // So for the moment cheat with 0.0f dunno if it work\n" + " return texture(PaletteSampler, vec2(u, 0.0f));\n" + "}\n" + "\n" + "vec4 sample_rt(vec2 uv)\n" + "{\n" + " return texture(RTCopySampler, uv);\n" + "}\n" + "\n" + "vec4 wrapuv(vec4 uv)\n" + "{\n" + " vec4 uv_out = uv;\n" + "\n" + " if(PS_WMS == PS_WMT)\n" + " {\n" + " if(PS_WMS == 2)\n" + " {\n" + " uv_out = clamp(uv, MinMax.xyxy, MinMax.zwzw);\n" + " }\n" + " else if(PS_WMS == 3)\n" + " {\n" + " uv_out = vec4(((ivec4(uv * WH.xyxy) & ivec4(MskFix.xyxy)) | ivec4(MskFix.zwzw)) / WH.xyxy);\n" + " }\n" + " }\n" + " else\n" + " {\n" + " if(PS_WMS == 2)\n" + " {\n" + " uv_out.xz = clamp(uv.xz, MinMax.xx, MinMax.zz);\n" + " }\n" + " else if(PS_WMS == 3)\n" + " {\n" + " uv_out.xz = vec2(((ivec2(uv.xz * WH.xx) & ivec2(MskFix.xx)) | ivec2(MskFix.zz)) / WH.xx);\n" + " }\n" + " if(PS_WMT == 2)\n" + " {\n" + " uv_out.yw = clamp(uv.yw, MinMax.yy, MinMax.ww);\n" + " }\n" + " else if(PS_WMT == 3)\n" + " {\n" + " uv_out.yw = vec2(((ivec2(uv.yw * WH.yy) & ivec2(MskFix.yy)) | ivec2(MskFix.ww)) / WH.yy);\n" + " }\n" + " }\n" + "\n" + " return uv_out;\n" + "}\n" + "\n" + "vec2 clampuv(vec2 uv)\n" + "{\n" + " vec2 uv_out = uv;\n" + "\n" + " if(PS_WMS == 2 && PS_WMT == 2) \n" + " {\n" + " uv_out = clamp(uv, MinF, MinMax.zw);\n" + " }\n" + " else if(PS_WMS == 2)\n" + " {\n" + " uv_out.x = clamp(uv.x, MinF.x, MinMax.z);\n" + " }\n" + " else if(PS_WMT == 2)\n" + " {\n" + " uv_out.y = clamp(uv.y, MinF.y, MinMax.w);\n" + " }\n" + "\n" + " return uv_out;\n" + "}\n" + "\n" + "mat4 sample_4c(vec4 uv)\n" + "{\n" + " mat4 c;\n" + "\n" + " c[0] = sample_c(uv.xy);\n" + " c[1] = sample_c(uv.zy);\n" + " c[2] = sample_c(uv.xw);\n" + " c[3] = sample_c(uv.zw);\n" + "\n" + " return c;\n" + "}\n" + "\n" + "vec4 sample_4a(vec4 uv)\n" + "{\n" + " vec4 c;\n" + "\n" + " // XXX\n" + " // I think .a is related to 8bit texture in alpha channel\n" + " // Opengl is only 8 bits on red channel. Not sure exactly of the impact\n" + " c.x = sample_c(uv.xy).a;\n" + " c.y = sample_c(uv.zy).a;\n" + " c.z = sample_c(uv.xw).a;\n" + " c.w = sample_c(uv.zw).a;\n" + "\n" + " return c * 255./256 + 0.5/256;\n" + "}\n" + "\n" + "mat4 sample_4p(vec4 u)\n" + "{\n" + " mat4 c;\n" + "\n" + " c[0] = sample_p(u.x);\n" + " c[1] = sample_p(u.y);\n" + " c[2] = sample_p(u.z);\n" + " c[3] = sample_p(u.w);\n" + "\n" + " return c;\n" + "}\n" + "\n" + "vec4 sample_color(vec2 st, float q)\n" + "{\n" + " if(PS_FST == 0) st /= q;\n" + "\n" + " if(PS_TCOFFSETHACK == 1) st += TC_OffsetHack.xy;\n" + "\n" + " vec4 t;\n" + " mat4 c;\n" + " vec2 dd;\n" + "\n" + " if (PS_LTF == 0 && PS_FMT <= FMT_16 && PS_WMS < 3 && PS_WMT < 3)\n" + " {\n" + " c[0] = sample_c(clampuv(st));\n" + " }\n" + " else\n" + " {\n" + " vec4 uv;\n" + "\n" + " if(PS_LTF != 0)\n" + " {\n" + " uv = st.xyxy + HalfTexel;\n" + " dd = fract(uv.xy * WH.zw);\n" + " }\n" + " else\n" + " {\n" + " uv = st.xyxy;\n" + " }\n" + "\n" + " uv = wrapuv(uv);\n" + "\n" + " if((PS_FMT & FMT_PAL) != 0)\n" + " {\n" + " c = sample_4p(sample_4a(uv));\n" + " }\n" + " else\n" + " {\n" + " c = sample_4c(uv);\n" + " }\n" + " }\n" + "\n" + " // PERF: see the impact of the exansion before/after the interpolation\n" + " for (int i = 0; i < 4; i++)\n" + " {\n" + " if((PS_FMT & ~FMT_PAL) == FMT_24)\n" + " {\n" + " // FIXME GLSL any only support bvec so try to mix it with notEqual\n" + " bvec3 rgb_check = notEqual( t.rgb, vec3(0.0f, 0.0f, 0.0f) );\n" + " t.a = ( (PS_AEM == 0) || any(rgb_check) ) ? TA.x : 0.0f;\n" + " }\n" + " else if((PS_FMT & ~FMT_PAL) == FMT_16)\n" + " {\n" + " // FIXME GLSL any only support bvec so try to mix it with notEqual\n" + " bvec3 rgb_check = notEqual( t.rgb, vec3(0.0f, 0.0f, 0.0f) );\n" + " t.a = t.a >= 0.5 ? TA.y : ( (PS_AEM == 0) || any(rgb_check) ) ? TA.x : 0.0f;\n" + " }\n" + " }\n" + "\n" + " if(PS_LTF != 0)\n" + " {\n" + " t = mix(mix(c[0], c[1], dd.x), mix(c[2], c[3], dd.x), dd.y);\n" + " }\n" + " else\n" + " {\n" + " t = c[0];\n" + " }\n" + "\n" + " return t;\n" + "}\n" + "\n" + "vec4 tfx(vec4 t, vec4 c)\n" + "{\n" + " vec4 c_out = c;\n" + " if(PS_TFX == 0)\n" + " {\n" + " if(PS_TCC != 0) \n" + " {\n" + " c_out = c * t * 255.0f / 128;\n" + " }\n" + " else\n" + " {\n" + " c_out.rgb = c.rgb * t.rgb * 255.0f / 128;\n" + " }\n" + " }\n" + " else if(PS_TFX == 1)\n" + " {\n" + " if(PS_TCC != 0) \n" + " {\n" + " c_out = t;\n" + " }\n" + " else\n" + " {\n" + " c_out.rgb = t.rgb;\n" + " }\n" + " }\n" + " else if(PS_TFX == 2)\n" + " {\n" + " c_out.rgb = c.rgb * t.rgb * 255.0f / 128 + c.a;\n" + "\n" + " if(PS_TCC != 0) \n" + " {\n" + " c_out.a += t.a;\n" + " }\n" + " }\n" + " else if(PS_TFX == 3)\n" + " {\n" + " c_out.rgb = c.rgb * t.rgb * 255.0f / 128 + c.a;\n" + "\n" + " if(PS_TCC != 0) \n" + " {\n" + " c_out.a = t.a;\n" + " }\n" + " }\n" + "\n" + " return clamp(c_out, vec4(0.0f, 0.0f, 0.0f, 0.0f), vec4(1.0f, 1.0f, 1.0f, 1.0f));\n" + "}\n" + "\n" + "void datst()\n" + "{\n" + "#if PS_DATE > 0\n" + " float alpha = sample_rt(PSin.tp.xy).a;\n" + " float alpha0x80 = 128. / 255;\n" + "\n" + " if (PS_DATE == 1 && alpha >= alpha0x80)\n" + " discard;\n" + " else if (PS_DATE == 2 && alpha < alpha0x80)\n" + " discard;\n" + "#endif\n" + "}\n" + "\n" + "void atst(vec4 c)\n" + "{\n" + " float a = trunc(c.a * 255 + 0.01);\n" + "\n" + " if(PS_ATST == 0) // never\n" + " {\n" + " discard;\n" + " }\n" + " else if(PS_ATST == 1) // always\n" + " {\n" + " // nothing to do\n" + " }\n" + " else if(PS_ATST == 2 ) // l\n" + " {\n" + " if (PS_SPRITEHACK == 0)\n" + " if ((AREF - a - 0.5f) < 0.0f)\n" + " discard;\n" + " }\n" + " else if(PS_ATST == 3 ) // le\n" + " {\n" + " if ((AREF - a + 0.5f) < 0.0f)\n" + " discard;\n" + " }\n" + " else if(PS_ATST == 4) // e\n" + " {\n" + " if ((0.5f - abs(a - AREF)) < 0.0f)\n" + " discard;\n" + " }\n" + " else if(PS_ATST == 5) // ge\n" + " {\n" + " if ((a-AREF + 0.5f) < 0.0f)\n" + " discard;\n" + " }\n" + " else if(PS_ATST == 6) // g\n" + " {\n" + " if ((a-AREF - 0.5f) < 0.0f)\n" + " discard;\n" + " }\n" + " else if(PS_ATST == 7) // ne\n" + " {\n" + " if ((abs(a - AREF) - 0.5f) < 0.0f)\n" + " discard;\n" + " }\n" + "}\n" + "\n" + "vec4 fog(vec4 c, float f)\n" + "{\n" + " vec4 c_out = c;\n" + " if(PS_FOG != 0)\n" + " {\n" + " c_out.rgb = mix(FogColor, c.rgb, f);\n" + " }\n" + "\n" + " return c_out;\n" + "}\n" + "\n" + "vec4 ps_color()\n" + "{\n" + " datst();\n" + "\n" + " vec4 t = sample_color(PSin.t.xy, PSin.t.w);\n" + "\n" + " vec4 c = tfx(t, PSin.c);\n" + "\n" + " atst(c);\n" + "\n" + " c = fog(c, PSin.t.z);\n" + "\n" + " if (PS_COLCLIP == 2)\n" + " {\n" + " c.rgb = 256.0f/255.0f - c.rgb;\n" + " }\n" + " if (PS_COLCLIP > 0)\n" + " {\n" + " // FIXME !!!!\n" + " //c.rgb *= c.rgb < 128./255;\n" + " bvec3 factor = bvec3(128.0f/255.0f, 128.0f/255.0f, 128.0f/255.0f);\n" + " c.rgb *= vec3(factor);\n" + " }\n" + "\n" + " if(PS_CLR1 != 0) // needed for Cd * (As/Ad/F + 1) blending modes\n" + " {\n" + " c.rgb = vec3(1.0f, 1.0f, 1.0f); \n" + " }\n" + "\n" + " return c;\n" + "}\n" + "\n" + "void ps_main()\n" + "{\n" + " //FIXME\n" + " vec4 c = ps_color();\n" + "\n" + " // FIXME: I'm not sure about the value of others field\n" + " // output.c1 = c.a * 2; // used for alpha blending\n" + "\n" + " float alpha = c.a * 2;\n" + "\n" + " if(PS_AOUT != 0) // 16 bit output\n" + " {\n" + " float a = 128.0f / 255; // alpha output will be 0x80\n" + "\n" + " c.a = (PS_FBA != 0) ? a : step(0.5, c.a) * a;\n" + " }\n" + " else if(PS_FBA != 0)\n" + " {\n" + " if(c.a < 0.5) c.a += 0.5;\n" + " }\n" + "\n" + " SV_Target0 = c;\n" + " SV_Target1 = vec4(alpha, alpha, alpha, alpha);\n" + "}\n" + "#endif\n" + ; diff --git a/plugins/GSdx/resource.h b/plugins/GSdx/resource.h index 70062a104c..a4b56979f5 100644 --- a/plugins/GSdx/resource.h +++ b/plugins/GSdx/resource.h @@ -80,7 +80,13 @@ #define IDC_AGGRESSIVECRC 2076 #define IDC_CHECK_DISABLE_ALL_HACKS 2077 #define IDC_ALPHASTENCIL 2078 -#define IDC_ADAPTER 2078 +#define IDC_ADAPTER 2079 +#define IDC_STATIC_TCOFFSETX 2080 +#define IDC_STATIC_TCOFFSETY 2081 +#define IDC_TCOFFSETX 2082 +#define IDC_TCOFFSETX2 2083 +#define IDC_TCOFFSETY 2084 +#define IDC_TCOFFSETY2 2085 #define IDC_COLORSPACE 3000 #define IDR_CONVERT_FX 10000 #define IDR_TFX_FX 10001 @@ -99,7 +105,7 @@ #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 10012 #define _APS_NEXT_COMMAND_VALUE 32771 -#define _APS_NEXT_CONTROL_VALUE 2079 +#define _APS_NEXT_CONTROL_VALUE 2086 #define _APS_NEXT_SYMED_VALUE 5000 #endif #endif diff --git a/plugins/GSdx/stdafx.h b/plugins/GSdx/stdafx.h index da2f7bc421..d7d4c407ac 100644 --- a/plugins/GSdx/stdafx.h +++ b/plugins/GSdx/stdafx.h @@ -438,7 +438,11 @@ struct aligned_free_second {template void operator()(T& p) {_aligned_fr #ifdef __GNUC__ - __forceinline unsigned long long __rdtsc() + // gcc 4.8 define __rdtsc but unfortunately the compiler crash... + // The redefine allow to skip the gcc __rdtsc version -- Gregory + #define __rdtsc _lnx_rdtsc + //__forceinline unsigned long long __rdtsc() + __forceinline unsigned long long _lnx_rdtsc() { #if defined(__amd64__) || defined(__x86_64__) unsigned long long low, high; diff --git a/plugins/dev9ghzdrk/DEV9.cpp b/plugins/dev9ghzdrk/DEV9.cpp new file mode 100644 index 0000000000..703ac8dd7c --- /dev/null +++ b/plugins/dev9ghzdrk/DEV9.cpp @@ -0,0 +1,615 @@ + +#define WINVER 0x0600 +#define _WIN32_WINNT 0x0600 + +#include +#include +#include +#include +#include +#include +#include +#include +#define EXTERN +#include "DEV9.h" +#undef EXTERN +#include "Config.h" +#include "smap.h" +#include "ata.h" + +#ifdef __WIN32__ +#pragma warning(disable:4244) + +HINSTANCE hInst=NULL; +#endif + +//#define HDD_48BIT + +u8 eeprom[] = { + //0x6D, 0x76, 0x63, 0x61, 0x31, 0x30, 0x08, 0x01, + 0x76, 0x6D, 0x61, 0x63, 0x30, 0x31, 0x07, 0x02, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +}; + +u32 *iopPC; + +const unsigned char version = PS2E_DEV9_VERSION; +const unsigned char revision = 0; +const unsigned char build = 3; // increase that with each version + + +static char *libraryName = "GiGaHeRz's DEV9 Driver" +#ifdef _DEBUG + "(debug)" +#endif +; + +HANDLE hEeprom; +HANDLE mapping; + +u32 CALLBACK PS2EgetLibType() { + return PS2E_LT_DEV9; +} + +char* CALLBACK PS2EgetLibName() { + return libraryName; +} + +u32 CALLBACK PS2EgetLibVersion2(u32 type) { + return (version<<16) | (revision<<8) | build; +} + +// Warning: The below log function is SLOW. Better fix it before attempting to use it. +int Log = 0; + +void __Log(char *fmt, ...) { + if (!Log) return; + va_list list; + + static int ticks=-1; + int nticks=GetTickCount(); + + if(ticks==-1) ticks=nticks; + + if(iopPC!=NULL) + { + fprintf(dev9Log,"[%10d + %4d, IOP PC = %08x] ",nticks,nticks-ticks,*iopPC); + } + else + { + fprintf(dev9Log,"[%10d + %4d] ",nticks,nticks-ticks); + } + ticks=nticks; + + va_start(list, fmt); + vfprintf(dev9Log, fmt, list); + va_end(list); +} + + +s32 CALLBACK DEV9init() +{ + +#ifdef DEV9_LOG_ENABLE + dev9Log = fopen("logs/dev9Log.txt", "w"); + setvbuf(dev9Log, NULL, _IONBF, 0); + DEV9_LOG("DEV9init\n"); +#endif + memset(&dev9, 0, sizeof(dev9)); + DEV9_LOG("DEV9init2\n"); + + DEV9_LOG("DEV9init3\n"); + + FLASHinit(); + + hEeprom = CreateFile( + "eeprom.dat", + GENERIC_READ|GENERIC_WRITE, + 0, + NULL, + OPEN_EXISTING, + FILE_FLAG_WRITE_THROUGH, + NULL + ); + + if(hEeprom==INVALID_HANDLE_VALUE) + { + dev9.eeprom=(u16*)eeprom; + } + else + { + mapping=CreateFileMapping(hEeprom,NULL,PAGE_READWRITE,0,0,NULL); + if(mapping==INVALID_HANDLE_VALUE) + { + CloseHandle(hEeprom); + dev9.eeprom=(u16*)eeprom; + } + else + { + dev9.eeprom = (u16*)MapViewOfFile(mapping,FILE_MAP_WRITE,0,0,0); + if(dev9.eeprom==NULL) + { + CloseHandle(mapping); + CloseHandle(hEeprom); + dev9.eeprom=(u16*)eeprom; + } + } + } + + + { + int rxbi; + + for(rxbi=0;rxbi<(SMAP_BD_SIZE/8);rxbi++) + { + smap_bd_t *pbd = (smap_bd_t *)&dev9.dev9R[SMAP_BD_RX_BASE & 0xffff]; + pbd = &pbd[rxbi]; + + pbd->ctrl_stat = SMAP_BD_RX_EMPTY; + pbd->length = 0; + } + } + + DEV9_LOG("DEV9init ok\n"); + + return 0; +} + +void CALLBACK DEV9shutdown() { + DEV9_LOG("DEV9shutdown\n"); +#ifdef DEV9_LOG_ENABLE + fclose(dev9Log); +#endif +} + +bool tx_p_first; +s32 CALLBACK DEV9open(void *pDsp) +{ + DEV9_LOG("DEV9open\n"); + LoadConf(); + DEV9_LOG("open r+: %s\n", config.Hdd); + config.HddSize = 8*1024; + + tx_p_first=false; // reset stack init hack so it works on game reboots + + iopPC = (u32*)pDsp; + +#ifdef ENABLE_ATA + ata_init(); +#endif + return _DEV9open(); +} + +void CALLBACK DEV9close() +{ + DEV9_LOG("DEV9close\n"); +#ifdef ENABLE_ATA + ata_term(); +#endif + _DEV9close(); +} + +int CALLBACK _DEV9irqHandler(void) +{ + //dev9Ru16(SPD_R_INTR_STAT)|= dev9.irqcause; + DEV9_LOG("_DEV9irqHandler %x, %x\n", dev9.irqcause, dev9Ru16(SPD_R_INTR_MASK)); + if (dev9.irqcause & dev9Ru16(SPD_R_INTR_MASK)) + return 1; + return 0; +} + +DEV9handler CALLBACK DEV9irqHandler(void) { + return (DEV9handler)_DEV9irqHandler; +} + +void _DEV9irq(int cause, int cycles) +{ + DEV9_LOG("_DEV9irq %x, %x\n", cause, dev9Ru16(SPD_R_INTR_MASK)); + + dev9.irqcause|= cause; + + if(cycles<1) + DEV9irq(1); + else + DEV9irq(cycles); +} + + +u8 CALLBACK DEV9read8(u32 addr) { + u8 hard; + if (addr>=ATA_DEV9_HDD_BASE && addr(addr); +#else + return 0; +#endif + } + if (addr>=SMAP_REGBASE && addr>11; + dev9.eeprom_bit++; + if(dev9.eeprom_bit==16) + { + dev9.eeprom_address++; + dev9.eeprom_bit=0; + } + } + else hard=0; + } + else hard=0; + return hard; + + case DEV9_R_REV: + hard = 0x32; // expansion bay + break; + + default: + if ((addr >= FLASH_REGBASE) && (addr < (FLASH_REGBASE + FLASH_REGSIZE))) { + return (u8)FLASHread32(addr, 1); + } + + hard = dev9Ru8(addr); + DEV9_LOG("*Unknown 8bit read at address %lx value %x\n", addr, hard); + return hard; + } + + DEV9_LOG("*Known 8bit read at address %lx value %x\n", addr, hard); + return hard; +} + +u16 CALLBACK DEV9read16(u32 addr) +{ + u16 hard; + if (addr>=ATA_DEV9_HDD_BASE && addr(addr); +#else + return 0; +#endif + } + if (addr>=SMAP_REGBASE && addr= FLASH_REGBASE) && (addr < (FLASH_REGBASE + FLASH_REGSIZE))) { + return (u16)FLASHread32(addr, 2); + } + + hard = dev9Ru16(addr); + DEV9_LOG("*Unknown 16bit read at address %lx value %x\n", addr, hard); + return hard; + } + + DEV9_LOG("*Known 16bit read at address %lx value %x\n", addr, hard); + return hard; +} + +u32 CALLBACK DEV9read32(u32 addr) +{ + u32 hard; + if (addr>=ATA_DEV9_HDD_BASE && addr(addr); +#else + return 0; +#endif + } + if (addr>=SMAP_REGBASE && addr= FLASH_REGBASE) && (addr < (FLASH_REGBASE + FLASH_REGSIZE))) { + return (u32)FLASHread32(addr, 4); + } + + hard = dev9Ru32(addr); + DEV9_LOG("*Unknown 32bit read at address %lx value %x\n", addr, hard); + return hard; + } + + DEV9_LOG("*Known 32bit read at address %lx: %lx\n", addr, hard); + return hard; +} + +void CALLBACK DEV9write8(u32 addr, u8 value) +{ + if (addr>=ATA_DEV9_HDD_BASE && addr(addr,value); +#endif + return; + } + if (addr>=SMAP_REGBASE && addr>4)&3; + + return; + + case SPD_R_PIO_DATA: + //DEV9_LOG("SPD_R_PIO_DATA 8bit write %x\n", value); + + if((value&0xc0)!=0xc0) + return; + + switch(dev9.eeprom_state) + { + case EEPROM_READY: + dev9.eeprom_command=0; + dev9.eeprom_state++; + break; + case EEPROM_OPCD0: + dev9.eeprom_command = (value>>4)&2; + dev9.eeprom_state++; + dev9.eeprom_bit=0xFF; + break; + case EEPROM_OPCD1: + dev9.eeprom_command |= (value>>5)&1; + dev9.eeprom_state++; + break; + case EEPROM_ADDR0: + case EEPROM_ADDR1: + case EEPROM_ADDR2: + case EEPROM_ADDR3: + case EEPROM_ADDR4: + case EEPROM_ADDR5: + dev9.eeprom_address = + (dev9.eeprom_address&(63^(1<<(dev9.eeprom_state-EEPROM_ADDR0))))| + ((value>>(dev9.eeprom_state-EEPROM_ADDR0))&(0x20>>(dev9.eeprom_state-EEPROM_ADDR0))); + dev9.eeprom_state++; + break; + case EEPROM_TDATA: + { + if(dev9.eeprom_command==1) //write + { + dev9.eeprom[dev9.eeprom_address] = + (dev9.eeprom[dev9.eeprom_address]&(63^(1<>dev9.eeprom_bit)&(0x8000>>dev9.eeprom_bit)); + dev9.eeprom_bit++; + if(dev9.eeprom_bit==16) + { + dev9.eeprom_address++; + dev9.eeprom_bit=0; + } + } + } + break; + } + + return; + + default: + if ((addr >= FLASH_REGBASE) && (addr < (FLASH_REGBASE + FLASH_REGSIZE))) { + FLASHwrite32(addr, (u32)value, 1); + return; + } + + dev9Ru8(addr) = value; + DEV9_LOG("*Unknown 8bit write at address %lx value %x\n", addr, value); + return; + } + dev9Ru8(addr) = value; + DEV9_LOG("*Known 8bit write at address %lx value %x\n", addr, value); +} + +void CALLBACK DEV9write16(u32 addr, u16 value) +{ + if (addr>=ATA_DEV9_HDD_BASE && addr(addr,value); +#endif + return; + } + if (addr>=SMAP_REGBASE && addr= FLASH_REGBASE) && (addr < (FLASH_REGBASE + FLASH_REGSIZE))) { + FLASHwrite32(addr, (u32)value, 2); + return; + } + + dev9Ru16(addr) = value; + DEV9_LOG("*Unknown 16bit write at address %lx value %x\n", addr, value); + return; + } + dev9Ru16(addr) = value; + DEV9_LOG("*Known 16bit write at address %lx value %x\n", addr, value); +} + +void CALLBACK DEV9write32(u32 addr, u32 value) +{ + if (addr>=ATA_DEV9_HDD_BASE && addr(addr,value); +#endif + return; + } + if (addr>=SMAP_REGBASE && addr= FLASH_REGBASE) && (addr < (FLASH_REGBASE + FLASH_REGSIZE))) { + FLASHwrite32(addr, (u32)value, 4); + return; + } + + dev9Ru32(addr) = value; + DEV9_LOG("*Unknown 32bit write at address %lx write %x\n", addr, value); + return; + } + dev9Ru32(addr) = value; + DEV9_LOG("*Known 32bit write at address %lx value %lx\n", addr, value); +} + +void CALLBACK DEV9readDMA8Mem(u32 *pMem, int size) +{ + DEV9_LOG("*DEV9readDMA8Mem: size %x\n", size); + emu_printf("rDMA\n"); + + smap_readDMA8Mem(pMem,size); +#ifdef ENABLE_ATA + ata_readDMA8Mem(pMem,size); +#endif +} + +void CALLBACK DEV9writeDMA8Mem(u32* pMem, int size) +{ + DEV9_LOG("*DEV9writeDMA8Mem: size %x\n", size); + emu_printf("wDMA\n"); + + smap_writeDMA8Mem(pMem,size); +#ifdef ENABLE_ATA + ata_writeDMA8Mem(pMem,size); +#endif +} + + +//plugin interface +void CALLBACK DEV9irqCallback(void (*callback)(int cycles)) { + DEV9irq = callback; +} + + +// extended funcs + +s32 CALLBACK DEV9test() { + return 0; +} + +void CALLBACK DEV9setSettingsDir(const char* dir) +{ + // Grab the ini directory. + // TODO: Use + // s_strIniPath = (dir == NULL) ? "inis" : dir; +} + + +int emu_printf(const char *fmt, ...) +{ + va_list vl; + int ret; + va_start(vl,fmt); + ret = vfprintf(stderr,fmt,vl); + va_end(vl); + fflush(stderr); + return ret; +} \ No newline at end of file diff --git a/plugins/dev9ghzdrk/DEV9.h b/plugins/dev9ghzdrk/DEV9.h new file mode 100644 index 0000000000..ef9d140b23 --- /dev/null +++ b/plugins/dev9ghzdrk/DEV9.h @@ -0,0 +1,629 @@ +#ifndef __DEV9_H__ +#define __DEV9_H__ + +#include +#ifndef EXTERN +#define EXTERN extern +#endif +#define DEV9defs +//#define WINVER 0x0600 +//#define _WIN32_WINNT 0x0500 + +#include "PS2Edefs.h" +#include "net.h" + +#ifdef __WIN32__ + +#define usleep(x) Sleep(x / 1000) +#include +#include +#include + +#else + +#include + +#define __inline inline + +#endif + +#define DEV9_LOG_ENABLE + +#ifdef DEV9_LOG_ENABLE +#define DEV9_LOG __Log +#else +#define DEV9_LOG(...) () +#endif + +void rx_process(NetPacket* pk); +bool rx_fifo_can_rx(); + +#define ETH_DEF "eth0" +#define HDD_DEF "DEV9hdd.raw" + + typedef struct { + char Eth[256]; + char Hdd[256]; + int HddSize; + + int hddEnable; + int ethEnable; +} Config; + +EXTERN Config config; + +typedef struct { + s8 dev9R[0x10000]; + u8 eeprom_state; + u8 eeprom_command; + u8 eeprom_address; + u8 eeprom_bit; + u8 eeprom_dir; + u16 *eeprom;//[32]; + + u32 rxbdi; + u8 rxfifo[16*1024]; + u16 rxfifo_wr_ptr; + + u32 txbdi; + u8 txfifo[16*1024]; + u16 txfifo_rd_ptr; + + u8 bd_swap; + u16 atabuf[1024]; + u32 atacount; + u32 atasize; + u16 phyregs[32]; + int irqcause; + u8 atacmd; + u32 atasector; + u32 atansector; +} dev9Struct; + +//EEPROM states +#define EEPROM_READY 0 +#define EEPROM_OPCD0 1 //waiting for first bit of opcode +#define EEPROM_OPCD1 2 //waiting for second bit of opcode +#define EEPROM_ADDR0 3 //waiting for address bits +#define EEPROM_ADDR1 4 +#define EEPROM_ADDR2 5 +#define EEPROM_ADDR3 6 +#define EEPROM_ADDR4 7 +#define EEPROM_ADDR5 8 +#define EEPROM_TDATA 9 //ready to send/receive data + +EXTERN dev9Struct dev9; + +#define dev9_rxfifo_write(x) (dev9.rxfifo[dev9.rxfifo_wr_ptr++]=x) + +#define dev9Rs8(mem) dev9.dev9R[(mem) & 0xffff] +#define dev9Rs16(mem) (*(s16*)&dev9.dev9R[(mem) & 0xffff]) +#define dev9Rs32(mem) (*(s32*)&dev9.dev9R[(mem) & 0xffff]) +#define dev9Ru8(mem) (*(u8*) &dev9.dev9R[(mem) & 0xffff]) +#define dev9Ru16(mem) (*(u16*)&dev9.dev9R[(mem) & 0xffff]) +#define dev9Ru32(mem) (*(u32*)&dev9.dev9R[(mem) & 0xffff]) + +EXTERN int ThreadRun; + +s32 _DEV9open(); +void _DEV9close(); +EXTERN DEV9callback DEV9irq; +//void DEV9thread(); + +EXTERN FILE *dev9Log; +void __Log(char *fmt, ...); + +void SysMessage(char *fmt, ...); + +#define DEV9_R_REV 0x1f80146e + + +/* + * SPEED (ASIC on SMAP) register definitions. + * + * Copyright (c) 2003 Marcus R. Brown + * + * * code included from the ps2smap iop driver, modified by linuzappz * + */ + +#define SPD_REGBASE 0x10000000 + +#define SPD_R_REV (SPD_REGBASE + 0x00) +#define SPD_R_REV_1 (SPD_REGBASE + 0x02) + // bit 0: smap + // bit 1: hdd + // bit 5: flash +#define SPD_R_REV_3 (SPD_REGBASE + 0x04) +#define SPD_R_0e (SPD_REGBASE + 0x0e) + +#define SPD_R_DMA_CTRL (SPD_REGBASE + 0x24) +#define SPD_R_INTR_STAT (SPD_REGBASE + 0x28) +#define SPD_R_INTR_MASK (SPD_REGBASE + 0x2a) +#define SPD_R_PIO_DIR (SPD_REGBASE + 0x2c) +#define SPD_R_PIO_DATA (SPD_REGBASE + 0x2e) +#define SPD_PP_DOUT (1<<4) /* Data output, read port */ +#define SPD_PP_DIN (1<<5) /* Data input, write port */ +#define SPD_PP_SCLK (1<<6) /* Clock, write port */ +#define SPD_PP_CSEL (1<<7) /* Chip select, write port */ +/* Operation codes */ +#define SPD_PP_OP_READ 2 +#define SPD_PP_OP_WRITE 1 +#define SPD_PP_OP_EWEN 0 +#define SPD_PP_OP_EWDS 0 + +#define SPD_R_XFR_CTRL (SPD_REGBASE + 0x32) +#define SPD_R_IF_CTRL (SPD_REGBASE + 0x64) +#define SPD_IF_ATA_RESET 0x80 +#define SPD_IF_DMA_ENABLE 0x04 +#define SPD_R_PIO_MODE (SPD_REGBASE + 0x70) +#define SPD_R_MWDMA_MODE (SPD_REGBASE + 0x72) +#define SPD_R_UDMA_MODE (SPD_REGBASE + 0x74) + + +/* + * SMAP (PS2 Network Adapter) register definitions. + * + * Copyright (c) 2003 Marcus R. Brown + * + * * code included from the ps2smap iop driver, modified by linuzappz * + */ + + +/* SMAP interrupt status bits (selected from the SPEED device). */ +#define SMAP_INTR_EMAC3 (1<<6) +#define SMAP_INTR_RXEND (1<<5) +#define SMAP_INTR_TXEND (1<<4) +#define SMAP_INTR_RXDNV (1<<3) /* descriptor not valid */ +#define SMAP_INTR_TXDNV (1<<2) /* descriptor not valid */ +#define SMAP_INTR_CLR_ALL (SMAP_INTR_RXEND|SMAP_INTR_TXEND|SMAP_INTR_RXDNV) +#define SMAP_INTR_ENA_ALL (SMAP_INTR_EMAC3|SMAP_INTR_CLR_ALL) +#define SMAP_INTR_BITMSK 0x7C + +/* SMAP Register Definitions. */ + +#define SMAP_REGBASE (SPD_REGBASE + 0x100) + +#define SMAP_R_BD_MODE (SMAP_REGBASE + 0x02) +#define SMAP_BD_SWAP (1<<0) + +#define SMAP_R_INTR_CLR (SMAP_REGBASE + 0x28) + +/* SMAP FIFO Registers. */ + +#define SMAP_R_TXFIFO_CTRL (SMAP_REGBASE + 0xf00) +#define SMAP_TXFIFO_RESET (1<<0) +#define SMAP_TXFIFO_DMAEN (1<<1) +#define SMAP_R_TXFIFO_WR_PTR (SMAP_REGBASE + 0xf04) +#define SMAP_R_TXFIFO_SIZE (SMAP_REGBASE + 0xf08) +#define SMAP_R_TXFIFO_FRAME_CNT (SMAP_REGBASE + 0xf0C) +#define SMAP_R_TXFIFO_FRAME_INC (SMAP_REGBASE + 0xf10) +#define SMAP_R_TXFIFO_DATA (SMAP_REGBASE + 0x1000) + +#define SMAP_R_RXFIFO_CTRL (SMAP_REGBASE + 0xf30) +#define SMAP_RXFIFO_RESET (1<<0) +#define SMAP_RXFIFO_DMAEN (1<<1) +#define SMAP_R_RXFIFO_RD_PTR (SMAP_REGBASE + 0xf34) +#define SMAP_R_RXFIFO_SIZE (SMAP_REGBASE + 0xf38) +#define SMAP_R_RXFIFO_FRAME_CNT (SMAP_REGBASE + 0xf3C) +#define SMAP_R_RXFIFO_FRAME_DEC (SMAP_REGBASE + 0xf40) +#define SMAP_R_RXFIFO_DATA (SMAP_REGBASE + 0x1100) + +#define SMAP_R_FIFO_ADDR (SMAP_REGBASE + 0x1200) +#define SMAP_FIFO_CMD_READ (1<<1) +#define SMAP_FIFO_DATA_SWAP (1<<0) +#define SMAP_R_FIFO_DATA (SMAP_REGBASE + 0x1208) + +/* EMAC3 Registers. */ + +#define SMAP_EMAC3_REGBASE (SMAP_REGBASE + 0x1f00) + +#define SMAP_R_EMAC3_MODE0_L (SMAP_EMAC3_REGBASE + 0x00) +#define SMAP_E3_RXMAC_IDLE (1<<(15+16)) +#define SMAP_E3_TXMAC_IDLE (1<<(14+16)) +#define SMAP_E3_SOFT_RESET (1<<(13+16)) +#define SMAP_E3_TXMAC_ENABLE (1<<(12+16)) +#define SMAP_E3_RXMAC_ENABLE (1<<(11+16)) +#define SMAP_E3_WAKEUP_ENABLE (1<<(10+16)) +#define SMAP_R_EMAC3_MODE0_H (SMAP_EMAC3_REGBASE + 0x02) + +#define SMAP_R_EMAC3_MODE1 (SMAP_EMAC3_REGBASE + 0x04) +#define SMAP_R_EMAC3_MODE1_L (SMAP_EMAC3_REGBASE + 0x04) +#define SMAP_R_EMAC3_MODE1_H (SMAP_EMAC3_REGBASE + 0x06) +#define SMAP_E3_FDX_ENABLE (1<<31) +#define SMAP_E3_INLPBK_ENABLE (1<<30) /* internal loop back */ +#define SMAP_E3_VLAN_ENABLE (1<<29) +#define SMAP_E3_FLOWCTRL_ENABLE (1<<28) /* integrated flow ctrl(pause frame) */ +#define SMAP_E3_ALLOW_PF (1<<27) /* allow pause frame */ +#define SMAP_E3_ALLOW_EXTMNGIF (1<<25) /* allow external management IF */ +#define SMAP_E3_IGNORE_SQE (1<<24) +#define SMAP_E3_MEDIA_FREQ_BITSFT (22) +#define SMAP_E3_MEDIA_10M (0<<22) +#define SMAP_E3_MEDIA_100M (1<<22) +#define SMAP_E3_MEDIA_1000M (2<<22) +#define SMAP_E3_MEDIA_MSK (3<<22) +#define SMAP_E3_RXFIFO_SIZE_BITSFT (20) +#define SMAP_E3_RXFIFO_512 (0<<20) +#define SMAP_E3_RXFIFO_1K (1<<20) +#define SMAP_E3_RXFIFO_2K (2<<20) +#define SMAP_E3_RXFIFO_4K (3<<20) +#define SMAP_E3_TXFIFO_SIZE_BITSFT (18) +#define SMAP_E3_TXFIFO_512 (0<<18) +#define SMAP_E3_TXFIFO_1K (1<<18) +#define SMAP_E3_TXFIFO_2K (2<<18) +#define SMAP_E3_TXREQ0_BITSFT (15) +#define SMAP_E3_TXREQ0_SINGLE (0<<15) +#define SMAP_E3_TXREQ0_MULTI (1<<15) +#define SMAP_E3_TXREQ0_DEPEND (2<<15) +#define SMAP_E3_TXREQ1_BITSFT (13) +#define SMAP_E3_TXREQ1_SINGLE (0<<13) +#define SMAP_E3_TXREQ1_MULTI (1<<13) +#define SMAP_E3_TXREQ1_DEPEND (2<<13) +#define SMAP_E3_JUMBO_ENABLE (1<<12) + +#define SMAP_R_EMAC3_TxMODE0_L (SMAP_EMAC3_REGBASE + 0x08) +#define SMAP_E3_TX_GNP_0 (1<<(15+16)) /* get new packet */ +#define SMAP_E3_TX_GNP_1 (1<<(14+16)) /* get new packet */ +#define SMAP_E3_TX_GNP_DEPEND (1<<(13+16)) /* get new packet */ +#define SMAP_E3_TX_FIRST_CHANNEL (1<<(12+16)) +#define SMAP_R_EMAC3_TxMODE0_H (SMAP_EMAC3_REGBASE + 0x0A) + +#define SMAP_R_EMAC3_TxMODE1_L (SMAP_EMAC3_REGBASE + 0x0C) +#define SMAP_R_EMAC3_TxMODE1_H (SMAP_EMAC3_REGBASE + 0x0E) +#define SMAP_E3_TX_LOW_REQ_MSK (0x1F) /* low priority request */ +#define SMAP_E3_TX_LOW_REQ_BITSFT (27) /* low priority request */ +#define SMAP_E3_TX_URG_REQ_MSK (0xFF) /* urgent priority request */ +#define SMAP_E3_TX_URG_REQ_BITSFT (16) /* urgent priority request */ + +#define SMAP_R_EMAC3_RxMODE (SMAP_EMAC3_REGBASE + 0x10) +#define SMAP_R_EMAC3_RxMODE_L (SMAP_EMAC3_REGBASE + 0x10) +#define SMAP_R_EMAC3_RxMODE_H (SMAP_EMAC3_REGBASE + 0x12) +#define SMAP_E3_RX_STRIP_PAD (1<<31) +#define SMAP_E3_RX_STRIP_FCS (1<<30) +#define SMAP_E3_RX_RX_RUNT_FRAME (1<<29) +#define SMAP_E3_RX_RX_FCS_ERR (1<<28) +#define SMAP_E3_RX_RX_TOO_LONG_ERR (1<<27) +#define SMAP_E3_RX_RX_IN_RANGE_ERR (1<<26) +#define SMAP_E3_RX_PROP_PF (1<<25) /* propagate pause frame */ +#define SMAP_E3_RX_PROMISC (1<<24) +#define SMAP_E3_RX_PROMISC_MCAST (1<<23) +#define SMAP_E3_RX_INDIVID_ADDR (1<<22) +#define SMAP_E3_RX_INDIVID_HASH (1<<21) +#define SMAP_E3_RX_BCAST (1<<20) +#define SMAP_E3_RX_MCAST (1<<19) + +#define SMAP_R_EMAC3_INTR_STAT (SMAP_EMAC3_REGBASE + 0x14) +#define SMAP_R_EMAC3_INTR_STAT_L (SMAP_EMAC3_REGBASE + 0x14) +#define SMAP_R_EMAC3_INTR_STAT_H (SMAP_EMAC3_REGBASE + 0x16) +#define SMAP_R_EMAC3_INTR_ENABLE (SMAP_EMAC3_REGBASE + 0x18) +#define SMAP_R_EMAC3_INTR_ENABLE_L (SMAP_EMAC3_REGBASE + 0x18) +#define SMAP_R_EMAC3_INTR_ENABLE_H (SMAP_EMAC3_REGBASE + 0x1A) +#define SMAP_E3_INTR_OVERRUN (1<<25) /* this bit does NOT WORKED */ +#define SMAP_E3_INTR_PF (1<<24) +#define SMAP_E3_INTR_BAD_FRAME (1<<23) +#define SMAP_E3_INTR_RUNT_FRAME (1<<22) +#define SMAP_E3_INTR_SHORT_EVENT (1<<21) +#define SMAP_E3_INTR_ALIGN_ERR (1<<20) +#define SMAP_E3_INTR_BAD_FCS (1<<19) +#define SMAP_E3_INTR_TOO_LONG (1<<18) +#define SMAP_E3_INTR_OUT_RANGE_ERR (1<<17) +#define SMAP_E3_INTR_IN_RANGE_ERR (1<<16) +#define SMAP_E3_INTR_DEAD_DEPEND (1<<9) +#define SMAP_E3_INTR_DEAD_0 (1<<8) +#define SMAP_E3_INTR_SQE_ERR_0 (1<<7) +#define SMAP_E3_INTR_TX_ERR_0 (1<<6) +#define SMAP_E3_INTR_DEAD_1 (1<<5) +#define SMAP_E3_INTR_SQE_ERR_1 (1<<4) +#define SMAP_E3_INTR_TX_ERR_1 (1<<3) +#define SMAP_E3_INTR_MMAOP_SUCCESS (1<<1) +#define SMAP_E3_INTR_MMAOP_FAIL (1<<0) +#define SMAP_E3_INTR_ALL \ + (SMAP_E3_INTR_OVERRUN|SMAP_E3_INTR_PF|SMAP_E3_INTR_BAD_FRAME| \ + SMAP_E3_INTR_RUNT_FRAME|SMAP_E3_INTR_SHORT_EVENT| \ + SMAP_E3_INTR_ALIGN_ERR|SMAP_E3_INTR_BAD_FCS| \ + SMAP_E3_INTR_TOO_LONG|SMAP_E3_INTR_OUT_RANGE_ERR| \ + SMAP_E3_INTR_IN_RANGE_ERR| \ + SMAP_E3_INTR_DEAD_DEPEND|SMAP_E3_INTR_DEAD_0| \ + SMAP_E3_INTR_SQE_ERR_0|SMAP_E3_INTR_TX_ERR_0| \ + SMAP_E3_INTR_DEAD_1|SMAP_E3_INTR_SQE_ERR_1| \ + SMAP_E3_INTR_TX_ERR_1| \ + SMAP_E3_INTR_MMAOP_SUCCESS|SMAP_E3_INTR_MMAOP_FAIL) +#define SMAP_E3_DEAD_ALL \ + (SMAP_E3_INTR_DEAD_DEPEND|SMAP_E3_INTR_DEAD_0| \ + SMAP_E3_INTR_DEAD_1) + +#define SMAP_R_EMAC3_ADDR_HI (SMAP_EMAC3_REGBASE + 0x1C) +#define SMAP_R_EMAC3_ADDR_LO (SMAP_EMAC3_REGBASE + 0x20) +#define SMAP_R_EMAC3_ADDR_HI_L (SMAP_EMAC3_REGBASE + 0x1C) +#define SMAP_R_EMAC3_ADDR_HI_H (SMAP_EMAC3_REGBASE + 0x1E) +#define SMAP_R_EMAC3_ADDR_LO_L (SMAP_EMAC3_REGBASE + 0x20) +#define SMAP_R_EMAC3_ADDR_LO_H (SMAP_EMAC3_REGBASE + 0x22) + +#define SMAP_R_EMAC3_VLAN_TPID (SMAP_EMAC3_REGBASE + 0x24) +#define SMAP_E3_VLAN_ID_MSK 0xFFFF + +#define SMAP_R_EMAC3_VLAN_TCI (SMAP_EMAC3_REGBASE + 0x28) +#define SMAP_E3_VLAN_TCITAG_MSK 0xFFFF + +#define SMAP_R_EMAC3_PAUSE_TIMER (SMAP_EMAC3_REGBASE + 0x2C) +#define SMAP_R_EMAC3_PAUSE_TIMER_L (SMAP_EMAC3_REGBASE + 0x2C) +#define SMAP_R_EMAC3_PAUSE_TIMER_H (SMAP_EMAC3_REGBASE + 0x2E) +#define SMAP_E3_PTIMER_MSK 0xFFFF + +#define SMAP_R_EMAC3_INDIVID_HASH1 (SMAP_EMAC3_REGBASE + 0x30) +#define SMAP_R_EMAC3_INDIVID_HASH2 (SMAP_EMAC3_REGBASE + 0x34) +#define SMAP_R_EMAC3_INDIVID_HASH3 (SMAP_EMAC3_REGBASE + 0x38) +#define SMAP_R_EMAC3_INDIVID_HASH4 (SMAP_EMAC3_REGBASE + 0x3C) +#define SMAP_R_EMAC3_GROUP_HASH1 (SMAP_EMAC3_REGBASE + 0x40) +#define SMAP_R_EMAC3_GROUP_HASH2 (SMAP_EMAC3_REGBASE + 0x44) +#define SMAP_R_EMAC3_GROUP_HASH3 (SMAP_EMAC3_REGBASE + 0x48) +#define SMAP_R_EMAC3_GROUP_HASH4 (SMAP_EMAC3_REGBASE + 0x4C) +#define SMAP_E3_HASH_MSK 0xFFFF + +#define SMAP_R_EMAC3_LAST_SA_HI (SMAP_EMAC3_REGBASE + 0x50) +#define SMAP_R_EMAC3_LAST_SA_LO (SMAP_EMAC3_REGBASE + 0x54) + +#define SMAP_R_EMAC3_INTER_FRAME_GAP (SMAP_EMAC3_REGBASE + 0x58) +#define SMAP_R_EMAC3_INTER_FRAME_GAP_L (SMAP_EMAC3_REGBASE + 0x58) +#define SMAP_R_EMAC3_INTER_FRAME_GAP_H (SMAP_EMAC3_REGBASE + 0x5A) +#define SMAP_E3_IFGAP_MSK 0x3F + + +#define SMAP_R_EMAC3_STA_CTRL_L (SMAP_EMAC3_REGBASE + 0x5C) +#define SMAP_R_EMAC3_STA_CTRL_H (SMAP_EMAC3_REGBASE + 0x5E) +#define SMAP_E3_PHY_DATA_MSK (0xFFFF) +#define SMAP_E3_PHY_DATA_BITSFT (16) +#define SMAP_E3_PHY_OP_COMP (1<<15) /* operation complete */ +#define SMAP_E3_PHY_ERR_READ (1<<14) +#define SMAP_E3_PHY_STA_CMD_BITSFT (12) +#define SMAP_E3_PHY_READ (1<<12) +#define SMAP_E3_PHY_WRITE (2<<12) +#define SMAP_E3_PHY_OPBCLCK_BITSFT (10) +#define SMAP_E3_PHY_50M (0<<10) +#define SMAP_E3_PHY_66M (1<<10) +#define SMAP_E3_PHY_83M (2<<10) +#define SMAP_E3_PHY_100M (3<<10) +#define SMAP_E3_PHY_ADDR_MSK (0x1F) +#define SMAP_E3_PHY_ADDR_BITSFT (5) +#define SMAP_E3_PHY_REG_ADDR_MSK (0x1F) + +#define SMAP_R_EMAC3_TX_THRESHOLD (SMAP_EMAC3_REGBASE + 0x60) +#define SMAP_R_EMAC3_TX_THRESHOLD_L (SMAP_EMAC3_REGBASE + 0x60) +#define SMAP_R_EMAC3_TX_THRESHOLD_H (SMAP_EMAC3_REGBASE + 0x62) +#define SMAP_E3_TX_THRESHLD_MSK (0x1F) +#define SMAP_E3_TX_THRESHLD_BITSFT (27) + +#define SMAP_R_EMAC3_RX_WATERMARK (SMAP_EMAC3_REGBASE + 0x64) +#define SMAP_R_EMAC3_RX_WATERMARK_L (SMAP_EMAC3_REGBASE + 0x64) +#define SMAP_R_EMAC3_RX_WATERMARK_H (SMAP_EMAC3_REGBASE + 0x66) +#define SMAP_E3_RX_LO_WATER_MSK (0x1FF) +#define SMAP_E3_RX_LO_WATER_BITSFT (23) +#define SMAP_E3_RX_HI_WATER_MSK (0x1FF) +#define SMAP_E3_RX_HI_WATER_BITSFT (7) + +#define SMAP_R_EMAC3_TX_OCTETS (SMAP_EMAC3_REGBASE + 0x68) +#define SMAP_R_EMAC3_RX_OCTETS (SMAP_EMAC3_REGBASE + 0x6C) +#define SMAP_EMAC3_REGEND (SMAP_EMAC3_REGBASE + 0x6C + 4) + +/* Buffer descriptors. */ + +typedef struct _smap_bd { + u16 ctrl_stat; + u16 reserved; /* must be zero */ + u16 length; /* number of bytes in pkt */ + u16 pointer; +} smap_bd_t; + +#define SMAP_BD_REGBASE (SMAP_REGBASE + 0x2f00) +#define SMAP_BD_TX_BASE (SMAP_BD_REGBASE + 0x0000) +#define SMAP_BD_RX_BASE (SMAP_BD_REGBASE + 0x0200) +#define SMAP_BD_SIZE 512 +#define SMAP_BD_MAX_ENTRY 64 + +#define SMAP_TX_BASE (SMAP_REGBASE + 0x1000) +#define SMAP_TX_BUFSIZE 4096 + +/* TX Control */ +#define SMAP_BD_TX_READY (1<<15) /* set:driver, clear:HW */ +#define SMAP_BD_TX_GENFCS (1<<9) /* generate FCS */ +#define SMAP_BD_TX_GENPAD (1<<8) /* generate padding */ +#define SMAP_BD_TX_INSSA (1<<7) /* insert source address */ +#define SMAP_BD_TX_RPLSA (1<<6) /* replace source address */ +#define SMAP_BD_TX_INSVLAN (1<<5) /* insert VLAN Tag */ +#define SMAP_BD_TX_RPLVLAN (1<<4) /* replace VLAN Tag */ + +/* TX Status */ +#define SMAP_BD_TX_READY (1<<15) /* set:driver, clear:HW */ +#define SMAP_BD_TX_BADFCS (1<<9) /* bad FCS */ +#define SMAP_BD_TX_BADPKT (1<<8) /* bad previous pkt in dependent mode */ +#define SMAP_BD_TX_LOSSCR (1<<7) /* loss of carrior sense */ +#define SMAP_BD_TX_EDEFER (1<<6) /* excessive deferal */ +#define SMAP_BD_TX_ECOLL (1<<5) /* excessive collision */ +#define SMAP_BD_TX_LCOLL (1<<4) /* late collision */ +#define SMAP_BD_TX_MCOLL (1<<3) /* multiple collision */ +#define SMAP_BD_TX_SCOLL (1<<2) /* single collision */ +#define SMAP_BD_TX_UNDERRUN (1<<1) /* underrun */ +#define SMAP_BD_TX_SQE (1<<0) /* SQE */ + +#define SMAP_BD_TX_ERROR (SMAP_BD_TX_LOSSCR|SMAP_BD_TX_EDEFER|SMAP_BD_TX_ECOLL| \ + SMAP_BD_TX_LCOLL|SMAP_BD_TX_UNDERRUN) + +/* RX Control */ +#define SMAP_BD_RX_EMPTY (1<<15) /* set:driver, clear:HW */ + +/* RX Status */ +#define SMAP_BD_RX_EMPTY (1<<15) /* set:driver, clear:HW */ +#define SMAP_BD_RX_OVERRUN (1<<9) /* overrun */ +#define SMAP_BD_RX_PFRM (1<<8) /* pause frame */ +#define SMAP_BD_RX_BADFRM (1<<7) /* bad frame */ +#define SMAP_BD_RX_RUNTFRM (1<<6) /* runt frame */ +#define SMAP_BD_RX_SHORTEVNT (1<<5) /* short event */ +#define SMAP_BD_RX_ALIGNERR (1<<4) /* alignment error */ +#define SMAP_BD_RX_BADFCS (1<<3) /* bad FCS */ +#define SMAP_BD_RX_FRMTOOLONG (1<<2) /* frame too long */ +#define SMAP_BD_RX_OUTRANGE (1<<1) /* out of range error */ +#define SMAP_BD_RX_INRANGE (1<<0) /* in range error */ + +#define SMAP_BD_RX_ERROR (SMAP_BD_RX_OVERRUN|SMAP_BD_RX_RUNTFRM|SMAP_BD_RX_SHORTEVNT| \ + SMAP_BD_RX_ALIGNERR|SMAP_BD_RX_BADFCS|SMAP_BD_RX_FRMTOOLONG| \ + SMAP_BD_RX_OUTRANGE|SMAP_BD_RX_INRANGE) + +/* PHY registers (National Semiconductor DP83846A). */ + +#define SMAP_NS_OUI 0x080017 +#define SMAP_DsPHYTER_ADDRESS 0x1 + +#define SMAP_DsPHYTER_BMCR 0x00 +#define SMAP_PHY_BMCR_RST (1<<15) /* ReSeT */ +#define SMAP_PHY_BMCR_LPBK (1<<14) /* LooPBacK */ +#define SMAP_PHY_BMCR_100M (1<<13) /* speed select, 1:100M, 0:10M */ +#define SMAP_PHY_BMCR_10M (0<<13) /* speed select, 1:100M, 0:10M */ +#define SMAP_PHY_BMCR_ANEN (1<<12) /* Auto-Negotiation ENable */ +#define SMAP_PHY_BMCR_PWDN (1<<11) /* PoWer DowN */ +#define SMAP_PHY_BMCR_ISOL (1<<10) /* ISOLate */ +#define SMAP_PHY_BMCR_RSAN (1<<9) /* ReStart Auto-Negotiation */ +#define SMAP_PHY_BMCR_DUPM (1<<8) /* DUPlex Mode, 1:FDX, 0:HDX */ +#define SMAP_PHY_BMCR_COLT (1<<7) /* COLlision Test */ + +#define SMAP_DsPHYTER_BMSR 0x01 +#define SMAP_PHY_BMSR_ANCP (1<<5) /* Auto-Negotiation ComPlete */ +#define SMAP_PHY_BMSR_LINK (1<<2) /* LINK status */ + +#define SMAP_DsPHYTER_PHYIDR1 0x02 +#define SMAP_PHY_IDR1_VAL (((SMAP_NS_OUI<<2)>>8)&0xffff) + +#define SMAP_DsPHYTER_PHYIDR2 0x03 +#define SMAP_PHY_IDR2_VMDL 0x2 /* Vendor MoDeL number */ +#define SMAP_PHY_IDR2_VAL \ + (((SMAP_NS_OUI<<10)&0xFC00)|((SMAP_PHY_IDR2_VMDL<<4)&0x3F0)) +#define SMAP_PHY_IDR2_MSK 0xFFF0 +#define SMAP_PHY_IDR2_REV_MSK 0x000F + +#define SMAP_DsPHYTER_ANAR 0x04 +#define SMAP_DsPHYTER_ANLPAR 0x05 +#define SMAP_DsPHYTER_ANLPARNP 0x05 +#define SMAP_DsPHYTER_ANER 0x06 +#define SMAP_DsPHYTER_ANNPTR 0x07 + +/* Extended registers. */ +#define SMAP_DsPHYTER_PHYSTS 0x10 +#define SMAP_PHY_STS_REL (1<<13) /* Receive Error Latch */ +#define SMAP_PHY_STS_POST (1<<12) /* POlarity STatus */ +#define SMAP_PHY_STS_FCSL (1<<11) /* False Carrier Sense Latch */ +#define SMAP_PHY_STS_SD (1<<10) /* 100BT unconditional Signal Detect */ +#define SMAP_PHY_STS_DSL (1<<9) /* 100BT DeScrambler Lock */ +#define SMAP_PHY_STS_PRCV (1<<8) /* Page ReCeiVed */ +#define SMAP_PHY_STS_RFLT (1<<6) /* Remote FauLT */ +#define SMAP_PHY_STS_JBDT (1<<5) /* JaBber DetecT */ +#define SMAP_PHY_STS_ANCP (1<<4) /* Auto-Negotiation ComPlete */ +#define SMAP_PHY_STS_LPBK (1<<3) /* LooPBacK status */ +#define SMAP_PHY_STS_DUPS (1<<2) /* DUPlex Status,1:FDX,0:HDX */ +#define SMAP_PHY_STS_FDX (1<<2) /* Full Duplex */ +#define SMAP_PHY_STS_HDX (0<<2) /* Half Duplex */ +#define SMAP_PHY_STS_SPDS (1<<1) /* SPeeD Status */ +#define SMAP_PHY_STS_10M (1<<1) /* 10Mbps */ +#define SMAP_PHY_STS_100M (0<<1) /* 100Mbps */ +#define SMAP_PHY_STS_LINK (1<<0) /* LINK status */ +#define SMAP_DsPHYTER_FCSCR 0x14 +#define SMAP_DsPHYTER_RECR 0x15 +#define SMAP_DsPHYTER_PCSR 0x16 +#define SMAP_DsPHYTER_PHYCTRL 0x19 +#define SMAP_DsPHYTER_10BTSCR 0x1A +#define SMAP_DsPHYTER_CDCTRL 0x1B + +/* + * ATA hardware types and definitions. + * + * Copyright (c) 2003 Marcus R. Brown + * + * * code included from the ps2drv iop driver, modified by linuzappz * + */ + + +#define ATA_DEV9_HDD_BASE (SPD_REGBASE + 0x40) +/* AIF on T10Ks - Not supported yet. */ +#define ATA_AIF_HDD_BASE (SPD_REGBASE + 0x4000000 + 0x60) + +#define ATA_R_DATA (ATA_DEV9_HDD_BASE + 0x00) +#define ATA_R_ERROR (ATA_DEV9_HDD_BASE + 0x02) +#define ATA_R_NSECTOR (ATA_DEV9_HDD_BASE + 0x04) +#define ATA_R_SECTOR (ATA_DEV9_HDD_BASE + 0x06) +#define ATA_R_LCYL (ATA_DEV9_HDD_BASE + 0x08) +#define ATA_R_HCYL (ATA_DEV9_HDD_BASE + 0x0a) +#define ATA_R_SELECT (ATA_DEV9_HDD_BASE + 0x0c) +#define ATA_R_STATUS (ATA_DEV9_HDD_BASE + 0x0e) +#define ATA_R_CONTROL (ATA_DEV9_HDD_BASE + 0x1c) +#define ATA_DEV9_INT (0x01) +#define ATA_DEV9_INT_DMA (0x02) //not sure rly +#define ATA_DEV9_HDD_END (ATA_R_CONTROL+4) +/* + * NAND Flash via Dev9 driver definitions + * + * Copyright (c) 2003 Marcus R. Brown + * + * * code included from the ps2sdk iop driver * + */ + +#define FLASH_ID_64MBIT 0xe6 +#define FLASH_ID_128MBIT 0x73 +#define FLASH_ID_256MBIT 0x75 +#define FLASH_ID_512MBIT 0x76 +#define FLASH_ID_1024MBIT 0x79 + +/* SmartMedia commands. */ +#define SM_CMD_READ1 0x00 +#define SM_CMD_READ2 0x01 +#define SM_CMD_READ3 0x50 +#define SM_CMD_RESET 0xff +#define SM_CMD_WRITEDATA 0x80 +#define SM_CMD_PROGRAMPAGE 0x10 +#define SM_CMD_ERASEBLOCK 0x60 +#define SM_CMD_ERASECONFIRM 0xd0 +#define SM_CMD_GETSTATUS 0x70 +#define SM_CMD_READID 0x90 + +typedef struct { + u32 id; + u32 mbits; + u32 page_bytes; /* bytes/page */ + u32 block_pages; /* pages/block */ + u32 blocks; +} flash_info_t; + +/* +static flash_info_t devices[] = { + { FLASH_ID_64MBIT, 64, 528, 16, 1024 }, + { FLASH_ID_128MBIT, 128, 528, 32, 1024 }, + { FLASH_ID_256MBIT, 256, 528, 32, 2048 }, + { FLASH_ID_512MBIT, 512, 528, 32, 4096 }, + { FLASH_ID_1024MBIT, 1024, 528, 32, 8192 } +}; +#define NUM_DEVICES (sizeof(devices)/sizeof(flash_info_t)) +*/ + +// definitions added by Florin + +#define FLASH_REGBASE 0x10004800 + +#define FLASH_R_DATA (FLASH_REGBASE + 0x00) +#define FLASH_R_CMD (FLASH_REGBASE + 0x04) +#define FLASH_R_ADDR (FLASH_REGBASE + 0x08) +#define FLASH_R_CTRL (FLASH_REGBASE + 0x0C) +#define FLASH_PP_READY (1<<0) // r/w /BUSY +#define FLASH_PP_WRITE (1<<7) // -/w WRITE data +#define FLASH_PP_CSEL (1<<8) // -/w CS +#define FLASH_PP_READ (1<<11) // -/w READ data +#define FLASH_PP_NOECC (1<<12) // -/w ECC disabled +//#define FLASH_R_10 (FLASH_REGBASE + 0x10) +#define FLASH_R_ID (FLASH_REGBASE + 0x14) + +#define FLASH_REGSIZE 0x20 + +void CALLBACK FLASHinit(); +u32 CALLBACK FLASHread32(u32 addr, int size); +void CALLBACK FLASHwrite32(u32 addr, u32 value, int size); +void _DEV9irq(int cause, int cycles); + +int emu_printf(const char *fmt, ...); + +#pragma warning(error:4013) +#endif diff --git a/plugins/dev9ghzdrk/PS2Edefs.h b/plugins/dev9ghzdrk/PS2Edefs.h new file mode 100644 index 0000000000..0b15378dc9 --- /dev/null +++ b/plugins/dev9ghzdrk/PS2Edefs.h @@ -0,0 +1,684 @@ +#ifndef __PS2EDEFS_H__ +#define __PS2EDEFS_H__ + +/* + * PS2E Definitions v0.5.5 (beta) + * + * Author: linuzappz@hotmail.com + * shadowpcsx2@yahoo.gr + * florinsasu@hotmail.com + */ + +/* + Notes: + * Since this is still beta things may change. + + * OSflags: + __LINUX__ (linux OS) + __WIN32__ (win32 OS) + + * common return values (for ie. GSinit): + 0 - success + -1 - error + + * reserved keys: + F1 to F10 are reserved for the emulator + + * plugins should NOT change the current + working directory. + (on win32, add flag OFN_NOCHANGEDIR for + GetOpenFileName) + +*/ + +#include "PS2Etypes.h" + +#ifdef __LINUX__ +#define CALLBACK +#else +#include +#endif + +/* common defines */ + +#if defined(GSdefs) || defined(PADdefs) || \ + defined(SPU2defs)|| defined(CDVDdefs) +#define COMMONdefs +#endif + +// PS2EgetLibType returns (may be OR'd) +#define PS2E_LT_GS 0x01 +#define PS2E_LT_PAD 0x02 +#define PS2E_LT_SPU2 0x04 +#define PS2E_LT_CDVD 0x08 +#define PS2E_LT_DEV9 0x10 +#define PS2E_LT_USB 0x20 +#define PS2E_LT_FIREWIRE 0x40 + +// PS2EgetLibVersion2 (high 16 bits) +#define PS2E_GS_VERSION 0x0005 +#define PS2E_PAD_VERSION 0x0002 +#define PS2E_SPU2_VERSION 0x0004 +#define PS2E_CDVD_VERSION 0x0003 +#define PS2E_DEV9_VERSION 0x0003 +#define PS2E_USB_VERSION 0x0003 +#define PS2E_FIREWIRE_VERSION 0x0002 +#ifdef COMMONdefs + +u32 CALLBACK PS2EgetLibType(void); +u32 CALLBACK PS2EgetLibVersion2(u32 type); +char* CALLBACK PS2EgetLibName(void); + +#endif + +// key values: +/* key values must be OS dependant: + win32: the VK_XXX will be used (WinUser) + linux: the XK_XXX will be used (XFree86) +*/ + +// event values: +#define KEYPRESS 1 +#define KEYRELEASE 2 + +typedef struct { + u32 key; + u32 event; +} keyEvent; + +typedef struct { // NOT bcd coded + u8 minute; + u8 second; + u8 frame; + u8 type; +} cdvdTD; + +typedef struct { + u8 strack; //number of the first track (usualy 1) + u8 etrack; //number of the last track +} cdvdTN; + +// CDVDreadTrack mode values: +#define CDVD_MODE_2352 0 // full 2352 bytes +#define CDVD_MODE_2340 1 // skip sync (12) bytes +#define CDVD_MODE_2328 2 // skip sync+head+sub (24) bytes +#define CDVD_MODE_2048 3 // skip sync+head+sub (24) bytes +#define CDVD_MODE_2368 4 // full 2352 bytes + 16 subq + +// CDVDgetType returns: +#define CDVD_TYPE_ILLEGAL 0xff // Illegal Disc +#define CDVD_TYPE_DVDV 0xfe // DVD Video +#define CDVD_TYPE_CDDA 0xfd // Audio CD +#define CDVD_TYPE_PS2DVD 0x14 // PS2 DVD +#define CDVD_TYPE_PS2CDDA 0x13 // PS2 CD (with audio) +#define CDVD_TYPE_PS2CD 0x12 // PS2 CD +#define CDVD_TYPE_PSCDDA 0x11 // PS CD (with audio) +#define CDVD_TYPE_PSCD 0x10 // PS CD +#define CDVD_TYPE_UNKNOWN 0x05 // Unknown +#define CDVD_TYPE_DETCTDVDD 0x04 // Detecting Dvd Dual Sided +#define CDVD_TYPE_DETCTDVDS 0x03 // Detecting Dvd Single Sided +#define CDVD_TYPE_DETCTCD 0x02 // Detecting Cd +#define CDVD_TYPE_DETCT 0x01 // Detecting +#define CDVD_TYPE_NODISC 0x00 // No Disc + +// CDVDgetTrayStatus returns: +#define CDVD_TRAY_CLOSE 0x00 +#define CDVD_TRAY_OPEN 0x01 + +// cdvdLoc:track type +#define CDVD_AUDIO_TRACK 0x01 +#define CDVD_MODE1_TRACK 0x41 +#define CDVD_MODE2_TRACK 0x61 + +#define CDVD_AUDIO_MASK 0x00 +#define CDVD_DATA_MASK 0x40 +// CDROM_DATA_TRACK 0x04 //do not enable this! (from linux kernel) + +typedef void (*DEV9callback)(int cycles); +typedef int (*DEV9handler)(void); + +typedef void (*USBcallback)(int cycles); +typedef int (*USBhandler)(void); + +// freeze modes: +#define FREEZE_LOAD 0 +#define FREEZE_SAVE 1 +#define FREEZE_SIZE 2 + +typedef struct { + int size; + s8 *data; +} freezeData; + +typedef struct { + char name[8]; + void *common; +} GSdriverInfo; + +#ifdef __WIN32__ +typedef struct { // unsupported values must be set to zero + HWND hWnd; + HMENU hMenu; + HWND hStatusWnd; +} winInfo; +#endif + +/* GS plugin API */ + +// if this file is included with this define +// the next api will not be skipped by the compiler +#ifdef GSdefs + +// basic funcs + +s32 CALLBACK GSinit(); +s32 CALLBACK GSopen(void *pDsp, char *Title); +void CALLBACK GSclose(); +void CALLBACK GSshutdown(); +void CALLBACK GSvsync(); +void CALLBACK GSgifTransfer1(u32 *pMem); +void CALLBACK GSgifTransfer2(u32 *pMem, u32 size); +void CALLBACK GSgifTransfer3(u32 *pMem, u32 size); +void CALLBACK GSwrite32(u32 mem, u32 value); +void CALLBACK GSwrite64(u32 mem, u64 value); +u32 CALLBACK GSread32(u32 mem); +u64 CALLBACK GSread64(u32 mem); +void CALLBACK GSreadFIFO(u64 *mem); + +// extended funcs + +// GSkeyEvent gets called when there is a keyEvent from the PAD plugin +void CALLBACK GSkeyEvent(keyEvent *ev); +void CALLBACK GSmakeSnapshot(char *path); +void CALLBACK GSirqCallback(void (*callback)()); +void CALLBACK GSprintf(int timeout, char *fmt, ...); +void CALLBACK GSgetDriverInfo(GSdriverInfo *info); +#ifdef __WIN32__ +s32 CALLBACK GSsetWindowInfo(winInfo *info); +#endif +s32 CALLBACK GSfreeze(int mode, freezeData *data); +void CALLBACK GSconfigure(); +void CALLBACK GSabout(); +s32 CALLBACK GStest(); + +#endif + +/* PAD plugin API */ + +// if this file is included with this define +// the next api will not be skipped by the compiler +#ifdef PADdefs + +// basic funcs + +s32 CALLBACK PADinit(u32 flags); +s32 CALLBACK PADopen(void *pDsp); +void CALLBACK PADclose(); +void CALLBACK PADshutdown(); +// PADkeyEvent is called every vsync (return NULL if no event) +keyEvent* CALLBACK PADkeyEvent(); +u8 CALLBACK PADstartPoll(int pad); +u8 CALLBACK PADpoll(u8 value); +// returns: 1 if supported pad1 +// 2 if supported pad2 +// 3 if both are supported +u32 CALLBACK PADquery(); + +// extended funcs + +void CALLBACK PADgsDriverInfo(GSdriverInfo *info); +void CALLBACK PADconfigure(); +void CALLBACK PADabout(); +s32 CALLBACK PADtest(); + +#endif + +/* SPU2 plugin API */ + +// if this file is included with this define +// the next api will not be skipped by the compiler +#ifdef SPU2defs + +// basic funcs + +s32 CALLBACK SPU2init(); +s32 CALLBACK SPU2open(void *pDsp); +void CALLBACK SPU2close(); +void CALLBACK SPU2shutdown(); +void CALLBACK SPU2write(u32 mem, u16 value); +u16 CALLBACK SPU2read(u32 mem); +void CALLBACK SPU2readDMA4Mem(u16 *pMem, int size); +void CALLBACK SPU2writeDMA4Mem(u16 *pMem, int size); +void CALLBACK SPU2interruptDMA4(); +void CALLBACK SPU2readDMA7Mem(u16* pMem, int size); +void CALLBACK SPU2writeDMA7Mem(u16 *pMem, int size); +void CALLBACK SPU2interruptDMA7(); +void CALLBACK SPU2irqCallback(void (*callback)()); + +// extended funcs + +void CALLBACK SPU2async(u32 cycles); +s32 CALLBACK SPU2freeze(int mode, freezeData *data); +void CALLBACK SPU2configure(); +void CALLBACK SPU2about(); +s32 CALLBACK SPU2test(); + +#endif + +/* CDVD plugin API */ + +// if this file is included with this define +// the next api will not be skipped by the compiler +#ifdef CDVDdefs + +// basic funcs + +s32 CALLBACK CDVDinit(); +s32 CALLBACK CDVDopen(); +void CALLBACK CDVDclose(); +void CALLBACK CDVDshutdown(); +s32 CALLBACK CDVDreadTrack(u32 lsn, int mode); + +// return can be NULL (for async modes) +u8* CALLBACK CDVDgetBuffer(); + +s32 CALLBACK CDVDgetTN(cdvdTN *Buffer); //disk information +s32 CALLBACK CDVDgetTD(u8 Track, cdvdTD *Buffer); //track info: min,sec,frame,type +s32 CALLBACK CDVDgetType(); //CDVD_TYPE_xxxx +s32 CALLBACK CDVDgetTrayStatus(); //CDVD_TRAY_xxxx + +// extended funcs + +void CALLBACK CDVDconfigure(); +void CALLBACK CDVDabout(); +s32 CALLBACK CDVDtest(); + +#endif + +/* DEV9 plugin API */ + +// if this file is included with this define +// the next api will not be skipped by the compiler +#ifdef DEV9defs + +// basic funcs + +s32 CALLBACK DEV9init(); +s32 CALLBACK DEV9open(void *pDsp); +void CALLBACK DEV9close(); +void CALLBACK DEV9shutdown(); +u8 CALLBACK DEV9read8(u32 addr); +u16 CALLBACK DEV9read16(u32 addr); +u32 CALLBACK DEV9read32(u32 addr); +void CALLBACK DEV9write8(u32 addr, u8 value); +void CALLBACK DEV9write16(u32 addr, u16 value); +void CALLBACK DEV9write32(u32 addr, u32 value); +void CALLBACK DEV9readDMA8Mem(u32 *pMem, int size); +void CALLBACK DEV9writeDMA8Mem(u32 *pMem, int size); +// cycles = IOP cycles before calling callback, +// if callback returns 1 the irq is triggered, else not +void CALLBACK DEV9irqCallback(DEV9callback callback); +DEV9handler CALLBACK DEV9irqHandler(void); + +// extended funcs + +s32 CALLBACK DEV9freeze(int mode, freezeData *data); +void CALLBACK DEV9configure(); +void CALLBACK DEV9about(); +s32 CALLBACK DEV9test(); + +#endif + +/* USB plugin API */ + +// if this file is included with this define +// the next api will not be skipped by the compiler +#ifdef USBdefs + +// basic funcs + +s32 CALLBACK USBinit(); +s32 CALLBACK USBopen(void *pDsp); +void CALLBACK USBclose(); +void CALLBACK USBshutdown(); +u8 CALLBACK USBread8(u32 addr); +u16 CALLBACK USBread16(u32 addr); +u32 CALLBACK USBread32(u32 addr); +void CALLBACK USBwrite8(u32 addr, u8 value); +void CALLBACK USBwrite16(u32 addr, u16 value); +void CALLBACK USBwrite32(u32 addr, u32 value); +// cycles = IOP cycles before calling callback, +// if callback returns 1 the irq is triggered, else not +void CALLBACK USBirqCallback(USBcallback callback); +USBhandler CALLBACK USBirqHandler(void); +void CALLBACK USBsetRAM(void *mem); + +// extended funcs + +s32 CALLBACK USBfreeze(int mode, freezeData *data); +void CALLBACK USBconfigure(); +void CALLBACK USBabout(); +s32 CALLBACK USBtest(); + +#endif +/* Firewire plugin API */ + +// if this file is included with this define +// the next api will not be skipped by the compiler +#ifdef FIREWIREdefs +// basic funcs + +s32 CALLBACK FireWireinit(); +s32 CALLBACK FireWireopen(void *pDsp); +void CALLBACK FireWireclose(); +void CALLBACK FireWireshutdown(); +u32 CALLBACK FireWireread32(u32 addr); +void CALLBACK FireWirewrite32(u32 addr, u32 value); +void CALLBACK FireWireirqCallback(void (*callback)()); + +// extended funcs + +s32 CALLBACK FireWirefreeze(int mode, freezeData *data); +void CALLBACK FireWireconfigure(); +void CALLBACK FireWireabout(); +s32 CALLBACK FireWiretest(); +#endif + +// might be useful for emulators +#ifdef PLUGINtypedefs + +typedef u32 (CALLBACK* _PS2EgetLibType)(void); +typedef u32 (CALLBACK* _PS2EgetLibVersion2)(u32 type); +typedef char*(CALLBACK* _PS2EgetLibName)(void); + +// GS +typedef s32 (CALLBACK* _GSinit)(); +typedef s32 (CALLBACK* _GSopen)(void *pDsp, char *Title); +typedef void (CALLBACK* _GSclose)(); +typedef void (CALLBACK* _GSshutdown)(); +typedef void (CALLBACK* _GSvsync)(); +typedef void (CALLBACK* _GSwrite32)(u32 mem, u32 value); +typedef void (CALLBACK* _GSwrite64)(u32 mem, u64 value); +typedef u32 (CALLBACK* _GSread32)(u32 mem); +typedef u64 (CALLBACK* _GSread64)(u32 mem); +typedef void (CALLBACK* _GSgifTransfer1)(u32 *pMem); +typedef void (CALLBACK* _GSgifTransfer2)(u32 *pMem, u32 size); +typedef void (CALLBACK* _GSgifTransfer3)(u32 *pMem, u32 size); +typedef void (CALLBACK* _GSreadFIFO)(u64 *pMem); + +typedef void (CALLBACK* _GSkeyEvent)(keyEvent* ev); +typedef void (CALLBACK* _GSirqCallback)(void (*callback)()); +typedef void (CALLBACK* _GSprintf)(int timeout, char *fmt, ...); +typedef void (CALLBACK* _GSgetDriverInfo)(GSdriverInfo *info); +#ifdef __WIN32__ +typedef s32 (CALLBACK* _GSsetWindowInfo)(winInfo *info); +#endif +typedef void (CALLBACK* _GSmakeSnapshot)(char *path); +typedef s32 (CALLBACK* _GSfreeze)(int mode, freezeData *data); +typedef void (CALLBACK* _GSconfigure)(); +typedef s32 (CALLBACK* _GStest)(); +typedef void (CALLBACK* _GSabout)(); + +// PAD +typedef s32 (CALLBACK* _PADinit)(u32 flags); +typedef s32 (CALLBACK* _PADopen)(void *pDsp); +typedef void (CALLBACK* _PADclose)(); +typedef void (CALLBACK* _PADshutdown)(); +typedef keyEvent* (CALLBACK* _PADkeyEvent)(); +typedef u8 (CALLBACK* _PADstartPoll)(int pad); +typedef u8 (CALLBACK* _PADpoll)(u8 value); +typedef u32 (CALLBACK* _PADquery)(); + +typedef void (CALLBACK* _PADgsDriverInfo)(GSdriverInfo *info); +typedef void (CALLBACK* _PADconfigure)(); +typedef s32 (CALLBACK* _PADtest)(); +typedef void (CALLBACK* _PADabout)(); + +// SPU2 +typedef s32 (CALLBACK* _SPU2init)(); +typedef s32 (CALLBACK* _SPU2open)(void *pDsp); +typedef void (CALLBACK* _SPU2close)(); +typedef void (CALLBACK* _SPU2shutdown)(); +typedef void (CALLBACK* _SPU2write)(u32 mem, u16 value); +typedef u16 (CALLBACK* _SPU2read)(u32 mem); +typedef void (CALLBACK* _SPU2readDMA4Mem)(u16 *pMem, int size); +typedef void (CALLBACK* _SPU2writeDMA4Mem)(u16 *pMem, int size); +typedef void (CALLBACK* _SPU2interruptDMA4)(); +typedef void (CALLBACK* _SPU2readDMA7Mem)(u16 *pMem, int size); +typedef void (CALLBACK* _SPU2writeDMA7Mem)(u16 *pMem, int size); +typedef void (CALLBACK* _SPU2interruptDMA7)(); +typedef void (CALLBACK* _SPU2irqCallback)(void (*callback)()); + +typedef void (CALLBACK* _SPU2async)(u32 cycles); +typedef s32 (CALLBACK* _SPU2freeze)(int mode, freezeData *data); +typedef void (CALLBACK* _SPU2configure)(); +typedef s32 (CALLBACK* _SPU2test)(); +typedef void (CALLBACK* _SPU2about)(); + +// CDVD +typedef s32 (CALLBACK* _CDVDinit)(); +typedef s32 (CALLBACK* _CDVDopen)(); +typedef void (CALLBACK* _CDVDclose)(); +typedef void (CALLBACK* _CDVDshutdown)(); +typedef s32 (CALLBACK* _CDVDreadTrack)(u32 lsn, int mode); +typedef u8* (CALLBACK* _CDVDgetBuffer)(); +typedef s32 (CALLBACK* _CDVDgetTN)(cdvdTN *Buffer); +typedef s32 (CALLBACK* _CDVDgetTD)(u8 Track, cdvdTD *Buffer); +typedef s32 (CALLBACK* _CDVDgetType)(); +typedef s32 (CALLBACK* _CDVDgetTrayStatus)(); + +typedef void (CALLBACK* _CDVDconfigure)(); +typedef s32 (CALLBACK* _CDVDtest)(); +typedef void (CALLBACK* _CDVDabout)(); + +// DEV9 +typedef s32 (CALLBACK* _DEV9init)(); +typedef s32 (CALLBACK* _DEV9open)(void *pDsp); +typedef void (CALLBACK* _DEV9close)(); +typedef void (CALLBACK* _DEV9shutdown)(); +typedef u8 (CALLBACK* _DEV9read8)(u32 mem); +typedef u16 (CALLBACK* _DEV9read16)(u32 mem); +typedef u32 (CALLBACK* _DEV9read32)(u32 mem); +typedef void (CALLBACK* _DEV9write8)(u32 mem, u8 value); +typedef void (CALLBACK* _DEV9write16)(u32 mem, u16 value); +typedef void (CALLBACK* _DEV9write32)(u32 mem, u32 value); +typedef void (CALLBACK* _DEV9readDMA8Mem)(u32 *pMem, int size); +typedef void (CALLBACK* _DEV9writeDMA8Mem)(u32 *pMem, int size); +typedef void (CALLBACK* _DEV9irqCallback)(DEV9callback callback); +typedef DEV9handler (CALLBACK* _DEV9irqHandler)(void); + +typedef s32 (CALLBACK* _DEV9freeze)(int mode, freezeData *data); +typedef void (CALLBACK* _DEV9configure)(); +typedef s32 (CALLBACK* _DEV9test)(); +typedef void (CALLBACK* _DEV9about)(); + +// USB +typedef s32 (CALLBACK* _USBinit)(); +typedef s32 (CALLBACK* _USBopen)(void *pDsp); +typedef void (CALLBACK* _USBclose)(); +typedef void (CALLBACK* _USBshutdown)(); +typedef u8 (CALLBACK* _USBread8)(u32 mem); +typedef u16 (CALLBACK* _USBread16)(u32 mem); +typedef u32 (CALLBACK* _USBread32)(u32 mem); +typedef void (CALLBACK* _USBwrite8)(u32 mem, u8 value); +typedef void (CALLBACK* _USBwrite16)(u32 mem, u16 value); +typedef void (CALLBACK* _USBwrite32)(u32 mem, u32 value); +typedef void (CALLBACK* _USBirqCallback)(USBcallback callback); +typedef USBhandler (CALLBACK* _USBirqHandler)(void); +typedef void (CALLBACK* _USBsetRAM)(void *mem); + +typedef s32 (CALLBACK* _USBfreeze)(int mode, freezeData *data); +typedef void (CALLBACK* _USBconfigure)(); +typedef s32 (CALLBACK* _USBtest)(); +typedef void (CALLBACK* _USBabout)(); + +//FireWire +typedef s32 (CALLBACK* _FireWireinit)(); +typedef s32 (CALLBACK* _FireWireopen)(void *pDsp); +typedef void (CALLBACK* _FireWireclose)(); +typedef void (CALLBACK* _FireWireshutdown)(); +typedef u32 (CALLBACK* _FireWireread32)(u32 mem); +typedef void (CALLBACK* _FireWirewrite32)(u32 mem, u32 value); +typedef void (CALLBACK* _FireWireirqCallback)(void (*callback)()); + +typedef s32 (CALLBACK* _FireWirefreeze)(int mode, freezeData *data); +typedef void (CALLBACK* _FireWireconfigure)(); +typedef s32 (CALLBACK* _FireWiretest)(); +typedef void (CALLBACK* _FireWireabout)(); + +#endif + +#ifdef PLUGINfuncs + +// GS +_GSinit GSinit; +_GSopen GSopen; +_GSclose GSclose; +_GSshutdown GSshutdown; +_GSvsync GSvsync; +_GSwrite32 GSwrite32; +_GSwrite64 GSwrite64; +_GSread32 GSread32; +_GSread64 GSread64; +_GSgifTransfer1 GSgifTransfer1; +_GSgifTransfer2 GSgifTransfer2; +_GSgifTransfer3 GSgifTransfer3; +_GSreadFIFO GSreadFIFO; + +_GSkeyEvent GSkeyEvent; +_GSmakeSnapshot GSmakeSnapshot; +_GSirqCallback GSirqCallback; +_GSprintf GSprintf; +_GSgetDriverInfo GSgetDriverInfo; +#ifdef __WIN32__ +_GSsetWindowInfo GSsetWindowInfo; +#endif +_GSfreeze GSfreeze; +_GSconfigure GSconfigure; +_GStest GStest; +_GSabout GSabout; + +// PAD1 +_PADinit PAD1init; +_PADopen PAD1open; +_PADclose PAD1close; +_PADshutdown PAD1shutdown; +_PADkeyEvent PAD1keyEvent; +_PADstartPoll PAD1startPoll; +_PADpoll PAD1poll; +_PADquery PAD1query; + +_PADgsDriverInfo PAD1gsDriverInfo; +_PADconfigure PAD1configure; +_PADtest PAD1test; +_PADabout PAD1about; + +// PAD2 +_PADinit PAD2init; +_PADopen PAD2open; +_PADclose PAD2close; +_PADshutdown PAD2shutdown; +_PADkeyEvent PAD2keyEvent; +_PADstartPoll PAD2startPoll; +_PADpoll PAD2poll; +_PADquery PAD2query; + +_PADgsDriverInfo PAD2gsDriverInfo; +_PADconfigure PAD2configure; +_PADtest PAD2test; +_PADabout PAD2about; + +// SPU2 +_SPU2init SPU2init; +_SPU2open SPU2open; +_SPU2close SPU2close; +_SPU2shutdown SPU2shutdown; +_SPU2write SPU2write; +_SPU2read SPU2read; +_SPU2readDMA4Mem SPU2readDMA4Mem; +_SPU2writeDMA4Mem SPU2writeDMA4Mem; +_SPU2interruptDMA4 SPU2interruptDMA4; +_SPU2readDMA7Mem SPU2readDMA7Mem; +_SPU2writeDMA7Mem SPU2writeDMA7Mem; +_SPU2interruptDMA7 SPU2interruptDMA7; +_SPU2irqCallback SPU2irqCallback; + +_SPU2async SPU2async; +_SPU2freeze SPU2freeze; +_SPU2configure SPU2configure; +_SPU2test SPU2test; +_SPU2about SPU2about; + +// CDVD +_CDVDinit CDVDinit; +_CDVDopen CDVDopen; +_CDVDclose CDVDclose; +_CDVDshutdown CDVDshutdown; +_CDVDreadTrack CDVDreadTrack; +_CDVDgetBuffer CDVDgetBuffer; +_CDVDgetTN CDVDgetTN; +_CDVDgetTD CDVDgetTD; +_CDVDgetType CDVDgetType; +_CDVDgetTrayStatus CDVDgetTrayStatus; + +_CDVDconfigure CDVDconfigure; +_CDVDtest CDVDtest; +_CDVDabout CDVDabout; + +// DEV9 +_DEV9init DEV9init; +_DEV9open DEV9open; +_DEV9close DEV9close; +_DEV9shutdown DEV9shutdown; +_DEV9read8 DEV9read8; +_DEV9read16 DEV9read16; +_DEV9read32 DEV9read32; +_DEV9write8 DEV9write8; +_DEV9write16 DEV9write16; +_DEV9write32 DEV9write32; +_DEV9readDMA8Mem DEV9readDMA8Mem; +_DEV9writeDMA8Mem DEV9writeDMA8Mem; +_DEV9irqCallback DEV9irqCallback; +_DEV9irqHandler DEV9irqHandler; + +_DEV9configure DEV9configure; +_DEV9freeze DEV9freeze; +_DEV9test DEV9test; +_DEV9about DEV9about; + +// USB +_USBinit USBinit; +_USBopen USBopen; +_USBclose USBclose; +_USBshutdown USBshutdown; +_USBread8 USBread8; +_USBread16 USBread16; +_USBread32 USBread32; +_USBwrite8 USBwrite8; +_USBwrite16 USBwrite16; +_USBwrite32 USBwrite32; +_USBirqCallback USBirqCallback; +_USBirqHandler USBirqHandler; +_USBsetRAM USBsetRAM; + +_USBconfigure USBconfigure; +_USBfreeze USBfreeze; +_USBtest USBtest; +_USBabout USBabout; + +// FireWire +_FireWireinit FireWireinit; +_FireWireopen FireWireopen; +_FireWireclose FireWireclose; +_FireWireshutdown FireWireshutdown; +_FireWireread32 FireWireread32; +_FireWirewrite32 FireWirewrite32; +_FireWireirqCallback FireWireirqCallback; + +_FireWireconfigure FireWireconfigure; +_FireWirefreeze FireWirefreeze; +_FireWiretest FireWiretest; +_FireWireabout FireWireabout; +#endif + +#endif /* __PS2EDEFS_H__ */ diff --git a/plugins/dev9ghzdrk/PS2Etypes.h b/plugins/dev9ghzdrk/PS2Etypes.h new file mode 100644 index 0000000000..f7a2fffdaa --- /dev/null +++ b/plugins/dev9ghzdrk/PS2Etypes.h @@ -0,0 +1,31 @@ +#ifndef __PS2ETYPES_H__ +#define __PS2ETYPES_H__ + +// Basic types +#if defined(__WIN32__) + +typedef __int8 s8; +typedef __int16 s16; +typedef __int32 s32; +typedef __int64 s64; + +typedef unsigned __int8 u8; +typedef unsigned __int16 u16; +typedef unsigned __int32 u32; +typedef unsigned __int64 u64; + +#elif defined(__LINUX__) + +typedef char s8; +typedef short s16; +typedef long s32; +typedef long long s64; + +typedef unsigned char u8; +typedef unsigned short u16; +typedef unsigned long u32; +typedef unsigned long long u64; + +#endif + +#endif /* __PS2ETYPES_H__ */ diff --git a/plugins/dev9ghzdrk/Win32/Config.cpp b/plugins/dev9ghzdrk/Win32/Config.cpp new file mode 100644 index 0000000000..4d9cb2e0ef --- /dev/null +++ b/plugins/dev9ghzdrk/Win32/Config.cpp @@ -0,0 +1,54 @@ + +#include + +#include +#include "..\DEV9.h" + +#define GetKeyV(name, var, s, t) \ + size = s; type = t; \ + RegQueryValueEx(myKey, name, 0, &type, (LPBYTE) var, &size); + +#define GetKeyVdw(name, var) \ + GetKeyV(name, var, 4, REG_DWORD); + +#define SetKeyV(name, var, s, t) \ + RegSetValueEx(myKey, name, 0, t, (LPBYTE) var, s); + +#define SetKeyVdw(name, var) \ + SetKeyV(name, var, 4, REG_DWORD); + +void SaveConf() { + HKEY myKey; + DWORD myDisp; + + RegCreateKeyEx(HKEY_CURRENT_USER, "Software\\PS2Eplugin\\DEV9\\DEV9linuz", 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &myKey, &myDisp); + SetKeyV("Eth", config.Eth, strlen(config.Eth), REG_SZ); + SetKeyV("Hdd", config.Hdd, strlen(config.Hdd), REG_SZ); + SetKeyVdw("HddSize", &config.HddSize); + SetKeyVdw("ethEnable", &config.ethEnable); + SetKeyVdw("hddEnable", &config.hddEnable); + + RegCloseKey(myKey); +} + +void LoadConf() { + HKEY myKey; + DWORD type, size; + + memset(&config, 0, sizeof(config)); + strcpy(config.Hdd, HDD_DEF); + config.HddSize=8*1024; + strcpy(config.Eth, ETH_DEF); + + if (RegOpenKeyEx(HKEY_CURRENT_USER, "Software\\PS2Eplugin\\DEV9\\DEV9linuz", 0, KEY_ALL_ACCESS, &myKey)!=ERROR_SUCCESS) { + SaveConf(); return; + } + GetKeyV("Eth", config.Eth, sizeof(config.Eth), REG_SZ); + GetKeyV("Hdd", config.Hdd, sizeof(config.Hdd), REG_SZ); + GetKeyVdw("HddSize", &config.HddSize); + GetKeyVdw("ethEnable", &config.ethEnable); + GetKeyVdw("hddEnable", &config.hddEnable); + + RegCloseKey(myKey); +} + diff --git a/plugins/dev9ghzdrk/Win32/Config.h b/plugins/dev9ghzdrk/Win32/Config.h new file mode 100644 index 0000000000..4e767be7d3 --- /dev/null +++ b/plugins/dev9ghzdrk/Win32/Config.h @@ -0,0 +1,2 @@ +void SaveConf(); +void LoadConf(); diff --git a/plugins/dev9ghzdrk/Win32/DEV9ghzdrk.def b/plugins/dev9ghzdrk/Win32/DEV9ghzdrk.def new file mode 100644 index 0000000000..22ac653bfa --- /dev/null +++ b/plugins/dev9ghzdrk/Win32/DEV9ghzdrk.def @@ -0,0 +1,28 @@ +; DEV9ghzdrk.def : Declares the module parameters for the DLL. + +EXPORTS + + ; Explicit exports can go here + + PS2EgetLibType @2 + PS2EgetLibName @3 + PS2EgetLibVersion2 @4 + DEV9init @5 + DEV9shutdown @6 + DEV9open @7 + DEV9close @8 + DEV9read8 @9 + DEV9read16 @10 + DEV9read32 @11 + DEV9write8 @12 + DEV9write16 @13 + DEV9write32 @14 + DEV9readDMA8Mem @15 + DEV9writeDMA8Mem @16 + DEV9configure @17 + DEV9test @18 + DEV9about @19 + DEV9irqCallback @20 + DEV9irqHandler @21 + + DEV9setSettingsDir \ No newline at end of file diff --git a/plugins/dev9ghzdrk/Win32/DEV9ghzdrk.rc b/plugins/dev9ghzdrk/Win32/DEV9ghzdrk.rc new file mode 100644 index 0000000000..2013fd27cf --- /dev/null +++ b/plugins/dev9ghzdrk/Win32/DEV9ghzdrk.rc @@ -0,0 +1,126 @@ +// Microsoft Visual C++ generated resource script. +// +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "afxres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// Spanish (Argentina) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ESS) +#ifdef _WIN32 +LANGUAGE LANG_SPANISH, SUBLANG_SPANISH_ARGENTINA +#pragma code_page(1252) +#endif //_WIN32 + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""afxres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Dialog +// + +IDD_CONFIG DIALOGEX 0, 0, 290, 170 +STYLE DS_SETFONT | DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "HDD Configure" +FONT 8, "MS Sans Serif", 0, 0, 0x0 +BEGIN + DEFPUSHBUTTON "OK",IDOK,115,150,50,14 + PUSHBUTTON "Cancel",IDCANCEL,233,150,50,14 + COMBOBOX IDC_BAYTYPE,60,10,223,47,CBS_DROPDOWNLIST | CBS_SORT | WS_DISABLED + LTEXT "DEV9 Type",IDC_STATIC,15,10,41,11,SS_CENTERIMAGE + LTEXT "Ethernet Device",IDC_STATIC,15,60,60,10,SS_CENTERIMAGE + COMBOBOX IDC_ETHDEV,83,60,193,82,CBS_DROPDOWNLIST | WS_VSCROLL | WS_TABSTOP + GROUPBOX "Ethernet",IDC_STATIC,7,30,276,50 + CONTROL "Enabled",IDC_ETHENABLED,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,15,45,42,10 + LTEXT "HDD File",IDC_STATIC,15,115,60,10,SS_CENTERIMAGE | WS_DISABLED + GROUPBOX "Hard Disk Drive (not yet properly implemented)",IDC_STATIC,7,90,276,50 + CONTROL "Enabled",IDC_HDDENABLED,"Button",BS_AUTOCHECKBOX | WS_DISABLED | WS_TABSTOP,15,100,42,10 + EDITTEXT IDC_HDDFILE,85,115,191,12,ES_AUTOHSCROLL | WS_DISABLED +END + +IDD_ABOUT DIALOGEX 0, 0, 177, 106 +STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "DEV9 About" +FONT 8, "MS Sans Serif", 0, 0, 0x1 +BEGIN + DEFPUSHBUTTON "OK",IDOK,65,85,50,14 + LTEXT "DEV9 Driver",IDC_NAME,59,7,42,8 + LTEXT "Original Authors:\n\tlinuzappz \n\tShadow ",IDC_STATIC,7,18,141,30 + LTEXT "Fixed and improved by:\n\tgigahez \n\tdrk||Raziel",IDC_STATIC,7,49,155,27 +END + + +///////////////////////////////////////////////////////////////////////////// +// +// DESIGNINFO +// + +#ifdef APSTUDIO_INVOKED +GUIDELINES DESIGNINFO +BEGIN + IDD_CONFIG, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 283 + TOPMARGIN, 7 + BOTTOMMARGIN, 164 + END + + IDD_ABOUT, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 170 + TOPMARGIN, 7 + BOTTOMMARGIN, 99 + END +END +#endif // APSTUDIO_INVOKED + +#endif // Spanish (Argentina) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED + diff --git a/plugins/dev9ghzdrk/Win32/DEV9ghzdrk.vcxproj b/plugins/dev9ghzdrk/Win32/DEV9ghzdrk.vcxproj new file mode 100644 index 0000000000..e9a5cb30c5 --- /dev/null +++ b/plugins/dev9ghzdrk/Win32/DEV9ghzdrk.vcxproj @@ -0,0 +1,136 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + + DEV9ghzdrk + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3} + DEV9ghzdrk + Win32Proj + + + + DynamicLibrary + MultiByte + true + + + DynamicLibrary + MultiByte + + + + + + + + + + + + + + + + + + + + + <_ProjectFileVersion>10.0.30319.1 + AllRules.ruleset + + + AllRules.ruleset + + + + + + Disabled + EnableFastChecks + MultiThreadedDebug + + + $(SvnRootDir)\common\include;$(SvnRootDir)\3rdparty\winpcap\include;%(AdditionalIncludeDirectories) + + + NDEBUG;%(PreprocessorDefinitions) + 0x0408 + + + $(OutDir)$(TargetName)$(TargetExt) + .\DEV9ghzdrk.def + false + + + MachineX86 + ws2_32.lib;iphlpapi.lib;wpcap.lib;packet.lib;%(AdditionalDependencies) + $(SolutionDir)3rdparty\winpcap\lib;%(AdditionalLibraryDirectories) + + + + + + + $(SvnRootDir)\common\include;$(SvnRootDir)\3rdparty\winpcap\include;%(AdditionalIncludeDirectories) + + + NDEBUG;%(PreprocessorDefinitions) + 0x0408 + + + DEV9ghzdrk.def + false + + + MachineX86 + $(SolutionDir)3rdparty\winpcap\lib;%(AdditionalLibraryDirectories) + ws2_32.lib;iphlpapi.lib;wpcap.lib;packet.lib;%(AdditionalDependencies) + + + + + + + + + + + + + true + true + + + true + true + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/plugins/dev9ghzdrk/Win32/DEV9ghzdrk.vcxproj.filters b/plugins/dev9ghzdrk/Win32/DEV9ghzdrk.vcxproj.filters new file mode 100644 index 0000000000..3a59b7752d --- /dev/null +++ b/plugins/dev9ghzdrk/Win32/DEV9ghzdrk.vcxproj.filters @@ -0,0 +1,97 @@ + + + + + {c269b350-967d-41e2-9e0e-e454d5bc53c4} + cpp;c;cxx;rc;def;r;odl;idl;hpj;bat + + + {c19bd699-ac94-4cd8-bb19-c8c47a0a4608} + + + {02c8fe11-fda9-4bc5-80c0-399198b16979} + + + {1c0eef21-bc05-4eaa-9984-27d43ea85743} + + + {8768cdfe-28b8-4cc5-a92e-c4f3f77d7660} + + + {63c91c1b-ddb1-49de-b9e1-198780595d23} + + + {068d3325-67a3-42e1-9091-91d5b4228dea} + h;hpp;hxx;hm;inl + + + {30994d8f-3093-437c-8bb0-5d22f02f59ef} + ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe + + + + + Source Files + + + Source Files + + + Source Files\smap + + + Source Files\ethernet i/o + + + Source Files\ethernet i/o\tap + + + Source Files\ethernet i/o\sock + + + Source Files\ethernet i/o\sock + + + Source Files + + + Source Files + + + Source Files\ethernet i/o\pcap + + + + + Source Files + + + Source Files\smap + + + Source Files\ethernet i/o + + + Source Files\ethernet i/o\pcap + + + Source Files\ethernet i/o\tap + + + Header Files + + + Header Files + + + + + Resource Files + + + + + Resource Files + + + \ No newline at end of file diff --git a/plugins/dev9ghzdrk/Win32/DEV9ghzdrk_vs11.vcxproj b/plugins/dev9ghzdrk/Win32/DEV9ghzdrk_vs11.vcxproj new file mode 100644 index 0000000000..21241ad5d2 --- /dev/null +++ b/plugins/dev9ghzdrk/Win32/DEV9ghzdrk_vs11.vcxproj @@ -0,0 +1,138 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + + DEV9ghzdrk + {BBE4E5FB-530A-4D18-A633-35AF0577B7F3} + DEV9ghzdrk + Win32Proj + + + + DynamicLibrary + MultiByte + true + v110 + + + DynamicLibrary + MultiByte + v110 + + + + + + + + + + + + + + + + + + + + + <_ProjectFileVersion>10.0.30319.1 + AllRules.ruleset + + + AllRules.ruleset + + + + + + Disabled + EnableFastChecks + MultiThreadedDebug + + + $(SvnRootDir)\common\include;$(SvnRootDir)\3rdparty\winpcap\include;%(AdditionalIncludeDirectories) + + + NDEBUG;%(PreprocessorDefinitions) + 0x0408 + + + $(OutDir)$(TargetName)$(TargetExt) + .\DEV9ghzdrk.def + false + + + MachineX86 + ws2_32.lib;iphlpapi.lib;wpcap.lib;packet.lib;%(AdditionalDependencies) + $(SolutionDir)3rdparty\winpcap\lib;%(AdditionalLibraryDirectories) + + + + + + + $(SvnRootDir)\common\include;$(SvnRootDir)\3rdparty\winpcap\include;%(AdditionalIncludeDirectories) + + + NDEBUG;%(PreprocessorDefinitions) + 0x0408 + + + DEV9ghzdrk.def + false + + + MachineX86 + $(SolutionDir)3rdparty\winpcap\lib;%(AdditionalLibraryDirectories) + ws2_32.lib;iphlpapi.lib;wpcap.lib;packet.lib;%(AdditionalDependencies) + + + + + + + + + + + + + true + true + + + true + true + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/plugins/dev9ghzdrk/Win32/Devioctl.h b/plugins/dev9ghzdrk/Win32/Devioctl.h new file mode 100644 index 0000000000..661fda0297 --- /dev/null +++ b/plugins/dev9ghzdrk/Win32/Devioctl.h @@ -0,0 +1,90 @@ +/*++ BUILD Version: 0004 // Increment this if a change has global effects + Copyright (c) 1992-1993 Microsoft Corporation + Module Name: + devioctl.h + Revision History: + -- */ +// begin_winioctl +#ifndef _DEVIOCTL_ +#define _DEVIOCTL_ +// begin_ntddk begin_nthal begin_ntifs +// +// Define the various device type values. Note that values used by Microsoft +// Corporation are in the range 0-32767, and 32768-65535 are reserved for use +// by customers. +// +#define DEVICE_TYPE ULONG +#define FILE_DEVICE_BEEP 0x00000001 +#define FILE_DEVICE_CD_ROM 0x00000002 +#define FILE_DEVICE_CD_ROM_FILE_SYSTEM 0x00000003 +#define FILE_DEVICE_CONTROLLER 0x00000004 +#define FILE_DEVICE_DATALINK 0x00000005 +#define FILE_DEVICE_DFS 0x00000006 +#define FILE_DEVICE_DISK 0x00000007 +#define FILE_DEVICE_DISK_FILE_SYSTEM 0x00000008 +#define FILE_DEVICE_FILE_SYSTEM 0x00000009 +#define FILE_DEVICE_INPORT_PORT 0x0000000a +#define FILE_DEVICE_KEYBOARD 0x0000000b +#define FILE_DEVICE_MAILSLOT 0x0000000c +#define FILE_DEVICE_MIDI_IN 0x0000000d +#define FILE_DEVICE_MIDI_OUT 0x0000000e +#define FILE_DEVICE_MOUSE 0x0000000f +#define FILE_DEVICE_MULTI_UNC_PROVIDER 0x00000010 +#define FILE_DEVICE_NAMED_PIPE 0x00000011 +#define FILE_DEVICE_NETWORK 0x00000012 +#define FILE_DEVICE_NETWORK_BROWSER 0x00000013 +#define FILE_DEVICE_NETWORK_FILE_SYSTEM 0x00000014 +#define FILE_DEVICE_NULL 0x00000015 +#define FILE_DEVICE_PARALLEL_PORT 0x00000016 +#define FILE_DEVICE_PHYSICAL_NETCARD 0x00000017 +#define FILE_DEVICE_PRINTER 0x00000018 +#define FILE_DEVICE_SCANNER 0x00000019 +#define FILE_DEVICE_SERIAL_MOUSE_PORT 0x0000001a +#define FILE_DEVICE_SERIAL_PORT 0x0000001b +#define FILE_DEVICE_SCREEN 0x0000001c +#define FILE_DEVICE_SOUND 0x0000001d +#define FILE_DEVICE_STREAMS 0x0000001e +#define FILE_DEVICE_TAPE 0x0000001f +#define FILE_DEVICE_TAPE_FILE_SYSTEM 0x00000020 +#define FILE_DEVICE_TRANSPORT 0x00000021 +#define FILE_DEVICE_UNKNOWN 0x00000022 +#define FILE_DEVICE_VIDEO 0x00000023 +#define FILE_DEVICE_VIRTUAL_DISK 0x00000024 +#define FILE_DEVICE_WAVE_IN 0x00000025 +#define FILE_DEVICE_WAVE_OUT 0x00000026 +#define FILE_DEVICE_8042_PORT 0x00000027 +#define FILE_DEVICE_NETWORK_REDIRECTOR 0x00000028 +#define FILE_DEVICE_BATTERY 0x00000029 +#define FILE_DEVICE_BUS_EXTENDER 0x0000002a +#define FILE_DEVICE_MODEM 0x0000002b +#define FILE_DEVICE_VDM 0x0000002c +#define FILE_DEVICE_MASS_STORAGE 0x0000002d +// +// Macro definition for defining IOCTL and FSCTL function control codes. Note +// that function codes 0-2047 are reserved for Microsoft Corporation, and +// 2048-4095 are reserved for customers. +// +#define CTL_CODE( DeviceType, Function, Method, Access ) ( \ + ((DeviceType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method) \ +) +// +// Define the method codes for how buffers are passed for I/O and FS controls +// +#define METHOD_BUFFERED 0 +#define METHOD_IN_DIRECT 1 +#define METHOD_OUT_DIRECT 2 +#define METHOD_NEITHER 3 +// +// Define the access check value for any access +// +// +// The FILE_READ_ACCESS and FILE_WRITE_ACCESS constants are also defined in +// ntioapi.h as FILE_READ_DATA and FILE_WRITE_DATA. The values for these +// constants *MUST* always be in sync. +// +#define FILE_ANY_ACCESS 0 +#define FILE_READ_ACCESS ( 0x0001 ) // file & pipe +#define FILE_WRITE_ACCESS ( 0x0002 ) // file & pipe +// end_ntddk end_nthal end_ntifs +#endif // _DEVIOCTL_ +// end_winioctl diff --git a/plugins/dev9ghzdrk/Win32/ProjectRootDir.props b/plugins/dev9ghzdrk/Win32/ProjectRootDir.props new file mode 100644 index 0000000000..8d9f9ad374 --- /dev/null +++ b/plugins/dev9ghzdrk/Win32/ProjectRootDir.props @@ -0,0 +1,15 @@ + + + + $(ProjectRootDir)\..\.. + $(SvnRootDir)\common + + + <_ProjectFileVersion>10.0.30128.1 + + + + $(SvnRootDir) + + + \ No newline at end of file diff --git a/plugins/dev9ghzdrk/Win32/ProjectRootDir.vsprops b/plugins/dev9ghzdrk/Win32/ProjectRootDir.vsprops new file mode 100644 index 0000000000..b8400f4c9c --- /dev/null +++ b/plugins/dev9ghzdrk/Win32/ProjectRootDir.vsprops @@ -0,0 +1,11 @@ + + + + diff --git a/plugins/dev9ghzdrk/Win32/Win32.cpp b/plugins/dev9ghzdrk/Win32/Win32.cpp new file mode 100644 index 0000000000..3d65280e4e --- /dev/null +++ b/plugins/dev9ghzdrk/Win32/Win32.cpp @@ -0,0 +1,168 @@ +#include +#include +#include +#include + +#include "Config.h" +#include "resource.h" +#include "..\DEV9.h" +#include "pcap.h" +#include "pcap_io.h" +#include "net.h" +#include "tap.h" + +extern HINSTANCE hInst; +//HANDLE handleDEV9Thread = NULL; +//DWORD dwThreadId, dwThrdParam; + +void SysMessage(char *fmt, ...) { + va_list list; + char tmp[512]; + + va_start(list,fmt); + vsprintf(tmp,fmt,list); + va_end(list); + MessageBox(0, tmp, "Dev9linuz Msg", 0); +} + +void OnInitDialog(HWND hW) { + char *dev; + //int i; + + LoadConf(); + + ComboBox_AddString(GetDlgItem(hW, IDC_BAYTYPE), "Expansion"); + ComboBox_AddString(GetDlgItem(hW, IDC_BAYTYPE), "PC Card"); + for (int j=0;j<2;j++) + { + for (int i=0; i * al=GetTapAdapters(); + for (int i=0; isize(); i++) { + + int itm=ComboBox_AddString(GetDlgItem(hW, IDC_ETHDEV), al[0][i].name.c_str()); + ComboBox_SetItemData(GetDlgItem(hW, IDC_ETHDEV),itm,strdup( al[0][i].guid.c_str())); + if (strcmp(al[0][i].guid.c_str(), config.Eth) == 0) { + ComboBox_SetCurSel(GetDlgItem(hW, IDC_ETHDEV), itm); + } + } + + Edit_SetText(GetDlgItem(hW, IDC_HDDFILE), config.Hdd); + + Button_SetCheck(GetDlgItem(hW, IDC_ETHENABLED), config.ethEnable); + Button_SetCheck(GetDlgItem(hW, IDC_HDDENABLED), config.hddEnable); +} + +void OnOk(HWND hW) { + int i = ComboBox_GetCurSel(GetDlgItem(hW, IDC_ETHDEV)); + char* ptr=(char*)ComboBox_GetItemData(GetDlgItem(hW, IDC_ETHDEV),i); + strcpy(config.Eth, ptr); + Edit_GetText(GetDlgItem(hW, IDC_HDDFILE), config.Hdd, 256); + + config.ethEnable = Button_GetCheck(GetDlgItem(hW, IDC_ETHENABLED)); + config.hddEnable = Button_GetCheck(GetDlgItem(hW, IDC_HDDENABLED)); + + SaveConf(); + + EndDialog(hW, TRUE); +} + +BOOL CALLBACK ConfigureDlgProc(HWND hW, UINT uMsg, WPARAM wParam, LPARAM lParam) { + + switch(uMsg) { + case WM_INITDIALOG: + OnInitDialog(hW); + return TRUE; + + case WM_COMMAND: + switch(LOWORD(wParam)) { + case IDCANCEL: + EndDialog(hW, FALSE); + return TRUE; + case IDOK: + OnOk(hW); + return TRUE; + } + } + return FALSE; +} + +BOOL CALLBACK AboutDlgProc(HWND hW, UINT uMsg, WPARAM wParam, LPARAM lParam) { + switch(uMsg) { + case WM_INITDIALOG: + return TRUE; + + case WM_COMMAND: + switch(LOWORD(wParam)) { + case IDOK: + EndDialog(hW, FALSE); + return TRUE; + } + } + return FALSE; +} + +void CALLBACK DEV9configure() { + DialogBox(hInst, + MAKEINTRESOURCE(IDD_CONFIG), + GetActiveWindow(), + (DLGPROC)ConfigureDlgProc); + //SysMessage("Nothing to Configure"); +} + +void CALLBACK DEV9about() { + DialogBox(hInst, + MAKEINTRESOURCE(IDD_ABOUT), + GetActiveWindow(), + (DLGPROC)AboutDlgProc); +} + +BOOL APIENTRY DllMain(HANDLE hModule, // DLL INIT + DWORD dwReason, + LPVOID lpReserved) { + hInst = (HINSTANCE)hModule; + return TRUE; // very quick :) +} +/* +UINT DEV9ThreadProc() { + DEV9thread(); + + return 0; +}*/ +NetAdapter* GetNetAdapter() +{ + if(config.Eth[0]=='p') + { + return new PCAPAdapter(); + } + else if (config.Eth[0]=='t') + { + return new TAPAdapter(); + } + else + return 0; +} +s32 _DEV9open() +{ + //handleDEV9Thread = CreateThread (NULL, 0, (LPTHREAD_START_ROUTINE) DEV9ThreadProc, &dwThrdParam, CREATE_SUSPENDED, &dwThreadId); + //SetThreadPriority(handleDEV9Thread,THREAD_PRIORITY_HIGHEST); + //ResumeThread (handleDEV9Thread); + NetAdapter* na=GetNetAdapter(); + if (!na) + emu_printf("Failed to GetNetAdapter()\n"); + InitNet( na); + return 0; +} + +void _DEV9close() { + //TerminateThread(handleDEV9Thread,0); + //handleDEV9Thread = NULL; + TermNet(); +} diff --git a/plugins/dev9ghzdrk/Win32/_Ntddndis.h b/plugins/dev9ghzdrk/Win32/_Ntddndis.h new file mode 100644 index 0000000000..77a53d7af4 --- /dev/null +++ b/plugins/dev9ghzdrk/Win32/_Ntddndis.h @@ -0,0 +1,1400 @@ +/*++ BUILD Version: 0001 // Increment this if a change has global effects + Copyright (c) 1990-1993 Microsoft Corporation + Module Name: + ntddndis.h + Abstract: + This is the include file that defines all constants and types for + accessing the Network driver interface device. + Author: + Steve Wood (stevewo) 27-May-1990 + Revision History: + Adam Barr (adamba) 04-Nov-1992 added the correct values for NDIS 3.0. + Jameel Hyder (jameelh) 01-Aug-95 added Pnp IoCTLs and structures + Kyle Brandon (kyleb) 09/24/96 added general co ndis oids. + -- */ +#ifndef _NTDDNDIS_ +#define _NTDDNDIS_ +// +// Device Name - this string is the name of the device. It is the name +// that should be passed to NtOpenFile when accessing the device. +// +// Note: For devices that support multiple units, it should be suffixed +// with the Ascii representation of the unit number. +// +#define DD_NDIS_DEVICE_NAME "\\Device\\UNKNOWN" +// +// NtDeviceIoControlFile IoControlCode values for this device. +// +// Warning: Remember that the low two bits of the code specify how the +// buffers are passed to the driver! +// +#define _NDIS_CONTROL_CODE(request,method) \ + CTL_CODE(FILE_DEVICE_PHYSICAL_NETCARD, request, method, FILE_ANY_ACCESS) +#define IOCTL_NDIS_QUERY_GLOBAL_STATS _NDIS_CONTROL_CODE( 0, METHOD_OUT_DIRECT ) +#define IOCTL_NDIS_QUERY_ALL_STATS _NDIS_CONTROL_CODE( 1, METHOD_OUT_DIRECT ) +#define IOCTL_NDIS_ADD_DEVICE _NDIS_CONTROL_CODE( 2, METHOD_BUFFERED ) +#define IOCTL_NDIS_DELETE_DEVICE _NDIS_CONTROL_CODE( 3, METHOD_BUFFERED ) +#define IOCTL_NDIS_TRANSLATE_NAME _NDIS_CONTROL_CODE( 4, METHOD_BUFFERED ) +#define IOCTL_NDIS_ADD_TDI_DEVICE _NDIS_CONTROL_CODE( 5, METHOD_BUFFERED ) +#define IOCTL_NDIS_NOTIFY_PROTOCOL _NDIS_CONTROL_CODE( 6, METHOD_BUFFERED ) +#define IOCTL_NDIS_GET_LOG_DATA _NDIS_CONTROL_CODE( 7, METHOD_OUT_DIRECT ) +// +// NtDeviceIoControlFile InputBuffer/OutputBuffer record structures for +// this device. +// +// +// This is the type of an NDIS OID value. +// +typedef ULONG NDIS_OID, *PNDIS_OID; +// +// IOCTL_NDIS_QUERY_ALL_STATS returns a sequence of these, packed +// together (no padding is required since statistics all have +// four or eight bytes of data). +// +typedef struct _NDIS_STATISTICS_VALUE { + NDIS_OID Oid; + ULONG DataLength; + UCHAR Data[1]; // variable length + +} NDIS_STATISTICS_VALUE, *PNDIS_STATISTICS_VALUE; + +// +// Structure used by TRANSLATE_NAME IOCTL +// +typedef struct _NET_PNP_ID { + ULONG ClassId; + ULONG Token; +} NET_PNP_ID, *PNET_PNP_ID; + +typedef struct _NET_PNP_TRANSLATE_LIST { + ULONG BytesNeeded; + NET_PNP_ID IdArray[ANYSIZE_ARRAY]; +} NET_PNP_TRANSLATE_LIST, *PNET_PNP_TRANSLATE_LIST; + +// +// Structure used to define a self-contained variable data structure +// +typedef struct _NDIS_VAR_DATA_DESC { + USHORT Length; // # of octects of data + + USHORT MaximumLength; // # of octects available + + LONG Offset; // Offset of data relative to the descriptor + +} NDIS_VAR_DATA_DESC, *PNDIS_VAR_DATA_DESC; + +// +// Object Identifiers used by NdisRequest Query/Set Information +// +// +// General Objects +// +#define OID_GEN_SUPPORTED_LIST 0x00010101 +#define OID_GEN_HARDWARE_STATUS 0x00010102 +#define OID_GEN_MEDIA_SUPPORTED 0x00010103 +#define OID_GEN_MEDIA_IN_USE 0x00010104 +#define OID_GEN_MAXIMUM_LOOKAHEAD 0x00010105 +#define OID_GEN_MAXIMUM_FRAME_SIZE 0x00010106 +#define OID_GEN_LINK_SPEED 0x00010107 +#define OID_GEN_TRANSMIT_BUFFER_SPACE 0x00010108 +#define OID_GEN_RECEIVE_BUFFER_SPACE 0x00010109 +#define OID_GEN_TRANSMIT_BLOCK_SIZE 0x0001010A +#define OID_GEN_RECEIVE_BLOCK_SIZE 0x0001010B +#define OID_GEN_VENDOR_ID 0x0001010C +#define OID_GEN_VENDOR_DESCRIPTION 0x0001010D +#define OID_GEN_CURRENT_PACKET_FILTER 0x0001010E +#define OID_GEN_CURRENT_LOOKAHEAD 0x0001010F +#define OID_GEN_DRIVER_VERSION 0x00010110 +#define OID_GEN_MAXIMUM_TOTAL_SIZE 0x00010111 +#define OID_GEN_PROTOCOL_OPTIONS 0x00010112 +#define OID_GEN_MAC_OPTIONS 0x00010113 +#define OID_GEN_MEDIA_CONNECT_STATUS 0x00010114 +#define OID_GEN_MAXIMUM_SEND_PACKETS 0x00010115 +#define OID_GEN_VENDOR_DRIVER_VERSION 0x00010116 +#define OID_GEN_XMIT_OK 0x00020101 +#define OID_GEN_RCV_OK 0x00020102 +#define OID_GEN_XMIT_ERROR 0x00020103 +#define OID_GEN_RCV_ERROR 0x00020104 +#define OID_GEN_RCV_NO_BUFFER 0x00020105 +#define OID_GEN_DIRECTED_BYTES_XMIT 0x00020201 +#define OID_GEN_DIRECTED_FRAMES_XMIT 0x00020202 +#define OID_GEN_MULTICAST_BYTES_XMIT 0x00020203 +#define OID_GEN_MULTICAST_FRAMES_XMIT 0x00020204 +#define OID_GEN_BROADCAST_BYTES_XMIT 0x00020205 +#define OID_GEN_BROADCAST_FRAMES_XMIT 0x00020206 +#define OID_GEN_DIRECTED_BYTES_RCV 0x00020207 +#define OID_GEN_DIRECTED_FRAMES_RCV 0x00020208 +#define OID_GEN_MULTICAST_BYTES_RCV 0x00020209 +#define OID_GEN_MULTICAST_FRAMES_RCV 0x0002020A +#define OID_GEN_BROADCAST_BYTES_RCV 0x0002020B +#define OID_GEN_BROADCAST_FRAMES_RCV 0x0002020C +#define OID_GEN_RCV_CRC_ERROR 0x0002020D +#define OID_GEN_TRANSMIT_QUEUE_LENGTH 0x0002020E +#define OID_GEN_GET_TIME_CAPS 0x0002020F +#define OID_GEN_GET_NETCARD_TIME 0x00020210 +// +// These are connection-oriented general OIDs. +// These replace the above OIDs for connection-oriented media. +// +#define OID_GEN_CO_SUPPORTED_LIST 0x00010101 +#define OID_GEN_CO_HARDWARE_STATUS 0x00010102 +#define OID_GEN_CO_MEDIA_SUPPORTED 0x00010103 +#define OID_GEN_CO_MEDIA_IN_USE 0x00010104 +#define OID_GEN_CO_LINK_SPEED 0x00010105 +#define OID_GEN_CO_VENDOR_ID 0x00010106 +#define OID_GEN_CO_VENDOR_DESCRIPTION 0x00010107 +#define OID_GEN_CO_DRIVER_VERSION 0x00010108 +#define OID_GEN_CO_PROTOCOL_OPTIONS 0x00010109 +#define OID_GEN_CO_MAC_OPTIONS 0x0001010A +#define OID_GEN_CO_MEDIA_CONNECT_STATUS 0x0001010B +#define OID_GEN_CO_VENDOR_DRIVER_VERSION 0x0001010C +#define OID_GEN_CO_MINIMUM_LINK_SPEED 0x0001010D +#define OID_GEN_CO_GET_TIME_CAPS 0x00010201 +#define OID_GEN_CO_GET_NETCARD_TIME 0x00010202 +// +// These are connection-oriented statistics OIDs. +// +#define OID_GEN_CO_XMIT_PDUS_OK 0x00020101 +#define OID_GEN_CO_RCV_PDUS_OK 0x00020102 +#define OID_GEN_CO_XMIT_PDUS_ERROR 0x00020103 +#define OID_GEN_CO_RCV_PDUS_ERROR 0x00020104 +#define OID_GEN_CO_RCV_PDUS_NO_BUFFER 0x00020105 +#define OID_GEN_CO_RCV_CRC_ERROR 0x00020201 +#define OID_GEN_CO_TRANSMIT_QUEUE_LENGTH 0x00020202 +#define OID_GEN_CO_BYTES_XMIT 0x00020203 +#define OID_GEN_CO_BYTES_RCV 0x00020204 +#define OID_GEN_CO_BYTES_XMIT_OUTSTANDING 0x00020205 +#define OID_GEN_CO_NETCARD_LOAD 0x00020206 +// +// These are objects for Connection-oriented media call-managers and are not +// valid for ndis drivers. Under construction. +// +#define OID_CO_ADD_PVC 0xFF000001 +#define OID_CO_DELETE_PVC 0xFF000002 +#define OID_CO_GET_CALL_INFORMATION 0xFF000003 +#define OID_CO_ADD_ADDRESS 0xFF000004 +#define OID_CO_DELETE_ADDRESS 0xFF000005 +#define OID_CO_GET_ADDRESSES 0xFF000006 +#define OID_CO_ADDRESS_CHANGE 0xFF000007 +#define OID_CO_SIGNALING_ENABLED 0xFF000008 +#define OID_CO_SIGNALING_DISABLED 0xFF000009 +// +// 802.3 Objects (Ethernet) +// +#define OID_802_3_PERMANENT_ADDRESS 0x01010101 +#define OID_802_3_CURRENT_ADDRESS 0x01010102 +#define OID_802_3_MULTICAST_LIST 0x01010103 +#define OID_802_3_MAXIMUM_LIST_SIZE 0x01010104 +#define OID_802_3_MAC_OPTIONS 0x01010105 +// +// +#define NDIS_802_3_MAC_OPTION_PRIORITY 0x00000001 +#define OID_802_3_RCV_ERROR_ALIGNMENT 0x01020101 +#define OID_802_3_XMIT_ONE_COLLISION 0x01020102 +#define OID_802_3_XMIT_MORE_COLLISIONS 0x01020103 +#define OID_802_3_XMIT_DEFERRED 0x01020201 +#define OID_802_3_XMIT_MAX_COLLISIONS 0x01020202 +#define OID_802_3_RCV_OVERRUN 0x01020203 +#define OID_802_3_XMIT_UNDERRUN 0x01020204 +#define OID_802_3_XMIT_HEARTBEAT_FAILURE 0x01020205 +#define OID_802_3_XMIT_TIMES_CRS_LOST 0x01020206 +#define OID_802_3_XMIT_LATE_COLLISIONS 0x01020207 +// +// 802.5 Objects (Token-Ring) +// +#define OID_802_5_PERMANENT_ADDRESS 0x02010101 +#define OID_802_5_CURRENT_ADDRESS 0x02010102 +#define OID_802_5_CURRENT_FUNCTIONAL 0x02010103 +#define OID_802_5_CURRENT_GROUP 0x02010104 +#define OID_802_5_LAST_OPEN_STATUS 0x02010105 +#define OID_802_5_CURRENT_RING_STATUS 0x02010106 +#define OID_802_5_CURRENT_RING_STATE 0x02010107 +#define OID_802_5_LINE_ERRORS 0x02020101 +#define OID_802_5_LOST_FRAMES 0x02020102 +#define OID_802_5_BURST_ERRORS 0x02020201 +#define OID_802_5_AC_ERRORS 0x02020202 +#define OID_802_5_ABORT_DELIMETERS 0x02020203 +#define OID_802_5_FRAME_COPIED_ERRORS 0x02020204 +#define OID_802_5_FREQUENCY_ERRORS 0x02020205 +#define OID_802_5_TOKEN_ERRORS 0x02020206 +#define OID_802_5_INTERNAL_ERRORS 0x02020207 +// +// FDDI Objects +// +#define OID_FDDI_LONG_PERMANENT_ADDR 0x03010101 +#define OID_FDDI_LONG_CURRENT_ADDR 0x03010102 +#define OID_FDDI_LONG_MULTICAST_LIST 0x03010103 +#define OID_FDDI_LONG_MAX_LIST_SIZE 0x03010104 +#define OID_FDDI_SHORT_PERMANENT_ADDR 0x03010105 +#define OID_FDDI_SHORT_CURRENT_ADDR 0x03010106 +#define OID_FDDI_SHORT_MULTICAST_LIST 0x03010107 +#define OID_FDDI_SHORT_MAX_LIST_SIZE 0x03010108 +#define OID_FDDI_ATTACHMENT_TYPE 0x03020101 +#define OID_FDDI_UPSTREAM_NODE_LONG 0x03020102 +#define OID_FDDI_DOWNSTREAM_NODE_LONG 0x03020103 +#define OID_FDDI_FRAME_ERRORS 0x03020104 +#define OID_FDDI_FRAMES_LOST 0x03020105 +#define OID_FDDI_RING_MGT_STATE 0x03020106 +#define OID_FDDI_LCT_FAILURES 0x03020107 +#define OID_FDDI_LEM_REJECTS 0x03020108 +#define OID_FDDI_LCONNECTION_STATE 0x03020109 +#define OID_FDDI_SMT_STATION_ID 0x03030201 +#define OID_FDDI_SMT_OP_VERSION_ID 0x03030202 +#define OID_FDDI_SMT_HI_VERSION_ID 0x03030203 +#define OID_FDDI_SMT_LO_VERSION_ID 0x03030204 +#define OID_FDDI_SMT_MANUFACTURER_DATA 0x03030205 +#define OID_FDDI_SMT_USER_DATA 0x03030206 +#define OID_FDDI_SMT_MIB_VERSION_ID 0x03030207 +#define OID_FDDI_SMT_MAC_CT 0x03030208 +#define OID_FDDI_SMT_NON_MASTER_CT 0x03030209 +#define OID_FDDI_SMT_MASTER_CT 0x0303020A +#define OID_FDDI_SMT_AVAILABLE_PATHS 0x0303020B +#define OID_FDDI_SMT_CONFIG_CAPABILITIES 0x0303020C +#define OID_FDDI_SMT_CONFIG_POLICY 0x0303020D +#define OID_FDDI_SMT_CONNECTION_POLICY 0x0303020E +#define OID_FDDI_SMT_T_NOTIFY 0x0303020F +#define OID_FDDI_SMT_STAT_RPT_POLICY 0x03030210 +#define OID_FDDI_SMT_TRACE_MAX_EXPIRATION 0x03030211 +#define OID_FDDI_SMT_PORT_INDEXES 0x03030212 +#define OID_FDDI_SMT_MAC_INDEXES 0x03030213 +#define OID_FDDI_SMT_BYPASS_PRESENT 0x03030214 +#define OID_FDDI_SMT_ECM_STATE 0x03030215 +#define OID_FDDI_SMT_CF_STATE 0x03030216 +#define OID_FDDI_SMT_HOLD_STATE 0x03030217 +#define OID_FDDI_SMT_REMOTE_DISCONNECT_FLAG 0x03030218 +#define OID_FDDI_SMT_STATION_STATUS 0x03030219 +#define OID_FDDI_SMT_PEER_WRAP_FLAG 0x0303021A +#define OID_FDDI_SMT_MSG_TIME_STAMP 0x0303021B +#define OID_FDDI_SMT_TRANSITION_TIME_STAMP 0x0303021C +#define OID_FDDI_SMT_SET_COUNT 0x0303021D +#define OID_FDDI_SMT_LAST_SET_STATION_ID 0x0303021E +#define OID_FDDI_MAC_FRAME_STATUS_FUNCTIONS 0x0303021F +#define OID_FDDI_MAC_BRIDGE_FUNCTIONS 0x03030220 +#define OID_FDDI_MAC_T_MAX_CAPABILITY 0x03030221 +#define OID_FDDI_MAC_TVX_CAPABILITY 0x03030222 +#define OID_FDDI_MAC_AVAILABLE_PATHS 0x03030223 +#define OID_FDDI_MAC_CURRENT_PATH 0x03030224 +#define OID_FDDI_MAC_UPSTREAM_NBR 0x03030225 +#define OID_FDDI_MAC_DOWNSTREAM_NBR 0x03030226 +#define OID_FDDI_MAC_OLD_UPSTREAM_NBR 0x03030227 +#define OID_FDDI_MAC_OLD_DOWNSTREAM_NBR 0x03030228 +#define OID_FDDI_MAC_DUP_ADDRESS_TEST 0x03030229 +#define OID_FDDI_MAC_REQUESTED_PATHS 0x0303022A +#define OID_FDDI_MAC_DOWNSTREAM_PORT_TYPE 0x0303022B +#define OID_FDDI_MAC_INDEX 0x0303022C +#define OID_FDDI_MAC_SMT_ADDRESS 0x0303022D +#define OID_FDDI_MAC_LONG_GRP_ADDRESS 0x0303022E +#define OID_FDDI_MAC_SHORT_GRP_ADDRESS 0x0303022F +#define OID_FDDI_MAC_T_REQ 0x03030230 +#define OID_FDDI_MAC_T_NEG 0x03030231 +#define OID_FDDI_MAC_T_MAX 0x03030232 +#define OID_FDDI_MAC_TVX_VALUE 0x03030233 +#define OID_FDDI_MAC_T_PRI0 0x03030234 +#define OID_FDDI_MAC_T_PRI1 0x03030235 +#define OID_FDDI_MAC_T_PRI2 0x03030236 +#define OID_FDDI_MAC_T_PRI3 0x03030237 +#define OID_FDDI_MAC_T_PRI4 0x03030238 +#define OID_FDDI_MAC_T_PRI5 0x03030239 +#define OID_FDDI_MAC_T_PRI6 0x0303023A +#define OID_FDDI_MAC_FRAME_CT 0x0303023B +#define OID_FDDI_MAC_COPIED_CT 0x0303023C +#define OID_FDDI_MAC_TRANSMIT_CT 0x0303023D +#define OID_FDDI_MAC_TOKEN_CT 0x0303023E +#define OID_FDDI_MAC_ERROR_CT 0x0303023F +#define OID_FDDI_MAC_LOST_CT 0x03030240 +#define OID_FDDI_MAC_TVX_EXPIRED_CT 0x03030241 +#define OID_FDDI_MAC_NOT_COPIED_CT 0x03030242 +#define OID_FDDI_MAC_LATE_CT 0x03030243 +#define OID_FDDI_MAC_RING_OP_CT 0x03030244 +#define OID_FDDI_MAC_FRAME_ERROR_THRESHOLD 0x03030245 +#define OID_FDDI_MAC_FRAME_ERROR_RATIO 0x03030246 +#define OID_FDDI_MAC_NOT_COPIED_THRESHOLD 0x03030247 +#define OID_FDDI_MAC_NOT_COPIED_RATIO 0x03030248 +#define OID_FDDI_MAC_RMT_STATE 0x03030249 +#define OID_FDDI_MAC_DA_FLAG 0x0303024A +#define OID_FDDI_MAC_UNDA_FLAG 0x0303024B +#define OID_FDDI_MAC_FRAME_ERROR_FLAG 0x0303024C +#define OID_FDDI_MAC_NOT_COPIED_FLAG 0x0303024D +#define OID_FDDI_MAC_MA_UNITDATA_AVAILABLE 0x0303024E +#define OID_FDDI_MAC_HARDWARE_PRESENT 0x0303024F +#define OID_FDDI_MAC_MA_UNITDATA_ENABLE 0x03030250 +#define OID_FDDI_PATH_INDEX 0x03030251 +#define OID_FDDI_PATH_RING_LATENCY 0x03030252 +#define OID_FDDI_PATH_TRACE_STATUS 0x03030253 +#define OID_FDDI_PATH_SBA_PAYLOAD 0x03030254 +#define OID_FDDI_PATH_SBA_OVERHEAD 0x03030255 +#define OID_FDDI_PATH_CONFIGURATION 0x03030256 +#define OID_FDDI_PATH_T_R_MODE 0x03030257 +#define OID_FDDI_PATH_SBA_AVAILABLE 0x03030258 +#define OID_FDDI_PATH_TVX_LOWER_BOUND 0x03030259 +#define OID_FDDI_PATH_T_MAX_LOWER_BOUND 0x0303025A +#define OID_FDDI_PATH_MAX_T_REQ 0x0303025B +#define OID_FDDI_PORT_MY_TYPE 0x0303025C +#define OID_FDDI_PORT_NEIGHBOR_TYPE 0x0303025D +#define OID_FDDI_PORT_CONNECTION_POLICIES 0x0303025E +#define OID_FDDI_PORT_MAC_INDICATED 0x0303025F +#define OID_FDDI_PORT_CURRENT_PATH 0x03030260 +#define OID_FDDI_PORT_REQUESTED_PATHS 0x03030261 +#define OID_FDDI_PORT_MAC_PLACEMENT 0x03030262 +#define OID_FDDI_PORT_AVAILABLE_PATHS 0x03030263 +#define OID_FDDI_PORT_MAC_LOOP_TIME 0x03030264 +#define OID_FDDI_PORT_PMD_CLASS 0x03030265 +#define OID_FDDI_PORT_CONNECTION_CAPABILITIES 0x03030266 +#define OID_FDDI_PORT_INDEX 0x03030267 +#define OID_FDDI_PORT_MAINT_LS 0x03030268 +#define OID_FDDI_PORT_BS_FLAG 0x03030269 +#define OID_FDDI_PORT_PC_LS 0x0303026A +#define OID_FDDI_PORT_EB_ERROR_CT 0x0303026B +#define OID_FDDI_PORT_LCT_FAIL_CT 0x0303026C +#define OID_FDDI_PORT_LER_ESTIMATE 0x0303026D +#define OID_FDDI_PORT_LEM_REJECT_CT 0x0303026E +#define OID_FDDI_PORT_LEM_CT 0x0303026F +#define OID_FDDI_PORT_LER_CUTOFF 0x03030270 +#define OID_FDDI_PORT_LER_ALARM 0x03030271 +#define OID_FDDI_PORT_CONNNECT_STATE 0x03030272 +#define OID_FDDI_PORT_PCM_STATE 0x03030273 +#define OID_FDDI_PORT_PC_WITHHOLD 0x03030274 +#define OID_FDDI_PORT_LER_FLAG 0x03030275 +#define OID_FDDI_PORT_HARDWARE_PRESENT 0x03030276 +#define OID_FDDI_SMT_STATION_ACTION 0x03030277 +#define OID_FDDI_PORT_ACTION 0x03030278 +#define OID_FDDI_IF_DESCR 0x03030279 +#define OID_FDDI_IF_TYPE 0x0303027A +#define OID_FDDI_IF_MTU 0x0303027B +#define OID_FDDI_IF_SPEED 0x0303027C +#define OID_FDDI_IF_PHYS_ADDRESS 0x0303027D +#define OID_FDDI_IF_ADMIN_STATUS 0x0303027E +#define OID_FDDI_IF_OPER_STATUS 0x0303027F +#define OID_FDDI_IF_LAST_CHANGE 0x03030280 +#define OID_FDDI_IF_IN_OCTETS 0x03030281 +#define OID_FDDI_IF_IN_UCAST_PKTS 0x03030282 +#define OID_FDDI_IF_IN_NUCAST_PKTS 0x03030283 +#define OID_FDDI_IF_IN_DISCARDS 0x03030284 +#define OID_FDDI_IF_IN_ERRORS 0x03030285 +#define OID_FDDI_IF_IN_UNKNOWN_PROTOS 0x03030286 +#define OID_FDDI_IF_OUT_OCTETS 0x03030287 +#define OID_FDDI_IF_OUT_UCAST_PKTS 0x03030288 +#define OID_FDDI_IF_OUT_NUCAST_PKTS 0x03030289 +#define OID_FDDI_IF_OUT_DISCARDS 0x0303028A +#define OID_FDDI_IF_OUT_ERRORS 0x0303028B +#define OID_FDDI_IF_OUT_QLEN 0x0303028C +#define OID_FDDI_IF_SPECIFIC 0x0303028D +// +// WAN objects +// +#define OID_WAN_PERMANENT_ADDRESS 0x04010101 +#define OID_WAN_CURRENT_ADDRESS 0x04010102 +#define OID_WAN_QUALITY_OF_SERVICE 0x04010103 +#define OID_WAN_PROTOCOL_TYPE 0x04010104 +#define OID_WAN_MEDIUM_SUBTYPE 0x04010105 +#define OID_WAN_HEADER_FORMAT 0x04010106 +#define OID_WAN_GET_INFO 0x04010107 +#define OID_WAN_SET_LINK_INFO 0x04010108 +#define OID_WAN_GET_LINK_INFO 0x04010109 +#define OID_WAN_LINE_COUNT 0x0401010A +#define OID_WAN_GET_BRIDGE_INFO 0x0401020A +#define OID_WAN_SET_BRIDGE_INFO 0x0401020B +#define OID_WAN_GET_COMP_INFO 0x0401020C +#define OID_WAN_SET_COMP_INFO 0x0401020D +#define OID_WAN_GET_STATS_INFO 0x0401020E +// +// LocalTalk objects +// +#define OID_LTALK_CURRENT_NODE_ID 0x05010102 +#define OID_LTALK_IN_BROADCASTS 0x05020101 +#define OID_LTALK_IN_LENGTH_ERRORS 0x05020102 +#define OID_LTALK_OUT_NO_HANDLERS 0x05020201 +#define OID_LTALK_COLLISIONS 0x05020202 +#define OID_LTALK_DEFERS 0x05020203 +#define OID_LTALK_NO_DATA_ERRORS 0x05020204 +#define OID_LTALK_RANDOM_CTS_ERRORS 0x05020205 +#define OID_LTALK_FCS_ERRORS 0x05020206 +// +// Arcnet objects +// +#define OID_ARCNET_PERMANENT_ADDRESS 0x06010101 +#define OID_ARCNET_CURRENT_ADDRESS 0x06010102 +#define OID_ARCNET_RECONFIGURATIONS 0x06020201 +// +// TAPI objects +// +#define OID_TAPI_ACCEPT 0x07030101 +#define OID_TAPI_ANSWER 0x07030102 +#define OID_TAPI_CLOSE 0x07030103 +#define OID_TAPI_CLOSE_CALL 0x07030104 +#define OID_TAPI_CONDITIONAL_MEDIA_DETECTION 0x07030105 +#define OID_TAPI_CONFIG_DIALOG 0x07030106 +#define OID_TAPI_DEV_SPECIFIC 0x07030107 +#define OID_TAPI_DIAL 0x07030108 +#define OID_TAPI_DROP 0x07030109 +#define OID_TAPI_GET_ADDRESS_CAPS 0x0703010A +#define OID_TAPI_GET_ADDRESS_ID 0x0703010B +#define OID_TAPI_GET_ADDRESS_STATUS 0x0703010C +#define OID_TAPI_GET_CALL_ADDRESS_ID 0x0703010D +#define OID_TAPI_GET_CALL_INFO 0x0703010E +#define OID_TAPI_GET_CALL_STATUS 0x0703010F +#define OID_TAPI_GET_DEV_CAPS 0x07030110 +#define OID_TAPI_GET_DEV_CONFIG 0x07030111 +#define OID_TAPI_GET_EXTENSION_ID 0x07030112 +#define OID_TAPI_GET_ID 0x07030113 +#define OID_TAPI_GET_LINE_DEV_STATUS 0x07030114 +#define OID_TAPI_MAKE_CALL 0x07030115 +#define OID_TAPI_NEGOTIATE_EXT_VERSION 0x07030116 +#define OID_TAPI_OPEN 0x07030117 +#define OID_TAPI_PROVIDER_INITIALIZE 0x07030118 +#define OID_TAPI_PROVIDER_SHUTDOWN 0x07030119 +#define OID_TAPI_SECURE_CALL 0x0703011A +#define OID_TAPI_SELECT_EXT_VERSION 0x0703011B +#define OID_TAPI_SEND_USER_USER_INFO 0x0703011C +#define OID_TAPI_SET_APP_SPECIFIC 0x0703011D +#define OID_TAPI_SET_CALL_PARAMS 0x0703011E +#define OID_TAPI_SET_DEFAULT_MEDIA_DETECTION 0x0703011F +#define OID_TAPI_SET_DEV_CONFIG 0x07030120 +#define OID_TAPI_SET_MEDIA_MODE 0x07030121 +#define OID_TAPI_SET_STATUS_MESSAGES 0x07030122 +// +// ATM Connection Oriented Ndis +// +#define OID_ATM_SUPPORTED_VC_RATES 0x08010101 +#define OID_ATM_SUPPORTED_SERVICE_CATEGORY 0x08010102 +#define OID_ATM_SUPPORTED_AAL_TYPES 0x08010103 +#define OID_ATM_HW_CURRENT_ADDRESS 0x08010104 +#define OID_ATM_MAX_ACTIVE_VCS 0x08010105 +#define OID_ATM_MAX_ACTIVE_VCI_BITS 0x08010106 +#define OID_ATM_MAX_ACTIVE_VPI_BITS 0x08010107 +#define OID_ATM_MAX_AAL0_PACKET_SIZE 0x08010108 +#define OID_ATM_MAX_AAL1_PACKET_SIZE 0x08010109 +#define OID_ATM_MAX_AAL34_PACKET_SIZE 0x0801010A +#define OID_ATM_MAX_AAL5_PACKET_SIZE 0x0801010B +#define OID_ATM_SIGNALING_VPIVCI 0x08010201 +#define OID_ATM_ASSIGNED_VPI 0x08010202 +#define OID_ATM_ACQUIRE_ACCESS_NET_RESOURCES 0x08010203 +#define OID_ATM_RELEASE_ACCESS_NET_RESOURCES 0x08010204 +#define OID_ATM_ILMI_VPIVCI 0x08010205 +#define OID_ATM_DIGITAL_BROADCAST_VPIVCI 0x08010206 +#define OID_ATM_GET_NEAREST_FLOW 0x08010207 +#define OID_ATM_ALIGNMENT_REQUIRED 0x08010208 +// +// ATM specific statistics OIDs. +// +#define OID_ATM_RCV_CELLS_OK 0x08020101 +#define OID_ATM_XMIT_CELLS_OK 0x08020102 +#define OID_ATM_RCV_CELLS_DROPPED 0x08020103 +#define OID_ATM_RCV_INVALID_VPI_VCI 0x08020201 +#define OID_ATM_CELLS_HEC_ERROR 0x08020202 +#define OID_ATM_RCV_REASSEMBLY_ERROR 0x08020203 +// +// PCCA (Wireless) object +// +// +// All WirelessWAN devices must support the following OIDs +// +#define OID_WW_GEN_NETWORK_TYPES_SUPPORTED 0x09010101 +#define OID_WW_GEN_NETWORK_TYPE_IN_USE 0x09010102 +#define OID_WW_GEN_HEADER_FORMATS_SUPPORTED 0x09010103 +#define OID_WW_GEN_HEADER_FORMAT_IN_USE 0x09010104 +#define OID_WW_GEN_INDICATION_REQUEST 0x09010105 +#define OID_WW_GEN_DEVICE_INFO 0x09010106 +#define OID_WW_GEN_OPERATION_MODE 0x09010107 +#define OID_WW_GEN_LOCK_STATUS 0x09010108 +#define OID_WW_GEN_DISABLE_TRANSMITTER 0x09010109 +#define OID_WW_GEN_NETWORK_ID 0x0901010A +#define OID_WW_GEN_PERMANENT_ADDRESS 0x0901010B +#define OID_WW_GEN_CURRENT_ADDRESS 0x0901010C +#define OID_WW_GEN_SUSPEND_DRIVER 0x0901010D +#define OID_WW_GEN_BASESTATION_ID 0x0901010E +#define OID_WW_GEN_CHANNEL_ID 0x0901010F +#define OID_WW_GEN_ENCRYPTION_SUPPORTED 0x09010110 +#define OID_WW_GEN_ENCRYPTION_IN_USE 0x09010111 +#define OID_WW_GEN_ENCRYPTION_STATE 0x09010112 +#define OID_WW_GEN_CHANNEL_QUALITY 0x09010113 +#define OID_WW_GEN_REGISTRATION_STATUS 0x09010114 +#define OID_WW_GEN_RADIO_LINK_SPEED 0x09010115 +#define OID_WW_GEN_LATENCY 0x09010116 +#define OID_WW_GEN_BATTERY_LEVEL 0x09010117 +#define OID_WW_GEN_EXTERNAL_POWER 0x09010118 +// +// Network Dependent OIDs - Mobitex: +// +#define OID_WW_MBX_SUBADDR 0x09050101 +// OID 0x09050102 is reserved and may not be used +#define OID_WW_MBX_FLEXLIST 0x09050103 +#define OID_WW_MBX_GROUPLIST 0x09050104 +#define OID_WW_MBX_TRAFFIC_AREA 0x09050105 +#define OID_WW_MBX_LIVE_DIE 0x09050106 +#define OID_WW_MBX_TEMP_DEFAULTLIST 0x09050107 +// +// Network Dependent OIDs - Pinpoint: +// +#define OID_WW_PIN_LOC_AUTHORIZE 0x09090101 +#define OID_WW_PIN_LAST_LOCATION 0x09090102 +#define OID_WW_PIN_LOC_FIX 0x09090103 +// +// Network Dependent - CDPD: +// +#define OID_WW_CDPD_SPNI 0x090D0101 +#define OID_WW_CDPD_WASI 0x090D0102 +#define OID_WW_CDPD_AREA_COLOR 0x090D0103 +#define OID_WW_CDPD_TX_POWER_LEVEL 0x090D0104 +#define OID_WW_CDPD_EID 0x090D0105 +#define OID_WW_CDPD_HEADER_COMPRESSION 0x090D0106 +#define OID_WW_CDPD_DATA_COMPRESSION 0x090D0107 +#define OID_WW_CDPD_CHANNEL_SELECT 0x090D0108 +#define OID_WW_CDPD_CHANNEL_STATE 0x090D0109 +#define OID_WW_CDPD_NEI 0x090D010A +#define OID_WW_CDPD_NEI_STATE 0x090D010B +#define OID_WW_CDPD_SERVICE_PROVIDER_IDENTIFIER 0x090D010C +#define OID_WW_CDPD_SLEEP_MODE 0x090D010D +#define OID_WW_CDPD_CIRCUIT_SWITCHED 0x090D010E +#define OID_WW_CDPD_TEI 0x090D010F +#define OID_WW_CDPD_RSSI 0x090D0110 +// +// Network Dependent - Ardis: +// +#define OID_WW_ARD_SNDCP 0x09110101 +#define OID_WW_ARD_TMLY_MSG 0x09110102 +#define OID_WW_ARD_DATAGRAM 0x09110103 +// +// Network Dependent - DataTac: +// +#define OID_WW_TAC_COMPRESSION 0x09150101 +#define OID_WW_TAC_SET_CONFIG 0x09150102 +#define OID_WW_TAC_GET_STATUS 0x09150103 +#define OID_WW_TAC_USER_HEADER 0x09150104 +// +// Network Dependent - Metricom: +// +#define OID_WW_MET_FUNCTION 0x09190101 +// +// IRDA objects +// +#define OID_IRDA_RECEIVING 0x0A010100 +#define OID_IRDA_TURNAROUND_TIME 0x0A010101 +#define OID_IRDA_SUPPORTED_SPEEDS 0x0A010102 +#define OID_IRDA_LINK_SPEED 0x0A010103 +#define OID_IRDA_MEDIA_BUSY 0x0A010104 +#define OID_IRDA_EXTRA_RCV_BOFS 0x0A010200 +#define OID_IRDA_RATE_SNIFF 0x0A010201 +#define OID_IRDA_UNICAST_LIST 0x0A010202 +#define OID_IRDA_MAX_UNICAST_LIST_SIZE 0x0A010203 +#define OID_IRDA_MAX_RECEIVE_WINDOW_SIZE 0x0A010204 +#define OID_IRDA_MAX_SEND_WINDOW_SIZE 0x0A010205 +// +// Medium the Ndis Driver is running on (OID_GEN_MEDIA_SUPPORTED/ +// OID_GEN_MEDIA_IN_USE). +// +typedef enum _NDIS_MEDIUM { + NdisMedium802_3, + NdisMedium802_5, + NdisMediumFddi, + NdisMediumWan, + NdisMediumLocalTalk, + NdisMediumDix, // defined for convenience, not a real medium + NdisMediumArcnetRaw, + NdisMediumArcnet878_2, + NdisMediumAtm, + NdisMediumWirelessWan, + NdisMediumIrda, + NdisMediumMax // Not a real medium, defined as an upper-bound +} NDIS_MEDIUM, *PNDIS_MEDIUM; + +// +// Hardware status codes (OID_GEN_HARDWARE_STATUS). +// +typedef enum _NDIS_HARDWARE_STATUS { + NdisHardwareStatusReady, + NdisHardwareStatusInitializing, + NdisHardwareStatusReset, + NdisHardwareStatusClosing, + NdisHardwareStatusNotReady +} NDIS_HARDWARE_STATUS, *PNDIS_HARDWARE_STATUS; + +// +// this is the type passed in the OID_GEN_GET_TIME_CAPS request +// +typedef struct _GEN_GET_TIME_CAPS { + ULONG Flags; // Bits defined below + + ULONG ClockPrecision; +} GEN_GET_TIME_CAPS, *PGEN_GET_TIME_CAPS; + +#define READABLE_LOCAL_CLOCK 0x000000001 +#define CLOCK_NETWORK_DERIVED 0x000000002 +#define CLOCK_PRECISION 0x000000004 +#define RECEIVE_TIME_INDICATION_CAPABLE 0x000000008 +#define TIMED_SEND_CAPABLE 0x000000010 +#define TIME_STAMP_CAPABLE 0x000000020 +// +// +// this is the type passed in the OID_GEN_GET_NETCARD_TIME request +// +typedef struct _GEN_GET_NETCARD_TIME { + ULONG ReadTime; +} GEN_GET_NETCARD_TIME, *PGEN_GET_NETCARD_TIME; + +// +// Defines the attachment types for FDDI (OID_FDDI_ATTACHMENT_TYPE). +// +typedef enum _NDIS_FDDI_ATTACHMENT_TYPE { + NdisFddiTypeIsolated = 1, + NdisFddiTypeLocalA, + NdisFddiTypeLocalB, + NdisFddiTypeLocalAB, + NdisFddiTypeLocalS, + NdisFddiTypeWrapA, + NdisFddiTypeWrapB, + NdisFddiTypeWrapAB, + NdisFddiTypeWrapS, + NdisFddiTypeCWrapA, + NdisFddiTypeCWrapB, + NdisFddiTypeCWrapS, + NdisFddiTypeThrough +} NDIS_FDDI_ATTACHMENT_TYPE, *PNDIS_FDDI_ATTACHMENT_TYPE; + +// +// Defines the ring management states for FDDI (OID_FDDI_RING_MGT_STATE). +// +typedef enum _NDIS_FDDI_RING_MGT_STATE { + NdisFddiRingIsolated = 1, + NdisFddiRingNonOperational, + NdisFddiRingOperational, + NdisFddiRingDetect, + NdisFddiRingNonOperationalDup, + NdisFddiRingOperationalDup, + NdisFddiRingDirected, + NdisFddiRingTrace +} NDIS_FDDI_RING_MGT_STATE, *PNDIS_FDDI_RING_MGT_STATE; + +// +// Defines the Lconnection state for FDDI (OID_FDDI_LCONNECTION_STATE). +// +typedef enum _NDIS_FDDI_LCONNECTION_STATE { + NdisFddiStateOff = 1, + NdisFddiStateBreak, + NdisFddiStateTrace, + NdisFddiStateConnect, + NdisFddiStateNext, + NdisFddiStateSignal, + NdisFddiStateJoin, + NdisFddiStateVerify, + NdisFddiStateActive, + NdisFddiStateMaintenance +} NDIS_FDDI_LCONNECTION_STATE, *PNDIS_FDDI_LCONNECTION_STATE; + +// +// Defines the medium subtypes for WAN medium (OID_WAN_MEDIUM_SUBTYPE). +// +typedef enum _NDIS_WAN_MEDIUM_SUBTYPE { + NdisWanMediumHub, + NdisWanMediumX_25, + NdisWanMediumIsdn, + NdisWanMediumSerial, + NdisWanMediumFrameRelay, + NdisWanMediumAtm, + NdisWanMediumSonet, + NdisWanMediumSW56K +} NDIS_WAN_MEDIUM_SUBTYPE, *PNDIS_WAN_MEDIUM_SUBTYPE; + +// +// Defines the header format for WAN medium (OID_WAN_HEADER_FORMAT). +// +typedef enum _NDIS_WAN_HEADER_FORMAT { + NdisWanHeaderNative, // src/dest based on subtype, followed by NLPID + NdisWanHeaderEthernet // emulation of ethernet header +} NDIS_WAN_HEADER_FORMAT, *PNDIS_WAN_HEADER_FORMAT; + +// +// Defines the line quality on a WAN line (OID_WAN_QUALITY_OF_SERVICE). +// +typedef enum _NDIS_WAN_QUALITY { + NdisWanRaw, + NdisWanErrorControl, + NdisWanReliable +} NDIS_WAN_QUALITY, *PNDIS_WAN_QUALITY; + +// +// Defines the state of a token-ring adapter (OID_802_5_CURRENT_RING_STATE). +// +typedef enum _NDIS_802_5_RING_STATE { + NdisRingStateOpened = 1, + NdisRingStateClosed, + NdisRingStateOpening, + NdisRingStateClosing, + NdisRingStateOpenFailure, + NdisRingStateRingFailure +} NDIS_802_5_RING_STATE, *PNDIS_802_5_RING_STATE; + +// +// Defines the state of the LAN media +// +typedef enum _NDIS_MEDIA_STATE { + NdisMediaStateConnected, + NdisMediaStateDisconnected +} NDIS_MEDIA_STATE, *PNDIS_MEDIA_STATE; + +// +// The following is set on a per-packet basis as OOB data with NdisClass802_3Priority +// +typedef ULONG Priority_802_3; // 0-7 priority levels +// +// The following structure is used to query OID_GEN_CO_LINK_SPEED and +// OID_GEN_CO_MINIMUM_LINK_SPEED. The first OID will return the current +// link speed of the adapter. The second will return the minimum link speed +// the adapter is capable of. +// + +typedef struct _NDIS_CO_LINK_SPEED { + ULONG Outbound; + ULONG Inbound; +} NDIS_CO_LINK_SPEED, + +*PNDIS_CO_LINK_SPEED; +// +// Ndis Packet Filter Bits (OID_GEN_CURRENT_PACKET_FILTER). +// +#define NDIS_PACKET_TYPE_DIRECTED 0x0001 +#define NDIS_PACKET_TYPE_MULTICAST 0x0002 +#define NDIS_PACKET_TYPE_ALL_MULTICAST 0x0004 +#define NDIS_PACKET_TYPE_BROADCAST 0x0008 +#define NDIS_PACKET_TYPE_SOURCE_ROUTING 0x0010 +#define NDIS_PACKET_TYPE_PROMISCUOUS 0x0020 +#define NDIS_PACKET_TYPE_SMT 0x0040 +#define NDIS_PACKET_TYPE_ALL_LOCAL 0x0080 +#define NDIS_PACKET_TYPE_MAC_FRAME 0x8000 +#define NDIS_PACKET_TYPE_FUNCTIONAL 0x4000 +#define NDIS_PACKET_TYPE_ALL_FUNCTIONAL 0x2000 +#define NDIS_PACKET_TYPE_GROUP 0x1000 +// +// Ndis Token-Ring Ring Status Codes (OID_802_5_CURRENT_RING_STATUS). +// +#define NDIS_RING_SIGNAL_LOSS 0x00008000 +#define NDIS_RING_HARD_ERROR 0x00004000 +#define NDIS_RING_SOFT_ERROR 0x00002000 +#define NDIS_RING_TRANSMIT_BEACON 0x00001000 +#define NDIS_RING_LOBE_WIRE_FAULT 0x00000800 +#define NDIS_RING_AUTO_REMOVAL_ERROR 0x00000400 +#define NDIS_RING_REMOVE_RECEIVED 0x00000200 +#define NDIS_RING_COUNTER_OVERFLOW 0x00000100 +#define NDIS_RING_SINGLE_STATION 0x00000080 +#define NDIS_RING_RING_RECOVERY 0x00000040 +// +// Ndis protocol option bits (OID_GEN_PROTOCOL_OPTIONS). +// +#define NDIS_PROT_OPTION_ESTIMATED_LENGTH 0x00000001 +#define NDIS_PROT_OPTION_NO_LOOPBACK 0x00000002 +#define NDIS_PROT_OPTION_NO_RSVD_ON_RCVPKT 0x00000004 +// +// Ndis MAC option bits (OID_GEN_MAC_OPTIONS). +// +#define NDIS_MAC_OPTION_COPY_LOOKAHEAD_DATA 0x00000001 +#define NDIS_MAC_OPTION_RECEIVE_SERIALIZED 0x00000002 +#define NDIS_MAC_OPTION_TRANSFERS_NOT_PEND 0x00000004 +#define NDIS_MAC_OPTION_NO_LOOPBACK 0x00000008 +#define NDIS_MAC_OPTION_FULL_DUPLEX 0x00000010 +#define NDIS_MAC_OPTION_EOTX_INDICATION 0x00000020 +#define NDIS_MAC_OPTION_RESERVED 0x80000000 +// +// NDIS MAC option bits for OID_GEN_CO_MAC_OPTIONS. +// +#define NDIS_CO_MAC_OPTION_DYNAMIC_LINK_SPEED 0x00000001 +#ifdef IRDA +// +// The following is set on a per-packet basis as OOB data with NdisClassIrdaPacketInfo +// This is the per-packet info specified on a per-packet basis +// +typedef struct _NDIS_IRDA_PACKET_INFO { + UINT ExtraBOFs; + UINT MinTurnAroundTime; +} NDIS_IRDA_PACKET_INFO, *PNDIS_IRDA_PACKET_INFO; + +#endif +#ifdef WIRELESS_WAN +// +// Wireless WAN structure definitions +// +// +// currently defined Wireless network subtypes +// +typedef enum _NDIS_WW_NETWORK_TYPE { + NdisWWGeneric, + NdisWWMobitex, + NdisWWPinpoint, + NdisWWCDPD, + NdisWWArdis, + NdisWWDataTAC, + NdisWWMetricom, + NdisWWGSM, + NdisWWCDMA, + NdisWWTDMA, + NdisWWAMPS, + NdisWWInmarsat, + NdisWWpACT +} NDIS_WW_NETWORK_TYPE; + +// +// currently defined header formats +// +typedef enum _NDIS_WW_HEADER_FORMAT { + NdisWWDIXEthernetFrames, + NdisWWMPAKFrames, + NdisWWRDLAPFrames, + NdisWWMDC4800Frames +} NDIS_WW_HEADER_FORMAT; + +// +// currently defined encryption types +// +typedef enum _NDIS_WW_ENCRYPTION_TYPE { + NdisWWUnknownEncryption = -1, + NdisWWNoEncryption, + NdisWWDefaultEncryption +} NDIS_WW_ENCRYPTION_TYPE, *PNDIS_WW_ENCRYPTION_TYPE; + +// +// OID_WW_GEN_INDICATION_REQUEST +// +typedef struct _NDIS_WW_INDICATION_REQUEST { + NDIS_OID Oid; // IN + + UINT uIndicationFlag; // IN + + UINT uApplicationToken; // IN OUT + + HANDLE hIndicationHandle; // IN OUT + + INT iPollingInterval; // IN OUT + + NDIS_VAR_DATA_DESC InitialValue; // IN OUT + + NDIS_VAR_DATA_DESC OIDIndicationValue; // OUT - only valid after indication + + NDIS_VAR_DATA_DESC TriggerValue; // IN + +} NDIS_WW_INDICATION_REQUEST, *PNDIS_WW_INDICATION_REQUEST; + +#define OID_INDICATION_REQUEST_ENABLE 0x0000 +#define OID_INDICATION_REQUEST_CANCEL 0x0001 +// +// OID_WW_GEN_DEVICE_INFO +// +typedef struct _WW_DEVICE_INFO { + NDIS_VAR_DATA_DESC Manufacturer; + NDIS_VAR_DATA_DESC ModelNum; + NDIS_VAR_DATA_DESC SWVersionNum; + NDIS_VAR_DATA_DESC SerialNum; +} WW_DEVICE_INFO, *PWW_DEVICE_INFO; + +// +// OID_WW_GEN_OPERATION_MODE +// +typedef INT WW_OPERATION_MODE; // 0 = Normal mode + // 1 = Power saving mode + // -1 = mode unknown +// +// OID_WW_GEN_LOCK_STATUS +// + +typedef INT WW_LOCK_STATUS; // 0 = unlocked + // 1 = locked + // -1 = unknown lock status +// +// OID_WW_GEN_DISABLE_TRANSMITTER +// + +typedef INT WW_DISABLE_TRANSMITTER; // 0 = transmitter enabled + // 1 = transmitter disabled + // -1 = unknown value +// +// OID_WW_GEN_NETWORK_ID +// + +typedef NDIS_VAR_DATA_DESC WW_NETWORK_ID; +// +// OID_WW_GEN_PERMANENT_ADDRESS +// +typedef NDIS_VAR_DATA_DESC WW_PERMANENT_ADDRESS; +// +// OID_WW_GEN_CURRENT_ADDRESS +// +typedef struct _WW_CURRENT_ADDRESS { + NDIS_WW_HEADER_FORMAT Format; + NDIS_VAR_DATA_DESC Address; +} WW_CURRENT_ADDRESS, *PWW_CURRENT_ADDRESS; + +// +// OID_WW_GEN_SUSPEND_DRIVER +// +typedef BOOLEAN WW_SUSPEND_DRIVER; // 0 = driver operational + // 1 = driver suspended +// +// OID_WW_GEN_BASESTATION_ID +// + +typedef NDIS_VAR_DATA_DESC WW_BASESTATION_ID; +// +// OID_WW_GEN_CHANNEL_ID +// +typedef NDIS_VAR_DATA_DESC WW_CHANNEL_ID; +// +// OID_WW_GEN_ENCRYPTION_STATE +// +typedef BOOLEAN WW_ENCRYPTION_STATE; // 0 = if encryption is disabled + // 1 = if encryption is enabled +// +// OID_WW_GEN_CHANNEL_QUALITY +// + +typedef INT WW_CHANNEL_QUALITY; // 0 = Not in network contact, + // 1-100 = Quality of Channel (100 is highest quality). + // -1 = channel quality is unknown +// +// OID_WW_GEN_REGISTRATION_STATUS +// + +typedef INT WW_REGISTRATION_STATUS; // 0 = Registration denied + // 1 = Registration pending + // 2 = Registered + // -1 = unknown registration status +// +// OID_WW_GEN_RADIO_LINK_SPEED +// + +typedef UINT WW_RADIO_LINK_SPEED; // Bits per second. +// +// OID_WW_GEN_LATENCY +// + +typedef UINT WW_LATENCY; // milliseconds +// +// OID_WW_GEN_BATTERY_LEVEL +// + +typedef INT WW_BATTERY_LEVEL; // 0-100 = battery level in percentage + // (100=fully charged) + // -1 = unknown battery level. +// +// OID_WW_GEN_EXTERNAL_POWER +// + +typedef INT WW_EXTERNAL_POWER; // 0 = no external power connected + // 1 = external power connected + // -1 = unknown +// +// OID_WW_MET_FUNCTION +// + +typedef NDIS_VAR_DATA_DESC WW_MET_FUNCTION; +// +// OID_WW_TAC_COMPRESSION +// +typedef BOOLEAN WW_TAC_COMPRESSION; // Determines whether or not network level compression + // is being used. +// +// OID_WW_TAC_SET_CONFIG +// + +typedef struct _WW_TAC_SETCONFIG { + NDIS_VAR_DATA_DESC RCV_MODE; + NDIS_VAR_DATA_DESC TX_CONTROL; + NDIS_VAR_DATA_DESC RX_CONTROL; + NDIS_VAR_DATA_DESC FLOW_CONTROL; + NDIS_VAR_DATA_DESC RESET_CNF; + NDIS_VAR_DATA_DESC READ_CNF; +} WW_TAC_SETCONFIG, *PWW_TAC_SETCONFIG; + +// +// OID_WW_TAC_GET_STATUS +// +typedef struct _WW_TAC_GETSTATUS { + BOOLEAN Action; // Set = Execute command. + + NDIS_VAR_DATA_DESC Command; + NDIS_VAR_DATA_DESC Option; + NDIS_VAR_DATA_DESC Response; // The response to the requested command + // - max. length of string is 256 octets. + +} WW_TAC_GETSTATUS, *PWW_TAC_GETSTATUS; + +// +// OID_WW_TAC_USER_HEADER +// +typedef NDIS_VAR_DATA_DESC WW_TAC_USERHEADER; // This will hold the user header - Max. 64 octets. +// +// OID_WW_ARD_SNDCP +// + +typedef struct _WW_ARD_SNDCP { + NDIS_VAR_DATA_DESC Version; // The version of SNDCP protocol supported. + + INT BlockSize; // The block size used for SNDCP + + INT Window; // The window size used in SNDCP + +} WW_ARD_SNDCP, *PWW_ARD_SNDCP; + +// +// OID_WW_ARD_TMLY_MSG +// +typedef BOOLEAN WW_ARD_CHANNEL_STATUS; // The current status of the inbound RF Channel. +// +// OID_WW_ARD_DATAGRAM +// + +typedef struct _WW_ARD_DATAGRAM { + BOOLEAN LoadLevel; // Byte that contains the load level info. + + INT SessionTime; // Datagram session time remaining. + + NDIS_VAR_DATA_DESC HostAddr; // Host address. + + NDIS_VAR_DATA_DESC THostAddr; // Test host address. + +} WW_ARD_DATAGRAM, *PWW_ARD_DATAGRAM; + +// +// OID_WW_CDPD_SPNI +// +typedef struct _WW_CDPD_SPNI { + UINT SPNI[10]; //10 16-bit service provider network IDs + + INT OperatingMode; // 0 = ignore SPNI, + // 1 = require SPNI from list, + // 2 = prefer SPNI from list. + // 3 = exclude SPNI from list. + +} WW_CDPD_SPNI, *PWW_CDPD_SPNI; + +// +// OID_WW_CDPD_WASI +// +typedef struct _WW_CDPD_WIDE_AREA_SERVICE_ID { + UINT WASI[10]; //10 16-bit wide area service IDs + + INT OperatingMode; // 0 = ignore WASI, + // 1 = Require WASI from list, + // 2 = prefer WASI from list + // 3 = exclude WASI from list. + +} WW_CDPD_WIDE_AREA_SERVICE_ID, *PWW_CDPD_WIDE_AREA_SERVICE_ID; + +// +// OID_WW_CDPD_AREA_COLOR +// +typedef INT WW_CDPD_AREA_COLOR; +// +// OID_WW_CDPD_TX_POWER_LEVEL +// +typedef UINT WW_CDPD_TX_POWER_LEVEL; +// +// OID_WW_CDPD_EID +// +typedef NDIS_VAR_DATA_DESC WW_CDPD_EID; +// +// OID_WW_CDPD_HEADER_COMPRESSION +// +typedef INT WW_CDPD_HEADER_COMPRESSION; // 0 = no header compression, + // 1 = always compress headers, + // 2 = compress headers if MD-IS does + // -1 = unknown +// +// OID_WW_CDPD_DATA_COMPRESSION +// + +typedef INT WW_CDPD_DATA_COMPRESSION; // 0 = no data compression, + // 1 = data compression enabled + // -1 = unknown +// +// OID_WW_CDPD_CHANNEL_SELECT +// + +typedef struct _WW_CDPD_CHANNEL_SELECT { + UINT ChannelID; // channel number + + UINT fixedDuration; // duration in seconds + +} WW_CDPD_CHANNEL_SELECT, *PWW_CDPD_CHANNEL_SELECT; + +// +// OID_WW_CDPD_CHANNEL_STATE +// +typedef enum _WW_CDPD_CHANNEL_STATE { + CDPDChannelNotAvail, + CDPDChannelScanning, + CDPDChannelInitAcquired, + CDPDChannelAcquired, + CDPDChannelSleeping, + CDPDChannelWaking, + CDPDChannelCSDialing, + CDPDChannelCSRedial, + CDPDChannelCSAnswering, + CDPDChannelCSConnected, + CDPDChannelCSSuspended +} WW_CDPD_CHANNEL_STATE, *PWW_CDPD_CHANNEL_STATE; + +// +// OID_WW_CDPD_NEI +// +typedef enum _WW_CDPD_NEI_FORMAT { + CDPDNeiIPv4, + CDPDNeiCLNP, + CDPDNeiIPv6 +} WW_CDPD_NEI_FORMAT, *PWW_CDPD_NEI_FORMAT; +typedef enum _WW_CDPD_NEI_TYPE { + CDPDNeiIndividual, + CDPDNeiMulticast, + CDPDNeiBroadcast +} WW_CDPD_NEI_TYPE; +typedef struct _WW_CDPD_NEI { + UINT uNeiIndex; + WW_CDPD_NEI_FORMAT NeiFormat; + WW_CDPD_NEI_TYPE NeiType; + WORD NeiGmid; // group member identifier, only + // meaningful if NeiType == + // CDPDNeiMulticast + + NDIS_VAR_DATA_DESC NeiAddress; +} WW_CDPD_NEI; + +// +// OID_WW_CDPD_NEI_STATE +// +typedef enum _WW_CDPD_NEI_STATE { + CDPDUnknown, + CDPDRegistered, + CDPDDeregistered +} WW_CDPD_NEI_STATE, *PWW_CDPD_NEI_STATE; +typedef enum _WW_CDPD_NEI_SUB_STATE { + CDPDPending, // Registration pending + CDPDNoReason, // Registration denied - no reason given + CDPDMDISNotCapable, // Registration denied - MD-IS not capable of + // handling M-ES at this time + CDPDNEINotAuthorized, // Registration denied - NEI is not authorized to + // use this subnetwork + CDPDInsufficientAuth, // Registration denied - M-ES gave insufficient + // authentication credentials + CDPDUnsupportedAuth, // Registration denied - M-ES gave unsupported + // authentication credentials + CDPDUsageExceeded, // Registration denied - NEI has exceeded usage + // limitations + CDPDDeniedThisNetwork // Registration denied on this network, service + // may be obtained on alternate Service Provider + // network +} WW_CDPD_NEI_SUB_STATE; +typedef struct _WW_CDPD_NEI_REG_STATE { + UINT uNeiIndex; + WW_CDPD_NEI_STATE NeiState; + WW_CDPD_NEI_SUB_STATE NeiSubState; +} WW_CDPD_NEI_REG_STATE, *PWW_CDPD_NEI_REG_STATE; + +// +// OID_WW_CDPD_SERVICE_PROVIDER_IDENTIFIER +// +typedef struct _WW_CDPD_SERVICE_PROVIDER_ID { + UINT SPI[10]; //10 16-bit service provider IDs + + INT OperatingMode; // 0 = ignore SPI, + // 1 = require SPI from list, + // 2 = prefer SPI from list. + // 3 = exclude SPI from list. + +} WW_CDPD_SERVICE_PROVIDER_ID, *PWW_CDPD_SERVICE_PROVIDER_ID; + +// +// OID_WW_CDPD_SLEEP_MODE +// +typedef INT WW_CDPD_SLEEP_MODE; +// +// OID_WW_CDPD_TEI +// +typedef ULONG WW_CDPD_TEI; +// +// OID_WW_CDPD_CIRCUIT_SWITCHED +// +typedef struct _WW_CDPD_CIRCUIT_SWITCHED { + INT service_preference; // -1 = unknown, + // 0 = always use packet switched CDPD, + // 1 = always use CS CDPD via AMPS, + // 2 = always use CS CDPD via PSTN, + // 3 = use circuit switched via AMPS only + // when packet switched is not available. + // 4 = use packet switched only when circuit + // switched via AMPS is not available. + // 5 = device manuf. defined service + // preference. + // 6 = device manuf. defined service + // preference. + + INT service_status; // -1 = unknown, + // 0 = packet switched CDPD, + // 1 = circuit switched CDPD via AMPS, + // 2 = circuit switched CDPD via PSTN. + + INT connect_rate; // CS connection bit rate (bits per second). + // 0 = no active connection, + // -1 = unknown + // Dial code last used to dial. + + NDIS_VAR_DATA_DESC dial_code[20]; + + UINT sid; // Current AMPS system ID + + INT a_b_side_selection; // -1 = unknown, + // 0 = no AMPS service + // 1 = AMPS "A" side channels selected + // 2 = AMPS "B" side channels selected + + INT AMPS_channel; // -1= unknown + // 0 = no AMPS service. + // 1-1023 = AMPS channel number in use + + UINT action; // 0 = no action + // 1 = suspend (hangup) + // 2 = dial + + // Default dial code for CS CDPD service + // encoded as specified in the CS CDPD + // implementor guidelines. + NDIS_VAR_DATA_DESC default_dial[20]; + + // Number for the CS CDPD network to call + // back the mobile, encoded as specified in + // the CS CDPD implementor guidelines. + NDIS_VAR_DATA_DESC call_back[20]; + + UINT sid_list[10]; // List of 10 16-bit preferred AMPS + // system IDs for CS CDPD. + + UINT inactivity_timer; // Wait time after last data before dropping + // call. + // 0-65535 = inactivity time limit (seconds). + + UINT receive_timer; // secs. per CS-CDPD Implementor Guidelines. + + UINT conn_resp_timer; // secs. per CS-CDPD Implementor Guidelines. + + UINT reconn_resp_timer; // secs. per CS-CDPD Implementor Guidelines. + + UINT disconn_timer; // secs. per CS-CDPD Implementor Guidelines. + + UINT NEI_reg_timer; // secs. per CS-CDPD Implementor Guidelines. + + UINT reconn_retry_timer; // secs. per CS-CDPD Implementor Guidelines. + + UINT link_reset_timer; // secs. per CS-CDPD Implementor Guidelines. + + UINT link_reset_ack_timer; // secs. per CS-CDPD Implementor Guidelines. + + UINT n401_retry_limit; // per CS-CDPD Implementor Guidelines. + + UINT n402_retry_limit; // per CS-CDPD Implementor Guidelines. + + UINT n404_retry_limit; // per CS-CDPD Implementor Guidelines. + + UINT n405_retry_limit; // per CS-CDPD Implementor Guidelines. + +} WW_CDPD_CIRCUIT_SWITCHED, *WW_PCDPD_CIRCUIT_SWITCHED; +typedef UINT WW_CDPD_RSSI; +// +// OID_WW_PIN_LOC_AUTHORIZE +// +typedef INT WW_PIN_AUTHORIZED; // 0 = unauthorized + // 1 = authorized + // -1 = unknown +// +// OID_WW_PIN_LAST_LOCATION +// OID_WW_PIN_LOC_FIX +// + +typedef struct _WW_PIN_LOCATION { + INT Latitude; // Latitude in hundredths of a second + + INT Longitude; // Longitude in hundredths of a second + + INT Altitude; // Altitude in feet + + INT FixTime; // Time of the location fix, since midnight, local time (of the + // current day), in tenths of a second + + INT NetTime; // Current local network time of the current day, since midnight, + // in tenths of a second + + INT LocQuality; // 0-100 = location quality + + INT LatReg; // Latitude registration offset, in hundredths of a second + + INT LongReg; // Longitude registration offset, in hundredths of a second + + INT GMTOffset; // Offset in minutes of the local time zone from GMT + +} WW_PIN_LOCATION, *PWW_PIN_LOCATION; + +// +// The following is set on a per-packet basis as OOB data with NdisClassWirelessWanMbxMailbox +// +typedef ULONG WW_MBX_MAILBOX_FLAG; // 1 = set mailbox flag, 0 = do not set mailbox flag +// +// OID_WW_MBX_SUBADDR +// + +typedef struct _WW_MBX_PMAN { + BOOLEAN ACTION; // 0 = Login PMAN, 1 = Logout PMAN + + UINT MAN; + UCHAR PASSWORD[8]; // Password should be null for Logout and indications. + // Maximum length of password is 8 chars. + +} WW_MBX_PMAN, *PWW_MBX_PMAN; + +// +// OID_WW_MBX_FLEXLIST +// +typedef struct _WW_MBX_FLEXLIST { + INT count; // Number of MAN entries used. + // -1=unknown. + + UINT MAN[7]; // List of MANs. + +} WW_MBX_FLEXLIST; + +// +// OID_WW_MBX_GROUPLIST +// +typedef struct _WW_MBX_GROUPLIST { + INT count; // Number of MAN entries used. + // -1=unknown. + + UINT MAN[15]; // List of MANs. + +} WW_MBX_GROUPLIST; + +// +// OID_WW_MBX_TRAFFIC_AREA +// +typedef enum _WW_MBX_TRAFFIC_AREA { + unknown_traffic_area, // The driver has no information about the current traffic area. + in_traffic_area, // Mobile unit has entered a subscribed traffic area. + in_auth_traffic_area, // Mobile unit is outside traffic area but is authorized. + unauth_traffic_area // Mobile unit is outside traffic area but is un-authorized. +} WW_MBX_TRAFFIC_AREA; + +// +// OID_WW_MBX_LIVE_DIE +// +typedef INT WW_MBX_LIVE_DIE; // 0 = DIE last received + // 1 = LIVE last received + // -1 = unknown +// +// OID_WW_MBX_TEMP_DEFAULTLIST +// + +typedef struct _WW_MBX_CHANNEL_PAIR { + UINT Mobile_Tx; + UINT Mobile_Rx; +} WW_MBX_CHANNEL_PAIR, *PWW_MBX_CHANNEL_PAIR; +typedef struct _WW_MBX_TEMPDEFAULTLIST { + UINT Length; + WW_MBX_CHANNEL_PAIR ChannelPair[1]; +} WW_MBX_TEMPDEFAULTLIST, *WW_PMBX_TEMPDEFAULTLIST; + +#endif // WIRELESS_WAN +#endif // _NTDDNDIS_ diff --git a/plugins/dev9ghzdrk/Win32/afxresmw.h b/plugins/dev9ghzdrk/Win32/afxresmw.h new file mode 100644 index 0000000000..99eace37c4 --- /dev/null +++ b/plugins/dev9ghzdrk/Win32/afxresmw.h @@ -0,0 +1,5 @@ + +#include +#include + +#define IDC_STATIC (-1) diff --git a/plugins/dev9ghzdrk/Win32/ata.cpp b/plugins/dev9ghzdrk/Win32/ata.cpp new file mode 100644 index 0000000000..de5f273050 --- /dev/null +++ b/plugins/dev9ghzdrk/Win32/ata.cpp @@ -0,0 +1,3442 @@ +/* + * QEMU IDE disk and CD-ROM Emulator + * + * Copyright (c) 2003 Fabrice Bellard + * + * 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. + */ +#include "dev9.h" +#include "vl.h" + +/* debug IDE devices */ +//#define DEBUG_IDE +//#define DEBUG_IDE_ATAPI +//#define DEBUG_AIO + +#define USE_DMA_CDROM +#define QEMU_VERSION " PCSX2" +#define snprintf _snprintf + +#define le32_to_cpu(x) (x) +#define le16_to_cpu(x) (x) +#define cpu_to_le16(x) (x) +#define cpu_to_le32(x) (x) + +/* Bits of HD_STATUS */ +#define ERR_STAT 0x01 +#define INDEX_STAT 0x02 +#define ECC_STAT 0x04 /* Corrected error */ +#define DRQ_STAT 0x08 +#define SEEK_STAT 0x10 +#define SRV_STAT 0x10 +#define WRERR_STAT 0x20 +#define READY_STAT 0x40 +#define BUSY_STAT 0x80 + +/* Bits for HD_ERROR */ +#define MARK_ERR 0x01 /* Bad address mark */ +#define TRK0_ERR 0x02 /* couldn't find track 0 */ +#define ABRT_ERR 0x04 /* Command aborted */ +#define MCR_ERR 0x08 /* media change request */ +#define ID_ERR 0x10 /* ID field not found */ +#define MC_ERR 0x20 /* media changed */ +#define ECC_ERR 0x40 /* Uncorrectable ECC error */ +#define BBD_ERR 0x80 /* pre-EIDE meaning: block marked bad */ +#define ICRC_ERR 0x80 /* new meaning: CRC error during transfer */ + +/* Bits of HD_NSECTOR */ +#define CD 0x01 +#define IO 0x02 +#define REL 0x04 +#define TAG_MASK 0xf8 + +#define IDE_CMD_RESET 0x04 +#define IDE_CMD_DISABLE_IRQ 0x02 + +/* ATA/ATAPI Commands pre T13 Spec */ +#define WIN_NOP 0x00 +/* + * 0x01->0x02 Reserved + */ +#define CFA_REQ_EXT_ERROR_CODE 0x03 /* CFA Request Extended Error Code */ +/* + * 0x04->0x07 Reserved + */ +#define WIN_SRST 0x08 /* ATAPI soft reset command */ +#define WIN_DEVICE_RESET 0x08 +/* + * 0x09->0x0F Reserved + */ +#define WIN_RECAL 0x10 +#define WIN_RESTORE WIN_RECAL +/* + * 0x10->0x1F Reserved + */ +#define WIN_READ 0x20 /* 28-Bit */ +#define WIN_READ_ONCE 0x21 /* 28-Bit without retries */ +#define WIN_READ_LONG 0x22 /* 28-Bit */ +#define WIN_READ_LONG_ONCE 0x23 /* 28-Bit without retries */ +#define WIN_READ_EXT 0x24 /* 48-Bit */ +#define WIN_READDMA_EXT 0x25 /* 48-Bit */ +#define WIN_READDMA_QUEUED_EXT 0x26 /* 48-Bit */ +#define WIN_READ_NATIVE_MAX_EXT 0x27 /* 48-Bit */ +/* + * 0x28 + */ +#define WIN_MULTREAD_EXT 0x29 /* 48-Bit */ +/* + * 0x2A->0x2F Reserved + */ +#define WIN_WRITE 0x30 /* 28-Bit */ +#define WIN_WRITE_ONCE 0x31 /* 28-Bit without retries */ +#define WIN_WRITE_LONG 0x32 /* 28-Bit */ +#define WIN_WRITE_LONG_ONCE 0x33 /* 28-Bit without retries */ +#define WIN_WRITE_EXT 0x34 /* 48-Bit */ +#define WIN_WRITEDMA_EXT 0x35 /* 48-Bit */ +#define WIN_WRITEDMA_QUEUED_EXT 0x36 /* 48-Bit */ +#define WIN_SET_MAX_EXT 0x37 /* 48-Bit */ +#define CFA_WRITE_SECT_WO_ERASE 0x38 /* CFA Write Sectors without erase */ +#define WIN_MULTWRITE_EXT 0x39 /* 48-Bit */ +/* + * 0x3A->0x3B Reserved + */ +#define WIN_WRITE_VERIFY 0x3C /* 28-Bit */ +/* + * 0x3D->0x3F Reserved + */ +#define WIN_VERIFY 0x40 /* 28-Bit - Read Verify Sectors */ +#define WIN_VERIFY_ONCE 0x41 /* 28-Bit - without retries */ +#define WIN_VERIFY_EXT 0x42 /* 48-Bit */ +/* + * 0x43->0x4F Reserved + */ +#define WIN_FORMAT 0x50 +/* + * 0x51->0x5F Reserved + */ +#define WIN_INIT 0x60 +/* + * 0x61->0x5F Reserved + */ +#define WIN_SEEK 0x70 /* 0x70-0x7F Reserved */ +#define CFA_TRANSLATE_SECTOR 0x87 /* CFA Translate Sector */ +#define WIN_DIAGNOSE 0x90 +#define WIN_SPECIFY 0x91 /* set drive geometry translation */ +#define WIN_DOWNLOAD_MICROCODE 0x92 +#define WIN_STANDBYNOW2 0x94 +#define WIN_STANDBY2 0x96 +#define WIN_SETIDLE2 0x97 +#define WIN_CHECKPOWERMODE2 0x98 +#define WIN_SLEEPNOW2 0x99 +/* + * 0x9A VENDOR + */ +#define WIN_PACKETCMD 0xA0 /* Send a packet command. */ +#define WIN_PIDENTIFY 0xA1 /* identify ATAPI device */ +#define WIN_QUEUED_SERVICE 0xA2 +#define WIN_SMART 0xB0 /* self-monitoring and reporting */ +#define CFA_ERASE_SECTORS 0xC0 +#define WIN_MULTREAD 0xC4 /* read sectors using multiple mode*/ +#define WIN_MULTWRITE 0xC5 /* write sectors using multiple mode */ +#define WIN_SETMULT 0xC6 /* enable/disable multiple mode */ +#define WIN_READDMA_QUEUED 0xC7 /* read sectors using Queued DMA transfers */ +#define WIN_READDMA 0xC8 /* read sectors using DMA transfers */ +#define WIN_READDMA_ONCE 0xC9 /* 28-Bit - without retries */ +#define WIN_WRITEDMA 0xCA /* write sectors using DMA transfers */ +#define WIN_WRITEDMA_ONCE 0xCB /* 28-Bit - without retries */ +#define WIN_WRITEDMA_QUEUED 0xCC /* write sectors using Queued DMA transfers */ +#define CFA_WRITE_MULTI_WO_ERASE 0xCD /* CFA Write multiple without erase */ +#define WIN_GETMEDIASTATUS 0xDA +#define WIN_ACKMEDIACHANGE 0xDB /* ATA-1, ATA-2 vendor */ +#define WIN_POSTBOOT 0xDC +#define WIN_PREBOOT 0xDD +#define WIN_DOORLOCK 0xDE /* lock door on removable drives */ +#define WIN_DOORUNLOCK 0xDF /* unlock door on removable drives */ +#define WIN_STANDBYNOW1 0xE0 +#define WIN_IDLEIMMEDIATE 0xE1 /* force drive to become "ready" */ +#define WIN_STANDBY 0xE2 /* Set device in Standby Mode */ +#define WIN_SETIDLE1 0xE3 +#define WIN_READ_BUFFER 0xE4 /* force read only 1 sector */ +#define WIN_CHECKPOWERMODE1 0xE5 +#define WIN_SLEEPNOW1 0xE6 +#define WIN_FLUSH_CACHE 0xE7 +#define WIN_WRITE_BUFFER 0xE8 /* force write only 1 sector */ +#define WIN_WRITE_SAME 0xE9 /* read ata-2 to use */ + /* SET_FEATURES 0x22 or 0xDD */ +#define WIN_FLUSH_CACHE_EXT 0xEA /* 48-Bit */ +#define WIN_IDENTIFY 0xEC /* ask drive to identify itself */ +#define WIN_MEDIAEJECT 0xED +#define WIN_IDENTIFY_DMA 0xEE /* same as WIN_IDENTIFY, but DMA */ +#define WIN_SETFEATURES 0xEF /* set special drive features */ +#define EXABYTE_ENABLE_NEST 0xF0 +#define WIN_SECURITY_SET_PASS 0xF1 +#define WIN_SECURITY_UNLOCK 0xF2 +#define WIN_SECURITY_ERASE_PREPARE 0xF3 +#define WIN_SECURITY_ERASE_UNIT 0xF4 +#define WIN_SECURITY_FREEZE_LOCK 0xF5 +#define WIN_SECURITY_DISABLE 0xF6 +#define WIN_READ_NATIVE_MAX 0xF8 /* return the native maximum address */ +#define WIN_SET_MAX 0xF9 +#define DISABLE_SEAGATE 0xFB + +/* set to 1 set disable mult support */ +#define MAX_MULT_SECTORS 16 + +/* ATAPI defines */ + +#define ATAPI_PACKET_SIZE 12 + +/* The generic packet command opcodes for CD/DVD Logical Units, + * From Table 57 of the SFF8090 Ver. 3 (Mt. Fuji) draft standard. */ +#define GPCMD_BLANK 0xa1 +#define GPCMD_CLOSE_TRACK 0x5b +#define GPCMD_FLUSH_CACHE 0x35 +#define GPCMD_FORMAT_UNIT 0x04 +#define GPCMD_GET_CONFIGURATION 0x46 +#define GPCMD_GET_EVENT_STATUS_NOTIFICATION 0x4a +#define GPCMD_GET_PERFORMANCE 0xac +#define GPCMD_INQUIRY 0x12 +#define GPCMD_LOAD_UNLOAD 0xa6 +#define GPCMD_MECHANISM_STATUS 0xbd +#define GPCMD_MODE_SELECT_10 0x55 +#define GPCMD_MODE_SENSE_10 0x5a +#define GPCMD_PAUSE_RESUME 0x4b +#define GPCMD_PLAY_AUDIO_10 0x45 +#define GPCMD_PLAY_AUDIO_MSF 0x47 +#define GPCMD_PLAY_AUDIO_TI 0x48 +#define GPCMD_PLAY_CD 0xbc +#define GPCMD_PREVENT_ALLOW_MEDIUM_REMOVAL 0x1e +#define GPCMD_READ_10 0x28 +#define GPCMD_READ_12 0xa8 +#define GPCMD_READ_CDVD_CAPACITY 0x25 +#define GPCMD_READ_CD 0xbe +#define GPCMD_READ_CD_MSF 0xb9 +#define GPCMD_READ_DISC_INFO 0x51 +#define GPCMD_READ_DVD_STRUCTURE 0xad +#define GPCMD_READ_FORMAT_CAPACITIES 0x23 +#define GPCMD_READ_HEADER 0x44 +#define GPCMD_READ_TRACK_RZONE_INFO 0x52 +#define GPCMD_READ_SUBCHANNEL 0x42 +#define GPCMD_READ_TOC_PMA_ATIP 0x43 +#define GPCMD_REPAIR_RZONE_TRACK 0x58 +#define GPCMD_REPORT_KEY 0xa4 +#define GPCMD_REQUEST_SENSE 0x03 +#define GPCMD_RESERVE_RZONE_TRACK 0x53 +#define GPCMD_SCAN 0xba +#define GPCMD_SEEK 0x2b +#define GPCMD_SEND_DVD_STRUCTURE 0xad +#define GPCMD_SEND_EVENT 0xa2 +#define GPCMD_SEND_KEY 0xa3 +#define GPCMD_SEND_OPC 0x54 +#define GPCMD_SET_READ_AHEAD 0xa7 +#define GPCMD_SET_STREAMING 0xb6 +#define GPCMD_START_STOP_UNIT 0x1b +#define GPCMD_STOP_PLAY_SCAN 0x4e +#define GPCMD_TEST_UNIT_READY 0x00 +#define GPCMD_VERIFY_10 0x2f +#define GPCMD_WRITE_10 0x2a +#define GPCMD_WRITE_AND_VERIFY_10 0x2e +/* This is listed as optional in ATAPI 2.6, but is (curiously) + * missing from Mt. Fuji, Table 57. It _is_ mentioned in Mt. Fuji + * Table 377 as an MMC command for SCSi devices though... Most ATAPI + * drives support it. */ +#define GPCMD_SET_SPEED 0xbb +/* This seems to be a SCSI specific CD-ROM opcode + * to play data at track/index */ +#define GPCMD_PLAYAUDIO_TI 0x48 +/* + * From MS Media Status Notification Support Specification. For + * older drives only. + */ +#define GPCMD_GET_MEDIA_STATUS 0xda + +/* Mode page codes for mode sense/set */ +#define GPMODE_R_W_ERROR_PAGE 0x01 +#define GPMODE_WRITE_PARMS_PAGE 0x05 +#define GPMODE_AUDIO_CTL_PAGE 0x0e +#define GPMODE_POWER_PAGE 0x1a +#define GPMODE_FAULT_FAIL_PAGE 0x1c +#define GPMODE_TO_PROTECT_PAGE 0x1d +#define GPMODE_CAPABILITIES_PAGE 0x2a +#define GPMODE_ALL_PAGES 0x3f +/* Not in Mt. Fuji, but in ATAPI 2.6 -- depricated now in favor + * of MODE_SENSE_POWER_PAGE */ +#define GPMODE_CDROM_PAGE 0x0d + +#define ATAPI_INT_REASON_CD 0x01 /* 0 = data transfer */ +#define ATAPI_INT_REASON_IO 0x02 /* 1 = transfer to the host */ +#define ATAPI_INT_REASON_REL 0x04 +#define ATAPI_INT_REASON_TAG 0xf8 + +/* same constants as bochs */ +#define ASC_ILLEGAL_OPCODE 0x20 +#define ASC_LOGICAL_BLOCK_OOR 0x21 +#define ASC_INV_FIELD_IN_CMD_PACKET 0x24 +#define ASC_MEDIUM_NOT_PRESENT 0x3a +#define ASC_SAVING_PARAMETERS_NOT_SUPPORTED 0x39 + +#define SENSE_NONE 0 +#define SENSE_NOT_READY 2 +#define SENSE_ILLEGAL_REQUEST 5 +#define SENSE_UNIT_ATTENTION 6 + +struct IDEState; + +typedef void EndTransferFunc(struct IDEState *); + +/* NOTE: IDEState represents in fact one drive */ +typedef struct IDEState { + /* ide config */ + int is_cdrom; + int cylinders, heads, sectors; + int64_t nb_sectors; + int mult_sectors; + int identify_set; + uint16_t identify_data[256]; + SetIRQFunc *set_irq; + void *irq_opaque; + int irq; + //* PCIDevice *pci_dev; + struct BMDMAState *bmdma; + int drive_serial; + /* ide regs */ + uint8_t feature; + uint8_t error; + uint32_t nsector; + uint8_t sector; + uint8_t lcyl; + uint8_t hcyl; + /* other part of tf for lba48 support */ + uint8_t hob_feature; + uint8_t hob_nsector; + uint8_t hob_sector; + uint8_t hob_lcyl; + uint8_t hob_hcyl; + + uint8_t select; + uint8_t status; + + /* 0x3f6 command, only meaningful for drive 0 */ + uint8_t cmd; + /* set for lba48 access */ + uint8_t lba48; + /* depends on bit 4 in select, only meaningful for drive 0 */ + struct IDEState *cur_drive; + BlockDriverState *bs; + /* ATAPI specific */ + uint8_t sense_key; + uint8_t asc; + int packet_transfer_size; + int elementary_transfer_size; + int io_buffer_index; + int lba; + int cd_sector_size; + int atapi_dma; /* true if dma is requested for the packet cmd */ + /* ATA DMA state */ + int io_buffer_size; + /* PIO transfer handling */ + int req_nb_sectors; /* number of sectors per interrupt */ + EndTransferFunc *end_transfer_func; + uint8_t *data_ptr; + uint8_t *data_end; + uint8_t io_buffer[MAX_MULT_SECTORS*512 + 4]; + QEMUTimer *sector_write_timer; /* only used for win2k instal hack */ + uint32_t irq_count; /* counts IRQs when using win2k install hack */ +} IDEState; + +#define BM_STATUS_DMAING 0x01 +#define BM_STATUS_ERROR 0x02 +#define BM_STATUS_INT 0x04 + +#define BM_CMD_START 0x01 +#define BM_CMD_READ 0x08 + +#define IDE_TYPE_PIIX3 0 +#define IDE_TYPE_CMD646 1 + +/* CMD646 specific */ +#define MRDMODE 0x71 +#define MRDMODE_INTR_CH0 0x04 +#define MRDMODE_INTR_CH1 0x08 +#define MRDMODE_BLK_CH0 0x10 +#define MRDMODE_BLK_CH1 0x20 +#define UDIDETCR0 0x73 +#define UDIDETCR1 0x7B + +typedef struct BMDMAState { + uint8_t cmd; + uint8_t status; + uint32_t addr; + + // struct PCIIDEState *pci_dev; + /* current transfer state */ + uint32_t cur_addr; + uint32_t cur_prd_last; + uint32_t cur_prd_addr; + uint32_t cur_prd_len; + IDEState *ide_if; + BlockDriverCompletionFunc *dma_cb; + BlockDriverAIOCB *aiocb; +} BMDMAState; +struct BlockDriverState { + int64_t total_sectors; /* if we are reading a disk image, give its + size in sectors */ + int read_only; /* if true, the media is read only */ + int removable; /* if true, the media can be removed */ + int locked; /* if true, the media cannot temporarily be ejected */ + int encrypted; /* if true, the media is encrypted */ + /* event callback when inserting/removing */ + void (*change_cb)(void *opaque); + void *change_opaque; + + BlockDriver *drv; /* NULL means no media */ + void *opaque; + + int boot_sector_enabled; + uint8_t boot_sector_data[512]; + + char filename[1024]; + char backing_file[1024]; /* if non zero, the image is a diff of + this file image */ + int is_temporary; + int media_changed; + + /* async read/write emulation */ + + void *sync_aiocb; + + /* NOTE: the following infos are only hints for real hardware + drivers. They are not used by the block driver */ + int cyls, heads, secs, translation; + int type; + char device_name[32]; +}; +#if 0 +typedef struct PCIIDEState { + PCIDevice dev; + IDEState ide_if[4]; + BMDMAState bmdma[2]; + int type; /* see IDE_TYPE_xxx */ +} PCIIDEState; +#endif +static void ide_dma_start(IDEState *s, BlockDriverCompletionFunc *dma_cb); +static void ide_atapi_cmd_read_dma_cb(void *opaque, int ret); + +void cpu_physical_memory_write(u32 addr,void* ptr,u32 sz); +void cpu_physical_memory_read(u32 addr,void* ptr,u32 sz); + +static void padstr(char *str, const char *src, int len) +{ + int i, v; + for(i = 0; i < len; i++) { + if (*src) + v = *src++; + else + v = ' '; + *(char *)((long)str ^ 1) = v; + str++; + } +} + +static void padstr8(uint8_t *buf, int buf_size, const char *src) +{ + int i; + for(i = 0; i < buf_size; i++) { + if (*src) + buf[i] = *src++; + else + buf[i] = ' '; + } +} + +static void put_le16(uint16_t *p, unsigned int v) +{ + *p = (v); +} + +static void ide_identify(IDEState *s) +{ + uint16_t *p; + unsigned int oldsize; + char buf[20]; + + if (s->identify_set) { + memcpy(s->io_buffer, s->identify_data, sizeof(s->identify_data)); + return; + } + + memset(s->io_buffer, 0, 512); + p = (uint16_t *)s->io_buffer; + put_le16(p + 0, 0x0040); + put_le16(p + 1, s->cylinders); + put_le16(p + 3, s->heads); + put_le16(p + 4, 512 * s->sectors); /* XXX: retired, remove ? */ + put_le16(p + 5, 512); /* XXX: retired, remove ? */ + put_le16(p + 6, s->sectors); + snprintf(buf, sizeof(buf), "QM%05d", s->drive_serial); + padstr((char *)(p + 10), buf, 20); /* serial number */ + put_le16(p + 20, 3); /* XXX: retired, remove ? */ + put_le16(p + 21, 512); /* cache size in sectors */ + put_le16(p + 22, 4); /* ecc bytes */ + padstr((char *)(p + 23), QEMU_VERSION, 8); /* firmware version */ + padstr((char *)(p + 27), "QEMU HARDDISK", 40); /* model */ +#if MAX_MULT_SECTORS > 1 + put_le16(p + 47, 0x8000 | MAX_MULT_SECTORS); +#endif + put_le16(p + 48, 1); /* dword I/O */ + put_le16(p + 49, (1 << 11) | (1 << 9) | (1 << 8)); /* DMA and LBA supported */ + put_le16(p + 51, 0x200); /* PIO transfer cycle */ + put_le16(p + 52, 0x200); /* DMA transfer cycle */ + put_le16(p + 53, 1 | (1 << 1) | (1 << 2)); /* words 54-58,64-70,88 are valid */ + put_le16(p + 54, s->cylinders); + put_le16(p + 55, s->heads); + put_le16(p + 56, s->sectors); + oldsize = s->cylinders * s->heads * s->sectors; + put_le16(p + 57, oldsize); + put_le16(p + 58, oldsize >> 16); + if (s->mult_sectors) + put_le16(p + 59, 0x100 | s->mult_sectors); + put_le16(p + 60, s->nb_sectors); + put_le16(p + 61, s->nb_sectors >> 16); + put_le16(p + 63, 0x07); /* mdma0-2 supported */ + put_le16(p + 65, 120); + put_le16(p + 66, 120); + put_le16(p + 67, 120); + put_le16(p + 68, 120); + put_le16(p + 80, 0xf0); /* ata3 -> ata6 supported */ + put_le16(p + 81, 0x16); /* conforms to ata5 */ + put_le16(p + 82, (1 << 14)); + /* 13=flush_cache_ext,12=flush_cache,10=lba48 */ + put_le16(p + 83, (1 << 14) | (1 << 13) | (1 <<12) | (1 << 10)); + put_le16(p + 84, (1 << 14)); + put_le16(p + 85, (1 << 14)); + /* 13=flush_cache_ext,12=flush_cache,10=lba48 */ + put_le16(p + 86, (1 << 14) | (1 << 13) | (1 <<12) | (1 << 10)); + put_le16(p + 87, (1 << 14)); + put_le16(p + 88, 0x3f | (1 << 13)); /* udma5 set and supported */ + put_le16(p + 93, 1 | (1 << 14) | 0x2000); + put_le16(p + 100, s->nb_sectors); + put_le16(p + 101, s->nb_sectors >> 16); + put_le16(p + 102, s->nb_sectors >> 32); + put_le16(p + 103, s->nb_sectors >> 48); + + memcpy(s->identify_data, p, sizeof(s->identify_data)); + s->identify_set = 1; +} + +static void ide_atapi_identify(IDEState *s) +{ + uint16_t *p; + char buf[20]; + + if (s->identify_set) { + memcpy(s->io_buffer, s->identify_data, sizeof(s->identify_data)); + return; + } + + memset(s->io_buffer, 0, 512); + p = (uint16_t *)s->io_buffer; + /* Removable CDROM, 50us response, 12 byte packets */ + put_le16(p + 0, (2 << 14) | (5 << 8) | (1 << 7) | (2 << 5) | (0 << 0)); + snprintf(buf, sizeof(buf), "QM%05d", s->drive_serial); + padstr((char *)(p + 10), buf, 20); /* serial number */ + put_le16(p + 20, 3); /* buffer type */ + put_le16(p + 21, 512); /* cache size in sectors */ + put_le16(p + 22, 4); /* ecc bytes */ + padstr((char *)(p + 23), QEMU_VERSION, 8); /* firmware version */ + padstr((char *)(p + 27), "QEMU CD-ROM", 40); /* model */ + put_le16(p + 48, 1); /* dword I/O (XXX: should not be set on CDROM) */ +#ifdef USE_DMA_CDROM + put_le16(p + 49, 1 << 9 | 1 << 8); /* DMA and LBA supported */ + put_le16(p + 53, 7); /* words 64-70, 54-58, 88 valid */ + put_le16(p + 63, 7); /* mdma0-2 supported */ + put_le16(p + 64, 0x3f); /* PIO modes supported */ +#else + put_le16(p + 49, 1 << 9); /* LBA supported, no DMA */ + put_le16(p + 53, 3); /* words 64-70, 54-58 valid */ + put_le16(p + 63, 0x103); /* DMA modes XXX: may be incorrect */ + put_le16(p + 64, 1); /* PIO modes */ +#endif + put_le16(p + 65, 0xb4); /* minimum DMA multiword tx cycle time */ + put_le16(p + 66, 0xb4); /* recommended DMA multiword tx cycle time */ + put_le16(p + 67, 0x12c); /* minimum PIO cycle time without flow control */ + put_le16(p + 68, 0xb4); /* minimum PIO cycle time with IORDY flow control */ + + put_le16(p + 71, 30); /* in ns */ + put_le16(p + 72, 30); /* in ns */ + + put_le16(p + 80, 0x1e); /* support up to ATA/ATAPI-4 */ +#ifdef USE_DMA_CDROM + put_le16(p + 88, 0x3f | (1 << 13)); /* udma5 set and supported */ +#endif + memcpy(s->identify_data, p, sizeof(s->identify_data)); + s->identify_set = 1; +} + +static void ide_set_signature(IDEState *s) +{ + s->select &= 0xf0; /* clear head */ + /* put signature */ + s->nsector = 1; + s->sector = 1; + if (s->is_cdrom) { + s->lcyl = 0x14; + s->hcyl = 0xeb; + } else if (s->bs) { + s->lcyl = 0; + s->hcyl = 0; + } else { + s->lcyl = 0xff; + s->hcyl = 0xff; + } +} + +static inline void ide_abort_command(IDEState *s) +{ + s->status = READY_STAT | ERR_STAT; + s->error = ABRT_ERR; +} + +static inline void ide_set_irq(IDEState *s) +{ + BMDMAState *bm = s->bmdma; + if (!(s->cmd & IDE_CMD_DISABLE_IRQ)) { + if (bm) { + bm->status |= BM_STATUS_INT; + } + s->set_irq(s->irq_opaque, s->irq, 1); + } +} + +/* prepare data transfer and tell what to do after */ +static void ide_transfer_start(IDEState *s, uint8_t *buf, int size, + EndTransferFunc *end_transfer_func) +{ + s->end_transfer_func = end_transfer_func; + s->data_ptr = buf; + s->data_end = buf + size; + s->status |= DRQ_STAT; +} + +static void ide_transfer_stop(IDEState *s) +{ + s->end_transfer_func = ide_transfer_stop; + s->data_ptr = s->io_buffer; + s->data_end = s->io_buffer; + s->status &= ~DRQ_STAT; +} + +static int64_t ide_get_sector(IDEState *s) +{ + int64_t sector_num; + if (s->select & 0x40) { + /* lba */ + if (!s->lba48) { + sector_num = ((s->select & 0x0f) << 24) | (s->hcyl << 16) | + (s->lcyl << 8) | s->sector; + } else { + sector_num = ((int64_t)s->hob_hcyl << 40) | + ((int64_t) s->hob_lcyl << 32) | + ((int64_t) s->hob_sector << 24) | + ((int64_t) s->hcyl << 16) | + ((int64_t) s->lcyl << 8) | s->sector; + } + } else { + sector_num = ((s->hcyl << 8) | s->lcyl) * s->heads * s->sectors + + (s->select & 0x0f) * s->sectors + (s->sector - 1); + } + return sector_num; +} + +static void ide_set_sector(IDEState *s, int64_t sector_num) +{ + unsigned int cyl, r; + if (s->select & 0x40) { + if (!s->lba48) { + s->select = (s->select & 0xf0) | (sector_num >> 24); + s->hcyl = (sector_num >> 16); + s->lcyl = (sector_num >> 8); + s->sector = (sector_num); + } else { + s->sector = sector_num; + s->lcyl = sector_num >> 8; + s->hcyl = sector_num >> 16; + s->hob_sector = sector_num >> 24; + s->hob_lcyl = sector_num >> 32; + s->hob_hcyl = sector_num >> 40; + } + } else { + cyl = sector_num / (s->heads * s->sectors); + r = sector_num % (s->heads * s->sectors); + s->hcyl = cyl >> 8; + s->lcyl = cyl; + s->select = (s->select & 0xf0) | ((r / s->sectors) & 0x0f); + s->sector = (r % s->sectors) + 1; + } +} + +static void ide_sector_read(IDEState *s) +{ + int64_t sector_num; + int ret, n; + + s->status = READY_STAT | SEEK_STAT; + s->error = 0; /* not needed by IDE spec, but needed by Windows */ + sector_num = ide_get_sector(s); + n = s->nsector; + if (n == 0) { + /* no more sector to read from disk */ + ide_transfer_stop(s); + } else { +#if defined(DEBUG_IDE) + // printf("read sector=%Ld\n", sector_num); +#endif + printf("ATA: read sector=%Ld\n", sector_num); + + if (n > s->req_nb_sectors) + n = s->req_nb_sectors; + ret = bdrv_read(s->bs, sector_num, s->io_buffer, n); + ide_transfer_start(s, s->io_buffer, 512 * n, ide_sector_read); + ide_set_irq(s); + ide_set_sector(s, sector_num + n); + s->nsector -= n; + } +} + +/* return 0 if buffer completed */ +static int dma_buf_rw(BMDMAState *bm, int is_write) +{ + IDEState *s = bm->ide_if; + struct { + uint32_t addr; + uint32_t size; + } prd; + int l, len; + + for(;;) { + l = s->io_buffer_size - s->io_buffer_index; + if (l <= 0) + break; + if (bm->cur_prd_len == 0) { + /* end of table (with a fail safe of one page) */ + if (bm->cur_prd_last || + (bm->cur_addr - bm->addr) >= 4096) + return 0; + emu_printf("dma seems to have ended .. duno what the code i removed from here does.. chan dma ?\n"); + return 2; + /* + ///i wonder what is this + //lets hope its not bad to remove it here xD + cpu_physical_memory_read(bm->cur_addr, (uint8_t *)&prd, 8); + bm->cur_addr += 8; + prd.addr = le32_to_cpu(prd.addr); + prd.size = le32_to_cpu(prd.size); + len = prd.size & 0xfffe; + if (len == 0) + len = 0x10000; + bm->cur_prd_len = len; + bm->cur_prd_addr = prd.addr; + bm->cur_prd_last = (prd.size & 0x80000000);*/ + } + if (l > bm->cur_prd_len) + l = bm->cur_prd_len; + if (l > 0) { + if (is_write) { + cpu_physical_memory_write(bm->cur_prd_addr, + s->io_buffer + s->io_buffer_index, l); + } else { + cpu_physical_memory_read(bm->cur_prd_addr, + s->io_buffer + s->io_buffer_index, l); + } + bm->cur_prd_addr += l; + bm->cur_prd_len -= l; + s->io_buffer_index += l; + } + } + return 1; +} + +/* XXX: handle errors */ +static void ide_read_dma_cb(void *opaque, int ret) +{ + BMDMAState* bm = (BMDMAState* )opaque; + IDEState *s = (IDEState*)bm->ide_if; + int n; + int64_t sector_num; + + n = s->io_buffer_size >> 9; + sector_num = ide_get_sector(s); + if (n > 0) { + sector_num += n; + ide_set_sector(s, sector_num); + s->nsector -= n; + int dmrv=dma_buf_rw(bm, 1); + if ( dmrv== 0) + goto eot; + else if (dmrv==2) + { + bm->status &= ~BM_STATUS_DMAING; + bm->status |= BM_STATUS_INT; + return; //end of dma buffer (ha !) + } + } + + /* end of transfer ? */ + if (s->nsector == 0) { + s->status = READY_STAT | SEEK_STAT; + ide_set_irq(s); + eot: + bm->status &= ~BM_STATUS_DMAING; + bm->status |= BM_STATUS_INT; + bm->dma_cb = NULL; + bm->ide_if = NULL; + bm->aiocb = NULL; + return; + } + + /* launch next transfer */ + n = s->nsector; + if (n > MAX_MULT_SECTORS) + n = MAX_MULT_SECTORS; + s->io_buffer_index = 0; + s->io_buffer_size = n * 512; +#ifdef DEBUG_AIO + printf("aio_read: sector_num=%lld n=%d\n", sector_num, n); +#endif + bm->aiocb = bdrv_aio_read(s->bs, sector_num, s->io_buffer, n, + ide_read_dma_cb, bm); +} + +static void ide_sector_read_dma(IDEState *s) +{ + s->status = READY_STAT | SEEK_STAT | DRQ_STAT | BUSY_STAT; + s->io_buffer_index = 0; + s->io_buffer_size = 0; + ide_dma_start(s, ide_read_dma_cb); +} + +static void ide_sector_write_timer_cb(void *opaque) +{ + IDEState* s = (IDEState*)opaque; + ide_set_irq(s); +} + +static void ide_sector_write(IDEState *s) +{ + int64_t sector_num; + int ret, n, n1; + + s->status = READY_STAT | SEEK_STAT; + sector_num = ide_get_sector(s); +#if defined(DEBUG_IDE) + printf("write sector=%Ld\n", sector_num); +#endif + printf("ATA: write sector=%Ld\n", sector_num); + n = s->nsector; + if (n > s->req_nb_sectors) + n = s->req_nb_sectors; + ret = bdrv_write(s->bs, sector_num, s->io_buffer, n); + s->nsector -= n; + if (s->nsector == 0) { + /* no more sector to write */ + ide_transfer_stop(s); + } else { + n1 = s->nsector; + if (n1 > s->req_nb_sectors) + n1 = s->req_nb_sectors; + ide_transfer_start(s, s->io_buffer, 512 * n1, ide_sector_write); + } + ide_set_sector(s, sector_num + n); + +#ifdef TARGET_I386 + if (win2k_install_hack && ((++s->irq_count % 16) == 0)) { + /* It seems there is a bug in the Windows 2000 installer HDD + IDE driver which fills the disk with empty logs when the + IDE write IRQ comes too early. This hack tries to correct + that at the expense of slower write performances. Use this + option _only_ to install Windows 2000. You must disable it + for normal use. */ + qemu_mod_timer(s->sector_write_timer, + qemu_get_clock(vm_clock) + (ticks_per_sec / 1000)); + } else +#endif + { + ide_set_irq(s); + } +} + +/* XXX: handle errors */ +static void ide_write_dma_cb(void *opaque, int ret) +{ + BMDMAState* bm =(BMDMAState*)opaque; + IDEState* s =(IDEState* ) bm->ide_if; + int n; + int64_t sector_num; + + n = s->io_buffer_size >> 9; + sector_num = ide_get_sector(s); + if (n > 0) { + sector_num += n; + ide_set_sector(s, sector_num); + s->nsector -= n; + } + + /* end of transfer ? */ + if (s->nsector == 0) { + s->status = READY_STAT | SEEK_STAT; + ide_set_irq(s); + eot: + bm->status &= ~BM_STATUS_DMAING; + bm->status |= BM_STATUS_INT; + bm->dma_cb = NULL; + bm->ide_if = NULL; + bm->aiocb = NULL; + return; + } + + /* launch next transfer */ + n = s->nsector; + if (n > MAX_MULT_SECTORS) + n = MAX_MULT_SECTORS; + s->io_buffer_index = 0; + s->io_buffer_size = n * 512; + + int dmrv=dma_buf_rw(bm, 0); + if ( dmrv== 0) + goto eot; + else if (dmrv==2) + { + bm->status &= ~BM_STATUS_DMAING; + bm->status |= BM_STATUS_INT; + return; //end of dma buffer (ha !) + } + +#ifdef DEBUG_AIO + printf("aio_write: sector_num=%lld n=%d\n", sector_num, n); +#endif + bm->aiocb = bdrv_aio_write(s->bs, sector_num, s->io_buffer, n, + ide_write_dma_cb, bm); +} + +static void ide_sector_write_dma(IDEState *s) +{ + s->status = READY_STAT | SEEK_STAT | DRQ_STAT | BUSY_STAT; + s->io_buffer_index = 0; + s->io_buffer_size = 0; + ide_dma_start(s, ide_write_dma_cb); +} + +static void ide_atapi_cmd_ok(IDEState *s) +{ + s->error = 0; + s->status = READY_STAT; + s->nsector = (s->nsector & ~7) | ATAPI_INT_REASON_IO | ATAPI_INT_REASON_CD; + ide_set_irq(s); +} + +static void ide_atapi_cmd_error(IDEState *s, int sense_key, int asc) +{ +#ifdef DEBUG_IDE_ATAPI + //printf("atapi_cmd_error: sense=0x%x asc=0x%x\n", sense_key, asc); +#endif + printf("atapi_cmd_error: sense=0x%x asc=0x%x\n", sense_key, asc); + s->error = sense_key << 4; + s->status = READY_STAT | ERR_STAT; + s->nsector = (s->nsector & ~7) | ATAPI_INT_REASON_IO | ATAPI_INT_REASON_CD; + s->sense_key = sense_key; + s->asc = asc; + ide_set_irq(s); +} + +static inline void cpu_to_ube16(uint8_t *buf, int val) +{ + buf[0] = val >> 8; + buf[1] = val; +} + +static inline void cpu_to_ube32(uint8_t *buf, unsigned int val) +{ + buf[0] = val >> 24; + buf[1] = val >> 16; + buf[2] = val >> 8; + buf[3] = val; +} + +static inline int ube16_to_cpu(const uint8_t *buf) +{ + return (buf[0] << 8) | buf[1]; +} + +static inline int ube32_to_cpu(const uint8_t *buf) +{ + return (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3]; +} + +static void lba_to_msf(uint8_t *buf, int lba) +{ + lba += 150; + buf[0] = (lba / 75) / 60; + buf[1] = (lba / 75) % 60; + buf[2] = lba % 75; +} + +static void cd_data_to_raw(uint8_t *buf, int lba) +{ + /* sync bytes */ + buf[0] = 0x00; + memset(buf + 1, 0xff, 10); + buf[11] = 0x00; + buf += 12; + /* MSF */ + lba_to_msf(buf, lba); + buf[3] = 0x01; /* mode 1 data */ + buf += 4; + /* data */ + buf += 2048; + /* XXX: ECC not computed */ + memset(buf, 0, 288); +} + +static int cd_read_sector(BlockDriverState *bs, int lba, uint8_t *buf, + int sector_size) +{ + int ret; + + switch(sector_size) { + case 2048: + ret = bdrv_read(bs, (int64_t)lba << 2, buf, 4); + break; + case 2352: + ret = bdrv_read(bs, (int64_t)lba << 2, buf + 16, 4); + if (ret < 0) + return ret; + cd_data_to_raw(buf, lba); + break; + default: + ret = -EIO; + break; + } + return ret; +} + +static void ide_atapi_io_error(IDEState *s, int ret) +{ + /* XXX: handle more errors */ + if (ret == -ENOMEDIUM) { + ide_atapi_cmd_error(s, SENSE_NOT_READY, + ASC_MEDIUM_NOT_PRESENT); + } else { + ide_atapi_cmd_error(s, SENSE_ILLEGAL_REQUEST, + ASC_LOGICAL_BLOCK_OOR); + } +} + +/* The whole ATAPI transfer logic is handled in this function */ +static void ide_atapi_cmd_reply_end(IDEState *s) +{ + int byte_count_limit, size, ret; +#ifdef DEBUG_IDE_ATAPI + printf("reply: tx_size=%d elem_tx_size=%d index=%d\n", + s->packet_transfer_size, + s->elementary_transfer_size, + s->io_buffer_index); +#endif + if (s->packet_transfer_size <= 0) { + /* end of transfer */ + ide_transfer_stop(s); + s->status = READY_STAT; + s->nsector = (s->nsector & ~7) | ATAPI_INT_REASON_IO | ATAPI_INT_REASON_CD; + ide_set_irq(s); +#ifdef DEBUG_IDE_ATAPI + printf("status=0x%x\n", s->status); +#endif + } else { + /* see if a new sector must be read */ + if (s->lba != -1 && s->io_buffer_index >= s->cd_sector_size) { + ret = cd_read_sector(s->bs, s->lba, s->io_buffer, s->cd_sector_size); + if (ret < 0) { + ide_transfer_stop(s); + ide_atapi_io_error(s, ret); + return; + } + s->lba++; + s->io_buffer_index = 0; + } + if (s->elementary_transfer_size > 0) { + /* there are some data left to transmit in this elementary + transfer */ + size = s->cd_sector_size - s->io_buffer_index; + if (size > s->elementary_transfer_size) + size = s->elementary_transfer_size; + ide_transfer_start(s, s->io_buffer + s->io_buffer_index, + size, ide_atapi_cmd_reply_end); + s->packet_transfer_size -= size; + s->elementary_transfer_size -= size; + s->io_buffer_index += size; + } else { + /* a new transfer is needed */ + s->nsector = (s->nsector & ~7) | ATAPI_INT_REASON_IO; + byte_count_limit = s->lcyl | (s->hcyl << 8); +#ifdef DEBUG_IDE_ATAPI + printf("byte_count_limit=%d\n", byte_count_limit); +#endif + if (byte_count_limit == 0xffff) + byte_count_limit--; + size = s->packet_transfer_size; + if (size > byte_count_limit) { + /* byte count limit must be even if this case */ + if (byte_count_limit & 1) + byte_count_limit--; + size = byte_count_limit; + } + s->lcyl = size; + s->hcyl = size >> 8; + s->elementary_transfer_size = size; + /* we cannot transmit more than one sector at a time */ + if (s->lba != -1) { + if (size > (s->cd_sector_size - s->io_buffer_index)) + size = (s->cd_sector_size - s->io_buffer_index); + } + ide_transfer_start(s, s->io_buffer + s->io_buffer_index, + size, ide_atapi_cmd_reply_end); + s->packet_transfer_size -= size; + s->elementary_transfer_size -= size; + s->io_buffer_index += size; + ide_set_irq(s); +#ifdef DEBUG_IDE_ATAPI + printf("status=0x%x\n", s->status); +#endif + } + } +} + +/* send a reply of 'size' bytes in s->io_buffer to an ATAPI command */ +static void ide_atapi_cmd_reply(IDEState *s, int size, int max_size) +{ + if (size > max_size) + size = max_size; + s->lba = -1; /* no sector read */ + s->packet_transfer_size = size; + s->io_buffer_size = size; /* dma: send the reply data as one chunk */ + s->elementary_transfer_size = 0; + s->io_buffer_index = 0; + + if (s->atapi_dma) { + s->status = READY_STAT | DRQ_STAT; + ide_dma_start(s, ide_atapi_cmd_read_dma_cb); + } else { + s->status = READY_STAT; + ide_atapi_cmd_reply_end(s); + } +} + +/* start a CD-CDROM read command */ +static void ide_atapi_cmd_read_pio(IDEState *s, int lba, int nb_sectors, + int sector_size) +{ + s->lba = lba; + s->packet_transfer_size = nb_sectors * sector_size; + s->elementary_transfer_size = 0; + s->io_buffer_index = sector_size; + s->cd_sector_size = sector_size; + + s->status = READY_STAT; + ide_atapi_cmd_reply_end(s); +} + +/* ATAPI DMA support */ + +/* XXX: handle read errors */ +static void ide_atapi_cmd_read_dma_cb(void *opaque, int ret) +{ + BMDMAState* bm =(BMDMAState*) opaque; + IDEState* s =(IDEState*) bm->ide_if; + int data_offset, n; + + if (ret < 0) { + ide_atapi_io_error(s, ret); + goto eot; + } + + if (s->io_buffer_size > 0) { + /* + * For a cdrom read sector command (s->lba != -1), + * adjust the lba for the next s->io_buffer_size chunk + * and dma the current chunk. + * For a command != read (s->lba == -1), just transfer + * the reply data. + */ + if (s->lba != -1) { + if (s->cd_sector_size == 2352) { + n = 1; + cd_data_to_raw(s->io_buffer, s->lba); + } else { + n = s->io_buffer_size >> 11; + } + s->lba += n; + } + s->packet_transfer_size -= s->io_buffer_size; + if (dma_buf_rw(bm, 1) == 0) + goto eot; + } + + if (s->packet_transfer_size <= 0) { + s->status = READY_STAT; + s->nsector = (s->nsector & ~7) | ATAPI_INT_REASON_IO | ATAPI_INT_REASON_CD; + ide_set_irq(s); + eot: + bm->status &= ~BM_STATUS_DMAING; + bm->status |= BM_STATUS_INT; + bm->dma_cb = NULL; + bm->ide_if = NULL; + bm->aiocb = NULL; + return; + } + + s->io_buffer_index = 0; + if (s->cd_sector_size == 2352) { + n = 1; + s->io_buffer_size = s->cd_sector_size; + data_offset = 16; + } else { + n = s->packet_transfer_size >> 11; + if (n > (MAX_MULT_SECTORS / 4)) + n = (MAX_MULT_SECTORS / 4); + s->io_buffer_size = n * 2048; + data_offset = 0; + } +#ifdef DEBUG_AIO + printf("aio_read_cd: lba=%u n=%d\n", s->lba, n); +#endif + bm->aiocb = bdrv_aio_read(s->bs, (int64_t)s->lba << 2, + s->io_buffer + data_offset, n * 4, + ide_atapi_cmd_read_dma_cb, bm); + if (!bm->aiocb) { + /* Note: media not present is the most likely case */ + ide_atapi_cmd_error(s, SENSE_NOT_READY, + ASC_MEDIUM_NOT_PRESENT); + goto eot; + } +} + +/* start a CD-CDROM read command with DMA */ +/* XXX: test if DMA is available */ +static void ide_atapi_cmd_read_dma(IDEState *s, int lba, int nb_sectors, + int sector_size) +{ + s->lba = lba; + s->packet_transfer_size = nb_sectors * sector_size; + s->io_buffer_index = 0; + s->io_buffer_size = 0; + s->cd_sector_size = sector_size; + + /* XXX: check if BUSY_STAT should be set */ + s->status = READY_STAT | DRQ_STAT | BUSY_STAT; + ide_dma_start(s, ide_atapi_cmd_read_dma_cb); +} + +static void ide_atapi_cmd_read(IDEState *s, int lba, int nb_sectors, + int sector_size) +{ +#ifdef DEBUG_IDE_ATAPI + printf("read %s: LBA=%d nb_sectors=%d\n", s->atapi_dma ? "dma" : "pio", + lba, nb_sectors); +#endif + if (s->atapi_dma) { + ide_atapi_cmd_read_dma(s, lba, nb_sectors, sector_size); + } else { + ide_atapi_cmd_read_pio(s, lba, nb_sectors, sector_size); + } +} + +static void ide_atapi_cmd(IDEState *s) +{ + const uint8_t *packet; + uint8_t *buf; + int max_len; + + packet = s->io_buffer; + buf = s->io_buffer; +#ifdef DEBUG_IDE_ATAPI + { + int i; + printf("ATAPI limit=0x%x packet:", s->lcyl | (s->hcyl << 8)); + for(i = 0; i < ATAPI_PACKET_SIZE; i++) { + printf(" %02x", packet[i]); + } + printf("\n"); + } +#endif + switch(s->io_buffer[0]) { + case GPCMD_TEST_UNIT_READY: + if (bdrv_is_inserted(s->bs)) { + ide_atapi_cmd_ok(s); + } else { + ide_atapi_cmd_error(s, SENSE_NOT_READY, + ASC_MEDIUM_NOT_PRESENT); + } + break; + case GPCMD_MODE_SENSE_10: + { + int action, code; + max_len = ube16_to_cpu(packet + 7); + action = packet[2] >> 6; + code = packet[2] & 0x3f; + switch(action) { + case 0: /* current values */ + switch(code) { + case 0x01: /* error recovery */ + cpu_to_ube16(&buf[0], 16 + 6); + buf[2] = 0x70; + buf[3] = 0; + buf[4] = 0; + buf[5] = 0; + buf[6] = 0; + buf[7] = 0; + + buf[8] = 0x01; + buf[9] = 0x06; + buf[10] = 0x00; + buf[11] = 0x05; + buf[12] = 0x00; + buf[13] = 0x00; + buf[14] = 0x00; + buf[15] = 0x00; + ide_atapi_cmd_reply(s, 16, max_len); + break; + case 0x2a: + cpu_to_ube16(&buf[0], 28 + 6); + buf[2] = 0x70; + buf[3] = 0; + buf[4] = 0; + buf[5] = 0; + buf[6] = 0; + buf[7] = 0; + + buf[8] = 0x2a; + buf[9] = 0x12; + buf[10] = 0x00; + buf[11] = 0x00; + + buf[12] = 0x70; + buf[13] = 3 << 5; + buf[14] = (1 << 0) | (1 << 3) | (1 << 5); + if (bdrv_is_locked(s->bs)) + buf[6] |= 1 << 1; + buf[15] = 0x00; + cpu_to_ube16(&buf[16], 706); + buf[18] = 0; + buf[19] = 2; + cpu_to_ube16(&buf[20], 512); + cpu_to_ube16(&buf[22], 706); + buf[24] = 0; + buf[25] = 0; + buf[26] = 0; + buf[27] = 0; + ide_atapi_cmd_reply(s, 28, max_len); + break; + default: + goto error_cmd; + } + break; + case 1: /* changeable values */ + goto error_cmd; + case 2: /* default values */ + goto error_cmd; + default: + case 3: /* saved values */ + ide_atapi_cmd_error(s, SENSE_ILLEGAL_REQUEST, + ASC_SAVING_PARAMETERS_NOT_SUPPORTED); + break; + } + } + break; + case GPCMD_REQUEST_SENSE: + max_len = packet[4]; + memset(buf, 0, 18); + buf[0] = 0x70 | (1 << 7); + buf[2] = s->sense_key; + buf[7] = 10; + buf[12] = s->asc; + ide_atapi_cmd_reply(s, 18, max_len); + break; + case GPCMD_PREVENT_ALLOW_MEDIUM_REMOVAL: + if (bdrv_is_inserted(s->bs)) { + bdrv_set_locked(s->bs, packet[4] & 1); + ide_atapi_cmd_ok(s); + } else { + ide_atapi_cmd_error(s, SENSE_NOT_READY, + ASC_MEDIUM_NOT_PRESENT); + } + break; + case GPCMD_READ_10: + case GPCMD_READ_12: + { + int nb_sectors, lba; + + if (packet[0] == GPCMD_READ_10) + nb_sectors = ube16_to_cpu(packet + 7); + else + nb_sectors = ube32_to_cpu(packet + 6); + lba = ube32_to_cpu(packet + 2); + if (nb_sectors == 0) { + ide_atapi_cmd_ok(s); + break; + } + ide_atapi_cmd_read(s, lba, nb_sectors, 2048); + } + break; + case GPCMD_READ_CD: + { + int nb_sectors, lba, transfer_request; + + nb_sectors = (packet[6] << 16) | (packet[7] << 8) | packet[8]; + lba = ube32_to_cpu(packet + 2); + if (nb_sectors == 0) { + ide_atapi_cmd_ok(s); + break; + } + transfer_request = packet[9]; + switch(transfer_request & 0xf8) { + case 0x00: + /* nothing */ + ide_atapi_cmd_ok(s); + break; + case 0x10: + /* normal read */ + ide_atapi_cmd_read(s, lba, nb_sectors, 2048); + break; + case 0xf8: + /* read all data */ + ide_atapi_cmd_read(s, lba, nb_sectors, 2352); + break; + default: + ide_atapi_cmd_error(s, SENSE_ILLEGAL_REQUEST, + ASC_INV_FIELD_IN_CMD_PACKET); + break; + } + } + break; + case GPCMD_SEEK: + { + int lba; + int64_t total_sectors; + + bdrv_get_geometry(s->bs, &total_sectors); + total_sectors >>= 2; + if (total_sectors <= 0) { + ide_atapi_cmd_error(s, SENSE_NOT_READY, + ASC_MEDIUM_NOT_PRESENT); + break; + } + lba = ube32_to_cpu(packet + 2); + if (lba >= total_sectors) { + ide_atapi_cmd_error(s, SENSE_ILLEGAL_REQUEST, + ASC_LOGICAL_BLOCK_OOR); + break; + } + ide_atapi_cmd_ok(s); + } + break; + case GPCMD_START_STOP_UNIT: + { + int start, eject; + start = packet[4] & 1; + eject = (packet[4] >> 1) & 1; + + if (eject && !start) { + /* eject the disk */ + bdrv_eject(s->bs, 1); + } else if (eject && start) { + /* close the tray */ + bdrv_eject(s->bs, 0); + } + ide_atapi_cmd_ok(s); + } + break; + case GPCMD_MECHANISM_STATUS: + { + max_len = ube16_to_cpu(packet + 8); + cpu_to_ube16(buf, 0); + /* no current LBA */ + buf[2] = 0; + buf[3] = 0; + buf[4] = 0; + buf[5] = 1; + cpu_to_ube16(buf + 6, 0); + ide_atapi_cmd_reply(s, 8, max_len); + } + break; + case GPCMD_READ_TOC_PMA_ATIP: + { + int format, msf, start_track, len; + int64_t total_sectors; + + bdrv_get_geometry(s->bs, &total_sectors); + total_sectors >>= 2; + if (total_sectors <= 0) { + ide_atapi_cmd_error(s, SENSE_NOT_READY, + ASC_MEDIUM_NOT_PRESENT); + break; + } + max_len = ube16_to_cpu(packet + 7); + format = packet[9] >> 6; + msf = (packet[1] >> 1) & 1; + start_track = packet[6]; + switch(format) { + case 0: + emu_printf("CDROM ?TOC?\n"); + len = -1;//cdrom_read_toc(total_sectors, buf, msf, start_track); + if (len < 0) + goto error_cmd; + ide_atapi_cmd_reply(s, len, max_len); + break; + case 1: + /* multi session : only a single session defined */ + memset(buf, 0, 12); + buf[1] = 0x0a; + buf[2] = 0x01; + buf[3] = 0x01; + ide_atapi_cmd_reply(s, 12, max_len); + break; + case 2: + emu_printf("CDROM ?TOC?\n"); + len = -1;// + // len = cdrom_read_toc_raw(total_sectors, buf, msf, start_track); + if (len < 0) + goto error_cmd; + ide_atapi_cmd_reply(s, len, max_len); + break; + default: + error_cmd: + ide_atapi_cmd_error(s, SENSE_ILLEGAL_REQUEST, + ASC_INV_FIELD_IN_CMD_PACKET); + break; + } + } + break; + case GPCMD_READ_CDVD_CAPACITY: + { + int64_t total_sectors; + + bdrv_get_geometry(s->bs, &total_sectors); + total_sectors >>= 2; + if (total_sectors <= 0) { + ide_atapi_cmd_error(s, SENSE_NOT_READY, + ASC_MEDIUM_NOT_PRESENT); + break; + } + /* NOTE: it is really the number of sectors minus 1 */ + cpu_to_ube32(buf, total_sectors - 1); + cpu_to_ube32(buf + 4, 2048); + ide_atapi_cmd_reply(s, 8, 8); + } + break; + case GPCMD_INQUIRY: + max_len = packet[4]; + buf[0] = 0x05; /* CD-ROM */ + buf[1] = 0x80; /* removable */ + buf[2] = 0x00; /* ISO */ + buf[3] = 0x21; /* ATAPI-2 (XXX: put ATAPI-4 ?) */ + buf[4] = 31; /* additionnal length */ + buf[5] = 0; /* reserved */ + buf[6] = 0; /* reserved */ + buf[7] = 0; /* reserved */ + padstr8(buf + 8, 8, "QEMU"); + padstr8(buf + 16, 16, "QEMU CD-ROM"); + padstr8(buf + 32, 4, QEMU_VERSION); + ide_atapi_cmd_reply(s, 36, max_len); + break; + default: + ide_atapi_cmd_error(s, SENSE_ILLEGAL_REQUEST, + ASC_ILLEGAL_OPCODE); + break; + } +} + +/* called when the inserted state of the media has changed */ +static void cdrom_change_cb(void *opaque) +{ + IDEState* s = (IDEState*)opaque; + int64_t nb_sectors; + + /* XXX: send interrupt too */ + bdrv_get_geometry(s->bs, &nb_sectors); + s->nb_sectors = nb_sectors; +} + +static void ide_cmd_lba48_transform(IDEState *s, int lba48) +{ + s->lba48 = lba48; + + /* handle the 'magic' 0 nsector count conversion here. to avoid + * fiddling with the rest of the read logic, we just store the + * full sector count in ->nsector and ignore ->hob_nsector from now + */ + if (!s->lba48) { + if (!s->nsector) + s->nsector = 256; + } else { + if (!s->nsector && !s->hob_nsector) + s->nsector = 65536; + else { + int lo = s->nsector; + int hi = s->hob_nsector; + + s->nsector = (hi << 8) | lo; + } + } +} + +static void ide_clear_hob(IDEState *ide_if) +{ + /* any write clears HOB high bit of device control register */ + ide_if[0].select &= ~(1 << 7); + ide_if[1].select &= ~(1 << 7); +} + +static void ide_ioport_write(void *opaque, uint32_t addr, uint32_t val) +{ + IDEState *ide_if =(IDEState*)opaque; + IDEState *s; + int unit, n; + int lba48 = 0; + +#ifdef DEBUG_IDE + printf("IDE: write addr=0x%x val=0x%02x\n", addr, val); +#endif + + addr &= 7; + switch(addr) { + case 0: + break; + case 1: + ide_clear_hob(ide_if); + /* NOTE: data is written to the two drives */ + ide_if[0].hob_feature = ide_if[0].feature; + ide_if[1].hob_feature = ide_if[1].feature; + ide_if[0].feature = val; + ide_if[1].feature = val; + break; + case 2: + ide_clear_hob(ide_if); + ide_if[0].hob_nsector = ide_if[0].nsector; + ide_if[1].hob_nsector = ide_if[1].nsector; + ide_if[0].nsector = val; + ide_if[1].nsector = val; + break; + case 3: + ide_clear_hob(ide_if); + ide_if[0].hob_sector = ide_if[0].sector; + ide_if[1].hob_sector = ide_if[1].sector; + ide_if[0].sector = val; + ide_if[1].sector = val; + break; + case 4: + ide_clear_hob(ide_if); + ide_if[0].hob_lcyl = ide_if[0].lcyl; + ide_if[1].hob_lcyl = ide_if[1].lcyl; + ide_if[0].lcyl = val; + ide_if[1].lcyl = val; + break; + case 5: + ide_clear_hob(ide_if); + ide_if[0].hob_hcyl = ide_if[0].hcyl; + ide_if[1].hob_hcyl = ide_if[1].hcyl; + ide_if[0].hcyl = val; + ide_if[1].hcyl = val; + break; + case 6: + /* FIXME: HOB readback uses bit 7 */ + ide_if[0].select = (val & ~0x10) | 0xa0; + ide_if[1].select = (val | 0x10) | 0xa0; + /* select drive */ + unit = (val >> 4) & 1; + s = ide_if + unit; + ide_if->cur_drive = s; + break; + default: + case 7: + /* command */ +#if defined(DEBUG_IDE) + printf("ide: CMD=%02x\n", val); +#endif + s = ide_if->cur_drive; + /* ignore commands to non existant slave */ + if (s != ide_if && !s->bs) + break; + + switch(val) { + case WIN_IDENTIFY: + if (s->bs && !s->is_cdrom) { + ide_identify(s); + s->status = READY_STAT | SEEK_STAT; + ide_transfer_start(s, s->io_buffer, 512, ide_transfer_stop); + } else { + if (s->is_cdrom) { + ide_set_signature(s); + } + ide_abort_command(s); + } + ide_set_irq(s); + break; + case WIN_SPECIFY: + case WIN_RECAL: + s->error = 0; + s->status = READY_STAT | SEEK_STAT; + ide_set_irq(s); + break; + case WIN_SETMULT: + if (s->nsector > MAX_MULT_SECTORS || + s->nsector == 0 || + (s->nsector & (s->nsector - 1)) != 0) { + ide_abort_command(s); + } else { + s->mult_sectors = s->nsector; + s->status = READY_STAT; + } + ide_set_irq(s); + break; + case WIN_VERIFY_EXT: + lba48 = 1; + case WIN_VERIFY: + case WIN_VERIFY_ONCE: + /* do sector number check ? */ + ide_cmd_lba48_transform(s, lba48); + s->status = READY_STAT; + ide_set_irq(s); + break; + case WIN_READ_EXT: + lba48 = 1; + case WIN_READ: + case WIN_READ_ONCE: + if (!s->bs) + goto abort_cmd; + ide_cmd_lba48_transform(s, lba48); + s->req_nb_sectors = 1; + ide_sector_read(s); + break; + case WIN_WRITE_EXT: + lba48 = 1; + case WIN_WRITE: + case WIN_WRITE_ONCE: + ide_cmd_lba48_transform(s, lba48); + s->error = 0; + s->status = SEEK_STAT | READY_STAT; + s->req_nb_sectors = 1; + ide_transfer_start(s, s->io_buffer, 512, ide_sector_write); + break; + case WIN_MULTREAD_EXT: + lba48 = 1; + case WIN_MULTREAD: + if (!s->mult_sectors) + goto abort_cmd; + ide_cmd_lba48_transform(s, lba48); + s->req_nb_sectors = s->mult_sectors; + ide_sector_read(s); + break; + case WIN_MULTWRITE_EXT: + lba48 = 1; + case WIN_MULTWRITE: + if (!s->mult_sectors) + goto abort_cmd; + ide_cmd_lba48_transform(s, lba48); + s->error = 0; + s->status = SEEK_STAT | READY_STAT; + s->req_nb_sectors = s->mult_sectors; + n = s->nsector; + if (n > s->req_nb_sectors) + n = s->req_nb_sectors; + ide_transfer_start(s, s->io_buffer, 512 * n, ide_sector_write); + break; + case WIN_READDMA_EXT: + lba48 = 1; + case WIN_READDMA: + case WIN_READDMA_ONCE: + if (!s->bs) + goto abort_cmd; + ide_cmd_lba48_transform(s, lba48); + ide_sector_read_dma(s); + break; + case WIN_WRITEDMA_EXT: + lba48 = 1; + case WIN_WRITEDMA: + case WIN_WRITEDMA_ONCE: + if (!s->bs) + goto abort_cmd; + ide_cmd_lba48_transform(s, lba48); + ide_sector_write_dma(s); + break; + case WIN_READ_NATIVE_MAX_EXT: + lba48 = 1; + case WIN_READ_NATIVE_MAX: + ide_cmd_lba48_transform(s, lba48); + ide_set_sector(s, s->nb_sectors - 1); + s->status = READY_STAT; + ide_set_irq(s); + break; + case WIN_CHECKPOWERMODE1: + s->nsector = 0xff; /* device active or idle */ + s->status = READY_STAT; + ide_set_irq(s); + break; + case WIN_SETFEATURES: + if (!s->bs) + goto abort_cmd; + /* XXX: valid for CDROM ? */ + switch(s->feature) { + case 0x02: /* write cache enable */ + case 0x82: /* write cache disable */ + case 0xaa: /* read look-ahead enable */ + case 0x55: /* read look-ahead disable */ + s->status = READY_STAT | SEEK_STAT; + ide_set_irq(s); + break; + case 0x03: { /* set transfer mode */ + uint8_t val = s->nsector & 0x07; + + switch (s->nsector >> 3) { + case 0x00: /* pio default */ + case 0x01: /* pio mode */ + put_le16(s->identify_data + 63,0x07); + put_le16(s->identify_data + 88,0x3f); + break; + case 0x04: /* mdma mode */ + put_le16(s->identify_data + 63,0x07 | (1 << (val + 8))); + put_le16(s->identify_data + 88,0x3f); + break; + case 0x08: /* udma mode */ + put_le16(s->identify_data + 63,0x07); + put_le16(s->identify_data + 88,0x3f | (1 << (val + 8))); + break; + default: + goto abort_cmd; + } + s->status = READY_STAT | SEEK_STAT; + ide_set_irq(s); + break; + } + default: + goto abort_cmd; + } + break; + case WIN_FLUSH_CACHE: + case WIN_FLUSH_CACHE_EXT: + if (s->bs) + bdrv_flush(s->bs); + s->status = READY_STAT; + ide_set_irq(s); + break; + case WIN_STANDBYNOW1: + case WIN_IDLEIMMEDIATE: + s->status = READY_STAT; + ide_set_irq(s); + break; + /* ATAPI commands */ + case WIN_PIDENTIFY: + if (s->is_cdrom) { + ide_atapi_identify(s); + s->status = READY_STAT | SEEK_STAT; + ide_transfer_start(s, s->io_buffer, 512, ide_transfer_stop); + } else { + ide_abort_command(s); + } + ide_set_irq(s); + break; + case WIN_DIAGNOSE: + ide_set_signature(s); + s->status = 0x00; /* NOTE: READY is _not_ set */ + s->error = 0x01; + break; + case WIN_SRST: + if (!s->is_cdrom) + goto abort_cmd; + ide_set_signature(s); + s->status = 0x00; /* NOTE: READY is _not_ set */ + s->error = 0x01; + break; + case WIN_PACKETCMD: + if (!s->is_cdrom) + goto abort_cmd; + /* overlapping commands not supported */ + if (s->feature & 0x02) + goto abort_cmd; + s->atapi_dma = s->feature & 1; + s->nsector = 1; + ide_transfer_start(s, s->io_buffer, ATAPI_PACKET_SIZE, + ide_atapi_cmd); + break; + default: + abort_cmd: + ide_abort_command(s); + ide_set_irq(s); + break; + } + } +} + +static uint32_t ide_ioport_read(void *opaque, uint32_t addr1) +{ + IDEState *ide_if = (IDEState*)opaque; + IDEState *s = (IDEState*)ide_if->cur_drive; + uint32_t addr; + int ret, hob; + + addr = addr1 & 7; + /* FIXME: HOB readback uses bit 7, but it's always set right now */ + //hob = s->select & (1 << 7); + hob = 0; + switch(addr) { + case 0: + ret = 0xff; + break; + case 1: + if (!ide_if[0].bs && !ide_if[1].bs) + ret = 0; + else if (!hob) + ret = s->error; + else + ret = s->hob_feature; + break; + case 2: + if (!ide_if[0].bs && !ide_if[1].bs) + ret = 0; + else if (!hob) + ret = s->nsector & 0xff; + else + ret = s->hob_nsector; + break; + case 3: + if (!ide_if[0].bs && !ide_if[1].bs) + ret = 0; + else if (!hob) + ret = s->sector; + else + ret = s->hob_sector; + break; + case 4: + if (!ide_if[0].bs && !ide_if[1].bs) + ret = 0; + else if (!hob) + ret = s->lcyl; + else + ret = s->hob_lcyl; + break; + case 5: + if (!ide_if[0].bs && !ide_if[1].bs) + ret = 0; + else if (!hob) + ret = s->hcyl; + else + ret = s->hob_hcyl; + break; + case 6: + if (!ide_if[0].bs && !ide_if[1].bs) + ret = 0; + else + ret = s->select; + break; + default: + case 7: + if ((!ide_if[0].bs && !ide_if[1].bs) || + (s != ide_if && !s->bs)) + ret = 0; + else + ret = s->status; + s->set_irq(s->irq_opaque, s->irq, 0); + break; + } +#ifdef DEBUG_IDE + printf("ide: read addr=0x%x val=%02x\n", addr1, ret); +#endif + return ret; +} + +static uint32_t ide_status_read(void *opaque, uint32_t addr) +{ + IDEState *ide_if =(IDEState*) opaque; + IDEState *s = (IDEState*)ide_if->cur_drive; + int ret; + + if ((!ide_if[0].bs && !ide_if[1].bs) || + (s != ide_if && !s->bs)) + ret = 0; + else + ret = s->status; +#ifdef DEBUG_IDE + printf("ide: read status addr=0x%x val=%02x\n", addr, ret); +#endif + return ret; +} + +static void ide_cmd_write(void *opaque, uint32_t addr, uint32_t val) +{ + IDEState *ide_if = (IDEState*)opaque; + IDEState *s; + int i; + +#ifdef DEBUG_IDE + printf("ide: write control addr=0x%x val=%02x\n", addr, val); +#endif + /* common for both drives */ + if (!(ide_if[0].cmd & IDE_CMD_RESET) && + (val & IDE_CMD_RESET)) { + /* reset low to high */ + for(i = 0;i < 2; i++) { + s = &ide_if[i]; + s->status = BUSY_STAT | SEEK_STAT; + s->error = 0x01; + } + } else if ((ide_if[0].cmd & IDE_CMD_RESET) && + !(val & IDE_CMD_RESET)) { + /* high to low */ + for(i = 0;i < 2; i++) { + s = &ide_if[i]; + if (s->is_cdrom) + s->status = 0x00; /* NOTE: READY is _not_ set */ + else + s->status = READY_STAT | SEEK_STAT; + ide_set_signature(s); + } + } + + ide_if[0].cmd = val; + ide_if[1].cmd = val; +} + +static void ide_data_writew(void *opaque, uint32_t addr, uint32_t val) +{ + IDEState *s = ((IDEState *)opaque)->cur_drive; + uint8_t *p; + + p = s->data_ptr; + *(uint16_t *)p = le16_to_cpu(val); + p += 2; + s->data_ptr = p; + if (p >= s->data_end) + s->end_transfer_func(s); +} + +static uint32_t ide_data_readw(void *opaque, uint32_t addr) +{ + IDEState *s = ((IDEState *)opaque)->cur_drive; + uint8_t *p; + int ret; + p = s->data_ptr; + ret = cpu_to_le16(*(uint16_t *)p); + p += 2; + s->data_ptr = p; + if (p >= s->data_end) + s->end_transfer_func(s); + return ret; +} + +static void ide_data_writel(void *opaque, uint32_t addr, uint32_t val) +{ + IDEState *s = ((IDEState *)opaque)->cur_drive; + uint8_t *p; + + p = s->data_ptr; + *(uint32_t *)p = le32_to_cpu(val); + p += 4; + s->data_ptr = p; + if (p >= s->data_end) + s->end_transfer_func(s); +} + +static uint32_t ide_data_readl(void *opaque, uint32_t addr) +{ + IDEState *s = ((IDEState *)opaque)->cur_drive; + uint8_t *p; + int ret; + + p = s->data_ptr; + ret = cpu_to_le32(*(uint32_t *)p); + p += 4; + s->data_ptr = p; + if (p >= s->data_end) + s->end_transfer_func(s); + return ret; +} + +static void ide_dummy_transfer_stop(IDEState *s) +{ + s->data_ptr = s->io_buffer; + s->data_end = s->io_buffer; + s->io_buffer[0] = 0xff; + s->io_buffer[1] = 0xff; + s->io_buffer[2] = 0xff; + s->io_buffer[3] = 0xff; +} + +static void ide_reset(IDEState *s) +{ + s->mult_sectors = MAX_MULT_SECTORS; + s->cur_drive = s; + s->select = 0xa0; + s->status = READY_STAT; + ide_set_signature(s); + /* init the transfer handler so that 0xffff is returned on data + accesses */ + s->end_transfer_func = ide_dummy_transfer_stop; + ide_dummy_transfer_stop(s); +} + +#pragma pack(1) +struct partition { + uint8_t boot_ind; /* 0x80 - active */ + uint8_t head; /* starting head */ + uint8_t sector; /* starting sector */ + uint8_t cyl; /* starting cylinder */ + uint8_t sys_ind; /* What partition type */ + uint8_t end_head; /* end head */ + uint8_t end_sector; /* end sector */ + uint8_t end_cyl; /* end cylinder */ + uint32_t start_sect; /* starting sector counting from 0 */ + uint32_t nr_sects; /* nr of sectors in partition */ +} ; + +/* try to guess the disk logical geometry from the MSDOS partition table. Return 0 if OK, -1 if could not guess */ +static int guess_disk_lchs(IDEState *s, + int *pcylinders, int *pheads, int *psectors) +{ + uint8_t buf[512]; + int ret, i, heads, sectors, cylinders; + struct partition *p; + uint32_t nr_sects; + + ret = bdrv_read(s->bs, 0, buf, 1); + if (ret < 0) + return -1; + /* test msdos magic */ + if (buf[510] != 0x55 || buf[511] != 0xaa) + return -1; + for(i = 0; i < 4; i++) { + p = ((struct partition *)(buf + 0x1be)) + i; + nr_sects = le32_to_cpu(p->nr_sects); + if (nr_sects && p->end_head) { + /* We make the assumption that the partition terminates on + a cylinder boundary */ + heads = p->end_head + 1; + sectors = p->end_sector & 63; + if (sectors == 0) + continue; + cylinders = s->nb_sectors / (heads * sectors); + if (cylinders < 1 || cylinders > 16383) + continue; + *pheads = heads; + *psectors = sectors; + *pcylinders = cylinders; +#if 0 + printf("guessed geometry: LCHS=%d %d %d\n", + cylinders, heads, sectors); +#endif + return 0; + } + } + return -1; +} + +static void ide_init2(IDEState *ide_state, + BlockDriverState *hd0, BlockDriverState *hd1, + SetIRQFunc *set_irq, void *irq_opaque, int irq) +{ + IDEState *s; + static int drive_serial = 1; + int i, cylinders, heads, secs, translation, lba_detected = 0; + int64_t nb_sectors; + + for(i = 0; i < 2; i++) { + s = ide_state + i; + if (i == 0) + s->bs = hd0; + else + s->bs = hd1; + if (s->bs) + { + bdrv_get_geometry(s->bs, &nb_sectors); + s->nb_sectors = nb_sectors; + /* if a geometry hint is available, use it */ + bdrv_get_geometry_hint(s->bs, &cylinders, &heads, &secs); + translation = bdrv_get_translation_hint(s->bs); + if (cylinders != 0) { + s->cylinders = cylinders; + s->heads = heads; + s->sectors = secs; + } + else + { + if (guess_disk_lchs(s, &cylinders, &heads, &secs) == 0) + { + if (heads > 16) { + /* if heads > 16, it means that a BIOS LBA + translation was active, so the default + hardware geometry is OK */ + lba_detected = 1; + goto default_geometry; + } + else + { + s->cylinders = cylinders; + s->heads = heads; + s->sectors = secs; + /* disable any translation to be in sync with + the logical geometry */ + if (translation == BIOS_ATA_TRANSLATION_AUTO) { + bdrv_set_translation_hint(s->bs, + BIOS_ATA_TRANSLATION_NONE); + } + } + } + else + { +default_geometry: + /* if no geometry, use a standard physical disk geometry */ + cylinders = nb_sectors / (16 * 63); + if (cylinders > 16383) + cylinders = 16383; + else if (cylinders < 2) + cylinders = 2; + s->cylinders = cylinders; + s->heads = 16; + s->sectors = 63; + if ((lba_detected == 1) && (translation == BIOS_ATA_TRANSLATION_AUTO)) + { + if ((s->cylinders * s->heads) <= 131072) + { + bdrv_set_translation_hint(s->bs, + BIOS_ATA_TRANSLATION_LARGE); + } + else + { + bdrv_set_translation_hint(s->bs, + BIOS_ATA_TRANSLATION_LBA); + } + } + } + bdrv_set_geometry_hint(s->bs, s->cylinders, s->heads, s->sectors); + } + if (bdrv_get_type_hint(s->bs) == BDRV_TYPE_CDROM) { + s->is_cdrom = 1; + bdrv_set_change_cb(s->bs, cdrom_change_cb, s); + } + } + s->drive_serial = drive_serial++; + s->set_irq = set_irq; + s->irq_opaque = irq_opaque; + s->irq = irq; + s->sector_write_timer =0;//* qemu_new_timer(vm_clock, + //* ide_sector_write_timer_cb, s); + ide_reset(s); + } +} +#if 0 +static void ide_init_ioport(IDEState *ide_state, int iobase, int iobase2) +{ + register_ioport_write(iobase, 8, 1, ide_ioport_write, ide_state); + register_ioport_read(iobase, 8, 1, ide_ioport_read, ide_state); + if (iobase2) { + register_ioport_read(iobase2, 1, 1, ide_status_read, ide_state); + register_ioport_write(iobase2, 1, 1, ide_cmd_write, ide_state); + } + + /* data ports */ + register_ioport_write(iobase, 2, 2, ide_data_writew, ide_state); + register_ioport_read(iobase, 2, 2, ide_data_readw, ide_state); + register_ioport_write(iobase, 4, 4, ide_data_writel, ide_state); + register_ioport_read(iobase, 4, 4, ide_data_readl, ide_state); +} + +/***********************************************************/ +/* ISA IDE definitions */ + +void isa_ide_init(int iobase, int iobase2, int irq, + BlockDriverState *hd0, BlockDriverState *hd1) +{ + IDEState *ide_state; + + ide_state = qemu_mallocz(sizeof(IDEState) * 2); + if (!ide_state) + return; + + ide_init2(ide_state, hd0, hd1, pic_set_irq_new, isa_pic, irq); + ide_init_ioport(ide_state, iobase, iobase2); +} + +/***********************************************************/ +/* PCI IDE definitions */ + +static void cmd646_update_irq(PCIIDEState *d); + +static void ide_map(PCIDevice *pci_dev, int region_num, + uint32_t addr, uint32_t size, int type) +{ + PCIIDEState *d = (PCIIDEState *)pci_dev; + IDEState *ide_state; + + if (region_num <= 3) { + ide_state = &d->ide_if[(region_num >> 1) * 2]; + if (region_num & 1) { + register_ioport_read(addr + 2, 1, 1, ide_status_read, ide_state); + register_ioport_write(addr + 2, 1, 1, ide_cmd_write, ide_state); + } else { + register_ioport_write(addr, 8, 1, ide_ioport_write, ide_state); + register_ioport_read(addr, 8, 1, ide_ioport_read, ide_state); + + /* data ports */ + register_ioport_write(addr, 2, 2, ide_data_writew, ide_state); + register_ioport_read(addr, 2, 2, ide_data_readw, ide_state); + register_ioport_write(addr, 4, 4, ide_data_writel, ide_state); + register_ioport_read(addr, 4, 4, ide_data_readl, ide_state); + } + } +} + +#endif +static void ide_dma_start(IDEState *s, BlockDriverCompletionFunc *dma_cb) +{ + BMDMAState *bm = s->bmdma; + if(!bm) + return; + bm->ide_if = s; + bm->dma_cb = dma_cb; + bm->cur_prd_last = 0; + bm->cur_prd_addr = 0; + bm->cur_prd_len = 0; + if (bm->status & BM_STATUS_DMAING) { + bm->dma_cb(bm, 0); + } +} + +#if 0 +static void bmdma_cmd_writeb(void *opaque, uint32_t addr, uint32_t val) +{ + BMDMAState *bm =(BMDMAState*) opaque; +#ifdef DEBUG_IDE + printf("%s: 0x%08x\n", __func__, val); +#endif + if (!(val & BM_CMD_START)) { + /* XXX: do it better */ + if (bm->status & BM_STATUS_DMAING) { + bm->status &= ~BM_STATUS_DMAING; + /* cancel DMA request */ + bm->ide_if = NULL; + bm->dma_cb = NULL; + if (bm->aiocb) { +#ifdef DEBUG_AIO + printf("aio_cancel\n"); +#endif + bdrv_aio_cancel(bm->aiocb); + bm->aiocb = NULL; + } + } + bm->cmd = val & 0x09; + } else { + if (!(bm->status & BM_STATUS_DMAING)) { + bm->status |= BM_STATUS_DMAING; + /* start dma transfer if possible */ + if (bm->dma_cb) + bm->dma_cb(bm, 0); + } + bm->cmd = val & 0x09; + } +} + +static uint32_t bmdma_readb(void *opaque, uint32_t addr) +{ + BMDMAState *bm =(BMDMAState*) opaque; + PCIIDEState *pci_dev; + uint32_t val; + + switch(addr & 3) { + case 0: + val = bm->cmd; + break; + case 1: + pci_dev = bm->pci_dev; + if (pci_dev->type == IDE_TYPE_CMD646) { + val = pci_dev->dev.config[MRDMODE]; + } else { + val = 0xff; + } + break; + case 2: + val = bm->status; + break; + case 3: + pci_dev = bm->pci_dev; + if (pci_dev->type == IDE_TYPE_CMD646) { + if (bm == &pci_dev->bmdma[0]) + val = pci_dev->dev.config[UDIDETCR0]; + else + val = pci_dev->dev.config[UDIDETCR1]; + } else { + val = 0xff; + } + break; + default: + val = 0xff; + break; + } +#ifdef DEBUG_IDE + printf("bmdma: readb 0x%02x : 0x%02x\n", addr, val); +#endif + return val; +} + +static void bmdma_writeb(void *opaque, uint32_t addr, uint32_t val) +{ + BMDMAState *bm = opaque; + PCIIDEState *pci_dev; +#ifdef DEBUG_IDE + printf("bmdma: writeb 0x%02x : 0x%02x\n", addr, val); +#endif + switch(addr & 3) { + case 1: + pci_dev = bm->pci_dev; + if (pci_dev->type == IDE_TYPE_CMD646) { + pci_dev->dev.config[MRDMODE] = + (pci_dev->dev.config[MRDMODE] & ~0x30) | (val & 0x30); + cmd646_update_irq(pci_dev); + } + break; + case 2: + bm->status = (val & 0x60) | (bm->status & 1) | (bm->status & ~val & 0x06); + break; + case 3: + pci_dev = bm->pci_dev; + if (pci_dev->type == IDE_TYPE_CMD646) { + if (bm == &pci_dev->bmdma[0]) + pci_dev->dev.config[UDIDETCR0] = val; + else + pci_dev->dev.config[UDIDETCR1] = val; + } + break; + } +} + +static uint32_t bmdma_addr_readl(void *opaque, uint32_t addr) +{ + BMDMAState *bm = opaque; + uint32_t val; + val = bm->addr; +#ifdef DEBUG_IDE + printf("%s: 0x%08x\n", __func__, val); +#endif + return val; +} + +static void bmdma_addr_writel(void *opaque, uint32_t addr, uint32_t val) +{ + BMDMAState *bm = opaque; +#ifdef DEBUG_IDE + printf("%s: 0x%08x\n", __func__, val); +#endif + bm->addr = val & ~3; + bm->cur_addr = bm->addr; +} + +static void bmdma_map(PCIDevice *pci_dev, int region_num, + uint32_t addr, uint32_t size, int type) +{ + PCIIDEState *d = (PCIIDEState *)pci_dev; + int i; + + for(i = 0;i < 2; i++) { + BMDMAState *bm = &d->bmdma[i]; + d->ide_if[2 * i].bmdma = bm; + d->ide_if[2 * i + 1].bmdma = bm; + bm->pci_dev = (PCIIDEState *)pci_dev; + + register_ioport_write(addr, 1, 1, bmdma_cmd_writeb, bm); + + register_ioport_write(addr + 1, 3, 1, bmdma_writeb, bm); + register_ioport_read(addr, 4, 1, bmdma_readb, bm); + + register_ioport_write(addr + 4, 4, 4, bmdma_addr_writel, bm); + register_ioport_read(addr + 4, 4, 4, bmdma_addr_readl, bm); + addr += 8; + } +} + + +/* XXX: call it also when the MRDMODE is changed from the PCI config + registers */ +static void cmd646_update_irq(PCIIDEState *d) +{ + int pci_level; + pci_level = ((d->dev.config[MRDMODE] & MRDMODE_INTR_CH0) && + !(d->dev.config[MRDMODE] & MRDMODE_BLK_CH0)) || + ((d->dev.config[MRDMODE] & MRDMODE_INTR_CH1) && + !(d->dev.config[MRDMODE] & MRDMODE_BLK_CH1)); + pci_set_irq((PCIDevice *)d, 0, pci_level); +} + +/* the PCI irq level is the logical OR of the two channels */ +static void cmd646_set_irq(void *opaque, int channel, int level) +{ + PCIIDEState *d = opaque; + int irq_mask; + + irq_mask = MRDMODE_INTR_CH0 << channel; + if (level) + d->dev.config[MRDMODE] |= irq_mask; + else + d->dev.config[MRDMODE] &= ~irq_mask; + cmd646_update_irq(d); +} + +/* CMD646 PCI IDE controller */ +void pci_cmd646_ide_init(PCIBus *bus, BlockDriverState **hd_table, + int secondary_ide_enabled) +{ + PCIIDEState *d; + uint8_t *pci_conf; + int i; + + d = (PCIIDEState *)pci_register_device(bus, "CMD646 IDE", + sizeof(PCIIDEState), + -1, + NULL, NULL); + d->type = IDE_TYPE_CMD646; + pci_conf = d->dev.config; + pci_conf[0x00] = 0x95; // CMD646 + pci_conf[0x01] = 0x10; + pci_conf[0x02] = 0x46; + pci_conf[0x03] = 0x06; + + pci_conf[0x08] = 0x07; // IDE controller revision + pci_conf[0x09] = 0x8f; + + pci_conf[0x0a] = 0x01; // class_sub = PCI_IDE + pci_conf[0x0b] = 0x01; // class_base = PCI_mass_storage + pci_conf[0x0e] = 0x00; // header_type + + if (secondary_ide_enabled) { + /* XXX: if not enabled, really disable the seconday IDE controller */ + pci_conf[0x51] = 0x80; /* enable IDE1 */ + } + + pci_register_io_region((PCIDevice *)d, 0, 0x8, + PCI_ADDRESS_SPACE_IO, ide_map); + pci_register_io_region((PCIDevice *)d, 1, 0x4, + PCI_ADDRESS_SPACE_IO, ide_map); + pci_register_io_region((PCIDevice *)d, 2, 0x8, + PCI_ADDRESS_SPACE_IO, ide_map); + pci_register_io_region((PCIDevice *)d, 3, 0x4, + PCI_ADDRESS_SPACE_IO, ide_map); + pci_register_io_region((PCIDevice *)d, 4, 0x10, + PCI_ADDRESS_SPACE_IO, bmdma_map); + + pci_conf[0x3d] = 0x01; // interrupt on pin 1 + + for(i = 0; i < 4; i++) + d->ide_if[i].pci_dev = (PCIDevice *)d; + ide_init2(&d->ide_if[0], hd_table[0], hd_table[1], + cmd646_set_irq, d, 0); + ide_init2(&d->ide_if[2], hd_table[2], hd_table[3], + cmd646_set_irq, d, 1); +} + +static void pci_ide_save(QEMUFile* f, void *opaque) +{ + PCIIDEState *d = opaque; + int i; + + pci_device_save(&d->dev, f); + + for(i = 0; i < 2; i++) { + BMDMAState *bm = &d->bmdma[i]; + qemu_put_8s(f, &bm->cmd); + qemu_put_8s(f, &bm->status); + qemu_put_be32s(f, &bm->addr); + /* XXX: if a transfer is pending, we do not save it yet */ + } + + /* per IDE interface data */ + for(i = 0; i < 2; i++) { + IDEState *s = &d->ide_if[i * 2]; + uint8_t drive1_selected; + qemu_put_8s(f, &s->cmd); + drive1_selected = (s->cur_drive != s); + qemu_put_8s(f, &drive1_selected); + } + + /* per IDE drive data */ + for(i = 0; i < 4; i++) { + IDEState *s = &d->ide_if[i]; + qemu_put_be32s(f, &s->mult_sectors); + qemu_put_be32s(f, &s->identify_set); + if (s->identify_set) { + qemu_put_buffer(f, (const uint8_t *)s->identify_data, 512); + } + qemu_put_8s(f, &s->feature); + qemu_put_8s(f, &s->error); + qemu_put_be32s(f, &s->nsector); + qemu_put_8s(f, &s->sector); + qemu_put_8s(f, &s->lcyl); + qemu_put_8s(f, &s->hcyl); + qemu_put_8s(f, &s->hob_feature); + qemu_put_8s(f, &s->hob_nsector); + qemu_put_8s(f, &s->hob_sector); + qemu_put_8s(f, &s->hob_lcyl); + qemu_put_8s(f, &s->hob_hcyl); + qemu_put_8s(f, &s->select); + qemu_put_8s(f, &s->status); + qemu_put_8s(f, &s->lba48); + + qemu_put_8s(f, &s->sense_key); + qemu_put_8s(f, &s->asc); + /* XXX: if a transfer is pending, we do not save it yet */ + } +} + +static int pci_ide_load(QEMUFile* f, void *opaque, int version_id) +{ + PCIIDEState *d = opaque; + int ret, i; + + if (version_id != 1) + return -EINVAL; + ret = pci_device_load(&d->dev, f); + if (ret < 0) + return ret; + + for(i = 0; i < 2; i++) { + BMDMAState *bm = &d->bmdma[i]; + qemu_get_8s(f, &bm->cmd); + qemu_get_8s(f, &bm->status); + qemu_get_be32s(f, &bm->addr); + /* XXX: if a transfer is pending, we do not save it yet */ + } + + /* per IDE interface data */ + for(i = 0; i < 2; i++) { + IDEState *s = &d->ide_if[i * 2]; + uint8_t drive1_selected; + qemu_get_8s(f, &s->cmd); + qemu_get_8s(f, &drive1_selected); + s->cur_drive = &d->ide_if[i * 2 + (drive1_selected != 0)]; + } + + /* per IDE drive data */ + for(i = 0; i < 4; i++) { + IDEState *s = &d->ide_if[i]; + qemu_get_be32s(f, &s->mult_sectors); + qemu_get_be32s(f, &s->identify_set); + if (s->identify_set) { + qemu_get_buffer(f, (uint8_t *)s->identify_data, 512); + } + qemu_get_8s(f, &s->feature); + qemu_get_8s(f, &s->error); + qemu_get_be32s(f, &s->nsector); + qemu_get_8s(f, &s->sector); + qemu_get_8s(f, &s->lcyl); + qemu_get_8s(f, &s->hcyl); + qemu_get_8s(f, &s->hob_feature); + qemu_get_8s(f, &s->hob_nsector); + qemu_get_8s(f, &s->hob_sector); + qemu_get_8s(f, &s->hob_lcyl); + qemu_get_8s(f, &s->hob_hcyl); + qemu_get_8s(f, &s->select); + qemu_get_8s(f, &s->status); + qemu_get_8s(f, &s->lba48); + + qemu_get_8s(f, &s->sense_key); + qemu_get_8s(f, &s->asc); + /* XXX: if a transfer is pending, we do not save it yet */ + } + return 0; +} + +static void piix3_reset(PCIIDEState *d) +{ + uint8_t *pci_conf = d->dev.config; + + pci_conf[0x04] = 0x00; + pci_conf[0x05] = 0x00; + pci_conf[0x06] = 0x80; /* FBC */ + pci_conf[0x07] = 0x02; // PCI_status_devsel_medium + pci_conf[0x20] = 0x01; /* BMIBA: 20-23h */ +} + +void pci_piix_ide_init(PCIBus *bus, BlockDriverState **hd_table, int devfn) +{ + PCIIDEState *d; + uint8_t *pci_conf; + + /* register a function 1 of PIIX */ + d = (PCIIDEState *)pci_register_device(bus, "PIIX IDE", + sizeof(PCIIDEState), + devfn, + NULL, NULL); + d->type = IDE_TYPE_PIIX3; + + pci_conf = d->dev.config; + pci_conf[0x00] = 0x86; // Intel + pci_conf[0x01] = 0x80; + pci_conf[0x02] = 0x30; + pci_conf[0x03] = 0x12; + pci_conf[0x08] = 0x02; // Step A1 + pci_conf[0x09] = 0x80; // legacy ATA mode + pci_conf[0x0a] = 0x01; // class_sub = PCI_IDE + pci_conf[0x0b] = 0x01; // class_base = PCI_mass_storage + pci_conf[0x0e] = 0x00; // header_type + + piix3_reset(d); + + pci_register_io_region((PCIDevice *)d, 4, 0x10, + PCI_ADDRESS_SPACE_IO, bmdma_map); + + ide_init2(&d->ide_if[0], hd_table[0], hd_table[1], + pic_set_irq_new, isa_pic, 14); + ide_init2(&d->ide_if[2], hd_table[2], hd_table[3], + pic_set_irq_new, isa_pic, 15); + ide_init_ioport(&d->ide_if[0], 0x1f0, 0x3f6); + ide_init_ioport(&d->ide_if[2], 0x170, 0x376); + + register_savevm("ide", 0, 1, pci_ide_save, pci_ide_load, d); +} + +/* hd_table must contain 4 block drivers */ +/* NOTE: for the PIIX3, the IRQs and IOports are hardcoded */ +void pci_piix3_ide_init(PCIBus *bus, BlockDriverState **hd_table, int devfn) +{ + PCIIDEState *d; + uint8_t *pci_conf; + + /* register a function 1 of PIIX3 */ + d = (PCIIDEState *)pci_register_device(bus, "PIIX3 IDE", + sizeof(PCIIDEState), + devfn, + NULL, NULL); + d->type = IDE_TYPE_PIIX3; + + pci_conf = d->dev.config; + pci_conf[0x00] = 0x86; // Intel + pci_conf[0x01] = 0x80; + pci_conf[0x02] = 0x10; + pci_conf[0x03] = 0x70; + pci_conf[0x09] = 0x80; // legacy ATA mode + pci_conf[0x0a] = 0x01; // class_sub = PCI_IDE + pci_conf[0x0b] = 0x01; // class_base = PCI_mass_storage + pci_conf[0x0e] = 0x00; // header_type + + piix3_reset(d); + + pci_register_io_region((PCIDevice *)d, 4, 0x10, + PCI_ADDRESS_SPACE_IO, bmdma_map); + + ide_init2(&d->ide_if[0], hd_table[0], hd_table[1], + pic_set_irq_new, isa_pic, 14); + ide_init2(&d->ide_if[2], hd_table[2], hd_table[3], + pic_set_irq_new, isa_pic, 15); + ide_init_ioport(&d->ide_if[0], 0x1f0, 0x3f6); + ide_init_ioport(&d->ide_if[2], 0x170, 0x376); + + register_savevm("ide", 0, 1, pci_ide_save, pci_ide_load, d); +} + +/***********************************************************/ +/* MacIO based PowerPC IDE */ + +/* PowerMac IDE memory IO */ +static void pmac_ide_writeb (void *opaque, + target_phys_addr_t addr, uint32_t val) +{ + addr = (addr & 0xFFF) >> 4; + switch (addr) { + case 1 ... 7: + ide_ioport_write(opaque, addr, val); + break; + case 8: + case 22: + ide_cmd_write(opaque, 0, val); + break; + default: + break; + } +} + +static uint32_t pmac_ide_readb (void *opaque,target_phys_addr_t addr) +{ + uint8_t retval; + + addr = (addr & 0xFFF) >> 4; + switch (addr) { + case 1 ... 7: + retval = ide_ioport_read(opaque, addr); + break; + case 8: + case 22: + retval = ide_status_read(opaque, 0); + break; + default: + retval = 0xFF; + break; + } + return retval; +} + +static void pmac_ide_writew (void *opaque, + target_phys_addr_t addr, uint32_t val) +{ + addr = (addr & 0xFFF) >> 4; +#ifdef TARGET_WORDS_BIGENDIAN + val = bswap16(val); +#endif + if (addr == 0) { + ide_data_writew(opaque, 0, val); + } +} + +static uint32_t pmac_ide_readw (void *opaque,target_phys_addr_t addr) +{ + uint16_t retval; + + addr = (addr & 0xFFF) >> 4; + if (addr == 0) { + retval = ide_data_readw(opaque, 0); + } else { + retval = 0xFFFF; + } +#ifdef TARGET_WORDS_BIGENDIAN + retval = bswap16(retval); +#endif + return retval; +} + +static void pmac_ide_writel (void *opaque, + target_phys_addr_t addr, uint32_t val) +{ + addr = (addr & 0xFFF) >> 4; +#ifdef TARGET_WORDS_BIGENDIAN + val = bswap32(val); +#endif + if (addr == 0) { + ide_data_writel(opaque, 0, val); + } +} + +static uint32_t pmac_ide_readl (void *opaque,target_phys_addr_t addr) +{ + uint32_t retval; + + addr = (addr & 0xFFF) >> 4; + if (addr == 0) { + retval = ide_data_readl(opaque, 0); + } else { + retval = 0xFFFFFFFF; + } +#ifdef TARGET_WORDS_BIGENDIAN + retval = bswap32(retval); +#endif + return retval; +} + +static CPUWriteMemoryFunc *pmac_ide_write[] = { + pmac_ide_writeb, + pmac_ide_writew, + pmac_ide_writel, +}; + +static CPUReadMemoryFunc *pmac_ide_read[] = { + pmac_ide_readb, + pmac_ide_readw, + pmac_ide_readl, +}; + +/* hd_table must contain 4 block drivers */ +/* PowerMac uses memory mapped registers, not I/O. Return the memory + I/O index to access the ide. */ +int pmac_ide_init (BlockDriverState **hd_table, + SetIRQFunc *set_irq, void *irq_opaque, int irq) +{ + IDEState *ide_if; + int pmac_ide_memory; + + ide_if = qemu_mallocz(sizeof(IDEState) * 2); + ide_init2(&ide_if[0], hd_table[0], hd_table[1], + set_irq, irq_opaque, irq); + + pmac_ide_memory = cpu_register_io_memory(0, pmac_ide_read, + pmac_ide_write, &ide_if[0]); + return pmac_ide_memory; +} + +#endif +#define ATA_R_DATA (ATA_DEV9_HDD_BASE + 0x00) +#define ATA_R_ERROR (ATA_DEV9_HDD_BASE + 0x02) +#define ATA_R_NSECTOR (ATA_DEV9_HDD_BASE + 0x04) +#define ATA_R_SECTOR (ATA_DEV9_HDD_BASE + 0x06) +#define ATA_R_LCYL (ATA_DEV9_HDD_BASE + 0x08) +#define ATA_R_HCYL (ATA_DEV9_HDD_BASE + 0x0a) +#define ATA_R_SELECT (ATA_DEV9_HDD_BASE + 0x0c) +#define ATA_R_STATUS (ATA_DEV9_HDD_BASE + 0x0e) +#define ATA_R_CONTROL (ATA_DEV9_HDD_BASE + 0x1c) + +//Feature -> error +//command -> status + +//data : 1,2,4 +//command : 1 +IDEState ps2_hdd_data; +BMDMAState ps2_hdd_bmdma_data; +BlockDriverState ps2_hdd_bds_data; + +#define ps2_hdd (&ps2_hdd_data) +void dev9_ata_irq(void *opaque, int irq_num, int level) +{ + emu_printf("ATA INTERRUPT level %d\n",level); + if (level) + { + _DEV9irq(ATA_DEV9_INT,0); + } + else + { + dev9.irqcause&=~ATA_DEV9_INT; + _DEV9irq(0,0); + } + +} +HANDLE HddFile; +void ata_init() +{ + HddFile = ::CreateFile("d:\\ps2_hdd.raw", GENERIC_READ|GENERIC_WRITE, + 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); + + DWORD dwTemp; + ::DeviceIoControl(HddFile, FSCTL_SET_SPARSE, NULL, 0, NULL, 0, &dwTemp, NULL); + LARGE_INTEGER sp; + + //20 GBs + /* + //~7 GB + sp.LowPart=0xEFFFFFFF; + sp.HighPart=1; + */ + sp.QuadPart=(u64)20*1000*1000*1000; + + int64_t rcc=(sp.QuadPart/512/16/63)+1; + + ps2_hdd_bds_data.total_sectors=rcc*16*63; + sp.QuadPart=ps2_hdd_bds_data.total_sectors*512; + + ps2_hdd_bds_data.secs=0; + ps2_hdd_bds_data.heads=0; + ps2_hdd_bds_data.cyls=0; + + emu_printf("Hdd size #.2fGB\n",(double)sp.QuadPart/1024/1024/1024); + + ::SetFilePointerEx(HddFile, sp, 0, FILE_BEGIN); + ::SetEndOfFile(HddFile); + + + ide_init2(ps2_hdd,&ps2_hdd_bds_data,0,dev9_ata_irq,0,0); + ps2_hdd->bmdma=&ps2_hdd_bmdma_data; +} +void ata_term() +{ + ::CloseHandle(HddFile); +} +#define LOG_IRS (sz!=2) +template +u8 CALLBACK ata_read(u32 addr) +{ + //emu_printf("ata_read%d(0x%X)\n",sz*8,addr); + switch(addr) + { + case ATA_R_DATA: + if (sz==1) + { + emu_printf("ATA: Invalid ATA_R_DATA size: register cannot be readen using 8 bit\n"); + } + else if (sz==2) + { + return ide_data_readw(ps2_hdd,0); + } + else + { + return ide_data_readl(ps2_hdd,0); + } + break; + case ATA_R_ERROR: + if (sz!=1 && LOG_IRS) + { + emu_printf("ATA: Invalid ATA_R_ERROR size: register cannot be read w/o using 8 bit\n"); + } + //else + { + return ide_ioport_read(ps2_hdd,1); + } + break; + case ATA_R_NSECTOR: + if (sz!=1 && LOG_IRS) + { + emu_printf("ATA: Invalid ATA_R_NSECTOR size: register cannot be read w/o using 8 bit\n"); + } + //else + { + return ide_ioport_read(ps2_hdd,2); + } + break; + case ATA_R_SECTOR: + if (sz!=1 && LOG_IRS) + { + emu_printf("ATA: Invalid ATA_R_SECTOR size: register cannot be read w/o using 8 bit\n"); + } + //else + { + return ide_ioport_read(ps2_hdd,3); + } + break; + case ATA_R_LCYL: + if (sz!=1 && LOG_IRS) + { + emu_printf("ATA: Invalid ATA_R_LCYL size: register cannot be read w/o using 8 bit\n"); + } + //else + { + return ide_ioport_read(ps2_hdd,4); + } + break; + case ATA_R_HCYL: + if (sz!=1 && LOG_IRS) + { + emu_printf("ATA: Invalid ATA_R_HCYL size: register cannot be read w/o using 8 bit\n"); + } + //else + { + return ide_ioport_read(ps2_hdd,5); + } + break; + case ATA_R_SELECT: + if (sz!=1 && LOG_IRS) + { + emu_printf("ATA: Invalid ATA_R_SELECT size: register cannot be read w/o using 8 bit\n"); + } + //else + { + return ide_ioport_read(ps2_hdd,6); + } + break; + //command -> status + case ATA_R_STATUS: + if (sz!=1 && LOG_IRS) + { + emu_printf("ATA: Invalid ATA_R_STATUS size: register cannot be read w/o using 8 bit\n"); + } + //else + { + return ide_ioport_read(ps2_hdd,7); + } + break; + case ATA_R_CONTROL: + //ide_cmd -> seems to be control + if (sz!=1 && LOG_IRS) + { + emu_printf("ATA: Invalid ATA_R_STATUS size: register cannot be read w/o using 8 bit\n"); + } + //else + { + return ide_status_read(ps2_hdd,0); + } + break; + default: + DEV9_LOG("ATA: Unknown %d bit read @ %X,v=%X\n",sz*8,addr,dev9Ru8(addr)); + if (sz==1) + { + return dev9Ru8(addr); + } + else if (sz==2) + { + return dev9Ru16(addr); + } + else + { + return dev9Ru32(addr); + } + } + + DEV9_LOG("ATA: Unknown %d bit read @ %X,v=%X\n",sz*8,addr,0xdeadb33f); + return 0xdeadb33f; +} +#define LOG_IWS (value&~0xFF) +template +void CALLBACK ata_write(u32 addr, u32 value) +{ + //emu_printf("ata_write%d(0x%X,0x%X)\n",sz*8,addr,value); + switch(addr) + { + case ATA_R_DATA: + if (sz==1) + { + emu_printf("ATA: Invalid ATA_R_DATA size: register cannot be writen using 8 bit\n"); + } + else if (sz==2) + { + ide_data_writew(ps2_hdd,0,value); + } + else + { + ide_data_writel(ps2_hdd,0,value); + } + break; + case ATA_R_ERROR: + if (sz!=1 && LOG_IWS) + { + emu_printf("ATA: Invalid ATA_R_ERROR(feature) size: register cannot be writen w/o using 8 bit\n"); + } + //else + { + ide_ioport_write(ps2_hdd,1,value); + } + break; + case ATA_R_NSECTOR: + if (sz!=1 && LOG_IWS) + { + emu_printf("ATA: Invalid ATA_R_NSECTOR size: register cannot be writen w/o using 8 bit\n"); + } + //else + { + ide_ioport_write(ps2_hdd,2,value); + } + break; + case ATA_R_SECTOR: + if (sz!=1 && LOG_IWS) + { + emu_printf("ATA: Invalid ATA_R_SECTOR size: register cannot be writen w/o using 8 bit\n"); + } + //else + { + ide_ioport_write(ps2_hdd,3,value); + } + break; + case ATA_R_LCYL: + if (sz!=1 && LOG_IWS) + { + emu_printf("ATA: Invalid ATA_R_LCYL size: register cannot be writen w/o using 8 bit\n"); + } + //else + { + ide_ioport_write(ps2_hdd,4,value); + } + break; + case ATA_R_HCYL: + if (sz!=1 && LOG_IWS) + { + emu_printf("ATA: Invalid ATA_R_HCYL size: register cannot be writen w/o using 8 bit\n"); + } + //else + { + ide_ioport_write(ps2_hdd,5,value); + } + break; + case ATA_R_SELECT: + if (sz!=1 && LOG_IWS) + { + emu_printf("ATA: Invalid ATA_R_SELECT size: register cannot be writen w/o using 8 bit\n"); + } + //else + { + ide_ioport_write(ps2_hdd,6,value); + } + break; + //command -> status + case ATA_R_STATUS: + if (sz!=1 && LOG_IWS) + { + emu_printf("ATA: Invalid ATA_R_STATUS(command) size: register cannot be writen w/o using 8 bit\n"); + } + //else + { + ide_ioport_write(ps2_hdd,7,value); + } + break; + case ATA_R_CONTROL: + //ide_cmd -> seems to be control + if (sz!=1 && LOG_IWS) + { + emu_printf("ATA: Invalid ATA_R_CONTROL size: register cannot be writen w/o using 8 bit\n"); + } + // else + { + ide_cmd_write(ps2_hdd,7,value); + } + break; + default: + DEV9_LOG("ATA: Unknown %d bit write @ %X,v=%X\n",addr,value); + if (sz==1) + { + dev9Ru8(addr)=value; + } + else if (sz==2) + { + dev9Ru16(addr)=value; + } + else + { + dev9Ru32(addr)=value; + } + } +} + +u8* pMem_dma; +void do_dma(int size) +{ + BMDMAState* bm=ps2_hdd->bmdma; + bm->addr=0; + bm->cur_prd_addr = 0; + bm->cur_prd_len = size; + + if (!(bm->status & BM_STATUS_DMAING)) + { + bm->status |= BM_STATUS_DMAING; + /* start dma transfer if possible */ + if (bm->dma_cb) + bm->dma_cb(bm, 0); + else + emu_printf("DMA ERROR 2 !!!!@#!@#!@#!#!@#!@#$####################################################^#^\n"); + //bm->status&=~BM_STATUS_DMAING; + } + else + { + emu_printf("DMA ERROR 1 !!!!@#!@#!@#!#!@#!@#$####################################################^#^\n"); + } + + _DEV9irq(ATA_DEV9_INT_DMA,0); +} +void CALLBACK ata_readDMA8Mem(u32 *pMem, int size) +{ + size>>=1; + //#define SPD_R_IF_CTRL (SPD_REGBASE + 0x64) + //#define SPD_IF_ATA_RESET 0x80 + //#define SPD_IF_DMA_ENABLE 0x04 + pMem_dma=(u8*)pMem; + if (dev9Ru8(SPD_R_IF_CTRL)&SPD_IF_DMA_ENABLE) + { + emu_printf("ATA: ata_readDMA8Mem(0x%X,%d) :D\n",pMem,size); + do_dma(size); + //bm->cmd = val & 0x09; + } + else + { + emu_printf("ATA: ata_readDMA8Mem & SPD_IF_DMA_ENABLE disabled\n"); + } +} +void CALLBACK ata_writeDMA8Mem(u32 *pMem, int size) +{ + size>>=1; + pMem_dma=(u8*)pMem; + if (dev9Ru8(SPD_R_IF_CTRL)&SPD_IF_DMA_ENABLE) + { + emu_printf("ATA: ata_writeDMA8Mem(0x%X,%d) :D\n",pMem,size); + do_dma(size); + //bm->cmd = val & 0x09; + } + else + { + emu_printf("ATA: ata_writeDMA8Mem & SPD_IF_DMA_ENABLE disabled\n"); + } +} +void _template_hack_() +{ + ata_read<1>(0); + ata_read<2>(0); + ata_read<4>(0); + + ata_write<1>(0,0); + ata_write<2>(0,0); + ata_write<4>(0,0); +} +#define printme emu_printf("Called stub:" __FUNCTION__ "\n"); + +//memory access +void __cdecl cpu_physical_memory_write(u32 addr,void* ptr,u32 sz) +{ + printf("cpu_physical_memory_write(0x%X,0x%X,%d)\n",addr,ptr,sz); + //return; + memcpy(pMem_dma+addr,ptr,sz); +} +void __cdecl cpu_physical_memory_read(u32 addr,void* ptr,u32 sz) +{ + printf("cpu_physical_memory_read(0x%X,0x%X,%d)\n",addr,ptr,sz); + //return; + memcpy(ptr,pMem_dma+addr,sz); +} + +//IMAGE IO + + +//Async io emulation =) +BlockDriverAIOCB *bdrv_aio_read(BlockDriverState *bs, + int64_t sector_num, uint8_t *buf, int nb_sectors, + BlockDriverCompletionFunc *cb, void *opaque) +{ + //printme + int ret; + ret = bdrv_read(bs, sector_num, buf, nb_sectors); + cb(opaque, ret); + return 0; +} +BlockDriverAIOCB *bdrv_aio_write(BlockDriverState *bs, + int64_t sector_num, const uint8_t *buf, int nb_sectors, + BlockDriverCompletionFunc *cb, void *opaque) +{ + //printme + int ret; + ret = bdrv_write(bs, sector_num, buf, nb_sectors); + cb(opaque, ret); + return 0; +} + +void bdrv_flush(BlockDriverState *bs) +{ + printme; + //return; + FlushFileBuffers(HddFile); +} +int bdrv_read(BlockDriverState *bs, int64_t sector_num, + uint8_t *buf, int nb_sectors) +{ + //printme; + //return 0; + if ((sector_num+nb_sectors)>bs->total_sectors) + { + emu_printf("ATA: ERROR , ((sector_num+nb_sectors)>bs->total_sectors)\n"); + return -1; + } + DWORD rv; + LARGE_INTEGER sp; + sp.QuadPart=sector_num*512; + + BOOL sfp=SetFilePointerEx(HddFile,sp,0,FILE_BEGIN); + if (!sfp) + { + emu_printf("SetFilePointerEx file failed\n"); + return -1; + } + + BOOL ss=ReadFile(HddFile,buf,nb_sectors*512,&rv,0); + if (!ss) + { + emu_printf("ReadFile file failed - %d\n",GetLastError()); + return -1; + } + emu_printf("Readed %d bytes from %d:%d@file\n",rv,sp.HighPart,sp.LowPart); + return 0; +} +int bdrv_write(BlockDriverState *bs, int64_t sector_num, + const uint8_t *buf, int nb_sectors) +{ + //printme; + //return 0; + if ((sector_num+nb_sectors)>bs->total_sectors) + { + emu_printf("ATA: ERROR , ((sector_num+nb_sectors)>bs->total_sectors)\n"); + return -1; + } + DWORD rv; + LARGE_INTEGER sp; + sp.QuadPart=sector_num*512; + + BOOL sfp=SetFilePointerEx(HddFile,sp,0,FILE_BEGIN); + if (!sfp) + { + emu_printf("SetFilePointerEx file failed\n"); + return -1; + } + + BOOL ss=WriteFile(HddFile,buf,nb_sectors*512,&rv,0); + if (!ss) + { + emu_printf("WriteFile file failed - %d\n",GetLastError()); + return -1; + } + emu_printf("Writen %d bytes to %d:%d@file\n",rv,sp.HighPart,sp.LowPart); + return 0; +} + +void __cdecl bdrv_eject(struct BlockDriverState *,int) +{ + printme; +} +void bdrv_get_geometry(BlockDriverState *bs, int64_t *nb_sectors_ptr) +{ + printme; + //return; + *nb_sectors_ptr=bs->total_sectors; +} +void bdrv_set_locked(BlockDriverState *bs, int locked) +{ + printme; + //return; + bs->locked = locked; +} + +int __cdecl bdrv_is_locked(struct BlockDriverState *bs) +{ + printme; + return bs->locked; +} +int __cdecl bdrv_is_inserted(struct BlockDriverState *) +{ + printme; + return 1; +} + +void __cdecl bdrv_set_change_cb(struct BlockDriverState *,void (__cdecl*)(void *),void *) +{ + printme +} +int __cdecl bdrv_get_type_hint(struct BlockDriverState *) +{ + printme; + return BDRV_TYPE_HD; +} +void bdrv_set_geometry_hint(BlockDriverState *bs, + int cyls, int heads, int secs) +{ + printme; + //return; + bs->cyls = cyls; + bs->heads = heads; + bs->secs = secs; +} +void bdrv_set_translation_hint(BlockDriverState *bs, int translation) +{ + printme; + bs->translation = translation; +} +int bdrv_get_translation_hint(BlockDriverState *bs) +{ + printme; + //return 0; + return bs->translation; +} + +void bdrv_get_geometry_hint(BlockDriverState *bs, + int *pcyls, int *pheads, int *psecs) +{ + printme; + //return; + *pcyls = bs->cyls; + *pheads = bs->heads; + *psecs = bs->secs; +} \ No newline at end of file diff --git a/plugins/dev9ghzdrk/Win32/ata.h b/plugins/dev9ghzdrk/Win32/ata.h new file mode 100644 index 0000000000..32e2d213c4 --- /dev/null +++ b/plugins/dev9ghzdrk/Win32/ata.h @@ -0,0 +1,13 @@ +#pragma once +#include "dev9.h" + +void ata_init(); +void ata_term(); + +template +void CALLBACK ata_write(u32 addr, u32 value); +template +u8 CALLBACK ata_read(u32 addr); + +void CALLBACK ata_readDMA8Mem(u32 *pMem, int size); +void CALLBACK ata_writeDMA8Mem(u32 *pMem, int size); \ No newline at end of file diff --git a/plugins/dev9ghzdrk/Win32/icmp.cpp b/plugins/dev9ghzdrk/Win32/icmp.cpp new file mode 100644 index 0000000000..18f71d83f0 --- /dev/null +++ b/plugins/dev9ghzdrk/Win32/icmp.cpp @@ -0,0 +1,105 @@ +#include +#include +#include +#include +#include +#include + +#include + +struct pending_icmp_request +{ + char ipaddress[4]; + HANDLE hEvent; + DWORD sTick; + DWORD timeOut; //ttl in ms + DWORD replyBufferSize; + char *replyBuffer; + char *requestData; + void *userdata; + + pending_icmp_request() + { + memset(this,0,sizeof(pending_icmp_request)); + } + + pending_icmp_request(pending_icmp_request&p) + { + memcpy(this,&p,sizeof(p)); + } +}; + +typedef std::list request_list; + +request_list ping_list; + +HANDLE hIP; + +int icmp_init() +{ + hIP = IcmpCreateFile(); + + if(hIP==INVALID_HANDLE_VALUE) + return -1; + + return 0; +} + +void icmp_start(unsigned char *ipaddr, int ttl, void *data, int datasize, void *udata) +{ + pending_icmp_request req; + + req.hEvent = CreateEvent(NULL,TRUE,FALSE,NULL); + req.sTick = GetTickCount(); + req.timeOut = ttl; + + req.requestData = (char*)malloc(datasize); + memcpy(req.requestData,data,datasize); + + memcpy(req.ipaddress,ipaddr,4); + + req.replyBufferSize = (sizeof(ICMP_ECHO_REPLY) + sizeof(datasize)); + req.replyBuffer = (char*)malloc(replyBufferSize); + + req.userdata=udata; + + ping_list.push_back(req); + + IcmpSendEcho2(hIP,req.hEvent,NULL,NULL,*(DWORD*)ipaddr,req.requestData,58, + NULL,req.replyBuffer,replyBufferSize,ttl); + +} + +int icmp_check_replies(char *ipaddress, void **udata) +{ + for(request_list::iterator rit=ping_list.begin();rit!=ping_list.end();rit++) + { + if(WaitForSingleObject(rit->hEvent,0)==0) //handle is signaled, reply received. + { + if(IcmpParseReplies(rit->replyBuffer,rit->replyBufferSize)>0) + { + memcpy(ipaddress,rit->ipaddress,4); + + ping_list.remove(rit); + + return 1; //reply received + } + ResetEvent(rit->hEvent); + } + if(GetTickCount() >= (rit->sTick+rit->timeOut)) + { + memcpy(ipaddress,rit->ipaddress,4); + *udata = rit->userdata; + + ping_list.remove(rit); + + return 2; //timeout + } + } + return 0; +} + +void icmp_close() +{ + IcmpCloseHandle(hIP); +} \ No newline at end of file diff --git a/plugins/dev9ghzdrk/Win32/mtfifo.h b/plugins/dev9ghzdrk/Win32/mtfifo.h new file mode 100644 index 0000000000..8e20c97208 --- /dev/null +++ b/plugins/dev9ghzdrk/Win32/mtfifo.h @@ -0,0 +1,70 @@ +#pragma once +#include +//a simple, mt-safe fifo template class +template +class mtfifo +{ + struct container + { + container(container* n,T d) + { + next=n; + data=d; + } + container* next;T data; + }; + container* start; + container* end; + + CRITICAL_SECTION cs; +public: + mtfifo() + { + InitializeCriticalSection(&cs); + } + ~mtfifo() + { + //no need to destroy the CS? i cant remember realy .. ;p + } + void put(T data) + { + EnterCriticalSection(&cs); + if (end==0) + { + end=start=new container(0,data); + } + else + { + end=end->next=new container(0,data); + } + LeaveCriticalSection(&cs); + } + //Note, this is partialy mt-safe, the get may fail even if that returned false + bool empty(){ return start==0;} + bool get(T& rvi) + { + container* rv; + EnterCriticalSection(&cs); + if (start==0) + { + rv=0; //error + + + } + else + { + rv=start; + start=rv->next; + if (!start) + end=0; //last item + } + LeaveCriticalSection(&cs); + + if(!rv) + return false; + rvi=rv->data; + delete rv; + + return true; + } +}; \ No newline at end of file diff --git a/plugins/dev9ghzdrk/Win32/net.cpp b/plugins/dev9ghzdrk/Win32/net.cpp new file mode 100644 index 0000000000..57edb104bf --- /dev/null +++ b/plugins/dev9ghzdrk/Win32/net.cpp @@ -0,0 +1,51 @@ +#include "net.h" +#include "..\Dev9.h" + +//mtfifo rx_fifo; +//mtfifo tx_fifo; + +NetAdapter* nif; +HANDLE rx_thread; + +volatile bool RxRunning=false; +//rx thread +DWORD WINAPI NetRxThread(LPVOID lpThreadParameter) +{ + NetPacket tmp; + while(RxRunning) + { + while(rx_fifo_can_rx() && nif->recv(&tmp)) + { + rx_process(&tmp); + } + + Sleep(10); + } + + return 0; +} + +void tx_put(NetPacket* pkt) +{ + nif->send(pkt); + //pkt must be copied if its not processed by here, since it can be allocated on the callers stack +} +void InitNet(NetAdapter* ad) +{ + nif=ad; + RxRunning=true; + + rx_thread=CreateThread(0,0,NetRxThread,0,CREATE_SUSPENDED,0); + + SetThreadPriority(rx_thread,THREAD_PRIORITY_HIGHEST); + ResumeThread(rx_thread); +} +void TermNet() +{ + RxRunning=false; + emu_printf("Waiting for RX-net thread to terminate.."); + WaitForSingleObject(rx_thread,-1); + emu_printf(".done\n"); + + delete nif; +} \ No newline at end of file diff --git a/plugins/dev9ghzdrk/Win32/net.h b/plugins/dev9ghzdrk/Win32/net.h new file mode 100644 index 0000000000..0b18e2ed53 --- /dev/null +++ b/plugins/dev9ghzdrk/Win32/net.h @@ -0,0 +1,29 @@ +#pragma once +#include +#include //uh isnt memcpy @ stdlib ? + +struct NetPacket +{ + NetPacket() {size=0;} + NetPacket(void* ptr,int sz) {size=sz;memcpy(buffer,ptr,sz);} + + int size; + char buffer[2048-sizeof(int)];//1536 is realy needed, just pad up to 2048 bytes :) +}; +/* +extern mtfifo rx_fifo; +extern mtfifo tx_fifo; +*/ + +class NetAdapter +{ +public: + virtual bool blocks()=0; + virtual bool recv(NetPacket* pkt)=0; //gets a packet + virtual bool send(NetPacket* pkt)=0; //sends the packet and deletes it when done + virtual ~NetAdapter(){} +}; + +void tx_put(NetPacket* ptr); +void InitNet(NetAdapter* adapter); +void TermNet(); \ No newline at end of file diff --git a/plugins/dev9ghzdrk/Win32/packet32.h b/plugins/dev9ghzdrk/Win32/packet32.h new file mode 100644 index 0000000000..d36b684d6a --- /dev/null +++ b/plugins/dev9ghzdrk/Win32/packet32.h @@ -0,0 +1,450 @@ +/* + * Copyright (c) 1999 - 2003 + * NetGroup, Politecnico di Torino (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. + * 3. Neither the name of the Politecnico di Torino 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. + * + */ + +/** @ingroup packetapi + * @{ + */ + +/** @defgroup packet32h Packet.dll definitions and data structures + * Packet32.h contains the data structures and the definitions used by packet.dll. + * The file is used both by the Win9x and the WinNTx versions of packet.dll, and can be included + * by the applications that use the functions of this library + * @{ + */ + +#ifndef __PACKET32 +#define __PACKET32 + +#include +#include "devioctl.h" +#ifdef HAVE_DAG_API +#include +#endif /* HAVE_DAG_API */ + +// Working modes +#define PACKET_MODE_CAPT 0x0 ///< Capture mode +#define PACKET_MODE_STAT 0x1 ///< Statistical mode +#define PACKET_MODE_MON 0x2 ///< Monitoring mode +#define PACKET_MODE_DUMP 0x10 ///< Dump mode +#define PACKET_MODE_STAT_DUMP MODE_DUMP | MODE_STAT ///< Statistical dump Mode + +// ioctls +#define FILE_DEVICE_PROTOCOL 0x8000 + +#define IOCTL_PROTOCOL_STATISTICS CTL_CODE(FILE_DEVICE_PROTOCOL, 2 , METHOD_BUFFERED, FILE_ANY_ACCESS) +#define IOCTL_PROTOCOL_RESET CTL_CODE(FILE_DEVICE_PROTOCOL, 3 , METHOD_BUFFERED, FILE_ANY_ACCESS) +#define IOCTL_PROTOCOL_READ CTL_CODE(FILE_DEVICE_PROTOCOL, 4 , METHOD_BUFFERED, FILE_ANY_ACCESS) +#define IOCTL_PROTOCOL_WRITE CTL_CODE(FILE_DEVICE_PROTOCOL, 5 , METHOD_BUFFERED, FILE_ANY_ACCESS) +#define IOCTL_PROTOCOL_MACNAME CTL_CODE(FILE_DEVICE_PROTOCOL, 6 , METHOD_BUFFERED, FILE_ANY_ACCESS) +#define IOCTL_OPEN CTL_CODE(FILE_DEVICE_PROTOCOL, 7 , METHOD_BUFFERED, FILE_ANY_ACCESS) +#define IOCTL_CLOSE CTL_CODE(FILE_DEVICE_PROTOCOL, 8 , METHOD_BUFFERED, FILE_ANY_ACCESS) + +#define pBIOCSETBUFFERSIZE 9592 ///< IOCTL code: set kernel buffer size. +#define pBIOCSETF 9030 ///< IOCTL code: set packet filtering program. +#define pBIOCGSTATS 9031 ///< IOCTL code: get the capture stats. +#define pBIOCSRTIMEOUT 7416 ///< IOCTL code: set the read timeout. +#define pBIOCSMODE 7412 ///< IOCTL code: set working mode. +#define pBIOCSWRITEREP 7413 ///< IOCTL code: set number of physical repetions of every packet written by the app. +#define pBIOCSMINTOCOPY 7414 ///< IOCTL code: set minimum amount of data in the kernel buffer that unlocks a read call. +#define pBIOCSETOID 2147483648 ///< IOCTL code: set an OID value. +#define pBIOCQUERYOID 2147483652 ///< IOCTL code: get an OID value. +#define pATTACHPROCESS 7117 ///< IOCTL code: attach a process to the driver. Used in Win9x only. +#define pDETACHPROCESS 7118 ///< IOCTL code: detach a process from the driver. Used in Win9x only. +#define pBIOCSETDUMPFILENAME 9029 ///< IOCTL code: set the name of a the file used by kernel dump mode. +#define pBIOCEVNAME 7415 ///< IOCTL code: get the name of the event that the driver signals when some data is present in the buffer. +#define pBIOCSENDPACKETSNOSYNC 9032 ///< IOCTL code: Send a buffer containing multiple packets to the network, ignoring the timestamps associated with the packets. +#define pBIOCSENDPACKETSSYNC 9033 ///< IOCTL code: Send a buffer containing multiple packets to the network, respecting the timestamps associated with the packets. +#define pBIOCSETDUMPLIMITS 9034 ///< IOCTL code: Set the dump file limits. See the PacketSetDumpLimits() function. +#define pBIOCISDUMPENDED 7411 ///< IOCTL code: Get the status of the kernel dump process. See the PacketIsDumpEnded() function. + +#define pBIOCSTIMEZONE 7471 ///< IOCTL code: set time zone. Used in Win9x only. + + +/// Alignment macro. Defines the alignment size. +#define Packet_ALIGNMENT sizeof(int) +/// Alignment macro. Rounds up to the next even multiple of Packet_ALIGNMENT. +#define Packet_WORDALIGN(x) (((x)+(Packet_ALIGNMENT-1))&~(Packet_ALIGNMENT-1)) + + +#define NdisMediumNull -1 // Custom linktype: NDIS doesn't provide an equivalent +#define NdisMediumCHDLC -2 // Custom linktype: NDIS doesn't provide an equivalent +#define NdisMediumPPPSerial -3 // Custom linktype: NDIS doesn't provide an equivalent + +/*! + \brief Network type structure. + + This structure is used by the PacketGetNetType() function to return information on the current adapter's type and speed. +*/ +typedef struct NetType +{ + UINT LinkType; ///< The MAC of the current network adapter (see function PacketGetNetType() for more information) + ULONGLONG LinkSpeed; ///< The speed of the network in bits per second +}NetType; + + +//some definitions stolen from libpcap + +#ifndef BPF_MAJOR_VERSION + +/*! + \brief A BPF pseudo-assembly program. + + The program will be injected in the kernel by the PacketSetBPF() function and applied to every incoming packet. +*/ +struct bpf_program +{ + UINT bf_len; ///< Indicates the number of instructions of the program, i.e. the number of struct bpf_insn that will follow. + struct bpf_insn *bf_insns; ///< A pointer to the first instruction of the program. +}; + +/*! + \brief A single BPF pseudo-instruction. + + bpf_insn contains a single instruction for the BPF register-machine. It is used to send a filter program to the driver. +*/ +struct bpf_insn +{ + USHORT code; ///< Instruction type and addressing mode. + UCHAR jt; ///< Jump if true + UCHAR jf; ///< Jump if false + int k; ///< Generic field used for various purposes. +}; + +/*! + \brief Structure that contains a couple of statistics values on the current capture. + + It is used by packet.dll to return statistics about a capture session. +*/ +struct bpf_stat +{ + UINT bs_recv; ///< Number of packets that the driver received from the network adapter + ///< from the beginning of the current capture. This value includes the packets + ///< lost by the driver. + UINT bs_drop; ///< number of packets that the driver lost from the beginning of a capture. + ///< Basically, a packet is lost when the the buffer of the driver is full. + ///< In this situation the packet cannot be stored and the driver rejects it. + UINT ps_ifdrop; ///< drops by interface. XXX not yet supported + UINT bs_capt; ///< number of packets that pass the filter, find place in the kernel buffer and + ///< thus reach the application. +}; + +/*! + \brief Packet header. + + This structure defines the header associated with every packet delivered to the application. +*/ +struct bpf_hdr +{ + struct timeval bh_tstamp; ///< The timestamp associated with the captured packet. + ///< It is stored in a TimeVal structure. + UINT bh_caplen; ///< Length of captured portion. The captured portion can be different + ///< from the original packet, because it is possible (with a proper filter) + ///< to instruct the driver to capture only a portion of the packets. + UINT bh_datalen; ///< Original length of packet + USHORT bh_hdrlen; ///< Length of bpf header (this struct plus alignment padding). In some cases, + ///< a padding could be added between the end of this structure and the packet + ///< data for performance reasons. This filed can be used to retrieve the actual data + ///< of the packet. +}; + +/*! + \brief Dump packet header. + + This structure defines the header associated with the packets in a buffer to be used with PacketSendPackets(). + It is simpler than the bpf_hdr, because it corresponds to the header associated by WinPcap and libpcap to a + packet in a dump file. This makes straightforward sending WinPcap dump files to the network. +*/ +struct dump_bpf_hdr{ + struct timeval ts; ///< Time stamp of the packet + UINT caplen; ///< Length of captured portion. The captured portion can smaller than the + ///< the original packet, because it is possible (with a proper filter) to + ///< instruct the driver to capture only a portion of the packets. + UINT len; ///< Length of the original packet (off wire). +}; + + +#endif + +#define DOSNAMEPREFIX TEXT("Packet_") ///< Prefix added to the adapters device names to create the WinPcap devices +#define MAX_LINK_NAME_LENGTH 64 //< Maximum length of the devices symbolic links +#define NMAX_PACKET 65535 + +/* + * Desired design of maximum size and alignment. + * These are implementation specific. + */ +#define _SS_MAXSIZE 128 // Maximum size. +#define _SS_ALIGNSIZE (sizeof(__int64)) // Desired alignment. + +/* + * Definitions used for sockaddr_storage structure paddings design. + */ +#define _SS_PAD1SIZE (_SS_ALIGNSIZE - sizeof (short)) +#define _SS_PAD2SIZE (_SS_MAXSIZE - (sizeof (short) + _SS_PAD1SIZE \ + + _SS_ALIGNSIZE)) +/* +struct sockaddr_storage { + short ss_family; // Address family. + char __ss_pad1[_SS_PAD1SIZE]; // 6 byte pad, this is to make + // implementation specific pad up to + // alignment field that follows explicit + // in the data structure. + __int64 __ss_align; // Field to force desired structure. + char __ss_pad2[_SS_PAD2SIZE]; // 112 byte pad to achieve desired size; + // _SS_MAXSIZE value minus size of + // ss_family, __ss_pad1, and + // __ss_align fields is 112. +}; +*/ +/*! + \brief Addresses of a network adapter. + + This structure is used by the PacketGetNetInfoEx() function to return the IP addresses associated with + an adapter. +*/ +typedef struct npf_if_addr { + struct sockaddr_storage IPAddress; ///< IP address. + struct sockaddr_storage SubnetMask; ///< Netmask for that address. + struct sockaddr_storage Broadcast; ///< Broadcast address. +}npf_if_addr; + + +#define ADAPTER_NAME_LENGTH 256 + 12 ///< Maximum length for the name of an adapter. The value is the same used by the IP Helper API. +#define ADAPTER_DESC_LENGTH 128 ///< Maximum length for the description of an adapter. The value is the same used by the IP Helper API. +#define MAX_MAC_ADDR_LENGTH 8 ///< Maximum length for the link layer address of an adapter. The value is the same used by the IP Helper API. +#define MAX_NETWORK_ADDRESSES 16 ///< Maximum length for the link layer address of an adapter. The value is the same used by the IP Helper API. + + +typedef struct WAN_ADAPTER_INT WAN_ADAPTER; ///< Describes an opened wan (dialup, VPN...) network adapter using the NetMon API +typedef WAN_ADAPTER *PWAN_ADAPTER; ///< Describes an opened wan (dialup, VPN...) network adapter using the NetMon API + +#define INFO_FLAG_NDIS_ADAPTER 0 ///< Flag for ADAPTER_INFO: this is a traditional ndis adapter +#define INFO_FLAG_NDISWAN_ADAPTER 1 ///< Flag for ADAPTER_INFO: this is a NdisWan adapter +#define INFO_FLAG_DAG_CARD 2 ///< Flag for ADAPTER_INFO: this is a DAG card +#define INFO_FLAG_DAG_FILE 6 ///< Flag for ADAPTER_INFO: this is a DAG file +#define INFO_FLAG_DONT_EXPORT 8 ///< Flag for ADAPTER_INFO: when this flag is set, the adapter will not be listed or openend by winpcap. This allows to prevent exporting broken network adapters, like for example FireWire ones. + +/*! + \brief Contains comprehensive information about a network adapter. + + This structure is filled with all the accessory information that the user can need about an adapter installed + on his system. +*/ +typedef struct _ADAPTER_INFO +{ + struct _ADAPTER_INFO *Next; ///< Pointer to the next adapter in the list. + CHAR Name[ADAPTER_NAME_LENGTH + 1]; ///< Name of the device representing the adapter. + CHAR Description[ADAPTER_DESC_LENGTH + 1]; ///< Human understandable description of the adapter + UINT MacAddressLen; ///< Length of the link layer address. + UCHAR MacAddress[MAX_MAC_ADDR_LENGTH]; ///< Link layer address. + NetType LinkLayer; ///< Physical characteristics of this adapter. This NetType structure contains the link type and the speed of the adapter. + INT NNetworkAddresses; ///< Number of network layer addresses of this adapter. + npf_if_addr *NetworkAddresses; ///< Pointer to an array of npf_if_addr, each of which specifies a network address of this adapter. + UINT Flags; ///< Adapter's flags. Tell if this adapter must be treated in a different way, using the Netmon API or the dagc API. +} +ADAPTER_INFO, *PADAPTER_INFO; + +/*! + \brief Describes an opened network adapter. + + This structure is the most important for the functioning of packet.dll, but the great part of its fields + should be ignored by the user, since the library offers functions that avoid to cope with low-level parameters +*/ +typedef struct _ADAPTER { + HANDLE hFile; ///< \internal Handle to an open instance of the NPF driver. + CHAR SymbolicLink[MAX_LINK_NAME_LENGTH]; ///< \internal A string containing the name of the network adapter currently opened. + int NumWrites; ///< \internal Number of times a packets written on this adapter will be repeated + ///< on the wire. + HANDLE ReadEvent; ///< A notification event associated with the read calls on the adapter. + ///< It can be passed to standard Win32 functions (like WaitForSingleObject + ///< or WaitForMultipleObjects) to wait until the driver's buffer contains some + ///< data. It is particularly useful in GUI applications that need to wait + ///< concurrently on several events. In Windows NT/2000 the PacketSetMinToCopy() + ///< function can be used to define the minimum amount of data in the kernel buffer + ///< that will cause the event to be signalled. + + UINT ReadTimeOut; ///< \internal The amount of time after which a read on the driver will be released and + ///< ReadEvent will be signaled, also if no packets were captured + CHAR Name[ADAPTER_NAME_LENGTH]; + PWAN_ADAPTER pWanAdapter; + UINT Flags; ///< Adapter's flags. Tell if this adapter must be treated in a different way, using the Netmon API or the dagc API. +#ifdef HAVE_DAG_API + dagc_t *pDagCard; ///< Pointer to the dagc API adapter descriptor for this adapter + PCHAR DagBuffer; ///< Pointer to the buffer with the packets that is received from the DAG card + struct timeval DagReadTimeout; ///< Read timeout. The dagc API requires a timeval structure + unsigned DagFcsLen; ///< Length of the frame check sequence attached to any packet by the card. Obtained from the registry + DWORD DagFastProcess; ///< True if the user requests fast capture processing on this card. Higher level applications can use this value to provide a faster but possibly unprecise capture (for example, libpcap doesn't convert the timestamps). +#endif // HAVE_DAG_API +} ADAPTER, *LPADAPTER; + +/*! + \brief Structure that contains a group of packets coming from the driver. + + This structure defines the header associated with every packet delivered to the application. +*/ +typedef struct _PACKET { + HANDLE hEvent; ///< \deprecated Still present for compatibility with old applications. + OVERLAPPED OverLapped; ///< \deprecated Still present for compatibility with old applications. + PVOID Buffer; ///< Buffer with containing the packets. See the PacketReceivePacket() for + ///< details about the organization of the data in this buffer + UINT Length; ///< Length of the buffer + DWORD ulBytesReceived; ///< Number of valid bytes present in the buffer, i.e. amount of data + ///< received by the last call to PacketReceivePacket() + BOOLEAN bIoComplete; ///< \deprecated Still present for compatibility with old applications. +} PACKET, *LPPACKET; + +/*! + \brief Structure containing an OID request. + + It is used by the PacketRequest() function to send an OID to the interface card driver. + It can be used, for example, to retrieve the status of the error counters on the adapter, its MAC address, + the list of the multicast groups defined on it, and so on. +*/ +struct _PACKET_OID_DATA { + ULONG Oid; ///< OID code. See the Microsoft DDK documentation or the file ntddndis.h + ///< for a complete list of valid codes. + ULONG Length; ///< Length of the data field + UCHAR Data[1]; ///< variable-lenght field that contains the information passed to or received + ///< from the adapter. +}; +typedef struct _PACKET_OID_DATA PACKET_OID_DATA, *PPACKET_OID_DATA; + + +#if _DBG +#define ODS(_x) OutputDebugString(TEXT(_x)) +#define ODSEx(_x, _y) +#else +#ifdef _DEBUG_TO_FILE +/*! + \brief Macro to print a debug string. The behavior differs depending on the debug level +*/ +#define ODS(_x) { \ + FILE *f; \ + f = fopen("winpcap_debug.txt", "a"); \ + fprintf(f, "%s", _x); \ + fclose(f); \ +} +/*! + \brief Macro to print debug data with the printf convention. The behavior differs depending on + the debug level +*/ +#define ODSEx(_x, _y) { \ + FILE *f; \ + f = fopen("winpcap_debug.txt", "a"); \ + fprintf(f, _x, _y); \ + fclose(f); \ +} + + + +LONG PacketDumpRegistryKey(PCHAR KeyName, PCHAR FileName); +#else +#define ODS(_x) +#define ODSEx(_x, _y) +#endif +#endif + +/* We load dinamically the dag library in order link it only when it's present on the system */ +#ifdef HAVE_DAG_API +typedef dagc_t* (*dagc_open_handler)(const char *source, unsigned flags, char *ebuf); ///< prototype used to dynamically load the dag dll +typedef void (*dagc_close_handler)(dagc_t *dagcfd); ///< prototype used to dynamically load the dag dll +typedef int (*dagc_getlinktype_handler)(dagc_t *dagcfd); ///< prototype used to dynamically load the dag dll +typedef int (*dagc_getlinkspeed_handler)(dagc_t *dagcfd); ///< prototype used to dynamically load the dag dll +typedef int (*dagc_setsnaplen_handler)(dagc_t *dagcfd, unsigned snaplen); ///< prototype used to dynamically load the dag dll +typedef unsigned (*dagc_getfcslen_handler)(dagc_t *dagcfd); ///< prototype used to dynamically load the dag dll +typedef int (*dagc_receive_handler)(dagc_t *dagcfd, u_char **buffer, u_int *bufsize); ///< prototype used to dynamically load the dag dll +typedef int (*dagc_stats_handler)(dagc_t *dagcfd, dagc_stats_t *ps); ///< prototype used to dynamically load the dag dll +typedef int (*dagc_wait_handler)(dagc_t *dagcfd, struct timeval *timeout); ///< prototype used to dynamically load the dag dll +typedef int (*dagc_finddevs_handler)(dagc_if_t **alldevsp, char *ebuf); ///< prototype used to dynamically load the dag dll +typedef int (*dagc_freedevs_handler)(dagc_if_t *alldevsp); ///< prototype used to dynamically load the dag dll +#endif // HAVE_DAG_API + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @} + */ + +// The following is used to check the adapter name in PacketOpenAdapterNPF and prevent +// opening of firewire adapters +#define FIREWIRE_SUBSTR L"1394" + +void PacketPopulateAdaptersInfoList(); +PWCHAR SChar2WChar(PCHAR string); +PCHAR WChar2SChar(PWCHAR string); +BOOL PacketGetFileVersion(LPTSTR FileName, PCHAR VersionBuff, UINT VersionBuffLen); +PADAPTER_INFO PacketFindAdInfo(PCHAR AdapterName); +BOOLEAN PacketUpdateAdInfo(PCHAR AdapterName); +BOOLEAN IsFireWire(TCHAR *AdapterDesc); + + +//--------------------------------------------------------------------------- +// EXPORTED FUNCTIONS +//--------------------------------------------------------------------------- + +PCHAR PacketGetVersion(); +PCHAR PacketGetDriverVersion(); +BOOLEAN PacketSetMinToCopy(LPADAPTER AdapterObject,int nbytes); +BOOLEAN PacketSetNumWrites(LPADAPTER AdapterObject,int nwrites); +BOOLEAN PacketSetMode(LPADAPTER AdapterObject,int mode); +BOOLEAN PacketSetReadTimeout(LPADAPTER AdapterObject,int timeout); +BOOLEAN PacketSetBpf(LPADAPTER AdapterObject,struct bpf_program *fp); +INT PacketSetSnapLen(LPADAPTER AdapterObject,int snaplen); +BOOLEAN PacketGetStats(LPADAPTER AdapterObject,struct bpf_stat *s); +BOOLEAN PacketGetStatsEx(LPADAPTER AdapterObject,struct bpf_stat *s); +BOOLEAN PacketSetBuff(LPADAPTER AdapterObject,int dim); +BOOLEAN PacketGetNetType (LPADAPTER AdapterObject,NetType *type); +LPADAPTER PacketOpenAdapter(PCHAR AdapterName); +BOOLEAN PacketSendPacket(LPADAPTER AdapterObject,LPPACKET pPacket,BOOLEAN Sync); +INT PacketSendPackets(LPADAPTER AdapterObject,PVOID PacketBuff,ULONG Size, BOOLEAN Sync); +LPPACKET PacketAllocatePacket(void); +VOID PacketInitPacket(LPPACKET lpPacket,PVOID Buffer,UINT Length); +VOID PacketFreePacket(LPPACKET lpPacket); +BOOLEAN PacketReceivePacket(LPADAPTER AdapterObject,LPPACKET lpPacket,BOOLEAN Sync); +BOOLEAN PacketSetHwFilter(LPADAPTER AdapterObject,ULONG Filter); +BOOLEAN PacketGetAdapterNames(PTSTR pStr,PULONG BufferSize); +BOOLEAN PacketGetNetInfoEx(PCHAR AdapterName, npf_if_addr* buffer, PLONG NEntries); +BOOLEAN PacketRequest(LPADAPTER AdapterObject,BOOLEAN Set,PPACKET_OID_DATA OidData); +HANDLE PacketGetReadEvent(LPADAPTER AdapterObject); +BOOLEAN PacketSetDumpName(LPADAPTER AdapterObject, void *name, int len); +BOOLEAN PacketSetDumpLimits(LPADAPTER AdapterObject, UINT maxfilesize, UINT maxnpacks); +BOOLEAN PacketIsDumpEnded(LPADAPTER AdapterObject, BOOLEAN sync); +BOOL PacketStopDriver(); +VOID PacketCloseAdapter(LPADAPTER lpAdapter); + +#ifdef __cplusplus +} +#endif + +#endif //__PACKET32 diff --git a/plugins/dev9ghzdrk/Win32/pcap_io.h b/plugins/dev9ghzdrk/Win32/pcap_io.h new file mode 100644 index 0000000000..c107882206 --- /dev/null +++ b/plugins/dev9ghzdrk/Win32/pcap_io.h @@ -0,0 +1,161 @@ +#pragma once +#include "net.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#pragma pack(push,1) + +typedef struct _ip_address +{ + u_char bytes[4]; +} ip_address; + +typedef struct _mac_address +{ + u_char bytes[6]; +} mac_address; + +typedef struct _ethernet_header +{ + mac_address dst; + mac_address src; + u_short protocol; +} ethernet_header; + +typedef struct _arp_packet +{ + u_short hw_type; + u_short protocol; + u_char h_addr_len; + u_char p_addr_len; + u_short operation; + mac_address h_src; + ip_address p_src; + mac_address h_dst; + ip_address p_dst; +} arp_packet; + +typedef struct _ip_header { + u_char ver_hlen; /* version << 4 | header length >> 2 */ + u_char type; /* type of service */ + u_short len; /* total length */ + u_short id; /* identification */ + u_short offset; /* fragment offset field */ + u_char ttl; /* time to live */ + u_char proto; /* protocol */ + u_short hdr_csum; /* checksum */ + ip_address src; /* source and dest address */ + ip_address dst; +} ip_header; + +/* Internet Control Message Protocol Constants and Packet Format */ + +/* ic_type field */ +#define ICT_ECHORP 0 /* Echo reply */ +#define ICT_DESTUR 3 /* Destination unreachable */ +#define ICT_SRCQ 4 /* Source quench */ +#define ICT_REDIRECT 5 /* Redirect message type */ +#define ICT_ECHORQ 8 /* Echo request */ +#define ICT_TIMEX 11 /* Time exceeded */ +#define ICT_PARAMP 12 /* Parameter Problem */ +#define ICT_TIMERQ 13 /* Timestamp request */ +#define ICT_TIMERP 14 /* Timestamp reply */ +#define ICT_INFORQ 15 /* Information request */ +#define ICT_INFORP 16 /* Information reply */ +#define ICT_MASKRQ 17 /* Mask request */ +#define ICT_MASKRP 18 /* Mask reply */ + +/* ic_code field */ +#define ICC_NETUR 0 /* dest unreachable, net unreachable */ +#define ICC_HOSTUR 1 /* dest unreachable, host unreachable */ +#define ICC_PROTOUR 2 /* dest unreachable, proto unreachable */ +#define ICC_PORTUR 3 /* dest unreachable, port unreachable */ +#define ICC_FNADF 4 /* dest unr, frag needed & don't frag */ +#define ICC_SRCRT 5 /* dest unreachable, src route failed */ + +#define ICC_NETRD 0 /* redirect: net */ +#define ICC_HOSTRD 1 /* redirect: host */ +#define IC_TOSNRD 2 /* redirect: type of service, net */ +#define IC_TOSHRD 3 /* redirect: type of service, host */ + +#define ICC_TIMEX 0 /* time exceeded, ttl */ +#define ICC_FTIMEX 1 /* time exceeded, frag */ + +#define IC_HLEN 8 /* octets */ +#define IC_PADLEN 3 /* pad length (octets) */ + +#define IC_RDTTL 300 /* ttl for redirect routes */ + + +/* ICMP packet format (following the IP header) */ +typedef struct _icmp_header { /* ICMP packet */ + char type; /* type of message (ICT_* above)*/ + char code; /* code (ICC_* above) */ + short csum; /* checksum of ICMP header+data */ + + union { + struct { + int ic1_id:16; /* echo type, a message id */ + int ic1_seq:16;/* echo type, a seq. number */ + } ic1; + ip_address ic2_gw; /* for redirect, gateway */ + struct { + char ic3_ptr;/* pointer, for ICT_PARAMP */ + char ic3_pad[IC_PADLEN]; + } ic3; + int ic4_mbz; /* must be zero */ + } icu; +} icmp_header; + +/*typedef struct _udp_header { + u16 src_port; + u16 dst_port; + u16 len; + u16 csum; +} udp_header;*/ + +typedef struct _full_arp_packet +{ + ethernet_header header; + arp_packet arp; +} full_arp_packet; + +#pragma pack(pop) + +#define ARP_REQUEST 0x0100 //values are big-endian + +extern mac_address virtual_mac; +extern mac_address broadcast_mac; + +extern ip_address virtual_ip; + +#define mac_compare(a,b) (memcmp(&(a),&(b),6)) +#define ip_compare(a,b) (memcmp(&(a),&(b),4)) + +/* +int pcap_io_init(char *adapter); +int pcap_io_send(void* packet, int plen); +int pcap_io_recv(void* packet, int max_len); +void pcap_io_close(); +*/ +int pcap_io_get_dev_num(); +char* pcap_io_get_dev_desc(int num,int md); +char* pcap_io_get_dev_name(int num,int md); + +#ifdef __cplusplus +} +#endif + +class PCAPAdapter : public NetAdapter +{ +public: + PCAPAdapter(); + virtual bool blocks(); + //gets a packet.rv :true success + virtual bool recv(NetPacket* pkt); + //sends the packet and deletes it when done (if successful).rv :true success + virtual bool send(NetPacket* pkt); + virtual ~PCAPAdapter(); +}; \ No newline at end of file diff --git a/plugins/dev9ghzdrk/Win32/resource.h b/plugins/dev9ghzdrk/Win32/resource.h new file mode 100644 index 0000000000..c1a6c820e6 --- /dev/null +++ b/plugins/dev9ghzdrk/Win32/resource.h @@ -0,0 +1,25 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Developer Studio generated include file. +// Used by DEV9linuz.rc +// +#define IDD_CONFDLG 101 +#define IDD_CONFIG 101 +#define IDD_ABOUT 103 +#define IDC_NAME 1000 +#define IDC_COMBO1 1007 +#define IDC_ETHDEV 1007 +#define IDC_BAYTYPE 1008 +#define IDC_ETHENABLED 1009 +#define IDC_HDDFILE 1010 +#define IDC_HDDENABLED 1011 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 105 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1011 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/plugins/dev9ghzdrk/Win32/smap.cpp b/plugins/dev9ghzdrk/Win32/smap.cpp new file mode 100644 index 0000000000..b48bbb08de --- /dev/null +++ b/plugins/dev9ghzdrk/Win32/smap.cpp @@ -0,0 +1,854 @@ +#define WINVER 0x0600 +#define _WIN32_WINNT 0x0600 +#include +#include +#include +#include +#include +#include +#include +#include + +#include "smap.h" +#include "net.h" +#include "pcap.h" +#include "pcap_io.h" +#include "tap.h" + +bool has_link=true; +/* +#define SMAP_BASE 0xb0000000 +#define SMAP_REG8(Offset) (*(u8 volatile*)(SMAP_BASE+(Offset))) +#define SMAP_REG16(Offset) (*(u16 volatile*)(SMAP_BASE+(Offset))) +#define SMAP_REG32(Offset) (*(u32 volatile*)(SMAP_BASE+(Offset))) + +u32 EMAC3REG_READ(u32 u32Offset) +{ + u32 hi=SMAP_REG16(u32Offset); + u32 lo=SMAP_REG16(u32Offset+2); + return (hi<<16)|lo; +} + + +void EMAC3REG_WRITE(u32 u32Offset,u32 u32V) +{ + SMAP_REG16(u32Offset)=((u32V>>16)&0xFFFF); + SMAP_REG16(u32Offset+2)=(u32V&0xFFFF); +} +#define SMAP_EMAC3_BASE 0x2000 +#define SMAP_EMAC3_STA_CTRL (SMAP_EMAC3_BASE+0x5C) +void test() +{ + printf ("EMAC3R 0x%08X raw read 0x%08X\n",EMAC3REG_READ(SMAP_EMAC3_STA_CTRL),SMAP_REG32(SMAP_EMAC3_STA_CTRL)); +}*/ + +//this can return a false positive, but its not problem since it may say it cant recv while it can (no harm done, just delay on packets) +bool rx_fifo_can_rx() +{ + //check if RX is on & stuff like that here + + //Check if there is space on RXBD + if (dev9Ru8(SMAP_R_RXFIFO_FRAME_CNT)==64) + return false; + + //Check if there is space on fifo + int rd_ptr = dev9Ru32(SMAP_R_RXFIFO_RD_PTR); + int space = sizeof(dev9.rxfifo) - + ((dev9.rxfifo_wr_ptr-rd_ptr)&16383); + + + if(space==0) + space = sizeof(dev9.rxfifo); + + if (space<1514) + return false; + + //we can recv a packet ! + return true; +} +void rx_process(NetPacket* pk) +{ + if (!rx_fifo_can_rx()) + { + emu_printf("ERROR : !rx_fifo_can_rx at rx_process\n"); + return; + } + smap_bd_t *pbd= ((smap_bd_t *)&dev9.dev9R[SMAP_BD_RX_BASE & 0xffff])+dev9.rxbdi; + + int bytes=(pk->size+3)&(~3); + + if (!(pbd->ctrl_stat & SMAP_BD_RX_EMPTY)) + { + emu_printf("ERROR : Discarding %d bytes (RX%d not ready)\n", bytes, dev9.rxbdi); + return; + } + + int pstart=(dev9.rxfifo_wr_ptr)&16383; + int i=0; + while(ibuffer[i++]); + dev9.rxfifo_wr_ptr&=16383; + } + + //increase RXBD + dev9.rxbdi++; + dev9.rxbdi&=(SMAP_BD_SIZE/8)-1; + + //Fill the BD with info ! + pbd->length = pk->size; + pbd->pointer = 0x4000 + pstart; + pbd->ctrl_stat&= ~SMAP_BD_RX_EMPTY; + + //increase frame count + dev9Ru8(SMAP_R_RXFIFO_FRAME_CNT)++; + //spams// emu_printf("Got packet, %d bytes (%d fifo)\n", pk->size,bytes); + _DEV9irq(SMAP_INTR_RXEND,0);//now ? or when the fifo is full ? i guess now atm + //note that this _is_ wrong since the IOP interrupt system is not thread safe.. but nothing i can do about that +} + +u32 wswap(u32 d) +{ + return (d>>16)|(d<<16); +} + +extern bool tx_p_first; +void tx_process() +{ + //we loop based on count ? or just *use* it ? + u32 cnt=dev9Ru8(SMAP_R_TXFIFO_FRAME_CNT); + //spams// printf("tx_process : %d cnt frames !\n",cnt); + + //Hack needed for GT4. Game fails to init the adapter otherwise (and notices about that via IOP kprintf on bootup). + //Reseting SMAP_R_TXFIFO_FRAME_CNT to 0 however breaks OPL. Thankfully not doing that fixes the problem while GT4 still works. + if (!tx_p_first) + { + //dev9Ru8(SMAP_R_TXFIFO_FRAME_CNT)=0; + tx_p_first=true; + //THIS IS A HACK.without that the stack wont init, i guess its missing e3/emac emulation .. + emu_printf("WARN : First packet interrupt hack ..\n"); + _DEV9irq(SMAP_INTR_RXEND|SMAP_INTR_TXEND|SMAP_INTR_TXDNV,100); + return; + } + + NetPacket pk; + int fc=0; + for (fc=0;fcctrl_stat&SMAP_BD_TX_READY)) + { + emu_printf("ERROR : !pbd->ctrl_stat&SMAP_BD_TX_READY\n"); + break; + } + if (pbd->length&3) + { + //spams// emu_printf("WARN : pbd->length not alligned %d\n",pbd->length); + } + + if(pbd->length>1514) + { + emu_printf("ERROR : Trying to send packet too big.\n"); + } + else + { + u32 base=(pbd->pointer-0x1000)&16383; + DEV9_LOG("Sending Packet from base %x, size %d\n", base, pbd->length); + //spams// emu_printf("Sending Packet from base %x, size %d\n", base, pbd->length); + + pk.size=pbd->length; + + if (!(pbd->pointer>=0x1000)) + { + emu_printf("ERROR: odd , !pbd->pointer>0x1000 | 0x%X %d\n", pbd->pointer, pbd->length); + } + //increase fifo pointer(s) + //uh does that even exist on real h/w ? + /* + if(dev9.txfifo_rd_ptr+pbd->length >= 16383) + { + //warp around ! + //first part + u32 was=16384-dev9.txfifo_rd_ptr; + memcpy(pk.buffer,dev9.txfifo+dev9.txfifo_rd_ptr,was); + //warp + dev9.txfifo_rd_ptr+=pbd->length; + dev9.txfifo_rd_ptr&=16383; + if (pbd->length!=was+dev9.txfifo_rd_ptr) + { + emu_printf("ERROR ON TX FIFO HANDLING, %x\n", dev9.txfifo_rd_ptr); + } + //second part + memcpy(pk.buffer+was,dev9.txfifo,pbd->length-was); + } + else + { //no warp or 'perfect' warp (reads end, resets to start + memcpy(pk.buffer,dev9.txfifo+dev9.txfifo_rd_ptr,pbd->length); + dev9.txfifo_rd_ptr+=pbd->length; + if (dev9.txfifo_rd_ptr==16384) + dev9.txfifo_rd_ptr=0; + } + + + + if (dev9.txfifo_rd_ptr&(~16383)) + { + emu_printf("ERROR ON TX FIFO HANDLING, %x\n", dev9.txfifo_rd_ptr); + } + */ + + if(base+pbd->length > 16384) + { + u32 was=16384-base; + memcpy(pk.buffer,dev9.txfifo+base,was); + memcpy(pk.buffer,dev9.txfifo,pbd->length-was); + printf("Warped read, was=%d, sz=%d, sz-was=%d\n",was,pbd->length,pbd->length-was); + } + else + { + memcpy(pk.buffer,dev9.txfifo+base,pbd->length); + } + tx_put(&pk); + } + + + pbd->ctrl_stat&= ~SMAP_BD_TX_READY; + + //increase TXBD + dev9.txbdi++; + dev9.txbdi&=(SMAP_BD_SIZE/8)-1; + + //decrease frame count -- this is not thread safe + dev9Ru8(SMAP_R_TXFIFO_FRAME_CNT)--; + } + + //spams// emu_printf("processed %d frames, %d count, cnt = %d\n",fc,dev9Ru8(SMAP_R_TXFIFO_FRAME_CNT),cnt); + //if some error/early exit signal TXDNV + if (fc!=cnt || cnt==0) + { + printf("WARN : (fc!=cnt || cnt==0) but packet send request was made oO..\n"); + _DEV9irq(SMAP_INTR_TXDNV,0); + } + //if we actualy send something send TXEND + if(fc!=0) + _DEV9irq(SMAP_INTR_TXEND,100);//now ? or when the fifo is empty ? i guess now atm +} + + +void emac3_write(u32 addr) +{ + u32 value=wswap(dev9Ru32(addr)); + switch(addr) + { + case SMAP_R_EMAC3_MODE0_L: + DEV9_LOG("SMAP: SMAP_R_EMAC3_MODE0 write %x\n", value); + value = (value & (~SMAP_E3_SOFT_RESET)) | SMAP_E3_TXMAC_IDLE | SMAP_E3_RXMAC_IDLE; + dev9Ru16(SMAP_R_EMAC3_STA_CTRL_H)|= SMAP_E3_PHY_OP_COMP; + break; + case SMAP_R_EMAC3_TxMODE0_L: + DEV9_LOG("SMAP: SMAP_R_EMAC3_TxMODE0_L write %x\n", value); + //spams// emu_printf("SMAP: SMAP_R_EMAC3_TxMODE0_L write %x\n", value); + //Process TX here ? + if (!value&SMAP_E3_TX_GNP_0) + emu_printf("SMAP_R_EMAC3_TxMODE0_L: SMAP_E3_TX_GNP_0 not set\n"); + + tx_process(); + value = value& ~SMAP_E3_TX_GNP_0; + if (value) + emu_printf("SMAP_R_EMAC3_TxMODE0_L: extra bits set !\n"); + break; + + case SMAP_R_EMAC3_TxMODE1_L: + emu_printf("SMAP_R_EMAC3_TxMODE1_L 32bit write %x\n", value); + break; + + + case SMAP_R_EMAC3_STA_CTRL_L: + DEV9_LOG("SMAP: SMAP_R_EMAC3_STA_CTRL write %x\n", value); + { + if (value & (SMAP_E3_PHY_READ)) + { + value|= SMAP_E3_PHY_OP_COMP; + int reg = value & (SMAP_E3_PHY_REG_ADDR_MSK); + u16 val = dev9.phyregs[reg]; + switch (reg) + { + case SMAP_DsPHYTER_BMSR: + if (has_link) + val|= SMAP_PHY_BMSR_LINK | SMAP_PHY_BMSR_ANCP; + break; + case SMAP_DsPHYTER_PHYSTS: + if (has_link) + val|= SMAP_PHY_STS_LINK |SMAP_PHY_STS_100M | SMAP_PHY_STS_FDX | SMAP_PHY_STS_ANCP; + break; + } + DEV9_LOG("phy_read %d: %x\n", reg, val); + value=(value&0xFFFF)|(val<<16); + } + if (value & (SMAP_E3_PHY_WRITE)) + { + value|= SMAP_E3_PHY_OP_COMP; + int reg = value & (SMAP_E3_PHY_REG_ADDR_MSK); + u16 val = value>>16; + switch (reg) + { + case SMAP_DsPHYTER_BMCR: + val&= ~SMAP_PHY_BMCR_RST; + val|= 0x1; + break; + } + DEV9_LOG("phy_write %d: %x\n", reg, val); + dev9.phyregs[reg] = val; + } + } + break; + default: + DEV9_LOG("SMAP: emac3 write %x=%x\n",addr, value); + } + dev9Ru32(addr)=wswap(value); +} +u8 CALLBACK smap_read8(u32 addr) +{ + switch(addr) + { + case SMAP_R_TXFIFO_FRAME_CNT: + printf("SMAP_R_TXFIFO_FRAME_CNT read 8\n"); + break; + case SMAP_R_RXFIFO_FRAME_CNT: + printf("SMAP_R_RXFIFO_FRAME_CNT read 8\n"); + break; + + case SMAP_R_BD_MODE: + return dev9.bd_swap; + + default: + DEV9_LOG("SMAP : Unknown 8 bit read @ %X,v=%X\n",addr,dev9Ru8(addr)); + return dev9Ru8(addr); + } + + DEV9_LOG("SMAP : error , 8 bit read @ %X,v=%X\n",addr,dev9Ru8(addr)); + return dev9Ru8(addr); +} +u16 CALLBACK smap_read16(u32 addr) +{ + if (addr >= SMAP_BD_TX_BASE && addr < (SMAP_BD_TX_BASE + SMAP_BD_SIZE)) + { + int rv = dev9Ru16(addr); + if(dev9.bd_swap) + return (rv<<8)|(rv>>8); + return rv; + /* + switch (addr & 0x7) + { + case 0: // ctrl_stat + hard = dev9Ru16(addr); + //DEV9_LOG("TX_CTRL_STAT[%d]: read %x\n", (addr - SMAP_BD_TX_BASE) / 8, hard); + if(dev9.bd_swap) + return (hard<<8)|(hard>>8); + return hard; + case 2: // unknown + hard = dev9Ru16(addr); + //DEV9_LOG("TX_UNKNOWN[%d]: read %x\n", (addr - SMAP_BD_TX_BASE) / 8, hard); + if(dev9.bd_swap) + return (hard<<8)|(hard>>8); + return hard; + case 4: // length + hard = dev9Ru16(addr); + DEV9_LOG("TX_LENGTH[%d]: read %x\n", (addr - SMAP_BD_TX_BASE) / 8, hard); + if(dev9.bd_swap) + return (hard<<8)|(hard>>8); + return hard; + case 6: // pointer + hard = dev9Ru16(addr); + DEV9_LOG("TX_POINTER[%d]: read %x\n", (addr - SMAP_BD_TX_BASE) / 8, hard); + if(dev9.bd_swap) + return (hard<<8)|(hard>>8); + return hard; + } + */ + } + else if (addr >= SMAP_BD_RX_BASE && addr < (SMAP_BD_RX_BASE + SMAP_BD_SIZE)) + { + int rv = dev9Ru16(addr); + if(dev9.bd_swap) + return (rv<<8)|(rv>>8); + return rv; + /* + switch (addr & 0x7) + { + case 0: // ctrl_stat + hard = dev9Ru16(addr); + //DEV9_LOG("RX_CTRL_STAT[%d]: read %x\n", (addr - SMAP_BD_RX_BASE) / 8, hard); + if(dev9.bd_swap) + return (hard<<8)|(hard>>8); + return hard; + case 2: // unknown + hard = dev9Ru16(addr); + //DEV9_LOG("RX_UNKNOWN[%d]: read %x\n", (addr - SMAP_BD_RX_BASE) / 8, hard); + if(dev9.bd_swap) + return (hard<<8)|(hard>>8); + return hard; + case 4: // length + hard = dev9Ru16(addr); + DEV9_LOG("RX_LENGTH[%d]: read %x\n", (addr - SMAP_BD_RX_BASE) / 8, hard); + if(dev9.bd_swap) + return (hard<<8)|(hard>>8); + return hard; + case 6: // pointer + hard = dev9Ru16(addr); + DEV9_LOG("RX_POINTER[%d]: read %x\n", (addr - SMAP_BD_RX_BASE) / 8, hard); + if(dev9.bd_swap) + return (hard<<8)|(hard>>8); + return hard; + } + */ + } + + switch(addr) + { +#ifdef DEV9_LOG_ENABLE + case SMAP_R_TXFIFO_FRAME_CNT: + printf("SMAP_R_TXFIFO_FRAME_CNT read 16\n"); + return dev9Ru16(addr); + case SMAP_R_RXFIFO_FRAME_CNT: + printf("SMAP_R_RXFIFO_FRAME_CNT read 16\n"); + return dev9Ru16(addr); + case SMAP_R_EMAC3_MODE0_L: + DEV9_LOG("SMAP_R_EMAC3_MODE0_L 16bit read %x\n", dev9Ru16(addr)); + return dev9Ru16(addr); + + case SMAP_R_EMAC3_MODE0_H: + DEV9_LOG("SMAP_R_EMAC3_MODE0_H 16bit read %x\n", dev9Ru16(addr)); + return dev9Ru16(addr); + + case SMAP_R_EMAC3_MODE1_L: + DEV9_LOG("SMAP_R_EMAC3_MODE1_L 16bit read %x\n", dev9Ru16(addr)); + return dev9Ru16(addr); + + case SMAP_R_EMAC3_MODE1_H: + DEV9_LOG("SMAP_R_EMAC3_MODE1_H 16bit read %x\n", dev9Ru16(addr)); + return dev9Ru16(addr); + + case SMAP_R_EMAC3_RxMODE_L: + DEV9_LOG("SMAP_R_EMAC3_RxMODE_L 16bit read %x\n", dev9Ru16(addr)); + return dev9Ru16(addr); + + case SMAP_R_EMAC3_RxMODE_H: + DEV9_LOG("SMAP_R_EMAC3_RxMODE_H 16bit read %x\n", dev9Ru16(addr)); + return dev9Ru16(addr); + + case SMAP_R_EMAC3_INTR_STAT_L: + DEV9_LOG("SMAP_R_EMAC3_INTR_STAT_L 16bit read %x\n", dev9Ru16(addr)); + return dev9Ru16(addr); + + case SMAP_R_EMAC3_INTR_STAT_H: + DEV9_LOG("SMAP_R_EMAC3_INTR_STAT_H 16bit read %x\n", dev9Ru16(addr)); + return dev9Ru16(addr); + + case SMAP_R_EMAC3_INTR_ENABLE_L: + DEV9_LOG("SMAP_R_EMAC3_INTR_ENABLE_L 16bit read %x\n", dev9Ru16(addr)); + return dev9Ru16(addr); + + case SMAP_R_EMAC3_INTR_ENABLE_H: + DEV9_LOG("SMAP_R_EMAC3_INTR_ENABLE_H 16bit read %x\n", dev9Ru16(addr)); + return dev9Ru16(addr); + + case SMAP_R_EMAC3_TxMODE0_L: + DEV9_LOG("SMAP_R_EMAC3_TxMODE0_L 16bit read %x\n", dev9Ru16(addr)); + return dev9Ru16(addr); + + case SMAP_R_EMAC3_TxMODE0_H: + DEV9_LOG("SMAP_R_EMAC3_TxMODE0_H 16bit read %x\n", dev9Ru16(addr)); + return dev9Ru16(addr); + + case SMAP_R_EMAC3_TxMODE1_L: + DEV9_LOG("SMAP_R_EMAC3_TxMODE1_L 16bit read %x\n", dev9Ru16(addr)); + return dev9Ru16(addr); + + case SMAP_R_EMAC3_TxMODE1_H: + DEV9_LOG("SMAP_R_EMAC3_TxMODE1_H 16bit read %x\n", dev9Ru16(addr)); + return dev9Ru16(addr); + + case SMAP_R_EMAC3_STA_CTRL_L: + DEV9_LOG("SMAP_R_EMAC3_STA_CTRL_L 16bit read %x\n", dev9Ru16(addr)); + return dev9Ru16(addr); + + case SMAP_R_EMAC3_STA_CTRL_H: + DEV9_LOG("SMAP_R_EMAC3_STA_CTRL_H 16bit read %x\n", dev9Ru16(addr)); + return dev9Ru16(addr); +#endif + default: + DEV9_LOG("SMAP : Unknown 16 bit read @ %X,v=%X\n",addr,dev9Ru16(addr)); + return dev9Ru16(addr); + } + + DEV9_LOG("SMAP : error , 16 bit read @ %X,v=%X\n",addr,dev9Ru16(addr)); + return dev9Ru16(addr); + +} +u32 CALLBACK smap_read32(u32 addr) +{ + if (addr>=SMAP_EMAC3_REGBASE && addr>24)|((rv>>8)&0xFF00)|((rv<<8)&0xFF0000); + + DEV9_LOG("SMAP_R_RXFIFO_DATA 32bit read %x\n", rv); + return rv; + } + default: + DEV9_LOG("SMAP : Unknown 32 bit read @ %X,v=%X\n",addr,dev9Ru32(addr)); + return dev9Ru32(addr); + } + + DEV9_LOG("SMAP : error , 32 bit read @ %X,v=%X\n",addr,dev9Ru32(addr)); + return dev9Ru32(addr); +} +void CALLBACK smap_write8(u32 addr, u8 value) +{ + switch(addr) + { + case SMAP_R_TXFIFO_FRAME_INC: + DEV9_LOG("SMAP_R_TXFIFO_FRAME_INC 8bit write %x\n", value); + { + dev9Ru8(SMAP_R_TXFIFO_FRAME_CNT)++; + } + return; + + case SMAP_R_RXFIFO_FRAME_DEC: + DEV9_LOG("SMAP_R_RXFIFO_FRAME_DEC 8bit write %x\n", value); + dev9Ru8(addr) = value; + { + dev9Ru8(SMAP_R_RXFIFO_FRAME_CNT)--; + } + return; + + case SMAP_R_TXFIFO_CTRL: + DEV9_LOG("SMAP_R_TXFIFO_CTRL 8bit write %x\n", value); + if(value&SMAP_TXFIFO_RESET) + { + dev9.txbdi=0; + dev9.txfifo_rd_ptr=0; + dev9Ru8(SMAP_R_TXFIFO_FRAME_CNT)=0; //this actualy needs to be atomic (lock mov ...) + dev9Ru32(SMAP_R_TXFIFO_WR_PTR)=0; + dev9Ru32(SMAP_R_TXFIFO_SIZE)=16384; + } + value&= ~SMAP_TXFIFO_RESET; + dev9Ru8(addr) = value; + return; + + case SMAP_R_RXFIFO_CTRL: + DEV9_LOG("SMAP_R_RXFIFO_CTRL 8bit write %x\n", value); + if(value&SMAP_RXFIFO_RESET) + { + dev9.rxbdi=0; + dev9.rxfifo_wr_ptr=0; + dev9Ru8(SMAP_R_RXFIFO_FRAME_CNT)=0; + dev9Ru32(SMAP_R_RXFIFO_RD_PTR)=0; + dev9Ru32(SMAP_R_RXFIFO_SIZE)=16384; + } + value&= ~SMAP_RXFIFO_RESET; + dev9Ru8(addr) = value; + return; + + case SMAP_R_BD_MODE: + if(value&SMAP_BD_SWAP) + { + DEV9_LOG("SMAP_R_BD_MODE: byteswapped.\n"); + emu_printf("BD Byteswapping enabled.\n"); + dev9.bd_swap=1; + } + else + { + DEV9_LOG("SMAP_R_BD_MODE: NOT byteswapped.\n"); + emu_printf("BD Byteswapping disabled.\n"); + dev9.bd_swap=0; + } + return; + default : + DEV9_LOG("SMAP : Unknown 8 bit write @ %X,v=%X\n",addr,value); + dev9Ru8(addr) = value; + return; + } + + DEV9_LOG("SMAP : error , 8 bit write @ %X,v=%X\n",addr,value); + dev9Ru8(addr) = value; +} +void CALLBACK smap_write16(u32 addr, u16 value) +{ + if (addr >= SMAP_BD_TX_BASE && addr < (SMAP_BD_TX_BASE + SMAP_BD_SIZE)) { + if(dev9.bd_swap) + value = (value>>8)|(value<<8); + dev9Ru16(addr) = value; + /* + switch (addr & 0x7) + { + case 0: // ctrl_stat + DEV9_LOG("TX_CTRL_STAT[%d]: write %x\n", (addr - SMAP_BD_TX_BASE) / 8, value); + //hacky + dev9Ru16(addr) = value; + return; + case 2: // unknown + //DEV9_LOG("TX_UNKNOWN[%d]: write %x\n", (addr - SMAP_BD_TX_BASE) / 8, value); + dev9Ru16(addr) = value; + return; + case 4: // length + DEV9_LOG("TX_LENGTH[%d]: write %x\n", (addr - SMAP_BD_TX_BASE) / 8, value); + dev9Ru16(addr) = value; + return; + case 6: // pointer + DEV9_LOG("TX_POINTER[%d]: write %x\n", (addr - SMAP_BD_TX_BASE) / 8, value); + dev9Ru16(addr) = value; + return; + } + */ + return; + } + else if (addr >= SMAP_BD_RX_BASE && addr < (SMAP_BD_RX_BASE + SMAP_BD_SIZE)) + { + int rx_index=(addr - SMAP_BD_RX_BASE)>>3; + if(dev9.bd_swap) + value = (value>>8)|(value<<8); + dev9Ru16(addr) = value; +/* + switch (addr & 0x7) + { + case 0: // ctrl_stat + DEV9_LOG("RX_CTRL_STAT[%d]: write %x\n", rx_index, value); + dev9Ru16(addr) = value; + if(value&0x8000) + { + DEV9_LOG(" * * PACKET READ COMPLETE: rd_ptr=%d, wr_ptr=%d\n", dev9Ru32(SMAP_R_RXFIFO_RD_PTR), dev9.rxfifo_wr_ptr); + } + return; + case 2: // unknown + //DEV9_LOG("RX_UNKNOWN[%d]: write %x\n", rx_index, value); + dev9Ru16(addr) = value; + return; + case 4: // length + DEV9_LOG("RX_LENGTH[%d]: write %x\n", rx_index, value); + dev9Ru16(addr) = value; + return; + case 6: // pointer + DEV9_LOG("RX_POINTER[%d]: write %x\n", rx_index, value); + dev9Ru16(addr) = value; + return; + } + */ + return; + } + + switch(addr) + { + case SMAP_R_INTR_CLR: + DEV9_LOG("SMAP: SMAP_R_INTR_CLR 16bit write %x\n", value); + dev9.irqcause&= ~value; + return; + + case SMAP_R_TXFIFO_WR_PTR: + DEV9_LOG("SMAP: SMAP_R_TXFIFO_WR_PTR 16bit write %x\n", value); + dev9Ru16(addr) = value; + return; +#define EMAC3_L_WRITE(name) \ + case name: \ + DEV9_LOG("SMAP: " #name " 16 bit write %x\n", value); \ + dev9Ru16(addr) = value; \ + return; + //handle L writes + EMAC3_L_WRITE(SMAP_R_EMAC3_MODE0_L ) + EMAC3_L_WRITE( SMAP_R_EMAC3_MODE1_L ) + EMAC3_L_WRITE( SMAP_R_EMAC3_TxMODE0_L ) + EMAC3_L_WRITE( SMAP_R_EMAC3_TxMODE1_L ) + EMAC3_L_WRITE( SMAP_R_EMAC3_RxMODE_L ) + EMAC3_L_WRITE( SMAP_R_EMAC3_INTR_STAT_L ) + EMAC3_L_WRITE( SMAP_R_EMAC3_INTR_ENABLE_L ) + EMAC3_L_WRITE( SMAP_R_EMAC3_ADDR_HI_L ) + EMAC3_L_WRITE( SMAP_R_EMAC3_ADDR_LO_L ) + EMAC3_L_WRITE( SMAP_R_EMAC3_VLAN_TPID ) + EMAC3_L_WRITE( SMAP_R_EMAC3_PAUSE_TIMER_L ) + EMAC3_L_WRITE( SMAP_R_EMAC3_INDIVID_HASH1 ) + EMAC3_L_WRITE( SMAP_R_EMAC3_INDIVID_HASH2 ) + EMAC3_L_WRITE( SMAP_R_EMAC3_INDIVID_HASH3 ) + EMAC3_L_WRITE( SMAP_R_EMAC3_INDIVID_HASH4 ) + EMAC3_L_WRITE( SMAP_R_EMAC3_GROUP_HASH1 ) + EMAC3_L_WRITE( SMAP_R_EMAC3_GROUP_HASH2 ) + EMAC3_L_WRITE( SMAP_R_EMAC3_GROUP_HASH3 ) + EMAC3_L_WRITE( SMAP_R_EMAC3_GROUP_HASH4 ) + + EMAC3_L_WRITE( SMAP_R_EMAC3_LAST_SA_HI ) + EMAC3_L_WRITE( SMAP_R_EMAC3_LAST_SA_LO ) + EMAC3_L_WRITE( SMAP_R_EMAC3_INTER_FRAME_GAP_L ) + EMAC3_L_WRITE( SMAP_R_EMAC3_STA_CTRL_L ) + EMAC3_L_WRITE( SMAP_R_EMAC3_TX_THRESHOLD_L ) + EMAC3_L_WRITE( SMAP_R_EMAC3_RX_WATERMARK_L ) + EMAC3_L_WRITE( SMAP_R_EMAC3_TX_OCTETS ) + EMAC3_L_WRITE( SMAP_R_EMAC3_RX_OCTETS ) + +#define EMAC3_H_WRITE(name) \ + case name: \ + DEV9_LOG("SMAP: " #name " 16 bit write %x\n", value); \ + dev9Ru16(addr) = value; \ + emac3_write(addr-2); \ + return; + //handle H writes + EMAC3_H_WRITE(SMAP_R_EMAC3_MODE0_H ) + EMAC3_H_WRITE( SMAP_R_EMAC3_MODE1_H ) + EMAC3_H_WRITE( SMAP_R_EMAC3_TxMODE0_H ) + EMAC3_H_WRITE( SMAP_R_EMAC3_TxMODE1_H ) + EMAC3_H_WRITE( SMAP_R_EMAC3_RxMODE_H ) + EMAC3_H_WRITE( SMAP_R_EMAC3_INTR_STAT_H ) + EMAC3_H_WRITE( SMAP_R_EMAC3_INTR_ENABLE_H ) + EMAC3_H_WRITE( SMAP_R_EMAC3_ADDR_HI_H ) + EMAC3_H_WRITE( SMAP_R_EMAC3_ADDR_LO_H ) + EMAC3_H_WRITE( SMAP_R_EMAC3_VLAN_TPID+2 ) + EMAC3_H_WRITE( SMAP_R_EMAC3_PAUSE_TIMER_H ) + EMAC3_H_WRITE( SMAP_R_EMAC3_INDIVID_HASH1+2 ) + EMAC3_H_WRITE( SMAP_R_EMAC3_INDIVID_HASH2+2 ) + EMAC3_H_WRITE( SMAP_R_EMAC3_INDIVID_HASH3+2 ) + EMAC3_H_WRITE( SMAP_R_EMAC3_INDIVID_HASH4+2 ) + EMAC3_H_WRITE( SMAP_R_EMAC3_GROUP_HASH1+2 ) + EMAC3_H_WRITE( SMAP_R_EMAC3_GROUP_HASH2+2 ) + EMAC3_H_WRITE( SMAP_R_EMAC3_GROUP_HASH3+2 ) + EMAC3_H_WRITE( SMAP_R_EMAC3_GROUP_HASH4+2 ) + + EMAC3_H_WRITE( SMAP_R_EMAC3_LAST_SA_HI+2 ) + EMAC3_H_WRITE( SMAP_R_EMAC3_LAST_SA_LO+2 ) + EMAC3_H_WRITE( SMAP_R_EMAC3_INTER_FRAME_GAP_H ) + EMAC3_H_WRITE( SMAP_R_EMAC3_STA_CTRL_H ) + EMAC3_H_WRITE( SMAP_R_EMAC3_TX_THRESHOLD_H ) + EMAC3_H_WRITE( SMAP_R_EMAC3_RX_WATERMARK_H ) + EMAC3_H_WRITE( SMAP_R_EMAC3_TX_OCTETS+2 ) + EMAC3_H_WRITE( SMAP_R_EMAC3_RX_OCTETS+2 ) +/* + case SMAP_R_EMAC3_MODE0_L: + DEV9_LOG("SMAP: SMAP_R_EMAC3_MODE0 write %x\n", value); + dev9Ru16(addr) = value; + return; + case SMAP_R_EMAC3_TxMODE0_L: + DEV9_LOG("SMAP: SMAP_R_EMAC3_TxMODE0_L 16bit write %x\n", value); + dev9Ru16(addr) = value; + return; + case SMAP_R_EMAC3_TxMODE1_L: + emu_printf("SMAP: SMAP_R_EMAC3_TxMODE1_L 16bit write %x\n", value); + dev9Ru16(addr) = value; + return; + + case SMAP_R_EMAC3_TxMODE0_H: + emu_printf("SMAP: SMAP_R_EMAC3_TxMODE0_H 16bit write %x\n", value); + dev9Ru16(addr) = value; + return; + + case SMAP_R_EMAC3_TxMODE1_H: + emu_printf("SMAP: SMAP_R_EMAC3_TxMODE1_H 16bit write %x\n", value); + dev9Ru16(addr) = value; + return; + case SMAP_R_EMAC3_STA_CTRL_H: + DEV9_LOG("SMAP: SMAP_R_EMAC3_STA_CTRL_H 16bit write %x\n", value); + dev9Ru16(addr) = value; + return; + */ + + default : + DEV9_LOG("SMAP : Unknown 16 bit write @ %X,v=%X\n",addr,value); + dev9Ru16(addr) = value; + return; + } + + DEV9_LOG("SMAP : error , 16 bit write @ %X,v=%X\n",addr,value); + dev9Ru16(addr) = value; +} +void CALLBACK smap_write32(u32 addr, u32 value) +{ + if (addr>=SMAP_EMAC3_REGBASE && addr>16); + return; + } + switch(addr) + { + case SMAP_R_TXFIFO_DATA: + if(dev9.bd_swap) + value=(value<<24)|(value>>24)|((value>>8)&0xFF00)|((value<<8)&0xFF0000); + + DEV9_LOG("SMAP_R_TXFIFO_DATA 32bit write %x\n", value); + *((u32*)(dev9.txfifo+dev9Ru32(SMAP_R_TXFIFO_WR_PTR)))=value; + dev9Ru32(SMAP_R_TXFIFO_WR_PTR) = (dev9Ru32(SMAP_R_TXFIFO_WR_PTR)+4)&16383; + return; + default : + DEV9_LOG("SMAP : Unknown 32 bit write @ %X,v=%X\n",addr,value); + dev9Ru32(addr) = value; + return; + } + + DEV9_LOG("SMAP : error , 32 bit write @ %X,v=%X\n",addr,value); + dev9Ru32(addr) = value; +} +void CALLBACK smap_readDMA8Mem(u32 *pMem, int size) +{ + if(dev9Ru16(SMAP_R_RXFIFO_CTRL)&SMAP_RXFIFO_DMAEN) + { + dev9Ru32(SMAP_R_RXFIFO_RD_PTR)&=16383; + size>>=1; + DEV9_LOG(" * * SMAP DMA READ START: rd_ptr=%d, wr_ptr=%d\n", dev9Ru32(SMAP_R_RXFIFO_RD_PTR), dev9.rxfifo_wr_ptr); + while(size>0) + { + *pMem = *((u32*)(dev9.rxfifo+dev9Ru32(SMAP_R_RXFIFO_RD_PTR))); + pMem++; + dev9Ru32(SMAP_R_RXFIFO_RD_PTR) = (dev9Ru32(SMAP_R_RXFIFO_RD_PTR)+4)&16383; + + size-=4; + } + DEV9_LOG(" * * SMAP DMA READ END: rd_ptr=%d, wr_ptr=%d\n", dev9Ru32(SMAP_R_RXFIFO_RD_PTR), dev9.rxfifo_wr_ptr); + + dev9Ru16(SMAP_R_RXFIFO_CTRL) &= ~SMAP_RXFIFO_DMAEN; + } +} +void CALLBACK smap_writeDMA8Mem(u32* pMem, int size) +{ + if(dev9Ru16(SMAP_R_TXFIFO_CTRL)&SMAP_TXFIFO_DMAEN) + { + dev9Ru32(SMAP_R_TXFIFO_WR_PTR)&=16383; + size>>=1; + DEV9_LOG(" * * SMAP DMA WRITE START: wr_ptr=%d, rd_ptr=%d\n", dev9Ru32(SMAP_R_TXFIFO_WR_PTR), dev9.txfifo_rd_ptr); + while(size>0) + { + int value=*pMem; + // value=(value<<24)|(value>>24)|((value>>8)&0xFF00)|((value<<8)&0xFF0000); + pMem++; + + *((u32*)(dev9.txfifo+dev9Ru32(SMAP_R_TXFIFO_WR_PTR)))=value; + dev9Ru32(SMAP_R_TXFIFO_WR_PTR) = (dev9Ru32(SMAP_R_TXFIFO_WR_PTR)+4)&16383; + size-=4; + } + DEV9_LOG(" * * SMAP DMA WRITE END: wr_ptr=%d, rd_ptr=%d\n", dev9Ru32(SMAP_R_TXFIFO_WR_PTR), dev9.txfifo_rd_ptr); + + dev9Ru16(SMAP_R_TXFIFO_CTRL) &= ~SMAP_TXFIFO_DMAEN; + + } +} diff --git a/plugins/dev9ghzdrk/Win32/smap.h b/plugins/dev9ghzdrk/Win32/smap.h new file mode 100644 index 0000000000..4247bc19f7 --- /dev/null +++ b/plugins/dev9ghzdrk/Win32/smap.h @@ -0,0 +1,13 @@ +#pragma once +#include "..\dev9.h" + +u8 CALLBACK smap_read8(u32 addr); +u16 CALLBACK smap_read16(u32 addr); +u32 CALLBACK smap_read32(u32 addr); + +void CALLBACK smap_write8(u32 addr, u8 value); +void CALLBACK smap_write16(u32 addr, u16 value); +void CALLBACK smap_write32(u32 addr, u32 value); + +void CALLBACK smap_readDMA8Mem(u32 *pMem, int size); +void CALLBACK smap_writeDMA8Mem(u32 *pMem, int size); \ No newline at end of file diff --git a/plugins/dev9ghzdrk/Win32/socket_io.cpp b/plugins/dev9ghzdrk/Win32/socket_io.cpp new file mode 100644 index 0000000000..78b557243c --- /dev/null +++ b/plugins/dev9ghzdrk/Win32/socket_io.cpp @@ -0,0 +1,294 @@ +#include +#include + +#include +extern "C" { +#include "dev9.h" +} +#include + +#include "pcap_io.h" + +#include +#include +#include + +//extern "C" int emu_printf(const char *fmt, ...); + +mac_address gateway_mac = { 0x76, 0x6D, 0x61, 0x63, 0x30, 0x32 }; +mac_address virtual_mac = { 0x76, 0x6D, 0x61, 0x63, 0x30, 0x31 }; +mac_address broadcast_mac = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }; + +//mac_address host_mac = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; + +ip_address virtual_gway_ip = { 192, 168, 1, 1}; +ip_address virtual_host_ip = { 192, 168, 1, 2}; + +char namebuff[256]; + +FILE*packet_log; + +int pcap_io_running=0; + +class packet_info +{ +public: + int length; + s8 data[2048]; + + packet_info() + { + length=0; + memset(data,0,2048); + } + + packet_info(const packet_info& pkt) + { + length=pkt.length; + memcpy(data,pkt.data,length); + } + + packet_info(int l, void*d) + { + length=l; + memcpy(data,d,l); + } +}; + +std::queue recv_queue; + + +int ip_checksum(u16 *data, int length) +{ + int n=(length+1)>>1; + int s=0; + for(int i=0;i>16); + return s; +} + +// +int pcap_io_init(char *adapter) +{ + WSADATA wsaData; + + emu_printf(" * Socket IO: Initializing virtual gateway...",adapter); + + WSAStartup(0x0200,&wsaData); + + packet_log=fopen("logs/packet.log","w"); + + pcap_io_running=1; + + emu_printf("Ok.\n"); + return 0; +} + +int pcap_io_send(void* packet, int plen) +{ + emu_printf(" * Socket IO: Sending %d byte packet.\n",plen); + + if(packet_log) + { + int i=0; + int n=0; + + fprintf(packet_log,"PACKET SEND: %d BYTES\n",plen); + for(i=0,n=0;idst,broadcast_mac)==0) //broadcast packets + { + if(eth->protocol == 0x0608) //ARP + { + arp_packet *arp = (arp_packet*)((s8*)packet+sizeof(ethernet_header)); + if(arp->operation == 0x0100) //ARP request + { + if(ip_compare(arp->p_dst,virtual_gway_ip)==0) //it's trying to resolve the virtual gateway's mac addr + { + full_arp_packet p; + p.header.src = gateway_mac; + p.header.dst = eth->src; + p.header.protocol = 0x0608; + p.arp.h_addr_len=6; + p.arp.h_dst = eth->src; + p.arp.h_src = gateway_mac; + p.arp.p_addr_len = 4; + p.arp.p_dst = arp->p_src; + p.arp.p_src = virtual_gway_ip; + p.arp.protocol = 0x0008; + p.arp.operation = 0x0200; + + //packet_info pkt(sizeof(p),&p) + recv_queue.push(packet_info(sizeof(p),&p)); + } + } + } + } + else if(mac_compare(eth->dst,gateway_mac)==0) + { + if(eth->protocol == 0x0008) //IP + { + ip_header *ip = (ip_header*)((s8*)packet+sizeof(ethernet_header)); + + if((ip->proto == 0x11) && (ip->dst.bytes[0]!=192)) //UDP (non-local) + { + // + //if(ip-> + } + else + if(ip->proto == 0x01) //ICMP + { + if (ip_compare(ip->dst,virtual_gway_ip)==0) //PING to gateway + { + static u8 icmp_packet[1024]; + + memcpy(icmp_packet,packet,plen); + + ethernet_header *eh = (ethernet_header *)icmp_packet; + + eh->dst=eth->src; + eh->src=gateway_mac; + + ip_header *iph = (ip_header*)(eh+1); + + iph->dst = ip->src; + iph->src = virtual_gway_ip; + + iph->hdr_csum = 0; + + int sum = ip_checksum((u16*)iph,sizeof(ip_header)); + iph->hdr_csum = sum; + + icmp_header *ich = (icmp_header*)(iph+1); + + ich->type=0; + ich->code=0; + ich->csum=0; + + sum = ip_checksum((u16*)ich,iph->len-sizeof(ip_header)); + ich->csum = sum; + + recv_queue.push(packet_info(plen,&icmp_packet)); + + } + else if (ip->dst.bytes[0] != 192) //PING to external + { + static u8 icmp_packet[1024]; + + memcpy(icmp_packet,packet,plen); + + ethernet_header *eh = (ethernet_header *)icmp_packet; + + eh->dst=eth->src; + eh->src=gateway_mac; + + ip_header *iph = (ip_header*)(eh+1); + + iph->dst = ip->src; + iph->src = virtual_gway_ip; + + iph->hdr_csum = 0; + + int sum = ip_checksum((u16*)iph,sizeof(ip_header)); + iph->hdr_csum = sum; + + icmp_header *ich = (icmp_header*)(iph+1); + + ich->type=0; + ich->code=0; + ich->csum=0; + + sum = ip_checksum((u16*)ich,iph->len-sizeof(ip_header)); + ich->csum = sum; + + recv_queue.push(packet_info(plen,&icmp_packet)); + + } + } + } + } + + return 0; +} + +int pcap_io_recv(void* packet, int max_len) +{ + if(pcap_io_running<=0) + return -1; + + if(!recv_queue.empty()) + { + packet_info pkt(recv_queue.front()); + recv_queue.pop(); + + memcpy(packet,pkt.data,pkt.length); + + if(packet_log) + { + int i=0; + int n=0; + int plen=pkt.length; + + fprintf(packet_log,"PACKET RECV: %d BYTES\n",plen); + for(i=0,n=0;i +#include + +#include "packet32.h" +#include "ntddndis.h" + +#include "socks.h" +#include "DEV9.h" + +#define BUFFER_SIZE (2048) + +LPADAPTER lpAdapter; +LPPACKET lpSendPacket; +LPPACKET lpRecvPacket; +u8 buffer[BUFFER_SIZE]; +u8 *buf; +int lbytes; +int tbytes; +typedef struct { + char name[256]; + char desc[256]; +} _Adapter; + +_Adapter AdapterList[16]; + +long sockOpen(char *Device) { + lpAdapter = PacketOpenAdapter(Device); + if (lpAdapter == NULL) return -1; + +#ifdef DEV9_LOG + DEV9_LOG("PacketOpenAdapter %s: %p\n", Device, lpAdapter); +#endif + + if(PacketSetHwFilter(lpAdapter,NDIS_PACKET_TYPE_PROMISCUOUS)==FALSE){ + SysMessage("Warning: unable to set promiscuous mode!"); + } + + if(PacketSetBuff(lpAdapter,512000)==FALSE){ + SysMessage("Unable to set the kernel buffer!"); + return -1; + } + + if(PacketSetReadTimeout(lpAdapter,100)==FALSE){ + SysMessage("Warning: unable to set the read tiemout!"); + } + + if((lpRecvPacket = PacketAllocatePacket())==NULL){ + SysMessage("Error: failed to allocate the LPPACKET structure."); + return (-1); + } + if((lpSendPacket = PacketAllocatePacket())==NULL){ + SysMessage("Error: failed to allocate the LPPACKET structure."); + return (-1); + } + + lbytes=0; + tbytes=0; + + return 0; +} + +void sockClose() { + PacketCloseAdapter(lpAdapter); +} + +long sockSendData(void *pData, int Size) { + u8 *data = (u8*)pData; +// printf("_sendPacket %d (time=%d)\n", Size, timeGetTime()); + while (Size > 0) { + PacketInitPacket(lpSendPacket, data, Size > 1024 ? 1024 : Size); + if(PacketSendPacket(lpAdapter,lpSendPacket,FALSE)==FALSE){ + printf("Error: PacketSendPacket failed\n"); + return (-1); + } + data+= 1024; Size-= 1024; + PacketFreePacket(lpSendPacket); + } + + return 0; +} + +int _filterPacket(u8 *_buf) { +/* DEV9_LOG("%2.2x:%2.2x:%2.2x:%2.2x:%2.2x:%2.2x\n", _buf[5], _buf[4], _buf[3], _buf[2], _buf[1], _buf[0]); + DEV9_LOG("%2.2x:%2.2x:%2.2x:%2.2x:%2.2x:%2.2x\n", _buf[11], _buf[10], _buf[9], _buf[8], _buf[7], _buf[6]); + DEV9_LOG("%2.2x:%2.2x:%2.2x:%2.2x:%2.2x:%2.2x\n", _buf[17], _buf[16], _buf[15], _buf[14], _buf[13], _buf[12]); + DEV9_LOG("%2.2x:%2.2x:%2.2x:%2.2x:%2.2x:%2.2x\n", _buf[23], _buf[22], _buf[21], _buf[20], _buf[19], _buf[18]); +*/ + if (_buf[0] == 0xff && _buf[1] == 0xff && _buf[2] == 0xff && + _buf[3] == 0xff && _buf[4] == 0xff && _buf[5] == 0xff) { + return 1; + } else + if (_buf[0] == 0x00 && _buf[1] == 0x00 && _buf[2] == 0x00 && + _buf[3] == 0x00 && _buf[4] == 0x00 && _buf[5] == 0x00) { + return 1; + } else + if (*((u16*)&_buf[12]) == 0x0806) { + printf("ARP\n"); + return 1; + } + + return 0; +} + +int _recvPacket(void *pData) { + struct bpf_hdr *hdr; + u8 *data; + int ret=0; + int size; + + while (lbytes > 0) { + hdr = (struct bpf_hdr *)buf; +// DEV9_LOG("hdr %d,%d,%d\n", hdr->bh_hdrlen, hdr->bh_caplen, hdr->bh_datalen); +// DEV9_LOG("lbytes %d\n", lbytes); + data = buf+hdr->bh_hdrlen; + size = Packet_WORDALIGN(hdr->bh_hdrlen+hdr->bh_datalen); + buf+= size; lbytes-= size; + if (_filterPacket(data)) { + struct bpf_stat stat; + + ret = hdr->bh_datalen; + memcpy(pData, data, ret); + if(PacketGetStats(lpAdapter,&stat)==FALSE){ + printf("Warning: unable to get stats from the kernel!\n"); + } +// printf("_recvPacket %d (tbytes=%d, packets=%d, lost=%d, time=%d)\n", ret, tbytes, stat.bs_recv,stat.bs_drop, timeGetTime()); +// printf("%2.2x:%2.2x:%2.2x:%2.2x:%2.2x:%2.2x\n", data[5], data[4], data[3], data[2], data[1], data[0]); + break; + } + } + + return ret; +} + +long sockRecvData(void *pData, int Size) { + int ret; + + ret = _recvPacket(pData); + if (ret > 0) return ret; + + PacketInitPacket(lpRecvPacket, buffer, BUFFER_SIZE); + if(PacketReceivePacket(lpAdapter,lpRecvPacket,TRUE)==FALSE){ + printf("Error: PacketReceivePacket failed"); + return (-1); + } + lbytes = lpRecvPacket->ulBytesReceived; + tbytes+= lbytes; +// DEV9_LOG("PacketReceivePacket %d:\n", lbytes); + if (lbytes == 0) return 0; + memcpy(buffer, lpRecvPacket->Buffer, lbytes); + buf = buffer; + PacketFreePacket(lpRecvPacket); + + return _recvPacket(pData); +} + +long sockGetDevicesNum() { + char AdapterName[8192]; // string that contains a list of the network adapters + ULONG AdapterLength; + char *temp,*temp1; + int i; + + AdapterLength = sizeof(AdapterName); + if(PacketGetAdapterNames(AdapterName,&AdapterLength)==FALSE){ + printf("Unable to retrieve the list of the adapters!\n"); + return -1; + } + temp=AdapterName; + temp1=AdapterName; + + i=0; + while (temp[0] != 0) { + strcpy(AdapterList[i++].name, temp); + temp+= strlen(temp)+1; + } + i=0; temp++; + while (temp[0] != 0) { + strcpy(AdapterList[i++].desc, temp); + temp+= strlen(temp)+1; + } + + return i; +} + +char *sockGetDevice(int index) { + return AdapterList[index].name; +} + +char *sockGetDeviceDesc(int index) { + return AdapterList[index].desc; +} + diff --git a/plugins/dev9ghzdrk/Win32/socks.h b/plugins/dev9ghzdrk/Win32/socks.h new file mode 100644 index 0000000000..55e29ef249 --- /dev/null +++ b/plugins/dev9ghzdrk/Win32/socks.h @@ -0,0 +1,12 @@ +#ifndef __SOCKS_H__ +#define __SOCKS_H__ + +long sockOpen(char *Device); +void sockClose(); +long sockSendData(void *pData, int Size); +long sockRecvData(void *pData, int Size); +long sockGetDevicesNum(); +char *sockGetDevice(int index); +char *sockGetDeviceDesc(int index); + +#endif /* __SOCKS_H__*/ diff --git a/plugins/dev9ghzdrk/Win32/tap-win32.cpp b/plugins/dev9ghzdrk/Win32/tap-win32.cpp new file mode 100644 index 0000000000..1223ec1dee --- /dev/null +++ b/plugins/dev9ghzdrk/Win32/tap-win32.cpp @@ -0,0 +1,1076 @@ +/* + * TAP-Win32 -- A kernel driver to provide virtual tap device functionality + * on Windows. Originally derived from the CIPE-Win32 + * project by Damion K. Wilson, with extensive modifications by + * James Yonan. + * + * All source code which derives from the CIPE-Win32 project is + * Copyright (C) Damion K. Wilson, 2003, and is released under the + * GPL version 2 (see below). + * + * All other source code is Copyright (C) James Yonan, 2003-2004, + * and is released under the GPL version 2 (see below). + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program (see the file COPYING included with this + * distribution); if not, write to the Free Software Foundation, Inc., + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ +#include +#include +#include "tap.h" +#include "..\dev9.h" +#include + +//============= +// TAP IOCTLs +//============= + +#define TAP_CONTROL_CODE(request,method) \ + CTL_CODE (FILE_DEVICE_UNKNOWN, request, method, FILE_ANY_ACCESS) + +#define TAP_IOCTL_GET_MAC TAP_CONTROL_CODE (1, METHOD_BUFFERED) +#define TAP_IOCTL_GET_VERSION TAP_CONTROL_CODE (2, METHOD_BUFFERED) +#define TAP_IOCTL_GET_MTU TAP_CONTROL_CODE (3, METHOD_BUFFERED) +#define TAP_IOCTL_GET_INFO TAP_CONTROL_CODE (4, METHOD_BUFFERED) +#define TAP_IOCTL_CONFIG_POINT_TO_POINT TAP_CONTROL_CODE (5, METHOD_BUFFERED) +#define TAP_IOCTL_SET_MEDIA_STATUS TAP_CONTROL_CODE (6, METHOD_BUFFERED) +#define TAP_IOCTL_CONFIG_DHCP_MASQ TAP_CONTROL_CODE (7, METHOD_BUFFERED) +#define TAP_IOCTL_GET_LOG_LINE TAP_CONTROL_CODE (8, METHOD_BUFFERED) +#define TAP_IOCTL_CONFIG_DHCP_SET_OPT TAP_CONTROL_CODE (9, METHOD_BUFFERED) + +//================= +// Registry keys +//================= + +#define ADAPTER_KEY "SYSTEM\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002BE10318}" + +#define NETWORK_CONNECTIONS_KEY "SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}" + +//====================== +// Filesystem prefixes +//====================== + +#define USERMODEDEVICEDIR "\\\\.\\Global\\" +#define TAPSUFFIX ".tap" + +#define TAP_COMPONENT_ID "tap0801" + +vector* get_tap_reg () +{ + vector* names = new vector(); + HKEY adapter_key; + LONG status; + DWORD len; + + int i = 0; + + status = RegOpenKeyEx( + HKEY_LOCAL_MACHINE, + ADAPTER_KEY, + 0, + KEY_READ, + &adapter_key); + + if (status != ERROR_SUCCESS) + printf ( "Error opening registry key: %s", ADAPTER_KEY); + + while (true) + { + char enum_name[256]; + char unit_string[256]; + HKEY unit_key; + char component_id_string[] = "ComponentId"; + char component_id[256]; + char net_cfg_instance_id_string[] = "NetCfgInstanceId"; + char net_cfg_instance_id[256]; + DWORD data_type; + + len = sizeof (enum_name); + status = RegEnumKeyEx( + adapter_key, + i, + enum_name, + &len, + NULL, + NULL, + NULL, + NULL); + if (status == ERROR_NO_MORE_ITEMS) + break; + else if (status != ERROR_SUCCESS) + printf ( "Error enumerating registry subkeys of key: %s", + ADAPTER_KEY); + + _snprintf (unit_string, sizeof(unit_string), "%s\\%s", + ADAPTER_KEY, enum_name); + + status = RegOpenKeyEx( + HKEY_LOCAL_MACHINE, + unit_string, + 0, + KEY_READ, + &unit_key); + + if (status != ERROR_SUCCESS) + printf ( "Error opening registry key: %s", unit_string); + else + { + len = sizeof (component_id); + status = RegQueryValueEx( + unit_key, + component_id_string, + NULL, + &data_type, + (LPBYTE)component_id, + &len); + + if (status != ERROR_SUCCESS || data_type != REG_SZ) + printf ( "Error opening registry key: %s\\%s", + unit_string, component_id_string); + else + { + len = sizeof (net_cfg_instance_id); + status = RegQueryValueEx( + unit_key, + net_cfg_instance_id_string, + NULL, + &data_type, + (LPBYTE)net_cfg_instance_id, + &len); + + if (status == ERROR_SUCCESS && data_type == REG_SZ) + { + if(!memcmp(component_id, "tap",3)) + { + printf("*** Found possible tap adapter: %s\n",component_id); + + int version = atoi(component_id+3); + if(version>=800) + { + names->push_back(net_cfg_instance_id); + } + } + } + } + RegCloseKey (unit_key); + } + ++i; + } + + RegCloseKey (adapter_key); + return names; +} + +struct temp_11{string name;string guid;}; +vector* get_panel_reg () +{ + LONG status; + HKEY network_connections_key; + DWORD len; + vector* names = new vector(); + int i = 0; + + status = RegOpenKeyEx( + HKEY_LOCAL_MACHINE, + NETWORK_CONNECTIONS_KEY, + 0, + KEY_READ, + &network_connections_key); + + if (status != ERROR_SUCCESS) + printf ( "Error opening registry key: %s", NETWORK_CONNECTIONS_KEY); + + while (true) + { + char enum_name[256]; + char connection_string[256]; + HKEY connection_key; + char name_data[256]; + DWORD name_type; + const char name_string[] = "Name"; + + len = sizeof (enum_name); + status = RegEnumKeyEx( + network_connections_key, + i, + enum_name, + &len, + NULL, + NULL, + NULL, + NULL); + if (status == ERROR_NO_MORE_ITEMS) + break; + else if (status != ERROR_SUCCESS) + printf ( "Error enumerating registry subkeys of key: %s", + NETWORK_CONNECTIONS_KEY); + + _snprintf (connection_string, sizeof(connection_string), + "%s\\%s\\Connection", + NETWORK_CONNECTIONS_KEY, enum_name); + + status = RegOpenKeyEx( + HKEY_LOCAL_MACHINE, + connection_string, + 0, + KEY_READ, + &connection_key); + + if (status != ERROR_SUCCESS) + printf ( "Error opening registry key: %s", connection_string); + else + { + len = sizeof (name_data); + status = RegQueryValueEx( + connection_key, + name_string, + NULL, + &name_type, + (LPBYTE)name_data, + &len); + + if (status != ERROR_SUCCESS || name_type != REG_SZ) + printf ( "Error opening registry key: %s\\%s\\%s", + NETWORK_CONNECTIONS_KEY, connection_string, name_string); + else + { + temp_11 t = {name_data,enum_name}; + names->push_back(t); + + } + RegCloseKey (connection_key); + } + ++i; + } + + RegCloseKey (network_connections_key); + + return names; +} + + +vector* GetTapAdapters() +{ + vector* rv = new vector(); + int links; + + vector *tap_reg = get_tap_reg (); + vector *panel_reg = get_panel_reg (); + + printf ( "\nAvailable TAP-WIN32 adapters [name, GUID]:\n"); + + /* loop through each TAP-Win32 adapter registry entry */ + for (size_t i = 0; isize();i++) + { + links = 0; + + /* loop through each network connections entry in the control panel */ + for (size_t j = 0; jsize();j++) + { + if (!strcmp ((*tap_reg)[i].c_str(), (*panel_reg)[j].guid.c_str())) + { + //printf ("'%s' %s\n", (*panel_reg)[j].name.c_str(),(*tap_reg)[i].c_str()); + tap_adapter t = { (*panel_reg)[j].name,(*tap_reg)[i]}; + t.guid= string("tap:") + t.guid; + t.name=string("tap:") + t.name; + rv->push_back(t); + ++links; + } + } + + if (links > 1) + { + //warn_panel_dup = true; + } + else if (links == 0) + { + /* a TAP adapter exists without a link from the network + connections control panel */ +// warn_panel_null = true; + printf ("[NULL] %s\n",(*tap_reg)[i].c_str()); + } + } + delete tap_reg,panel_reg; + return rv; +} + +//Set the connection status +static int TAPSetStatus(HANDLE handle, int status) +{ + unsigned long len = 0; + + return DeviceIoControl(handle, TAP_IOCTL_SET_MEDIA_STATUS, + &status, sizeof (status), + &status, sizeof (status), &len, NULL); +} +//Open the TAP adapter and set the connection to enabled :) +HANDLE TAPOpen(const char *device_guid) +{ + char device_path[256]; + + struct { + unsigned long major; + unsigned long minor; + unsigned long debug; + } version; + LONG version_len; + + _snprintf (device_path, sizeof(device_path), "%s%s%s", + USERMODEDEVICEDIR, + device_guid, + TAPSUFFIX); + + HANDLE handle = CreateFile ( + device_path, + GENERIC_READ | GENERIC_WRITE, + 0, + 0, + OPEN_EXISTING, + FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED, + 0 ); + + if (handle == INVALID_HANDLE_VALUE) { + return INVALID_HANDLE_VALUE; + } + + BOOL bret = DeviceIoControl(handle, TAP_IOCTL_GET_VERSION, + &version, sizeof (version), + &version, sizeof (version), (LPDWORD)&version_len, NULL); + + if (bret == FALSE) { + CloseHandle(handle); + return INVALID_HANDLE_VALUE; + } + + if (!TAPSetStatus(handle, TRUE)) { + return INVALID_HANDLE_VALUE; + } + + return handle; +} + + + +TAPAdapter::TAPAdapter() +{ + htap=TAPOpen(config.Eth+4); + + read.Offset = 0; + read.OffsetHigh = 0; + read.hEvent = CreateEvent(NULL, FALSE, FALSE, NULL); + + write.Offset = 0; + write.OffsetHigh = 0; + write.hEvent = CreateEvent(NULL, FALSE, FALSE, NULL); + + +} + +bool TAPAdapter::blocks() +{ + return true; //we use blocking io +} +u8 broadcast_adddrrrr[6]={0xFF,0xFF,0xFF,0xFF,0xFF,0xFF}; +//gets a packet.rv :true success +bool TAPAdapter::recv(NetPacket* pkt) +{ + DWORD read_size; + BOOL result = ReadFile(htap, + pkt->buffer, + sizeof(pkt->buffer), + &read_size, + &read); + + if (!result) { + DWORD dwError = GetLastError(); + if (dwError == ERROR_IO_PENDING) + { + WaitForSingleObject(read.hEvent, INFINITE); + result = GetOverlappedResult( htap, &read, + &read_size, FALSE); + if (!result) + { + + } + } + else { + + } + } + + + if (result) + { + if((memcmp(pkt->buffer,dev9.eeprom,6)!=0)&&(memcmp(pkt->buffer,&broadcast_adddrrrr,6)!=0)) + { + //ignore strange packets + return false; + } + + if(memcmp(pkt->buffer+6,dev9.eeprom,6)==0) + { + //avoid pcap looping packets + return false; + } + pkt->size=read_size; + return true; + } + else + return false; +} +//sends the packet .rv :true success +bool TAPAdapter::send(NetPacket* pkt) +{ + DWORD writen; + BOOL result = WriteFile(htap, + pkt->buffer, + pkt->size, + &writen, + &write); + + if (!result) { + DWORD dwError = GetLastError(); + if (dwError == ERROR_IO_PENDING) + { + WaitForSingleObject(write.hEvent, INFINITE); + result = GetOverlappedResult( htap, &write, + &writen, FALSE); + if (!result) + { + + } + } + else { + + } + } + + if (result) + { + if (writen!=pkt->size) + return false; + + return true; + } + else + return false; +} +TAPAdapter::~TAPAdapter() +{ + CloseHandle(read.hEvent); + CloseHandle(write.hEvent); + TAPSetStatus(htap, FALSE); + CloseHandle(htap); +} + +//i leave these for reference, in case we need msth :p +#if 0==666 +//====================== +// Compile time configuration +//====================== + +//#define DEBUG_TAP_WIN32 1 + +#define TUN_ASYNCHRONOUS_WRITES 1 + +#define TUN_BUFFER_SIZE 1560 +#define TUN_MAX_BUFFER_COUNT 32 + +/* + * The data member "buffer" must be the first element in the tun_buffer + * structure. See the function, tap_win32_free_buffer. + */ +typedef struct tun_buffer_s { + unsigned char buffer [TUN_BUFFER_SIZE]; + unsigned long read_size; + struct tun_buffer_s* next; +} tun_buffer_t; + +typedef struct tap_win32_overlapped { + HANDLE handle; + HANDLE read_event; + HANDLE write_event; + HANDLE output_queue_semaphore; + HANDLE free_list_semaphore; + HANDLE tap_semaphore; + CRITICAL_SECTION output_queue_cs; + CRITICAL_SECTION free_list_cs; + OVERLAPPED read_overlapped; + OVERLAPPED write_overlapped; + tun_buffer_t buffers[TUN_MAX_BUFFER_COUNT]; + tun_buffer_t* free_list; + tun_buffer_t* output_queue_front; + tun_buffer_t* output_queue_back; +} tap_win32_overlapped_t; + +static tap_win32_overlapped_t tap_overlapped; + +static tun_buffer_t* get_buffer_from_free_list(tap_win32_overlapped_t* const overlapped) +{ + tun_buffer_t* buffer = NULL; + WaitForSingleObject(overlapped->free_list_semaphore, INFINITE); + EnterCriticalSection(&overlapped->free_list_cs); + buffer = overlapped->free_list; +// assert(buffer != NULL); + overlapped->free_list = buffer->next; + LeaveCriticalSection(&overlapped->free_list_cs); + buffer->next = NULL; + return buffer; +} + +static void put_buffer_on_free_list(tap_win32_overlapped_t* const overlapped, tun_buffer_t* const buffer) +{ + EnterCriticalSection(&overlapped->free_list_cs); + buffer->next = overlapped->free_list; + overlapped->free_list = buffer; + LeaveCriticalSection(&overlapped->free_list_cs); + ReleaseSemaphore(overlapped->free_list_semaphore, 1, NULL); +} + +static tun_buffer_t* get_buffer_from_output_queue(tap_win32_overlapped_t* const overlapped, const int block) +{ + tun_buffer_t* buffer = NULL; + DWORD result, timeout = block ? INFINITE : 0L; + + // Non-blocking call + result = WaitForSingleObject(overlapped->output_queue_semaphore, timeout); + + switch (result) + { + // The semaphore object was signaled. + case WAIT_OBJECT_0: + EnterCriticalSection(&overlapped->output_queue_cs); + + buffer = overlapped->output_queue_front; + overlapped->output_queue_front = buffer->next; + + if(overlapped->output_queue_front == NULL) { + overlapped->output_queue_back = NULL; + } + + LeaveCriticalSection(&overlapped->output_queue_cs); + break; + + // Semaphore was nonsignaled, so a time-out occurred. + case WAIT_TIMEOUT: + // Cannot open another window. + break; + } + + return buffer; +} + +static tun_buffer_t* get_buffer_from_output_queue_immediate (tap_win32_overlapped_t* const overlapped) +{ + return get_buffer_from_output_queue(overlapped, 0); +} + +static void put_buffer_on_output_queue(tap_win32_overlapped_t* const overlapped, tun_buffer_t* const buffer) +{ + EnterCriticalSection(&overlapped->output_queue_cs); + + if(overlapped->output_queue_front == NULL && overlapped->output_queue_back == NULL) { + overlapped->output_queue_front = overlapped->output_queue_back = buffer; + } else { + buffer->next = NULL; + overlapped->output_queue_back->next = buffer; + overlapped->output_queue_back = buffer; + } + + LeaveCriticalSection(&overlapped->output_queue_cs); + + ReleaseSemaphore(overlapped->output_queue_semaphore, 1, NULL); +} + + +static int is_tap_win32_dev(const char *guid) +{ + HKEY netcard_key; + LONG status; + DWORD len; + int i = 0; + + status = RegOpenKeyEx( + HKEY_LOCAL_MACHINE, + ADAPTER_KEY, + 0, + KEY_READ, + &netcard_key); + + if (status != ERROR_SUCCESS) { + return FALSE; + } + + for (;;) { + char enum_name[256]; + char unit_string[256]; + HKEY unit_key; + char component_id_string[] = "ComponentId"; + char component_id[256]; + char net_cfg_instance_id_string[] = "NetCfgInstanceId"; + char net_cfg_instance_id[256]; + DWORD data_type; + + len = sizeof (enum_name); + status = RegEnumKeyEx( + netcard_key, + i, + enum_name, + &len, + NULL, + NULL, + NULL, + NULL); + + if (status == ERROR_NO_MORE_ITEMS) + break; + else if (status != ERROR_SUCCESS) { + return FALSE; + } + + _snprintf(unit_string, sizeof(unit_string), "%s\\%s", + ADAPTER_KEY, enum_name); + + status = RegOpenKeyEx( + HKEY_LOCAL_MACHINE, + unit_string, + 0, + KEY_READ, + &unit_key); + + if (status != ERROR_SUCCESS) { + return FALSE; + } else { + len = sizeof (component_id); + status = RegQueryValueEx( + unit_key, + component_id_string, + NULL, + &data_type, + (LPBYTE)component_id, + &len); + + if (!(status != ERROR_SUCCESS || data_type != REG_SZ)) { + len = sizeof (net_cfg_instance_id); + status = RegQueryValueEx( + unit_key, + net_cfg_instance_id_string, + NULL, + &data_type, + (LPBYTE)net_cfg_instance_id, + &len); + + if (status == ERROR_SUCCESS && data_type == REG_SZ) { + if (/* !strcmp (component_id, TAP_COMPONENT_ID) &&*/ + !strcmp (net_cfg_instance_id, guid)) { + RegCloseKey (unit_key); + RegCloseKey (netcard_key); + return TRUE; + } + } + } + RegCloseKey (unit_key); + } + ++i; + } + + RegCloseKey (netcard_key); + return FALSE; +} + +static int get_device_guid( + char *name, + int name_size, + char *actual_name, + int actual_name_size) +{ + LONG status; + HKEY control_net_key; + DWORD len; + int i = 0; + int stop = 0; + + status = RegOpenKeyEx( + HKEY_LOCAL_MACHINE, + NETWORK_CONNECTIONS_KEY, + 0, + KEY_READ, + &control_net_key); + + if (status != ERROR_SUCCESS) { + return -1; + } + + while (!stop) + { + char enum_name[256]; + char connection_string[256]; + HKEY connection_key; + char name_data[256]; + DWORD name_type; + const char name_string[] = "Name"; + + len = sizeof (enum_name); + status = RegEnumKeyEx( + control_net_key, + i, + enum_name, + &len, + NULL, + NULL, + NULL, + NULL); + + if (status == ERROR_NO_MORE_ITEMS) + break; + else if (status != ERROR_SUCCESS) { + return -1; + } + + _snprintf(connection_string, + sizeof(connection_string), + "%s\\%s\\Connection", + NETWORK_CONNECTIONS_KEY, enum_name); + + status = RegOpenKeyEx( + HKEY_LOCAL_MACHINE, + connection_string, + 0, + KEY_READ, + &connection_key); + + if (status == ERROR_SUCCESS) { + len = sizeof (name_data); + status = RegQueryValueEx( + connection_key, + name_string, + NULL, + &name_type, + (LPBYTE)name_data, + &len); + + if (status != ERROR_SUCCESS || name_type != REG_SZ) { + return -1; + } + else { + if (is_tap_win32_dev(enum_name)) { + _snprintf(name, name_size, "%s", enum_name); + if (actual_name) { + if (strcmp(actual_name, "") != 0) { + if (strcmp(name_data, actual_name) != 0) { + RegCloseKey (connection_key); + ++i; + continue; + } + } + else { + _snprintf(actual_name, actual_name_size, "%s", name_data); + } + } + stop = 1; + } + } + + RegCloseKey (connection_key); + } + ++i; + } + + RegCloseKey (control_net_key); + + if (stop == 0) + return -1; + + return 0; +} + + + +static void tap_win32_overlapped_init(tap_win32_overlapped_t* const overlapped, const HANDLE handle) +{ + overlapped->handle = handle; + + overlapped->read_event = CreateEvent(NULL, FALSE, FALSE, NULL); + overlapped->write_event = CreateEvent(NULL, FALSE, FALSE, NULL); + + overlapped->read_overlapped.Offset = 0; + overlapped->read_overlapped.OffsetHigh = 0; + overlapped->read_overlapped.hEvent = overlapped->read_event; + + overlapped->write_overlapped.Offset = 0; + overlapped->write_overlapped.OffsetHigh = 0; + overlapped->write_overlapped.hEvent = overlapped->write_event; + + InitializeCriticalSection(&overlapped->output_queue_cs); + InitializeCriticalSection(&overlapped->free_list_cs); + + overlapped->output_queue_semaphore = CreateSemaphore( + NULL, // default security attributes + 0, // initial count + TUN_MAX_BUFFER_COUNT, // maximum count + NULL); // unnamed semaphore + + if(!overlapped->output_queue_semaphore) { + fprintf(stderr, "error creating output queue semaphore!\n"); + } + + overlapped->free_list_semaphore = CreateSemaphore( + NULL, // default security attributes + TUN_MAX_BUFFER_COUNT, // initial count + TUN_MAX_BUFFER_COUNT, // maximum count + NULL); // unnamed semaphore + + if(!overlapped->free_list_semaphore) { + fprintf(stderr, "error creating free list semaphore!\n"); + } + + overlapped->free_list = overlapped->output_queue_front = overlapped->output_queue_back = NULL; + + { + unsigned index; + for(index = 0; index < TUN_MAX_BUFFER_COUNT; index++) { + tun_buffer_t* element = &overlapped->buffers[index]; + element->next = overlapped->free_list; + overlapped->free_list = element; + } + } + /* To count buffers, initially no-signal. */ + overlapped->tap_semaphore = CreateSemaphore(NULL, 0, TUN_MAX_BUFFER_COUNT, NULL); + if(!overlapped->tap_semaphore) + fprintf(stderr, "error creating tap_semaphore.\n"); +} + +static int tap_win32_write(tap_win32_overlapped_t *overlapped, + const void *buffer, unsigned long size) +{ + unsigned long write_size; + BOOL result; + DWORD error; + + result = GetOverlappedResult( overlapped->handle, &overlapped->write_overlapped, + &write_size, FALSE); + + if (!result && GetLastError() == ERROR_IO_INCOMPLETE) + WaitForSingleObject(overlapped->write_event, INFINITE); + + result = WriteFile(overlapped->handle, buffer, size, + &write_size, &overlapped->write_overlapped); + + if (!result) { + switch (error = GetLastError()) + { + case ERROR_IO_PENDING: +#ifndef TUN_ASYNCHRONOUS_WRITES + WaitForSingleObject(overlapped->write_event, INFINITE); +#endif + break; + default: + return -1; + } + } + + return 0; +} + +static DWORD WINAPI tap_win32_thread_entry(LPVOID param) +{ + tap_win32_overlapped_t *overlapped = (tap_win32_overlapped_t*)param; + unsigned long read_size; + BOOL result; + DWORD dwError; + tun_buffer_t* buffer = get_buffer_from_free_list(overlapped); + + + for (;;) { + result = ReadFile(overlapped->handle, + buffer->buffer, + sizeof(buffer->buffer), + &read_size, + &overlapped->read_overlapped); + if (!result) { + dwError = GetLastError(); + if (dwError == ERROR_IO_PENDING) { + WaitForSingleObject(overlapped->read_event, INFINITE); + result = GetOverlappedResult( overlapped->handle, &overlapped->read_overlapped, + &read_size, FALSE); + if (!result) { +#if DEBUG_TAP_WIN32 + LPVOID lpBuffer; + dwError = GetLastError(); + FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, + NULL, dwError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + (LPTSTR) & lpBuffer, 0, NULL ); + fprintf(stderr, "Tap-Win32: Error GetOverlappedResult %d - %s\n", dwError, lpBuffer); + LocalFree( lpBuffer ); +#endif + } + } else { +#if DEBUG_TAP_WIN32 + LPVOID lpBuffer; + FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, + NULL, dwError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + (LPTSTR) & lpBuffer, 0, NULL ); + fprintf(stderr, "Tap-Win32: Error ReadFile %d - %s\n", dwError, lpBuffer); + LocalFree( lpBuffer ); +#endif + } + } + + if(read_size > 0) { + buffer->read_size = read_size; + put_buffer_on_output_queue(overlapped, buffer); + ReleaseSemaphore(overlapped->tap_semaphore, 1, NULL); + buffer = get_buffer_from_free_list(overlapped); + } + } + + return 0; +} + +typedef unsigned __int8 uint8_t; + +static int tap_win32_read(tap_win32_overlapped_t *overlapped, + uint8_t **pbuf, int max_size) +{ + int size = 0; + + tun_buffer_t* buffer = get_buffer_from_output_queue_immediate(overlapped); + + if(buffer != NULL) { + *pbuf = buffer->buffer; + size = (int)buffer->read_size; + if(size > max_size) { + size = max_size; + } + } + + return size; +} + +static void tap_win32_free_buffer(tap_win32_overlapped_t *overlapped, + char* pbuf) +{ + tun_buffer_t* buffer = (tun_buffer_t*)pbuf; + put_buffer_on_free_list(overlapped, buffer); +} + +static int tap_win32_open(tap_win32_overlapped_t **phandle, + const char *prefered_name) +{ + char device_path[256]; + char device_guid[0x100]; + int rc; + HANDLE handle; + BOOL bret; + char name_buffer[0x100] = {0, }; + struct { + unsigned long major; + unsigned long minor; + unsigned long debug; + } version; + LONG version_len; + DWORD idThread; + HANDLE hThread; + + if (prefered_name != NULL) + _snprintf(name_buffer, sizeof(name_buffer), "%s", prefered_name); + + rc = get_device_guid(device_guid, sizeof(device_guid), name_buffer, sizeof(name_buffer)); + if (rc) + return -1; + + _snprintf (device_path, sizeof(device_path), "%s%s%s", + USERMODEDEVICEDIR, + device_guid, + TAPSUFFIX); + + handle = CreateFile ( + device_path, + GENERIC_READ | GENERIC_WRITE, + 0, + 0, + OPEN_EXISTING, + FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED, + 0 ); + + if (handle == INVALID_HANDLE_VALUE) { + return -1; + } + + bret = DeviceIoControl(handle, TAP_IOCTL_GET_VERSION, + &version, sizeof (version), + &version, sizeof (version), (LPDWORD)&version_len, NULL); + + if (bret == FALSE) { + CloseHandle(handle); + return -1; + } + + if (!tap_win32_set_status(handle, TRUE)) { + return -1; + } + + tap_win32_overlapped_init(&tap_overlapped, handle); + + *phandle = &tap_overlapped; + + hThread = CreateThread(NULL, 0, tap_win32_thread_entry, + (LPVOID)&tap_overlapped, 0, &idThread); + return 0; +} + +/********************************************/ + + typedef struct TAPState { + tap_win32_overlapped_t *handle; + } TAPState; + +static void tap_receive(void *opaque, const uint8_t *buf, int size) +{ + TAPState *s = (TAPState *)opaque; + + tap_win32_write(s->handle, buf, size); +} + +static void tap_win32_send(void *opaque) +{ + TAPState *s = (TAPState *)opaque; + uint8_t *buf; + int max_size = 4096; + int size; + + size = tap_win32_read(s->handle, &buf, max_size); + if (size > 0) { + //qemu_send_packet(s->vc, buf, size); + tap_win32_free_buffer(s->handle, (char*)buf); + } +} + +int tap_win32_init(const char *ifname) +{ + TAPState *s = (TAPState *)malloc(sizeof(TAPState)); + if (!s) + return -1; + + memset(s,0,sizeof(TAPState)); + + if (tap_win32_open(&s->handle, ifname) < 0) { + printf("tap: Could not open '%s'\n", ifname); + return -1; + } + + return 0; +} + +#endif diff --git a/plugins/dev9ghzdrk/Win32/tap.h b/plugins/dev9ghzdrk/Win32/tap.h new file mode 100644 index 0000000000..82c3c4f411 --- /dev/null +++ b/plugins/dev9ghzdrk/Win32/tap.h @@ -0,0 +1,24 @@ +#pragma once +#include +#include "net.h" +using namespace std; + +struct tap_adapter +{ + string name; + string guid; +}; +vector* GetTapAdapters(); +class TAPAdapter : public NetAdapter +{ + HANDLE htap; + OVERLAPPED read,write; +public: + TAPAdapter(); + virtual bool blocks(); + //gets a packet.rv :true success + virtual bool recv(NetPacket* pkt); + //sends the packet and deletes it when done (if successful).rv :true success + virtual bool send(NetPacket* pkt); + virtual ~TAPAdapter(); +}; \ No newline at end of file diff --git a/plugins/dev9ghzdrk/Win32/vl.h b/plugins/dev9ghzdrk/Win32/vl.h new file mode 100644 index 0000000000..618519fca8 --- /dev/null +++ b/plugins/dev9ghzdrk/Win32/vl.h @@ -0,0 +1,1419 @@ +/* + * QEMU System Emulator header + * + * Copyright (c) 2003 Fabrice Bellard + * + * 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. + */ +#ifndef VL_H +#define VL_H + +/* we put basic includes here to avoid repeating them in device drivers */ +#include +#include +#include +#include +//#include +typedef signed char int8_t; +typedef signed short int16_t; +typedef signed int int32_t; + +typedef unsigned char uint8_t; +typedef unsigned short uint16_t; +typedef unsigned int uint32_t; + +//typedef signed long int intptr_t; +//typedef unsigned long int uintptr_t; + +typedef signed long long int64_t; +typedef unsigned long long uint64_t; +typedef signed long long int intmax_t; +typedef unsigned long long int uintmax_t; + + +#include +#include +#include +#include +//#include +#include +#include + +#ifndef O_LARGEFILE +#define O_LARGEFILE 0 +#endif +#ifndef O_BINARY +#define O_BINARY 0 +#endif + +#ifndef ENOMEDIUM +#define ENOMEDIUM ENODEV +#endif + +#ifdef _WIN32 +#include +#define fsync _commit +#define lseek _lseeki64 +#define ENOTSUP 4096 +extern int qemu_ftruncate64(int, int64_t); +#define ftruncate qemu_ftruncate64 + + +static inline char *realpath(const char *path, char *resolved_path) +{ + _fullpath(resolved_path, path, _MAX_PATH); + return resolved_path; +} + +#define PRId64 "I64d" +#define PRIx64 "I64x" +#define PRIu64 "I64u" +#define PRIo64 "I64o" +#endif + +#ifdef QEMU_TOOL + +/* we use QEMU_TOOL in the command line tools which do not depend on + the target CPU type */ +#include "config-host.h" +#include +#include "osdep.h" +#include "bswap.h" + +#else + +//#include "audio/audio.h" +//#include "cpu.h" + +#endif /* !defined(QEMU_TOOL) */ + +#ifndef glue +#define xglue(x, y) x ## y +#define glue(x, y) xglue(x, y) +#define stringify(s) tostring(s) +#define tostring(s) #s +#endif + +#ifndef MIN +#define MIN(a, b) (((a) < (b)) ? (a) : (b)) +#endif +#ifndef MAX +#define MAX(a, b) (((a) > (b)) ? (a) : (b)) +#endif + +/* cutils.c */ +void pstrcpy(char *buf, int buf_size, const char *str); +char *pstrcat(char *buf, int buf_size, const char *s); +int strstart(const char *str, const char *val, const char **ptr); +int stristart(const char *str, const char *val, const char **ptr); + +/* vl.c */ +uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c); + +void hw_error(const char *fmt, ...); + +extern const char *bios_dir; + +extern int vm_running; + +typedef struct vm_change_state_entry VMChangeStateEntry; +typedef void VMChangeStateHandler(void *opaque, int running); +typedef void VMStopHandler(void *opaque, int reason); + +VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb, + void *opaque); +void qemu_del_vm_change_state_handler(VMChangeStateEntry *e); + +int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque); +void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque); + +void vm_start(void); +void vm_stop(int reason); + +typedef void QEMUResetHandler(void *opaque); + +void qemu_register_reset(QEMUResetHandler *func, void *opaque); +void qemu_system_reset_request(void); +void qemu_system_shutdown_request(void); +void qemu_system_powerdown_request(void); +#if !defined(TARGET_SPARC) +// Please implement a power failure function to signal the OS +#define qemu_system_powerdown() do{}while(0) +#else +void qemu_system_powerdown(void); +#endif + +void main_loop_wait(int timeout); + +extern int ram_size; +extern int bios_size; +extern int rtc_utc; +extern int cirrus_vga_enabled; +extern int graphic_width; +extern int graphic_height; +extern int graphic_depth; +extern const char *keyboard_layout; +extern int kqemu_allowed; +extern int win2k_install_hack; +extern int usb_enabled; +extern int smp_cpus; +extern int no_quit; +extern int semihosting_enabled; +extern int autostart; + +#define MAX_OPTION_ROMS 16 +extern const char *option_rom[MAX_OPTION_ROMS]; +extern int nb_option_roms; + +/* XXX: make it dynamic */ +#if defined (TARGET_PPC) || defined (TARGET_SPARC64) +#define BIOS_SIZE ((512 + 32) * 1024) +#elif defined(TARGET_MIPS) +#define BIOS_SIZE (4 * 1024 * 1024) +#else +#define BIOS_SIZE ((256 + 64) * 1024) +#endif + +/* keyboard/mouse support */ + +#define MOUSE_EVENT_LBUTTON 0x01 +#define MOUSE_EVENT_RBUTTON 0x02 +#define MOUSE_EVENT_MBUTTON 0x04 + +typedef void QEMUPutKBDEvent(void *opaque, int keycode); +typedef void QEMUPutMouseEvent(void *opaque, int dx, int dy, int dz, int buttons_state); + +typedef struct QEMUPutMouseEntry { + QEMUPutMouseEvent *qemu_put_mouse_event; + void *qemu_put_mouse_event_opaque; + int qemu_put_mouse_event_absolute; + char *qemu_put_mouse_event_name; + + /* used internally by qemu for handling mice */ + struct QEMUPutMouseEntry *next; +} QEMUPutMouseEntry; + +void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque); +QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func, + void *opaque, int absolute, + const char *name); +void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry); + +void kbd_put_keycode(int keycode); +void kbd_mouse_event(int dx, int dy, int dz, int buttons_state); +int kbd_mouse_is_absolute(void); + +void do_info_mice(void); +void do_mouse_set(int index); + +/* keysym is a unicode code except for special keys (see QEMU_KEY_xxx + constants) */ +#define QEMU_KEY_ESC1(c) ((c) | 0xe100) +#define QEMU_KEY_BACKSPACE 0x007f +#define QEMU_KEY_UP QEMU_KEY_ESC1('A') +#define QEMU_KEY_DOWN QEMU_KEY_ESC1('B') +#define QEMU_KEY_RIGHT QEMU_KEY_ESC1('C') +#define QEMU_KEY_LEFT QEMU_KEY_ESC1('D') +#define QEMU_KEY_HOME QEMU_KEY_ESC1(1) +#define QEMU_KEY_END QEMU_KEY_ESC1(4) +#define QEMU_KEY_PAGEUP QEMU_KEY_ESC1(5) +#define QEMU_KEY_PAGEDOWN QEMU_KEY_ESC1(6) +#define QEMU_KEY_DELETE QEMU_KEY_ESC1(3) + +#define QEMU_KEY_CTRL_UP 0xe400 +#define QEMU_KEY_CTRL_DOWN 0xe401 +#define QEMU_KEY_CTRL_LEFT 0xe402 +#define QEMU_KEY_CTRL_RIGHT 0xe403 +#define QEMU_KEY_CTRL_HOME 0xe404 +#define QEMU_KEY_CTRL_END 0xe405 +#define QEMU_KEY_CTRL_PAGEUP 0xe406 +#define QEMU_KEY_CTRL_PAGEDOWN 0xe407 + +void kbd_put_keysym(int keysym); + +/* async I/O support */ + +typedef void IOReadHandler(void *opaque, const uint8_t *buf, int size); +typedef int IOCanRWHandler(void *opaque); +typedef void IOHandler(void *opaque); + +int qemu_set_fd_handler2(int fd, + IOCanRWHandler *fd_read_poll, + IOHandler *fd_read, + IOHandler *fd_write, + void *opaque); +int qemu_set_fd_handler(int fd, + IOHandler *fd_read, + IOHandler *fd_write, + void *opaque); + +/* Polling handling */ + +/* return TRUE if no sleep should be done afterwards */ +typedef int PollingFunc(void *opaque); + +int qemu_add_polling_cb(PollingFunc *func, void *opaque); +void qemu_del_polling_cb(PollingFunc *func, void *opaque); + +#ifdef _WIN32 +/* Wait objects handling */ +typedef void WaitObjectFunc(void *opaque); + +int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque); +void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque); +#endif + +typedef struct QEMUBH QEMUBH; + +/* character device */ + +#define CHR_EVENT_BREAK 0 /* serial break char */ +#define CHR_EVENT_FOCUS 1 /* focus to this terminal (modal input needed) */ +#define CHR_EVENT_RESET 2 /* new connection established */ + + +#define CHR_IOCTL_SERIAL_SET_PARAMS 1 +typedef struct { + int speed; + int parity; + int data_bits; + int stop_bits; +} QEMUSerialSetParams; + +#define CHR_IOCTL_SERIAL_SET_BREAK 2 + +#define CHR_IOCTL_PP_READ_DATA 3 +#define CHR_IOCTL_PP_WRITE_DATA 4 +#define CHR_IOCTL_PP_READ_CONTROL 5 +#define CHR_IOCTL_PP_WRITE_CONTROL 6 +#define CHR_IOCTL_PP_READ_STATUS 7 + +typedef void IOEventHandler(void *opaque, int event); + +typedef struct CharDriverState { + int (*chr_write)(struct CharDriverState *s, const uint8_t *buf, int len); + void (*chr_update_read_handler)(struct CharDriverState *s); + int (*chr_ioctl)(struct CharDriverState *s, int cmd, void *arg); + IOEventHandler *chr_event; + IOCanRWHandler *chr_can_read; + IOReadHandler *chr_read; + void *handler_opaque; + void (*chr_send_event)(struct CharDriverState *chr, int event); + void (*chr_close)(struct CharDriverState *chr); + void *opaque; + QEMUBH *bh; +} CharDriverState; + +CharDriverState *qemu_chr_open(const char *filename); +void qemu_chr_printf(CharDriverState *s, const char *fmt, ...); +int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len); +void qemu_chr_send_event(CharDriverState *s, int event); +void qemu_chr_add_handlers(CharDriverState *s, + IOCanRWHandler *fd_can_read, + IOReadHandler *fd_read, + IOEventHandler *fd_event, + void *opaque); +int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg); +void qemu_chr_reset(CharDriverState *s); +int qemu_chr_can_read(CharDriverState *s); +void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len); + +/* consoles */ + +typedef struct DisplayState DisplayState; +typedef struct TextConsole TextConsole; + +typedef void (*vga_hw_update_ptr)(void *); +typedef void (*vga_hw_invalidate_ptr)(void *); +typedef void (*vga_hw_screen_dump_ptr)(void *, const char *); + +TextConsole *graphic_console_init(DisplayState *ds, vga_hw_update_ptr update, + vga_hw_invalidate_ptr invalidate, + vga_hw_screen_dump_ptr screen_dump, + void *opaque); +void vga_hw_update(void); +void vga_hw_invalidate(void); +void vga_hw_screen_dump(const char *filename); + +int is_graphic_console(void); +CharDriverState *text_console_init(DisplayState *ds); +void console_select(unsigned int index); + +/* serial ports */ + +#define MAX_SERIAL_PORTS 4 + +extern CharDriverState *serial_hds[MAX_SERIAL_PORTS]; + +/* parallel ports */ + +#define MAX_PARALLEL_PORTS 3 + +extern CharDriverState *parallel_hds[MAX_PARALLEL_PORTS]; + +/* VLANs support */ + +typedef struct VLANClientState VLANClientState; + +struct VLANClientState { + IOReadHandler *fd_read; + /* Packets may still be sent if this returns zero. It's used to + rate-limit the slirp code. */ + IOCanRWHandler *fd_can_read; + void *opaque; + struct VLANClientState *next; + struct VLANState *vlan; + char info_str[256]; +}; + +typedef struct VLANState { + int id; + VLANClientState *first_client; + struct VLANState *next; +} VLANState; + +VLANState *qemu_find_vlan(int id); +VLANClientState *qemu_new_vlan_client(VLANState *vlan, + IOReadHandler *fd_read, + IOCanRWHandler *fd_can_read, + void *opaque); +int qemu_can_send_packet(VLANClientState *vc); +void qemu_send_packet(VLANClientState *vc, const uint8_t *buf, int size); +void qemu_handler_true(void *opaque); + +void do_info_network(void); + +/* TAP win32 */ +int tap_win32_init(VLANState *vlan, const char *ifname); + +/* NIC info */ + +#define MAX_NICS 8 + +typedef struct NICInfo { + uint8_t macaddr[6]; + const char *model; + VLANState *vlan; +} NICInfo; + +extern int nb_nics; +extern NICInfo nd_table[MAX_NICS]; + +/* timers */ + +typedef struct QEMUClock QEMUClock; +typedef struct QEMUTimer QEMUTimer; +typedef void QEMUTimerCB(void *opaque); + +/* The real time clock should be used only for stuff which does not + change the virtual machine state, as it is run even if the virtual + machine is stopped. The real time clock has a frequency of 1000 + Hz. */ +extern QEMUClock *rt_clock; + +/* The virtual clock is only run during the emulation. It is stopped + when the virtual machine is stopped. Virtual timers use a high + precision clock, usually cpu cycles (use ticks_per_sec). */ +extern QEMUClock *vm_clock; + +int64_t qemu_get_clock(QEMUClock *clock); + +QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque); +void qemu_free_timer(QEMUTimer *ts); +void qemu_del_timer(QEMUTimer *ts); +void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time); +int qemu_timer_pending(QEMUTimer *ts); + +extern int64_t ticks_per_sec; +extern int pit_min_timer_count; + +int64_t cpu_get_ticks(void); +void cpu_enable_ticks(void); +void cpu_disable_ticks(void); + +/* VM Load/Save */ + +typedef struct QEMUFile QEMUFile; + +QEMUFile *qemu_fopen(const char *filename, const char *mode); +void qemu_fflush(QEMUFile *f); +void qemu_fclose(QEMUFile *f); +void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size); +void qemu_put_byte(QEMUFile *f, int v); +void qemu_put_be16(QEMUFile *f, unsigned int v); +void qemu_put_be32(QEMUFile *f, unsigned int v); +void qemu_put_be64(QEMUFile *f, uint64_t v); +int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size); +int qemu_get_byte(QEMUFile *f); +unsigned int qemu_get_be16(QEMUFile *f); +unsigned int qemu_get_be32(QEMUFile *f); +uint64_t qemu_get_be64(QEMUFile *f); + +static inline void qemu_put_be64s(QEMUFile *f, const uint64_t *pv) +{ + qemu_put_be64(f, *pv); +} + +static inline void qemu_put_be32s(QEMUFile *f, const uint32_t *pv) +{ + qemu_put_be32(f, *pv); +} + +static inline void qemu_put_be16s(QEMUFile *f, const uint16_t *pv) +{ + qemu_put_be16(f, *pv); +} + +static inline void qemu_put_8s(QEMUFile *f, const uint8_t *pv) +{ + qemu_put_byte(f, *pv); +} + +static inline void qemu_get_be64s(QEMUFile *f, uint64_t *pv) +{ + *pv = qemu_get_be64(f); +} + +static inline void qemu_get_be32s(QEMUFile *f, uint32_t *pv) +{ + *pv = qemu_get_be32(f); +} + +static inline void qemu_get_be16s(QEMUFile *f, uint16_t *pv) +{ + *pv = qemu_get_be16(f); +} + +static inline void qemu_get_8s(QEMUFile *f, uint8_t *pv) +{ + *pv = qemu_get_byte(f); +} + +#if TARGET_LONG_BITS == 64 +#define qemu_put_betl qemu_put_be64 +#define qemu_get_betl qemu_get_be64 +#define qemu_put_betls qemu_put_be64s +#define qemu_get_betls qemu_get_be64s +#else +#define qemu_put_betl qemu_put_be32 +#define qemu_get_betl qemu_get_be32 +#define qemu_put_betls qemu_put_be32s +#define qemu_get_betls qemu_get_be32s +#endif + +int64_t qemu_ftell(QEMUFile *f); +int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence); + +typedef void SaveStateHandler(QEMUFile *f, void *opaque); +typedef int LoadStateHandler(QEMUFile *f, void *opaque, int version_id); + +int register_savevm(const char *idstr, + int instance_id, + int version_id, + SaveStateHandler *save_state, + LoadStateHandler *load_state, + void *opaque); +void qemu_get_timer(QEMUFile *f, QEMUTimer *ts); +void qemu_put_timer(QEMUFile *f, QEMUTimer *ts); + +void cpu_save(QEMUFile *f, void *opaque); +int cpu_load(QEMUFile *f, void *opaque, int version_id); + +void do_savevm(const char *name); +void do_loadvm(const char *name); +void do_delvm(const char *name); +void do_info_snapshots(void); + +/* bottom halves */ +typedef void QEMUBHFunc(void *opaque); + +QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque); +void qemu_bh_schedule(QEMUBH *bh); +void qemu_bh_cancel(QEMUBH *bh); +void qemu_bh_delete(QEMUBH *bh); +int qemu_bh_poll(void); + +/* block.c */ +typedef struct BlockDriverState BlockDriverState; +typedef struct BlockDriver BlockDriver; + +extern BlockDriver bdrv_raw; +extern BlockDriver bdrv_host_device; +extern BlockDriver bdrv_cow; +extern BlockDriver bdrv_qcow; +extern BlockDriver bdrv_vmdk; +extern BlockDriver bdrv_cloop; +extern BlockDriver bdrv_dmg; +extern BlockDriver bdrv_bochs; +extern BlockDriver bdrv_vpc; +extern BlockDriver bdrv_vvfat; +extern BlockDriver bdrv_qcow2; + +typedef struct BlockDriverInfo { + /* in bytes, 0 if irrelevant */ + int cluster_size; + /* offset at which the VM state can be saved (0 if not possible) */ + int64_t vm_state_offset; +} BlockDriverInfo; + +typedef struct QEMUSnapshotInfo { + char id_str[128]; /* unique snapshot id */ + /* the following fields are informative. They are not needed for + the consistency of the snapshot */ + char name[256]; /* user choosen name */ + uint32_t vm_state_size; /* VM state info size */ + uint32_t date_sec; /* UTC date of the snapshot */ + uint32_t date_nsec; + uint64_t vm_clock_nsec; /* VM clock relative to boot */ +} QEMUSnapshotInfo; + +#define BDRV_O_RDONLY 0x0000 +#define BDRV_O_RDWR 0x0002 +#define BDRV_O_ACCESS 0x0003 +#define BDRV_O_CREAT 0x0004 /* create an empty file */ +#define BDRV_O_SNAPSHOT 0x0008 /* open the file read only and save writes in a snapshot */ +#define BDRV_O_FILE 0x0010 /* open as a raw file (do not try to + use a disk image format on top of + it (default for + bdrv_file_open()) */ + +void bdrv_init(void); +BlockDriver *bdrv_find_format(const char *format_name); +int bdrv_create(BlockDriver *drv, + const char *filename, int64_t size_in_sectors, + const char *backing_file, int flags); +BlockDriverState *bdrv_new(const char *device_name); +void bdrv_delete(BlockDriverState *bs); +int bdrv_file_open(BlockDriverState **pbs, const char *filename, int flags); +int bdrv_open(BlockDriverState *bs, const char *filename, int flags); +int bdrv_open2(BlockDriverState *bs, const char *filename, int flags, + BlockDriver *drv); +void bdrv_close(BlockDriverState *bs); +int bdrv_read(BlockDriverState *bs, int64_t sector_num, + uint8_t *buf, int nb_sectors); +int bdrv_write(BlockDriverState *bs, int64_t sector_num, + const uint8_t *buf, int nb_sectors); +int bdrv_pread(BlockDriverState *bs, int64_t offset, + void *buf, int count); +int bdrv_pwrite(BlockDriverState *bs, int64_t offset, + const void *buf, int count); +int bdrv_truncate(BlockDriverState *bs, int64_t offset); +int64_t bdrv_getlength(BlockDriverState *bs); +void bdrv_get_geometry(BlockDriverState *bs, int64_t *nb_sectors_ptr); +int bdrv_commit(BlockDriverState *bs); +void bdrv_set_boot_sector(BlockDriverState *bs, const uint8_t *data, int size); +/* async block I/O */ +typedef struct BlockDriverAIOCB BlockDriverAIOCB; +typedef void BlockDriverCompletionFunc(void *opaque, int ret); + +BlockDriverAIOCB *bdrv_aio_read(BlockDriverState *bs, int64_t sector_num, + uint8_t *buf, int nb_sectors, + BlockDriverCompletionFunc *cb, void *opaque); +BlockDriverAIOCB *bdrv_aio_write(BlockDriverState *bs, int64_t sector_num, + const uint8_t *buf, int nb_sectors, + BlockDriverCompletionFunc *cb, void *opaque); +void bdrv_aio_cancel(BlockDriverAIOCB *acb); + +void qemu_aio_init(void); +void qemu_aio_poll(void); +void qemu_aio_flush(void); +void qemu_aio_wait_start(void); +void qemu_aio_wait(void); +void qemu_aio_wait_end(void); + +/* Ensure contents are flushed to disk. */ +void bdrv_flush(BlockDriverState *bs); + +#define BDRV_TYPE_HD 0 +#define BDRV_TYPE_CDROM 1 +#define BDRV_TYPE_FLOPPY 2 +#define BIOS_ATA_TRANSLATION_AUTO 0 +#define BIOS_ATA_TRANSLATION_NONE 1 +#define BIOS_ATA_TRANSLATION_LBA 2 +#define BIOS_ATA_TRANSLATION_LARGE 3 +#define BIOS_ATA_TRANSLATION_RECHS 4 + +void bdrv_set_geometry_hint(BlockDriverState *bs, + int cyls, int heads, int secs); +void bdrv_set_type_hint(BlockDriverState *bs, int type); +void bdrv_set_translation_hint(BlockDriverState *bs, int translation); +void bdrv_get_geometry_hint(BlockDriverState *bs, + int *pcyls, int *pheads, int *psecs); +int bdrv_get_type_hint(BlockDriverState *bs); +int bdrv_get_translation_hint(BlockDriverState *bs); +int bdrv_is_removable(BlockDriverState *bs); +int bdrv_is_read_only(BlockDriverState *bs); +int bdrv_is_inserted(BlockDriverState *bs); +int bdrv_media_changed(BlockDriverState *bs); +int bdrv_is_locked(BlockDriverState *bs); +void bdrv_set_locked(BlockDriverState *bs, int locked); +void bdrv_eject(BlockDriverState *bs, int eject_flag); +void bdrv_set_change_cb(BlockDriverState *bs, + void (*change_cb)(void *opaque), void *opaque); +void bdrv_get_format(BlockDriverState *bs, char *buf, int buf_size); +void bdrv_info(void); +BlockDriverState *bdrv_find(const char *name); +void bdrv_iterate(void (*it)(void *opaque, const char *name), void *opaque); +int bdrv_is_encrypted(BlockDriverState *bs); +int bdrv_set_key(BlockDriverState *bs, const char *key); +void bdrv_iterate_format(void (*it)(void *opaque, const char *name), + void *opaque); +const char *bdrv_get_device_name(BlockDriverState *bs); +int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num, + const uint8_t *buf, int nb_sectors); +int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi); + +void bdrv_get_backing_filename(BlockDriverState *bs, + char *filename, int filename_size); +int bdrv_snapshot_create(BlockDriverState *bs, + QEMUSnapshotInfo *sn_info); +int bdrv_snapshot_goto(BlockDriverState *bs, + const char *snapshot_id); +int bdrv_snapshot_delete(BlockDriverState *bs, const char *snapshot_id); +int bdrv_snapshot_list(BlockDriverState *bs, + QEMUSnapshotInfo **psn_info); +char *bdrv_snapshot_dump(char *buf, int buf_size, QEMUSnapshotInfo *sn); + +char *get_human_readable_size(char *buf, int buf_size, int64_t size); +int path_is_absolute(const char *path); +void path_combine(char *dest, int dest_size, + const char *base_path, + const char *filename); + +#ifndef QEMU_TOOL + +typedef void QEMUMachineInitFunc(int ram_size, int vga_ram_size, + int boot_device, + DisplayState *ds, const char **fd_filename, int snapshot, + const char *kernel_filename, const char *kernel_cmdline, + const char *initrd_filename); + +typedef struct QEMUMachine { + const char *name; + const char *desc; + QEMUMachineInitFunc *init; + struct QEMUMachine *next; +} QEMUMachine; + +int qemu_register_machine(QEMUMachine *m); + +typedef void SetIRQFunc(void *opaque, int irq_num, int level); +typedef void IRQRequestFunc(void *opaque, int level); + +#ifdef ASDDasdasda0011 +/* ISA bus */ + +extern target_phys_addr_t isa_mem_base; + +typedef void (IOPortWriteFunc)(void *opaque, uint32_t address, uint32_t data); +typedef uint32_t (IOPortReadFunc)(void *opaque, uint32_t address); + +int register_ioport_read(int start, int length, int size, + IOPortReadFunc *func, void *opaque); +int register_ioport_write(int start, int length, int size, + IOPortWriteFunc *func, void *opaque); +void isa_unassign_ioport(int start, int length); + +void isa_mmio_init(target_phys_addr_t base, target_phys_addr_t size); + +/* PCI bus */ + +extern target_phys_addr_t pci_mem_base; + +typedef struct PCIBus PCIBus; +typedef struct PCIDevice PCIDevice; + +typedef void PCIConfigWriteFunc(PCIDevice *pci_dev, + uint32_t address, uint32_t data, int len); +typedef uint32_t PCIConfigReadFunc(PCIDevice *pci_dev, + uint32_t address, int len); +typedef void PCIMapIORegionFunc(PCIDevice *pci_dev, int region_num, + uint32_t addr, uint32_t size, int type); + +#define PCI_ADDRESS_SPACE_MEM 0x00 +#define PCI_ADDRESS_SPACE_IO 0x01 +#define PCI_ADDRESS_SPACE_MEM_PREFETCH 0x08 + +typedef struct PCIIORegion { + uint32_t addr; /* current PCI mapping address. -1 means not mapped */ + uint32_t size; + uint8_t type; + PCIMapIORegionFunc *map_func; +} PCIIORegion; + +#define PCI_ROM_SLOT 6 +#define PCI_NUM_REGIONS 7 + +#define PCI_DEVICES_MAX 64 + +#define PCI_VENDOR_ID 0x00 /* 16 bits */ +#define PCI_DEVICE_ID 0x02 /* 16 bits */ +#define PCI_COMMAND 0x04 /* 16 bits */ +#define PCI_COMMAND_IO 0x1 /* Enable response in I/O space */ +#define PCI_COMMAND_MEMORY 0x2 /* Enable response in Memory space */ +#define PCI_CLASS_DEVICE 0x0a /* Device class */ +#define PCI_INTERRUPT_LINE 0x3c /* 8 bits */ +#define PCI_INTERRUPT_PIN 0x3d /* 8 bits */ +#define PCI_MIN_GNT 0x3e /* 8 bits */ +#define PCI_MAX_LAT 0x3f /* 8 bits */ + +struct PCIDevice { + /* PCI config space */ + uint8_t config[256]; + + /* the following fields are read only */ + PCIBus *bus; + int devfn; + char name[64]; + PCIIORegion io_regions[PCI_NUM_REGIONS]; + + /* do not access the following fields */ + PCIConfigReadFunc *config_read; + PCIConfigWriteFunc *config_write; + /* ??? This is a PC-specific hack, and should be removed. */ + int irq_index; + + /* Current IRQ levels. Used internally by the generic PCI code. */ + int irq_state[4]; +}; + +PCIDevice *pci_register_device(PCIBus *bus, const char *name, + int instance_size, int devfn, + PCIConfigReadFunc *config_read, + PCIConfigWriteFunc *config_write); + +void pci_register_io_region(PCIDevice *pci_dev, int region_num, + uint32_t size, int type, + PCIMapIORegionFunc *map_func); + +void pci_set_irq(PCIDevice *pci_dev, int irq_num, int level); + +uint32_t pci_default_read_config(PCIDevice *d, + uint32_t address, int len); +void pci_default_write_config(PCIDevice *d, + uint32_t address, uint32_t val, int len); +void pci_device_save(PCIDevice *s, QEMUFile *f); +int pci_device_load(PCIDevice *s, QEMUFile *f); + +typedef void (*pci_set_irq_fn)(void *pic, int irq_num, int level); +typedef int (*pci_map_irq_fn)(PCIDevice *pci_dev, int irq_num); +PCIBus *pci_register_bus(pci_set_irq_fn set_irq, pci_map_irq_fn map_irq, + void *pic, int devfn_min, int nirq); + +void pci_nic_init(PCIBus *bus, NICInfo *nd, int devfn); +void pci_data_write(void *opaque, uint32_t addr, uint32_t val, int len); +uint32_t pci_data_read(void *opaque, uint32_t addr, int len); +int pci_bus_num(PCIBus *s); +void pci_for_each_device(int bus_num, void (*fn)(PCIDevice *d)); + +void pci_info(void); +PCIBus *pci_bridge_init(PCIBus *bus, int devfn, uint32_t id, + pci_map_irq_fn map_irq, const char *name); + +/* prep_pci.c */ +PCIBus *pci_prep_init(void); + +/* grackle_pci.c */ +PCIBus *pci_grackle_init(uint32_t base, void *pic); + +/* unin_pci.c */ +PCIBus *pci_pmac_init(void *pic); + +/* apb_pci.c */ +PCIBus *pci_apb_init(target_ulong special_base, target_ulong mem_base, + void *pic); + +PCIBus *pci_vpb_init(void *pic, int irq, int realview); + +/* piix_pci.c */ +PCIBus *i440fx_init(PCIDevice **pi440fx_state); +void i440fx_set_smm(PCIDevice *d, int val); +int piix3_init(PCIBus *bus, int devfn); +void i440fx_init_memory_mappings(PCIDevice *d); + +int piix4_init(PCIBus *bus, int devfn); + +/* openpic.c */ +typedef struct openpic_t openpic_t; +void openpic_set_irq(void *opaque, int n_IRQ, int level); +openpic_t *openpic_init (PCIBus *bus, int *pmem_index, int nb_cpus, + CPUState **envp); + +/* heathrow_pic.c */ +typedef struct HeathrowPICS HeathrowPICS; +void heathrow_pic_set_irq(void *opaque, int num, int level); +HeathrowPICS *heathrow_pic_init(int *pmem_index); + +/* gt64xxx.c */ +PCIBus *pci_gt64120_init(void *pic); + +#ifdef HAS_AUDIO +struct soundhw { + const char *name; + const char *descr; + int enabled; + int isa; + union { + int (*init_isa) (AudioState *s); + int (*init_pci) (PCIBus *bus, AudioState *s); + } init; +}; + +extern struct soundhw soundhw[]; +#endif + +/* vga.c */ + +#define VGA_RAM_SIZE (8192 * 1024) + +struct DisplayState { + uint8_t *data; + int linesize; + int depth; + int bgr; /* BGR color order instead of RGB. Only valid for depth == 32 */ + int width; + int height; + void *opaque; + + void (*dpy_update)(struct DisplayState *s, int x, int y, int w, int h); + void (*dpy_resize)(struct DisplayState *s, int w, int h); + void (*dpy_refresh)(struct DisplayState *s); + void (*dpy_copy)(struct DisplayState *s, int src_x, int src_y, int dst_x, int dst_y, int w, int h); +}; + +static inline void dpy_update(DisplayState *s, int x, int y, int w, int h) +{ + s->dpy_update(s, x, y, w, h); +} + +static inline void dpy_resize(DisplayState *s, int w, int h) +{ + s->dpy_resize(s, w, h); +} + +int isa_vga_init(DisplayState *ds, uint8_t *vga_ram_base, + unsigned long vga_ram_offset, int vga_ram_size); +int pci_vga_init(PCIBus *bus, DisplayState *ds, uint8_t *vga_ram_base, + unsigned long vga_ram_offset, int vga_ram_size, + unsigned long vga_bios_offset, int vga_bios_size); + +/* cirrus_vga.c */ +void pci_cirrus_vga_init(PCIBus *bus, DisplayState *ds, uint8_t *vga_ram_base, + unsigned long vga_ram_offset, int vga_ram_size); +void isa_cirrus_vga_init(DisplayState *ds, uint8_t *vga_ram_base, + unsigned long vga_ram_offset, int vga_ram_size); + +/* sdl.c */ +void sdl_display_init(DisplayState *ds, int full_screen); + +/* cocoa.m */ +void cocoa_display_init(DisplayState *ds, int full_screen); + +/* vnc.c */ +void vnc_display_init(DisplayState *ds, const char *display); +void do_info_vnc(void); + +/* x_keymap.c */ +extern uint8_t _translate_keycode(const int key); + +/* ide.c */ +#define MAX_DISKS 4 + +extern BlockDriverState *bs_table[MAX_DISKS + 1]; + +void isa_ide_init(int iobase, int iobase2, int irq, + BlockDriverState *hd0, BlockDriverState *hd1); +void pci_cmd646_ide_init(PCIBus *bus, BlockDriverState **hd_table, + int secondary_ide_enabled); +void pci_piix3_ide_init(PCIBus *bus, BlockDriverState **hd_table, int devfn); +int pmac_ide_init (BlockDriverState **hd_table, + SetIRQFunc *set_irq, void *irq_opaque, int irq); + +/* cdrom.c */ +int cdrom_read_toc(int nb_sectors, uint8_t *buf, int msf, int start_track); +int cdrom_read_toc_raw(int nb_sectors, uint8_t *buf, int msf, int session_num); + +/* es1370.c */ +int es1370_init (PCIBus *bus, AudioState *s); + +/* sb16.c */ +int SB16_init (AudioState *s); + +/* adlib.c */ +int Adlib_init (AudioState *s); + +/* gus.c */ +int GUS_init (AudioState *s); + +/* dma.c */ +typedef int (*DMA_transfer_handler) (void *opaque, int nchan, int pos, int size); +int DMA_get_channel_mode (int nchan); +int DMA_read_memory (int nchan, void *buf, int pos, int size); +int DMA_write_memory (int nchan, void *buf, int pos, int size); +void DMA_hold_DREQ (int nchan); +void DMA_release_DREQ (int nchan); +void DMA_schedule(int nchan); +void DMA_run (void); +void DMA_init (int high_page_enable); +void DMA_register_channel (int nchan, + DMA_transfer_handler transfer_handler, + void *opaque); +/* fdc.c */ +#define MAX_FD 2 +extern BlockDriverState *fd_table[MAX_FD]; + +typedef struct fdctrl_t fdctrl_t; + +fdctrl_t *fdctrl_init (int irq_lvl, int dma_chann, int mem_mapped, + uint32_t io_base, + BlockDriverState **fds); +int fdctrl_get_drive_type(fdctrl_t *fdctrl, int drive_num); + +/* ne2000.c */ + +void isa_ne2000_init(int base, int irq, NICInfo *nd); +void pci_ne2000_init(PCIBus *bus, NICInfo *nd, int devfn); + +/* rtl8139.c */ + +void pci_rtl8139_init(PCIBus *bus, NICInfo *nd, int devfn); + +/* pcnet.c */ + +void pci_pcnet_init(PCIBus *bus, NICInfo *nd, int devfn); +void pcnet_h_reset(void *opaque); +void *lance_init(NICInfo *nd, uint32_t leaddr, void *dma_opaque); + + +/* pckbd.c */ + +void kbd_init(void); + +/* mc146818rtc.c */ + +typedef struct RTCState RTCState; + +RTCState *rtc_init(int base, int irq); +void rtc_set_memory(RTCState *s, int addr, int val); +void rtc_set_date(RTCState *s, const struct tm *tm); + +/* serial.c */ + +typedef struct SerialState SerialState; +SerialState *serial_init(SetIRQFunc *set_irq, void *opaque, + int base, int irq, CharDriverState *chr); +SerialState *serial_mm_init (SetIRQFunc *set_irq, void *opaque, + target_ulong base, int it_shift, + int irq, CharDriverState *chr); + +/* parallel.c */ + +typedef struct ParallelState ParallelState; +ParallelState *parallel_init(int base, int irq, CharDriverState *chr); + +/* i8259.c */ + +typedef struct PicState2 PicState2; +extern PicState2 *isa_pic; +void pic_set_irq(int irq, int level); +void pic_set_irq_new(void *opaque, int irq, int level); +PicState2 *pic_init(IRQRequestFunc *irq_request, void *irq_request_opaque); +void pic_set_alt_irq_func(PicState2 *s, SetIRQFunc *alt_irq_func, + void *alt_irq_opaque); +int pic_read_irq(PicState2 *s); +void pic_update_irq(PicState2 *s); +uint32_t pic_intack_read(PicState2 *s); +void pic_info(void); +void irq_info(void); + +/* APIC */ +typedef struct IOAPICState IOAPICState; + +int apic_init(CPUState *env); +int apic_get_interrupt(CPUState *env); +IOAPICState *ioapic_init(void); +void ioapic_set_irq(void *opaque, int vector, int level); + +/* i8254.c */ + +#define PIT_FREQ 1193182 + +typedef struct PITState PITState; + +PITState *pit_init(int base, int irq); +void pit_set_gate(PITState *pit, int channel, int val); +int pit_get_gate(PITState *pit, int channel); +int pit_get_initial_count(PITState *pit, int channel); +int pit_get_mode(PITState *pit, int channel); +int pit_get_out(PITState *pit, int channel, int64_t current_time); + +/* pcspk.c */ +void pcspk_init(PITState *); +int pcspk_audio_init(AudioState *); + +#include "hw/smbus.h" + +/* acpi.c */ +extern int acpi_enabled; +void piix4_pm_init(PCIBus *bus, int devfn); +void piix4_smbus_register_device(SMBusDevice *dev, uint8_t addr); +void acpi_bios_init(void); + +/* smbus_eeprom.c */ +SMBusDevice *smbus_eeprom_device_init(uint8_t addr, uint8_t *buf); + +/* pc.c */ +extern QEMUMachine pc_machine; +extern QEMUMachine isapc_machine; +extern int fd_bootchk; + +void ioport_set_a20(int enable); +int ioport_get_a20(void); + +/* ppc.c */ +extern QEMUMachine prep_machine; +extern QEMUMachine core99_machine; +extern QEMUMachine heathrow_machine; + +/* mips_r4k.c */ +extern QEMUMachine mips_machine; + +/* mips_malta.c */ +extern QEMUMachine mips_malta_machine; + +/* mips_int */ +extern void cpu_mips_irq_request(void *opaque, int irq, int level); + +/* mips_timer.c */ +extern void cpu_mips_clock_init(CPUState *); +extern void cpu_mips_irqctrl_init (void); + +/* shix.c */ +extern QEMUMachine shix_machine; + +#ifdef TARGET_PPC +ppc_tb_t *cpu_ppc_tb_init (CPUState *env, uint32_t freq); +#endif +void PREP_debug_write (void *opaque, uint32_t addr, uint32_t val); + +extern CPUWriteMemoryFunc *PPC_io_write[]; +extern CPUReadMemoryFunc *PPC_io_read[]; +void PPC_debug_write (void *opaque, uint32_t addr, uint32_t val); + +/* sun4m.c */ +extern QEMUMachine sun4m_machine; +void pic_set_irq_cpu(int irq, int level, unsigned int cpu); + +/* iommu.c */ +void *iommu_init(uint32_t addr); +void sparc_iommu_memory_rw(void *opaque, target_phys_addr_t addr, + uint8_t *buf, int len, int is_write); +static inline void sparc_iommu_memory_read(void *opaque, + target_phys_addr_t addr, + uint8_t *buf, int len) +{ + sparc_iommu_memory_rw(opaque, addr, buf, len, 0); +} + +static inline void sparc_iommu_memory_write(void *opaque, + target_phys_addr_t addr, + uint8_t *buf, int len) +{ + sparc_iommu_memory_rw(opaque, addr, buf, len, 1); +} + +/* tcx.c */ +void tcx_init(DisplayState *ds, uint32_t addr, uint8_t *vram_base, + unsigned long vram_offset, int vram_size, int width, int height); + +/* slavio_intctl.c */ +void *slavio_intctl_init(); +void slavio_intctl_set_cpu(void *opaque, unsigned int cpu, CPUState *env); +void slavio_pic_info(void *opaque); +void slavio_irq_info(void *opaque); +void slavio_pic_set_irq(void *opaque, int irq, int level); +void slavio_pic_set_irq_cpu(void *opaque, int irq, int level, unsigned int cpu); + +/* loader.c */ +int get_image_size(const char *filename); +int load_image(const char *filename, uint8_t *addr); +int load_elf(const char *filename, int64_t virt_to_phys_addend, uint64_t *pentry); +int load_aout(const char *filename, uint8_t *addr); + +/* slavio_timer.c */ +void slavio_timer_init(uint32_t addr, int irq, int mode, unsigned int cpu); + +/* slavio_serial.c */ +SerialState *slavio_serial_init(int base, int irq, CharDriverState *chr1, CharDriverState *chr2); +void slavio_serial_ms_kbd_init(int base, int irq); + +/* slavio_misc.c */ +void *slavio_misc_init(uint32_t base, int irq); +void slavio_set_power_fail(void *opaque, int power_failing); + +/* esp.c */ +void esp_scsi_attach(void *opaque, BlockDriverState *bd, int id); +void *esp_init(BlockDriverState **bd, uint32_t espaddr, void *dma_opaque); +void esp_reset(void *opaque); + +/* sparc32_dma.c */ +void *sparc32_dma_init(uint32_t daddr, int espirq, int leirq, void *iommu, + void *intctl); +void ledma_set_irq(void *opaque, int isr); +void ledma_memory_read(void *opaque, target_phys_addr_t addr, + uint8_t *buf, int len, int do_bswap); +void ledma_memory_write(void *opaque, target_phys_addr_t addr, + uint8_t *buf, int len, int do_bswap); +void espdma_raise_irq(void *opaque); +void espdma_clear_irq(void *opaque); +void espdma_memory_read(void *opaque, uint8_t *buf, int len); +void espdma_memory_write(void *opaque, uint8_t *buf, int len); +void sparc32_dma_set_reset_data(void *opaque, void *esp_opaque, + void *lance_opaque); + +/* cs4231.c */ +void cs_init(target_phys_addr_t base, int irq, void *intctl); + +/* sun4u.c */ +extern QEMUMachine sun4u_machine; + +/* NVRAM helpers */ +#include "hw/m48t59.h" + +void NVRAM_set_byte (m48t59_t *nvram, uint32_t addr, uint8_t value); +uint8_t NVRAM_get_byte (m48t59_t *nvram, uint32_t addr); +void NVRAM_set_word (m48t59_t *nvram, uint32_t addr, uint16_t value); +uint16_t NVRAM_get_word (m48t59_t *nvram, uint32_t addr); +void NVRAM_set_lword (m48t59_t *nvram, uint32_t addr, uint32_t value); +uint32_t NVRAM_get_lword (m48t59_t *nvram, uint32_t addr); +void NVRAM_set_string (m48t59_t *nvram, uint32_t addr, + const unsigned char *str, uint32_t max); +int NVRAM_get_string (m48t59_t *nvram, uint8_t *dst, uint16_t addr, int max); +void NVRAM_set_crc (m48t59_t *nvram, uint32_t addr, + uint32_t start, uint32_t count); +int PPC_NVRAM_set_params (m48t59_t *nvram, uint16_t NVRAM_size, + const unsigned char *arch, + uint32_t RAM_size, int boot_device, + uint32_t kernel_image, uint32_t kernel_size, + const char *cmdline, + uint32_t initrd_image, uint32_t initrd_size, + uint32_t NVRAM_image, + int width, int height, int depth); + +/* adb.c */ + +#define MAX_ADB_DEVICES 16 + +#define ADB_MAX_OUT_LEN 16 + +typedef struct ADBDevice ADBDevice; + +/* buf = NULL means polling */ +typedef int ADBDeviceRequest(ADBDevice *d, uint8_t *buf_out, + const uint8_t *buf, int len); +typedef int ADBDeviceReset(ADBDevice *d); + +struct ADBDevice { + struct ADBBusState *bus; + int devaddr; + int handler; + ADBDeviceRequest *devreq; + ADBDeviceReset *devreset; + void *opaque; +}; + +typedef struct ADBBusState { + ADBDevice devices[MAX_ADB_DEVICES]; + int nb_devices; + int poll_index; +} ADBBusState; + +int adb_request(ADBBusState *s, uint8_t *buf_out, + const uint8_t *buf, int len); +int adb_poll(ADBBusState *s, uint8_t *buf_out); + +ADBDevice *adb_register_device(ADBBusState *s, int devaddr, + ADBDeviceRequest *devreq, + ADBDeviceReset *devreset, + void *opaque); +void adb_kbd_init(ADBBusState *bus); +void adb_mouse_init(ADBBusState *bus); + +/* cuda.c */ + +extern ADBBusState adb_bus; +int cuda_init(SetIRQFunc *set_irq, void *irq_opaque, int irq); + +#include "hw/usb.h" + +/* usb ports of the VM */ + +void qemu_register_usb_port(USBPort *port, void *opaque, int index, + usb_attachfn attach); + +#define VM_USB_HUB_SIZE 8 + +void do_usb_add(const char *devname); +void do_usb_del(const char *devname); +void usb_info(void); + +/* scsi-disk.c */ +enum scsi_reason { + SCSI_REASON_DONE, /* Command complete. */ + SCSI_REASON_DATA /* Transfer complete, more data required. */ +}; + +typedef struct SCSIDevice SCSIDevice; +typedef void (*scsi_completionfn)(void *opaque, int reason, uint32_t tag, + uint32_t arg); + +SCSIDevice *scsi_disk_init(BlockDriverState *bdrv, + int tcq, + scsi_completionfn completion, + void *opaque); +void scsi_disk_destroy(SCSIDevice *s); + +int32_t scsi_send_command(SCSIDevice *s, uint32_t tag, uint8_t *buf, int lun); +/* SCSI data transfers are asynchrnonous. However, unlike the block IO + layer the completion routine may be called directly by + scsi_{read,write}_data. */ +void scsi_read_data(SCSIDevice *s, uint32_t tag); +int scsi_write_data(SCSIDevice *s, uint32_t tag); +void scsi_cancel_io(SCSIDevice *s, uint32_t tag); +uint8_t *scsi_get_buf(SCSIDevice *s, uint32_t tag); + +/* lsi53c895a.c */ +void lsi_scsi_attach(void *opaque, BlockDriverState *bd, int id); +void *lsi_scsi_init(PCIBus *bus, int devfn); + +/* integratorcp.c */ +extern QEMUMachine integratorcp926_machine; +extern QEMUMachine integratorcp1026_machine; + +/* versatilepb.c */ +extern QEMUMachine versatilepb_machine; +extern QEMUMachine versatileab_machine; + +/* realview.c */ +extern QEMUMachine realview_machine; + +/* ps2.c */ +void *ps2_kbd_init(void (*update_irq)(void *, int), void *update_arg); +void *ps2_mouse_init(void (*update_irq)(void *, int), void *update_arg); +void ps2_write_mouse(void *, int val); +void ps2_write_keyboard(void *, int val); +uint32_t ps2_read_data(void *); +void ps2_queue(void *, int b); +void ps2_keyboard_set_translation(void *opaque, int mode); + +/* smc91c111.c */ +void smc91c111_init(NICInfo *, uint32_t, void *, int); + +/* pl110.c */ +void *pl110_init(DisplayState *ds, uint32_t base, void *pic, int irq, int); + +/* pl011.c */ +void pl011_init(uint32_t base, void *pic, int irq, CharDriverState *chr); + +/* pl050.c */ +void pl050_init(uint32_t base, void *pic, int irq, int is_mouse); + +/* pl080.c */ +void *pl080_init(uint32_t base, void *pic, int irq, int nchannels); + +/* pl190.c */ +void *pl190_init(uint32_t base, void *parent, int irq, int fiq); + +/* arm-timer.c */ +void sp804_init(uint32_t base, void *pic, int irq); +void icp_pit_init(uint32_t base, void *pic, int irq); + +/* arm_sysctl.c */ +void arm_sysctl_init(uint32_t base, uint32_t sys_id); + +/* arm_gic.c */ +void *arm_gic_init(uint32_t base, void *parent, int parent_irq); + +/* arm_boot.c */ + +void arm_load_kernel(CPUState *env, int ram_size, const char *kernel_filename, + const char *kernel_cmdline, const char *initrd_filename, + int board_id); + +/* sh7750.c */ +struct SH7750State; + +struct SH7750State *sh7750_init(CPUState * cpu); + +typedef struct { + /* The callback will be triggered if any of the designated lines change */ + uint16_t portamask_trigger; + uint16_t portbmask_trigger; + /* Return 0 if no action was taken */ + int (*port_change_cb) (uint16_t porta, uint16_t portb, + uint16_t * periph_pdtra, + uint16_t * periph_portdira, + uint16_t * periph_pdtrb, + uint16_t * periph_portdirb); +} sh7750_io_device; + +int sh7750_register_io_device(struct SH7750State *s, + sh7750_io_device * device); +/* tc58128.c */ +int tc58128_init(struct SH7750State *s, char *zone1, char *zone2); + +/* NOR flash devices */ +typedef struct pflash_t pflash_t; + +pflash_t *pflash_register (target_ulong base, ram_addr_t off, + BlockDriverState *bs, + target_ulong sector_len, int nb_blocs, int width, + uint16_t id0, uint16_t id1, + uint16_t id2, uint16_t id3); + +#include "gdbstub.h" + +#endif /* defined(QEMU_TOOL) */ + +/* monitor.c */ +void monitor_init(CharDriverState *hd, int show_banner); +void term_puts(const char *str); +void term_vprintf(const char *fmt, va_list ap); +void term_printf(const char *fmt, ...); +void term_print_filename(const char *filename); +void term_flush(void); +void term_print_help(void); +void monitor_readline(const char *prompt, int is_password, + char *buf, int buf_size); + +/* readline.c */ +typedef void ReadLineFunc(void *opaque, const char *str); + +extern int completion_index; +void add_completion(const char *str); +void readline_handle_byte(int ch); +void readline_find_completion(const char *cmdline); +const char *readline_get_history(unsigned int index); +void readline_start(const char *prompt, int is_password, + ReadLineFunc *readline_func, void *opaque); + +void kqemu_record_dump(void); +#endif + +#endif /* VL_H */ diff --git a/plugins/dev9ghzdrk/flash.cpp b/plugins/dev9ghzdrk/flash.cpp new file mode 100644 index 0000000000..0a4f2a2f24 --- /dev/null +++ b/plugins/dev9ghzdrk/flash.cpp @@ -0,0 +1,249 @@ +// The code has been designed for 64Mb flash and uses as file support the second memory card +#include +#include +#include "DEV9.h" + +#define PAGE_SIZE_BITS 9 +#define PAGE_SIZE (1<>2), page+PAGE_SIZE+0*3);//(ECC_SIZE>>2)); + xfromman_call20_calculateXors(page + 1*(PAGE_SIZE>>2), page+PAGE_SIZE+1*3);//(ECC_SIZE>>2)); + xfromman_call20_calculateXors(page + 2*(PAGE_SIZE>>2), page+PAGE_SIZE+2*3);//(ECC_SIZE>>2)); + xfromman_call20_calculateXors(page + 3*(PAGE_SIZE>>2), page+PAGE_SIZE+3*3);//(ECC_SIZE>>2)); +} + +static char* getCmdName(u32 cmd){ + switch(cmd) { + case SM_CMD_READ1: return "READ1"; + case SM_CMD_READ2: return "READ2"; + case SM_CMD_READ3: return "READ3"; + case SM_CMD_RESET: return "RESET"; + case SM_CMD_WRITEDATA: return "WRITEDATA"; + case SM_CMD_PROGRAMPAGE: return "PROGRAMPAGE"; + case SM_CMD_ERASEBLOCK: return "ERASEBLOCK"; + case SM_CMD_ERASECONFIRM: return "ERASECONFIRM"; + case SM_CMD_GETSTATUS: return "GETSTATUS"; + case SM_CMD_READID: return "READID"; + default: return "unknown"; + } +} + +void CALLBACK FLASHinit(){ + FILE *fd; + + id= FLASH_ID_64MBIT; + counter= 0; + addrbyte= 0; + + address = 0; + memset(data, 0xFF, PAGE_SIZE); + calculateECC(data); + ctrl = FLASH_PP_READY; + + if (fd=fopen("flash.dat", "rb")){ + fread(file, 1, CARD_SIZE_ECC, fd); + fclose(fd); + }else + memset(file, 0xFF, CARD_SIZE_ECC); +} + +u32 CALLBACK FLASHread32(u32 addr, int size) { + u32 value, refill= 0; + + switch(addr) { + case FLASH_R_DATA: + memcpy(&value, &data[counter], size); + counter += size; + DEV9_LOG("*FLASH DATA %dbit read 0x%08lX %s\n", size*8, value, (ctrl & FLASH_PP_READ) ? "READ_ENABLE" : "READ_DISABLE"); + if (cmd == SM_CMD_READ3){ + if (counter >= PAGE_SIZE_ECC){ + counter= PAGE_SIZE; + refill= 1; + } + }else{ + if ( (ctrl & FLASH_PP_NOECC) && (counter >= PAGE_SIZE)){ + counter %= PAGE_SIZE; + refill= 1; + }else + if (!(ctrl & FLASH_PP_NOECC) && (counter >= PAGE_SIZE_ECC)){ + counter %= PAGE_SIZE_ECC; + refill= 1; + } + } + + if (refill){ + ctrl &= ~FLASH_PP_READY; + address += PAGE_SIZE; + address %= CARD_SIZE; + memcpy(data, file+(address>>PAGE_SIZE_BITS)*PAGE_SIZE_ECC, PAGE_SIZE); + calculateECC(data); // calculate ECC; should be in the file already + ctrl |= FLASH_PP_READY; + } + + return value; + + case FLASH_R_CMD: + DEV9_LOG("*FLASH CMD %dbit read %s DENIED\n", size*8, getCmdName(cmd)); + return cmd; + + case FLASH_R_ADDR: + DEV9_LOG("*FLASH ADDR %dbit read DENIED\n", size*8); + return 0; + + case FLASH_R_CTRL: + DEV9_LOG("*FLASH CTRL %dbit read 0x%08lX\n", size*8, ctrl); + return ctrl; + + case FLASH_R_ID: + if (cmd == SM_CMD_READID){ + DEV9_LOG("*FLASH ID %dbit read 0x%08lX\n", size*8, id); + return id;//0x98=Toshiba/0xEC=Samsung maker code should be returned first + }else + if (cmd == SM_CMD_GETSTATUS){ + value= 0x80 | ((ctrl & 1) << 6); // 0:0=pass, 6:ready/busy, 7:1=not protected + DEV9_LOG("*FLASH STATUS %dbit read 0x%08lX\n", size*8, value); + return value; + }//else fall off + + default: + DEV9_LOG("*FLASH Unkwnown %dbit read at address %lx\n", size*8, addr); + return 0; + } +} + +void CALLBACK FLASHwrite32(u32 addr, u32 value, int size) { + + switch(addr & 0x1FFFFFFF) { + case FLASH_R_DATA: + + DEV9_LOG("*FLASH DATA %dbit write 0x%08lX %s\n", size*8, value, (ctrl & FLASH_PP_WRITE) ? "WRITE_ENABLE" : "WRITE_DISABLE"); + memcpy(&data[counter], &value, size); + counter += size; + counter %= PAGE_SIZE_ECC;//should not get past the last byte, but at the end + break; + + case FLASH_R_CMD: + if (!(ctrl & FLASH_PP_READY)){ + if ((value != SM_CMD_GETSTATUS) && (value != SM_CMD_RESET)){ + DEV9_LOG("*FLASH CMD %dbit write %s ILLEGAL in busy mode - IGNORED\n", size*8, getCmdName(value)); + break; + } + } + if (cmd == SM_CMD_WRITEDATA){ + if ((value != SM_CMD_PROGRAMPAGE) && (value != SM_CMD_RESET)){ + DEV9_LOG("*FLASH CMD %dbit write %s ILLEGAL after WRITEDATA cmd - IGNORED\n", size*8, getCmdName(value)); + ctrl &= ~FLASH_PP_READY;//go busy, reset is needed + break; + } + } + DEV9_LOG("*FLASH CMD %dbit write %s\n", size*8, getCmdName(value)); + switch (value){ // A8 bit is encoded in READ cmd;) + case SM_CMD_READ1: counter= 0; if (cmd != SM_CMD_GETSTATUS) address= counter; addrbyte= 0; break; + case SM_CMD_READ2: counter= PAGE_SIZE/2; if (cmd != SM_CMD_GETSTATUS) address= counter; addrbyte= 0; break; + case SM_CMD_READ3: counter= PAGE_SIZE; if (cmd != SM_CMD_GETSTATUS) address= counter; addrbyte= 0; break; + case SM_CMD_RESET: FLASHinit(); break; + case SM_CMD_WRITEDATA: counter= 0; address= counter; addrbyte= 0; break; + case SM_CMD_ERASEBLOCK: counter= 0; memset(data, 0xFF, PAGE_SIZE); address= counter; addrbyte= 1; break; + case SM_CMD_PROGRAMPAGE: //fall + case SM_CMD_ERASECONFIRM: + ctrl &= ~FLASH_PP_READY; + calculateECC(data); + memcpy(file+(address/PAGE_SIZE)*PAGE_SIZE_ECC, data, PAGE_SIZE_ECC); + /*write2file*/ + ctrl |= FLASH_PP_READY; break; + case SM_CMD_GETSTATUS: break; + case SM_CMD_READID: counter= 0; address= counter; addrbyte= 0; break; + default: + ctrl &= ~FLASH_PP_READY; + return;//ignore any other command; go busy, reset is needed + } + cmd= value; + break; + + case FLASH_R_ADDR: + DEV9_LOG("*FLASH ADDR %dbit write 0x%08lX\n", size*8, value); + address |= (value & 0xFF) << (addrbyte == 0 ? 0 : (1 + 8 * addrbyte)); + addrbyte++; + DEV9_LOG("*FLASH ADDR = 0x%08lX (addrbyte=%d)\n", address, addrbyte); + if (!(value & 0x100)){ // address is complete + if ((cmd == SM_CMD_READ1) || (cmd == SM_CMD_READ2) || (cmd == SM_CMD_READ3)) { + ctrl &= ~FLASH_PP_READY; + memcpy(data, file+(address>>PAGE_SIZE_BITS)*PAGE_SIZE_ECC, PAGE_SIZE); + calculateECC(data); // calculate ECC; should be in the file already + ctrl |= FLASH_PP_READY; + } + addrbyte= 0; // address reset + { + u32 bytes, pages, blocks; + + blocks = address / BLOCK_SIZE; + pages = address-(blocks*BLOCK_SIZE); + bytes = pages % PAGE_SIZE; + pages = pages / PAGE_SIZE; + DEV9_LOG("*FLASH ADDR = 0x%08lX (%d:%d:%d) (addrbyte=%d) FINAL\n", address, blocks, pages, bytes, addrbyte); + } + } + break; + + case FLASH_R_CTRL: + DEV9_LOG("*FLASH CTRL %dbit write 0x%08lX\n", size*8, value); + ctrl = (ctrl & FLASH_PP_READY) | (value & ~FLASH_PP_READY); + break; + + case FLASH_R_ID: + DEV9_LOG("*FLASH ID %dbit write 0x%08lX DENIED :P\n", size*8, value); + break; + + default: + DEV9_LOG("*FLASH Unkwnown %dbit write at address 0x%08lX= 0x%08lX IGNORED\n", size*8, addr, value); + break; + } +} + +static unsigned char xor_table[256]={ + 0x00, 0x87, 0x96, 0x11, 0xA5, 0x22, 0x33, 0xB4, 0xB4, 0x33, 0x22, 0xA5, 0x11, 0x96, 0x87, 0x00, + 0xC3, 0x44, 0x55, 0xD2, 0x66, 0xE1, 0xF0, 0x77, 0x77, 0xF0, 0xE1, 0x66, 0xD2, 0x55, 0x44, 0xC3, + 0xD2, 0x55, 0x44, 0xC3, 0x77, 0xF0, 0xE1, 0x66, 0x66, 0xE1, 0xF0, 0x77, 0xC3, 0x44, 0x55, 0xD2, + 0x11, 0x96, 0x87, 0x00, 0xB4, 0x33, 0x22, 0xA5, 0xA5, 0x22, 0x33, 0xB4, 0x00, 0x87, 0x96, 0x11, + 0xE1, 0x66, 0x77, 0xF0, 0x44, 0xC3, 0xD2, 0x55, 0x55, 0xD2, 0xC3, 0x44, 0xF0, 0x77, 0x66, 0xE1, + 0x22, 0xA5, 0xB4, 0x33, 0x87, 0x00, 0x11, 0x96, 0x96, 0x11, 0x00, 0x87, 0x33, 0xB4, 0xA5, 0x22, + 0x33, 0xB4, 0xA5, 0x22, 0x96, 0x11, 0x00, 0x87, 0x87, 0x00, 0x11, 0x96, 0x22, 0xA5, 0xB4, 0x33, + 0xF0, 0x77, 0x66, 0xE1, 0x55, 0xD2, 0xC3, 0x44, 0x44, 0xC3, 0xD2, 0x55, 0xE1, 0x66, 0x77, 0xF0, + 0xF0, 0x77, 0x66, 0xE1, 0x55, 0xD2, 0xC3, 0x44, 0x44, 0xC3, 0xD2, 0x55, 0xE1, 0x66, 0x77, 0xF0, + 0x33, 0xB4, 0xA5, 0x22, 0x96, 0x11, 0x00, 0x87, 0x87, 0x00, 0x11, 0x96, 0x22, 0xA5, 0xB4, 0x33, + 0x22, 0xA5, 0xB4, 0x33, 0x87, 0x00, 0x11, 0x96, 0x96, 0x11, 0x00, 0x87, 0x33, 0xB4, 0xA5, 0x22, + 0xE1, 0x66, 0x77, 0xF0, 0x44, 0xC3, 0xD2, 0x55, 0x55, 0xD2, 0xC3, 0x44, 0xF0, 0x77, 0x66, 0xE1, + 0x11, 0x96, 0x87, 0x00, 0xB4, 0x33, 0x22, 0xA5, 0xA5, 0x22, 0x33, 0xB4, 0x00, 0x87, 0x96, 0x11, + 0xD2, 0x55, 0x44, 0xC3, 0x77, 0xF0, 0xE1, 0x66, 0x66, 0xE1, 0xF0, 0x77, 0xC3, 0x44, 0x55, 0xD2, + 0xC3, 0x44, 0x55, 0xD2, 0x66, 0xE1, 0xF0, 0x77, 0x77, 0xF0, 0xE1, 0x66, 0xD2, 0x55, 0x44, 0xC3, + 0x00, 0x87, 0x96, 0x11, 0xA5, 0x22, 0x33, 0xB4, 0xB4, 0x33, 0x22, 0xA5, 0x11, 0x96, 0x87, 0x00}; + +static void xfromman_call20_calculateXors(unsigned char buffer[128], unsigned char xor[4]){ + register unsigned char a=0, b=0, c=0, i; + + for (i=0; i<128; i++){ + a ^= xor_table[buffer[i]]; + if (xor_table[buffer[i]] & 0x80){ + b ^= ~i; + c ^= i; + } + } + + xor[0]=(~a) & 0x77; + xor[1]=(~b) & 0x7F; + xor[2]=(~c) & 0x7F; +} diff --git a/plugins/dev9ghzdrk/pcap_io.cpp b/plugins/dev9ghzdrk/pcap_io.cpp new file mode 100644 index 0000000000..0d744c22ac --- /dev/null +++ b/plugins/dev9ghzdrk/pcap_io.cpp @@ -0,0 +1,419 @@ +#include +#include +#include "pcap.h" +#include "pcap_io.h" + +#include "dev9.h" +#include "net.h" + +#include + +enum pcap_m_e +{ + switched, + bridged +}; +pcap_m_e pcap_mode=switched; +mac_address virtual_mac = { 0x76, 0x6D, 0x61, 0x63, 0x30, 0x31 }; +//mac_address virtual_mac = { 0x6D, 0x76, 0x63, 0x61, 0x31, 0x30 }; +mac_address broadcast_mac = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }; + +ip_address virtual_ip = { 192, 168, 1, 4}; + +pcap_t *adhandle; +int pcap_io_running=0; + +char errbuf[PCAP_ERRBUF_SIZE]; + +char namebuff[256]; + +FILE*packet_log; + +pcap_dumper_t *dump_pcap; + +mac_address host_mac = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; + +// Fetches the MAC address and prints it +int GetMACAddress(char *adapter, mac_address* addr) +{ + static IP_ADAPTER_INFO AdapterInfo[128]; // Allocate information + // for up to 128 NICs + static PIP_ADAPTER_INFO pAdapterInfo; + ULONG dwBufLen = sizeof(AdapterInfo); // Save memory size of buffer + + DWORD dwStatus = GetAdaptersInfo( // Call GetAdapterInfo + AdapterInfo, // [out] buffer to receive data + &dwBufLen); // [in] size of receive data buffer + if(dwStatus != ERROR_SUCCESS) // Verify return value is + return 0; // valid, no buffer overflow + + pAdapterInfo = AdapterInfo; // Contains pointer to + // current adapter info + do { + if(strcmp(pAdapterInfo->AdapterName,adapter+12)==0) + { + memcpy(addr,pAdapterInfo->Address,6); + return 1; + } + + pAdapterInfo = pAdapterInfo->Next; // Progress through + } + while(pAdapterInfo); // Terminate if last adapter + return 0; +} + +int pcap_io_init(char *adapter) +{ + int dlt; + char *dlt_name; + emu_printf("Opening adapter '%s'...",adapter); + + GetMACAddress(adapter,&host_mac); + + /* Open the adapter */ + if ((adhandle= pcap_open_live(adapter, // name of the device + 65536, // portion of the packet to capture. + // 65536 grants that the whole packet will be captured on all the MACs. + pcap_mode==switched?1:0, // promiscuous mode (nonzero means promiscuous) + 1, // read timeout + errbuf // error buffer + )) == NULL) + { + fprintf(stderr,"\nUnable to open the adapter. %s is not supported by WinPcap\n", adapter); + return -1; + } + + dlt = pcap_datalink(adhandle); + dlt_name = (char*)pcap_datalink_val_to_name(dlt); + + fprintf(stderr,"Device uses DLT %d: %s\n",dlt,dlt_name); + switch(dlt) + { + case DLT_EN10MB : + //case DLT_IEEE802_11: + break; + default: + SysMessage("ERROR: Unsupported DataLink Type (%d): %s",dlt,dlt_name); + pcap_close(adhandle); + return -1; + } + + if(pcap_setnonblock(adhandle,1,errbuf)==-1) + { + fprintf(stderr,"WARNING: Error setting non-blocking mode. Default mode will be used.\n"); + } + + packet_log=fopen("logs/packet.log","w"); + + dump_pcap = pcap_dump_open(adhandle,"logs/pkt_log.pcap"); + + pcap_io_running=1; + emu_printf("Ok.\n"); + return 0; +} + +int gettimeofday (struct timeval *tv, void* tz) +{ + unsigned __int64 ns100; /*time since 1 Jan 1601 in 100ns units */ + + GetSystemTimeAsFileTime((LPFILETIME)&ns100); + tv->tv_usec = (long) ((ns100 / 10L) % 1000000L); + tv->tv_sec = (long) ((ns100 - 116444736000000000L) / 10000000L); + return (0); +} + +int pcap_io_send(void* packet, int plen) +{ + struct pcap_pkthdr ph; + + if(pcap_io_running<=0) + return -1; + emu_printf(" * pcap io: Sending %d byte packet.\n",plen); + + if (pcap_mode==bridged) + { + if(((ethernet_header*)packet)->protocol == 0x0008) //IP + { +#ifndef PLOT_VERSION + virtual_ip = ((ip_header*)((u8*)packet+sizeof(ethernet_header)))->src; +#endif + virtual_mac = ((ethernet_header*)packet)->src; + } + if(((ethernet_header*)packet)->protocol == 0x0608) //ARP + { +#ifndef PLOT_VERSION + virtual_ip = ((arp_packet*)((u8*)packet+sizeof(ethernet_header)))->p_src; +#endif + virtual_mac = ((ethernet_header*)packet)->src; + + ((arp_packet*)((u8*)packet+sizeof(ethernet_header)))->h_src = host_mac; + } + ((ethernet_header*)packet)->src = host_mac; + } + + if(dump_pcap) + { + gettimeofday(&ph.ts,NULL); + ph.caplen=plen; + ph.len=plen; + pcap_dump((u_char*)dump_pcap,&ph,(u_char*)packet); + } + + if(packet_log) + { + int i=0; + int n=0; + + fprintf(packet_log,"PACKET SEND: %d BYTES\n",plen); + for(i=0,n=0;idst,broadcast_mac)==0) + { + static char pack[65536]; + memcpy(pack,packet,plen); + + ((ethernet_header*)packet)->dst=host_mac; + pcap_sendpacket(adhandle, (u_char*)pack, plen); + } + } + + return pcap_sendpacket(adhandle, (u_char*)packet, plen); +} + +int pcap_io_recv(void* packet, int max_len) +{ + int res; + struct pcap_pkthdr *header; + const u_char *pkt_data1; + static u_char pkt_data[32768]; + + if(pcap_io_running<=0) + return -1; + + if((res = pcap_next_ex(adhandle, &header, &pkt_data1)) > 0) + { + ethernet_header *ph=(ethernet_header*)pkt_data; + + memcpy(pkt_data,pkt_data1,header->len); + + if (pcap_mode==bridged) + { + if(((ethernet_header*)pkt_data)->protocol == 0x0008) + { + ip_header *iph=((ip_header*)((u8*)pkt_data+sizeof(ethernet_header))); + if(ip_compare(iph->dst,virtual_ip)==0) + { + ((ethernet_header*)pkt_data)->dst = virtual_mac; + } + } + if(((ethernet_header*)pkt_data)->protocol == 0x0608) + { + arp_packet *aph=((arp_packet*)((u8*)pkt_data+sizeof(ethernet_header))); + if(ip_compare(aph->p_dst,virtual_ip)==0) + { + ((ethernet_header*)pkt_data)->dst = virtual_mac; + ((arp_packet*)((u8*)packet+sizeof(ethernet_header)))->h_dst = virtual_mac; + } + } + } + + if((memcmp(pkt_data,dev9.eeprom,6)!=0)&&(memcmp(pkt_data,&broadcast_mac,6)!=0)) + { + //ignore strange packets + return 0; + } + + if(memcmp(pkt_data+6,dev9.eeprom,6)==0) + { + //avoid pcap looping packets + return 0; + } + + memcpy(packet,pkt_data,header->len); + + if(dump_pcap) + pcap_dump((u_char*)dump_pcap,header,(u_char*)packet); + + + if(packet_log) + { + int i=0; + int n=0; + int plen=header->len; + + fprintf(packet_log,"PACKET RECV: %d BYTES\n",plen); + for(i=0,n=0;ilen; + } + + return -1; +} + +void pcap_io_close() +{ + if(packet_log) + fclose(packet_log); + if(dump_pcap) + pcap_dump_close(dump_pcap); + pcap_close(adhandle); + pcap_io_running=0; +} + + +int pcap_io_get_dev_num() +{ + pcap_if_t *alldevs; + pcap_if_t *d; + int i=0; + + if(pcap_findalldevs(&alldevs, errbuf) == -1) + { + return 0; + } + + d=alldevs; + while(d!=NULL) {d=d->next; i++;} + + pcap_freealldevs(alldevs); + + return i; +} + +char* pcap_io_get_dev_name(int num,int md) +{ + pcap_if_t *alldevs; + pcap_if_t *d; + int i=0; + + if(pcap_findalldevs(&alldevs, errbuf) == -1) + { + return NULL; + } + + d=alldevs; + while(d!=NULL) { + if(num==i) + { + if (!md) + strcpy(namebuff,"pcap switch:"); + else + strcpy(namebuff,"pcap bridge:"); + strcat(namebuff,d->name); + pcap_freealldevs(alldevs); + return namebuff; + } + d=d->next; i++; + } + + pcap_freealldevs(alldevs); + + return NULL; +} + +char* pcap_io_get_dev_desc(int num,int md) +{ + pcap_if_t *alldevs; + pcap_if_t *d; + int i=0; + + if(pcap_findalldevs(&alldevs, errbuf) == -1) + { + return NULL; + } + + d=alldevs; + while(d!=NULL) { + if(num==i) + { + if (!md) + strcpy(namebuff,"pcap switch:"); + else + strcpy(namebuff,"pcap bridge:"); + strcat(namebuff,d->description); + pcap_freealldevs(alldevs); + return namebuff; + } + d=d->next; i++; + } + + pcap_freealldevs(alldevs); + + return NULL; +} + + +PCAPAdapter::PCAPAdapter() +{ + //if (config.ethEnable == 0) return; //whut? nada! + if (config.Eth[5]=='s') + pcap_mode=switched; + else + pcap_mode=bridged; + + if (pcap_io_init(config.Eth+12) == -1) { + SysMessage("Can't open Device '%s'\n", config.Eth); + } +} +bool PCAPAdapter::blocks() +{ + return false; +} +//gets a packet.rv :true success +bool PCAPAdapter::recv(NetPacket* pkt) +{ + int size=pcap_io_recv(pkt->buffer,sizeof(pkt->buffer)); + if(size<=0) + { + return false; + } + else + { + pkt->size=size; + return true; + } +} +//sends the packet .rv :true success +bool PCAPAdapter::send(NetPacket* pkt) +{ + if(pcap_io_send(pkt->buffer,pkt->size)) + { + return false; + } + else + { + return true; + } +} +PCAPAdapter::~PCAPAdapter() +{ + pcap_io_close(); +} diff --git a/plugins/spu2-x/src/Dma.cpp b/plugins/spu2-x/src/Dma.cpp index 141c41e9c6..766816c5f1 100644 --- a/plugins/spu2-x/src/Dma.cpp +++ b/plugins/spu2-x/src/Dma.cpp @@ -197,10 +197,11 @@ void V_Core::PlainDMAWrite(u16 *pMem, u32 size) // but it could be indicative of an emulation foopah elsewhere. if(MsgToConsole()) { - if((uptr)pMem & 15) + // Don't need this anymore. Target may still be good to know though. + /*if((uptr)pMem & 15) { ConLog("* SPU2 DMA Write > Misaligned source. Core: %d IOP: %p TSA: 0x%x Size: 0x%x\n", Index, (void*)pMem, TSA, size); - } + }*/ if(TSA & 7) { diff --git a/plugins/spu2-x/src/Windows/Spu2-X_vs11.vcxproj b/plugins/spu2-x/src/Windows/Spu2-X_vs11.vcxproj index 6b9085852f..d4808abcd2 100644 --- a/plugins/spu2-x/src/Windows/Spu2-X_vs11.vcxproj +++ b/plugins/spu2-x/src/Windows/Spu2-X_vs11.vcxproj @@ -462,47 +462,47 @@ - + {0a18a071-125e-442f-aff7-a3f68abecf99} false - + {e9b51944-7e6d-4bcd-83f2-7bbd5a46182d} false - + {26511268-2902-4997-8421-ecd7055f9e28} false - + {7e9b2be7-cec3-4f14-847b-0ab8d562fb86} false - + {0e231fb1-f3c9-4724-accb-de8bcb3c089e} false - + {48ad7e0a-25b1-4974-a1e3-03f8c438d34f} false - + {c34487af-228a-4d11-8e50-27803df76873} false - + {0318ba30-ef48-441a-9e10-dc85efae39f0} false - + {2f6c0388-20cb-4242-9f6c-a6ebb6a83f47} false - + {4639972e-424e-4e13-8b07-ca403c481346} false - + {a51123f5-9505-4eae-85e7-d320290a272c} false diff --git a/plugins/zerogs/dx/Windows/zerogs_vs11.vcxproj b/plugins/zerogs/dx/Windows/zerogs_vs11.vcxproj index 90b731ef93..2ea7f8a781 100644 --- a/plugins/zerogs/dx/Windows/zerogs_vs11.vcxproj +++ b/plugins/zerogs/dx/Windows/zerogs_vs11.vcxproj @@ -196,7 +196,7 @@ - + {2f6c0388-20cb-4242-9f6c-a6ebb6a83f47} true false diff --git a/plugins/zzogl-pg-cg/opengl/Win32/zerogsogl-cg_vs11.vcxproj b/plugins/zzogl-pg-cg/opengl/Win32/zerogsogl-cg_vs11.vcxproj index 43dacdf0ee..81ad89f66c 100644 --- a/plugins/zzogl-pg-cg/opengl/Win32/zerogsogl-cg_vs11.vcxproj +++ b/plugins/zzogl-pg-cg/opengl/Win32/zerogsogl-cg_vs11.vcxproj @@ -223,7 +223,7 @@ - + {bc236261-77e8-4567-8d09-45cd02965eb6} true false @@ -231,7 +231,7 @@ true false - + {26511268-2902-4997-8421-ecd7055f9e28} true false @@ -239,7 +239,7 @@ true false - + {7e9b2be7-cec3-4f14-847b-0ab8d562fb86} true false @@ -247,7 +247,7 @@ true false - + {48ad7e0a-25b1-4974-a1e3-03f8c438d34f} true false @@ -255,7 +255,7 @@ true false - + {0318ba30-ef48-441a-9e10-dc85efae39f0} true false @@ -263,7 +263,7 @@ true false - + {2f6c0388-20cb-4242-9f6c-a6ebb6a83f47} true false @@ -271,7 +271,7 @@ true false - + {4639972e-424e-4e13-8b07-ca403c481346} true false diff --git a/plugins/zzogl-pg/opengl/Mem.cpp b/plugins/zzogl-pg/opengl/Mem.cpp index e4895957f5..d337b4bcf2 100644 --- a/plugins/zzogl-pg/opengl/Mem.cpp +++ b/plugins/zzogl-pg/opengl/Mem.cpp @@ -249,12 +249,9 @@ void TransferLocalHost24Z(void* pbyMem, u32 nQWordSize) {FUNCLOG} void TransferLocalHost16Z(void* pbyMem, u32 nQWordSize) {FUNCLOG} void TransferLocalHost16SZ(void* pbyMem, u32 nQWordSize) {FUNCLOG} -void fill_block(BLOCK b, vector& vBlockData, vector& vBilinearData, int floatfmt) +void fill_block(BLOCK b, vector& vBlockData, vector& vBilinearData) { float* psrcf = (float*)&vBlockData[0] + b.ox + b.oy * BLOCK_TEXWIDTH; - u16* psrcw = NULL; - if (!floatfmt) - psrcw = (u16*)&vBlockData[0] + b.ox + b.oy * BLOCK_TEXWIDTH; for(int i = 0; i < b.height; ++i) { @@ -266,43 +263,33 @@ void fill_block(BLOCK b, vector& vBlockData, vector& vBilinearData, u32 ct = b.columnTable[(i%b.colheight)*b.colwidth + (j%b.colwidth)]; u32 u = bt * 64 * b.mult + ct; b.pageTable[i * b.width + j] = u; - if (floatfmt) - psrcf[i_width + j] = (float)(u) / (float)(GPU_TEXWIDTH * b.mult); - else - psrcw[i_width + j] = u; - + psrcf[i_width + j] = (float)(u) / (float)(GPU_TEXWIDTH * b.mult); } } - if (floatfmt) { - float4* psrcv = (float4*)&vBilinearData[0] + b.ox + b.oy * BLOCK_TEXWIDTH; + float4* psrcv = (float4*)&vBilinearData[0] + b.ox + b.oy * BLOCK_TEXWIDTH; - for(int i = 0; i < b.height; ++i) - { - u32 i_width = i*BLOCK_TEXWIDTH; - u32 i_width2 = ((i+1)%b.height)*BLOCK_TEXWIDTH; - for(int j = 0; j < b.width; ++j) - { - u32 temp = ((j + 1) % b.width); - float4* pv = &psrcv[i_width + j]; - pv->x = psrcf[i_width + j]; - pv->y = psrcf[i_width + temp]; - pv->z = psrcf[i_width2 + j]; - pv->w = psrcf[i_width2 + temp]; - } - } - } + for(int i = 0; i < b.height; ++i) + { + u32 i_width = i*BLOCK_TEXWIDTH; + u32 i_width2 = ((i+1)%b.height)*BLOCK_TEXWIDTH; + for(int j = 0; j < b.width; ++j) + { + u32 temp = ((j + 1) % b.width); + float4* pv = &psrcv[i_width + j]; + pv->x = psrcf[i_width + j]; + pv->y = psrcf[i_width + temp]; + pv->z = psrcf[i_width2 + j]; + pv->w = psrcf[i_width2 + temp]; + } + } } -void BLOCK::FillBlocks(vector& vBlockData, vector& vBilinearData, int floatfmt) +void BLOCK::FillBlocks(vector& vBlockData, vector& vBilinearData) { FUNCLOG - if (floatfmt) { - vBlockData.resize(BLOCK_TEXWIDTH * BLOCK_TEXHEIGHT * 4); - vBilinearData.resize(BLOCK_TEXWIDTH * BLOCK_TEXHEIGHT * sizeof(float4)); - } else { - vBlockData.resize(BLOCK_TEXWIDTH * BLOCK_TEXHEIGHT * 2); - } + vBlockData.resize(BLOCK_TEXWIDTH * BLOCK_TEXHEIGHT * 4); + vBilinearData.resize(BLOCK_TEXWIDTH * BLOCK_TEXHEIGHT * sizeof(float4)); BLOCK b; @@ -311,7 +298,7 @@ void BLOCK::FillBlocks(vector& vBlockData, vector& vBilinearData, in // 32 b.SetDim(64, 32, 0, 0, 1); b.SetTable(PSMCT32); - fill_block(b, vBlockData, vBilinearData, floatfmt); + fill_block(b, vBlockData, vBilinearData); m_Blocks[PSMCT32] = b; m_Blocks[PSMCT32].SetFun(PSMCT32); @@ -332,7 +319,7 @@ void BLOCK::FillBlocks(vector& vBlockData, vector& vBilinearData, in // 32z b.SetDim(64, 32, 64, 0, 1); b.SetTable(PSMT32Z); - fill_block(b, vBlockData, vBilinearData, floatfmt); + fill_block(b, vBlockData, vBilinearData); m_Blocks[PSMT32Z] = b; m_Blocks[PSMT32Z].SetFun(PSMT32Z); @@ -343,42 +330,42 @@ void BLOCK::FillBlocks(vector& vBlockData, vector& vBilinearData, in // 16 b.SetDim(64, 64, 0, 32, 2); b.SetTable(PSMCT16); - fill_block(b, vBlockData, vBilinearData, floatfmt); + fill_block(b, vBlockData, vBilinearData); m_Blocks[PSMCT16] = b; m_Blocks[PSMCT16].SetFun(PSMCT16); // 16s b.SetDim(64, 64, 64, 32, 2); b.SetTable(PSMCT16S); - fill_block(b, vBlockData, vBilinearData, floatfmt); + fill_block(b, vBlockData, vBilinearData); m_Blocks[PSMCT16S] = b; m_Blocks[PSMCT16S].SetFun(PSMCT16S); // 16z b.SetDim(64, 64, 0, 96, 2); b.SetTable(PSMT16Z); - fill_block(b, vBlockData, vBilinearData, floatfmt); + fill_block(b, vBlockData, vBilinearData); m_Blocks[PSMT16Z] = b; m_Blocks[PSMT16Z].SetFun(PSMT16Z); // 16sz b.SetDim(64, 64, 64, 96, 2); b.SetTable(PSMT16SZ); - fill_block(b, vBlockData, vBilinearData, floatfmt); + fill_block(b, vBlockData, vBilinearData); m_Blocks[PSMT16SZ] = b; m_Blocks[PSMT16SZ].SetFun(PSMT16SZ); // 8 b.SetDim(128, 64, 0, 160, 4); b.SetTable(PSMT8); - fill_block(b, vBlockData, vBilinearData, floatfmt); + fill_block(b, vBlockData, vBilinearData); m_Blocks[PSMT8] = b; m_Blocks[PSMT8].SetFun(PSMT8); // 4 b.SetDim(128, 128, 0, 224, 8); b.SetTable(PSMT4); - fill_block(b, vBlockData, vBilinearData, floatfmt); + fill_block(b, vBlockData, vBilinearData); m_Blocks[PSMT4] = b; m_Blocks[PSMT4].SetFun(PSMT4); } diff --git a/plugins/zzogl-pg/opengl/Mem.h b/plugins/zzogl-pg/opengl/Mem.h index ad8986c39e..f92a1a16e6 100644 --- a/plugins/zzogl-pg/opengl/Mem.h +++ b/plugins/zzogl-pg/opengl/Mem.h @@ -150,7 +150,7 @@ struct BLOCK _TransferLocalHost TransferLocalHost; // texture must be of dims BLOCK_TEXWIDTH and BLOCK_TEXHEIGHT - static void FillBlocks(std::vector& vBlockData, std::vector& vBilinearData, int floatfmt); + static void FillBlocks(std::vector& vBlockData, std::vector& vBilinearData); void SetDim(u32 bw, u32 bh, u32 ox2, u32 oy2, u32 mult2) { diff --git a/plugins/zzogl-pg/opengl/Win32/zerogsogl_vs11.vcxproj b/plugins/zzogl-pg/opengl/Win32/zerogsogl_vs11.vcxproj index c2eada6488..8b347299c6 100644 --- a/plugins/zzogl-pg/opengl/Win32/zerogsogl_vs11.vcxproj +++ b/plugins/zzogl-pg/opengl/Win32/zerogsogl_vs11.vcxproj @@ -231,7 +231,7 @@ - + {bc236261-77e8-4567-8d09-45cd02965eb6} true false @@ -239,7 +239,7 @@ true false - + {26511268-2902-4997-8421-ecd7055f9e28} true false @@ -247,7 +247,7 @@ true false - + {7e9b2be7-cec3-4f14-847b-0ab8d562fb86} true false @@ -255,7 +255,7 @@ true false - + {48ad7e0a-25b1-4974-a1e3-03f8c438d34f} true false @@ -263,7 +263,7 @@ true false - + {0318ba30-ef48-441a-9e10-dc85efae39f0} true false @@ -271,7 +271,7 @@ true false - + {2f6c0388-20cb-4242-9f6c-a6ebb6a83f47} true false @@ -279,7 +279,7 @@ true false - + {4639972e-424e-4e13-8b07-ca403c481346} true false diff --git a/plugins/zzogl-pg/opengl/ZZGl.h b/plugins/zzogl-pg/opengl/ZZGl.h index 5814e89368..fd4f3b8467 100644 --- a/plugins/zzogl-pg/opengl/ZZGl.h +++ b/plugins/zzogl-pg/opengl/ZZGl.h @@ -95,9 +95,6 @@ static __forceinline void SET_STREAM() #endif } -// global alpha blending settings -extern GLenum g_internalRGBAFloat16Fmt; - //static __forceinline void SAFE_RELEASE_TEX(u32& x) //{ // if (x != 0) @@ -148,7 +145,6 @@ extern PFNGLFRAMEBUFFERTEXTURE2DEXTPROC glFramebufferTexture2DEXT; extern PFNGLFRAMEBUFFERTEXTURE3DEXTPROC glFramebufferTexture3DEXT; extern PFNGLFRAMEBUFFERRENDERBUFFEREXTPROC glFramebufferRenderbufferEXT; extern PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVEXTPROC glGetFramebufferAttachmentParameterivEXT; -extern PFNGLGENERATEMIPMAPEXTPROC glGenerateMipmapEXT; extern PFNGLDRAWBUFFERSPROC glDrawBuffers; #ifdef GLSL4_API diff --git a/plugins/zzogl-pg/opengl/ZZoglCreate.cpp b/plugins/zzogl-pg/opengl/ZZoglCreate.cpp index caa46e8f11..ea17bf8c1f 100644 --- a/plugins/zzogl-pg/opengl/ZZoglCreate.cpp +++ b/plugins/zzogl-pg/opengl/ZZoglCreate.cpp @@ -96,10 +96,6 @@ GLenum s_srcrgb, s_dstrgb, s_srcalpha, s_dstalpha; // set by zgsBlendFuncSeparat u32 s_stencilfunc, s_stencilref, s_stencilmask; GLenum s_drawbuffers[] = { GL_COLOR_ATTACHMENT0_EXT, GL_COLOR_ATTACHMENT1_EXT }; -GLenum g_internalFloatFmt = GL_ALPHA_FLOAT32_ATI; -GLenum g_internalRGBAFloatFmt = GL_RGBA_FLOAT32_ATI; -GLenum g_internalRGBAFloat16Fmt = GL_RGBA_FLOAT16_ATI; - u32 ptexLogo = 0; int nLogoWidth, nLogoHeight; u32 s_ptexInterlace = 0; // holds interlace fields @@ -136,35 +132,55 @@ bool IsGLExt(const char* szTargetExtension) return mapGLExtensions.find(string(szTargetExtension)) != mapGLExtensions.end(); } +inline bool check_gl_version(uint32 major, uint32 minor) { + const GLubyte* s; + s = glGetString(GL_VERSION); + if (s == NULL) return false; + ZZLog::Error_Log("Supported Opengl version: %s on GPU: %s. Vendor: %s\n", s, glGetString(GL_RENDERER), glGetString(GL_VENDOR)); + // Could be useful to detect the GPU vendor: + // if ( strcmp((const char*)glGetString(GL_VENDOR), "ATI Technologies Inc.") == 0 ) + + GLuint dot = 0; + while (s[dot] != '\0' && s[dot] != '.') dot++; + if (dot == 0) return false; + + GLuint major_gl = s[dot-1]-'0'; + GLuint minor_gl = s[dot+1]-'0'; + + if ( (major_gl < major) || ( major_gl == major && minor_gl < minor ) ) { + ZZLog::Error_Log("OPENGL %d.%d is not supported\n", major, minor); + return false; + } + + return true; +} + // Function asks about different OGL extensions, that are required to setup accordingly. Return false if checks failed inline bool CreateImportantCheck() { bool bSuccess = true; + #ifndef _WIN32 int const glew_ok = glewInit(); if (glew_ok != GLEW_OK) { ZZLog::Error_Log("glewInit() is not ok!"); - bSuccess = false; - } else { - const GLubyte* gl_version = glGetString(GL_VERSION); - ZZLog::Error_Log("Supported Opengl version : %s\n", gl_version); + // Better exit now, any openGL call will segfault. + return false; } - #endif + // Require a minimum of openGL2.0 (first version that support hardware shader) + bSuccess &= check_gl_version(2, 0); + + // GL_EXT_framebuffer_object -> GL3.0 + // Opensource driver -> Intel OK. Radeon need EXT_packed_depth_stencil if (!IsGLExt("GL_EXT_framebuffer_object")) { ZZLog::Error_Log("*********\nZZogl: ERROR: Need GL_EXT_framebuffer_object for multiple render targets\nZZogl: *********"); bSuccess = false; } - if (!IsGLExt("GL_EXT_secondary_color")) - { - ZZLog::Error_Log("*********\nZZogl: OGL WARNING: Need GL_EXT_secondary_color\nZZogl: *********"); - bSuccess = false; - } - bSuccess &= ZZshCheckProfilesSupport(); return bSuccess; @@ -173,39 +189,21 @@ inline bool CreateImportantCheck() // This is a check for less important open gl extensions. inline void CreateOtherCheck() { - if (!IsGLExt("GL_EXT_blend_equation_separate") || glBlendEquationSeparateEXT == NULL) - { - ZZLog::Error_Log("*********\nZZogl: OGL WARNING: Need GL_EXT_blend_equation_separate\nZZogl: *********"); - zgsBlendEquationSeparateEXT = glBlendEquationSeparateDummy; - } - else - zgsBlendEquationSeparateEXT = glBlendEquationSeparateEXT; + // GL_EXT_blend_equation_separate -> GL2.0 + // Opensource driver -> Intel OK. Radeon OK. + zgsBlendEquationSeparateEXT = glBlendEquationSeparateEXT; - if (!IsGLExt("GL_EXT_blend_func_separate") || glBlendFuncSeparateEXT == NULL) - { - ZZLog::Error_Log("*********\nZZogl: OGL WARNING: Need GL_EXT_blend_func_separate\nZZogl: *********"); - zgsBlendFuncSeparateEXT = glBlendFuncSeparateDummy; - } - else - zgsBlendFuncSeparateEXT = glBlendFuncSeparateEXT; + // GL_EXT_blend_func_separate -> GL1.4 + // Opensource driver -> Intel OK. Radeon OK. + zgsBlendFuncSeparateEXT = glBlendFuncSeparateEXT; - if (!IsGLExt("GL_ARB_draw_buffers") && !IsGLExt("GL_ATI_draw_buffers")) - { - ZZLog::Error_Log("*********\nZZogl: OGL WARNING: multiple render targets not supported, some effects might look bad\nZZogl: *********"); + // GL_ARB_draw_buffers -> GL2.0 + // Opensource driver -> Intel (need gen4). Radeon OK. + if (glDrawBuffers == NULL) { + ZZLog::Error_Log("*********\nZZogl: OGL ERROR: multiple render targets not supported, some effects might look bad\nZZogl: *********"); conf.mrtdepth = 0; } - if (IsGLExt("GL_ARB_draw_buffers")) - glDrawBuffers = (PFNGLDRAWBUFFERSPROC)GLWin.GetProcAddress("glDrawBuffers"); - else if (IsGLExt("GL_ATI_draw_buffers")) - glDrawBuffers = (PFNGLDRAWBUFFERSPROC)GLWin.GetProcAddress("glDrawBuffersATI"); - - - if (!IsGLExt("GL_ARB_multitexture")) - ZZLog::Error_Log("No multitexturing."); - else - ZZLog::Error_Log("Using multitexturing."); - GLint Max_Texture_Size_NV = 0; GLint Max_Texture_Size_2d = 0; @@ -396,6 +394,8 @@ inline bool CreateFillExtensionsMap() void LoadglFunctions() { + // GL_EXT_framebuffer_object + // CORE -> 3.0 and replaced by GL_ARB_framebuffer_object GL_LOADFN(glIsRenderbufferEXT); GL_LOADFN(glBindRenderbufferEXT); GL_LOADFN(glDeleteRenderbuffersEXT); @@ -412,23 +412,21 @@ void LoadglFunctions() GL_LOADFN(glFramebufferTexture3DEXT); GL_LOADFN(glFramebufferRenderbufferEXT); GL_LOADFN(glGetFramebufferAttachmentParameterivEXT); - GL_LOADFN(glGenerateMipmapEXT); + + // CORE -> 2.0 + GL_LOADFN(glDrawBuffers); } inline bool TryBlockFormat(GLint fmt, const GLvoid* vBlockData) { - g_internalFloatFmt = fmt; - glTexImage2D(GL_TEXTURE_2D, 0, g_internalFloatFmt, BLOCK_TEXWIDTH, BLOCK_TEXHEIGHT, 0, GL_ALPHA, GL_FLOAT, vBlockData); + glTexImage2D(GL_TEXTURE_2D, 0, fmt, BLOCK_TEXWIDTH, BLOCK_TEXHEIGHT, 0, GL_ALPHA, GL_FLOAT, vBlockData); return (glGetError() == GL_NO_ERROR); } -inline bool TryBlinearFormat(GLint fmt32, GLint fmt16, const GLvoid* vBilinearData) { - g_internalRGBAFloatFmt = fmt32; - g_internalRGBAFloat16Fmt = fmt16; - glTexImage2D(GL_TEXTURE_2D, 0, g_internalRGBAFloatFmt, BLOCK_TEXWIDTH, BLOCK_TEXHEIGHT, 0, GL_RGBA, GL_FLOAT, vBilinearData); +inline bool TryBlinearFormat(GLint fmt32, const GLvoid* vBilinearData) { + glTexImage2D(GL_TEXTURE_2D, 0, fmt32, BLOCK_TEXWIDTH, BLOCK_TEXHEIGHT, 0, GL_RGBA, GL_FLOAT, vBilinearData); return (glGetError() == GL_NO_ERROR); } - bool ZZCreate(int _width, int _height) { GLenum err = GL_NO_ERROR; @@ -584,7 +582,6 @@ bool ZZCreate(int _width, int _height) // create the blocks texture g_fBlockMult = 1; - bool do_not_use_billinear = false; #ifndef ZZNORMAL_MEMORY FillAlowedPsnTable(); @@ -592,58 +589,54 @@ bool ZZCreate(int _width, int _height) #endif vector vBlockData, vBilinearData; - BLOCK::FillBlocks(vBlockData, vBilinearData, 1); + BLOCK::FillBlocks(vBlockData, vBilinearData); glGenTextures(1, &ptexBlocks); glBindTexture(GL_TEXTURE_2D, ptexBlocks); + // Opensource driver -> Intel (need gen4) (enabled by default on mesa 9). Radeon depends on the HW capability +#ifdef GLSL4_API + // texture float -> GL3.0 + glTexImage2D(GL_TEXTURE_2D, 0, GL_R32F, BLOCK_TEXWIDTH, BLOCK_TEXHEIGHT, 0, GL_RED, GL_FLOAT, &vBlockData[0]); + if (glGetError() != GL_NO_ERROR) { + ZZLog::Error_Log("ZZogl ERROR: could not fill blocks"); + return false; + } +#else if (TryBlockFormat(GL_RGBA32F, &vBlockData[0])) ZZLog::Error_Log("Use GL_RGBA32F for blockdata."); else if (TryBlockFormat(GL_ALPHA_FLOAT32_ATI, &vBlockData[0])) ZZLog::Error_Log("Use ATI_texture_float for blockdata."); - else if (TryBlockFormat(GL_ALPHA32F_ARB, &vBlockData[0])) - ZZLog::Error_Log("Use ARB_texture_float for blockdata."); - else - { // This case is bad. But for really old cards it could be nice. - g_fBlockMult = 65535.0f*(float)g_fiGPU_TEXWIDTH; - BLOCK::FillBlocks(vBlockData, vBilinearData, 0); - g_internalFloatFmt = GL_ALPHA16; - - // We store block data on u16 rather float numbers. It's not so preciese, but ALPHA16 is OpenGL 2.0 standart - // and use only 16 bit. Old zerogs use red channel, but it does not work. - - glTexImage2D(GL_TEXTURE_2D, 0, g_internalFloatFmt, BLOCK_TEXWIDTH, BLOCK_TEXHEIGHT, 0, GL_ALPHA, GL_UNSIGNED_SHORT, &vBlockData[0]); - if( glGetError() != GL_NO_ERROR ) { - ZZLog::Error_Log("ZZogl ERROR: could not fill blocks"); - return false; - } - - do_not_use_billinear = true; - conf.bilinear = 0; - ZZLog::Error_Log("Using non-bilinear fill, quallity is outdated!"); + else { + ZZLog::Error_Log("ZZogl ERROR: float texture not supported. If you use opensource driver (aka Mesa), you probably need to compile it with texture float support."); + ZZLog::Error_Log("ZZogl ERROR: Otherwise you probably have a very very old GPU, either use an older version of the plugin or upgrade your computer"); + return false; } +#endif setTex2DFilters(GL_NEAREST); setTex2DWrap(GL_REPEAT); - if (!do_not_use_billinear) - { - // fill in the bilinear blocks (main variant). - glGenTextures(1, &ptexBilinearBlocks); - glBindTexture(GL_TEXTURE_2D, ptexBilinearBlocks); - - if (TryBlinearFormat(GL_RGBA32F, GL_RGBA16F, &vBilinearData[0])) - ZZLog::Error_Log("Fill bilinear blocks OK.!"); - else if (TryBlinearFormat(GL_RGBA_FLOAT32_ATI, GL_RGBA_FLOAT16_ATI, &vBilinearData[0])) - ZZLog::Error_Log("Fill bilinear blocks with ATI_texture_float."); - else if (TryBlinearFormat(GL_FLOAT_RGBA32_NV, GL_FLOAT_RGBA16_NV, &vBilinearData[0])) - ZZLog::Error_Log("ZZogl Fill bilinear blocks with NVidia_float."); - else - ZZLog::Error_Log("Fill bilinear blocks failed."); + // fill in the bilinear blocks (main variant). + glGenTextures(1, &ptexBilinearBlocks); + glBindTexture(GL_TEXTURE_2D, ptexBilinearBlocks); - setTex2DFilters(GL_NEAREST); - setTex2DWrap(GL_REPEAT); - } +#ifdef GLSL4_API + if (!TryBlinearFormat(GL_RGBA32F, &vBilinearData[0])) + ZZLog::Error_Log("Fill bilinear blocks failed."); +#else + if (TryBlinearFormat(GL_RGBA32F, &vBilinearData[0])) + ZZLog::Error_Log("Fill bilinear blocks OK.!"); + else if (TryBlinearFormat(GL_RGBA_FLOAT32_ATI, &vBilinearData[0])) + ZZLog::Error_Log("Fill bilinear blocks with ATI_texture_float."); + else if (TryBlinearFormat(GL_FLOAT_RGBA32_NV, &vBilinearData[0])) + ZZLog::Error_Log("ZZogl Fill bilinear blocks with NVidia_float."); + else + ZZLog::Error_Log("Fill bilinear blocks failed."); +#endif + + setTex2DFilters(GL_NEAREST); + setTex2DWrap(GL_REPEAT); float fpri = 1; @@ -688,11 +681,6 @@ bool ZZCreate(int _width, int _height) GL_REPORT_ERROR(); #endif - // some cards don't support this -// glClientActiveTexture(GL_TEXTURE0); -// glEnableClientState(GL_TEXTURE_COORD_ARRAY); -// glTexCoordPointer(4, GL_UNSIGNED_BYTE, sizeof(VertexGPU), (void*)12); - // create the conversion textures glGenTextures(1, &ptexConv16to32); glBindTexture(GL_TEXTURE_2D, ptexConv16to32); @@ -746,6 +734,7 @@ bool ZZCreate(int _width, int _height) GL_REPORT_ERROR(); + if (err != GL_NO_ERROR) bSuccess = false; glDisable(GL_STENCIL_TEST); @@ -773,10 +762,6 @@ bool ZZCreate(int _width, int _height) g_vsprog = g_psprog = sZero; -#ifdef OGL4_LOG - glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB); -#endif - if (glGetError() == GL_NO_ERROR) { return bSuccess; diff --git a/plugins/zzogl-pg/opengl/ZZoglMem.cpp b/plugins/zzogl-pg/opengl/ZZoglMem.cpp index 1a593ef645..90bd49fc81 100644 --- a/plugins/zzogl-pg/opengl/ZZoglMem.cpp +++ b/plugins/zzogl-pg/opengl/ZZoglMem.cpp @@ -428,7 +428,7 @@ void TransferLocalHost24Z(void* pbyMem, u32 nQWordSize) { FUNCLOG } void TransferLocalHost16Z(void* pbyMem, u32 nQWordSize) { FUNCLOG } void TransferLocalHost16SZ(void* pbyMem, u32 nQWordSize) { FUNCLOG } -inline void FILL_BLOCK(BLOCK& b, int floatfmt, vector& vBlockData, vector& vBilinearData, int ox, int oy, int psmX) { +inline void FILL_BLOCK(BLOCK& b, vector& vBlockData, vector& vBilinearData, int ox, int oy, int psmX) { int bw = ZZ_DT[psmX][4] + 1; int bh = ZZ_DT[psmX][3] + 1; int mult = 1 << ZZ_DT[psmX][0]; @@ -448,36 +448,28 @@ inline void FILL_BLOCK(BLOCK& b, int floatfmt, vector& vBlockData, vector< // This is never true. //assert( sizeof(g_pageTable[psmX]) == bw*bh*sizeof(g_pageTable[psmX][0][0]) ); float* psrcf = (float*)&vBlockData[0] + ox + oy * BLOCK_TEXWIDTH; - u16* psrcw = (u16*)&vBlockData[0] + ox + oy * BLOCK_TEXWIDTH; for(int i = 0; i < bh; ++i) { for(int j = 0; j < bw; ++j) { /* fill the table */ u32 u = g_blockTable[psmX][(i / b.colheight)][(j / b.colwidth)] * 64 * mult + g_columnTable[psmX][i%b.colheight][j%b.colwidth]; b.pageTable[i][j] = u; - if( floatfmt ) { - psrcf[i*BLOCK_TEXWIDTH+j] = (float)(u) / (float)(GPU_TEXWIDTH*mult); - } - else { - psrcw[i*BLOCK_TEXWIDTH+j] = u; - } + psrcf[i*BLOCK_TEXWIDTH+j] = (float)(u) / (float)(GPU_TEXWIDTH*mult); } } - if( floatfmt ) { - float4* psrcv = (float4*)&vBilinearData[0] + ox + oy * BLOCK_TEXWIDTH; - for(int i = 0; i < bh; ++i) { - for(int j = 0; j < bw; ++j) { - float4* pv = &psrcv[i*BLOCK_TEXWIDTH+j]; - pv->x = psrcf[i*BLOCK_TEXWIDTH+j]; - pv->y = psrcf[i*BLOCK_TEXWIDTH+((j+1)%bw)]; - pv->z = psrcf[((i+1)%bh)*BLOCK_TEXWIDTH+j]; - pv->w = psrcf[((i+1)%bh)*BLOCK_TEXWIDTH+((j+1)%bw)]; - } + float4* psrcv = (float4*)&vBilinearData[0] + ox + oy * BLOCK_TEXWIDTH; + for(int i = 0; i < bh; ++i) { + for(int j = 0; j < bw; ++j) { + float4* pv = &psrcv[i*BLOCK_TEXWIDTH+j]; + pv->x = psrcf[i*BLOCK_TEXWIDTH+j]; + pv->y = psrcf[i*BLOCK_TEXWIDTH+((j+1)%bw)]; + pv->z = psrcf[((i+1)%bh)*BLOCK_TEXWIDTH+j]; + pv->w = psrcf[((i+1)%bh)*BLOCK_TEXWIDTH+((j+1)%bw)]; } } } -void BLOCK::FillBlocks(vector& vBlockData, vector& vBilinearData, int floatfmt) +void BLOCK::FillBlocks(vector& vBlockData, vector& vBilinearData) { FUNCLOG vBlockData.resize(BLOCK_TEXWIDTH * BLOCK_TEXHEIGHT * (floatfmt ? 4 : 2)); @@ -490,7 +482,7 @@ void BLOCK::FillBlocks(vector& vBlockData, vector& vBilinearData, in memset(m_Blocks, 0, sizeof(m_Blocks)); // 32 - FILL_BLOCK(b, floatfmt, vBlockData, vBilinearData, 0, 0, PSMCT32); + FILL_BLOCK(b, vBlockData, vBilinearData, 0, 0, PSMCT32); b.TransferHostLocal = TransferHostLocal32; b.TransferLocalHost = TransferLocalHost32; m_Blocks[PSMCT32] = b; @@ -514,7 +506,7 @@ void BLOCK::FillBlocks(vector& vBlockData, vector& vBilinearData, in m_Blocks[PSMT4HH] = b; // 32z - FILL_BLOCK(b, floatfmt, vBlockData, vBilinearData, 64, 0, PSMT32Z); + FILL_BLOCK(b, vBlockData, vBilinearData, 64, 0, PSMT32Z); b.TransferHostLocal = TransferHostLocal32Z; b.TransferLocalHost = TransferLocalHost32Z; m_Blocks[PSMT32Z] = b; @@ -525,37 +517,37 @@ void BLOCK::FillBlocks(vector& vBlockData, vector& vBilinearData, in m_Blocks[PSMT24Z] = b; // 16 - FILL_BLOCK(b, floatfmt, vBlockData, vBilinearData, 0, 32, PSMCT16); + FILL_BLOCK(b, vBlockData, vBilinearData, 0, 32, PSMCT16); b.TransferHostLocal = TransferHostLocal16; b.TransferLocalHost = TransferLocalHost16; m_Blocks[PSMCT16] = b; // 16s - FILL_BLOCK(b, floatfmt, vBlockData, vBilinearData, 64, 32, PSMCT16S); + FILL_BLOCK(b, vBlockData, vBilinearData, 64, 32, PSMCT16S); b.TransferHostLocal = TransferHostLocal16S; b.TransferLocalHost = TransferLocalHost16S; m_Blocks[PSMCT16S] = b; // 16z - FILL_BLOCK(b, floatfmt, vBlockData, vBilinearData, 0, 96, PSMT16Z); + FILL_BLOCK(b, vBlockData, vBilinearData, 0, 96, PSMT16Z); b.TransferHostLocal = TransferHostLocal16Z; b.TransferLocalHost = TransferLocalHost16Z; m_Blocks[PSMT16Z] = b; // 16sz - FILL_BLOCK(b, floatfmt, vBlockData, vBilinearData, 64, 96, PSMT16SZ); + FILL_BLOCK(b, vBlockData, vBilinearData, 64, 96, PSMT16SZ); b.TransferHostLocal = TransferHostLocal16SZ; b.TransferLocalHost = TransferLocalHost16SZ; m_Blocks[PSMT16SZ] = b; // 8 - FILL_BLOCK(b, floatfmt, vBlockData, vBilinearData, 0, 160, PSMT8); + FILL_BLOCK(b, vBlockData, vBilinearData, 0, 160, PSMT8); b.TransferHostLocal = TransferHostLocal8; b.TransferLocalHost = TransferLocalHost8; m_Blocks[PSMT8] = b; // 4 - FILL_BLOCK(b, floatfmt, vBlockData, vBilinearData, 0, 224, PSMT4); + FILL_BLOCK(b, vBlockData, vBilinearData, 0, 224, PSMT4); b.TransferHostLocal = TransferHostLocal4; b.TransferLocalHost = TransferLocalHost4; m_Blocks[PSMT4] = b; diff --git a/plugins/zzogl-pg/opengl/ZZoglMem.h b/plugins/zzogl-pg/opengl/ZZoglMem.h index 42eaca3c2d..33a8572557 100644 --- a/plugins/zzogl-pg/opengl/ZZoglMem.h +++ b/plugins/zzogl-pg/opengl/ZZoglMem.h @@ -95,7 +95,7 @@ struct BLOCK void (*TransferLocalHost)(void* pbyMem, u32 nQWordSize); // texture must be of dims BLOCK_TEXWIDTH and BLOCK_TEXHEIGHT - static void FillBlocks(std::vector& vBlockData, std::vector& vBilinearData, int floatfmt); + static void FillBlocks(std::vector& vBlockData, std::vector& vBilinearData); }; void FillBlockTables(); diff --git a/plugins/zzogl-pg/opengl/ps2hw.fx b/plugins/zzogl-pg/opengl/ps2hw.fx index 0965c3adc3..9eb7111275 100644 --- a/plugins/zzogl-pg/opengl/ps2hw.fx +++ b/plugins/zzogl-pg/opengl/ps2hw.fx @@ -96,7 +96,7 @@ float2 ps2memcoord(float2 realtex) off.xy = realtex.xy-fblock.xy; #ifdef ACCURATE_DECOMPRESSION - off.zw = tex2D(g_sBlocks, g_fTexBlock.xy*fblock + g_fTexBlock.zw).ar; + off.z = tex2D(g_sBlocks, g_fTexBlock.xy*fblock + g_fTexBlock.zw).a; off.x = dot(off.xy, g_fTexOffset.xy); float r = g_fTexOffset.w; float f = frac(off.x); diff --git a/plugins/zzogl-pg/opengl/ps2hw_gl4.glsl b/plugins/zzogl-pg/opengl/ps2hw_gl4.glsl index f69dea94dd..8227dae51e 100644 --- a/plugins/zzogl-pg/opengl/ps2hw_gl4.glsl +++ b/plugins/zzogl-pg/opengl/ps2hw_gl4.glsl @@ -193,7 +193,7 @@ float2 ps2memcoord(float2 realtex) off.xy = realtex.xy-fblock.xy; #ifdef ACCURATE_DECOMPRESSION - off.zw = texture(g_sBlocks, g_fTexBlock.xy*fblock + g_fTexBlock.zw).ar; + off.z = texture(g_sBlocks, g_fTexBlock.xy*fblock + g_fTexBlock.zw).r; off.x = dot(off.xy, g_fTexOffset.xy); float r = g_fTexOffset.w; float f = fract(off.x); @@ -202,7 +202,7 @@ float2 ps2memcoord(float2 realtex) off.x = fract(f + fadd + r); off.w -= off.x ; #else - off.z = texture(g_sBlocks, g_fTexBlock.xy*fblock + g_fTexBlock.zw).a; + off.z = texture(g_sBlocks, g_fTexBlock.xy*fblock + g_fTexBlock.zw).r; // combine the two off.x = dot(off.xyz, g_fTexOffset.xyz)+g_fTexOffset.w; @@ -232,10 +232,10 @@ void ps2memcoord4(float4 orgtex, out float4 off0, out float4 off1) float4 colors;// = texture(g_sBilinearBlocks, ftransblock.xy); // this is faster on ffx ingame - colors.x = texture(g_sBlocks, ftransblock.xy).a; - colors.y = texture(g_sBlocks, ftransblock.zy).a; - colors.z = texture(g_sBlocks, ftransblock.xw).a; - colors.w = texture(g_sBlocks, ftransblock.zw).a; + colors.x = texture(g_sBlocks, ftransblock.xy).r; + colors.y = texture(g_sBlocks, ftransblock.zy).r; + colors.z = texture(g_sBlocks, ftransblock.xw).r; + colors.w = texture(g_sBlocks, ftransblock.zw).r; float4 fr, rem; diff --git a/plugins/zzogl-pg/opengl/zerogs.h b/plugins/zzogl-pg/opengl/zerogs.h index b898d46829..f95542e9a6 100644 --- a/plugins/zzogl-pg/opengl/zerogs.h +++ b/plugins/zzogl-pg/opengl/zerogs.h @@ -63,7 +63,6 @@ PFNGLFRAMEBUFFERTEXTURE2DEXTPROC glFramebufferTexture2DEXT = NULL; PFNGLFRAMEBUFFERTEXTURE3DEXTPROC glFramebufferTexture3DEXT = NULL; PFNGLFRAMEBUFFERRENDERBUFFEREXTPROC glFramebufferRenderbufferEXT = NULL; PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVEXTPROC glGetFramebufferAttachmentParameterivEXT = NULL; -PFNGLGENERATEMIPMAPEXTPROC glGenerateMipmapEXT = NULL; PFNGLDRAWBUFFERSPROC glDrawBuffers = NULL; #ifndef GL_FRAMEBUFFER_INCOMPLETE_DUPLICATE_ATTACHMENT_EXT