]> git.zerfleddert.de Git - proxmark3-svn/blame - common/lfdemod.c
lfem4x cleanup/add/fix
[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
eb191de6 9//-----------------------------------------------------------------------------
10
eb191de6 11#include <stdlib.h>
12#include <string.h>
eb191de6 13#include "lfdemod.h"
a1d17964 14uint8_t justNoise(uint8_t *BitStream, size_t size)
15{
16 static const uint8_t THRESHOLD = 123;
17 //test samples are not just noise
18 uint8_t justNoise1 = 1;
19 for(size_t idx=0; idx < size && justNoise1 ;idx++){
20 justNoise1 = BitStream[idx] < THRESHOLD;
21 }
22 return justNoise1;
23}
24
1e090a61 25//by marshmellow
872e3d4d 26//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 27int getHiLo(uint8_t *BitStream, size_t size, int *high, int *low, uint8_t fuzzHi, uint8_t fuzzLo)
28{
29 *high=0;
30 *low=255;
31 // get high and low thresholds
2eec55c8 32 for (size_t i=0; i < size; i++){
1e090a61 33 if (BitStream[i] > *high) *high = BitStream[i];
34 if (BitStream[i] < *low) *low = BitStream[i];
35 }
36 if (*high < 123) return -1; // just noise
75cbbe9a 37 *high = ((*high-128)*fuzzHi + 12800)/100;
38 *low = ((*low-128)*fuzzLo + 12800)/100;
1e090a61 39 return 1;
40}
41
a1d17964 42// by marshmellow
43// pass bits to be tested in bits, length bits passed in bitLen, and parity type (even=0 | odd=1) in pType
44// returns 1 if passed
45uint8_t parityTest(uint32_t bits, uint8_t bitLen, uint8_t pType)
46{
47 uint8_t ans = 0;
48 for (uint8_t i = 0; i < bitLen; i++){
49 ans ^= ((bits >> i) & 1);
50 }
f3bf15e4 51 //PrintAndLog("DEBUG: ans: %d, ptype: %d",ans,pType);
a1d17964 52 return (ans == pType);
53}
54
55//by marshmellow
2147c307 56//search for given preamble in given BitStream and return success=1 or fail=0 and startIndex and length
a1d17964 57uint8_t preambleSearch(uint8_t *BitStream, uint8_t *preamble, size_t pLen, size_t *size, size_t *startIdx)
58{
e0165dcf 59 uint8_t foundCnt=0;
60 for (int idx=0; idx < *size - pLen; idx++){
61 if (memcmp(BitStream+idx, preamble, pLen) == 0){
62 //first index found
63 foundCnt++;
64 if (foundCnt == 1){
65 *startIdx = idx;
66 }
67 if (foundCnt == 2){
68 *size = idx - *startIdx;
69 return 1;
70 }
71 }
72 }
73 return 0;
a1d17964 74}
75
2147c307 76//by marshmellow
77//takes 1s and 0s and searches for EM410x format - output EM ID
78uint8_t Em410xDecode(uint8_t *BitStream, size_t *size, size_t *startIdx, uint32_t *hi, uint64_t *lo)
79{
e0165dcf 80 //no arguments needed - built this way in case we want this to be a direct call from "data " cmds in the future
81 // otherwise could be a void with no arguments
82 //set defaults
83 uint32_t i = 0;
84 if (BitStream[1]>1){ //allow only 1s and 0s
85 // PrintAndLog("no data found");
86 return 0;
87 }
88 // 111111111 bit pattern represent start of frame
89 // include 0 in front to help get start pos
90 uint8_t preamble[] = {0,1,1,1,1,1,1,1,1,1};
91 uint32_t idx = 0;
92 uint32_t parityBits = 0;
93 uint8_t errChk = 0;
94 uint8_t FmtLen = 10;
95 *startIdx = 0;
96 errChk = preambleSearch(BitStream, preamble, sizeof(preamble), size, startIdx);
97 if (errChk == 0 || *size < 64) return 0;
98 if (*size > 64) FmtLen = 22;
99 *startIdx += 1; //get rid of 0 from preamble
100 idx = *startIdx + 9;
101 for (i=0; i<FmtLen; i++){ //loop through 10 or 22 sets of 5 bits (50-10p = 40 bits or 88 bits)
102 parityBits = bytebits_to_byte(BitStream+(i*5)+idx,5);
2eec55c8 103 //check even parity - quit if failed
104 if (parityTest(parityBits, 5, 0) == 0) return 0;
e0165dcf 105 //set uint64 with ID from BitStream
106 for (uint8_t ii=0; ii<4; ii++){
107 *hi = (*hi << 1) | (*lo >> 63);
108 *lo = (*lo << 1) | (BitStream[(i*5)+ii+idx]);
109 }
110 }
111 if (errChk != 0) return 1;
112 //skip last 5 bit parity test for simplicity.
113 // *size = 64 | 128;
114 return 0;
2147c307 115}
116
23f0a7d8 117// demodulates strong heavily clipped samples
118int cleanAskRawDemod(uint8_t *BinStream, size_t *size, int clk, int invert, int high, int low)
119{
120 size_t bitCnt=0, smplCnt=0, errCnt=0;
121 uint8_t waveHigh = 0;
122 //PrintAndLog("clk: %d", clk);
123 for (size_t i=0; i < *size; i++){
124 if (BinStream[i] >= high && waveHigh){
125 smplCnt++;
126 } else if (BinStream[i] <= low && !waveHigh){
127 smplCnt++;
128 } else { //transition
129 if ((BinStream[i] >= high && !waveHigh) || (BinStream[i] <= low && waveHigh)){
130 if (smplCnt > clk-(clk/4)-1) { //full clock
131 if (smplCnt > clk + (clk/4)+1) { //too many samples
132 errCnt++;
133 BinStream[bitCnt++]=77;
134 } else if (waveHigh) {
135 BinStream[bitCnt++] = invert;
136 BinStream[bitCnt++] = invert;
137 } else if (!waveHigh) {
138 BinStream[bitCnt++] = invert ^ 1;
139 BinStream[bitCnt++] = invert ^ 1;
140 }
141 waveHigh ^= 1;
142 smplCnt = 0;
143 } else if (smplCnt > (clk/2) - (clk/4)-1) {
144 if (waveHigh) {
145 BinStream[bitCnt++] = invert;
146 } else if (!waveHigh) {
147 BinStream[bitCnt++] = invert ^ 1;
148 }
149 waveHigh ^= 1;
150 smplCnt = 0;
151 } else if (!bitCnt) {
152 //first bit
153 waveHigh = (BinStream[i] >= high);
154 smplCnt = 1;
155 } else {
156 smplCnt++;
157 //transition bit oops
158 }
159 } else { //haven't hit new high or new low yet
160 smplCnt++;
161 }
162 }
163 }
164 *size = bitCnt;
165 return errCnt;
166}
167
eb191de6 168//by marshmellow
6de43508 169//takes 3 arguments - clock, invert, maxErr as integers
ba1a299c 170//attempts to demodulate ask while decoding manchester
eb191de6 171//prints binary found and saves in graphbuffer for further commands
6de43508 172int askmandemod(uint8_t *BinStream, size_t *size, int *clk, int *invert, int maxErr)
eb191de6 173{
2eec55c8 174 size_t i;
6de43508 175 int start = DetectASKClock(BinStream, *size, clk, 20); //clock default
2eec55c8 176 if (*clk==0 || start < 0) return -3;
177 if (*invert != 1) *invert=0;
178 uint8_t initLoopMax = 255;
179 if (initLoopMax > *size) initLoopMax = *size;
ba1a299c 180 // Detect high and lows
1e090a61 181 // 25% fuzz in case highs and lows aren't clipped [marshmellow]
2eec55c8 182 int high, low;
183 if (getHiLo(BinStream, initLoopMax, &high, &low, 75, 75) < 1) return -2; //just noise
ba1a299c 184
23f0a7d8 185 // if clean clipped waves detected run alternate demod
186 if (DetectCleanAskWave(BinStream, *size, high, low)) {
187 cleanAskRawDemod(BinStream, size, *clk, *invert, high, low);
188 return manrawdecode(BinStream, size);
189 }
190
191
1e090a61 192 // PrintAndLog("DEBUG - valid high: %d - valid low: %d",high,low);
ba1a299c 193 int lastBit = 0; //set first clock check
2eec55c8 194 uint16_t bitnum = 0; //output counter
195 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
196 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
197 size_t iii = 0;
2147c307 198 //if 0 errors allowed then only try first 2 clock cycles as we want a low tolerance
23f0a7d8 199 if (!maxErr && initLoopMax > *clk*3) initLoopMax = *clk * 3;
2eec55c8 200 uint16_t errCnt = 0, MaxBits = 512;
201 uint16_t bestStart = start;
202 uint16_t bestErrCnt = 0;
1e090a61 203 // PrintAndLog("DEBUG - lastbit - %d",lastBit);
2eec55c8 204 // if best start position not already found by detect clock then
205 if (start <= 0 || start > initLoopMax){
206 bestErrCnt = maxErr+1;
207 // loop to find first wave that works
23f0a7d8 208 for (iii=0; iii < initLoopMax-tol-*clk; ++iii){
2eec55c8 209 // if no peak skip
210 if (BinStream[iii] < high && BinStream[iii] > low) continue;
211
212 lastBit = iii - *clk;
1e090a61 213 // loop through to see if this start location works
ba1a299c 214 for (i = iii; i < *size; ++i) {
2eec55c8 215 if ((i-lastBit) > (*clk-tol) && (BinStream[i] >= high || BinStream[i] <= low)) {
216 lastBit += *clk;
217 } else if ((i-lastBit) > (*clk+tol)) {
218 errCnt++;
219 lastBit += *clk;
ba1a299c 220 }
2eec55c8 221 if ((i-iii) > (MaxBits * *clk) || errCnt > maxErr) break; //got plenty of bits or too many errors
ba1a299c 222 }
223 //we got more than 64 good bits and not all errors
23f0a7d8 224 if ((((i-iii)/ *clk) > (32)) && (errCnt<=maxErr)) {
ba1a299c 225 //possible good read
2eec55c8 226 if (!errCnt || errCnt < bestErrCnt){
227 bestStart = iii; //set this as new best run
228 bestErrCnt = errCnt;
229 if (!errCnt) break; //great read - finish
ba1a299c 230 }
231 }
2eec55c8 232 errCnt = 0;
ba1a299c 233 }
234 }
2eec55c8 235 if (bestErrCnt > maxErr){
236 *invert = bestStart;
237 *clk = iii;
ba1a299c 238 return -1;
2eec55c8 239 }
240 //best run is good enough set to best run and set overwrite BinStream
241 lastBit = bestStart - *clk;
242 errCnt = 0;
243 for (i = bestStart; i < *size; ++i) {
244 if ((BinStream[i] >= high) && ((i-lastBit) > (*clk-tol))){
245 //high found and we are expecting a bar
246 lastBit += *clk;
247 BinStream[bitnum++] = *invert;
248 } else if ((BinStream[i] <= low) && ((i-lastBit) > (*clk-tol))){
249 //low found and we are expecting a bar
250 lastBit += *clk;
251 BinStream[bitnum++] = *invert ^ 1;
252 } else if ((i-lastBit)>(*clk+tol)){
253 //should have hit a high or low based on clock!!
254 //PrintAndLog("DEBUG - no wave in expected area - location: %d, expected: %d-%d, lastBit: %d - resetting search",i,(lastBit+(clk-((int)(tol)))),(lastBit+(clk+((int)(tol)))),lastBit);
255 if (bitnum > 0) {
256 BinStream[bitnum++] = 77;
257 errCnt++;
258 }
259 lastBit += *clk;//skip over error
260 }
261 if (bitnum >= MaxBits) break;
ba1a299c 262 }
2eec55c8 263 *size = bitnum;
ba1a299c 264 return bestErrCnt;
eb191de6 265}
266
ec75f5c1 267//by marshmellow
268//encode binary data into binary manchester
269int ManchesterEncode(uint8_t *BitStream, size_t size)
270{
271 size_t modIdx=20000, i=0;
272 if (size>modIdx) return -1;
f3bf15e4 273 for (size_t idx=0; idx < size; idx++){
274 BitStream[idx+modIdx++] = BitStream[idx];
275 BitStream[idx+modIdx++] = BitStream[idx]^1;
276 }
277 for (; i<(size*2); i++){
278 BitStream[i] = BitStream[i+20000];
279 }
280 return i;
ec75f5c1 281}
282
eb191de6 283//by marshmellow
284//take 10 and 01 and manchester decode
285//run through 2 times and take least errCnt
ba1a299c 286int manrawdecode(uint8_t * BitStream, size_t *size)
eb191de6 287{
13d77ef9 288 uint16_t bitnum=0, MaxBits = 512, errCnt = 0;
289 size_t i, ii;
290 uint16_t bestErr = 1000, bestRun = 0;
6de43508 291 if (size == 0) return -1;
13d77ef9 292 for (ii=0;ii<2;++ii){
2eec55c8 293 for (i=ii; i<*size-2; i+=2)
294 if (BitStream[i]==BitStream[i+1])
ba1a299c 295 errCnt++;
2eec55c8 296
ba1a299c 297 if (bestErr>errCnt){
298 bestErr=errCnt;
299 bestRun=ii;
300 }
301 errCnt=0;
302 }
23f0a7d8 303 for (i=bestRun; i < *size-2; i+=2){
304 if(BitStream[i] == 1 && (BitStream[i+1] == 0)){
305 BitStream[bitnum++]=0;
306 } else if((BitStream[i] == 0) && BitStream[i+1] == 1){
307 BitStream[bitnum++]=1;
308 } else {
309 BitStream[bitnum++]=77;
ba1a299c 310 }
23f0a7d8 311 if(bitnum>MaxBits) break;
ba1a299c 312 }
23f0a7d8 313 *size=bitnum;
2eec55c8 314 return bestErr;
f822a063 315}
316
f822a063 317//by marshmellow
2147c307 318//take 01 or 10 = 1 and 11 or 00 = 0
319//check for phase errors - should never have 111 or 000 should be 01001011 or 10110100 for 1010
13d77ef9 320//decodes biphase or if inverted it is AKA conditional dephase encoding AKA differential manchester encoding
1e090a61 321int BiphaseRawDecode(uint8_t *BitStream, size_t *size, int offset, int invert)
f822a063 322{
2eec55c8 323 uint16_t bitnum = 0;
324 uint16_t errCnt = 0;
325 size_t i = offset;
2147c307 326 uint16_t MaxBits=512;
327 //if not enough samples - error
328 if (*size < 51) return -1;
329 //check for phase change faults - skip one sample if faulty
330 uint8_t offsetA = 1, offsetB = 1;
331 for (; i<48; i+=2){
332 if (BitStream[i+1]==BitStream[i+2]) offsetA=0;
333 if (BitStream[i+2]==BitStream[i+3]) offsetB=0;
334 }
335 if (!offsetA && offsetB) offset++;
336 for (i=offset; i<*size-3; i+=2){
337 //check for phase error
13d77ef9 338 if (BitStream[i+1]==BitStream[i+2]) {
2147c307 339 BitStream[bitnum++]=77;
340 errCnt++;
341 }
ba1a299c 342 if((BitStream[i]==1 && BitStream[i+1]==0) || (BitStream[i]==0 && BitStream[i+1]==1)){
1e090a61 343 BitStream[bitnum++]=1^invert;
ba1a299c 344 } else if((BitStream[i]==0 && BitStream[i+1]==0) || (BitStream[i]==1 && BitStream[i+1]==1)){
1e090a61 345 BitStream[bitnum++]=invert;
ba1a299c 346 } else {
347 BitStream[bitnum++]=77;
348 errCnt++;
349 }
6de43508 350 if(bitnum>MaxBits) break;
ba1a299c 351 }
352 *size=bitnum;
353 return errCnt;
eb191de6 354}
355
356//by marshmellow
6de43508 357void askAmp(uint8_t *BitStream, size_t size)
358{
f3bf15e4 359 int shift = 127;
360 int shiftedVal=0;
2eec55c8 361 for(size_t i = 1; i<size; i++){
f3bf15e4 362 if (BitStream[i]-BitStream[i-1]>=30) //large jump up
363 shift=127;
364 else if(BitStream[i]-BitStream[i-1]<=-20) //large jump down
365 shift=-127;
366
367 shiftedVal=BitStream[i]+shift;
368
369 if (shiftedVal>255)
370 shiftedVal=255;
371 else if (shiftedVal<0)
372 shiftedVal=0;
373 BitStream[i-1] = shiftedVal;
374 }
375 return;
6de43508 376}
377
378//by marshmellow
379//takes 3 arguments - clock, invert and maxErr as integers
eb191de6 380//attempts to demodulate ask only
6de43508 381int askrawdemod(uint8_t *BinStream, size_t *size, int *clk, int *invert, int maxErr, uint8_t amp)
eb191de6 382{
6de43508 383 if (*size==0) return -1;
384 int start = DetectASKClock(BinStream, *size, clk, 20); //clock default
2eec55c8 385 if (*clk==0 || start < 0) return -1;
386 if (*invert != 1) *invert = 0;
13d77ef9 387 if (amp==1) askAmp(BinStream, *size);
388
2eec55c8 389 uint8_t initLoopMax = 255;
c12512e9 390 if (initLoopMax > *size) initLoopMax=*size;
ba1a299c 391 // Detect high and lows
13d77ef9 392 //25% clip in case highs and lows aren't clipped [marshmellow]
2eec55c8 393 int high, low;
394 if (getHiLo(BinStream, initLoopMax, &high, &low, 75, 75) < 1)
395 return -1; //just noise
ba1a299c 396
2eec55c8 397 // if clean clipped waves detected run alternate demod
398 if (DetectCleanAskWave(BinStream, *size, high, low))
13d77ef9 399 return cleanAskRawDemod(BinStream, size, *clk, *invert, high, low);
13d77ef9 400
2eec55c8 401 int lastBit = 0; //set first clock check - can go negative
402 size_t i, iii = 0;
403 size_t errCnt = 0, bitnum = 0; //output counter
404 uint8_t midBit = 0;
405 size_t bestStart = start, bestErrCnt = 0; //(*size/1000);
406 size_t MaxBits = 1024;
ba1a299c 407
2eec55c8 408 //if 0 errors allowed then only try first 2 clock cycles as we want a low tolerance
23f0a7d8 409 if (!maxErr && initLoopMax > *clk*3) initLoopMax = *clk * 3;
2eec55c8 410 //if best start not already found by detectclock
411 if (start <= 0 || start > initLoopMax){
412 bestErrCnt = maxErr+1;
413 //PrintAndLog("DEBUG - lastbit - %d",lastBit);
414 //loop to find first wave that works
23f0a7d8 415 for (iii=0; iii < initLoopMax - *clk; ++iii){
2eec55c8 416 if ((BinStream[iii] >= high) || (BinStream[iii] <= low)){
417 lastBit = iii - *clk;
418 //loop through to see if this start location works
419 for (i = iii; i < *size; ++i) {
420 if (i-lastBit > *clk && (BinStream[i] >= high || BinStream[i] <= low)){
421 lastBit += *clk;
422 midBit = 0;
423 } else if (i-lastBit > (*clk/2) && midBit == 0) {
424 midBit = 1;
425 } else if ((i-lastBit) > *clk) {
ba1a299c 426 //should have hit a high or low based on clock!!
ba1a299c 427 //PrintAndLog("DEBUG - no wave in expected area - location: %d, expected: %d-%d, lastBit: %d - resetting search",i,(lastBit+(clk-((int)(tol)))),(lastBit+(clk+((int)(tol)))),lastBit);
ba1a299c 428 errCnt++;
2eec55c8 429 lastBit += *clk;//skip over until hit too many errors
430 if (errCnt > maxErr)
ba1a299c 431 break;
ba1a299c 432 }
2eec55c8 433 if ((i-iii)>(MaxBits * *clk)) break; //got enough bits
ba1a299c 434 }
23f0a7d8 435 //we got more than 32 good bits and not all errors
436 if ((((i-iii)/ *clk) > 32) && (errCnt<=maxErr)) {
2eec55c8 437 //possible good read
438 if (errCnt==0){
439 bestStart=iii;
440 bestErrCnt=errCnt;
441 break; //great read - finish
442 }
443 if (errCnt<bestErrCnt){ //set this as new best run
444 bestErrCnt=errCnt;
445 bestStart = iii;
446 }
ba1a299c 447 }
2eec55c8 448 errCnt=0;
ba1a299c 449 }
450 }
ba1a299c 451 }
2eec55c8 452 if (bestErrCnt > maxErr){
453 *invert = bestStart;
454 *clk = iii;
455 return -1;
456 }
457 //best run is good enough - set to best run and overwrite BinStream
458 lastBit = bestStart - *clk - 1;
459 errCnt = 0;
460
461 for (i = bestStart; i < *size; ++i) {
462 if (i - lastBit > *clk){
463 if (BinStream[i] >= high) {
464 BinStream[bitnum++] = *invert;
465 } else if (BinStream[i] <= low) {
466 BinStream[bitnum++] = *invert ^ 1;
1e090a61 467 } else {
2eec55c8 468 if (bitnum > 0) {
469 BinStream[bitnum++]=77;
470 errCnt++;
471 }
472 }
473 midBit = 0;
474 lastBit += *clk;
475 } else if (i-lastBit > (*clk/2) && midBit == 0){
476 if (BinStream[i] >= high) {
477 BinStream[bitnum++] = *invert;
478 } else if (BinStream[i] <= low) {
479 BinStream[bitnum++] = *invert ^ 1;
480 } else {
481
482 BinStream[bitnum] = BinStream[bitnum-1];
483 bitnum++;
1e090a61 484 }
2eec55c8 485 midBit = 1;
ba1a299c 486 }
2eec55c8 487 if (bitnum >= MaxBits) break;
1e090a61 488 }
2eec55c8 489 *size = bitnum;
490 return errCnt;
eb191de6 491}
11081e04 492
493// demod gProxIIDemod
494// error returns as -x
495// success returns start position in BitStream
496// BitStream must contain previously askrawdemod and biphasedemoded data
497int gProxII_Demod(uint8_t BitStream[], size_t *size)
498{
499 size_t startIdx=0;
500 uint8_t preamble[] = {1,1,1,1,1,0};
501
502 uint8_t errChk = preambleSearch(BitStream, preamble, sizeof(preamble), size, &startIdx);
503 if (errChk == 0) return -3; //preamble not found
504 if (*size != 96) return -2; //should have found 96 bits
505 //check first 6 spacer bits to verify format
506 if (!BitStream[startIdx+5] && !BitStream[startIdx+10] && !BitStream[startIdx+15] && !BitStream[startIdx+20] && !BitStream[startIdx+25] && !BitStream[startIdx+30]){
507 //confirmed proper separator bits found
508 //return start position
509 return (int) startIdx;
510 }
511 return -5;
512}
513
ba1a299c 514//translate wave to 11111100000 (1 for each short wave 0 for each long wave)
f822a063 515size_t fsk_wave_demod(uint8_t * dest, size_t size, uint8_t fchigh, uint8_t fclow)
eb191de6 516{
2eec55c8 517 size_t last_transition = 0;
518 size_t idx = 1;
ac3ba7ee 519 //uint32_t maxVal=0;
ba1a299c 520 if (fchigh==0) fchigh=10;
521 if (fclow==0) fclow=8;
84871873 522 //set the threshold close to 0 (graph) or 128 std to avoid static
523 uint8_t threshold_value = 123;
ba1a299c 524
525 // sync to first lo-hi transition, and threshold
526
527 // Need to threshold first sample
528
529 if(dest[0] < threshold_value) dest[0] = 0;
530 else dest[0] = 1;
531
532 size_t numBits = 0;
533 // count cycles between consecutive lo-hi transitions, there should be either 8 (fc/8)
534 // or 10 (fc/10) cycles but in practice due to noise etc we may end up with with anywhere
535 // between 7 to 11 cycles so fuzz it by treat anything <9 as 8 and anything else as 10
536 for(idx = 1; idx < size; idx++) {
537 // threshold current value
538
539 if (dest[idx] < threshold_value) dest[idx] = 0;
540 else dest[idx] = 1;
541
542 // Check for 0->1 transition
543 if (dest[idx-1] < dest[idx]) { // 0 -> 1 transition
544 if ((idx-last_transition)<(fclow-2)){ //0-5 = garbage noise
545 //do nothing with extra garbage
546 } else if ((idx-last_transition) < (fchigh-1)) { //6-8 = 8 waves
2eec55c8 547 dest[numBits++]=1;
13d77ef9 548 } else if ((idx-last_transition) > (fchigh+1) && !numBits) { //12 + and first bit = garbage
549 //do nothing with beginning garbage
550 } else { //9+ = 10 waves
2eec55c8 551 dest[numBits++]=0;
ba1a299c 552 }
553 last_transition = idx;
ba1a299c 554 }
555 }
556 return numBits; //Actually, it returns the number of bytes, but each byte represents a bit: 1 or 0
eb191de6 557}
558
ba1a299c 559//translate 11111100000 to 10
2eec55c8 560size_t aggregate_bits(uint8_t *dest, size_t size, uint8_t rfLen,
e0165dcf 561 uint8_t invert, uint8_t fchigh, uint8_t fclow)
eb191de6 562{
ba1a299c 563 uint8_t lastval=dest[0];
2eec55c8 564 size_t idx=0;
ba1a299c 565 size_t numBits=0;
566 uint32_t n=1;
ba1a299c 567 for( idx=1; idx < size; idx++) {
13d77ef9 568 n++;
2eec55c8 569 if (dest[idx]==lastval) continue;
570
ba1a299c 571 //if lastval was 1, we have a 1->0 crossing
13d77ef9 572 if (dest[idx-1]==1) {
75cbbe9a 573 if (!numBits && n < rfLen/fclow) {
13d77ef9 574 n=0;
575 lastval = dest[idx];
576 continue;
577 }
75cbbe9a 578 n = (n * fclow + rfLen/2) / rfLen;
13d77ef9 579 } else {// 0->1 crossing
580 //test first bitsample too small
75cbbe9a 581 if (!numBits && n < rfLen/fchigh) {
13d77ef9 582 n=0;
583 lastval = dest[idx];
584 continue;
585 }
75cbbe9a 586 n = (n * fchigh + rfLen/2) / rfLen;
ba1a299c 587 }
588 if (n == 0) n = 1;
589
2eec55c8 590 memset(dest+numBits, dest[idx-1]^invert , n);
591 numBits += n;
ba1a299c 592 n=0;
593 lastval=dest[idx];
594 }//end for
13d77ef9 595 // if valid extra bits at the end were all the same frequency - add them in
75cbbe9a 596 if (n > rfLen/fchigh) {
13d77ef9 597 if (dest[idx-2]==1) {
75cbbe9a 598 n = (n * fclow + rfLen/2) / rfLen;
13d77ef9 599 } else {
75cbbe9a 600 n = (n * fchigh + rfLen/2) / rfLen;
13d77ef9 601 }
2eec55c8 602 memset(dest+numBits, dest[idx-1]^invert , n);
13d77ef9 603 numBits += n;
604 }
ba1a299c 605 return numBits;
eb191de6 606}
607//by marshmellow (from holiman's base)
608// full fsk demod from GraphBuffer wave to decoded 1s and 0s (no mandemod)
f822a063 609int fskdemod(uint8_t *dest, size_t size, uint8_t rfLen, uint8_t invert, uint8_t fchigh, uint8_t fclow)
eb191de6 610{
ba1a299c 611 // FSK demodulator
612 size = fsk_wave_demod(dest, size, fchigh, fclow);
2eec55c8 613 size = aggregate_bits(dest, size, rfLen, invert, fchigh, fclow);
ba1a299c 614 return size;
eb191de6 615}
a1d17964 616
eb191de6 617// loop to get raw HID waveform then FSK demodulate the TAG ID from it
ec75f5c1 618int HIDdemodFSK(uint8_t *dest, size_t *size, uint32_t *hi2, uint32_t *hi, uint32_t *lo)
eb191de6 619{
e0165dcf 620 if (justNoise(dest, *size)) return -1;
621
622 size_t numStart=0, size2=*size, startIdx=0;
623 // FSK demodulator
624 *size = fskdemod(dest, size2,50,1,10,8); //fsk2a
2eec55c8 625 if (*size < 96*2) return -2;
e0165dcf 626 // 00011101 bit pattern represent start of frame, 01 pattern represents a 0 and 10 represents a 1
627 uint8_t preamble[] = {0,0,0,1,1,1,0,1};
628 // find bitstring in array
629 uint8_t errChk = preambleSearch(dest, preamble, sizeof(preamble), size, &startIdx);
630 if (errChk == 0) return -3; //preamble not found
631
632 numStart = startIdx + sizeof(preamble);
633 // final loop, go over previously decoded FSK data and manchester decode into usable tag ID
634 for (size_t idx = numStart; (idx-numStart) < *size - sizeof(preamble); idx+=2){
635 if (dest[idx] == dest[idx+1]){
636 return -4; //not manchester data
637 }
638 *hi2 = (*hi2<<1)|(*hi>>31);
639 *hi = (*hi<<1)|(*lo>>31);
640 //Then, shift in a 0 or one into low
641 if (dest[idx] && !dest[idx+1]) // 1 0
642 *lo=(*lo<<1)|1;
643 else // 0 1
644 *lo=(*lo<<1)|0;
645 }
646 return (int)startIdx;
eb191de6 647}
648
ec75f5c1 649// loop to get raw paradox waveform then FSK demodulate the TAG ID from it
a1d17964 650int ParadoxdemodFSK(uint8_t *dest, size_t *size, uint32_t *hi2, uint32_t *hi, uint32_t *lo)
ec75f5c1 651{
a1d17964 652 if (justNoise(dest, *size)) return -1;
653
654 size_t numStart=0, size2=*size, startIdx=0;
ec75f5c1 655 // FSK demodulator
a1d17964 656 *size = fskdemod(dest, size2,50,1,10,8); //fsk2a
657 if (*size < 96) return -2;
ec75f5c1 658
a1d17964 659 // 00001111 bit pattern represent start of frame, 01 pattern represents a 0 and 10 represents a 1
660 uint8_t preamble[] = {0,0,0,0,1,1,1,1};
661
662 uint8_t errChk = preambleSearch(dest, preamble, sizeof(preamble), size, &startIdx);
663 if (errChk == 0) return -3; //preamble not found
664
665 numStart = startIdx + sizeof(preamble);
666 // final loop, go over previously decoded FSK data and manchester decode into usable tag ID
667 for (size_t idx = numStart; (idx-numStart) < *size - sizeof(preamble); idx+=2){
668 if (dest[idx] == dest[idx+1])
669 return -4; //not manchester data
670 *hi2 = (*hi2<<1)|(*hi>>31);
671 *hi = (*hi<<1)|(*lo>>31);
672 //Then, shift in a 0 or one into low
673 if (dest[idx] && !dest[idx+1]) // 1 0
674 *lo=(*lo<<1)|1;
675 else // 0 1
676 *lo=(*lo<<1)|0;
ec75f5c1 677 }
a1d17964 678 return (int)startIdx;
ec75f5c1 679}
680
ba1a299c 681uint32_t bytebits_to_byte(uint8_t* src, size_t numbits)
eb191de6 682{
ba1a299c 683 uint32_t num = 0;
684 for(int i = 0 ; i < numbits ; i++)
685 {
686 num = (num << 1) | (*src);
687 src++;
688 }
689 return num;
eb191de6 690}
691
692int IOdemodFSK(uint8_t *dest, size_t size)
693{
a1d17964 694 if (justNoise(dest, size)) return -1;
ba1a299c 695 //make sure buffer has data
a1d17964 696 if (size < 66*64) return -2;
ba1a299c 697 // FSK demodulator
a1d17964 698 size = fskdemod(dest, size, 64, 1, 10, 8); // FSK2a RF/64
699 if (size < 65) return -3; //did we get a good demod?
ba1a299c 700 //Index map
701 //0 10 20 30 40 50 60
702 //| | | | | | |
703 //01234567 8 90123456 7 89012345 6 78901234 5 67890123 4 56789012 3 45678901 23
704 //-----------------------------------------------------------------------------
705 //00000000 0 11110000 1 facility 1 version* 1 code*one 1 code*two 1 ???????? 11
706 //
707 //XSF(version)facility:codeone+codetwo
708 //Handle the data
a1d17964 709 size_t startIdx = 0;
710 uint8_t preamble[] = {0,0,0,0,0,0,0,0,0,1};
711 uint8_t errChk = preambleSearch(dest, preamble, sizeof(preamble), &size, &startIdx);
712 if (errChk == 0) return -4; //preamble not found
eb191de6 713
a1d17964 714 if (!dest[startIdx+8] && dest[startIdx+17]==1 && dest[startIdx+26]==1 && dest[startIdx+35]==1 && dest[startIdx+44]==1 && dest[startIdx+53]==1){
715 //confirmed proper separator bits found
716 //return start position
717 return (int) startIdx;
1e090a61 718 }
a1d17964 719 return -5;
1e090a61 720}
721
722// by marshmellow
723// takes a array of binary values, start position, length of bits per parity (includes parity bit),
724// Parity Type (1 for odd 0 for even), and binary Length (length to run)
725size_t removeParity(uint8_t *BitStream, size_t startIdx, uint8_t pLen, uint8_t pType, size_t bLen)
726{
727 uint32_t parityWd = 0;
728 size_t j = 0, bitCnt = 0;
729 for (int word = 0; word < (bLen); word+=pLen){
730 for (int bit=0; bit < pLen; bit++){
731 parityWd = (parityWd << 1) | BitStream[startIdx+word+bit];
f3bf15e4 732 BitStream[j++] = (BitStream[startIdx+word+bit]);
1e090a61 733 }
734 j--;
735 // if parity fails then return 0
736 if (parityTest(parityWd, pLen, pType) == 0) return -1;
737 bitCnt+=(pLen-1);
738 parityWd = 0;
739 }
740 // if we got here then all the parities passed
741 //return ID start index and size
742 return bitCnt;
743}
744
745// by marshmellow
746// FSK Demod then try to locate an AWID ID
a1d17964 747int AWIDdemodFSK(uint8_t *dest, size_t *size)
1e090a61 748{
a1d17964 749 //make sure buffer has enough data
750 if (*size < 96*50) return -1;
751
752 if (justNoise(dest, *size)) return -2;
1e090a61 753
754 // FSK demodulator
a1d17964 755 *size = fskdemod(dest, *size, 50, 1, 10, 8); // fsk2a RF/50
756 if (*size < 96) return -3; //did we get a good demod?
757
758 uint8_t preamble[] = {0,0,0,0,0,0,0,1};
759 size_t startIdx = 0;
760 uint8_t errChk = preambleSearch(dest, preamble, sizeof(preamble), size, &startIdx);
761 if (errChk == 0) return -4; //preamble not found
762 if (*size != 96) return -5;
763 return (int)startIdx;
1e090a61 764}
765
766// by marshmellow
767// FSK Demod then try to locate an Farpointe Data (pyramid) ID
a1d17964 768int PyramiddemodFSK(uint8_t *dest, size_t *size)
1e090a61 769{
f3bf15e4 770 //make sure buffer has data
771 if (*size < 128*50) return -5;
a1d17964 772
f3bf15e4 773 //test samples are not just noise
774 if (justNoise(dest, *size)) return -1;
1e090a61 775
f3bf15e4 776 // FSK demodulator
777 *size = fskdemod(dest, *size, 50, 1, 10, 8); // fsk2a RF/50
778 if (*size < 128) return -2; //did we get a good demod?
a1d17964 779
f3bf15e4 780 uint8_t preamble[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};
a1d17964 781 size_t startIdx = 0;
782 uint8_t errChk = preambleSearch(dest, preamble, sizeof(preamble), size, &startIdx);
783 if (errChk == 0) return -4; //preamble not found
784 if (*size != 128) return -3;
785 return (int)startIdx;
1e090a61 786}
787
6de43508 788
789uint8_t DetectCleanAskWave(uint8_t dest[], size_t size, int high, int low)
790{
1fbf8956 791 uint16_t allPeaks=1;
6de43508 792 uint16_t cntPeaks=0;
1fbf8956 793 size_t loopEnd = 572;
794 if (loopEnd > size) loopEnd = size;
795 for (size_t i=60; i<loopEnd; i++){
6de43508 796 if (dest[i]>low && dest[i]<high)
797 allPeaks=0;
798 else
799 cntPeaks++;
800 }
1fbf8956 801 if (allPeaks == 0){
802 if (cntPeaks > 300) return 1;
6de43508 803 }
804 return allPeaks;
805}
806
2eec55c8 807// by marshmellow
808// to help detect clocks on heavily clipped samples
809// based on counts between zero crossings
13d77ef9 810int DetectStrongAskClock(uint8_t dest[], size_t size)
811{
2eec55c8 812 int clk[]={0,8,16,32,40,50,64,100,128};
e0165dcf 813 size_t idx = 40;
13d77ef9 814 uint8_t high=0;
815 size_t cnt = 0;
816 size_t highCnt = 0;
817 size_t highCnt2 = 0;
818 for (;idx < size; idx++){
819 if (dest[idx]>128) {
820 if (!high){
821 high=1;
822 if (cnt > highCnt){
823 if (highCnt != 0) highCnt2 = highCnt;
824 highCnt = cnt;
825 } else if (cnt > highCnt2) {
826 highCnt2 = cnt;
827 }
828 cnt=1;
829 } else {
830 cnt++;
831 }
832 } else if (dest[idx] <= 128){
833 if (high) {
834 high=0;
835 if (cnt > highCnt) {
836 if (highCnt != 0) highCnt2 = highCnt;
837 highCnt = cnt;
838 } else if (cnt > highCnt2) {
839 highCnt2 = cnt;
840 }
841 cnt=1;
842 } else {
843 cnt++;
844 }
845 }
846 }
1fbf8956 847 uint8_t tol;
13d77ef9 848 for (idx=8; idx>0; idx--){
1fbf8956 849 tol = clk[idx]/8;
850 if (clk[idx] >= highCnt - tol && clk[idx] <= highCnt + tol)
13d77ef9 851 return clk[idx];
1fbf8956 852 if (clk[idx] >= highCnt2 - tol && clk[idx] <= highCnt2 + tol)
13d77ef9 853 return clk[idx];
854 }
855 return -1;
856}
857
eb191de6 858// by marshmellow
859// not perfect especially with lower clocks or VERY good antennas (heavy wave clipping)
860// maybe somehow adjust peak trimming value based on samples to fix?
6de43508 861// return start index of best starting position for that clock and return clock (by reference)
862int DetectASKClock(uint8_t dest[], size_t size, int *clock, int maxErr)
eb191de6 863{
2eec55c8 864 size_t i=0;
865 uint8_t clk[]={8,16,32,40,50,64,100,128,255};
866 uint8_t loopCnt = 255; //don't need to loop through entire array...
23f0a7d8 867 if (size==0) return -1;
868 if (size <= loopCnt) loopCnt = size-1; //not enough samples
e0165dcf 869 //if we already have a valid clock quit
870
871 for (;i<8;++i)
872 if (clk[i] == *clock) return 0;
873
874 //get high and low peak
875 int peak, low;
2eec55c8 876 if (getHiLo(dest, loopCnt, &peak, &low, 75, 75) < 1) return -1;
e0165dcf 877
878 //test for large clean peaks
879 if (DetectCleanAskWave(dest, size, peak, low)==1){
880 int ans = DetectStrongAskClock(dest, size);
881 for (i=7; i>0; i--){
882 if (clk[i] == ans) {
2eec55c8 883 *clock = ans;
e0165dcf 884 return 0;
885 }
886 }
887 }
2eec55c8 888 uint8_t ii;
889 uint8_t clkCnt, tol = 0;
890 uint16_t bestErr[]={1000,1000,1000,1000,1000,1000,1000,1000,1000};
891 uint8_t bestStart[]={0,0,0,0,0,0,0,0,0};
892 size_t errCnt = 0;
893 size_t arrLoc, loopEnd;
e0165dcf 894 //test each valid clock from smallest to greatest to see which lines up
895 for(clkCnt=0; clkCnt < 8; clkCnt++){
896 if (clk[clkCnt] == 32){
897 tol=1;
898 }else{
899 tol=0;
900 }
23f0a7d8 901 if (!maxErr && loopCnt>clk[clkCnt]*2) loopCnt=clk[clkCnt]*2;
e0165dcf 902 bestErr[clkCnt]=1000;
903 //try lining up the peaks by moving starting point (try first 256)
23f0a7d8 904 for (ii=0; ii < loopCnt-tol-clk[clkCnt]; ii++){
2eec55c8 905 if (dest[ii] < peak && dest[ii] > low) continue;
906
907 errCnt=0;
908 // now that we have the first one lined up test rest of wave array
909 loopEnd = ((size-ii-tol) / clk[clkCnt]) - 1;
910 for (i=0; i < loopEnd; ++i){
911 arrLoc = ii + (i * clk[clkCnt]);
912 if (dest[arrLoc] >= peak || dest[arrLoc] <= low){
913 }else if (dest[arrLoc-tol] >= peak || dest[arrLoc-tol] <= low){
914 }else if (dest[arrLoc+tol] >= peak || dest[arrLoc+tol] <= low){
915 }else{ //error no peak detected
916 errCnt++;
e0165dcf 917 }
918 }
2eec55c8 919 //if we found no errors then we can stop here
920 // this is correct one - return this clock
921 //PrintAndLog("DEBUG: clk %d, err %d, ii %d, i %d",clk[clkCnt],errCnt,ii,i);
922 if(errCnt==0 && clkCnt<6) {
923 *clock = clk[clkCnt];
924 return ii;
925 }
926 //if we found errors see if it is lowest so far and save it as best run
927 if(errCnt<bestErr[clkCnt]){
928 bestErr[clkCnt]=errCnt;
929 bestStart[clkCnt]=ii;
930 }
e0165dcf 931 }
932 }
933 uint8_t iii=0;
934 uint8_t best=0;
935 for (iii=0; iii<8; ++iii){
2eec55c8 936 if (bestErr[iii] < bestErr[best]){
937 if (bestErr[iii] == 0) bestErr[iii]=1;
e0165dcf 938 // current best bit to error ratio vs new bit to error ratio
2eec55c8 939 if ( (size/clk[best])/bestErr[best] < (size/clk[iii])/bestErr[iii] ){
e0165dcf 940 best = iii;
941 }
942 }
943 }
2eec55c8 944 if (bestErr[best] > maxErr) return -1;
945 *clock = clk[best];
e0165dcf 946 return bestStart[best];
eb191de6 947}
ba1a299c 948
949//by marshmellow
6de43508 950//detect psk clock by reading each phase shift
951// a phase shift is determined by measuring the sample length of each wave
952int DetectPSKClock(uint8_t dest[], size_t size, int clock)
ba1a299c 953{
e0165dcf 954 uint8_t clk[]={255,16,32,40,50,64,100,128,255}; //255 is not a valid clock
955 uint16_t loopCnt = 4096; //don't need to loop through entire array...
956 if (size == 0) return 0;
957 if (size<loopCnt) loopCnt = size;
958
959 //if we already have a valid clock quit
960 size_t i=1;
961 for (; i < 8; ++i)
962 if (clk[i] == clock) return clock;
963
964 size_t waveStart=0, waveEnd=0, firstFullWave=0, lastClkBit=0;
965 uint8_t clkCnt, fc=0, fullWaveLen=0, tol=1;
966 uint16_t peakcnt=0, errCnt=0, waveLenCnt=0;
967 uint16_t bestErr[]={1000,1000,1000,1000,1000,1000,1000,1000,1000};
968 uint16_t peaksdet[]={0,0,0,0,0,0,0,0,0};
2eec55c8 969 fc = countFC(dest, size, 0);
970 if (fc!=2 && fc!=4 && fc!=8) return -1;
e0165dcf 971 //PrintAndLog("DEBUG: FC: %d",fc);
972
973 //find first full wave
974 for (i=0; i<loopCnt; i++){
975 if (dest[i] < dest[i+1] && dest[i+1] >= dest[i+2]){
976 if (waveStart == 0) {
977 waveStart = i+1;
978 //PrintAndLog("DEBUG: waveStart: %d",waveStart);
979 } else {
980 waveEnd = i+1;
981 //PrintAndLog("DEBUG: waveEnd: %d",waveEnd);
982 waveLenCnt = waveEnd-waveStart;
983 if (waveLenCnt > fc){
984 firstFullWave = waveStart;
985 fullWaveLen=waveLenCnt;
986 break;
987 }
988 waveStart=0;
989 }
990 }
991 }
992 //PrintAndLog("DEBUG: firstFullWave: %d, waveLen: %d",firstFullWave,fullWaveLen);
993
994 //test each valid clock from greatest to smallest to see which lines up
995 for(clkCnt=7; clkCnt >= 1 ; clkCnt--){
996 lastClkBit = firstFullWave; //set end of wave as clock align
997 waveStart = 0;
998 errCnt=0;
999 peakcnt=0;
1000 //PrintAndLog("DEBUG: clk: %d, lastClkBit: %d",clk[clkCnt],lastClkBit);
1001
1002 for (i = firstFullWave+fullWaveLen-1; i < loopCnt-2; i++){
1003 //top edge of wave = start of new wave
1004 if (dest[i] < dest[i+1] && dest[i+1] >= dest[i+2]){
1005 if (waveStart == 0) {
1006 waveStart = i+1;
1007 waveLenCnt=0;
1008 } else { //waveEnd
1009 waveEnd = i+1;
1010 waveLenCnt = waveEnd-waveStart;
1011 if (waveLenCnt > fc){
1012 //if this wave is a phase shift
1013 //PrintAndLog("DEBUG: phase shift at: %d, len: %d, nextClk: %d, ii: %d, fc: %d",waveStart,waveLenCnt,lastClkBit+clk[clkCnt]-tol,ii+1,fc);
1014 if (i+1 >= lastClkBit + clk[clkCnt] - tol){ //should be a clock bit
1015 peakcnt++;
1016 lastClkBit+=clk[clkCnt];
1017 } else if (i<lastClkBit+8){
1018 //noise after a phase shift - ignore
1019 } else { //phase shift before supposed to based on clock
1020 errCnt++;
1021 }
1022 } else if (i+1 > lastClkBit + clk[clkCnt] + tol + fc){
1023 lastClkBit+=clk[clkCnt]; //no phase shift but clock bit
1024 }
1025 waveStart=i+1;
1026 }
1027 }
1028 }
1029 if (errCnt == 0){
1030 return clk[clkCnt];
1031 }
1032 if (errCnt <= bestErr[clkCnt]) bestErr[clkCnt]=errCnt;
1033 if (peakcnt > peaksdet[clkCnt]) peaksdet[clkCnt]=peakcnt;
1034 }
1035 //all tested with errors
1036 //return the highest clk with the most peaks found
1037 uint8_t best=7;
1038 for (i=7; i>=1; i--){
1039 if (peaksdet[i] > peaksdet[best]) {
1040 best = i;
1041 }
1042 //PrintAndLog("DEBUG: Clk: %d, peaks: %d, errs: %d, bestClk: %d",clk[iii],peaksdet[iii],bestErr[iii],clk[best]);
1043 }
1044 return clk[best];
ba1a299c 1045}
1046
6de43508 1047//by marshmellow
1048//detect nrz clock by reading #peaks vs no peaks(or errors)
1049int DetectNRZClock(uint8_t dest[], size_t size, int clock)
ba1a299c 1050{
2eec55c8 1051 size_t i=0;
1052 uint8_t clk[]={8,16,32,40,50,64,100,128,255};
1053 size_t loopCnt = 4096; //don't need to loop through entire array...
e0165dcf 1054 if (size == 0) return 0;
1055 if (size<loopCnt) loopCnt = size;
1056
1057 //if we already have a valid clock quit
1058 for (; i < 8; ++i)
1059 if (clk[i] == clock) return clock;
1060
1061 //get high and low peak
1062 int peak, low;
2eec55c8 1063 if (getHiLo(dest, loopCnt, &peak, &low, 75, 75) < 1) return 0;
e0165dcf 1064
1065 //PrintAndLog("DEBUG: peak: %d, low: %d",peak,low);
2eec55c8 1066 size_t ii;
e0165dcf 1067 uint8_t clkCnt;
1068 uint8_t tol = 0;
2eec55c8 1069 uint16_t peakcnt=0;
1070 uint16_t peaksdet[]={0,0,0,0,0,0,0,0};
1071 uint16_t maxPeak=0;
e0165dcf 1072 //test for large clipped waves
1073 for (i=0; i<loopCnt; i++){
1074 if (dest[i] >= peak || dest[i] <= low){
1075 peakcnt++;
1076 } else {
1077 if (peakcnt>0 && maxPeak < peakcnt){
1078 maxPeak = peakcnt;
1079 }
1080 peakcnt=0;
1081 }
1082 }
1083 peakcnt=0;
1084 //test each valid clock from smallest to greatest to see which lines up
1085 for(clkCnt=0; clkCnt < 8; ++clkCnt){
1086 //ignore clocks smaller than largest peak
1087 if (clk[clkCnt]<maxPeak) continue;
1088
1089 //try lining up the peaks by moving starting point (try first 256)
1090 for (ii=0; ii< loopCnt; ++ii){
1091 if ((dest[ii] >= peak) || (dest[ii] <= low)){
1092 peakcnt=0;
1093 // now that we have the first one lined up test rest of wave array
1094 for (i=0; i < ((int)((size-ii-tol)/clk[clkCnt])-1); ++i){
1095 if (dest[ii+(i*clk[clkCnt])]>=peak || dest[ii+(i*clk[clkCnt])]<=low){
1096 peakcnt++;
1097 }
1098 }
1099 if(peakcnt>peaksdet[clkCnt]) {
1100 peaksdet[clkCnt]=peakcnt;
1101 }
1102 }
1103 }
1104 }
1105 int iii=7;
2eec55c8 1106 uint8_t best=0;
e0165dcf 1107 for (iii=7; iii > 0; iii--){
1108 if (peaksdet[iii] > peaksdet[best]){
1109 best = iii;
1110 }
1111 //PrintAndLog("DEBUG: Clk: %d, peaks: %d, errs: %d, bestClk: %d",clk[iii],peaksdet[iii],bestErr[iii],clk[best]);
1112 }
1113 return clk[best];
ba1a299c 1114}
1115
04d2721b 1116// by marshmellow
1117// convert psk1 demod to psk2 demod
1118// only transition waves are 1s
1119void psk1TOpsk2(uint8_t *BitStream, size_t size)
1120{
1121 size_t i=1;
1122 uint8_t lastBit=BitStream[0];
1123 for (; i<size; i++){
7a8a982b 1124 if (BitStream[i]==77){
1125 //ignore errors
1126 } else if (lastBit!=BitStream[i]){
04d2721b 1127 lastBit=BitStream[i];
1128 BitStream[i]=1;
1129 } else {
1130 BitStream[i]=0;
1131 }
1132 }
1133 return;
1134}
ba1a299c 1135
3bc66a96 1136// by marshmellow
1137// convert psk2 demod to psk1 demod
1138// from only transition waves are 1s to phase shifts change bit
1139void psk2TOpsk1(uint8_t *BitStream, size_t size)
1140{
712ebfa6 1141 uint8_t phase=0;
1142 for (size_t i=0; i<size; i++){
1143 if (BitStream[i]==1){
3bc66a96 1144 phase ^=1;
1145 }
1146 BitStream[i]=phase;
1147 }
1148 return;
1149}
1150
04d2721b 1151// redesigned by marshmellow adjusted from existing decode functions
1152// indala id decoding - only tested on 26 bit tags, but attempted to make it work for more
ba1a299c 1153int indala26decode(uint8_t *bitStream, size_t *size, uint8_t *invert)
1154{
1155 //26 bit 40134 format (don't know other formats)
1156 int i;
84871873 1157 int long_wait=29;//29 leading zeros in format
ba1a299c 1158 int start;
1159 int first = 0;
1160 int first2 = 0;
1161 int bitCnt = 0;
1162 int ii;
1163 // Finding the start of a UID
1164 for (start = 0; start <= *size - 250; start++) {
1165 first = bitStream[start];
1166 for (i = start; i < start + long_wait; i++) {
1167 if (bitStream[i] != first) {
1168 break;
1169 }
1170 }
1171 if (i == (start + long_wait)) {
1172 break;
1173 }
1174 }
1175 if (start == *size - 250 + 1) {
1176 // did not find start sequence
1177 return -1;
1178 }
ba1a299c 1179 // Inverting signal if needed
1180 if (first == 1) {
1181 for (i = start; i < *size; i++) {
1182 bitStream[i] = !bitStream[i];
1183 }
1184 *invert = 1;
1185 }else *invert=0;
1186
1187 int iii;
84871873 1188 //found start once now test length by finding next one
ba1a299c 1189 for (ii=start+29; ii <= *size - 250; ii++) {
1190 first2 = bitStream[ii];
1191 for (iii = ii; iii < ii + long_wait; iii++) {
1192 if (bitStream[iii] != first2) {
1193 break;
1194 }
1195 }
1196 if (iii == (ii + long_wait)) {
1197 break;
1198 }
1199 }
1200 if (ii== *size - 250 + 1){
1201 // did not find second start sequence
1202 return -2;
1203 }
1204 bitCnt=ii-start;
1205
1206 // Dumping UID
1207 i = start;
1208 for (ii = 0; ii < bitCnt; ii++) {
1209 bitStream[ii] = bitStream[i++];
1210 }
1211 *size=bitCnt;
1212 return 1;
1213}
1214
6de43508 1215// by marshmellow - demodulate NRZ wave (both similar enough)
04d2721b 1216// peaks invert bit (high=1 low=0) each clock cycle = 1 bit determined by last peak
6de43508 1217// there probably is a much simpler way to do this....
1218int nrzRawDemod(uint8_t *dest, size_t *size, int *clk, int *invert, int maxErr)
ba1a299c 1219{
e0165dcf 1220 if (justNoise(dest, *size)) return -1;
1221 *clk = DetectNRZClock(dest, *size, *clk);
1222 if (*clk==0) return -2;
2eec55c8 1223 size_t i, gLen = 4096;
e0165dcf 1224 if (gLen>*size) gLen = *size;
1225 int high, low;
1226 if (getHiLo(dest, gLen, &high, &low, 75, 75) < 1) return -3; //25% fuzz on high 25% fuzz on low
1227 int lastBit = 0; //set first clock check
2eec55c8 1228 size_t iii = 0, bitnum = 0; //bitnum counter
1229 uint16_t errCnt = 0, MaxBits = 1000;
1230 size_t bestErrCnt = maxErr+1;
1231 size_t bestPeakCnt = 0, bestPeakStart = 0;
1232 uint8_t bestFirstPeakHigh=0, firstPeakHigh=0, curBit=0, bitHigh=0, errBitHigh=0;
e0165dcf 1233 uint8_t tol = 1; //clock tolerance adjust - waves will be accepted as within the clock if they fall + or - this value + clock from last valid wave
e0165dcf 1234 uint16_t peakCnt=0;
1235 uint8_t ignoreWindow=4;
2eec55c8 1236 uint8_t ignoreCnt=ignoreWindow; //in case of noise near peak
e0165dcf 1237 //loop to find first wave that works - align to clock
1238 for (iii=0; iii < gLen; ++iii){
1239 if ((dest[iii]>=high) || (dest[iii]<=low)){
1240 if (dest[iii]>=high) firstPeakHigh=1;
1241 else firstPeakHigh=0;
1242 lastBit=iii-*clk;
1243 peakCnt=0;
1244 errCnt=0;
e0165dcf 1245 //loop through to see if this start location works
1246 for (i = iii; i < *size; ++i) {
2eec55c8 1247 // if we are at a clock bit
1248 if ((i >= lastBit + *clk - tol) && (i <= lastBit + *clk + tol)) {
1249 //test high/low
1250 if (dest[i] >= high || dest[i] <= low) {
1251 bitHigh = 1;
1252 peakCnt++;
1253 errBitHigh = 0;
1254 ignoreCnt = ignoreWindow;
1255 lastBit += *clk;
1256 } else if (i == lastBit + *clk + tol) {
1257 lastBit += *clk;
1258 }
e0165dcf 1259 //else if no bars found
2eec55c8 1260 } else if (dest[i] < high && dest[i] > low){
e0165dcf 1261 if (ignoreCnt==0){
1262 bitHigh=0;
2eec55c8 1263 if (errBitHigh==1) errCnt++;
e0165dcf 1264 errBitHigh=0;
1265 } else {
1266 ignoreCnt--;
1267 }
2eec55c8 1268 } else if ((dest[i]>=high || dest[i]<=low) && (bitHigh==0)) {
e0165dcf 1269 //error bar found no clock...
1270 errBitHigh=1;
1271 }
2eec55c8 1272 if (((i-iii) / *clk)>=MaxBits) break;
e0165dcf 1273 }
1274 //we got more than 64 good bits and not all errors
2eec55c8 1275 if (((i-iii) / *clk) > 64 && (errCnt <= (maxErr))) {
e0165dcf 1276 //possible good read
2eec55c8 1277 if (!errCnt || peakCnt > bestPeakCnt){
e0165dcf 1278 bestFirstPeakHigh=firstPeakHigh;
1279 bestErrCnt = errCnt;
1280 bestPeakCnt = peakCnt;
1281 bestPeakStart = iii;
2eec55c8 1282 if (!errCnt) break; //great read - finish
e0165dcf 1283 }
e0165dcf 1284 }
1285 }
1286 }
1287 //PrintAndLog("DEBUG: bestErrCnt: %d, maxErr: %d, bestStart: %d, bestPeakCnt: %d, bestPeakStart: %d",bestErrCnt,maxErr,bestStart,bestPeakCnt,bestPeakStart);
2eec55c8 1288 if (bestErrCnt > maxErr) return bestErrCnt;
1289
1290 //best run is good enough set to best run and set overwrite BinStream
1291 lastBit = bestPeakStart - *clk;
1292 memset(dest, bestFirstPeakHigh^1, bestPeakStart / *clk);
1293 bitnum += (bestPeakStart / *clk);
1294 for (i = bestPeakStart; i < *size; ++i) {
1295 // if expecting a clock bit
1296 if ((i >= lastBit + *clk - tol) && (i <= lastBit + *clk + tol)) {
1297 // test high/low
1298 if (dest[i] >= high || dest[i] <= low) {
1299 peakCnt++;
1300 bitHigh = 1;
1301 errBitHigh = 0;
1302 ignoreCnt = ignoreWindow;
1303 curBit = *invert;
1304 if (dest[i] >= high) curBit ^= 1;
1305 dest[bitnum++] = curBit;
1306 lastBit += *clk;
1307 //else no bars found in clock area
1308 } else if (i == lastBit + *clk + tol) {
1309 dest[bitnum++] = curBit;
1310 lastBit += *clk;
1311 }
1312 //else if no bars found
1313 } else if (dest[i] < high && dest[i] > low){
1314 if (ignoreCnt == 0){
1315 bitHigh = 0;
1316 if (errBitHigh == 1){
1317 dest[bitnum++] = 77;
1318 errCnt++;
e0165dcf 1319 }
2eec55c8 1320 errBitHigh=0;
1321 } else {
1322 ignoreCnt--;
e0165dcf 1323 }
2eec55c8 1324 } else if ((dest[i] >= high || dest[i] <= low) && (bitHigh == 0)) {
1325 //error bar found no clock...
1326 errBitHigh=1;
e0165dcf 1327 }
2eec55c8 1328 if (bitnum >= MaxBits) break;
e0165dcf 1329 }
2eec55c8 1330 *size = bitnum;
1331 return bestErrCnt;
ba1a299c 1332}
1333
1e090a61 1334//by marshmellow
03e6bb4a 1335//detects the bit clock for FSK given the high and low Field Clocks
1336uint8_t detectFSKClk(uint8_t *BitStream, size_t size, uint8_t fcHigh, uint8_t fcLow)
1e090a61 1337{
e0165dcf 1338 uint8_t clk[] = {8,16,32,40,50,64,100,128,0};
1339 uint16_t rfLens[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
1340 uint8_t rfCnts[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
1341 uint8_t rfLensFnd = 0;
2eec55c8 1342 uint8_t lastFCcnt = 0;
1343 uint16_t fcCounter = 0;
e0165dcf 1344 uint16_t rfCounter = 0;
1345 uint8_t firstBitFnd = 0;
1346 size_t i;
1347 if (size == 0) return 0;
1348
1349 uint8_t fcTol = (uint8_t)(0.5+(float)(fcHigh-fcLow)/2);
1350 rfLensFnd=0;
1351 fcCounter=0;
1352 rfCounter=0;
1353 firstBitFnd=0;
1354 //PrintAndLog("DEBUG: fcTol: %d",fcTol);
1355 // prime i to first up transition
1356 for (i = 1; i < size-1; i++)
1357 if (BitStream[i] > BitStream[i-1] && BitStream[i]>=BitStream[i+1])
1358 break;
1359
1360 for (; i < size-1; i++){
2eec55c8 1361 fcCounter++;
1362 rfCounter++;
1363
1364 if (BitStream[i] <= BitStream[i-1] || BitStream[i] < BitStream[i+1])
1365 continue;
1366 // else new peak
1367 // if we got less than the small fc + tolerance then set it to the small fc
1368 if (fcCounter < fcLow+fcTol)
1369 fcCounter = fcLow;
1370 else //set it to the large fc
1371 fcCounter = fcHigh;
1372
1373 //look for bit clock (rf/xx)
1374 if ((fcCounter < lastFCcnt || fcCounter > lastFCcnt)){
1375 //not the same size as the last wave - start of new bit sequence
1376 if (firstBitFnd > 1){ //skip first wave change - probably not a complete bit
1377 for (int ii=0; ii<15; ii++){
1378 if (rfLens[ii] == rfCounter){
1379 rfCnts[ii]++;
1380 rfCounter = 0;
1381 break;
e0165dcf 1382 }
e0165dcf 1383 }
2eec55c8 1384 if (rfCounter > 0 && rfLensFnd < 15){
1385 //PrintAndLog("DEBUG: rfCntr %d, fcCntr %d",rfCounter,fcCounter);
1386 rfCnts[rfLensFnd]++;
1387 rfLens[rfLensFnd++] = rfCounter;
1388 }
1389 } else {
1390 firstBitFnd++;
e0165dcf 1391 }
2eec55c8 1392 rfCounter=0;
1393 lastFCcnt=fcCounter;
e0165dcf 1394 }
2eec55c8 1395 fcCounter=0;
e0165dcf 1396 }
1397 uint8_t rfHighest=15, rfHighest2=15, rfHighest3=15;
1398
1399 for (i=0; i<15; i++){
1400 //PrintAndLog("DEBUG: RF %d, cnts %d",rfLens[i], rfCnts[i]);
1401 //get highest 2 RF values (might need to get more values to compare or compare all?)
1402 if (rfCnts[i]>rfCnts[rfHighest]){
1403 rfHighest3=rfHighest2;
1404 rfHighest2=rfHighest;
1405 rfHighest=i;
1406 } else if(rfCnts[i]>rfCnts[rfHighest2]){
1407 rfHighest3=rfHighest2;
1408 rfHighest2=i;
1409 } else if(rfCnts[i]>rfCnts[rfHighest3]){
1410 rfHighest3=i;
1411 }
1412 }
1413 // set allowed clock remainder tolerance to be 1 large field clock length+1
1414 // we could have mistakenly made a 9 a 10 instead of an 8 or visa versa so rfLens could be 1 FC off
1415 uint8_t tol1 = fcHigh+1;
1416
1417 //PrintAndLog("DEBUG: hightest: 1 %d, 2 %d, 3 %d",rfLens[rfHighest],rfLens[rfHighest2],rfLens[rfHighest3]);
1418
1419 // loop to find the highest clock that has a remainder less than the tolerance
1420 // compare samples counted divided by
1421 int ii=7;
1422 for (; ii>=0; ii--){
1423 if (rfLens[rfHighest] % clk[ii] < tol1 || rfLens[rfHighest] % clk[ii] > clk[ii]-tol1){
1424 if (rfLens[rfHighest2] % clk[ii] < tol1 || rfLens[rfHighest2] % clk[ii] > clk[ii]-tol1){
1425 if (rfLens[rfHighest3] % clk[ii] < tol1 || rfLens[rfHighest3] % clk[ii] > clk[ii]-tol1){
1426 break;
1427 }
1428 }
1429 }
1430 }
1431
1432 if (ii<0) return 0; // oops we went too far
1433
1434 return clk[ii];
03e6bb4a 1435}
1e090a61 1436
03e6bb4a 1437//by marshmellow
1438//countFC is to detect the field clock lengths.
1439//counts and returns the 2 most common wave lengths
6de43508 1440//mainly used for FSK field clock detection
2eec55c8 1441uint16_t countFC(uint8_t *BitStream, size_t size, uint8_t fskAdj)
03e6bb4a 1442{
e0165dcf 1443 uint8_t fcLens[] = {0,0,0,0,0,0,0,0,0,0};
1444 uint16_t fcCnts[] = {0,0,0,0,0,0,0,0,0,0};
1445 uint8_t fcLensFnd = 0;
1446 uint8_t lastFCcnt=0;
2eec55c8 1447 uint8_t fcCounter = 0;
e0165dcf 1448 size_t i;
1449 if (size == 0) return 0;
1450
1451 // prime i to first up transition
1452 for (i = 1; i < size-1; i++)
1453 if (BitStream[i] > BitStream[i-1] && BitStream[i] >= BitStream[i+1])
1454 break;
1455
1456 for (; i < size-1; i++){
1457 if (BitStream[i] > BitStream[i-1] && BitStream[i] >= BitStream[i+1]){
1458 // new up transition
1459 fcCounter++;
2eec55c8 1460 if (fskAdj){
1461 //if we had 5 and now have 9 then go back to 8 (for when we get a fc 9 instead of an 8)
1462 if (lastFCcnt==5 && fcCounter==9) fcCounter--;
1463 //if fc=9 or 4 add one (for when we get a fc 9 instead of 10 or a 4 instead of a 5)
1464 if ((fcCounter==9) || fcCounter==4) fcCounter++;
e0165dcf 1465 // save last field clock count (fc/xx)
2eec55c8 1466 lastFCcnt = fcCounter;
1467 }
e0165dcf 1468 // find which fcLens to save it to:
1469 for (int ii=0; ii<10; ii++){
1470 if (fcLens[ii]==fcCounter){
1471 fcCnts[ii]++;
1472 fcCounter=0;
1473 break;
1474 }
1475 }
1476 if (fcCounter>0 && fcLensFnd<10){
1477 //add new fc length
1478 fcCnts[fcLensFnd]++;
1479 fcLens[fcLensFnd++]=fcCounter;
1480 }
1481 fcCounter=0;
1482 } else {
1483 // count sample
1484 fcCounter++;
1485 }
1486 }
1487
1488 uint8_t best1=9, best2=9, best3=9;
1489 uint16_t maxCnt1=0;
1490 // go through fclens and find which ones are bigest 2
1491 for (i=0; i<10; i++){
1492 // PrintAndLog("DEBUG: FC %d, Cnt %d, Errs %d",fcLens[i],fcCnts[i],errCnt);
1493 // get the 3 best FC values
1494 if (fcCnts[i]>maxCnt1) {
1495 best3=best2;
1496 best2=best1;
1497 maxCnt1=fcCnts[i];
1498 best1=i;
1499 } else if(fcCnts[i]>fcCnts[best2]){
1500 best3=best2;
1501 best2=i;
1502 } else if(fcCnts[i]>fcCnts[best3]){
1503 best3=i;
1504 }
1505 }
1506 uint8_t fcH=0, fcL=0;
1507 if (fcLens[best1]>fcLens[best2]){
1508 fcH=fcLens[best1];
1509 fcL=fcLens[best2];
1510 } else{
1511 fcH=fcLens[best2];
1512 fcL=fcLens[best1];
1513 }
1514
e0165dcf 1515 // TODO: take top 3 answers and compare to known Field clocks to get top 2
1516
1517 uint16_t fcs = (((uint16_t)fcH)<<8) | fcL;
1518 // PrintAndLog("DEBUG: Best %d best2 %d best3 %d",fcLens[best1],fcLens[best2],fcLens[best3]);
2eec55c8 1519 if (fskAdj) return fcs;
1520 return fcLens[best1];
6de43508 1521}
1522
1523//by marshmellow - demodulate PSK1 wave
1524//uses wave lengths (# Samples)
1525int pskRawDemod(uint8_t dest[], size_t *size, int *clock, int *invert)
1526{
e0165dcf 1527 if (size == 0) return -1;
2eec55c8 1528 uint16_t loopCnt = 4096; //don't need to loop through entire array...
e0165dcf 1529 if (*size<loopCnt) loopCnt = *size;
1530
1531 uint8_t curPhase = *invert;
1532 size_t i, waveStart=1, waveEnd=0, firstFullWave=0, lastClkBit=0;
1533 uint8_t fc=0, fullWaveLen=0, tol=1;
1534 uint16_t errCnt=0, waveLenCnt=0;
2eec55c8 1535 fc = countFC(dest, *size, 0);
e0165dcf 1536 if (fc!=2 && fc!=4 && fc!=8) return -1;
1537 //PrintAndLog("DEBUG: FC: %d",fc);
1538 *clock = DetectPSKClock(dest, *size, *clock);
2eec55c8 1539 if (*clock == 0) return -1;
e0165dcf 1540 int avgWaveVal=0, lastAvgWaveVal=0;
1541 //find first phase shift
1542 for (i=0; i<loopCnt; i++){
1543 if (dest[i]+fc < dest[i+1] && dest[i+1] >= dest[i+2]){
1544 waveEnd = i+1;
1545 //PrintAndLog("DEBUG: waveEnd: %d",waveEnd);
1546 waveLenCnt = waveEnd-waveStart;
1547 if (waveLenCnt > fc && waveStart > fc){ //not first peak and is a large wave
1548 lastAvgWaveVal = avgWaveVal/(waveLenCnt);
1549 firstFullWave = waveStart;
1550 fullWaveLen=waveLenCnt;
1551 //if average wave value is > graph 0 then it is an up wave or a 1
2eec55c8 1552 if (lastAvgWaveVal > 123) curPhase ^= 1; //fudge graph 0 a little 123 vs 128
e0165dcf 1553 break;
1554 }
1555 waveStart = i+1;
1556 avgWaveVal = 0;
1557 }
2eec55c8 1558 avgWaveVal += dest[i+2];
e0165dcf 1559 }
1560 //PrintAndLog("DEBUG: firstFullWave: %d, waveLen: %d",firstFullWave,fullWaveLen);
1561 lastClkBit = firstFullWave; //set start of wave as clock align
1562 //PrintAndLog("DEBUG: clk: %d, lastClkBit: %d", *clock, lastClkBit);
1563 waveStart = 0;
e0165dcf 1564 size_t numBits=0;
1565 //set skipped bits
2eec55c8 1566 memset(dest, curPhase^1, firstFullWave / *clock);
e0165dcf 1567 numBits += (firstFullWave / *clock);
1568 dest[numBits++] = curPhase; //set first read bit
2eec55c8 1569 for (i = firstFullWave + fullWaveLen - 1; i < *size-3; i++){
e0165dcf 1570 //top edge of wave = start of new wave
1571 if (dest[i]+fc < dest[i+1] && dest[i+1] >= dest[i+2]){
1572 if (waveStart == 0) {
1573 waveStart = i+1;
2eec55c8 1574 waveLenCnt = 0;
e0165dcf 1575 avgWaveVal = dest[i+1];
1576 } else { //waveEnd
1577 waveEnd = i+1;
1578 waveLenCnt = waveEnd-waveStart;
1579 lastAvgWaveVal = avgWaveVal/waveLenCnt;
1580 if (waveLenCnt > fc){
1581 //PrintAndLog("DEBUG: avgWaveVal: %d, waveSum: %d",lastAvgWaveVal,avgWaveVal);
2eec55c8 1582 //this wave is a phase shift
e0165dcf 1583 //PrintAndLog("DEBUG: phase shift at: %d, len: %d, nextClk: %d, i: %d, fc: %d",waveStart,waveLenCnt,lastClkBit+*clock-tol,i+1,fc);
1584 if (i+1 >= lastClkBit + *clock - tol){ //should be a clock bit
2eec55c8 1585 curPhase ^= 1;
e0165dcf 1586 dest[numBits++] = curPhase;
1587 lastClkBit += *clock;
2eec55c8 1588 } else if (i < lastClkBit+10+fc){
e0165dcf 1589 //noise after a phase shift - ignore
1590 } else { //phase shift before supposed to based on clock
1591 errCnt++;
1592 dest[numBits++] = 77;
1593 }
1594 } else if (i+1 > lastClkBit + *clock + tol + fc){
1595 lastClkBit += *clock; //no phase shift but clock bit
1596 dest[numBits++] = curPhase;
1597 }
2eec55c8 1598 avgWaveVal = 0;
1599 waveStart = i+1;
e0165dcf 1600 }
1601 }
2eec55c8 1602 avgWaveVal += dest[i+1];
e0165dcf 1603 }
1604 *size = numBits;
1605 return errCnt;
6de43508 1606}
Impressum, Datenschutz