add verification data was entered-lf em 4x05 write
[proxmark3-svn] / common / lfdemod.c
CommitLineData
eb191de6 1//-----------------------------------------------------------------------------
ba1a299c 2// Copyright (C) 2014
eb191de6 3//
4// This code is licensed to you under the terms of the GNU GPL, version 2 or,
5// at your option, any later version. See the LICENSE.txt file for the text of
6// the license.
7//-----------------------------------------------------------------------------
bf74114d 8// Low frequency demod/decode commands - by marshmellow, holiman, iceman and
9// many others who came before
4d3c1796 10//
11// NOTES:
12// LF Demod functions are placed here to allow the flexability to use client or
13// device side. Most BUT NOT ALL of these functions are currenlty safe for
14// device side use currently. (DetectST for example...)
15//
16// There are likely many improvements to the code that could be made, please
17// make suggestions...
18//
bf74114d 19// we tried to include author comments so any questions could be directed to
20// the source.
21//
4d3c1796 22// There are 4 main sections of code below:
23// Utilities Section:
24// for general utilities used by multiple other functions
4d3c1796 25// Clock / Bitrate Detection Section:
26// for clock detection functions for each modulation
d5051b98 27// Modulation Demods &/or Decoding Section:
28// for main general modulation demodulating and encoding decoding code.
4d3c1796 29// Tag format detection section:
30// for detection of specific tag formats within demodulated data
31//
32// marshmellow
eb191de6 33//-----------------------------------------------------------------------------
34
d5051b98 35#include <string.h> // for memset, memcmp and size_t
36#include <stdint.h> // for uint_32+
37#include <stdbool.h> // for bool
f2ea55fb 38#include "parity.h" // for parity test
6fe5c94b 39
d5051b98 40//**********************************************************************************************
41//---------------------------------Utilities Section--------------------------------------------
42//**********************************************************************************************
56de46b4 43#define LOWEST_DEFAULT_CLOCK 32
6f36848f 44#define FSK_PSK_THRESHOLD 123
ec187c2f 45
d1869c33 46//to allow debug print calls when used not on device
6fe5c94b 47void dummy(char *fmt, ...){}
6fe5c94b 48#ifndef ON_DEVICE
49#include "ui.h"
709665b5 50#include "cmdparser.h"
51#include "cmddata.h"
6fe5c94b 52#define prnt PrintAndLog
53#else
709665b5 54 uint8_t g_debugMode=0;
6fe5c94b 55#define prnt dummy
56#endif
6fe5c94b 57
bf74114d 58uint8_t justNoise(uint8_t *BitStream, size_t size) {
a1d17964 59 //test samples are not just noise
60 uint8_t justNoise1 = 1;
61 for(size_t idx=0; idx < size && justNoise1 ;idx++){
6f36848f 62 justNoise1 = BitStream[idx] < FSK_PSK_THRESHOLD;
a1d17964 63 }
64 return justNoise1;
65}
66
1e090a61 67//by marshmellow
872e3d4d 68//get high and low values of a wave with passed in fuzz factor. also return noise test = 1 for passed or 0 for only noise
bf74114d 69int getHiLo(uint8_t *BitStream, size_t size, int *high, int *low, uint8_t fuzzHi, uint8_t fuzzLo) {
1e090a61 70 *high=0;
71 *low=255;
72 // get high and low thresholds
2eec55c8 73 for (size_t i=0; i < size; i++){
1e090a61 74 if (BitStream[i] > *high) *high = BitStream[i];
75 if (BitStream[i] < *low) *low = BitStream[i];
76 }
6f36848f 77 if (*high < FSK_PSK_THRESHOLD) return -1; // just noise
75cbbe9a 78 *high = ((*high-128)*fuzzHi + 12800)/100;
79 *low = ((*low-128)*fuzzLo + 12800)/100;
1e090a61 80 return 1;
81}
82
a1d17964 83// by marshmellow
84// pass bits to be tested in bits, length bits passed in bitLen, and parity type (even=0 | odd=1) in pType
85// returns 1 if passed
f2ea55fb 86bool parityTest(uint32_t bits, uint8_t bitLen, uint8_t pType) {
87 return oddparity32(bits) ^ pType;
a1d17964 88}
89
709665b5 90// by marshmellow
f2ea55fb 91// takes a array of binary values, start position, length of bits per parity (includes parity bit - MAX 32),
92// Parity Type (1 for odd; 0 for even; 2 for Always 1's; 3 for Always 0's), and binary Length (length to run)
bf74114d 93size_t removeParity(uint8_t *BitStream, size_t startIdx, uint8_t pLen, uint8_t pType, size_t bLen) {
709665b5 94 uint32_t parityWd = 0;
f2ea55fb 95 size_t bitCnt = 0;
e39a92bb 96 for (int word = 0; word < (bLen); word+=pLen) {
97 for (int bit=0; bit < pLen; bit++) {
f2ea55fb 98 if (word+bit >= bLen) break;
709665b5 99 parityWd = (parityWd << 1) | BitStream[startIdx+word+bit];
f2ea55fb 100 BitStream[bitCnt++] = (BitStream[startIdx+word+bit]);
709665b5 101 }
e88096ba 102 if (word+pLen > bLen) break;
e39a92bb 103
f2ea55fb 104 bitCnt--; // overwrite parity with next data
709665b5 105 // if parity fails then return 0
88e85bde 106 switch (pType) {
f2ea55fb 107 case 3: if (BitStream[bitCnt]==1) {return 0;} break; //should be 0 spacer bit
108 case 2: if (BitStream[bitCnt]==0) {return 0;} break; //should be 1 spacer bit
29435274 109 default: if (parityTest(parityWd, pLen, pType) == 0) {return 0;} break; //test parity
709665b5 110 }
709665b5 111 parityWd = 0;
112 }
113 // if we got here then all the parities passed
f2ea55fb 114 //return size
709665b5 115 return bitCnt;
116}
117
118// by marshmellow
119// takes a array of binary values, length of bits per parity (includes parity bit),
88e85bde 120// Parity Type (1 for odd; 0 for even; 2 Always 1's; 3 Always 0's), and binary Length (length to run)
121// Make sure *dest is long enough to store original sourceLen + #_of_parities_to_be_added
bf74114d 122size_t addParity(uint8_t *BitSource, uint8_t *dest, uint8_t sourceLen, uint8_t pLen, uint8_t pType) {
709665b5 123 uint32_t parityWd = 0;
124 size_t j = 0, bitCnt = 0;
125 for (int word = 0; word < sourceLen; word+=pLen-1) {
126 for (int bit=0; bit < pLen-1; bit++){
127 parityWd = (parityWd << 1) | BitSource[word+bit];
128 dest[j++] = (BitSource[word+bit]);
129 }
130 // if parity fails then return 0
88e85bde 131 switch (pType) {
132 case 3: dest[j++]=0; break; // marker bit which should be a 0
133 case 2: dest[j++]=1; break; // marker bit which should be a 1
134 default:
135 dest[j++] = parityTest(parityWd, pLen-1, pType) ^ 1;
136 break;
709665b5 137 }
138 bitCnt += pLen;
139 parityWd = 0;
140 }
141 // if we got here then all the parities passed
142 //return ID start index and size
143 return bitCnt;
144}
145
bf74114d 146uint32_t bytebits_to_byte(uint8_t *src, size_t numbits) {
709665b5 147 uint32_t num = 0;
148 for(int i = 0 ; i < numbits ; i++)
149 {
150 num = (num << 1) | (*src);
151 src++;
152 }
153 return num;
154}
155
156//least significant bit first
bf74114d 157uint32_t bytebits_to_byteLSBF(uint8_t *src, size_t numbits) {
709665b5 158 uint32_t num = 0;
159 for(int i = 0 ; i < numbits ; i++)
160 {
161 num = (num << 1) | *(src + (numbits-(i+1)));
162 }
163 return num;
164}
165
e88096ba 166// search for given preamble in given BitStream and return success=1 or fail=0 and startIndex (where it was found) and length if not fineone
167// fineone does not look for a repeating preamble for em4x05/4x69 sends preamble once, so look for it once in the first pLen bits
168bool preambleSearchEx(uint8_t *BitStream, uint8_t *preamble, size_t pLen, size_t *size, size_t *startIdx, bool findone) {
59f726c9 169 // Sanity check. If preamble length is bigger than bitstream length.
e88096ba 170 if ( *size <= pLen ) return false;
59f726c9 171
e88096ba 172 uint8_t foundCnt = 0;
173 for (size_t idx = 0; idx < *size - pLen; idx++) {
174 if (memcmp(BitStream+idx, preamble, pLen) == 0) {
e0165dcf 175 //first index found
176 foundCnt++;
e88096ba 177 if (foundCnt == 1) {
178 if (g_debugMode) prnt("DEBUG: preamble found at %u", idx);
e0165dcf 179 *startIdx = idx;
e88096ba 180 if (findone) return true;
181 } else if (foundCnt == 2) {
e0165dcf 182 *size = idx - *startIdx;
e88096ba 183 return true;
e0165dcf 184 }
185 }
186 }
4c6ccc2b 187 return false;
188}
189
bf74114d 190//by marshmellow
191//search for given preamble in given BitStream and return success=1 or fail=0 and startIndex and length
192uint8_t preambleSearch(uint8_t *BitStream, uint8_t *preamble, size_t pLen, size_t *size, size_t *startIdx) {
193 return (preambleSearchEx(BitStream, preamble, pLen, size, startIdx, false)) ? 1 : 0;
194}
195
34ff8985 196// find start of modulating data (for fsk and psk) in case of beginning noise or slow chip startup.
6f36848f 197size_t findModStart(uint8_t dest[], size_t size, uint8_t expWaveSize) {
34ff8985 198 size_t i = 0;
199 size_t waveSizeCnt = 0;
200 uint8_t thresholdCnt = 0;
6f36848f 201 bool isAboveThreshold = dest[i++] >= FSK_PSK_THRESHOLD;
34ff8985 202 for (; i < size-20; i++ ) {
6f36848f 203 if(dest[i] < FSK_PSK_THRESHOLD && isAboveThreshold) {
34ff8985 204 thresholdCnt++;
205 if (thresholdCnt > 2 && waveSizeCnt < expWaveSize+1) break;
206 isAboveThreshold = false;
207 waveSizeCnt = 0;
6f36848f 208 } else if (dest[i] >= FSK_PSK_THRESHOLD && !isAboveThreshold) {
34ff8985 209 thresholdCnt++;
210 if (thresholdCnt > 2 && waveSizeCnt < expWaveSize+1) break;
211 isAboveThreshold = true;
212 waveSizeCnt = 0;
213 } else {
214 waveSizeCnt++;
215 }
216 if (thresholdCnt > 10) break;
217 }
218 if (g_debugMode == 2) prnt("DEBUG: threshold Count reached at %u, count: %u",i, thresholdCnt);
219 return i;
220}
221
56de46b4 222int getClosestClock(int testclk) {
223 uint8_t fndClk[] = {8,16,32,40,50,64,128};
224
225 for (uint8_t clkCnt = 0; clkCnt<7; clkCnt++)
226 if (testclk >= fndClk[clkCnt]-(fndClk[clkCnt]/8) && testclk <= fndClk[clkCnt]+1)
227 return fndClk[clkCnt];
228
229 return 0;
230}
231
232void getNextLow(uint8_t samples[], size_t size, int low, size_t *i) {
d87bf156 233 while ((samples[*i] > low) && (*i < size))
234 *i+=1;
235}
236
56de46b4 237void getNextHigh(uint8_t samples[], size_t size, int high, size_t *i) {
d87bf156 238 while ((samples[*i] < high) && (*i < size))
239 *i+=1;
240}
241
242// load wave counters
243bool loadWaveCounters(uint8_t samples[], size_t size, int lowToLowWaveLen[], int highToLowWaveLen[], int *waveCnt, int *skip, int *minClk, int *high, int *low) {
56de46b4 244 size_t i=0, firstLow, firstHigh;
d87bf156 245 size_t testsize = (size < 512) ? size : 512;
246
247 if ( getHiLo(samples, testsize, high, low, 80, 80) == -1 ) {
248 if (g_debugMode==2) prnt("DEBUG STT: just noise detected - quitting");
249 return false; //just noise
250 }
251
252 // get to first full low to prime loop and skip incomplete first pulse
253 getNextHigh(samples, size, *high, &i);
254 getNextLow(samples, size, *low, &i);
255 *skip = i;
256
257 // populate tmpbuff buffer with pulse lengths
258 while (i < size) {
259 // measure from low to low
56de46b4 260 firstLow = i;
d87bf156 261 //find first high point for this wave
262 getNextHigh(samples, size, *high, &i);
56de46b4 263 firstHigh = i;
d87bf156 264
265 getNextLow(samples, size, *low, &i);
266
56de46b4 267 if (*waveCnt >= (size/LOWEST_DEFAULT_CLOCK))
d87bf156 268 break;
269
56de46b4 270 highToLowWaveLen[*waveCnt] = i - firstHigh; //first high to first low
271 lowToLowWaveLen[*waveCnt] = i - firstLow;
d87bf156 272 *waveCnt += 1;
56de46b4 273 if (i-firstLow < *minClk && i < size) {
274 *minClk = i - firstLow;
d87bf156 275 }
276 }
277 return true;
278}
279
2147c307 280//by marshmellow
4d3c1796 281//amplify based on ask edge detection - not accurate enough to use all the time
282void askAmp(uint8_t *BitStream, size_t size) {
16ea2b8c 283 uint8_t Last = 128;
fef74fdc 284 for(size_t i = 1; i<size; i++){
285 if (BitStream[i]-BitStream[i-1]>=30) //large jump up
16ea2b8c 286 Last = 255;
287 else if(BitStream[i-1]-BitStream[i]>=20) //large jump down
288 Last = 0;
289
290 BitStream[i-1] = Last;
fef74fdc 291 }
292 return;
293}
f822a063 294
3606ac0a 295uint32_t manchesterEncode2Bytes(uint16_t datain) {
296 uint32_t output = 0;
297 uint8_t curBit = 0;
298 for (uint8_t i=0; i<16; i++) {
299 curBit = (datain >> (15-i) & 1);
300 output |= (1<<(((15-i)*2)+curBit));
301 }
302 return output;
303}
304
fef74fdc 305//by marshmellow
306//encode binary data into binary manchester
86b8ecb5 307//NOTE: BitStream must have triple the size of "size" available in memory to do the swap
4d3c1796 308int ManchesterEncode(uint8_t *BitStream, size_t size) {
86b8ecb5 309 //allow up to 4K out (means BitStream must be at least 2048+4096 to handle the swap)
310 size = (size>2048) ? 2048 : size;
311 size_t modIdx = size;
312 size_t i;
fef74fdc 313 for (size_t idx=0; idx < size; idx++){
314 BitStream[idx+modIdx++] = BitStream[idx];
315 BitStream[idx+modIdx++] = BitStream[idx]^1;
316 }
86b8ecb5 317 for (i=0; i<(size*2); i++){
4d3c1796 318 BitStream[i] = BitStream[i+size];
fef74fdc 319 }
320 return i;
321}
322
d5051b98 323// by marshmellow
324// to detect a wave that has heavily clipped (clean) samples
325uint8_t DetectCleanAskWave(uint8_t dest[], size_t size, uint8_t high, uint8_t low) {
326 bool allArePeaks = true;
327 uint16_t cntPeaks=0;
328 size_t loopEnd = 512+160;
329 if (loopEnd > size) loopEnd = size;
330 for (size_t i=160; i<loopEnd; i++){
331 if (dest[i]>low && dest[i]<high)
332 allArePeaks = false;
333 else
334 cntPeaks++;
bf74114d 335 }
d5051b98 336 if (!allArePeaks){
337 if (cntPeaks > 300) return true;
338 }
339 return allArePeaks;
bf74114d 340}
4d3c1796 341
d5051b98 342//**********************************************************************************************
343//-------------------Clock / Bitrate Detection Section------------------------------------------
344//**********************************************************************************************
345
346// by marshmellow
347// to help detect clocks on heavily clipped samples
348// based on count of low to low
56de46b4 349int DetectStrongAskClock(uint8_t dest[], size_t size, int high, int low, int *clock) {
d5051b98 350 size_t startwave;
351 size_t i = 100;
352 size_t minClk = 255;
353 int shortestWaveIdx = 0;
354 // get to first full low to prime loop and skip incomplete first pulse
56de46b4 355 getNextHigh(dest, size, high, &i);
356 getNextLow(dest, size, low, &i);
4d3c1796 357
d5051b98 358 // loop through all samples
359 while (i < size) {
4d3c1796 360 // measure from low to low
d5051b98 361 startwave = i;
56de46b4 362
363 getNextHigh(dest, size, high, &i);
364 getNextLow(dest, size, low, &i);
d5051b98 365 //get minimum measured distance
366 if (i-startwave < minClk && i < size) {
367 minClk = i - startwave;
368 shortestWaveIdx = startwave;
4d3c1796 369 }
370 }
d5051b98 371 // set clock
56de46b4 372 if (g_debugMode==2) prnt("DEBUG ASK: DetectStrongAskClock smallest wave: %d",minClk);
373 *clock = getClosestClock(minClk);
374 if (*clock == 0)
375 return 0;
376
377 return shortestWaveIdx;
d5051b98 378}
4d3c1796 379
d5051b98 380// by marshmellow
381// not perfect especially with lower clocks or VERY good antennas (heavy wave clipping)
382// maybe somehow adjust peak trimming value based on samples to fix?
383// return start index of best starting position for that clock and return clock (by reference)
384int DetectASKClock(uint8_t dest[], size_t size, int *clock, int maxErr) {
385 size_t i=1;
386 uint8_t clk[] = {255,8,16,32,40,50,64,100,128,255};
387 uint8_t clkEnd = 9;
388 uint8_t loopCnt = 255; //don't need to loop through entire array...
389 if (size <= loopCnt+60) return -1; //not enough samples
390 size -= 60; //sometimes there is a strange end wave - filter out this....
391 //if we already have a valid clock
392 uint8_t clockFnd=0;
393 for (;i<clkEnd;++i)
394 if (clk[i] == *clock) clockFnd = i;
395 //clock found but continue to find best startpos
396
397 //get high and low peak
398 int peak, low;
399 if (getHiLo(dest, loopCnt, &peak, &low, 75, 75) < 1) return -1;
4d3c1796 400
d5051b98 401 //test for large clean peaks
402 if (!clockFnd){
403 if (DetectCleanAskWave(dest, size, peak, low)==1){
404 int ans = DetectStrongAskClock(dest, size, peak, low, clock);
405 if (g_debugMode==2) prnt("DEBUG ASK: detectaskclk Clean Ask Wave Detected: clk %i, ShortestWave: %i",clock, ans);
406 if (ans > 0) {
407 return ans; //return shortest wave start position
4d3c1796 408 }
4d3c1796 409 }
d5051b98 410 }
411 uint8_t ii;
412 uint8_t clkCnt, tol = 0;
413 uint16_t bestErr[]={1000,1000,1000,1000,1000,1000,1000,1000,1000};
414 uint8_t bestStart[]={0,0,0,0,0,0,0,0,0};
415 size_t errCnt = 0;
416 size_t arrLoc, loopEnd;
4d3c1796 417
d5051b98 418 if (clockFnd>0) {
419 clkCnt = clockFnd;
420 clkEnd = clockFnd+1;
4d3c1796 421 }
d5051b98 422 else clkCnt=1;
4d3c1796 423
d5051b98 424 //test each valid clock from smallest to greatest to see which lines up
425 for(; clkCnt < clkEnd; clkCnt++){
426 if (clk[clkCnt] <= 32){
427 tol=1;
428 }else{
429 tol=0;
ba1a299c 430 }
d5051b98 431 //if no errors allowed - keep start within the first clock
432 if (!maxErr && size > clk[clkCnt]*2 + tol && clk[clkCnt]<128) loopCnt=clk[clkCnt]*2;
433 bestErr[clkCnt]=1000;
434 //try lining up the peaks by moving starting point (try first few clocks)
435 for (ii=0; ii < loopCnt; ii++){
436 if (dest[ii] < peak && dest[ii] > low) continue;
11081e04 437
d5051b98 438 errCnt=0;
439 // now that we have the first one lined up test rest of wave array
440 loopEnd = ((size-ii-tol) / clk[clkCnt]) - 1;
441 for (i=0; i < loopEnd; ++i){
442 arrLoc = ii + (i * clk[clkCnt]);
443 if (dest[arrLoc] >= peak || dest[arrLoc] <= low){
444 }else if (dest[arrLoc-tol] >= peak || dest[arrLoc-tol] <= low){
445 }else if (dest[arrLoc+tol] >= peak || dest[arrLoc+tol] <= low){
446 }else{ //error no peak detected
447 errCnt++;
448 }
449 }
450 //if we found no errors then we can stop here and a low clock (common clocks)
451 // this is correct one - return this clock
452 if (g_debugMode == 2) prnt("DEBUG ASK: clk %d, err %d, startpos %d, endpos %d",clk[clkCnt],errCnt,ii,i);
453 if(errCnt==0 && clkCnt<7) {
454 if (!clockFnd) *clock = clk[clkCnt];
455 return ii;
456 }
457 //if we found errors see if it is lowest so far and save it as best run
458 if(errCnt<bestErr[clkCnt]){
459 bestErr[clkCnt]=errCnt;
460 bestStart[clkCnt]=ii;
461 }
4d3c1796 462 }
11081e04 463 }
d5051b98 464 uint8_t iii;
465 uint8_t best=0;
466 for (iii=1; iii<clkEnd; ++iii){
467 if (bestErr[iii] < bestErr[best]){
468 if (bestErr[iii] == 0) bestErr[iii]=1;
469 // current best bit to error ratio vs new bit to error ratio
470 if ( (size/clk[best])/bestErr[best] < (size/clk[iii])/bestErr[iii] ){
471 best = iii;
472 }
4d3c1796 473 }
d5051b98 474 if (g_debugMode == 2) prnt("DEBUG ASK: clk %d, # Errors %d, Current Best Clk %d, bestStart %d",clk[iii],bestErr[iii],clk[best],bestStart[best]);
4d3c1796 475 }
d5051b98 476 if (!clockFnd) *clock = clk[best];
477 return bestStart[best];
11081e04 478}
479
d5051b98 480int DetectStrongNRZClk(uint8_t *dest, size_t size, int peak, int low){
481 //find shortest transition from high to low
482 size_t i = 0;
483 size_t transition1 = 0;
484 int lowestTransition = 255;
485 bool lastWasHigh = false;
486
487 //find first valid beginning of a high or low wave
488 while ((dest[i] >= peak || dest[i] <= low) && (i < size))
489 ++i;
490 while ((dest[i] < peak && dest[i] > low) && (i < size))
491 ++i;
492 lastWasHigh = (dest[i] >= peak);
493
494 if (i==size) return 0;
495 transition1 = i;
496
497 for (;i < size; i++) {
498 if ((dest[i] >= peak && !lastWasHigh) || (dest[i] <= low && lastWasHigh)) {
499 lastWasHigh = (dest[i] >= peak);
500 if (i-transition1 < lowestTransition) lowestTransition = i-transition1;
501 transition1 = i;
502 }
4d3c1796 503 }
d5051b98 504 if (lowestTransition == 255) lowestTransition = 0;
505 if (g_debugMode==2) prnt("DEBUG NRZ: detectstrongNRZclk smallest wave: %d",lowestTransition);
506 return lowestTransition;
4d3c1796 507}
508
509//by marshmellow
d5051b98 510//detect nrz clock by reading #peaks vs no peaks(or errors)
6f36848f 511int DetectNRZClock(uint8_t dest[], size_t size, int clock, size_t *clockStartIdx) {
d5051b98 512 size_t i=0;
513 uint8_t clk[]={8,16,32,40,50,64,100,128,255};
514 size_t loopCnt = 4096; //don't need to loop through entire array...
515 if (size == 0) return 0;
516 if (size<loopCnt) loopCnt = size-20;
517 //if we already have a valid clock quit
518 for (; i < 8; ++i)
519 if (clk[i] == clock) return clock;
520
521 //get high and low peak
522 int peak, low;
523 if (getHiLo(dest, loopCnt, &peak, &low, 75, 75) < 1) return 0;
524
525 int lowestTransition = DetectStrongNRZClk(dest, size-20, peak, low);
526 size_t ii;
527 uint8_t clkCnt;
528 uint8_t tol = 0;
529 uint16_t smplCnt = 0;
530 int16_t peakcnt = 0;
531 int16_t peaksdet[] = {0,0,0,0,0,0,0,0};
532 uint16_t maxPeak = 255;
533 bool firstpeak = false;
534 //test for large clipped waves
535 for (i=0; i<loopCnt; i++){
536 if (dest[i] >= peak || dest[i] <= low){
537 if (!firstpeak) continue;
4d3c1796 538 smplCnt++;
d5051b98 539 } else {
540 firstpeak=true;
541 if (smplCnt > 6 ){
542 if (maxPeak > smplCnt){
543 maxPeak = smplCnt;
544 //prnt("maxPk: %d",maxPeak);
4d3c1796 545 }
d5051b98 546 peakcnt++;
547 //prnt("maxPk: %d, smplCnt: %d, peakcnt: %d",maxPeak,smplCnt,peakcnt);
548 smplCnt=0;
4d3c1796 549 }
550 }
551 }
d5051b98 552 bool errBitHigh = 0;
553 bool bitHigh = 0;
554 uint8_t ignoreCnt = 0;
555 uint8_t ignoreWindow = 4;
556 bool lastPeakHigh = 0;
557 int lastBit = 0;
558 size_t bestStart[]={0,0,0,0,0,0,0,0,0};
559 peakcnt=0;
560 //test each valid clock from smallest to greatest to see which lines up
561 for(clkCnt=0; clkCnt < 8; ++clkCnt){
562 //ignore clocks smaller than smallest peak
563 if (clk[clkCnt] < maxPeak - (clk[clkCnt]/4)) continue;
564 //try lining up the peaks by moving starting point (try first 256)
565 for (ii=20; ii < loopCnt; ++ii){
566 if ((dest[ii] >= peak) || (dest[ii] <= low)){
567 peakcnt = 0;
568 bitHigh = false;
569 ignoreCnt = 0;
570 lastBit = ii-clk[clkCnt];
571 //loop through to see if this start location works
572 for (i = ii; i < size-20; ++i) {
573 //if we are at a clock bit
574 if ((i >= lastBit + clk[clkCnt] - tol) && (i <= lastBit + clk[clkCnt] + tol)) {
575 //test high/low
576 if (dest[i] >= peak || dest[i] <= low) {
577 //if same peak don't count it
578 if ((dest[i] >= peak && !lastPeakHigh) || (dest[i] <= low && lastPeakHigh)) {
579 peakcnt++;
580 }
581 lastPeakHigh = (dest[i] >= peak);
582 bitHigh = true;
583 errBitHigh = false;
584 ignoreCnt = ignoreWindow;
585 lastBit += clk[clkCnt];
586 } else if (i == lastBit + clk[clkCnt] + tol) {
587 lastBit += clk[clkCnt];
588 }
589 //else if not a clock bit and no peaks
590 } else if (dest[i] < peak && dest[i] > low){
591 if (ignoreCnt==0){
592 bitHigh=false;
593 if (errBitHigh==true) peakcnt--;
594 errBitHigh=false;
595 } else {
596 ignoreCnt--;
597 }
598 // else if not a clock bit but we have a peak
599 } else if ((dest[i]>=peak || dest[i]<=low) && (!bitHigh)) {
600 //error bar found no clock...
601 errBitHigh=true;
602 }
603 }
604 if(peakcnt>peaksdet[clkCnt]) {
605 bestStart[clkCnt]=ii;
606 peaksdet[clkCnt]=peakcnt;
607 }
4d3c1796 608 }
4d3c1796 609 }
4d3c1796 610 }
d5051b98 611 int iii=7;
612 uint8_t best=0;
613 for (iii=7; iii > 0; iii--){
614 if ((peaksdet[iii] >= (peaksdet[best]-1)) && (peaksdet[iii] <= peaksdet[best]+1) && lowestTransition) {
615 if (clk[iii] > (lowestTransition - (clk[iii]/8)) && clk[iii] < (lowestTransition + (clk[iii]/8))) {
616 best = iii;
4d3c1796 617 }
d5051b98 618 } else if (peaksdet[iii] > peaksdet[best]){
619 best = iii;
4d3c1796 620 }
d5051b98 621 if (g_debugMode==2) prnt("DEBUG NRZ: Clk: %d, peaks: %d, maxPeak: %d, bestClk: %d, lowestTrs: %d",clk[iii],peaksdet[iii],maxPeak, clk[best], lowestTransition);
4d3c1796 622 }
d5051b98 623 *clockStartIdx = bestStart[best];
624 return clk[best];
4d3c1796 625}
d5051b98 626
d5051b98 627//by marshmellow
628//countFC is to detect the field clock lengths.
629//counts and returns the 2 most common wave lengths
630//mainly used for FSK field clock detection
631uint16_t countFC(uint8_t *BitStream, size_t size, uint8_t fskAdj) {
632 uint8_t fcLens[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
633 uint16_t fcCnts[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
634 uint8_t fcLensFnd = 0;
635 uint8_t lastFCcnt = 0;
636 uint8_t fcCounter = 0;
637 size_t i;
638 if (size < 180) return 0;
c85858f5 639
d5051b98 640 // prime i to first up transition
641 for (i = 160; i < size-20; i++)
642 if (BitStream[i] > BitStream[i-1] && BitStream[i] >= BitStream[i+1])
643 break;
ba1a299c 644
d5051b98 645 for (; i < size-20; i++){
646 if (BitStream[i] > BitStream[i-1] && BitStream[i] >= BitStream[i+1]){
647 // new up transition
648 fcCounter++;
649 if (fskAdj){
650 //if we had 5 and now have 9 then go back to 8 (for when we get a fc 9 instead of an 8)
651 if (lastFCcnt==5 && fcCounter==9) fcCounter--;
652 //if fc=9 or 4 add one (for when we get a fc 9 instead of 10 or a 4 instead of a 5)
653 if ((fcCounter==9) || fcCounter==4) fcCounter++;
654 // save last field clock count (fc/xx)
655 lastFCcnt = fcCounter;
656 }
657 // find which fcLens to save it to:
658 for (int ii=0; ii<15; ii++){
659 if (fcLens[ii]==fcCounter){
660 fcCnts[ii]++;
661 fcCounter=0;
662 break;
f4eadf8a 663 }
ba1a299c 664 }
d5051b98 665 if (fcCounter>0 && fcLensFnd<15){
666 //add new fc length
667 fcCnts[fcLensFnd]++;
668 fcLens[fcLensFnd++]=fcCounter;
669 }
670 fcCounter=0;
671 } else {
672 // count sample
673 fcCounter++;
ba1a299c 674 }
675 }
d5051b98 676
677 uint8_t best1=14, best2=14, best3=14;
678 uint16_t maxCnt1=0;
679 // go through fclens and find which ones are bigest 2
680 for (i=0; i<15; i++){
681 // get the 3 best FC values
682 if (fcCnts[i]>maxCnt1) {
683 best3=best2;
684 best2=best1;
685 maxCnt1=fcCnts[i];
686 best1=i;
687 } else if(fcCnts[i]>fcCnts[best2]){
688 best3=best2;
689 best2=i;
690 } else if(fcCnts[i]>fcCnts[best3]){
691 best3=i;
692 }
693 if (g_debugMode==2) prnt("DEBUG countfc: FC %u, Cnt %u, best fc: %u, best2 fc: %u",fcLens[i],fcCnts[i],fcLens[best1],fcLens[best2]);
694 }
695 if (fcLens[best1]==0) return 0;
696 uint8_t fcH=0, fcL=0;
697 if (fcLens[best1]>fcLens[best2]){
698 fcH=fcLens[best1];
699 fcL=fcLens[best2];
700 } else{
701 fcH=fcLens[best2];
702 fcL=fcLens[best1];
703 }
704 if ((size-180)/fcH/3 > fcCnts[best1]+fcCnts[best2]) {
705 if (g_debugMode==2) prnt("DEBUG countfc: fc is too large: %u > %u. Not psk or fsk",(size-180)/fcH/3,fcCnts[best1]+fcCnts[best2]);
706 return 0; //lots of waves not psk or fsk
707 }
708 // TODO: take top 3 answers and compare to known Field clocks to get top 2
709
710 uint16_t fcs = (((uint16_t)fcH)<<8) | fcL;
711 if (fskAdj) return fcs;
712 return fcLens[best1];
eb191de6 713}
714
d5051b98 715//by marshmellow
716//detect psk clock by reading each phase shift
717// a phase shift is determined by measuring the sample length of each wave
718int DetectPSKClock_ext(uint8_t dest[], size_t size, int clock, int *firstPhaseShift) {
719 uint8_t clk[]={255,16,32,40,50,64,100,128,255}; //255 is not a valid clock
720 uint16_t loopCnt = 4096; //don't need to loop through entire array...
721 if (size == 0) return 0;
722 if (size<loopCnt) loopCnt = size-20;
723
724 //if we already have a valid clock quit
725 size_t i=1;
726 for (; i < 8; ++i)
727 if (clk[i] == clock) return clock;
728
729 size_t waveStart=0, waveEnd=0, firstFullWave=0, lastClkBit=0;
730 uint8_t clkCnt, fc=0, fullWaveLen=0, tol=1;
731 uint16_t peakcnt=0, errCnt=0, waveLenCnt=0;
732 uint16_t bestErr[]={1000,1000,1000,1000,1000,1000,1000,1000,1000};
733 uint16_t peaksdet[]={0,0,0,0,0,0,0,0,0};
734 fc = countFC(dest, size, 0);
735 if (fc!=2 && fc!=4 && fc!=8) return -1;
736 if (g_debugMode==2) prnt("DEBUG PSK: FC: %d",fc);
737
738 //find first full wave
739 for (i=160; i<loopCnt; i++){
740 if (dest[i] < dest[i+1] && dest[i+1] >= dest[i+2]){
741 if (waveStart == 0) {
742 waveStart = i+1;
743 //prnt("DEBUG: waveStart: %d",waveStart);
669959bc 744 } else {
d5051b98 745 waveEnd = i+1;
746 //prnt("DEBUG: waveEnd: %d",waveEnd);
747 waveLenCnt = waveEnd-waveStart;
748 if (waveLenCnt > fc){
749 firstFullWave = waveStart;
750 fullWaveLen=waveLenCnt;
751 break;
752 }
753 waveStart=0;
669959bc 754 }
755 }
d5051b98 756 }
757 *firstPhaseShift = firstFullWave;
758 if (g_debugMode ==2) prnt("DEBUG PSK: firstFullWave: %d, waveLen: %d",firstFullWave,fullWaveLen);
759 //test each valid clock from greatest to smallest to see which lines up
760 for(clkCnt=7; clkCnt >= 1 ; clkCnt--){
761 lastClkBit = firstFullWave; //set end of wave as clock align
762 waveStart = 0;
763 errCnt=0;
764 peakcnt=0;
765 if (g_debugMode == 2) prnt("DEBUG PSK: clk: %d, lastClkBit: %d",clk[clkCnt],lastClkBit);
ba1a299c 766
d5051b98 767 for (i = firstFullWave+fullWaveLen-1; i < loopCnt-2; i++){
768 //top edge of wave = start of new wave
769 if (dest[i] < dest[i+1] && dest[i+1] >= dest[i+2]){
770 if (waveStart == 0) {
771 waveStart = i+1;
772 waveLenCnt=0;
773 } else { //waveEnd
774 waveEnd = i+1;
775 waveLenCnt = waveEnd-waveStart;
776 if (waveLenCnt > fc){
777 //if this wave is a phase shift
778 if (g_debugMode == 2) prnt("DEBUG PSK: phase shift at: %d, len: %d, nextClk: %d, i: %d, fc: %d",waveStart,waveLenCnt,lastClkBit+clk[clkCnt]-tol,i+1,fc);
779 if (i+1 >= lastClkBit + clk[clkCnt] - tol){ //should be a clock bit
780 peakcnt++;
781 lastClkBit+=clk[clkCnt];
782 } else if (i<lastClkBit+8){
783 //noise after a phase shift - ignore
784 } else { //phase shift before supposed to based on clock
785 errCnt++;
786 }
787 } else if (i+1 > lastClkBit + clk[clkCnt] + tol + fc){
788 lastClkBit+=clk[clkCnt]; //no phase shift but clock bit
789 }
790 waveStart=i+1;
791 }
792 }
13d77ef9 793 }
d5051b98 794 if (errCnt == 0){
795 return clk[clkCnt];
796 }
797 if (errCnt <= bestErr[clkCnt]) bestErr[clkCnt]=errCnt;
798 if (peakcnt > peaksdet[clkCnt]) peaksdet[clkCnt]=peakcnt;
799 }
800 //all tested with errors
801 //return the highest clk with the most peaks found
802 uint8_t best=7;
803 for (i=7; i>=1; i--){
804 if (peaksdet[i] > peaksdet[best]) {
805 best = i;
806 }
807 if (g_debugMode == 2) prnt("DEBUG PSK: Clk: %d, peaks: %d, errs: %d, bestClk: %d",clk[i],peaksdet[i],bestErr[i],clk[best]);
13d77ef9 808 }
d5051b98 809 return clk[best];
eb191de6 810}
6fe5c94b 811
d5051b98 812int DetectPSKClock(uint8_t dest[], size_t size, int clock) {
813 int firstPhaseShift = 0;
814 return DetectPSKClock_ext(dest, size, clock, &firstPhaseShift);
eb191de6 815}
a1d17964 816
d5051b98 817//by marshmellow
818//detects the bit clock for FSK given the high and low Field Clocks
819uint8_t detectFSKClk_ext(uint8_t *BitStream, size_t size, uint8_t fcHigh, uint8_t fcLow, int *firstClockEdge) {
820 uint8_t clk[] = {8,16,32,40,50,64,100,128,0};
821 uint16_t rfLens[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
822 uint8_t rfCnts[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
823 uint8_t rfLensFnd = 0;
824 uint8_t lastFCcnt = 0;
825 uint16_t fcCounter = 0;
826 uint16_t rfCounter = 0;
827 uint8_t firstBitFnd = 0;
828 size_t i;
829 if (size == 0) return 0;
669959bc 830
d5051b98 831 uint8_t fcTol = ((fcHigh*100 - fcLow*100)/2 + 50)/100; //(uint8_t)(0.5+(float)(fcHigh-fcLow)/2);
832 rfLensFnd=0;
833 fcCounter=0;
834 rfCounter=0;
835 firstBitFnd=0;
836 //PrintAndLog("DEBUG: fcTol: %d",fcTol);
837 // prime i to first peak / up transition
838 for (i = 160; i < size-20; i++)
839 if (BitStream[i] > BitStream[i-1] && BitStream[i]>=BitStream[i+1])
840 break;
841
842 for (; i < size-20; i++){
843 fcCounter++;
844 rfCounter++;
845
846 if (BitStream[i] <= BitStream[i-1] || BitStream[i] < BitStream[i+1])
847 continue;
848 // else new peak
849 // if we got less than the small fc + tolerance then set it to the small fc
850 // if it is inbetween set it to the last counter
851 if (fcCounter < fcHigh && fcCounter > fcLow)
852 fcCounter = lastFCcnt;
853 else if (fcCounter < fcLow+fcTol)
854 fcCounter = fcLow;
855 else //set it to the large fc
856 fcCounter = fcHigh;
857
858 //look for bit clock (rf/xx)
859 if ((fcCounter < lastFCcnt || fcCounter > lastFCcnt)){
860 //not the same size as the last wave - start of new bit sequence
861 if (firstBitFnd > 1){ //skip first wave change - probably not a complete bit
862 for (int ii=0; ii<15; ii++){
863 if (rfLens[ii] >= (rfCounter-4) && rfLens[ii] <= (rfCounter+4)){
864 rfCnts[ii]++;
865 rfCounter = 0;
866 break;
867 }
868 }
869 if (rfCounter > 0 && rfLensFnd < 15){
870 //PrintAndLog("DEBUG: rfCntr %d, fcCntr %d",rfCounter,fcCounter);
871 rfCnts[rfLensFnd]++;
872 rfLens[rfLensFnd++] = rfCounter;
873 }
874 } else {
875 *firstClockEdge = i;
876 firstBitFnd++;
877 }
878 rfCounter=0;
879 lastFCcnt=fcCounter;
e0165dcf 880 }
d5051b98 881 fcCounter=0;
e0165dcf 882 }
d5051b98 883 uint8_t rfHighest=15, rfHighest2=15, rfHighest3=15;
884
885 for (i=0; i<15; i++){
886 //get highest 2 RF values (might need to get more values to compare or compare all?)
887 if (rfCnts[i]>rfCnts[rfHighest]){
888 rfHighest3=rfHighest2;
889 rfHighest2=rfHighest;
890 rfHighest=i;
891 } else if(rfCnts[i]>rfCnts[rfHighest2]){
892 rfHighest3=rfHighest2;
893 rfHighest2=i;
894 } else if(rfCnts[i]>rfCnts[rfHighest3]){
895 rfHighest3=i;
896 }
897 if (g_debugMode==2) prnt("DEBUG FSK: RF %d, cnts %d",rfLens[i], rfCnts[i]);
898 }
899 // set allowed clock remainder tolerance to be 1 large field clock length+1
900 // we could have mistakenly made a 9 a 10 instead of an 8 or visa versa so rfLens could be 1 FC off
901 uint8_t tol1 = fcHigh+1;
902
903 if (g_debugMode==2) prnt("DEBUG FSK: most counted rf values: 1 %d, 2 %d, 3 %d",rfLens[rfHighest],rfLens[rfHighest2],rfLens[rfHighest3]);
eb191de6 904
d5051b98 905 // loop to find the highest clock that has a remainder less than the tolerance
906 // compare samples counted divided by
907 // test 128 down to 32 (shouldn't be possible to have fc/10 & fc/8 and rf/16 or less)
908 int ii=7;
909 for (; ii>=2; ii--){
910 if (rfLens[rfHighest] % clk[ii] < tol1 || rfLens[rfHighest] % clk[ii] > clk[ii]-tol1){
911 if (rfLens[rfHighest2] % clk[ii] < tol1 || rfLens[rfHighest2] % clk[ii] > clk[ii]-tol1){
912 if (rfLens[rfHighest3] % clk[ii] < tol1 || rfLens[rfHighest3] % clk[ii] > clk[ii]-tol1){
913 if (g_debugMode==2) prnt("DEBUG FSK: clk %d divides into the 3 most rf values within tolerance",clk[ii]);
914 break;
915 }
916 }
4d3c1796 917 }
ec75f5c1 918 }
ec75f5c1 919
d5051b98 920 if (ii<2) return 0; // oops we went too far
eb191de6 921
d5051b98 922 return clk[ii];
923}
415274a7 924
d5051b98 925uint8_t detectFSKClk(uint8_t *BitStream, size_t size, uint8_t fcHigh, uint8_t fcLow) {
926 int firstClockEdge = 0;
927 return detectFSKClk_ext(BitStream, size, fcHigh, fcLow, &firstClockEdge);
928}
415274a7 929
d5051b98 930//**********************************************************************************************
931//--------------------Modulation Demods &/or Decoding Section-----------------------------------
932//**********************************************************************************************
1e090a61 933
d5051b98 934// look for Sequence Terminator - should be pulses of clk*(1 or 2), clk*2, clk*(1.5 or 2), by idx we mean graph position index...
56de46b4 935bool findST(int *stStopLoc, int *stStartIdx, int lowToLowWaveLen[], int highToLowWaveLen[], int clk, int tol, int buffSize, size_t *i) {
549daaf7 936 for (; *i < buffSize - 4; *i+=1) {
937 *stStartIdx += lowToLowWaveLen[*i]; //caution part of this wave may be data and part may be ST.... to be accounted for in main function for now...
938 if (lowToLowWaveLen[*i] >= clk*1-tol && lowToLowWaveLen[*i] <= (clk*2)+tol && highToLowWaveLen[*i] < clk+tol) { //1 to 2 clocks depending on 2 bits prior
939 if (lowToLowWaveLen[*i+1] >= clk*2-tol && lowToLowWaveLen[*i+1] <= clk*2+tol && highToLowWaveLen[*i+1] > clk*3/2-tol) { //2 clocks and wave size is 1 1/2
940 if (lowToLowWaveLen[*i+2] >= (clk*3)/2-tol && lowToLowWaveLen[*i+2] <= clk*2+tol && highToLowWaveLen[*i+2] > clk-tol) { //1 1/2 to 2 clocks and at least one full clock wave
941 if (lowToLowWaveLen[*i+3] >= clk*1-tol && lowToLowWaveLen[*i+3] <= clk*2+tol) { //1 to 2 clocks for end of ST + first bit
942 *stStopLoc = *i + 3;
d5051b98 943 return true;
4d3c1796 944 }
4d3c1796 945 }
4d3c1796 946 }
947 }
4d3c1796 948 }
d5051b98 949 return false;
6923d3f1 950}
d5051b98 951//by marshmellow
952//attempt to identify a Sequence Terminator in ASK modulated raw wave
953bool DetectST_ext(uint8_t buffer[], size_t *size, int *foundclock, size_t *ststart, size_t *stend) {
954 size_t bufsize = *size;
955 //need to loop through all samples and identify our clock, look for the ST pattern
d5051b98 956 int clk = 0;
957 int tol = 0;
56de46b4 958 int j, high, low, skip, start, end, minClk=255;
959 size_t i = 0;
d5051b98 960 //probably should malloc... || test if memory is available ... handle device side? memory danger!!! [marshmellow]
56de46b4 961 int tmpbuff[bufsize / LOWEST_DEFAULT_CLOCK]; // low to low wave count //guess rf/32 clock, if click is smaller we will only have room for a fraction of the samples captured
962 int waveLen[bufsize / LOWEST_DEFAULT_CLOCK]; // high to low wave count //if clock is larger then we waste memory in array size that is not needed...
c83d6dc6 963 //size_t testsize = (bufsize < 512) ? bufsize : 512;
d5051b98 964 int phaseoff = 0;
965 high = low = 128;
966 memset(tmpbuff, 0, sizeof(tmpbuff));
549daaf7 967 memset(waveLen, 0, sizeof(waveLen));
d5051b98 968
c83d6dc6 969 if (!loadWaveCounters(buffer, bufsize, tmpbuff, waveLen, &j, &skip, &minClk, &high, &low)) return false;
d5051b98 970 // set clock - might be able to get this externally and remove this work...
56de46b4 971 clk = getClosestClock(minClk);
972 // clock not found - ERROR
973 if (clk == 0) {
974 if (g_debugMode==2) prnt("DEBUG STT: clock not found - quitting");
975 return false;
976 }
d5051b98 977 *foundclock = clk;
56de46b4 978
979 tol = clk/8;
549daaf7 980 if (!findST(&start, &skip, tmpbuff, waveLen, clk, tol, j, &i)) {
d5051b98 981 // first ST not found - ERROR
982 if (g_debugMode==2) prnt("DEBUG STT: first STT not found - quitting");
983 return false;
984 } else {
549daaf7 985 if (g_debugMode==2) prnt("DEBUG STT: first STT found at wave: %i, skip: %i, j=%i", start, skip, j);
cc15a118 986 }
d5051b98 987 if (waveLen[i+2] > clk*1+tol)
988 phaseoff = 0;
989 else
990 phaseoff = clk/2;
991
992 // skip over the remainder of ST
993 skip += clk*7/2; //3.5 clocks from tmpbuff[i] = end of st - also aligns for ending point
2eec55c8 994
d5051b98 995 // now do it again to find the end
996 int dummy1 = 0;
997 end = skip;
549daaf7 998 i+=3;
999 if (!findST(&dummy1, &end, tmpbuff, waveLen, clk, tol, j, &i)) {
d5051b98 1000 //didn't find second ST - ERROR
1001 if (g_debugMode==2) prnt("DEBUG STT: second STT not found - quitting");
1002 return false;
1003 }
1004 end -= phaseoff;
1005 if (g_debugMode==2) prnt("DEBUG STT: start of data: %d end of data: %d, datalen: %d, clk: %d, bits: %d, phaseoff: %d", skip, end, end-skip, clk, (end-skip)/clk, phaseoff);
1006 //now begin to trim out ST so we can use normal demod cmds
1007 start = skip;
1008 size_t datalen = end - start;
1009 // check validity of datalen (should be even clock increments) - use a tolerance of up to 1/8th a clock
1010 if ( clk - (datalen % clk) <= clk/8) {
1011 // padd the amount off - could be problematic... but shouldn't happen often
1012 datalen += clk - (datalen % clk);
1013 } else if ( (datalen % clk) <= clk/8 ) {
1014 // padd the amount off - could be problematic... but shouldn't happen often
1015 datalen -= datalen % clk;
1016 } else {
1017 if (g_debugMode==2) prnt("DEBUG STT: datalen not divisible by clk: %u %% %d = %d - quitting", datalen, clk, datalen % clk);
1018 return false;
1019 }
1020 // if datalen is less than one t55xx block - ERROR
1021 if (datalen/clk < 8*4) {
1022 if (g_debugMode==2) prnt("DEBUG STT: datalen is less than 1 full t55xx block - quitting");
1023 return false;
1024 }
1025 size_t dataloc = start;
1026 if (buffer[dataloc-(clk*4)-(clk/8)] <= low && buffer[dataloc] <= low && buffer[dataloc-(clk*4)] >= high) {
1027 //we have low drift (and a low just before the ST and a low just after the ST) - compensate by backing up the start
1028 for ( i=0; i <= (clk/8); ++i ) {
1029 if ( buffer[dataloc - (clk*4) - i] <= low ) {
1030 dataloc -= i;
1031 break;
2eec55c8 1032 }
e0165dcf 1033 }
1034 }
d5051b98 1035
1036 size_t newloc = 0;
1037 i=0;
1038 if (g_debugMode==2) prnt("DEBUG STT: Starting STT trim - start: %d, datalen: %d ",dataloc, datalen);
1039 bool firstrun = true;
1040 // warning - overwriting buffer given with raw wave data with ST removed...
1041 while ( dataloc < bufsize-(clk/2) ) {
1042 //compensate for long high at end of ST not being high due to signal loss... (and we cut out the start of wave high part)
1043 if (buffer[dataloc]<high && buffer[dataloc]>low && buffer[dataloc+3]<high && buffer[dataloc+3]>low) {
1044 for(i=0; i < clk/2-tol; ++i) {
1045 buffer[dataloc+i] = high+5;
1046 }
1047 } //test for single sample outlier (high between two lows) in the case of very strong waves
1048 if (buffer[dataloc] >= high && buffer[dataloc+2] <= low) {
1049 buffer[dataloc] = buffer[dataloc+2];
1050 buffer[dataloc+1] = buffer[dataloc+2];
1051 }
1052 if (firstrun) {
1053 *stend = dataloc;
1054 *ststart = dataloc-(clk*4);
1055 firstrun=false;
1056 }
1057 for (i=0; i<datalen; ++i) {
1058 if (i+newloc < bufsize) {
1059 if (i+newloc < dataloc)
1060 buffer[i+newloc] = buffer[dataloc];
1061
1062 dataloc++;
e0165dcf 1063 }
1064 }
d5051b98 1065 newloc += i;
1066 //skip next ST - we just assume it will be there from now on...
1067 if (g_debugMode==2) prnt("DEBUG STT: skipping STT at %d to %d", dataloc, dataloc+(clk*4));
1068 dataloc += clk*4;
e0165dcf 1069 }
d5051b98 1070 *size = newloc;
1071 return true;
1072}
1073bool DetectST(uint8_t buffer[], size_t *size, int *foundclock) {
1074 size_t ststart = 0, stend = 0;
1075 return DetectST_ext(buffer, size, foundclock, &ststart, &stend);
eb191de6 1076}
ba1a299c 1077
549daaf7 1078//by marshmellow
127f1490 1079//take 11 10 01 11 00 and make 01100 ... miller decoding
549daaf7 1080//check for phase errors - should never have half a 1 or 0 by itself and should never exceed 1111 or 0000 in a row
1081//decodes miller encoded binary
1082//NOTE askrawdemod will NOT demod miller encoded ask unless the clock is manually set to 1/2 what it is detected as!
127f1490 1083int millerRawDecode(uint8_t *BitStream, size_t *size, int invert) {
549daaf7 1084 if (*size < 16) return -1;
127f1490 1085 uint16_t MaxBits = 512, errCnt = 0;
1086 size_t i, bitCnt=0;
1087 uint8_t alignCnt = 0, curBit = BitStream[0], alignedIdx = 0;
1088 uint8_t halfClkErr = 0;
549daaf7 1089 //find alignment, needs 4 1s or 0s to properly align
127f1490 1090 for (i=1; i < *size-1; i++) {
549daaf7 1091 alignCnt = (BitStream[i] == curBit) ? alignCnt+1 : 0;
1092 curBit = BitStream[i];
1093 if (alignCnt == 4) break;
1094 }
1095 // for now error if alignment not found. later add option to run it with multiple offsets...
1096 if (alignCnt != 4) {
1097 if (g_debugMode) prnt("ERROR MillerDecode: alignment not found so either your bitstream is not miller or your data does not have a 101 in it");
1098 return -1;
1099 }
127f1490 1100 alignedIdx = (i-1) % 2;
1101 for (i=alignedIdx; i < *size-3; i+=2) {
1102 halfClkErr = (uint8_t)((halfClkErr << 1 | BitStream[i]) & 0xFF);
1103 if ( (halfClkErr & 0x7) == 5 || (halfClkErr & 0x7) == 2 || (i > 2 && (halfClkErr & 0x7) == 0) || (halfClkErr & 0x1F) == 0x1F) {
1104 errCnt++;
1105 BitStream[bitCnt++] = 7;
1106 continue;
1107 }
1108 BitStream[bitCnt++] = BitStream[i] ^ BitStream[i+1] ^ invert;
549daaf7 1109
127f1490 1110 if (bitCnt > MaxBits) break;
1111 }
1112 *size = bitCnt;
1113 return errCnt;
1114}
549daaf7 1115
d5051b98 1116//by marshmellow
1117//take 01 or 10 = 1 and 11 or 00 = 0
1118//check for phase errors - should never have 111 or 000 should be 01001011 or 10110100 for 1010
1119//decodes biphase or if inverted it is AKA conditional dephase encoding AKA differential manchester encoding
1120int BiphaseRawDecode(uint8_t *BitStream, size_t *size, int offset, int invert) {
1121 uint16_t bitnum = 0;
1122 uint16_t errCnt = 0;
1123 size_t i = offset;
1124 uint16_t MaxBits=512;
1125 //if not enough samples - error
1126 if (*size < 51) return -1;
1127 //check for phase change faults - skip one sample if faulty
1128 uint8_t offsetA = 1, offsetB = 1;
1129 for (; i<48; i+=2){
1130 if (BitStream[i+1]==BitStream[i+2]) offsetA=0;
1131 if (BitStream[i+2]==BitStream[i+3]) offsetB=0;
1132 }
1133 if (!offsetA && offsetB) offset++;
1134 for (i=offset; i<*size-3; i+=2){
1135 //check for phase error
1136 if (BitStream[i+1]==BitStream[i+2]) {
1137 BitStream[bitnum++]=7;
1138 errCnt++;
1139 }
1140 if((BitStream[i]==1 && BitStream[i+1]==0) || (BitStream[i]==0 && BitStream[i+1]==1)){
1141 BitStream[bitnum++]=1^invert;
1142 } else if((BitStream[i]==0 && BitStream[i+1]==0) || (BitStream[i]==1 && BitStream[i+1]==1)){
1143 BitStream[bitnum++]=invert;
1144 } else {
1145 BitStream[bitnum++]=7;
1146 errCnt++;
db829602 1147 }
d5051b98 1148 if(bitnum>MaxBits) break;
db829602 1149 }
d5051b98 1150 *size=bitnum;
1151 return errCnt;
db829602 1152}
1153
6de43508 1154//by marshmellow
d5051b98 1155//take 10 and 01 and manchester decode
1156//run through 2 times and take least errCnt
1157int manrawdecode(uint8_t * BitStream, size_t *size, uint8_t invert, uint8_t *alignPos) {
1158 uint16_t bitnum=0, MaxBits = 512, errCnt = 0;
1159 size_t i, ii;
1160 uint16_t bestErr = 1000, bestRun = 0;
1161 if (*size < 16) return -1;
1162 //find correct start position [alignment]
1163 for (ii=0;ii<2;++ii){
1164 for (i=ii; i<*size-3; i+=2)
1165 if (BitStream[i]==BitStream[i+1])
1166 errCnt++;
1167
1168 if (bestErr>errCnt){
1169 bestErr=errCnt;
1170 bestRun=ii;
1171 }
1172 errCnt=0;
1173 }
1174 *alignPos=bestRun;
1175 //decode
1176 for (i=bestRun; i < *size-3; i+=2){
1177 if(BitStream[i] == 1 && (BitStream[i+1] == 0)){
1178 BitStream[bitnum++]=invert;
1179 } else if((BitStream[i] == 0) && BitStream[i+1] == 1){
1180 BitStream[bitnum++]=invert^1;
e0165dcf 1181 } else {
d5051b98 1182 BitStream[bitnum++]=7;
e0165dcf 1183 }
d5051b98 1184 if(bitnum>MaxBits) break;
e0165dcf 1185 }
d5051b98 1186 *size=bitnum;
1187 return bestErr;
1188}
1189
1190//by marshmellow
1191//demodulates strong heavily clipped samples
1192int cleanAskRawDemod(uint8_t *BinStream, size_t *size, int clk, int invert, int high, int low, int *startIdx)
1193{
1194 *startIdx=0;
1195 size_t bitCnt=0, smplCnt=1, errCnt=0;
1196 bool waveHigh = (BinStream[0] >= high);
1197 for (size_t i=1; i < *size; i++){
1198 if (BinStream[i] >= high && waveHigh){
1199 smplCnt++;
1200 } else if (BinStream[i] <= low && !waveHigh){
1201 smplCnt++;
1202 } else { //transition
1203 if ((BinStream[i] >= high && !waveHigh) || (BinStream[i] <= low && waveHigh)){
1204 if (smplCnt > clk-(clk/4)-1) { //full clock
1205 if (smplCnt > clk + (clk/4)+1) { //too many samples
1206 errCnt++;
1207 if (g_debugMode==2) prnt("DEBUG ASK: Modulation Error at: %u", i);
1208 BinStream[bitCnt++] = 7;
1209 } else if (waveHigh) {
1210 BinStream[bitCnt++] = invert;
1211 BinStream[bitCnt++] = invert;
1212 } else if (!waveHigh) {
1213 BinStream[bitCnt++] = invert ^ 1;
1214 BinStream[bitCnt++] = invert ^ 1;
e0165dcf 1215 }
d5051b98 1216 if (*startIdx==0) *startIdx = i-clk;
1217 waveHigh = !waveHigh;
1218 smplCnt = 0;
1219 } else if (smplCnt > (clk/2) - (clk/4)-1) { //half clock
1220 if (waveHigh) {
1221 BinStream[bitCnt++] = invert;
1222 } else if (!waveHigh) {
1223 BinStream[bitCnt++] = invert ^ 1;
1224 }
1225 if (*startIdx==0) *startIdx = i-(clk/2);
1226 waveHigh = !waveHigh;
1227 smplCnt = 0;
1228 } else {
1229 smplCnt++;
1230 //transition bit oops
e0165dcf 1231 }
d5051b98 1232 } else { //haven't hit new high or new low yet
1233 smplCnt++;
db829602 1234 }
e0165dcf 1235 }
e0165dcf 1236 }
d5051b98 1237 *size = bitCnt;
1238 return errCnt;
669959bc 1239}
1240
4d3c1796 1241//by marshmellow
d5051b98 1242//attempts to demodulate ask modulations, askType == 0 for ask/raw, askType==1 for ask/manchester
1243int askdemod_ext(uint8_t *BinStream, size_t *size, int *clk, int *invert, int maxErr, uint8_t amp, uint8_t askType, int *startIdx) {
1244 if (*size==0) return -1;
1245 int start = DetectASKClock(BinStream, *size, clk, maxErr); //clock default
1246 if (*clk==0 || start < 0) return -3;
1247 if (*invert != 1) *invert = 0;
1248 if (amp==1) askAmp(BinStream, *size);
1249 if (g_debugMode==2) prnt("DEBUG ASK: clk %d, beststart %d, amp %d", *clk, start, amp);
4d3c1796 1250
d5051b98 1251 //start pos from detect ask clock is 1/2 clock offset
1252 // NOTE: can be negative (demod assumes rest of wave was there)
1253 *startIdx = start - (*clk/2);
1254 uint8_t initLoopMax = 255;
1255 if (initLoopMax > *size) initLoopMax = *size;
1256 // Detect high and lows
1257 //25% clip in case highs and lows aren't clipped [marshmellow]
1258 int high, low;
1259 if (getHiLo(BinStream, initLoopMax, &high, &low, 75, 75) < 1)
1260 return -2; //just noise
4d3c1796 1261
d5051b98 1262 size_t errCnt = 0;
1263 // if clean clipped waves detected run alternate demod
1264 if (DetectCleanAskWave(BinStream, *size, high, low)) {
1265 if (g_debugMode==2) prnt("DEBUG ASK: Clean Wave Detected - using clean wave demod");
1266 errCnt = cleanAskRawDemod(BinStream, size, *clk, *invert, high, low, startIdx);
1267 if (askType) { //askman
1268 uint8_t alignPos = 0;
1269 errCnt = manrawdecode(BinStream, size, 0, &alignPos);
1270 *startIdx += *clk/2 * alignPos;
1271 if (g_debugMode) prnt("DEBUG ASK CLEAN: startIdx %i, alignPos %u", *startIdx, alignPos);
1272 return errCnt;
1273 } else { //askraw
1274 return errCnt;
1275 }
1276 }
1277 if (g_debugMode) prnt("DEBUG ASK WEAK: startIdx %i", *startIdx);
1278 if (g_debugMode==2) prnt("DEBUG ASK: Weak Wave Detected - using weak wave demod");
1279
1280 int lastBit; //set first clock check - can go negative
1281 size_t i, bitnum = 0; //output counter
1282 uint8_t midBit = 0;
1283 uint8_t tol = 0; //clock tolerance adjust - waves will be accepted as within the clock if they fall + or - this value + clock from last valid wave
1284 if (*clk <= 32) tol = 1; //clock tolerance may not be needed anymore currently set to + or - 1 but could be increased for poor waves or removed entirely
1285 size_t MaxBits = 3072; //max bits to collect
1286 lastBit = start - *clk;
1287
1288 for (i = start; i < *size; ++i) {
1289 if (i-lastBit >= *clk-tol){
1290 if (BinStream[i] >= high) {
1291 BinStream[bitnum++] = *invert;
1292 } else if (BinStream[i] <= low) {
1293 BinStream[bitnum++] = *invert ^ 1;
1294 } else if (i-lastBit >= *clk+tol) {
1295 if (bitnum > 0) {
1296 if (g_debugMode==2) prnt("DEBUG ASK: Modulation Error at: %u", i);
1297 BinStream[bitnum++]=7;
1298 errCnt++;
1299 }
1300 } else { //in tolerance - looking for peak
1301 continue;
4d3c1796 1302 }
d5051b98 1303 midBit = 0;
1304 lastBit += *clk;
1305 } else if (i-lastBit >= (*clk/2-tol) && !midBit && !askType){
1306 if (BinStream[i] >= high) {
1307 BinStream[bitnum++] = *invert;
1308 } else if (BinStream[i] <= low) {
1309 BinStream[bitnum++] = *invert ^ 1;
1310 } else if (i-lastBit >= *clk/2+tol) {
1311 BinStream[bitnum] = BinStream[bitnum-1];
1312 bitnum++;
1313 } else { //in tolerance - looking for peak
1314 continue;
4d3c1796 1315 }
d5051b98 1316 midBit = 1;
04d2721b 1317 }
d5051b98 1318 if (bitnum >= MaxBits) break;
04d2721b 1319 }
d5051b98 1320 *size = bitnum;
1321 return errCnt;
1322}
1323
1324int askdemod(uint8_t *BinStream, size_t *size, int *clk, int *invert, int maxErr, uint8_t amp, uint8_t askType) {
1325 int start = 0;
1326 return askdemod_ext(BinStream, size, clk, invert, maxErr, amp, askType, &start);
1327}
1328
1329// by marshmellow - demodulate NRZ wave - requires a read with strong signal
1330// peaks invert bit (high=1 low=0) each clock cycle = 1 bit determined by last peak
6f36848f 1331int nrzRawDemod(uint8_t *dest, size_t *size, int *clk, int *invert, int *startIdx) {
d5051b98 1332 if (justNoise(dest, *size)) return -1;
6f36848f 1333 size_t clkStartIdx = 0;
1334 *clk = DetectNRZClock(dest, *size, *clk, &clkStartIdx);
d5051b98 1335 if (*clk==0) return -2;
1336 size_t i, gLen = 4096;
1337 if (gLen>*size) gLen = *size-20;
1338 int high, low;
1339 if (getHiLo(dest, gLen, &high, &low, 75, 75) < 1) return -3; //25% fuzz on high 25% fuzz on low
4d3c1796 1340
d5051b98 1341 uint8_t bit=0;
1342 //convert wave samples to 1's and 0's
1343 for(i=20; i < *size-20; i++){
1344 if (dest[i] >= high) bit = 1;
1345 if (dest[i] <= low) bit = 0;
1346 dest[i] = bit;
4d3c1796 1347 }
d5051b98 1348 //now demod based on clock (rf/32 = 32 1's for one 1 bit, 32 0's for one 0 bit)
1349 size_t lastBit = 0;
1350 size_t numBits = 0;
1351 for(i=21; i < *size-20; i++) {
1352 //if transition detected or large number of same bits - store the passed bits
1353 if (dest[i] != dest[i-1] || (i-lastBit) == (10 * *clk)) {
1354 memset(dest+numBits, dest[i-1] ^ *invert, (i - lastBit + (*clk/4)) / *clk);
1355 numBits += (i - lastBit + (*clk/4)) / *clk;
1356 if (lastBit == 0) {
1357 *startIdx = i - (numBits * *clk);
1358 if (g_debugMode==2) prnt("DEBUG NRZ: startIdx %i", *startIdx);
1359 }
1360 lastBit = i-1;
1361 }
4d3c1796 1362 }
d5051b98 1363 *size = numBits;
1364 return 0;
1365}
3bc66a96 1366
d5051b98 1367//translate wave to 11111100000 (1 for each short wave [higher freq] 0 for each long wave [lower freq])
1368size_t fsk_wave_demod(uint8_t * dest, size_t size, uint8_t fchigh, uint8_t fclow, int *startIdx) {
1369 size_t last_transition = 0;
1370 size_t idx = 1;
1371 if (fchigh==0) fchigh=10;
1372 if (fclow==0) fclow=8;
1373 //set the threshold close to 0 (graph) or 128 std to avoid static
d5051b98 1374 size_t preLastSample = 0;
1375 size_t LastSample = 0;
1376 size_t currSample = 0;
1377 if ( size < 1024 ) return 0; // not enough samples
ba1a299c 1378
d5051b98 1379 //find start of modulating data in trace
6f36848f 1380 idx = findModStart(dest, size, fchigh);
d5051b98 1381 // Need to threshold first sample
6f36848f 1382 if(dest[idx] < FSK_PSK_THRESHOLD) dest[0] = 0;
d5051b98 1383 else dest[0] = 1;
1384
1385 last_transition = idx;
1386 idx++;
1387 size_t numBits = 0;
1388 // count cycles between consecutive lo-hi transitions, there should be either 8 (fc/8)
1389 // or 10 (fc/10) cycles but in practice due to noise etc we may end up with anywhere
1390 // between 7 to 11 cycles so fuzz it by treat anything <9 as 8 and anything else as 10
1391 // (could also be fc/5 && fc/7 for fsk1 = 4-9)
1392 for(; idx < size; idx++) {
1393 // threshold current value
6f36848f 1394 if (dest[idx] < FSK_PSK_THRESHOLD) dest[idx] = 0;
d5051b98 1395 else dest[idx] = 1;
4d3c1796 1396
d5051b98 1397 // Check for 0->1 transition
1398 if (dest[idx-1] < dest[idx]) {
1399 preLastSample = LastSample;
1400 LastSample = currSample;
1401 currSample = idx-last_transition;
1402 if (currSample < (fclow-2)) { //0-5 = garbage noise (or 0-3)
1403 //do nothing with extra garbage
1404 } else if (currSample < (fchigh-1)) { //6-8 = 8 sample waves (or 3-6 = 5)
1405 //correct previous 9 wave surrounded by 8 waves (or 6 surrounded by 5)
1406 if (numBits > 1 && LastSample > (fchigh-2) && (preLastSample < (fchigh-1))){
1407 dest[numBits-1]=1;
1408 }
1409 dest[numBits++]=1;
1410 if (numBits > 0 && *startIdx==0) *startIdx = idx - fclow;
1411 } else if (currSample > (fchigh+1) && numBits < 3) { //12 + and first two bit = unusable garbage
1412 //do nothing with beginning garbage and reset.. should be rare..
1413 numBits = 0;
1414 } else if (currSample == (fclow+1) && LastSample == (fclow-1)) { // had a 7 then a 9 should be two 8's (or 4 then a 6 should be two 5's)
1415 dest[numBits++]=1;
1416 if (numBits > 0 && *startIdx==0) *startIdx = idx - fclow;
1417 } else { //9+ = 10 sample waves (or 6+ = 7)
1418 dest[numBits++]=0;
1419 if (numBits > 0 && *startIdx==0) *startIdx = idx - fchigh;
4d3c1796 1420 }
d5051b98 1421 last_transition = idx;
4d3c1796 1422 }
e0165dcf 1423 }
d5051b98 1424 return numBits; //Actually, it returns the number of bytes, but each byte represents a bit: 1 or 0
1425}
4d3c1796 1426
d5051b98 1427//translate 11111100000 to 10
1428//rfLen = clock, fchigh = larger field clock, fclow = smaller field clock
1429size_t aggregate_bits(uint8_t *dest, size_t size, uint8_t rfLen, uint8_t invert, uint8_t fchigh, uint8_t fclow, int *startIdx) {
1430 uint8_t lastval=dest[0];
1431 size_t idx=0;
1432 size_t numBits=0;
1433 uint32_t n=1;
1434 for( idx=1; idx < size; idx++) {
1435 n++;
1436 if (dest[idx]==lastval) continue; //skip until we hit a transition
1437
1438 //find out how many bits (n) we collected (use 1/2 clk tolerance)
1439 //if lastval was 1, we have a 1->0 crossing
1440 if (dest[idx-1]==1) {
1441 n = (n * fclow + rfLen/2) / rfLen;
1442 } else {// 0->1 crossing
1443 n = (n * fchigh + rfLen/2) / rfLen;
e0165dcf 1444 }
d5051b98 1445 if (n == 0) n = 1;
1446
1447 //first transition - save startidx
1448 if (numBits == 0) {
1449 if (lastval == 1) { //high to low
1450 *startIdx += (fclow * idx) - (n*rfLen);
1451 if (g_debugMode==2) prnt("DEBUG FSK: startIdx %i, fclow*idx %i, n*rflen %u", *startIdx, fclow*(idx), n*rfLen);
1452 } else {
1453 *startIdx += (fchigh * idx) - (n*rfLen);
1454 if (g_debugMode==2) prnt("DEBUG FSK: startIdx %i, fchigh*idx %i, n*rflen %u", *startIdx, fchigh*(idx), n*rfLen);
1455 }
4d3c1796 1456 }
d5051b98 1457
1458 //add to our destination the bits we collected
1459 memset(dest+numBits, dest[idx-1]^invert , n);
1460 numBits += n;
1461 n=0;
1462 lastval=dest[idx];
1463 }//end for
1464 // if valid extra bits at the end were all the same frequency - add them in
1465 if (n > rfLen/fchigh) {
1466 if (dest[idx-2]==1) {
1467 n = (n * fclow + rfLen/2) / rfLen;
1468 } else {
1469 n = (n * fchigh + rfLen/2) / rfLen;
4d3c1796 1470 }
d5051b98 1471 memset(dest+numBits, dest[idx-1]^invert , n);
1472 numBits += n;
e0165dcf 1473 }
d5051b98 1474 return numBits;
ba1a299c 1475}
4d3c1796 1476
d5051b98 1477//by marshmellow (from holiman's base)
1478// full fsk demod from GraphBuffer wave to decoded 1s and 0s (no mandemod)
1479int fskdemod_ext(uint8_t *dest, size_t size, uint8_t rfLen, uint8_t invert, uint8_t fchigh, uint8_t fclow, int *startIdx) {
1480 // FSK demodulator
1481 size = fsk_wave_demod(dest, size, fchigh, fclow, startIdx);
1482 size = aggregate_bits(dest, size, rfLen, invert, fchigh, fclow, startIdx);
1483 return size;
8b6abef5 1484}
1485
d5051b98 1486int fskdemod(uint8_t *dest, size_t size, uint8_t rfLen, uint8_t invert, uint8_t fchigh, uint8_t fclow) {
1487 int startIdx=0;
1488 return fskdemod_ext(dest, size, rfLen, invert, fchigh, fclow, &startIdx);
1489}
e0165dcf 1490
d5051b98 1491// by marshmellow
1492// convert psk1 demod to psk2 demod
1493// only transition waves are 1s
1494void psk1TOpsk2(uint8_t *BitStream, size_t size) {
1495 size_t i=1;
1496 uint8_t lastBit=BitStream[0];
1497 for (; i<size; i++){
1498 if (BitStream[i]==7){
1499 //ignore errors
1500 } else if (lastBit!=BitStream[i]){
1501 lastBit=BitStream[i];
1502 BitStream[i]=1;
1503 } else {
1504 BitStream[i]=0;
1505 }
1506 }
1507 return;
1508}
e0165dcf 1509
d5051b98 1510// by marshmellow
1511// convert psk2 demod to psk1 demod
1512// from only transition waves are 1s to phase shifts change bit
1513void psk2TOpsk1(uint8_t *BitStream, size_t size) {
1514 uint8_t phase=0;
1515 for (size_t i=0; i<size; i++){
1516 if (BitStream[i]==1){
1517 phase ^=1;
1518 }
1519 BitStream[i]=phase;
1520 }
1521 return;
1522}
2eec55c8 1523
6f36848f 1524size_t pskFindFirstPhaseShift(uint8_t samples[], size_t size, uint8_t *curPhase, size_t waveStart, uint16_t fc, uint16_t *fullWaveLen) {
1525 uint16_t loopCnt = (size+3 < 4096) ? size : 4096; //don't need to loop through entire array...
1526
1527 uint16_t avgWaveVal=0, lastAvgWaveVal=0;
1528 size_t i = waveStart, waveEnd, waveLenCnt, firstFullWave;
1529 for (; i<loopCnt; i++) {
1530 // find peak
1531 if (samples[i]+fc < samples[i+1] && samples[i+1] >= samples[i+2]){
1532 waveEnd = i+1;
1533 if (g_debugMode == 2) prnt("DEBUG PSK: waveEnd: %u, waveStart: %u", waveEnd, waveStart);
1534 waveLenCnt = waveEnd-waveStart;
1535 if (waveLenCnt > fc && waveStart > fc && !(waveLenCnt > fc+8)){ //not first peak and is a large wave but not out of whack
1536 lastAvgWaveVal = avgWaveVal/(waveLenCnt);
1537 firstFullWave = waveStart;
1538 *fullWaveLen = waveLenCnt;
1539 //if average wave value is > graph 0 then it is an up wave or a 1 (could cause inverting)
1540 if (lastAvgWaveVal > FSK_PSK_THRESHOLD) *curPhase ^= 1;
1541 return firstFullWave;
1542 }
1543 waveStart = i+1;
1544 avgWaveVal = 0;
1545 }
1546 avgWaveVal += samples[i+2];
1547 }
1548 return 0;
1549}
1550
d5051b98 1551//by marshmellow - demodulate PSK1 wave
1552//uses wave lengths (# Samples)
1553int pskRawDemod_ext(uint8_t dest[], size_t *size, int *clock, int *invert, int *startIdx) {
6f36848f 1554 if (*size < 170) return -1;
2eec55c8 1555
d5051b98 1556 uint8_t curPhase = *invert;
6f36848f 1557 size_t i=0, numBits=0, waveStart=1, waveEnd=0, firstFullWave=0, lastClkBit=0;
1558 uint16_t fc=0, fullWaveLen=0, waveLenCnt=0, avgWaveVal, tol=1;
1559 uint16_t errCnt=0, errCnt2=0;
1560
d5051b98 1561 fc = countFC(dest, *size, 1);
6f36848f 1562 if ((fc >> 8) == 10) return -1; //fsk found - quit
d5051b98 1563 fc = fc & 0xFF;
1564 if (fc!=2 && fc!=4 && fc!=8) return -1;
d5051b98 1565 *clock = DetectPSKClock(dest, *size, *clock);
1566 if (*clock == 0) return -1;
1567
1568 //find start of modulating data in trace
6f36848f 1569 i = findModStart(dest, *size, fc);
d5051b98 1570
1571 //find first phase shift
6f36848f 1572 firstFullWave = pskFindFirstPhaseShift(dest, *size, &curPhase, i, fc, &fullWaveLen);
d5051b98 1573 if (firstFullWave == 0) {
1574 // no phase shift detected - could be all 1's or 0's - doesn't matter where we start
1575 // so skip a little to ensure we are past any Start Signal
1576 firstFullWave = 160;
1577 memset(dest, curPhase, firstFullWave / *clock);
1578 } else {
1579 memset(dest, curPhase^1, firstFullWave / *clock);
1580 }
1581 //advance bits
1582 numBits += (firstFullWave / *clock);
1583 *startIdx = firstFullWave - (*clock * numBits)+2;
1584 //set start of wave as clock align
1585 lastClkBit = firstFullWave;
1586 if (g_debugMode==2) prnt("DEBUG PSK: firstFullWave: %u, waveLen: %u, startIdx %i",firstFullWave,fullWaveLen, *startIdx);
1587 if (g_debugMode==2) prnt("DEBUG PSK: clk: %d, lastClkBit: %u, fc: %u", *clock, lastClkBit,(unsigned int) fc);
1588 waveStart = 0;
1589 dest[numBits++] = curPhase; //set first read bit
1590 for (i = firstFullWave + fullWaveLen - 1; i < *size-3; i++){
1591 //top edge of wave = start of new wave
1592 if (dest[i]+fc < dest[i+1] && dest[i+1] >= dest[i+2]){
1593 if (waveStart == 0) {
1594 waveStart = i+1;
1595 waveLenCnt = 0;
1596 avgWaveVal = dest[i+1];
1597 } else { //waveEnd
1598 waveEnd = i+1;
1599 waveLenCnt = waveEnd-waveStart;
d5051b98 1600 if (waveLenCnt > fc){
d5051b98 1601 //this wave is a phase shift
1602 //PrintAndLog("DEBUG: phase shift at: %d, len: %d, nextClk: %d, i: %d, fc: %d",waveStart,waveLenCnt,lastClkBit+*clock-tol,i+1,fc);
1603 if (i+1 >= lastClkBit + *clock - tol){ //should be a clock bit
1604 curPhase ^= 1;
1605 dest[numBits++] = curPhase;
1606 lastClkBit += *clock;
1607 } else if (i < lastClkBit+10+fc){
1608 //noise after a phase shift - ignore
1609 } else { //phase shift before supposed to based on clock
1610 errCnt++;
1611 dest[numBits++] = 7;
1612 }
1613 } else if (i+1 > lastClkBit + *clock + tol + fc){
1614 lastClkBit += *clock; //no phase shift but clock bit
1615 dest[numBits++] = curPhase;
1616 } else if (waveLenCnt < fc - 1) { //wave is smaller than field clock (shouldn't happen often)
1617 errCnt2++;
1618 if(errCnt2 > 101) return errCnt2;
e0165dcf 1619 }
d5051b98 1620 avgWaveVal = 0;
1621 waveStart = i+1;
e0165dcf 1622 }
1623 }
d5051b98 1624 avgWaveVal += dest[i+1];
e0165dcf 1625 }
d5051b98 1626 *size = numBits;
1627 return errCnt;
03e6bb4a 1628}
1e090a61 1629
d5051b98 1630int pskRawDemod(uint8_t dest[], size_t *size, int *clock, int *invert) {
1631 int startIdx = 0;
1632 return pskRawDemod_ext(dest, size, clock, invert, &startIdx);
669959bc 1633}
1634
d5051b98 1635//**********************************************************************************************
1636//-----------------Tag format detection section-------------------------------------------------
1637//**********************************************************************************************
4d3c1796 1638
1639// by marshmellow
1640// FSK Demod then try to locate an AWID ID
1641int AWIDdemodFSK(uint8_t *dest, size_t *size) {
1642 //make sure buffer has enough data
1643 if (*size < 96*50) return -1;
1644
1645 if (justNoise(dest, *size)) return -2;
1646
1647 // FSK demodulator
1648 *size = fskdemod(dest, *size, 50, 1, 10, 8); // fsk2a RF/50
1649 if (*size < 96) return -3; //did we get a good demod?
1650
1651 uint8_t preamble[] = {0,0,0,0,0,0,0,1};
1652 size_t startIdx = 0;
1653 uint8_t errChk = preambleSearch(dest, preamble, sizeof(preamble), size, &startIdx);
1654 if (errChk == 0) return -4; //preamble not found
1655 if (*size != 96) return -5;
1656 return (int)startIdx;
1657}
1658
03e6bb4a 1659//by marshmellow
4d3c1796 1660//takes 1s and 0s and searches for EM410x format - output EM ID
1661uint8_t Em410xDecode(uint8_t *BitStream, size_t *size, size_t *startIdx, uint32_t *hi, uint64_t *lo)
03e6bb4a 1662{
4d3c1796 1663 //sanity checks
1664 if (*size < 64) return 0;
1665 if (BitStream[1]>1) return 0; //allow only 1s and 0s
e0165dcf 1666
4d3c1796 1667 // 111111111 bit pattern represent start of frame
1668 // include 0 in front to help get start pos
1669 uint8_t preamble[] = {0,1,1,1,1,1,1,1,1,1};
1670 uint8_t errChk = 0;
1671 uint8_t FmtLen = 10; // sets of 4 bits = end data
1672 *startIdx = 0;
1673 errChk = preambleSearch(BitStream, preamble, sizeof(preamble), size, startIdx);
1674 if ( errChk == 0 || (*size != 64 && *size != 128) ) return 0;
1675 if (*size == 128) FmtLen = 22; // 22 sets of 4 bits
e0165dcf 1676
4d3c1796 1677 //skip last 4bit parity row for simplicity
1678 *size = removeParity(BitStream, *startIdx + sizeof(preamble), 5, 0, FmtLen * 5);
1679 if (*size == 40) { // std em410x format
1680 *hi = 0;
1681 *lo = ((uint64_t)(bytebits_to_byte(BitStream, 8)) << 32) | (bytebits_to_byte(BitStream + 8, 32));
1682 } else if (*size == 88) { // long em format
1683 *hi = (bytebits_to_byte(BitStream, 24));
1684 *lo = ((uint64_t)(bytebits_to_byte(BitStream + 24, 32)) << 32) | (bytebits_to_byte(BitStream + 24 + 32, 32));
1685 } else {
f2ea55fb 1686 if (g_debugMode) prnt("Error removing parity: %u", *size);
4d3c1796 1687 return 0;
709665b5 1688 }
4d3c1796 1689 return 1;
6de43508 1690}
1691
4d3c1796 1692// Ask/Biphase Demod then try to locate an ISO 11784/85 ID
1693// BitStream must contain previously askrawdemod and biphasedemoded data
1694int FDXBdemodBI(uint8_t *dest, size_t *size) {
1695 //make sure buffer has enough data
1696 if (*size < 128) return -1;
e0165dcf 1697
4d3c1796 1698 size_t startIdx = 0;
1699 uint8_t preamble[] = {0,0,0,0,0,0,0,0,0,0,1};
6980d66b 1700
4d3c1796 1701 uint8_t errChk = preambleSearch(dest, preamble, sizeof(preamble), size, &startIdx);
1702 if (errChk == 0) return -2; //preamble not found
4db6f3bb 1703 if (*size != 128) return -3; //wrong size for fdxb
1704 //return start position
4d3c1796 1705 return (int)startIdx;
1706}
6980d66b 1707
4d3c1796 1708// by marshmellow
1709// demod gProxIIDemod
1710// error returns as -x
1711// success returns start position in BitStream
1712// BitStream must contain previously askrawdemod and biphasedemoded data
1713int gProxII_Demod(uint8_t BitStream[], size_t *size) {
1714 size_t startIdx=0;
1715 uint8_t preamble[] = {1,1,1,1,1,0};
669959bc 1716
4d3c1796 1717 uint8_t errChk = preambleSearch(BitStream, preamble, sizeof(preamble), size, &startIdx);
1718 if (errChk == 0) return -3; //preamble not found
1719 if (*size != 96) return -2; //should have found 96 bits
1720 //check first 6 spacer bits to verify format
1721 if (!BitStream[startIdx+5] && !BitStream[startIdx+10] && !BitStream[startIdx+15] && !BitStream[startIdx+20] && !BitStream[startIdx+25] && !BitStream[startIdx+30]){
1722 //confirmed proper separator bits found
1723 //return start position
1724 return (int) startIdx;
e0165dcf 1725 }
4d3c1796 1726 return -5; //spacer bits not found - not a valid gproxII
ab812dfa 1727}
1728
4d3c1796 1729// loop to get raw HID waveform then FSK demodulate the TAG ID from it
1730int HIDdemodFSK(uint8_t *dest, size_t *size, uint32_t *hi2, uint32_t *hi, uint32_t *lo) {
1731 if (justNoise(dest, *size)) return -1;
d1869c33 1732
4d3c1796 1733 size_t numStart=0, size2=*size, startIdx=0;
1734 // FSK demodulator
1735 *size = fskdemod(dest, size2,50,1,10,8); //fsk2a
1736 if (*size < 96*2) return -2;
1737 // 00011101 bit pattern represent start of frame, 01 pattern represents a 0 and 10 represents a 1
1738 uint8_t preamble[] = {0,0,0,1,1,1,0,1};
1739 // find bitstring in array
1740 uint8_t errChk = preambleSearch(dest, preamble, sizeof(preamble), size, &startIdx);
1741 if (errChk == 0) return -3; //preamble not found
d1869c33 1742
4d3c1796 1743 numStart = startIdx + sizeof(preamble);
1744 // final loop, go over previously decoded FSK data and manchester decode into usable tag ID
1745 for (size_t idx = numStart; (idx-numStart) < *size - sizeof(preamble); idx+=2){
1746 if (dest[idx] == dest[idx+1]){
1747 return -4; //not manchester data
d1869c33 1748 }
4d3c1796 1749 *hi2 = (*hi2<<1)|(*hi>>31);
1750 *hi = (*hi<<1)|(*lo>>31);
1751 //Then, shift in a 0 or one into low
1752 if (dest[idx] && !dest[idx+1]) // 1 0
1753 *lo=(*lo<<1)|1;
1754 else // 0 1
1755 *lo=(*lo<<1)|0;
d1869c33 1756 }
4d3c1796 1757 return (int)startIdx;
1758}
d1869c33 1759
4d3c1796 1760int IOdemodFSK(uint8_t *dest, size_t size) {
1761 if (justNoise(dest, size)) return -1;
1762 //make sure buffer has data
1763 if (size < 66*64) return -2;
1764 // FSK demodulator
1765 size = fskdemod(dest, size, 64, 1, 10, 8); // FSK2a RF/64
1766 if (size < 65) return -3; //did we get a good demod?
1767 //Index map
1768 //0 10 20 30 40 50 60
1769 //| | | | | | |
1770 //01234567 8 90123456 7 89012345 6 78901234 5 67890123 4 56789012 3 45678901 23
1771 //-----------------------------------------------------------------------------
1772 //00000000 0 11110000 1 facility 1 version* 1 code*one 1 code*two 1 ???????? 11
1773 //
1774 //XSF(version)facility:codeone+codetwo
1775 //Handle the data
1776 size_t startIdx = 0;
1777 uint8_t preamble[] = {0,0,0,0,0,0,0,0,0,1};
1778 uint8_t errChk = preambleSearch(dest, preamble, sizeof(preamble), &size, &startIdx);
1779 if (errChk == 0) return -4; //preamble not found
d1869c33 1780
4d3c1796 1781 if (!dest[startIdx+8] && dest[startIdx+17]==1 && dest[startIdx+26]==1 && dest[startIdx+35]==1 && dest[startIdx+44]==1 && dest[startIdx+53]==1){
1782 //confirmed proper separator bits found
1783 //return start position
1784 return (int) startIdx;
d1869c33 1785 }
4d3c1796 1786 return -5;
1787}
d1869c33 1788
4d3c1796 1789// redesigned by marshmellow adjusted from existing decode functions
1790// indala id decoding - only tested on 26 bit tags, but attempted to make it work for more
1791int indala26decode(uint8_t *bitStream, size_t *size, uint8_t *invert) {
1792 //26 bit 40134 format (don't know other formats)
1793 uint8_t preamble[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};
1794 uint8_t preamble_i[] = {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0};
1795 size_t startidx = 0;
1796 if (!preambleSearch(bitStream, preamble, sizeof(preamble), size, &startidx)){
1797 // if didn't find preamble try again inverting
1798 if (!preambleSearch(bitStream, preamble_i, sizeof(preamble_i), size, &startidx)) return -1;
1799 *invert ^= 1;
1800 }
1801 if (*size != 64 && *size != 224) return -2;
1802 if (*invert==1)
1803 for (size_t i = startidx; i < *size; i++)
1804 bitStream[i] ^= 1;
1805
1806 return (int) startidx;
1807}
1808
1809// loop to get raw paradox waveform then FSK demodulate the TAG ID from it
1810int ParadoxdemodFSK(uint8_t *dest, size_t *size, uint32_t *hi2, uint32_t *hi, uint32_t *lo) {
1811 if (justNoise(dest, *size)) return -1;
01d0f8ae 1812
4d3c1796 1813 size_t numStart=0, size2=*size, startIdx=0;
1814 // FSK demodulator
1815 *size = fskdemod(dest, size2,50,1,10,8); //fsk2a
1816 if (*size < 96) return -2;
d1869c33 1817
4d3c1796 1818 // 00001111 bit pattern represent start of frame, 01 pattern represents a 0 and 10 represents a 1
1819 uint8_t preamble[] = {0,0,0,0,1,1,1,1};
1820
1821 uint8_t errChk = preambleSearch(dest, preamble, sizeof(preamble), size, &startIdx);
1822 if (errChk == 0) return -3; //preamble not found
1823
1824 numStart = startIdx + sizeof(preamble);
1825 // final loop, go over previously decoded FSK data and manchester decode into usable tag ID
1826 for (size_t idx = numStart; (idx-numStart) < *size - sizeof(preamble); idx+=2){
1827 if (dest[idx] == dest[idx+1])
1828 return -4; //not manchester data
1829 *hi2 = (*hi2<<1)|(*hi>>31);
1830 *hi = (*hi<<1)|(*lo>>31);
1831 //Then, shift in a 0 or one into low
1832 if (dest[idx] && !dest[idx+1]) // 1 0
1833 *lo=(*lo<<1)|1;
1834 else // 0 1
1835 *lo=(*lo<<1)|0;
d1869c33 1836 }
4d3c1796 1837 return (int)startIdx;
d1869c33 1838}
8b6abef5 1839
4d3c1796 1840// find presco preamble 0x10D in already demoded data
1841int PrescoDemod(uint8_t *dest, size_t *size) {
1842 //make sure buffer has data
1843 if (*size < 64*2) return -2;
1844
1845 size_t startIdx = 0;
1846 uint8_t preamble[] = {1,0,0,0,0,1,1,0,1,0,0,0,0,0,0,0,0,0,0,0};
1847 uint8_t errChk = preambleSearch(dest, preamble, sizeof(preamble), size, &startIdx);
1848 if (errChk == 0) return -4; //preamble not found
1849 //return start position
1850 return (int) startIdx;
669959bc 1851}
1852
4d3c1796 1853// by marshmellow
1854// FSK Demod then try to locate a Farpointe Data (pyramid) ID
1855int PyramiddemodFSK(uint8_t *dest, size_t *size) {
1856 //make sure buffer has data
1857 if (*size < 128*50) return -5;
1858
1859 //test samples are not just noise
1860 if (justNoise(dest, *size)) return -1;
1861
1862 // FSK demodulator
1863 *size = fskdemod(dest, *size, 50, 1, 10, 8); // fsk2a RF/50
1864 if (*size < 128) return -2; //did we get a good demod?
1865
1866 uint8_t preamble[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};
1867 size_t startIdx = 0;
1868 uint8_t errChk = preambleSearch(dest, preamble, sizeof(preamble), size, &startIdx);
1869 if (errChk == 0) return -4; //preamble not found
1870 if (*size != 128) return -3;
1871 return (int)startIdx;
1872}
1873
1874// by marshmellow
1875// find viking preamble 0xF200 in already demoded data
1876int VikingDemod_AM(uint8_t *dest, size_t *size) {
1877 //make sure buffer has data
1878 if (*size < 64*2) return -2;
1879
1880 size_t startIdx = 0;
1881 uint8_t preamble[] = {1,1,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
1882 uint8_t errChk = preambleSearch(dest, preamble, sizeof(preamble), size, &startIdx);
1883 if (errChk == 0) return -4; //preamble not found
1884 uint32_t checkCalc = bytebits_to_byte(dest+startIdx,8) ^ bytebits_to_byte(dest+startIdx+8,8) ^ bytebits_to_byte(dest+startIdx+16,8)
1885 ^ bytebits_to_byte(dest+startIdx+24,8) ^ bytebits_to_byte(dest+startIdx+32,8) ^ bytebits_to_byte(dest+startIdx+40,8)
1886 ^ bytebits_to_byte(dest+startIdx+48,8) ^ bytebits_to_byte(dest+startIdx+56,8);
1887 if ( checkCalc != 0xA8 ) return -5;
1888 if (*size != 64) return -6;
1889 //return start position
1890 return (int) startIdx;
1891}
1892
8b6abef5 1893// by iceman
1894// find Visa2000 preamble in already demoded data
1895int Visa2kDemod_AM(uint8_t *dest, size_t *size) {
1896 if (*size < 96) return -1; //make sure buffer has data
1897 size_t startIdx = 0;
1898 uint8_t preamble[] = {0,1,0,1,0,1,1,0,0,1,0,0,1,0,0,1,0,1,0,1,0,0,1,1,0,0,1,1,0,0,1,0};
1899 if (preambleSearch(dest, preamble, sizeof(preamble), size, &startIdx) == 0)
1900 return -2; //preamble not found
1901 if (*size != 96) return -3; //wrong demoded size
1902 //return start position
1903 return (int)startIdx;
1904}
Impressum, Datenschutz