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