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