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