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