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