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