Debian Codegraph @

scripts/gmapi-builder.py

raw symbols SCIP
1 #!/usr/bin/python
2
3 """
4 Simple convertor for files in Garmins MapSource format to the directory
5 structure RoadTrip for OS X uses.
6
7 Copyright (c) 2009, Berteun Damman
8 All rights reserved.
9
10 Redistribution and use in source and binary forms, with or without
11 modification, are permitted provided that the following conditions are met:
12 * Redistributions of source code must retain the above copyright
13 notice, this list of conditions and the following disclaimer.
14 * Redistributions in binary form must reproduce the above copyright
15 notice, this list of conditions and the following disclaimer in the
16 documentation and/or other materials provided with the distribution.
17 * Neither the name of the OpenStreetMap Project nor the
18 names of its contributors may be used to endorse or promote products
19 derived from this software without specific prior written permission.
20
21 THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY
22 EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
23 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
24 DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
25 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
26 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
27 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
28 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
30 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
32 First of all: This program is not a replacement for Garmins MapConverter.exe.
33 It was specifically written to convert a bunch of .IMG and .TDB files of
34 the OpenStreetmap project to a .gmapi directory structure which can be
35 installed under OS X. As such it is geared towards the versions of the format
36 used by OSM. This means it will most certain not work on non-OSM files (this
37 has not been tested in anyway!).
38
39 The conversion itself is fairly simple, under Windows you have:
40 * Registry entries indicating the TDB-file, the Base Image and the Image dir,
41 and optionally a TYP file and some other types.
42 * A single TDB-file
43 * A whole collection of IMG files.
44
45 Under Mac you have:
46 * An XML file which contains the information of the Windows Register
47 * For each IMG file a directory with the same basename as the IMG-file,
48 and with the subfiles of this IMG extracted into this directory; the IMG-files
49 are in fact containers (they are similar to disk images).
50
51 This program does the conversion.
52 """
53
54 import logging
55 import optparse
56 import os
57 import shutil
58 import struct
59 import sys
60 import StringIO
61
62 # Logger setup
63 logging.NORMAL = logging.INFO + 5
64 logging.addLevelName(logging.NORMAL, 'NORMAL')
65 logger = logging.getLogger('logger')
66 logger.setLevel(logging.DEBUG)
67
68 # Program options can increase the verbosity
69 cons = logging.StreamHandler(sys.stdout)
70 cons.setLevel(logging.NORMAL)
71 logger.addHandler(cons)
72
73 def error_exit(msg):
74 sys.exit(msg)
75
76 def write(msg, *args, **kwargs):
77 logger.log(logging.NORMAL, msg, *args, **kwargs)
78
79 class EndOfFile(IOError):
80 pass
81
82 class FileFormatError(Exception):
83 pass
84
85 # Auxiliary functions that make life easier to read bytes, shorts, int and
86 # so on from a file.
87 def getX(length, fmt):
88 def get(f):
89 v = f.read(length)
90 if len(v) < length:
91 raise EndOfFile("End of file reached on '%s'." % f.name)
92 return struct.unpack(fmt, v)[0]
93 return get
94
95 # See the documentation of struct for an explanation of these
96 # format specifiers. Notably, the < indicates little endian
97 # format.
98 get_short = getX(2, '<h')
99 get_ushort = getX(2, '<H')
100 get_int = getX(4, '<i')
101 get_uint = getX(4, '<I')
102 get_byte = getX(1, 'B')
103
104 def get_str(f):
105 c = f.read(1)
106 s = ''
107 while c != '\x00':
108 s += c
109 c = f.read(1)
110 return s
111
112 def get_nstr(f, n):
113 c = f.read(n)
114 if len(c) < n:
115 raise EndOfFile("End of file reached on '%s'." % f.name)
116 s = struct.unpack('%ds' % n, c)[0]
117 return s
118
119 # For the 4.X TDB file format, 24bit integers are used; already here
120 # for the future.
121 #def get_middle(f):
122 # l = list(f.read(3))
123 # if len(l) < 3:
124 # raise EndOfFile("End of file reached on '%s'." % f.name)
125 # sign, l[2] = l[2] >> 7, l[2] & 0x7F
126 # v = -sign * (1<<23) + (l[2] << 16) + (l[1] << 8) + l[0]
127
128 def todegrees(n):
129 return (n * 360.0) / (2 ** 32)
130
131 # A TDB file consists of a sequence of blocks, the format of each
132 # block is simply:
133 # 1 Byte: Block ID
134 # 2 Bytes: Block length (l):
135 # l Bytes: Data
136
137 class Block(object):
138 def __init__(self, f):
139 self.bid = get_byte(f)
140 self.length = get_ushort(f)
141 self.data = StringIO.StringIO(f.read(self.length))
142 if len(self.data.buf) < self.length:
143 raise EndOfFile("End of file reached early on '%s'." % f.name)
144
145 class TDBFile(object):
146 """This represents the TDBFile with its known blocks, such as
147 the header, copyright block, overview block and detailed maps."""
148 def __init__(self, filename):
149 self.f = open(filename, 'rb')
150 self.header_block = None
151 self.copyright_block = None
152 self.overview_block = None
153 self.trademark_block = None
154 self.detail_blocks = []
155 self._parse()
156
157 def _parse(self):
158 """Dispatches subparsers for *known* blocks"""
159 block_parsers = {
160 0x50: self.parse_header,
161 0x44: self.parse_copyright,
162 0x42: self.parse_overview,
163 0x4C: self.parse_detail,
164 0x52: self.parse_trademark,
165 }
166
167 while self.f.read(1):
168 self.f.seek(-1, 1)
169 b = Block(self.f)
170 if b.bid in block_parsers:
171 block_parsers[b.bid](b)
172 else:
173 logger.info('Unknown Block: %02X, length: %d, %s' % (b.bid, b.length, repr(b.data.buf)))
174 self.f.close()
175
176 def parse_header(self, block):
177 hb = {}
178 hb['Product ID'] = get_ushort(block.data)
179 hb['Family ID'] = get_ushort(block.data)
180
181 tdb_version = get_ushort(block.data)
182 hb['TDB Major Version'] = tdb_version / 100
183 hb['TDB Minor Version'] = tdb_version % 100
184 hb['TDB Version'] = "%d.%02d" % (hb['TDB Major Version'], hb['TDB Minor Version'])
185
186 hb['Map Series'] = get_str(block.data)
187
188 prod_version = get_ushort(block.data)
189 hb['Product Major Version'] = prod_version / 100
190 hb['Product Minor Version'] = prod_version % 100
191 hb['Product Version'] = "%d.%02d" % (hb['Product Major Version'], hb['Product Minor Version'])
192
193 hb['Map Family'] = get_str(block.data)
194
195 self.header_block = hb
196
197 def parse_copyright(self, block):
198 cl = []
199 while block.data.pos < len(block.data.buf):
200 copyright_code = get_byte(block.data)
201 where_code = get_byte(block.data)
202 extra = get_short(block.data)
203 copyright_string = get_str(block.data)
204 if copyright_code == 0x00:
205 cl.append({'Source': copyright_string.decode('latin1').encode('utf-8')})
206 elif copyright_code == 0x06:
207 cl.append({'Copyright': copyright_string.decode('latin1').encode('utf-8')})
208 elif copyright_code == 0x07:
209 cl.append({'Bitmap': copyright_string, 'Scale factor': extra})
210 else:
211 cl.append({'Unknown (%02X)' % copyright_code: copyright_string, 'Extra': extra})
212 self.copyright_block = cl
213
214 def parse_overview(self, block):
215 ob = {}
216 ob['Map Number'] = get_uint(block.data)
217 ob['Parent Map'] = get_uint(block.data)
218 ob['Latitude North'] = "%7.4f" % todegrees(get_int(block.data))
219 ob['Longitude East'] = "%7.4f" % todegrees(get_int(block.data))
220 ob['Latitude South'] = "%7.4f" % todegrees(get_int(block.data))
221 ob['Longitude West'] = "%7.4f" % todegrees(get_int(block.data))
222 ob['Description'] = get_str(block.data)
223 self.overview_block = ob
224
225 def parse_detail(self, block):
226 db = {}
227 db['Map Number'] = get_uint(block.data)
228 db['Parent Map'] = get_uint(block.data)
229 db['Latitude North'] = "%7.4f" % todegrees(get_int(block.data))
230 db['Longitude East'] = "%7.4f" % todegrees(get_int(block.data))
231 db['Latitude South'] = "%7.4f" % todegrees(get_int(block.data))
232 db['Longitude West'] = "%7.4f" % todegrees(get_int(block.data))
233 db['Description'] = get_str(block.data)
234 # Unknown
235 block.data.seek(4, 1)
236 # Could it be that these values have changed in v4?
237 db['RGN Size'] = get_uint(block.data)
238 db['TRE Size'] = get_uint(block.data)
239 db['LBL Size'] = get_uint(block.data)
240 self.detail_blocks.append(db)
241
242 def parse_trademark(self, block):
243 tb = {}
244 block.data.seek(1, 1)
245 tb['Trademark'] = get_str(block.data)
246 self.trademark_block = tb
247
248 def print_header(self):
249 for f in ['TDB Version', 'Product ID', 'Family ID', 'Map Series', 'Map Family', 'Product Version']:
250 write("%-20s%s" % (f + ':', str(self.header_block[f])))
251
252 def print_copyright(self):
253 for c in self.copyright_block:
254 write('\n '.join(["%-20s%s" % (f + ":", str(c[f])) for f in c]))
255
256 def print_trademark(self):
257 write("%-20s%s" % ('Trademark:', self.trademark_block['Trademark'].encode('utf-8')))
258
259 def print_overview(self):
260 logger.info('Overview map:')
261 for f in ['Map Number', 'Parent Map', 'Latitude North', 'Longitude East',
262 'Latitude South', 'Longitude West', 'Description']:
263 logger.info(" %-20s%s" % (f + ':', str(self.overview_block[f])))
264
265 def print_detail_blocks(self):
266 logger.debug('Detailed maps:')
267 for db in self.detail_blocks:
268 logger.debug(" %-20s%s" % ('Map Number:', str(db['Map Number'])))
269 logger.debug(" %-20s%s" % ('Parent Map:', str(db['Parent Map'])))
270 logger.debug(" %-20s%s" % ('Description:', str(db['Description'])))
271 logger.debug(" N: %s, S: %s, W: %s, E: %s" % (db['Latitude North'], db['Latitude South'],
272 db['Longitude West'], db['Longitude East']))
273 logger.debug(" RGN: %d, TRE: %d, LBL: %d" % (db['RGN Size'], db['TRE Size'], db['LBL Size']))
274 logger.debug("")
275
276
277 def print_dump(self):
278 """Gives a short textual description of the data."""
279 if self.header_block:
280 self.print_header()
281 else:
282 logger.warning('TDB file contains no header block.')
283 write("")
284 if self.copyright_block:
285 self.print_copyright()
286 else:
287 logger.info('TDB file contains no copyright block.')
288 write("")
289 if self.trademark_block:
290 self.print_trademark()
291 write("")
292 else:
293 logger.info('TDB file contains no trademark block.')
294 logger.info("")
295 if self.overview_block:
296 self.print_overview()
297 else:
298 logger.warning('TDB file contains no overview map.')
299 logger.info("")
300 if self.detail_blocks:
301 self.print_detail_blocks()
302 else:
303 logger.warning('TDB file contains no detail blocks.')
304
305 class SubFile(object):
306 """Represents a subfile in the IMG file
307
308 The image is like a FAT file system; for each file it lists
309 the sectors on which a part of the file can be found. If the
310 file is larger than 240 sectors, it split into parts.
311 """
312 def __init__(self, name, extension):
313 self.name = name
314 self.extension = extension
315 self.fullname = '%s.%s' % (name, extension)
316 self.size = None
317 self.part_list = []
318
319 def add_part(self, part, sectors):
320 self.part_list.append((part, sectors))
321
322 def merge_parts(self):
323 """Merges all the sectors in the parts into
324 a large (sorted) sector list which can be used to dump the file.
325 """
326 self.part_list.sort()
327 for n in range(len(self.part_list)):
328 if self.part_list[n][0] != n:
329 raise FileFormatError('Missing part: %d of %s in IMG-file.' % (n, self.fullname))
330 self.sector_list = []
331 for (n, sl) in self.part_list:
332 self.sector_list.extend(sl)
333
334 class IMGFile(object):
335 """Very crude representation of the IMG file
336
337 We only want to extract the subfiles, so we ignore lots of infomation in this file."""
338 def __init__(self, filename):
339 self.f = open(filename)
340 self.basename = os.path.basename(filename[:filename.rfind('.')])
341 self._check_file()
342 self.block_size = self._get_block_size()
343 self._read_files()
344
345 def _check_file(self):
346 first_b = get_byte(self.f)
347 if first_b != 0x00:
348 raise FileFormatError("%s is not a Garmin IMG file, or it is encrypted." % self.f.name)
349 self.f.seek(0x10)
350 if get_str(self.f) != "DSKIMG":
351 raise FileFormatError("%s is not a Garmin IMG file, or is an unknown version." % self.f.name)
352 self.f.seek(0x41)
353 if get_str(self.f) != "GARMIN":
354 raise FileFormatError("%s is not a Garmin IMG file, or is an unknown version." % self.f.name)
355
356 def _get_block_size(self):
357 # Probably 512
358 self.f.seek(0x61)
359 e1 = get_byte(self.f)
360 e2 = get_byte(self.f)
361 bs = 1<<(e1 + e2)
362 return bs
363
364 def _read_files(self):
365 """Scans the FAT for files"""
366 files = {}
367 file_count = 0
368 while True:
369 # FAT starts at 0x600, each entry is
370 # exactly 512 bytes, padded if necessary.
371 self.f.seek(0x600 + file_count * 512)
372 if get_byte(self.f) == 0:
373 break
374
375 filename = get_nstr(self.f, 8)
376 file_type = get_nstr(self.f, 3)
377 size = get_uint(self.f)
378
379 self.f.seek(1, 1)
380 part_no = get_byte(self.f)
381 fullname ='%s.%s' % (filename, file_type)
382 self.f.seek(14, 1)
383 sector_list = []
384 for n in range(240):
385 sector_no = get_ushort(self.f)
386 if sector_no != -1:
387 sector_list.append(sector_no)
388
389 if not fullname in files:
390 files[fullname] = SubFile(filename, file_type)
391 if part_no == 0:
392 files[fullname].size = size
393
394 files[fullname].add_part(part_no, sector_list)
395 file_count += 1
396
397 for fn in files:
398 files[fn].merge_parts()
399 self.files = files
400
401 def dump(self, base_dir):
402 """Dumps the subfiles of this IMG file"""
403 output_dir = os.path.join(base_dir, self.basename)
404 os.mkdir(output_dir)
405 for sfn in self.files:
406 subfile = self.files[sfn]
407 out = open(os.path.join(output_dir, subfile.fullname), 'w')
408 for s in subfile.sector_list:
409 self.f.seek(s * self.block_size)
410 out.write(self.f.read(self.block_size))
411 out.truncate(subfile.size)
412 logger.debug('Wrote: %s/%s' % (output_dir, subfile.fullname))
413 out.close()
414
415 def close(self):
416 self.f.close()
417
418 def print_info(self):
419 logger.debug("Contents of %s:" % (self.basename))
420 for fn in self.files:
421 logger.debug(" %s: Size: %d" % (self.files[fn].fullname, self.files[fn].size))
422
423 def parse_options(option_list):
424 usage = 'usage: %prog: [-h] [-o <outputdir>] [-s <typfile>] -t <tdbfile> -b <base-image> <file1.img> [<file2.img> [<file3.img> ... ]]'
425 oparser = optparse.OptionParser(usage=usage)
426 oparser.add_option("-o", "--output", dest="output", default="./",
427 help="specify the output directory for the .gmapi folder")
428 oparser.add_option("-t", "--tdbfile", dest="tdbfile",
429 help="the name of this mapset's TDB file")
430 oparser.add_option("-b", "--baseimg", dest="baseimg",
431 help="the name of the base img")
432 oparser.add_option("-i", "--idxfile", dest="mdx",
433 help="the name of this mapset's index (mdx) file")
434 oparser.add_option("-m", "--mdrfile", dest="mdr",
435 help="the name of this mapset's MDR file")
436 oparser.add_option("-v", "--verbose", dest="verbosity",
437 action="count", help="verbosity")
438 oparser.add_option("-s", "--style", dest="style",
439 help="an optional style-file (TYP)")
440 oparser.add_option("-d", "--dryrun", dest="dryrun",
441 action="store_true", default=False)
442
443 (options, args) = oparser.parse_args(option_list)
444
445 if options.verbosity:
446 if options.verbosity == 1:
447 cons.setLevel(logging.INFO)
448 elif options.verbosity > 1:
449 cons.setLevel(logging.DEBUG)
450
451 if not options.tdbfile:
452 oparser.print_help()
453 error_exit("\nError: You must specify a TDB-file with -t!")
454
455 if not options.baseimg:
456 oparser.print_help()
457 error_exit("\nError: You must specify the base image with -b!")
458 elif not os.path.isfile(options.baseimg):
459 error_exit("\nError: Baseimage not found.")
460
461 if options.style:
462 if not os.path.isfile(options.style):
463 error_exit("\nError: Style file not found.")
464
465 if options.mdx:
466 if not os.path.isfile(options.mdx):
467 error_exit("\nError: Index (mdx) file not found.")
468
469 if options.mdr:
470 if not os.path.isfile(options.mdr):
471 error_exit("\nError: MDR file not found.")
472
473 if not args:
474 oparser.print_help()
475 error_exit('No filenames specified!')
476
477 return (options, args)
478
479 def prepare_output_dir(tdbfile, options):
480 dir_prefix = tdbfile.header_block['Map Series']
481 if not os.path.isdir(options.output):
482 error_exit('Output dir does not exist')
483 gmapi = os.path.join(options.output, dir_prefix + '.gmapi')
484 gmap = os.path.join(gmapi, dir_prefix + '.gmap')
485 if os.path.exists(gmapi):
486 logger.info("Removing existing file '%s' recursively" % gmapi)
487 if os.path.isdir(gmapi):
488 shutil.rmtree(gmapi)
489 else:
490 os.unlink(gmapi)
491 if os.path.exists(gmapi):
492 error_exit("Could not remove existing '%s', please do so yourself, or specify another output dir.")
493 # This directory is empty indeed
494 os.mkdir(gmapi)
495 os.mkdir(gmap)
496 return gmap
497
498 def write_xml_file(tdbfile, options, output_dir):
499 def write_field(field, value, indent):
500 f.write('%s<%s>%s</%s>\n' % (indent * ' ', field, value, field))
501 f = open(os.path.join(output_dir, 'Info.xml'), 'w')
502 f.write('<?xml version="1.0" encoding="UTF-8" standalone="no" ?>\n')
503 f.write('<MapProduct xmlns="http://www.garmin.com/xmlschemas/MapProduct/v1">\n\n')
504 write_field('Name', tdbfile.header_block['Map Family'], 1)
505 f.write('\n')
506 write_field('DataVersion', str(tdbfile.header_block['Product Major Version']) + ("%02d" % tdbfile.header_block['Product Minor Version']), 1)
507 f.write('\n')
508 write_field('DataFormat', 'Original', 1)
509 f.write('\n')
510 # It appears the windows converter does not write the family ID
511 # if it is zero, so neither do we!"
512 if tdbfile.header_block['Family ID'] > 0:
513 write_field('ID', tdbfile.header_block['Family ID'], 1)
514 f.write('\n')
515 if options.mdx:
516 write_field('IDX', os.path.basename(options.mdx), 1)
517 f.write('\n')
518 if options.mdr:
519 mdr = os.path.basename(options.mdr)
520 mdr = mdr[:mdr.rfind('.')]
521 write_field('MDR', mdr, 1)
522 f.write('\n')
523 if options.style:
524 write_field('TYP', os.path.basename(options.style), 1)
525 f.write('\n')
526 f.write(' <SubProduct>\n')
527 write_field('Name', tdbfile.header_block['Map Series'], 2)
528 write_field('ID', tdbfile.header_block['Product ID'], 2)
529 baseimg = os.path.basename(options.baseimg)
530 baseimg = baseimg[:baseimg.rfind('.')]
531 write_field('BaseMap', baseimg, 2)
532 write_field('TDB', os.path.basename(options.tdbfile), 2)
533 write_field('Directory', 'OSMTiles', 2)
534 f.write(' </SubProduct>\n')
535 f.write('</MapProduct>\n')
536 f.close()
537
538 if __name__ == '__main__':
539 (options, filenames) = parse_options(sys.argv[1:])
540 try:
541 tdbfile = TDBFile(options.tdbfile)
542 tdbfile.print_dump()
543 except IOError:
544 error_exit("Could not open '%s' for reading." % options.tdbfile)
545
546 if not options.dryrun:
547 output_dir = prepare_output_dir(tdbfile, options)
548 write_xml_file(tdbfile, options, output_dir)
549
550 try:
551 if not options.dryrun:
552 imgoutput = os.path.join(output_dir, 'OSMTiles')
553 os.mkdir(imgoutput)
554 shutil.copy(options.tdbfile, os.path.join(imgoutput, os.path.basename(options.tdbfile)))
555 if options.style:
556 shutil.copy(options.style, os.path.join(output_dir, os.path.basename(options.style)))
557
558 if options.mdx:
559 shutil.copy(options.mdx, os.path.join(output_dir, os.path.basename(options.mdx)))
560
561 if options.mdr:
562 mdr_file = os.path.basename(options.mdr)
563
564 for fn in filenames:
565 logger.info("Processing " + fn)
566 imgfile = IMGFile(fn)
567 imgfile.print_info()
568 if not options.dryrun:
569 if fn != options.mdr:
570 imgfile.dump(imgoutput)
571 else:
572 logger.info("MDR file")
573 imgfile.dump(output_dir)
574 imgfile.close()
575 except IOError:
576 error_exit("Could not open '%s' for reading." % fn)
577 except FileFormatError, m:
578 error_exit(m)