]> git.zerfleddert.de Git - proxmark3-svn/blob - common/lfdemod.c
CHG: move some methods, its easier to read now. Cosmetic change.
[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 size_t preLastSample = 0;
373 size_t LastSample = 0;
374 size_t currSample = 0;
375 // sync to first lo-hi transition, and threshold
376
377 // Need to threshold first sample
378
379 if(dest[0] < threshold_value) dest[0] = 0;
380 else dest[0] = 1;
381
382 size_t numBits = 0;
383 // count cycles between consecutive lo-hi transitions, there should be either 8 (fc/8)
384 // or 10 (fc/10) cycles but in practice due to noise etc we may end up with with anywhere
385 // between 7 to 11 cycles so fuzz it by treat anything <9 as 8 and anything else as 10
386 for(idx = 1; idx < size; idx++) {
387 // threshold current value
388
389 if (dest[idx] < threshold_value) dest[idx] = 0;
390 else dest[idx] = 1;
391
392 // Check for 0->1 transition
393 if (dest[idx-1] < dest[idx]) { // 0 -> 1 transition
394 preLastSample = LastSample;
395 LastSample = currSample;
396 currSample = idx-last_transition;
397 if (currSample < (fclow-2)){ //0-5 = garbage noise
398 //do nothing with extra garbage
399 } else if (currSample < (fchigh-1)) { //6-8 = 8 sample waves
400 if (LastSample > (fchigh-2) && preLastSample < (fchigh-1)){
401 dest[numBits-1]=1; //correct last 9 wave surrounded by 8 waves
402 }
403 dest[numBits++]=1;
404
405 } else if (currSample > (fchigh+1) && !numBits) { //12 + and first bit = garbage
406 //do nothing with beginning garbage
407 } else if (currSample == (fclow+1) && LastSample == (fclow-1)) { // had a 7 then a 9 should be two 8's
408 dest[numBits++]=1;
409 } else { //9+ = 10 sample waves
410 dest[numBits++]=0;
411 }
412 last_transition = idx;
413 }
414 }
415 return numBits; //Actually, it returns the number of bytes, but each byte represents a bit: 1 or 0
416 }
417
418 //translate 11111100000 to 10
419 size_t aggregate_bits(uint8_t *dest, size_t size, uint8_t rfLen,
420 uint8_t invert, uint8_t fchigh, uint8_t fclow)
421 {
422 uint8_t lastval=dest[0];
423 size_t idx=0;
424 size_t numBits=0;
425 uint32_t n=1;
426 for( idx=1; idx < size; idx++) {
427 n++;
428 if (dest[idx]==lastval) continue;
429
430 //if lastval was 1, we have a 1->0 crossing
431 if (dest[idx-1]==1) {
432 if (!numBits && n < rfLen/fclow) {
433 n=0;
434 lastval = dest[idx];
435 continue;
436 }
437 n = (n * fclow + rfLen/2) / rfLen;
438 } else {// 0->1 crossing
439 //test first bitsample too small
440 if (!numBits && n < rfLen/fchigh) {
441 n=0;
442 lastval = dest[idx];
443 continue;
444 }
445 n = (n * fchigh + rfLen/2) / rfLen;
446 }
447 if (n == 0) n = 1;
448
449 memset(dest+numBits, dest[idx-1]^invert , n);
450 numBits += n;
451 n=0;
452 lastval=dest[idx];
453 }//end for
454 // if valid extra bits at the end were all the same frequency - add them in
455 if (n > rfLen/fchigh) {
456 if (dest[idx-2]==1) {
457 n = (n * fclow + rfLen/2) / rfLen;
458 } else {
459 n = (n * fchigh + rfLen/2) / rfLen;
460 }
461 memset(dest+numBits, dest[idx-1]^invert , n);
462 numBits += n;
463 }
464 return numBits;
465 }
466 //by marshmellow (from holiman's base)
467 // full fsk demod from GraphBuffer wave to decoded 1s and 0s (no mandemod)
468 int fskdemod(uint8_t *dest, size_t size, uint8_t rfLen, uint8_t invert, uint8_t fchigh, uint8_t fclow)
469 {
470 // FSK demodulator
471 size = fsk_wave_demod(dest, size, fchigh, fclow);
472 size = aggregate_bits(dest, size, rfLen, invert, fchigh, fclow);
473 return size;
474 }
475
476 // loop to get raw HID waveform then FSK demodulate the TAG ID from it
477 int HIDdemodFSK(uint8_t *dest, size_t *size, uint32_t *hi2, uint32_t *hi, uint32_t *lo)
478 {
479 if (justNoise(dest, *size)) return -1;
480
481 size_t numStart=0, size2=*size, startIdx=0;
482 // FSK demodulator
483 *size = fskdemod(dest, size2,50,1,10,8); //fsk2a
484 if (*size < 96*2) return -2;
485 // 00011101 bit pattern represent start of frame, 01 pattern represents a 0 and 10 represents a 1
486 uint8_t preamble[] = {0,0,0,1,1,1,0,1};
487 // find bitstring in array
488 uint8_t errChk = preambleSearch(dest, preamble, sizeof(preamble), size, &startIdx);
489 if (errChk == 0) return -3; //preamble not found
490
491 numStart = startIdx + sizeof(preamble);
492 // final loop, go over previously decoded FSK data and manchester decode into usable tag ID
493 for (size_t idx = numStart; (idx-numStart) < *size - sizeof(preamble); idx+=2){
494 if (dest[idx] == dest[idx+1]){
495 return -4; //not manchester data
496 }
497 *hi2 = (*hi2<<1)|(*hi>>31);
498 *hi = (*hi<<1)|(*lo>>31);
499 //Then, shift in a 0 or one into low
500 if (dest[idx] && !dest[idx+1]) // 1 0
501 *lo=(*lo<<1)|1;
502 else // 0 1
503 *lo=(*lo<<1)|0;
504 }
505 return (int)startIdx;
506 }
507
508 // loop to get raw paradox waveform then FSK demodulate the TAG ID from it
509 int ParadoxdemodFSK(uint8_t *dest, size_t *size, uint32_t *hi2, uint32_t *hi, uint32_t *lo)
510 {
511 if (justNoise(dest, *size)) return -1;
512
513 size_t numStart=0, size2=*size, startIdx=0;
514 // FSK demodulator
515 *size = fskdemod(dest, size2,50,1,10,8); //fsk2a
516 if (*size < 96) return -2;
517
518 // 00001111 bit pattern represent start of frame, 01 pattern represents a 0 and 10 represents a 1
519 uint8_t preamble[] = {0,0,0,0,1,1,1,1};
520
521 uint8_t errChk = preambleSearch(dest, preamble, sizeof(preamble), size, &startIdx);
522 if (errChk == 0) return -3; //preamble not found
523
524 numStart = startIdx + sizeof(preamble);
525 // final loop, go over previously decoded FSK data and manchester decode into usable tag ID
526 for (size_t idx = numStart; (idx-numStart) < *size - sizeof(preamble); idx+=2){
527 if (dest[idx] == dest[idx+1])
528 return -4; //not manchester data
529 *hi2 = (*hi2<<1)|(*hi>>31);
530 *hi = (*hi<<1)|(*lo>>31);
531 //Then, shift in a 0 or one into low
532 if (dest[idx] && !dest[idx+1]) // 1 0
533 *lo=(*lo<<1)|1;
534 else // 0 1
535 *lo=(*lo<<1)|0;
536 }
537 return (int)startIdx;
538 }
539
540 uint32_t bytebits_to_byte(uint8_t* src, size_t numbits)
541 {
542 uint32_t num = 0;
543 for(int i = 0 ; i < numbits ; i++)
544 {
545 num = (num << 1) | (*src);
546 src++;
547 }
548 return num;
549 }
550
551 //least significant bit first
552 uint32_t bytebits_to_byteLSBF(uint8_t *src, size_t numbits)
553 {
554 uint32_t num = 0;
555 for(int i = 0 ; i < numbits ; i++)
556 {
557 num = (num << 1) | *(src + (numbits-(i+1)));
558 }
559 return num;
560 }
561
562 int IOdemodFSK(uint8_t *dest, size_t size)
563 {
564 if (justNoise(dest, size)) return -1;
565 //make sure buffer has data
566 if (size < 66*64) return -2;
567 // FSK demodulator
568 size = fskdemod(dest, size, 64, 1, 10, 8); // FSK2a RF/64
569 if (size < 65) return -3; //did we get a good demod?
570 //Index map
571 //0 10 20 30 40 50 60
572 //| | | | | | |
573 //01234567 8 90123456 7 89012345 6 78901234 5 67890123 4 56789012 3 45678901 23
574 //-----------------------------------------------------------------------------
575 //00000000 0 11110000 1 facility 1 version* 1 code*one 1 code*two 1 ???????? 11
576 //
577 //XSF(version)facility:codeone+codetwo
578 //Handle the data
579 size_t startIdx = 0;
580 uint8_t preamble[] = {0,0,0,0,0,0,0,0,0,1};
581 uint8_t errChk = preambleSearch(dest, preamble, sizeof(preamble), &size, &startIdx);
582 if (errChk == 0) return -4; //preamble not found
583
584 if (!dest[startIdx+8] && dest[startIdx+17]==1 && dest[startIdx+26]==1 && dest[startIdx+35]==1 && dest[startIdx+44]==1 && dest[startIdx+53]==1){
585 //confirmed proper separator bits found
586 //return start position
587 return (int) startIdx;
588 }
589 return -5;
590 }
591
592 // by marshmellow
593 // takes a array of binary values, start position, length of bits per parity (includes parity bit),
594 // Parity Type (1 for odd; 0 for even; 2 Always 1's), and binary Length (length to run)
595 size_t removeParity(uint8_t *BitStream, size_t startIdx, uint8_t pLen, uint8_t pType, size_t bLen)
596 {
597 uint32_t parityWd = 0;
598 size_t j = 0, bitCnt = 0;
599 for (int word = 0; word < (bLen); word+=pLen){
600 for (int bit=0; bit < pLen; bit++){
601 parityWd = (parityWd << 1) | BitStream[startIdx+word+bit];
602 BitStream[j++] = (BitStream[startIdx+word+bit]);
603 }
604 j--; // overwrite parity with next data
605 // if parity fails then return 0
606 if (pType == 2) { // then marker bit which should be a 1
607 if (!BitStream[j]) return 0;
608 } else {
609 if (parityTest(parityWd, pLen, pType) == 0) return 0;
610 }
611 bitCnt+=(pLen-1);
612 parityWd = 0;
613 }
614 // if we got here then all the parities passed
615 //return ID start index and size
616 return bitCnt;
617 }
618
619 // Ask/Biphase Demod then try to locate an ISO 11784/85 ID
620 // BitStream must contain previously askrawdemod and biphasedemoded data
621 int FDXBdemodBI(uint8_t *dest, size_t *size)
622 {
623 //make sure buffer has enough data
624 if (*size < 128) return -1;
625
626 size_t startIdx = 0;
627 uint8_t preamble[] = {0,0,0,0,0,0,0,0,0,0,1};
628
629 uint8_t errChk = preambleSearch(dest, preamble, sizeof(preamble), size, &startIdx);
630 if (errChk == 0) return -2; //preamble not found
631 return (int)startIdx;
632 }
633
634 // by marshmellow
635 // FSK Demod then try to locate an AWID ID
636 int AWIDdemodFSK(uint8_t *dest, size_t *size)
637 {
638 //make sure buffer has enough data
639 if (*size < 96*50) return -1;
640
641 if (justNoise(dest, *size)) return -2;
642
643 // FSK demodulator
644 *size = fskdemod(dest, *size, 50, 1, 10, 8); // fsk2a RF/50
645 if (*size < 96) return -3; //did we get a good demod?
646
647 uint8_t preamble[] = {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 != 96) return -5;
652 return (int)startIdx;
653 }
654
655 // by marshmellow
656 // FSK Demod then try to locate an Farpointe Data (pyramid) ID
657 int PyramiddemodFSK(uint8_t *dest, size_t *size)
658 {
659 //make sure buffer has data
660 if (*size < 128*50) return -5;
661
662 //test samples are not just noise
663 if (justNoise(dest, *size)) return -1;
664
665 // FSK demodulator
666 *size = fskdemod(dest, *size, 50, 1, 10, 8); // fsk2a RF/50
667 if (*size < 128) return -2; //did we get a good demod?
668
669 uint8_t preamble[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};
670 size_t startIdx = 0;
671 uint8_t errChk = preambleSearch(dest, preamble, sizeof(preamble), size, &startIdx);
672 if (errChk == 0) return -4; //preamble not found
673 if (*size != 128) return -3;
674 return (int)startIdx;
675 }
676
677 // by marshmellow
678 // to detect a wave that has heavily clipped (clean) samples
679 uint8_t DetectCleanAskWave(uint8_t dest[], size_t size, uint8_t high, uint8_t low)
680 {
681 uint16_t allPeaks=1;
682 uint16_t cntPeaks=0;
683 size_t loopEnd = 512+60;
684 if (loopEnd > size) loopEnd = size;
685 for (size_t i=60; i<loopEnd; i++){
686 if (dest[i]>low && dest[i]<high)
687 allPeaks=0;
688 else
689 cntPeaks++;
690 }
691 if (allPeaks == 0){
692 if (cntPeaks > 300) return 1;
693 }
694 return allPeaks;
695 }
696
697 // by marshmellow
698 // to help detect clocks on heavily clipped samples
699 // based on count of low to low
700 int DetectStrongAskClock(uint8_t dest[], size_t size, uint8_t high, uint8_t low)
701 {
702 uint8_t fndClk[] = {8,16,32,40,50,64,128};
703 size_t startwave;
704 size_t i = 0;
705 size_t minClk = 255;
706 // get to first full low to prime loop and skip incomplete first pulse
707 while ((dest[i] < high) && (i < size))
708 ++i;
709 while ((dest[i] > low) && (i < size))
710 ++i;
711
712 // loop through all samples
713 while (i < size) {
714 // measure from low to low
715 while ((dest[i] > low) && (i < size))
716 ++i;
717 startwave= i;
718 while ((dest[i] < high) && (i < size))
719 ++i;
720 while ((dest[i] > low) && (i < size))
721 ++i;
722 //get minimum measured distance
723 if (i-startwave < minClk && i < size)
724 minClk = i - startwave;
725 }
726 // set clock
727 for (uint8_t clkCnt = 0; clkCnt<7; clkCnt++) {
728 if (minClk >= fndClk[clkCnt]-(fndClk[clkCnt]/8) && minClk <= fndClk[clkCnt]+1)
729 return fndClk[clkCnt];
730 }
731 return 0;
732 }
733
734 // by marshmellow
735 // not perfect especially with lower clocks or VERY good antennas (heavy wave clipping)
736 // maybe somehow adjust peak trimming value based on samples to fix?
737 // return start index of best starting position for that clock and return clock (by reference)
738 int DetectASKClock(uint8_t dest[], size_t size, int *clock, int maxErr)
739 {
740 size_t i=1;
741 uint8_t clk[] = {255,8,16,32,40,50,64,100,128,255};
742 uint8_t clkEnd = 9;
743 uint8_t loopCnt = 255; //don't need to loop through entire array...
744 if (size <= loopCnt) return -1; //not enough samples
745
746 //if we already have a valid clock
747 uint8_t clockFnd=0;
748 for (;i<clkEnd;++i)
749 if (clk[i] == *clock) clockFnd = i;
750 //clock found but continue to find best startpos
751
752 //get high and low peak
753 int peak, low;
754 if (getHiLo(dest, loopCnt, &peak, &low, 75, 75) < 1) return -1;
755
756 //test for large clean peaks
757 if (!clockFnd){
758 if (DetectCleanAskWave(dest, size, peak, low)==1){
759 int ans = DetectStrongAskClock(dest, size, peak, low);
760 for (i=clkEnd-1; i>0; i--){
761 if (clk[i] == ans) {
762 *clock = ans;
763 //clockFnd = i;
764 return 0; // for strong waves i don't use the 'best start position' yet...
765 //break; //clock found but continue to find best startpos [not yet]
766 }
767 }
768 }
769 }
770
771 uint8_t ii;
772 uint8_t clkCnt, tol = 0;
773 uint16_t bestErr[]={1000,1000,1000,1000,1000,1000,1000,1000,1000};
774 uint8_t bestStart[]={0,0,0,0,0,0,0,0,0};
775 size_t errCnt = 0;
776 size_t arrLoc, loopEnd;
777
778 if (clockFnd>0) {
779 clkCnt = clockFnd;
780 clkEnd = clockFnd+1;
781 }
782 else clkCnt=1;
783
784 //test each valid clock from smallest to greatest to see which lines up
785 for(; clkCnt < clkEnd; clkCnt++){
786 if (clk[clkCnt] <= 32){
787 tol=1;
788 }else{
789 tol=0;
790 }
791 //if no errors allowed - keep start within the first clock
792 if (!maxErr && size > clk[clkCnt]*2 + tol && clk[clkCnt]<128) loopCnt=clk[clkCnt]*2;
793 bestErr[clkCnt]=1000;
794 //try lining up the peaks by moving starting point (try first few clocks)
795 for (ii=0; ii < loopCnt; ii++){
796 if (dest[ii] < peak && dest[ii] > low) continue;
797
798 errCnt=0;
799 // now that we have the first one lined up test rest of wave array
800 loopEnd = ((size-ii-tol) / clk[clkCnt]) - 1;
801 for (i=0; i < loopEnd; ++i){
802 arrLoc = ii + (i * clk[clkCnt]);
803 if (dest[arrLoc] >= peak || dest[arrLoc] <= low){
804 }else if (dest[arrLoc-tol] >= peak || dest[arrLoc-tol] <= low){
805 }else if (dest[arrLoc+tol] >= peak || dest[arrLoc+tol] <= low){
806 }else{ //error no peak detected
807 errCnt++;
808 }
809 }
810 //if we found no errors then we can stop here and a low clock (common clocks)
811 // this is correct one - return this clock
812 //PrintAndLog("DEBUG: clk %d, err %d, ii %d, i %d",clk[clkCnt],errCnt,ii,i);
813 if(errCnt==0 && clkCnt<7) {
814 if (!clockFnd) *clock = clk[clkCnt];
815 return ii;
816 }
817 //if we found errors see if it is lowest so far and save it as best run
818 if(errCnt<bestErr[clkCnt]){
819 bestErr[clkCnt]=errCnt;
820 bestStart[clkCnt]=ii;
821 }
822 }
823 }
824 uint8_t iii;
825 uint8_t best=0;
826 for (iii=1; iii<clkEnd; ++iii){
827 if (bestErr[iii] < bestErr[best]){
828 if (bestErr[iii] == 0) bestErr[iii]=1;
829 // current best bit to error ratio vs new bit to error ratio
830 if ( (size/clk[best])/bestErr[best] < (size/clk[iii])/bestErr[iii] ){
831 best = iii;
832 }
833 }
834 }
835 //if (bestErr[best] > maxErr) return -1;
836 if (!clockFnd) *clock = clk[best];
837 return bestStart[best];
838 }
839
840 //by marshmellow
841 //detect psk clock by reading each phase shift
842 // a phase shift is determined by measuring the sample length of each wave
843 int DetectPSKClock(uint8_t dest[], size_t size, int clock)
844 {
845 uint8_t clk[]={255,16,32,40,50,64,100,128,255}; //255 is not a valid clock
846 uint16_t loopCnt = 4096; //don't need to loop through entire array...
847 if (size == 0) return 0;
848 if (size<loopCnt) loopCnt = size;
849
850 //if we already have a valid clock quit
851 size_t i=1;
852 for (; i < 8; ++i)
853 if (clk[i] == clock) return clock;
854
855 size_t waveStart=0, waveEnd=0, firstFullWave=0, lastClkBit=0;
856 uint8_t clkCnt, fc=0, fullWaveLen=0, tol=1;
857 uint16_t peakcnt=0, errCnt=0, waveLenCnt=0;
858 uint16_t bestErr[]={1000,1000,1000,1000,1000,1000,1000,1000,1000};
859 uint16_t peaksdet[]={0,0,0,0,0,0,0,0,0};
860 fc = countFC(dest, size, 0);
861 if (fc!=2 && fc!=4 && fc!=8) return -1;
862 //PrintAndLog("DEBUG: FC: %d",fc);
863
864 //find first full wave
865 for (i=0; i<loopCnt; i++){
866 if (dest[i] < dest[i+1] && dest[i+1] >= dest[i+2]){
867 if (waveStart == 0) {
868 waveStart = i+1;
869 //PrintAndLog("DEBUG: waveStart: %d",waveStart);
870 } else {
871 waveEnd = i+1;
872 //PrintAndLog("DEBUG: waveEnd: %d",waveEnd);
873 waveLenCnt = waveEnd-waveStart;
874 if (waveLenCnt > fc){
875 firstFullWave = waveStart;
876 fullWaveLen=waveLenCnt;
877 break;
878 }
879 waveStart=0;
880 }
881 }
882 }
883 //PrintAndLog("DEBUG: firstFullWave: %d, waveLen: %d",firstFullWave,fullWaveLen);
884
885 //test each valid clock from greatest to smallest to see which lines up
886 for(clkCnt=7; clkCnt >= 1 ; clkCnt--){
887 lastClkBit = firstFullWave; //set end of wave as clock align
888 waveStart = 0;
889 errCnt=0;
890 peakcnt=0;
891 //PrintAndLog("DEBUG: clk: %d, lastClkBit: %d",clk[clkCnt],lastClkBit);
892
893 for (i = firstFullWave+fullWaveLen-1; i < loopCnt-2; i++){
894 //top edge of wave = start of new wave
895 if (dest[i] < dest[i+1] && dest[i+1] >= dest[i+2]){
896 if (waveStart == 0) {
897 waveStart = i+1;
898 waveLenCnt=0;
899 } else { //waveEnd
900 waveEnd = i+1;
901 waveLenCnt = waveEnd-waveStart;
902 if (waveLenCnt > fc){
903 //if this wave is a phase shift
904 //PrintAndLog("DEBUG: phase shift at: %d, len: %d, nextClk: %d, ii: %d, fc: %d",waveStart,waveLenCnt,lastClkBit+clk[clkCnt]-tol,ii+1,fc);
905 if (i+1 >= lastClkBit + clk[clkCnt] - tol){ //should be a clock bit
906 peakcnt++;
907 lastClkBit+=clk[clkCnt];
908 } else if (i<lastClkBit+8){
909 //noise after a phase shift - ignore
910 } else { //phase shift before supposed to based on clock
911 errCnt++;
912 }
913 } else if (i+1 > lastClkBit + clk[clkCnt] + tol + fc){
914 lastClkBit+=clk[clkCnt]; //no phase shift but clock bit
915 }
916 waveStart=i+1;
917 }
918 }
919 }
920 if (errCnt == 0){
921 return clk[clkCnt];
922 }
923 if (errCnt <= bestErr[clkCnt]) bestErr[clkCnt]=errCnt;
924 if (peakcnt > peaksdet[clkCnt]) peaksdet[clkCnt]=peakcnt;
925 }
926 //all tested with errors
927 //return the highest clk with the most peaks found
928 uint8_t best=7;
929 for (i=7; i>=1; i--){
930 if (peaksdet[i] > peaksdet[best]) {
931 best = i;
932 }
933 //PrintAndLog("DEBUG: Clk: %d, peaks: %d, errs: %d, bestClk: %d",clk[iii],peaksdet[iii],bestErr[iii],clk[best]);
934 }
935 return clk[best];
936 }
937
938 //by marshmellow
939 //detect nrz clock by reading #peaks vs no peaks(or errors)
940 int DetectNRZClock(uint8_t dest[], size_t size, int clock)
941 {
942 size_t i=0;
943 uint8_t clk[]={8,16,32,40,50,64,100,128,255};
944 size_t loopCnt = 4096; //don't need to loop through entire array...
945 if (size == 0) return 0;
946 if (size<loopCnt) loopCnt = size;
947
948 //if we already have a valid clock quit
949 for (; i < 8; ++i)
950 if (clk[i] == clock) return clock;
951
952 //get high and low peak
953 int peak, low;
954 if (getHiLo(dest, loopCnt, &peak, &low, 75, 75) < 1) return 0;
955
956 //PrintAndLog("DEBUG: peak: %d, low: %d",peak,low);
957 size_t ii;
958 uint8_t clkCnt;
959 uint8_t tol = 0;
960 uint16_t peakcnt=0;
961 uint16_t peaksdet[]={0,0,0,0,0,0,0,0};
962 uint16_t maxPeak=0;
963 //test for large clipped waves
964 for (i=0; i<loopCnt; i++){
965 if (dest[i] >= peak || dest[i] <= low){
966 peakcnt++;
967 } else {
968 if (peakcnt>0 && maxPeak < peakcnt){
969 maxPeak = peakcnt;
970 }
971 peakcnt=0;
972 }
973 }
974 peakcnt=0;
975 //test each valid clock from smallest to greatest to see which lines up
976 for(clkCnt=0; clkCnt < 8; ++clkCnt){
977 //ignore clocks smaller than largest peak
978 if (clk[clkCnt]<maxPeak) continue;
979
980 //try lining up the peaks by moving starting point (try first 256)
981 for (ii=0; ii< loopCnt; ++ii){
982 if ((dest[ii] >= peak) || (dest[ii] <= low)){
983 peakcnt=0;
984 // now that we have the first one lined up test rest of wave array
985 for (i=0; i < ((int)((size-ii-tol)/clk[clkCnt])-1); ++i){
986 if (dest[ii+(i*clk[clkCnt])]>=peak || dest[ii+(i*clk[clkCnt])]<=low){
987 peakcnt++;
988 }
989 }
990 if(peakcnt>peaksdet[clkCnt]) {
991 peaksdet[clkCnt]=peakcnt;
992 }
993 }
994 }
995 }
996 int iii=7;
997 uint8_t best=0;
998 for (iii=7; iii > 0; iii--){
999 if (peaksdet[iii] > peaksdet[best]){
1000 best = iii;
1001 }
1002 //PrintAndLog("DEBUG: Clk: %d, peaks: %d, errs: %d, bestClk: %d",clk[iii],peaksdet[iii],bestErr[iii],clk[best]);
1003 }
1004 return clk[best];
1005 }
1006
1007 // by marshmellow
1008 // convert psk1 demod to psk2 demod
1009 // only transition waves are 1s
1010 void psk1TOpsk2(uint8_t *BitStream, size_t size)
1011 {
1012 size_t i=1;
1013 uint8_t lastBit=BitStream[0];
1014 for (; i<size; i++){
1015 if (BitStream[i]==7){
1016 //ignore errors
1017 } else if (lastBit!=BitStream[i]){
1018 lastBit=BitStream[i];
1019 BitStream[i]=1;
1020 } else {
1021 BitStream[i]=0;
1022 }
1023 }
1024 return;
1025 }
1026
1027 // by marshmellow
1028 // convert psk2 demod to psk1 demod
1029 // from only transition waves are 1s to phase shifts change bit
1030 void psk2TOpsk1(uint8_t *BitStream, size_t size)
1031 {
1032 uint8_t phase=0;
1033 for (size_t i=0; i<size; i++){
1034 if (BitStream[i]==1){
1035 phase ^=1;
1036 }
1037 BitStream[i]=phase;
1038 }
1039 return;
1040 }
1041
1042 // redesigned by marshmellow adjusted from existing decode functions
1043 // indala id decoding - only tested on 26 bit tags, but attempted to make it work for more
1044 int indala26decode(uint8_t *bitStream, size_t *size, uint8_t *invert)
1045 {
1046 //26 bit 40134 format (don't know other formats)
1047 int i;
1048 int long_wait=29;//29 leading zeros in format
1049 int start;
1050 int first = 0;
1051 int first2 = 0;
1052 int bitCnt = 0;
1053 int ii;
1054 // Finding the start of a UID
1055 for (start = 0; start <= *size - 250; start++) {
1056 first = bitStream[start];
1057 for (i = start; i < start + long_wait; i++) {
1058 if (bitStream[i] != first) {
1059 break;
1060 }
1061 }
1062 if (i == (start + long_wait)) {
1063 break;
1064 }
1065 }
1066 if (start == *size - 250 + 1) {
1067 // did not find start sequence
1068 return -1;
1069 }
1070 // Inverting signal if needed
1071 if (first == 1) {
1072 for (i = start; i < *size; i++) {
1073 bitStream[i] = !bitStream[i];
1074 }
1075 *invert = 1;
1076 }else *invert=0;
1077
1078 int iii;
1079 //found start once now test length by finding next one
1080 for (ii=start+29; ii <= *size - 250; ii++) {
1081 first2 = bitStream[ii];
1082 for (iii = ii; iii < ii + long_wait; iii++) {
1083 if (bitStream[iii] != first2) {
1084 break;
1085 }
1086 }
1087 if (iii == (ii + long_wait)) {
1088 break;
1089 }
1090 }
1091 if (ii== *size - 250 + 1){
1092 // did not find second start sequence
1093 return -2;
1094 }
1095 bitCnt=ii-start;
1096
1097 // Dumping UID
1098 i = start;
1099 for (ii = 0; ii < bitCnt; ii++) {
1100 bitStream[ii] = bitStream[i++];
1101 }
1102 *size=bitCnt;
1103 return 1;
1104 }
1105
1106 // by marshmellow - demodulate NRZ wave (both similar enough)
1107 // peaks invert bit (high=1 low=0) each clock cycle = 1 bit determined by last peak
1108 // there probably is a much simpler way to do this....
1109 int nrzRawDemod(uint8_t *dest, size_t *size, int *clk, int *invert, int maxErr)
1110 {
1111 if (justNoise(dest, *size)) return -1;
1112 *clk = DetectNRZClock(dest, *size, *clk);
1113 if (*clk==0) return -2;
1114 size_t i, gLen = 4096;
1115 if (gLen>*size) gLen = *size;
1116 int high, low;
1117 if (getHiLo(dest, gLen, &high, &low, 75, 75) < 1) return -3; //25% fuzz on high 25% fuzz on low
1118 int lastBit = 0; //set first clock check
1119 size_t iii = 0, bitnum = 0; //bitnum counter
1120 uint16_t errCnt = 0, MaxBits = 1000;
1121 size_t bestErrCnt = maxErr+1;
1122 size_t bestPeakCnt = 0, bestPeakStart = 0;
1123 uint8_t bestFirstPeakHigh=0, firstPeakHigh=0, curBit=0, bitHigh=0, errBitHigh=0;
1124 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
1125 uint16_t peakCnt=0;
1126 uint8_t ignoreWindow=4;
1127 uint8_t ignoreCnt=ignoreWindow; //in case of noise near peak
1128 //loop to find first wave that works - align to clock
1129 for (iii=0; iii < gLen; ++iii){
1130 if ((dest[iii]>=high) || (dest[iii]<=low)){
1131 if (dest[iii]>=high) firstPeakHigh=1;
1132 else firstPeakHigh=0;
1133 lastBit=iii-*clk;
1134 peakCnt=0;
1135 errCnt=0;
1136 //loop through to see if this start location works
1137 for (i = iii; i < *size; ++i) {
1138 // if we are at a clock bit
1139 if ((i >= lastBit + *clk - tol) && (i <= lastBit + *clk + tol)) {
1140 //test high/low
1141 if (dest[i] >= high || dest[i] <= low) {
1142 bitHigh = 1;
1143 peakCnt++;
1144 errBitHigh = 0;
1145 ignoreCnt = ignoreWindow;
1146 lastBit += *clk;
1147 } else if (i == lastBit + *clk + tol) {
1148 lastBit += *clk;
1149 }
1150 //else if no bars found
1151 } else if (dest[i] < high && dest[i] > low){
1152 if (ignoreCnt==0){
1153 bitHigh=0;
1154 if (errBitHigh==1) errCnt++;
1155 errBitHigh=0;
1156 } else {
1157 ignoreCnt--;
1158 }
1159 } else if ((dest[i]>=high || dest[i]<=low) && (bitHigh==0)) {
1160 //error bar found no clock...
1161 errBitHigh=1;
1162 }
1163 if (((i-iii) / *clk)>=MaxBits) break;
1164 }
1165 //we got more than 64 good bits and not all errors
1166 if (((i-iii) / *clk) > 64 && (errCnt <= (maxErr))) {
1167 //possible good read
1168 if (!errCnt || peakCnt > bestPeakCnt){
1169 bestFirstPeakHigh=firstPeakHigh;
1170 bestErrCnt = errCnt;
1171 bestPeakCnt = peakCnt;
1172 bestPeakStart = iii;
1173 if (!errCnt) break; //great read - finish
1174 }
1175 }
1176 }
1177 }
1178 //PrintAndLog("DEBUG: bestErrCnt: %d, maxErr: %d, bestStart: %d, bestPeakCnt: %d, bestPeakStart: %d",bestErrCnt,maxErr,bestStart,bestPeakCnt,bestPeakStart);
1179 if (bestErrCnt > maxErr) return bestErrCnt;
1180
1181 //best run is good enough set to best run and set overwrite BinStream
1182 lastBit = bestPeakStart - *clk;
1183 memset(dest, bestFirstPeakHigh^1, bestPeakStart / *clk);
1184 bitnum += (bestPeakStart / *clk);
1185 for (i = bestPeakStart; i < *size; ++i) {
1186 // if expecting a clock bit
1187 if ((i >= lastBit + *clk - tol) && (i <= lastBit + *clk + tol)) {
1188 // test high/low
1189 if (dest[i] >= high || dest[i] <= low) {
1190 peakCnt++;
1191 bitHigh = 1;
1192 errBitHigh = 0;
1193 ignoreCnt = ignoreWindow;
1194 curBit = *invert;
1195 if (dest[i] >= high) curBit ^= 1;
1196 dest[bitnum++] = curBit;
1197 lastBit += *clk;
1198 //else no bars found in clock area
1199 } else if (i == lastBit + *clk + tol) {
1200 dest[bitnum++] = curBit;
1201 lastBit += *clk;
1202 }
1203 //else if no bars found
1204 } else if (dest[i] < high && dest[i] > low){
1205 if (ignoreCnt == 0){
1206 bitHigh = 0;
1207 if (errBitHigh == 1){
1208 dest[bitnum++] = 7;
1209 errCnt++;
1210 }
1211 errBitHigh=0;
1212 } else {
1213 ignoreCnt--;
1214 }
1215 } else if ((dest[i] >= high || dest[i] <= low) && (bitHigh == 0)) {
1216 //error bar found no clock...
1217 errBitHigh=1;
1218 }
1219 if (bitnum >= MaxBits) break;
1220 }
1221 *size = bitnum;
1222 return bestErrCnt;
1223 }
1224
1225 //by marshmellow
1226 //detects the bit clock for FSK given the high and low Field Clocks
1227 uint8_t detectFSKClk(uint8_t *BitStream, size_t size, uint8_t fcHigh, uint8_t fcLow)
1228 {
1229 uint8_t clk[] = {8,16,32,40,50,64,100,128,0};
1230 uint16_t rfLens[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
1231 uint8_t rfCnts[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
1232 uint8_t rfLensFnd = 0;
1233 uint8_t lastFCcnt = 0;
1234 uint16_t fcCounter = 0;
1235 uint16_t rfCounter = 0;
1236 uint8_t firstBitFnd = 0;
1237 size_t i;
1238 if (size == 0) return 0;
1239
1240 uint8_t fcTol = (uint8_t)(0.5+(float)(fcHigh-fcLow)/2);
1241 rfLensFnd=0;
1242 fcCounter=0;
1243 rfCounter=0;
1244 firstBitFnd=0;
1245 //PrintAndLog("DEBUG: fcTol: %d",fcTol);
1246 // prime i to first up transition
1247 for (i = 1; i < size-1; i++)
1248 if (BitStream[i] > BitStream[i-1] && BitStream[i]>=BitStream[i+1])
1249 break;
1250
1251 for (; i < size-1; i++){
1252 fcCounter++;
1253 rfCounter++;
1254
1255 if (BitStream[i] <= BitStream[i-1] || BitStream[i] < BitStream[i+1])
1256 continue;
1257 // else new peak
1258 // if we got less than the small fc + tolerance then set it to the small fc
1259 if (fcCounter < fcLow+fcTol)
1260 fcCounter = fcLow;
1261 else //set it to the large fc
1262 fcCounter = fcHigh;
1263
1264 //look for bit clock (rf/xx)
1265 if ((fcCounter < lastFCcnt || fcCounter > lastFCcnt)){
1266 //not the same size as the last wave - start of new bit sequence
1267 if (firstBitFnd > 1){ //skip first wave change - probably not a complete bit
1268 for (int ii=0; ii<15; ii++){
1269 if (rfLens[ii] == rfCounter){
1270 rfCnts[ii]++;
1271 rfCounter = 0;
1272 break;
1273 }
1274 }
1275 if (rfCounter > 0 && rfLensFnd < 15){
1276 //PrintAndLog("DEBUG: rfCntr %d, fcCntr %d",rfCounter,fcCounter);
1277 rfCnts[rfLensFnd]++;
1278 rfLens[rfLensFnd++] = rfCounter;
1279 }
1280 } else {
1281 firstBitFnd++;
1282 }
1283 rfCounter=0;
1284 lastFCcnt=fcCounter;
1285 }
1286 fcCounter=0;
1287 }
1288 uint8_t rfHighest=15, rfHighest2=15, rfHighest3=15;
1289
1290 for (i=0; i<15; i++){
1291 //PrintAndLog("DEBUG: RF %d, cnts %d",rfLens[i], rfCnts[i]);
1292 //get highest 2 RF values (might need to get more values to compare or compare all?)
1293 if (rfCnts[i]>rfCnts[rfHighest]){
1294 rfHighest3=rfHighest2;
1295 rfHighest2=rfHighest;
1296 rfHighest=i;
1297 } else if(rfCnts[i]>rfCnts[rfHighest2]){
1298 rfHighest3=rfHighest2;
1299 rfHighest2=i;
1300 } else if(rfCnts[i]>rfCnts[rfHighest3]){
1301 rfHighest3=i;
1302 }
1303 }
1304 // set allowed clock remainder tolerance to be 1 large field clock length+1
1305 // we could have mistakenly made a 9 a 10 instead of an 8 or visa versa so rfLens could be 1 FC off
1306 uint8_t tol1 = fcHigh+1;
1307
1308 //PrintAndLog("DEBUG: hightest: 1 %d, 2 %d, 3 %d",rfLens[rfHighest],rfLens[rfHighest2],rfLens[rfHighest3]);
1309
1310 // loop to find the highest clock that has a remainder less than the tolerance
1311 // compare samples counted divided by
1312 int ii=7;
1313 for (; ii>=0; ii--){
1314 if (rfLens[rfHighest] % clk[ii] < tol1 || rfLens[rfHighest] % clk[ii] > clk[ii]-tol1){
1315 if (rfLens[rfHighest2] % clk[ii] < tol1 || rfLens[rfHighest2] % clk[ii] > clk[ii]-tol1){
1316 if (rfLens[rfHighest3] % clk[ii] < tol1 || rfLens[rfHighest3] % clk[ii] > clk[ii]-tol1){
1317 break;
1318 }
1319 }
1320 }
1321 }
1322
1323 if (ii<0) return 0; // oops we went too far
1324
1325 return clk[ii];
1326 }
1327
1328 //by marshmellow
1329 //countFC is to detect the field clock lengths.
1330 //counts and returns the 2 most common wave lengths
1331 //mainly used for FSK field clock detection
1332 uint16_t countFC(uint8_t *BitStream, size_t size, uint8_t fskAdj)
1333 {
1334 uint8_t fcLens[] = {0,0,0,0,0,0,0,0,0,0};
1335 uint16_t fcCnts[] = {0,0,0,0,0,0,0,0,0,0};
1336 uint8_t fcLensFnd = 0;
1337 uint8_t lastFCcnt=0;
1338 uint8_t fcCounter = 0;
1339 size_t i;
1340 if (size == 0) return 0;
1341
1342 // prime i to first up transition
1343 for (i = 1; i < size-1; i++)
1344 if (BitStream[i] > BitStream[i-1] && BitStream[i] >= BitStream[i+1])
1345 break;
1346
1347 for (; i < size-1; i++){
1348 if (BitStream[i] > BitStream[i-1] && BitStream[i] >= BitStream[i+1]){
1349 // new up transition
1350 fcCounter++;
1351 if (fskAdj){
1352 //if we had 5 and now have 9 then go back to 8 (for when we get a fc 9 instead of an 8)
1353 if (lastFCcnt==5 && fcCounter==9) fcCounter--;
1354 //if fc=9 or 4 add one (for when we get a fc 9 instead of 10 or a 4 instead of a 5)
1355 if ((fcCounter==9) || fcCounter==4) fcCounter++;
1356 // save last field clock count (fc/xx)
1357 lastFCcnt = fcCounter;
1358 }
1359 // find which fcLens to save it to:
1360 for (int ii=0; ii<10; ii++){
1361 if (fcLens[ii]==fcCounter){
1362 fcCnts[ii]++;
1363 fcCounter=0;
1364 break;
1365 }
1366 }
1367 if (fcCounter>0 && fcLensFnd<10){
1368 //add new fc length
1369 fcCnts[fcLensFnd]++;
1370 fcLens[fcLensFnd++]=fcCounter;
1371 }
1372 fcCounter=0;
1373 } else {
1374 // count sample
1375 fcCounter++;
1376 }
1377 }
1378
1379 uint8_t best1=9, best2=9, best3=9;
1380 uint16_t maxCnt1=0;
1381 // go through fclens and find which ones are bigest 2
1382 for (i=0; i<10; i++){
1383 // PrintAndLog("DEBUG: FC %d, Cnt %d, Errs %d",fcLens[i],fcCnts[i],errCnt);
1384 // get the 3 best FC values
1385 if (fcCnts[i]>maxCnt1) {
1386 best3=best2;
1387 best2=best1;
1388 maxCnt1=fcCnts[i];
1389 best1=i;
1390 } else if(fcCnts[i]>fcCnts[best2]){
1391 best3=best2;
1392 best2=i;
1393 } else if(fcCnts[i]>fcCnts[best3]){
1394 best3=i;
1395 }
1396 }
1397 uint8_t fcH=0, fcL=0;
1398 if (fcLens[best1]>fcLens[best2]){
1399 fcH=fcLens[best1];
1400 fcL=fcLens[best2];
1401 } else{
1402 fcH=fcLens[best2];
1403 fcL=fcLens[best1];
1404 }
1405
1406 // TODO: take top 3 answers and compare to known Field clocks to get top 2
1407
1408 uint16_t fcs = (((uint16_t)fcH)<<8) | fcL;
1409 // PrintAndLog("DEBUG: Best %d best2 %d best3 %d",fcLens[best1],fcLens[best2],fcLens[best3]);
1410 if (fskAdj) return fcs;
1411 return fcLens[best1];
1412 }
1413
1414 //by marshmellow - demodulate PSK1 wave
1415 //uses wave lengths (# Samples)
1416 int pskRawDemod(uint8_t dest[], size_t *size, int *clock, int *invert)
1417 {
1418 if (size == 0) return -1;
1419 uint16_t loopCnt = 4096; //don't need to loop through entire array...
1420 if (*size<loopCnt) loopCnt = *size;
1421
1422 uint8_t curPhase = *invert;
1423 size_t i, waveStart=1, waveEnd=0, firstFullWave=0, lastClkBit=0;
1424 uint8_t fc=0, fullWaveLen=0, tol=1;
1425 uint16_t errCnt=0, waveLenCnt=0;
1426 fc = countFC(dest, *size, 0);
1427 if (fc!=2 && fc!=4 && fc!=8) return -1;
1428 //PrintAndLog("DEBUG: FC: %d",fc);
1429 *clock = DetectPSKClock(dest, *size, *clock);
1430 if (*clock == 0) return -1;
1431 int avgWaveVal=0, lastAvgWaveVal=0;
1432 //find first phase shift
1433 for (i=0; i<loopCnt; i++){
1434 if (dest[i]+fc < dest[i+1] && dest[i+1] >= dest[i+2]){
1435 waveEnd = i+1;
1436 //PrintAndLog("DEBUG: waveEnd: %d",waveEnd);
1437 waveLenCnt = waveEnd-waveStart;
1438 if (waveLenCnt > fc && waveStart > fc){ //not first peak and is a large wave
1439 lastAvgWaveVal = avgWaveVal/(waveLenCnt);
1440 firstFullWave = waveStart;
1441 fullWaveLen=waveLenCnt;
1442 //if average wave value is > graph 0 then it is an up wave or a 1
1443 if (lastAvgWaveVal > 123) curPhase ^= 1; //fudge graph 0 a little 123 vs 128
1444 break;
1445 }
1446 waveStart = i+1;
1447 avgWaveVal = 0;
1448 }
1449 avgWaveVal += dest[i+2];
1450 }
1451 //PrintAndLog("DEBUG: firstFullWave: %d, waveLen: %d",firstFullWave,fullWaveLen);
1452 lastClkBit = firstFullWave; //set start of wave as clock align
1453 //PrintAndLog("DEBUG: clk: %d, lastClkBit: %d", *clock, lastClkBit);
1454 waveStart = 0;
1455 size_t numBits=0;
1456 //set skipped bits
1457 memset(dest, curPhase^1, firstFullWave / *clock);
1458 numBits += (firstFullWave / *clock);
1459 dest[numBits++] = curPhase; //set first read bit
1460 for (i = firstFullWave + fullWaveLen - 1; i < *size-3; i++){
1461 //top edge of wave = start of new wave
1462 if (dest[i]+fc < dest[i+1] && dest[i+1] >= dest[i+2]){
1463 if (waveStart == 0) {
1464 waveStart = i+1;
1465 waveLenCnt = 0;
1466 avgWaveVal = dest[i+1];
1467 } else { //waveEnd
1468 waveEnd = i+1;
1469 waveLenCnt = waveEnd-waveStart;
1470 lastAvgWaveVal = avgWaveVal/waveLenCnt;
1471 if (waveLenCnt > fc){
1472 //PrintAndLog("DEBUG: avgWaveVal: %d, waveSum: %d",lastAvgWaveVal,avgWaveVal);
1473 //this wave is a phase shift
1474 //PrintAndLog("DEBUG: phase shift at: %d, len: %d, nextClk: %d, i: %d, fc: %d",waveStart,waveLenCnt,lastClkBit+*clock-tol,i+1,fc);
1475 if (i+1 >= lastClkBit + *clock - tol){ //should be a clock bit
1476 curPhase ^= 1;
1477 dest[numBits++] = curPhase;
1478 lastClkBit += *clock;
1479 } else if (i < lastClkBit+10+fc){
1480 //noise after a phase shift - ignore
1481 } else { //phase shift before supposed to based on clock
1482 errCnt++;
1483 dest[numBits++] = 7;
1484 }
1485 } else if (i+1 > lastClkBit + *clock + tol + fc){
1486 lastClkBit += *clock; //no phase shift but clock bit
1487 dest[numBits++] = curPhase;
1488 }
1489 avgWaveVal = 0;
1490 waveStart = i+1;
1491 }
1492 }
1493 avgWaveVal += dest[i+1];
1494 }
1495 *size = numBits;
1496 return errCnt;
1497 }
1498 // on successful return 1 otherwise return 0
1499 int VikingDecode(uint8_t *BitStream,
1500 size_t size,
1501 size_t *startIdx,
1502 uint8_t *id_bits,
1503 size_t id_bits_size)
1504 {
1505 //no arguments needed - built this way in case we want this to be a direct call from "data " cmds in the future
1506 // otherwise could be a void with no arguments
1507 //set defaults
1508 uint32_t i = 0;
1509 uint32_t lastcheckindex = size - (id_bits_size * 2);
1510 int found = 0;
1511 while (i < lastcheckindex)
1512 {
1513 if (memcmp(BitStream + i,id_bits,id_bits_size) == 0)
1514 {
1515 *startIdx = i;
1516 found = 1;
1517 break;
1518 }
1519 i++;
1520 }
1521 return found;
1522 }
1523
1524
Impressum, Datenschutz