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