Image/ExifTool/LigoGPS.pm untested

filter: Statementstmt 0.0% 0 / 224 Branchbran 0.0% 0 / 120 Conditioncond 0.0% 0 / 115 MC/DCmcdc 0.0% 0 / 70 Subroutinesub 0.0% 0 / 16 Podpod 0.0% 0 / 12 totaltotal 0.0% 0 / 557 CC 61 SCAR 49.0
CC
61
Cov
0%
DecipherLigoGPS
210.0
ProcessLigoJSON
182.0
DecryptLigoGPS
156.0
CRAP 134.4
1 #------------------------------------------------------------------------------
2 # File: LigoGPS.pm
3 #
4 # Description: Read LIGOGPSINFO timed GPS records
5 #
6 # Revisions: 2024-12-30 - P. Harvey Created
7 #------------------------------------------------------------------------------
8 package Image::ExifTool::LigoGPS;
9  
10 use strict;
11 use vars qw($VERSION);
12 use Image::ExifTool;
13  
14 $VERSION = '1.06';
15  
16 sub ProcessLigoGPS($$$;$);
17 sub ProcessLigoJSON($$$);
18 sub OrderCipherDigits($$$;$);
19  
20 my $knotsToKph = 1.852; # knots --> km/h
21  
22 #------------------------------------------------------------------------------
23 # Clean up cipher variables and print warning if deciphering was unsuccessful
24 # Inputs: 0) ExifTool ref
25 sub CleanupCipher($)
26 {
27 my $et = shift;
28 if ($$et{LigoCipher} and $$et{LigoCipher}{'next'}) {
29 $et->Warn('Not enough GPS points to determine cipher for decoding LIGOGPSINFO');
30 }
31 delete $$et{LigoCipher};
32 }
33  
34 #------------------------------------------------------------------------------
35 # Un-do LIGOGPS fuzzing
36 # Inputs: 0) fuzzed latitude, 1) fuzzed longitude, 2) scale factor
37 # Returns: 0) latitude, 1) longitude
38 sub UnfuzzLigoGPS($$$)
39 {
40 my ($lat, $lon, $scl) = @_;
41 my $lat2 = int($lat / 10) * 10;
42 my $lon2 = int($lon / 10) * 10;
43 return($lat2 + ($lon - $lon2) * $scl, $lon2 + ($lat - $lat2) * $scl);
44 }
45  
46 #------------------------------------------------------------------------------
47 # Decrypt LIGOGPSINFO record (starting with "####")
48 # Inputs: 0) encrypted GPS record incuding 8-byte header
49 # Returns: decrypted record including 4-byte uint32 header, or undef on error
50 sub DecryptLigoGPS($)
51 {
52 my $str = shift;
53 my $num = unpack('x4V',$str);
54 return undef if $num < 4;
55 $num = 0x84 if $num > 0x84; # (be safe)
56 my @in = unpack("x8C$num",$str);
57 my @out;
58 while (@in) {
59 my $b = shift @in; # get next byte in data
60 # upper 3 bits steer the decryption for this round
61 my $steeringBits = $b & 0xe0;
62 if ($steeringBits >= 0xc0) {
63 return undef if @in < 4; # next 4 bytes are encrypted data
64 push @out, (shift(@in) | $b & 0x01) ^ 0x20,
65 (shift(@in) | $b & 0x02) ^ 0x20,
66 (shift(@in) | $b & 0x0c) ^ 0x20,
67 shift(@in) ^ 0x20 | $b & 0x30;
68 } elsif ($steeringBits >= 0x40) {
69 return undef if @in < 3; # next 3 bytes are encrypted data
70 if ($steeringBits == 0x40) {
71 push @out, 0x20,
72 (shift(@in) | $b & 0x01) ^ 0x20,
73 (shift(@in) | $b & 0x06) ^ 0x20,
74 (shift(@in) | $b & 0x18) ^ 0x20;
75 } elsif ($steeringBits == 0x60) {
76 push @out, (shift(@in) | $b & 0x03) ^ 0x20,
77 0x20,
78 (shift(@in) | $b & 0x04) ^ 0x20,
79 (shift(@in) | $b & 0x18) ^ 0x20;
80 } elsif ($steeringBits == 0x80) {
81 push @out, (shift(@in) | $b & 0x03) ^ 0x20,
82 (shift(@in) | $b & 0x0c) ^ 0x20,
83 0x20,
84 (shift(@in) | $b & 0x10) ^ 0x20;
85 } else {
86 push @out, (shift(@in) | $b & 0x01) ^ 0x20,
87 (shift(@in) | $b & 0x06) ^ 0x20,
88 (shift(@in) | $b & 0x18) ^ 0x20,
89 0x20;
90 }
91 } elsif ($steeringBits == 0x00) {
92 return undef if @in < 1; # next byte is encrypted data
93 push @out, shift(@in) | $b & 0x13;
94 } else {
95 return undef; # (shouldn't happen)
96 }
97 }
98 return pack 'C*', @out;
99 }
100  
101 #------------------------------------------------------------------------------
102 # Determine correct ordering of enciphered digits (unit digits of seconds)
103 # Inputs: 0) starting character code, 1) lookup for next character(s) in sequence
104 # 2) i/o list of ordered characters, 3) hash of used characters
105 # Returns: true if a consistent ordering was found
106 # - loops through all possible orders based on $next sequence until a complete
107 # cycle is established
108 # - this complexity is necessary because GPS may skip some seconds
109 sub OrderCipherDigits($$$;$)
110 {
111 my ($ch, $next, $order, $did) = @_;
112 $did or $did = { };
113 while ($$next{$ch}) {
114 if (@$order < 10) {
115 last if $$did{$ch};
116 } else {
117 # success if we have cycled through all 10 digits and back to the first
118 return 1 if @$order == 10 and $ch eq $$order[0];
119 last;
120 }
121 push @$order, $ch;
122 $$did{$ch} = 1;
123 # continue with next character if there is only one possibility
124 @{$$next{$ch}} == 1 and $ch = $$next{$ch}[0], next;
125 # otherwise, test all possibilities
126 my $n = $#$order;
127 foreach (@{$$next{$ch}}) {
128 my %did = %$did; # make a copy of the used-character lookup
129 return 1 if OrderCipherDigits($_, $next, $order, \%did);
130 $#$order = $n; # restore order and try next possibility
131 }
132 last;
133 }
134 return 0; # failure
135 }
136  
137 #------------------------------------------------------------------------------
138 # Decipher and parse LIGOGPSINFO record (starting with "####")
139 # Inputs: 0) ExifTool ref, 1) enciphered string, 2) tag table ref
140 # 3) true if GPS coordinates don't need de-fuzzing
141 # Returns: true if this looked like an enciphered string
142 # Notes: handles contained tags, but may defer handling until full cipher is known
143 sub DecipherLigoGPS($$$;$)
144 {
145 my ($et, $str, $tagTbl, $noFuzz) = @_;
146  
147 # (enciphered characters must be in the range 0x30-0x5f ('0' - '_'))
148 $str =~ m[^####.{4}([0-_])[0-_]{3}/[0-_]{2}/[0-_]{2} ..([0-_])..([0-_]).([0-_]) ]s or return undef;
149 return undef unless $2 eq $3; # (colons in time string must be the same)
150  
151 my $cipherInfo = $$et{LigoCipher};
152 unless ($cipherInfo) {
153 $cipherInfo = $$et{LigoCipher} = { cache => [ ], 'next' => { } };
154 $et->AddCleanup(\&CleanupCipher);
155 };
156 my $decipher = $$cipherInfo{decipher};
157 my $cache = $$cipherInfo{cache};
158  
159 # determine the cipher code table based on the advancing 1's digit of seconds
160 unless ($decipher) {
161 push @$cache, $str; # cache records until we can decipher them
162 my $next = $$cipherInfo{next};
163 my ($millennium, $colon, $ch2) = ($1, $2, $4);
164 # determine the cipher lookup table
165 # (only characters in range 0x30-0x5f are encrypted)
166 my $ch1 = $$cipherInfo{ch1};
167 $$cipherInfo{ch1} = $ch2;
168 return 1 if not defined $ch1 or $ch1 eq $ch2; # ignore duplicate sequential digits
169 if ($$next{$ch1}) {
170 return 1 if grep /\Q$ch2\E/, @{$$next{$ch1}}; # don't add twice
171 push @{$$next{$ch1}}, $ch2;
172 } else {
173 $$next{$ch1} = [ $ch2 ];
174 }
175 # must wait until the lookup contains all 10 digits
176 scalar(keys %$next) < 10 and return 1;
177 # protect against trying to decipher bad data
178 scalar(keys %$next) > 10 and $$cipherInfo{'next'} = { }, return 1;
179 my (@order, $two);
180 return 1 unless OrderCipherDigits($ch1, $next, \@order);
181 # get index of enciphered "2" in ordered array
182 $order[$_] eq $millennium and $two = $_, last foreach 0..9;
183 defined $two or $et->Warn('Problem deciphering LIGOGPSINFO'), return 1;
184 delete $$cipherInfo{'next'}; # all done with 'next' lookup
185 my %decipher = ( $colon => ':' ); # (':' is the time separator)
186 foreach (0..9) {
187 my $ch = $order[($_ + $two - 2 + 10) % 10];
188 $decipher{$ch} = chr($_ + 0x30);
189 }
190 # may also know the lat/lon quadrant from the signs of the coordinates
191 if ($str =~ / ([0-_])$colon(-?).*? ([0-_])$colon(-?)/) {
192 @decipher{$1,$3} = ($2 ? 'S' : 'N', $4 ? 'W' : 'E');
193 unless ($2 or $4) {
194 my ($ns, $ew) = ($1, $3);
195 if ($$et{OPTIONS}{GPSQuadrant} and $$et{OPTIONS}{GPSQuadrant} =~ /^([NS])([EW])$/i) {
196 @decipher{$ns,$ew} = (uc($1), uc($2));
197 } else {
198 $et->Warn('May need to set API GPSQuadrant option (eg. "NW")');
199 }
200 }
201 }
202 # fill in unknown entries with '?' (only chars 0x30-0x5f are enciphered)
203 defined $decipher{$_} or $decipher{$_} = '?' foreach map(chr, 0x30..0x5f);
204 $decipher = $$cipherInfo{decipher} = \%decipher;
205 $str = shift @$cache; # start deciphering at oldest cache entry
206 }
207  
208 # apply reverse cipher and extract GPS information
209 do {
210 my $pre = substr($str, 4, 4); # save second 4 bytes of header
211 ($str = substr($str,8)) =~ s/\0+$//; # remove 8-byte header and null padding
212 $str =~ s/([0-_])/$$decipher{$1}/g; # decipher
213 if ($$et{OPTIONS}{Verbose} > 1) {
214 $et->VPrint(1, "$$et{INDENT}\(Deciphered: ".unpack('H8',$pre)." $str)\n");
215 }
216 # add back leading 4 bytes (int16u counter plus 2 unknown bytes), and parse
217 ParseLigoGPS($et, "$pre$str", $tagTbl, $noFuzz);
218 } while $str = shift @$cache;
219  
220 return 1;
221 }
222  
223 #------------------------------------------------------------------------------
224 # Parse decrypted/deciphered (but not defuzzed) LIGOGPSINFO record
225 # (record starts with 4-byte int32u counter followed by date/time, etc)
226 # Inputs: 0) ExifTool ref, 1) GPS string, 2) tag table ref,
227 # 3) flags: 0x01=not fuzzed, 0x02=spd in km/h
228 # Returns: nothing
229 sub ParseLigoGPS($$$;$)
230 {
231 my ($et, $str, $tagTbl, $flags) = @_;
232  
233 # example string input
234 # "....2022/09/19 12:45:24 N:31.285065 W:124.759483 46.93 km/h x:-0.000 y:-0.000 z:-0.000"
235 unless ($str=~ /^.{4}(\S+ \S+)\s+([NS?]):(-?)([.\d]+)\s+([EW?]):(-?)([\.\d]+)\s+([.\d]+)/s) {
236 $et->Warn('LIGOGPSINFO format error');
237 return;
238 }
239 $flags or $flags = 0;
240 my ($time,$latRef,$latNeg,$lat,$lonRef,$lonNeg,$lon,$spd) = ($1,$2,$3,$4,$5,$6,$7,$8);
241 my %gpsScl = ( 1 => 1.524855137, 2 => 1.456027985, 3 => 1.15368 );
242 my $spdScl = $flags & 0x01 ? ($flags & 0x02 ? 1 : $knotsToKph) : 1.85407333;
243 $$et{DOC_NUM} = ++$$et{DOC_COUNT};
244 $time =~ tr(/)(:);
245 # convert from DDMM.MMMMMM to DD.DDDDDD if necessary
246 # (speed wasn't scaled in my 1 sample with this format)
247 $lat =~ /^\d{3}/ and Image::ExifTool::QuickTime::ConvertLatLon($lat,$lon), $spdScl = 1;
248 unless ($flags & 0x01) { # unfuzz the coordinates if necessary
249 my $scl = $$et{OPTIONS}{LigoGPSScale} || $$et{LigoGPSScale} || 1;
250 $scl = $gpsScl{$scl} if $gpsScl{$scl};
251 ($lat, $lon) = UnfuzzLigoGPS($lat, $lon, $scl);
252 }
253 # a final sanity check
254 ($lat > 90 or $lon > 180) and $et->Warn('LIGOGPSINFO coordinates out of range'), return;
255 $$et{SET_GROUP1} = 'LIGO';
256 $et->HandleTag($tagTbl, 'GPSDateTime', $time);
257 # (ignore N/S/E/W if coordinate is signed)
258 $et->HandleTag($tagTbl, 'GPSLatitude', $lat * (($latNeg or $latRef eq 'S') ? -1 : 1));
259 $et->HandleTag($tagTbl, 'GPSLongitude', $lon * (($lonNeg or $lonRef eq 'W') ? -1 : 1));
260 $et->HandleTag($tagTbl, 'GPSSpeed', $spd * $spdScl);
261 $et->HandleTag($tagTbl, 'GPSTrack', $1) if $str =~ /\bA:(\S+)/;
262 $et->HandleTag($tagTbl, 'GPSAltitude', $1) if $str =~ /\bH:(\S+)/;
263 $et->HandleTag($tagTbl, 'MagneticVariation', $1) if $str =~ /\bM:(\S+)/;
264 # (have a sample where tab is used to separate acc components)
265 $et->HandleTag($tagTbl, 'Accelerometer',"$1 $2 $3") if $str =~ /x:(\S+)\sy:(\S+)\sz:(\S+)/;
266 delete $$et{SET_GROUP1};
267 }
268  
269 #------------------------------------------------------------------------------
270 # Process GKU dashcam trailer containing JSON-format LigoGPS
271 # Inputs: 0) ExifTool ref, 1) dirInfo ref, 2) tag table ref
272 # Returns: 1 on success
273 sub ProcessGKU($$$;$)
274 {
275 my ($et, $dirInfo, $tagTbl) = @_;
276 my $dataPt = $$dirInfo{DataPt};
277 my $pos = unpack('V', $$dataPt);
278 return 0 if $pos + 13 > length $$dataPt or substr($$dataPt, $pos, 13) ne 'LIGOGPSINFO {';
279 pos($$dataPt) = $pos;
280 return ProcessLigoJSON($et, $dirInfo, $tagTbl);
281 }
282  
283 #------------------------------------------------------------------------------
284 # Process LIGOGPSINFO data (non-JSON format)
285 # Inputs: 0) ExifTool object ref, 1) dirInfo ref, 2) tag table ref
286 # 3) 1=LIGOGPS lat/lon/spd weren't fuzzed
287 # Returns: 1 on success
288 # Notes: The directory data should start with the string "LIGOGPSINFO\0"
289 sub ProcessLigoGPS($$$;$)
290 {
291 my ($et, $dirInfo, $tagTbl, $noFuzz) = @_;
292 my $dataPt = $$dirInfo{DataPt};
293 my $pos = ($$dirInfo{DirStart} || 0) + 0x14;
294 return undef if $pos > length $$dataPt;
295 my $cipherInfo = $$et{LigoCipher};
296 my $dirName = $$dirInfo{DirName} || 'LigoGPS';
297 push @{$$et{PATH}}, $dirName unless $$dirInfo{DirID};
298 # not fuzzed if header =~ /LIGOGPSINFO\0\0\0\0[\x01\x14]/ (\x01=BlueSkySeaDV688)
299 $noFuzz = 1 if substr($$dataPt, $pos-8, 4) =~ /^\0\0\0[\x01\x14]/;
300 $et->VerboseDir($dirName);
301 for (; $pos + 0x84 <= length($$dataPt); $pos+=0x84) {
302 my $dat = substr($$dataPt, $pos, 0x84);
303 unless ($dat =~ /^####/) {
304 next unless $dat =~ m(^.{4}\d{4}/\d{2}/\d{2} )s; # (have seen blank records filled with zeros, so keep trying)
305 # non-encrypted format written by Redtiger F9 4K
306 $dat =~ s/\0+$//; # remove trailing nulls
307 ParseLigoGPS($et, $dat, $tagTbl, 0x03);
308 next;
309 }
310 # decipher if we already know the encryption
311 $cipherInfo and $$cipherInfo{decipher} and DecipherLigoGPS($et, $dat, $tagTbl, $noFuzz) and next;
312 my $str = DecryptLigoGPS($dat);
313 defined $str or DecipherLigoGPS($et, $dat, $tagTbl, $noFuzz), next; # try to decipher
314 $et->VPrint(1, "$$et{INDENT}\(Decrypted: ",unpack('V',$str),' ',substr($str,4),")\n") if $$et{OPTIONS}{Verbose} > 1;
315 ParseLigoGPS($et, $str, $tagTbl, $noFuzz);
316 }
317 pop @{$$et{PATH}} unless $$dirInfo{DirID};
318 delete $$et{DOC_NUM};
319 return 1;
320 }
321  
322 #------------------------------------------------------------------------------
323 # Process LIGOGPSINFO JSON-format GPS (Yada RoadCam Pro 4K BT58189)
324 # Inputs: 0) ExifTool ref, 1) dirInfo ref, 2) tag table ref
325 # Returns: 1 on success
326 # Sample data (chained 512-byte records starting like this):
327 # 0000: 4c 49 47 4f 47 50 53 49 4e 46 4f 20 7b 22 48 6f [LIGOGPSINFO {"Ho]
328 # 0010: 75 72 22 3a 20 22 32 33 22 2c 20 22 4d 69 6e 75 [ur": "23", "Minu]
329 # 0020: 74 65 22 3a 20 22 31 30 22 2c 20 22 53 65 63 6f [te": "10", "Seco]
330 # 0030: 6e 64 22 3a 20 22 32 32 22 2c 20 22 59 65 61 72 [nd": "22", "Year]
331 # 0040: 22 3a 20 22 32 30 32 33 22 2c 20 22 4d 6f 6e 74 [": "2023", "Mont]
332 # 0050: 68 22 3a 20 22 31 32 22 2c 20 22 44 61 79 22 3a [h": "12", "Day":]
333 # 0060: 20 22 32 38 22 2c 20 22 73 74 61 74 75 73 22 3a [ "28", "status":]
334 sub ProcessLigoJSON($$$)
335 {
336 my ($et, $dirInfo, $tagTbl) = @_;
337 my $dataPt = $$dirInfo{DataPt};
338 my $dirLen = $$dirInfo{DirLen};
339 require Image::ExifTool::Import;
340 $et->VerboseDir('LIGO_JSON', undef, length($$dataPt) - (pos($$dataPt) || 0));
341 $$et{SET_GROUP1} = 'LIGO';
342 while ($$dataPt =~ /LIGOGPSINFO (\{.*?\})/g) {
343 my $json = $1;
344 my %dbase;
345 Image::ExifTool::Import::ReadJSON(\$json, \%dbase);
346 my $info = $dbase{'*'} or next;
347 # my sample contains the following JSON fields (in this order):
348 # Hour Minute Second Year Month Day (GPS UTC time)
349 # status NS EW Latitude Longitude Speed (speed in knots)
350 # GsensorX GsensorY GsensorZ (units? - only seen "000" for all)
351 # MHour MMinute MSecond MYear MMonth MDay (local dashcam clock time)
352 # OLatitude OLongitude (? same values as Latitude/Longitude)
353 next unless defined $$info{status} and $$info{status} eq 'A'; # only read if GPS is active
354 $$et{DOC_NUM} = ++$$et{DOC_COUNT};
355 my $num = 0;
356 defined $$info{$_} and ++$num foreach qw(Year Month Day Hour Minute Second);
357 if ($num == 6) {
358 # this is the GPS time in UTC
359 my $time = sprintf('%.4d:%.2d:%.2d %.2d:%.2d:%.2dZ',@$info{qw{Year Month Day Hour Minute Second}});
360 $et->HandleTag($tagTbl, GPSDateTime => $time);
361 }
362 if ($$info{Latitude} and $$info{Longitude}) {
363 my $lat = $$info{Latitude};
364 $lat = -$lat if $$info{NS} and $$info{NS} eq 'S';
365 my $lon = $$info{Longitude};
366 $lon = -$lon if $$info{EW} and $$info{EW} eq 'W';
367 $et->HandleTag($tagTbl, GPSLatitude => $lat);
368 $et->HandleTag($tagTbl, GPSLongitude => $lon);
369 }
370 $et->HandleTag($tagTbl, GPSSpeed => $$info{Speed} * $knotsToKph) if defined $$info{Speed};
371 if (defined $$info{GsensorX} and defined $$info{GsensorY} and defined $$info{GsensorZ}) {
372 # (don't know conversion factor for accel data, so leave it raw for now)
373 $et->HandleTag($tagTbl, Accelerometer => "$$info{GsensorX} $$info{GsensorY} $$info{GsensorZ}");
374 }
375 $num = 0;
376 defined $$info{$_} and ++$num foreach qw(MYear MMonth MDay MHour MMinute MSecond);
377 if ($num == 6) {
378 # this is the dashcam clock time (local time zone)
379 my $time = sprintf('%.4d:%.2d:%.2d %.2d:%.2d:%.2d',@$info{qw{MYear MMonth MDay MHour MMinute MSecond}});
380 $et->HandleTag($tagTbl, DateTimeOriginal => $time);
381 }
382 if (defined $$info{OLatitude} and defined $$info{OLongitude}) {
383 my $lat = $$info{OLatitude};
384 $lat = -$lat if $$info{NS} and $$info{NS} eq 'S';
385 my $lon = $$info{OLongitude};
386 $lon = -$lon if $$info{EW} and $$info{EW} eq 'W';
387 $et->HandleTag($tagTbl, GPSLatitude2 => $lat);
388 $et->HandleTag($tagTbl, GPSLongitude2 => $lon);
389 }
390 unless ($et->Options('ExtractEmbedded')) {
391 $et->Warn('Use the ExtractEmbedded option to extract all timed GPS',3);
392 last;
393 }
394 }
395 delete $$et{DOC_NUM};
396 delete $$et{SET_GROUP1};
397 return 1;
398 }
399  
400 1; #end
401  
402  
403 __END__