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