MIE.pm 102 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564
  1. #------------------------------------------------------------------------------
  2. # File: MIE.pm
  3. #
  4. # Description: Read/write MIE meta information
  5. #
  6. # Revisions: 11/18/2005 - P. Harvey Created
  7. #------------------------------------------------------------------------------
  8. package Image::ExifTool::MIE;
  9. use strict;
  10. use vars qw($VERSION %tableDefaults);
  11. use Image::ExifTool qw(:DataAccess :Utils);
  12. use Image::ExifTool::Exif;
  13. use Image::ExifTool::GPS;
  14. $VERSION = '1.45';
  15. sub ProcessMIE($$);
  16. sub ProcessMIEGroup($$$);
  17. sub WriteMIEGroup($$$);
  18. sub CheckMIE($$$);
  19. sub GetLangInfo($$);
  20. # local variables
  21. my $hasZlib; # 1=Zlib available, 0=no Zlib
  22. my %mieCode; # reverse lookup for MIE format names
  23. my $doneMieMap; # flag indicating we added user-defined groups to %mieMap
  24. # MIE format codes
  25. my %mieFormat = (
  26. 0x00 => 'undef',
  27. 0x10 => 'MIE',
  28. 0x18 => 'MIE',
  29. 0x20 => 'string', # ASCII (ISO 8859-1)
  30. 0x28 => 'utf8',
  31. 0x29 => 'utf16',
  32. 0x2a => 'utf32',
  33. 0x30 => 'string_list',
  34. 0x38 => 'utf8_list',
  35. 0x39 => 'utf16_list',
  36. 0x3a => 'utf32_list',
  37. 0x40 => 'int8u',
  38. 0x41 => 'int16u',
  39. 0x42 => 'int32u',
  40. 0x43 => 'int64u',
  41. 0x48 => 'int8s',
  42. 0x49 => 'int16s',
  43. 0x4a => 'int32s',
  44. 0x4b => 'int64s',
  45. 0x52 => 'rational32u',
  46. 0x53 => 'rational64u',
  47. 0x5a => 'rational32s',
  48. 0x5b => 'rational64s',
  49. 0x61 => 'fixed16u',
  50. 0x62 => 'fixed32u',
  51. 0x69 => 'fixed16s',
  52. 0x6a => 'fixed32s',
  53. 0x72 => 'float',
  54. 0x73 => 'double',
  55. 0x80 => 'free',
  56. );
  57. # map of MIE directory locations
  58. my %mieMap = (
  59. 'MIE-Meta' => 'MIE',
  60. 'MIE-Audio' => 'MIE-Meta',
  61. 'MIE-Camera' => 'MIE-Meta',
  62. 'MIE-Doc' => 'MIE-Meta',
  63. 'MIE-Geo' => 'MIE-Meta',
  64. 'MIE-Image' => 'MIE-Meta',
  65. 'MIE-MakerNotes' => 'MIE-Meta',
  66. 'MIE-Preview' => 'MIE-Meta',
  67. 'MIE-Thumbnail' => 'MIE-Meta',
  68. 'MIE-Video' => 'MIE-Meta',
  69. 'MIE-Flash' => 'MIE-Camera',
  70. 'MIE-Lens' => 'MIE-Camera',
  71. 'MIE-Orient' => 'MIE-Camera',
  72. 'MIE-Extender' => 'MIE-Lens',
  73. 'MIE-GPS' => 'MIE-Geo',
  74. 'MIE-UTM' => 'MIE-Geo',
  75. 'MIE-Canon' => 'MIE-MakerNotes',
  76. EXIF => 'MIE-Meta',
  77. XMP => 'MIE-Meta',
  78. IPTC => 'MIE-Meta',
  79. ICC_Profile => 'MIE-Meta',
  80. ID3 => 'MIE-Meta',
  81. CanonVRD => 'MIE-Canon',
  82. IFD0 => 'EXIF',
  83. IFD1 => 'IFD0',
  84. ExifIFD => 'IFD0',
  85. GPS => 'IFD0',
  86. SubIFD => 'IFD0',
  87. GlobParamIFD => 'IFD0',
  88. PrintIM => 'IFD0',
  89. InteropIFD => 'ExifIFD',
  90. MakerNotes => 'ExifIFD',
  91. );
  92. # convenience variables for common tagInfo entries
  93. my %binaryConv = (
  94. Writable => 'undef',
  95. Binary => 1,
  96. );
  97. my %dateInfo = (
  98. Shift => 'Time',
  99. PrintConv => '$self->ConvertDateTime($val)',
  100. PrintConvInv => '$self->InverseDateTime($val)',
  101. );
  102. my %noYes = ( 0 => 'No', 1 => 'Yes' );
  103. my %offOn = ( 0 => 'Off', 1 => 'On' );
  104. # default entries for MIE tag tables
  105. %tableDefaults = (
  106. PROCESS_PROC => \&ProcessMIE,
  107. WRITE_PROC => \&ProcessMIE,
  108. CHECK_PROC => \&CheckMIE,
  109. LANG_INFO => \&GetLangInfo,
  110. WRITABLE => 'string',
  111. PREFERRED => 1,
  112. );
  113. # MIE info
  114. %Image::ExifTool::MIE::Main = (
  115. %tableDefaults,
  116. GROUPS => { 1 => 'MIE-Main' },
  117. WRITE_GROUP => 'MIE-Main',
  118. NOTES => q{
  119. MIE is a flexible format which may be used as a stand-alone meta information
  120. format, for encapsulation of other files and information, or as a trailer
  121. appended to other file formats. The tables below represent currently
  122. defined MIE tags, however ExifTool will also extract any other information
  123. present in a MIE file.
  124. When writing MIE information, some special features are supported:
  125. 1) String values may be written as ASCII (ISO 8859-1) or UTF-8. ExifTool
  126. automatically detects the presence of wide characters and treats the string
  127. appropriately. Internally, UTF-8 text may be converted to UTF-16 or UTF-32
  128. and stored in this format in the file if it is more compact.
  129. 2) All MIE string-value tags support localized text. Localized values are
  130. written by adding a language/country code to the tag name in the form
  131. C<TAG-xx_YY>, where C<TAG> is the tag name, C<xx> is a 2-character lower
  132. case ISO 639-1 language code, and C<YY> is a 2-character upper case ISO
  133. 3166-1 alpha 2 country code (eg. C<Title-en_US>). But as usual, the user
  134. interface is case-insensitive, and ExifTool will write the correct case to
  135. the file.
  136. 3) Some numerical MIE tags allow units of measurement to be specified. For
  137. these tags, units may be added in brackets immediately following the value
  138. (eg. C<55(mi/h)>). If no units are specified, the default units are
  139. written.
  140. See L<http://owl.phy.queensu.ca/~phil/exiftool/MIE1.1-20070121.pdf> for the
  141. official MIE specification.
  142. },
  143. '0Type' => {
  144. Name => 'SubfileType',
  145. Notes => q{
  146. the capitalized common extension for this type of file. If the extension
  147. has a dot-3 abbreviation, then the longer version is used here. For
  148. instance, JPEG and TIFF are used, not JPG and TIF
  149. },
  150. },
  151. '0Vers' => {
  152. Name => 'MIEVersion',
  153. Notes => 'version 1.1 is assumed if not specified',
  154. },
  155. '1Directory' => {
  156. Name => 'SubfileDirectory',
  157. Notes => 'original directory for the file',
  158. },
  159. '1Name' => {
  160. Name => 'SubfileName',
  161. Notes => 'the file name, including extension if it exists',
  162. },
  163. '2MIME' => { Name => 'SubfileMIMEType' },
  164. Meta => {
  165. SubDirectory => {
  166. TagTable => 'Image::ExifTool::MIE::Meta',
  167. DirName => 'MIE-Meta',
  168. },
  169. },
  170. data => {
  171. Name => 'SubfileData',
  172. Notes => 'the subfile data',
  173. %binaryConv,
  174. },
  175. rsrc => {
  176. Name => 'SubfileResource',
  177. Notes => 'subfile resource fork if it exists',
  178. %binaryConv,
  179. },
  180. zmd5 => {
  181. Name => 'MD5Digest',
  182. Notes => q{
  183. 16-byte MD5 digest written in binary form or as a 32-character hex-encoded
  184. ASCII string. Value is an MD5 digest of the entire 0MIE group as it would be
  185. with the digest value itself set to all null bytes
  186. },
  187. },
  188. zmie => {
  189. Name => 'TrailerSignature',
  190. Writable => 'undef',
  191. Notes => q{
  192. used as the last element in the main "0MIE" group to identify a MIE trailer
  193. when appended to another type of file. ExifTool will create this tag if set
  194. to any value, but always with an empty data block
  195. },
  196. ValueConvInv => '""', # data block must be empty
  197. },
  198. );
  199. # MIE meta information group
  200. %Image::ExifTool::MIE::Meta = (
  201. %tableDefaults,
  202. GROUPS => { 1 => 'MIE-Meta', 2 => 'Image' },
  203. WRITE_GROUP => 'MIE-Meta',
  204. Audio => {
  205. SubDirectory => {
  206. TagTable => 'Image::ExifTool::MIE::Audio',
  207. DirName => 'MIE-Audio',
  208. },
  209. },
  210. Camera => {
  211. SubDirectory => {
  212. TagTable => 'Image::ExifTool::MIE::Camera',
  213. DirName => 'MIE-Camera',
  214. },
  215. },
  216. Document => {
  217. SubDirectory => {
  218. TagTable => 'Image::ExifTool::MIE::Doc',
  219. DirName => 'MIE-Doc',
  220. },
  221. },
  222. EXIF => {
  223. SubDirectory => {
  224. TagTable => 'Image::ExifTool::Exif::Main',
  225. ProcessProc => \&Image::ExifTool::ProcessTIFF,
  226. WriteProc => \&Image::ExifTool::WriteTIFF,
  227. },
  228. },
  229. Geo => {
  230. SubDirectory => {
  231. TagTable => 'Image::ExifTool::MIE::Geo',
  232. DirName => 'MIE-Geo',
  233. },
  234. },
  235. ICCProfile => {
  236. Name => 'ICC_Profile',
  237. SubDirectory => { TagTable => 'Image::ExifTool::ICC_Profile::Main' },
  238. },
  239. ID3 => { SubDirectory => { TagTable => 'Image::ExifTool::ID3::Main' } },
  240. IPTC => { SubDirectory => { TagTable => 'Image::ExifTool::IPTC::Main' } },
  241. Image => {
  242. SubDirectory => {
  243. TagTable => 'Image::ExifTool::MIE::Image',
  244. DirName => 'MIE-Image',
  245. },
  246. },
  247. MakerNotes => {
  248. SubDirectory => {
  249. TagTable => 'Image::ExifTool::MIE::MakerNotes',
  250. DirName => 'MIE-MakerNotes',
  251. },
  252. },
  253. Preview => {
  254. SubDirectory => {
  255. TagTable => 'Image::ExifTool::MIE::Preview',
  256. DirName => 'MIE-Preview',
  257. },
  258. },
  259. Thumbnail => {
  260. SubDirectory => {
  261. TagTable => 'Image::ExifTool::MIE::Thumbnail',
  262. DirName => 'MIE-Thumbnail',
  263. },
  264. },
  265. Video => {
  266. SubDirectory => {
  267. TagTable => 'Image::ExifTool::MIE::Video',
  268. DirName => 'MIE-Video',
  269. },
  270. },
  271. XMP => { SubDirectory => { TagTable => 'Image::ExifTool::XMP::Main' } },
  272. );
  273. # MIE document information
  274. %Image::ExifTool::MIE::Doc = (
  275. %tableDefaults,
  276. GROUPS => { 1 => 'MIE-Doc', 2 => 'Document' },
  277. WRITE_GROUP => 'MIE-Doc',
  278. NOTES => 'Information describing the main document, image or file.',
  279. Author => { Groups => { 2 => 'Author' } },
  280. Comment => { },
  281. Contributors=> { Groups => { 2 => 'Author' }, List => 1 },
  282. Copyright => { Groups => { 2 => 'Author' } },
  283. CreateDate => { Groups => { 2 => 'Time' }, %dateInfo },
  284. EMail => { Name => 'Email', Groups => { 2 => 'Author' } },
  285. Keywords => { List => 1 },
  286. ModifyDate => { Groups => { 2 => 'Time' }, %dateInfo },
  287. OriginalDate=> {
  288. Name => 'DateTimeOriginal',
  289. Description => 'Date/Time Original',
  290. Groups => { 2 => 'Time' },
  291. %dateInfo,
  292. },
  293. Phone => { Name => 'PhoneNumber', Groups => { 2 => 'Author' } },
  294. References => { List => 1 },
  295. Software => { },
  296. Title => { },
  297. URL => { },
  298. );
  299. # MIE geographic information
  300. %Image::ExifTool::MIE::Geo = (
  301. %tableDefaults,
  302. GROUPS => { 1 => 'MIE-Geo', 2 => 'Location' },
  303. WRITE_GROUP => 'MIE-Geo',
  304. NOTES => 'Information related to geographic location.',
  305. Address => { },
  306. City => { },
  307. Country => { },
  308. GPS => {
  309. SubDirectory => {
  310. TagTable => 'Image::ExifTool::MIE::GPS',
  311. DirName => 'MIE-GPS',
  312. },
  313. },
  314. PostalCode => { },
  315. State => { Notes => 'state or province' },
  316. UTM => {
  317. SubDirectory => {
  318. TagTable => 'Image::ExifTool::MIE::UTM',
  319. DirName => 'MIE-UTM',
  320. },
  321. },
  322. );
  323. # MIE GPS information
  324. %Image::ExifTool::MIE::GPS = (
  325. %tableDefaults,
  326. GROUPS => { 1 => 'MIE-GPS', 2 => 'Location' },
  327. WRITE_GROUP => 'MIE-GPS',
  328. Altitude => {
  329. Name => 'GPSAltitude',
  330. Writable => 'rational64s',
  331. Units => [ qw(m ft) ],
  332. Notes => q{'m' above sea level unless 'ft' specified},
  333. },
  334. Bearing => {
  335. Name => 'GPSDestBearing',
  336. Writable => 'rational64s',
  337. Units => [ qw(deg deg{mag}) ],
  338. Notes => q{'deg' CW from true north unless 'deg{mag}' specified},
  339. },
  340. Datum => { Name => 'GPSMapDatum', Notes => 'WGS-84 assumed if not specified' },
  341. Differential => {
  342. Name => 'GPSDifferential',
  343. Writable => 'int8u',
  344. PrintConv => {
  345. 0 => 'No Correction',
  346. 1 => 'Differential Corrected',
  347. },
  348. },
  349. Distance => {
  350. Name => 'GPSDestDistance',
  351. Writable => 'rational64s',
  352. Units => [ qw(km mi nmi) ],
  353. Notes => q{'km' unless 'mi' or 'nmi' specified},
  354. },
  355. Heading => {
  356. Name => 'GPSTrack',
  357. Writable => 'rational64s',
  358. Units => [ qw(deg deg{mag}) ],
  359. Notes => q{'deg' CW from true north unless 'deg{mag}' specified},
  360. },
  361. Latitude => {
  362. Name => 'GPSLatitude',
  363. Writable => 'rational64s',
  364. Count => -1,
  365. Notes => q{
  366. 1 to 3 numbers: degrees, minutes then seconds. South latitudes are stored
  367. as all negative numbers, but may be entered as positive numbers with a
  368. trailing 'S' for convenience. For example, these are all equivalent: "-40
  369. -30", "-40.5", "40 30 0.00 S"
  370. },
  371. ValueConv => 'Image::ExifTool::GPS::ToDegrees($val, 1)',
  372. ValueConvInv => 'Image::ExifTool::GPS::ToDMS($self, $val, 0)',
  373. PrintConv => 'Image::ExifTool::GPS::ToDMS($self, $val, 1, "N")',
  374. PrintConvInv => 'Image::ExifTool::GPS::ToDegrees($val, 1)',
  375. },
  376. Longitude => {
  377. Name => 'GPSLongitude',
  378. Writable => 'rational64s',
  379. Count => -1,
  380. Notes => q{
  381. 1 to 3 numbers: degrees, minutes then seconds. West longitudes are
  382. negative, but may be entered as positive numbers with a trailing 'W'
  383. },
  384. ValueConv => 'Image::ExifTool::GPS::ToDegrees($val, 1)',
  385. ValueConvInv => 'Image::ExifTool::GPS::ToDMS($self, $val, 0)',
  386. PrintConv => 'Image::ExifTool::GPS::ToDMS($self, $val, 1, "E")',
  387. PrintConvInv => 'Image::ExifTool::GPS::ToDegrees($val, 1)',
  388. },
  389. MeasureMode => {
  390. Name => 'GPSMeasureMode',
  391. Writable => 'int8u',
  392. PrintConv => { 2 => '2-D', 3 => '3-D' },
  393. },
  394. Satellites => 'GPSSatellites',
  395. Speed => {
  396. Name => 'GPSSpeed',
  397. Writable => 'rational64s',
  398. Units => [ qw(km/h mi/h m/s kn) ],
  399. Notes => q{'km/h' unless 'mi/h', 'm/s' or 'kn' specified},
  400. },
  401. DateTime => { Name => 'GPSDateTime', Groups => { 2 => 'Time' }, %dateInfo },
  402. );
  403. # MIE UTM information
  404. %Image::ExifTool::MIE::UTM = (
  405. %tableDefaults,
  406. GROUPS => { 1 => 'MIE-UTM', 2 => 'Location' },
  407. WRITE_GROUP => 'MIE-UTM',
  408. Datum => { Name => 'UTMMapDatum', Notes => 'WGS-84 assumed if not specified' },
  409. Easting => { Name => 'UTMEasting' },
  410. Northing => { Name => 'UTMNorthing' },
  411. Zone => { Name => 'UTMZone', Writable => 'int8s' },
  412. );
  413. # MIE image information
  414. %Image::ExifTool::MIE::Image = (
  415. %tableDefaults,
  416. GROUPS => { 1 => 'MIE-Image', 2 => 'Image' },
  417. WRITE_GROUP => 'MIE-Image',
  418. '0Type' => { Name => 'FullSizeImageType', Notes => 'JPEG if not specified' },
  419. '1Name' => { Name => 'FullSizeImageName' },
  420. BitDepth => { Name => 'BitDepth', Writable => 'int16u' },
  421. ColorSpace => { Notes => 'standard ColorSpace values are "sRGB" and "Adobe RGB"' },
  422. Components => {
  423. Name => 'ComponentsConfiguration',
  424. Notes => 'string composed of R, G, B, Y, Cb and Cr',
  425. },
  426. Compression => { Name => 'CompressionRatio', Writable => 'rational32u' },
  427. ImageSize => {
  428. Writable => 'int16u',
  429. Count => -1,
  430. Notes => '2 or 3 values, for number of XY or XYZ pixels',
  431. PrintConv => '$val=~tr/ /x/;$val',
  432. PrintConvInv => '$val=~tr/x/ /;$val',
  433. },
  434. Resolution => {
  435. Writable => 'rational64u',
  436. Units => [ qw(/in /cm /deg /arcmin /arcsec), '' ],
  437. Count => -1,
  438. Notes => q{
  439. 1 to 3 values. A single value for equal resolution in all directions, or
  440. separate X, Y and Z values if necessary. Units are '/in' unless '/cm',
  441. '/deg', '/arcmin', '/arcsec' or '' specified
  442. },
  443. PrintConv => '$val=~tr/ /x/;$val',
  444. PrintConvInv => '$val=~tr/x/ /;$val',
  445. },
  446. data => {
  447. Name => 'FullSizeImage',
  448. Groups => { 2 => 'Preview' },
  449. %binaryConv,
  450. RawConv => '$self->ValidateImage(\$val,$tag)',
  451. },
  452. );
  453. # MIE preview image
  454. %Image::ExifTool::MIE::Preview = (
  455. %tableDefaults,
  456. GROUPS => { 1 => 'MIE-Preview', 2 => 'Image' },
  457. WRITE_GROUP => 'MIE-Preview',
  458. '0Type' => { Name => 'PreviewImageType', Notes => 'JPEG if not specified' },
  459. '1Name' => { Name => 'PreviewImageName' },
  460. ImageSize => {
  461. Name => 'PreviewImageSize',
  462. Writable => 'int16u',
  463. Count => -1,
  464. Notes => '2 or 3 values, for number of XY or XYZ pixels',
  465. PrintConv => '$val=~tr/ /x/;$val',
  466. PrintConvInv => '$val=~tr/x/ /;$val',
  467. },
  468. data => {
  469. Name => 'PreviewImage',
  470. Groups => { 2 => 'Preview' },
  471. %binaryConv,
  472. RawConv => '$self->ValidateImage(\$val,$tag)',
  473. },
  474. );
  475. # MIE thumbnail image
  476. %Image::ExifTool::MIE::Thumbnail = (
  477. %tableDefaults,
  478. GROUPS => { 1 => 'MIE-Thumbnail', 2 => 'Image' },
  479. WRITE_GROUP => 'MIE-Thumbnail',
  480. '0Type' => { Name => 'ThumbnailImageType', Notes => 'JPEG if not specified' },
  481. '1Name' => { Name => 'ThumbnailImageName' },
  482. ImageSize => {
  483. Name => 'ThumbnailImageSize',
  484. Writable => 'int16u',
  485. Count => -1,
  486. Notes => '2 or 3 values, for number of XY or XYZ pixels',
  487. PrintConv => '$val=~tr/ /x/;$val',
  488. PrintConvInv => '$val=~tr/x/ /;$val',
  489. },
  490. data => {
  491. Name => 'ThumbnailImage',
  492. Groups => { 2 => 'Preview' },
  493. %binaryConv,
  494. RawConv => '$self->ValidateImage(\$val,$tag)',
  495. },
  496. );
  497. # MIE audio information
  498. %Image::ExifTool::MIE::Audio = (
  499. %tableDefaults,
  500. GROUPS => { 1 => 'MIE-Audio', 2 => 'Audio' },
  501. WRITE_GROUP => 'MIE-Audio',
  502. NOTES => q{
  503. For the Audio group (and any other group containing a 'data' element), tags
  504. refer to the contained data if present, otherwise they refer to the main
  505. SubfileData. The C<0Type> and C<1Name> elements should exist only if C<data>
  506. is present.
  507. },
  508. '0Type' => { Name => 'RelatedAudioFileType', Notes => 'MP3 if not specified' },
  509. '1Name' => { Name => 'RelatedAudioFileName' },
  510. SampleBits => { Writable => 'int16u' },
  511. Channels => { Writable => 'int8u' },
  512. Compression => { Name => 'AudioCompression' },
  513. Duration => { Writable => 'rational64u', PrintConv => 'ConvertDuration($val)' },
  514. SampleRate => { Writable => 'int32u' },
  515. data => { Name => 'RelatedAudioFile', %binaryConv },
  516. );
  517. # MIE video information
  518. %Image::ExifTool::MIE::Video = (
  519. %tableDefaults,
  520. GROUPS => { 1 => 'MIE-Video', 2 => 'Video' },
  521. WRITE_GROUP => 'MIE-Video',
  522. '0Type' => { Name => 'RelatedVideoFileType', Notes => 'MOV if not specified' },
  523. '1Name' => { Name => 'RelatedVideoFileName' },
  524. Codec => { },
  525. Duration => { Writable => 'rational64u', PrintConv => 'ConvertDuration($val)' },
  526. data => { Name => 'RelatedVideoFile', %binaryConv },
  527. );
  528. # MIE camera information
  529. %Image::ExifTool::MIE::Camera = (
  530. %tableDefaults,
  531. GROUPS => { 1 => 'MIE-Camera', 2 => 'Camera' },
  532. WRITE_GROUP => 'MIE-Camera',
  533. Brightness => { Writable => 'int8s' },
  534. ColorTemperature=> { Writable => 'int32u' },
  535. ColorBalance => {
  536. Writable => 'rational64u',
  537. Count => 3,
  538. Notes => 'RGB scaling factors',
  539. },
  540. Contrast => { Writable => 'int8s' },
  541. DigitalZoom => { Writable => 'rational64u' },
  542. ExposureComp => { Name => 'ExposureCompensation', Writable => 'rational64s' },
  543. ExposureMode => { },
  544. ExposureTime => {
  545. Writable => 'rational64u',
  546. PrintConv => 'Image::ExifTool::Exif::PrintExposureTime($val)',
  547. PrintConvInv => 'Image::ExifTool::Exif::ConvertFraction($val)',
  548. },
  549. Flash => {
  550. SubDirectory => {
  551. TagTable => 'Image::ExifTool::MIE::Flash',
  552. DirName => 'MIE-Flash',
  553. },
  554. },
  555. FirmwareVersion => { },
  556. FocusMode => { },
  557. ISO => { Writable => 'int16u' },
  558. ISOSetting => {
  559. Writable => 'int16u',
  560. Notes => '0 = Auto, otherwise manual ISO speed setting',
  561. },
  562. ImageNumber => { Writable => 'int32u' },
  563. ImageQuality => { Notes => 'Economy, Normal, Fine, Super Fine or Raw' },
  564. ImageStabilization => { Writable => 'int8u', %offOn },
  565. Lens => {
  566. SubDirectory => {
  567. TagTable => 'Image::ExifTool::MIE::Lens',
  568. DirName => 'MIE-Lens',
  569. },
  570. },
  571. Make => { },
  572. MeasuredEV => { Writable => 'rational64s' },
  573. Model => { },
  574. OwnerName => { },
  575. Orientation => {
  576. SubDirectory => {
  577. TagTable => 'Image::ExifTool::MIE::Orient',
  578. DirName => 'MIE-Orient',
  579. },
  580. },
  581. Saturation => { Writable => 'int8s' },
  582. SensorSize => {
  583. Writable => 'rational64u',
  584. Count => 2,
  585. Notes => 'width and height of active sensor area in mm',
  586. },
  587. SerialNumber => { },
  588. Sharpness => { Writable => 'int8s' },
  589. ShootingMode => { },
  590. );
  591. # Camera orientation information
  592. %Image::ExifTool::MIE::Orient = (
  593. %tableDefaults,
  594. GROUPS => { 1 => 'MIE-Orient', 2 => 'Camera' },
  595. WRITE_GROUP => 'MIE-Orient',
  596. NOTES => 'These tags describe the camera orientation.',
  597. Azimuth => {
  598. Writable => 'rational64s',
  599. Units => [ qw(deg deg{mag}) ],
  600. Notes => q{'deg' CW from true north unless 'deg{mag}' specified},
  601. },
  602. Declination => { Writable => 'rational64s' },
  603. Elevation => { Writable => 'rational64s' },
  604. RightAscension => { Writable => 'rational64s' },
  605. Rotation => {
  606. Writable => 'rational64s',
  607. Notes => 'CW rotation angle of camera about lens axis',
  608. },
  609. );
  610. # MIE camera lens information
  611. %Image::ExifTool::MIE::Lens = (
  612. %tableDefaults,
  613. GROUPS => { 1 => 'MIE-Lens', 2 => 'Camera' },
  614. WRITE_GROUP => 'MIE-Lens',
  615. NOTES => q{
  616. All recorded lens parameters (focal length, aperture, etc) include the
  617. effects of the extender if present.
  618. },
  619. Extender => {
  620. SubDirectory => {
  621. TagTable => 'Image::ExifTool::MIE::Extender',
  622. DirName => 'MIE-Extender',
  623. },
  624. },
  625. FNumber => { Writable => 'rational64u' },
  626. FocalLength => { Writable => 'rational64u', Notes => 'all focal lengths in mm' },
  627. FocusDistance => {
  628. Writable => 'rational64u',
  629. Units => [ qw(m ft) ],
  630. Notes => q{'m' unless 'ft' specified},
  631. },
  632. Make => { Name => 'LensMake' },
  633. MaxAperture => { Writable => 'rational64u' },
  634. MaxApertureAtMaxFocal => { Writable => 'rational64u' },
  635. MaxFocalLength => { Writable => 'rational64u' },
  636. MinAperture => { Writable => 'rational64u' },
  637. MinFocalLength => { Writable => 'rational64u' },
  638. Model => { Name => 'LensModel' },
  639. OpticalZoom => { Writable => 'rational64u' },
  640. SerialNumber => { Name => 'LensSerialNumber' },
  641. );
  642. # MIE lens extender information
  643. %Image::ExifTool::MIE::Extender = (
  644. %tableDefaults,
  645. GROUPS => { 1 => 'MIE-Extender', 2 => 'Camera' },
  646. WRITE_GROUP => 'MIE-Extender',
  647. Magnification => { Name => 'ExtenderMagnification', Writable => 'rational64s' },
  648. Make => { Name => 'ExtenderMake' },
  649. Model => { Name => 'ExtenderModel' },
  650. SerialNumber => { Name => 'ExtenderSerialNumber' },
  651. );
  652. # MIE camera flash information
  653. %Image::ExifTool::MIE::Flash = (
  654. %tableDefaults,
  655. GROUPS => { 1 => 'MIE-Flash', 2 => 'Camera' },
  656. WRITE_GROUP => 'MIE-Flash',
  657. ExposureComp => { Name => 'FlashExposureComp', Writable => 'rational64s' },
  658. Fired => { Name => 'FlashFired', Writable => 'int8u', PrintConv => \%noYes },
  659. GuideNumber => { Name => 'FlashGuideNumber' },
  660. Make => { Name => 'FlashMake' },
  661. Mode => { Name => 'FlashMode' },
  662. Model => { Name => 'FlashModel' },
  663. SerialNumber => { Name => 'FlashSerialNumber' },
  664. Type => { Name => 'FlashType', Notes => '"Internal" or "External"' },
  665. );
  666. # MIE maker notes information
  667. %Image::ExifTool::MIE::MakerNotes = (
  668. %tableDefaults,
  669. GROUPS => { 1 => 'MIE-MakerNotes' },
  670. WRITE_GROUP => 'MIE-MakerNotes',
  671. NOTES => q{
  672. MIE maker notes are contained within separate groups for each manufacturer
  673. to avoid name conflicts.
  674. },
  675. Canon => {
  676. SubDirectory => {
  677. TagTable => 'Image::ExifTool::MIE::Canon',
  678. DirName => 'MIE-Canon',
  679. },
  680. },
  681. Casio => { SubDirectory => { TagTable => 'Image::ExifTool::MIE::Unknown' } },
  682. FujiFilm => { SubDirectory => { TagTable => 'Image::ExifTool::MIE::Unknown' } },
  683. Kodak => { SubDirectory => { TagTable => 'Image::ExifTool::MIE::Unknown' } },
  684. KonicaMinolta=>{ SubDirectory => { TagTable => 'Image::ExifTool::MIE::Unknown' } },
  685. Nikon => { SubDirectory => { TagTable => 'Image::ExifTool::MIE::Unknown' } },
  686. Olympus => { SubDirectory => { TagTable => 'Image::ExifTool::MIE::Unknown' } },
  687. Panasonic => { SubDirectory => { TagTable => 'Image::ExifTool::MIE::Unknown' } },
  688. Pentax => { SubDirectory => { TagTable => 'Image::ExifTool::MIE::Unknown' } },
  689. Ricoh => { SubDirectory => { TagTable => 'Image::ExifTool::MIE::Unknown' } },
  690. Sigma => { SubDirectory => { TagTable => 'Image::ExifTool::MIE::Unknown' } },
  691. Sony => { SubDirectory => { TagTable => 'Image::ExifTool::MIE::Unknown' } },
  692. );
  693. # MIE Canon-specific information
  694. %Image::ExifTool::MIE::Canon = (
  695. %tableDefaults,
  696. GROUPS => { 1 => 'MIE-Canon' },
  697. WRITE_GROUP => 'MIE-Canon',
  698. VRD => {
  699. Name => 'CanonVRD',
  700. SubDirectory => { TagTable => 'Image::ExifTool::CanonVRD::Main' },
  701. },
  702. );
  703. %Image::ExifTool::MIE::Unknown = (
  704. PROCESS_PROC => \&ProcessMIE,
  705. GROUPS => { 1 => 'MIE-Unknown' },
  706. );
  707. #------------------------------------------------------------------------------
  708. # Add user-defined MIE groups to %mieMap
  709. # Inputs: none; Returns: nothing, but sets $doneMieMap flag
  710. sub UpdateMieMap()
  711. {
  712. $doneMieMap = 1; # set flag so we only do this once
  713. return unless %Image::ExifTool::UserDefined;
  714. my ($tableName, @tables, %doneTable, $tagID);
  715. # get list of top-level MIE tables with user-defined tags
  716. foreach $tableName (keys %Image::ExifTool::UserDefined) {
  717. next unless $tableName =~ /^Image::ExifTool::MIE::/;
  718. my $userTable = $Image::ExifTool::UserDefined{$tableName};
  719. my $tagTablePtr = GetTagTable($tableName) or next;
  720. # copy the WRITE_GROUP from the actual table
  721. $$userTable{WRITE_GROUP} = $$tagTablePtr{WRITE_GROUP};
  722. # add to list of tables to process
  723. $doneTable{$tableName} = 1;
  724. push @tables, [$tableName, $userTable];
  725. }
  726. # recursively add all user-defined groups to MIE map
  727. while (@tables) {
  728. my ($tableName, $tagTablePtr) = @{shift @tables};
  729. my $parent = $$tagTablePtr{WRITE_GROUP};
  730. $parent or warn("No WRITE_GROUP for $tableName\n"), next;
  731. $mieMap{$parent} or warn("$parent is not in MIE map\n"), next;
  732. foreach $tagID (TagTableKeys($tagTablePtr)) {
  733. my $tagInfo = $$tagTablePtr{$tagID};
  734. next unless ref $tagInfo eq 'HASH' and $$tagInfo{SubDirectory};
  735. my $subTableName = $tagInfo->{SubDirectory}->{TagTable};
  736. my $subTablePtr = GetTagTable($subTableName) or next;
  737. # only care about MIE tables
  738. next unless $$subTablePtr{PROCESS_PROC} and
  739. $$subTablePtr{PROCESS_PROC} eq \&ProcessMIE;
  740. my $group = $$subTablePtr{WRITE_GROUP};
  741. $group or warn("No WRITE_GROUP for $subTableName\n"), next;
  742. if ($mieMap{$group} and $mieMap{$group} ne $parent) {
  743. warn("$group already has different parent ($mieMap{$group})\n"), next;
  744. }
  745. $mieMap{$group} = $parent; # add to map
  746. # process tables within this one too
  747. $doneTable{$subTableName} and next;
  748. $doneTable{$subTableName} = 1;
  749. push @tables, [$subTableName, $subTablePtr];
  750. }
  751. }
  752. }
  753. #------------------------------------------------------------------------------
  754. # Get localized version of tagInfo hash
  755. # Inputs: 0) tagInfo hash ref, 1) locale code (eg. "en_CA")
  756. # Returns: new tagInfo hash ref, or undef if invalid
  757. sub GetLangInfo($$)
  758. {
  759. my ($tagInfo, $langCode) = @_;
  760. # check for properly formatted language code
  761. return undef unless $langCode =~ /^[a-z]{2}([-_])[A-Z]{2}$/;
  762. # use '_' as a separator, but recognize '_' or '-'
  763. $langCode =~ tr/-/_/ if $1 eq '-';
  764. # can only set locale on string types
  765. return undef if $$tagInfo{Writable} and $$tagInfo{Writable} ne 'string';
  766. return Image::ExifTool::GetLangInfo($tagInfo, $langCode);
  767. }
  768. #------------------------------------------------------------------------------
  769. # return true if we have Zlib::Compress
  770. # Inputs: 0) ExifTool object ref, 1) verb for what you want to do with the info
  771. # Returns: 1 if Zlib available, 0 otherwise
  772. sub HasZlib($$)
  773. {
  774. unless (defined $hasZlib) {
  775. $hasZlib = eval { require Compress::Zlib };
  776. unless ($hasZlib) {
  777. $hasZlib = 0;
  778. $_[0]->Warn("Install Compress::Zlib to $_[1] compressed information");
  779. }
  780. }
  781. return $hasZlib;
  782. }
  783. #------------------------------------------------------------------------------
  784. # Get format code for MIE group element with current byte order
  785. # Inputs: 0) [optional] true to convert result to chr()
  786. # Returns: format code
  787. sub MIEGroupFormat(;$)
  788. {
  789. my $chr = shift;
  790. my $format = GetByteOrder() eq 'MM' ? 0x10 : 0x18;
  791. return $chr ? chr($format) : $format;
  792. }
  793. #------------------------------------------------------------------------------
  794. # ReadValue() with added support for UTF formats (utf8, utf16 and utf32)
  795. # Inputs: 0) data reference, 1) value offset, 2) format string,
  796. # 3) number of values (or undef to use all data)
  797. # 4) valid data length relative to offset, 5) returned rational ref
  798. # Returns: converted value, or undefined if data isn't there
  799. # or list of values in list context
  800. # Notes: all string formats are converted to UTF8
  801. sub ReadMIEValue($$$$$;$)
  802. {
  803. my ($dataPt, $offset, $format, $count, $size, $ratPt) = @_;
  804. my $val;
  805. if ($format =~ /^(utf(8|16|32)|string)/) {
  806. if ($1 eq 'utf8' or $1 eq 'string') {
  807. # read the 8-bit string
  808. $val = substr($$dataPt, $offset, $size);
  809. # (as of ExifTool 7.62, leave string values unconverted)
  810. } else {
  811. # convert to UTF8
  812. my $fmt;
  813. if (GetByteOrder() eq 'MM') {
  814. $fmt = ($1 eq 'utf16') ? 'n' : 'N';
  815. } else {
  816. $fmt = ($1 eq 'utf16') ? 'v' : 'V';
  817. }
  818. my @unpk = unpack("x$offset$fmt$size",$$dataPt);
  819. if ($] >= 5.006001) {
  820. $val = pack('C0U*', @unpk);
  821. } else {
  822. $val = Image::ExifTool::PackUTF8(@unpk);
  823. }
  824. }
  825. # truncate at null unless this is a list
  826. # (strings shouldn't have a null, but just in case)
  827. $val =~ s/\0.*//s unless $format =~ /_list$/;
  828. } else {
  829. $format = 'undef' if $format eq 'free'; # read 'free' as 'undef'
  830. return ReadValue($dataPt, $offset, $format, $count, $size, $ratPt);
  831. }
  832. return $val;
  833. }
  834. #------------------------------------------------------------------------------
  835. # validate raw values for writing
  836. # Inputs: 0) ExifTool object ref, 1) tagInfo hash ref, 2) raw value ref
  837. # Returns: error string or undef (and possibly changes value) on success
  838. sub CheckMIE($$$)
  839. {
  840. my ($et, $tagInfo, $valPtr) = @_;
  841. my $format = $$tagInfo{Writable} || $tagInfo->{Table}->{WRITABLE};
  842. my $err;
  843. return 'No writable format' if not $format or $format eq '1';
  844. # handle units if supported by this tag
  845. my $ulist = $$tagInfo{Units};
  846. if ($ulist and $$valPtr =~ /(.*)\((.*)\)$/) {
  847. my ($val, $units) = ($1, $2);
  848. ($units) = grep /^$units$/i, @$ulist;
  849. defined $units or return 'Allowed units: (' . join('|', @$ulist) . ')';
  850. $err = Image::ExifTool::CheckValue(\$val, $format, $$tagInfo{Count});
  851. # add units back onto value
  852. $$valPtr = "$val($units)" unless $err;
  853. } elsif ($format !~ /^(utf|string|undef)/ and $$valPtr =~ /\)$/) {
  854. return 'Units not supported';
  855. } else {
  856. if ($format eq 'string' and $$et{OPTIONS}{Charset} ne 'UTF8' and
  857. $$valPtr =~ /[\x80-\xff]/)
  858. {
  859. # convert from Charset to UTF-8
  860. $$valPtr = $et->Encode($$valPtr,'UTF8');
  861. }
  862. $err = Image::ExifTool::CheckValue($valPtr, $format, $$tagInfo{Count});
  863. }
  864. return $err;
  865. }
  866. #------------------------------------------------------------------------------
  867. # Rewrite a MIE directory
  868. # Inputs: 0) ExifTool object reference, 1) DirInfo reference, 2) tag table ptr
  869. # Returns: undef on success, otherwise error message (empty message if nothing to write)
  870. sub WriteMIEGroup($$$)
  871. {
  872. my ($et, $dirInfo, $tagTablePtr) = @_;
  873. my $outfile = $$dirInfo{OutFile};
  874. my $dirName = $$dirInfo{DirName};
  875. my $toWrite = $$dirInfo{ToWrite} || '';
  876. my $raf = $$dirInfo{RAF};
  877. my $verbose = $et->Options('Verbose');
  878. my $optCompress = $et->Options('Compress');
  879. my $out = $et->Options('TextOut');
  880. my ($msg, $err, $ok, $sync, $delGroup);
  881. my $tag = '';
  882. my $deletedTag = '';
  883. # count each MIE directory found and make name for this specific instance
  884. my ($grp1, %isWriting);
  885. my $cnt = $$et{MIE_COUNT};
  886. my $grp = $tagTablePtr->{GROUPS}->{1};
  887. my $n = $$cnt{'MIE-Main'} || 0;
  888. if ($grp eq 'MIE-Main') {
  889. $$cnt{$grp} = ++$n;
  890. ($grp1 = $grp) =~ s/MIE-/MIE$n-/;
  891. } else {
  892. ($grp1 = $grp) =~ s/MIE-/MIE$n-/;
  893. my $m = $$cnt{$grp1} = ($$cnt{$grp1} || 0) + 1;
  894. $isWriting{"$grp$m"} = 1; # eg. 'MIE-Doc2'
  895. $isWriting{$grp1} = 1; # eg. 'MIE1-Doc'
  896. $grp1 .= $m;
  897. }
  898. # build lookup for all valid group names for this MIE group
  899. $isWriting{$grp} = 1; # eg. 'MIE-Doc'
  900. $isWriting{$grp1} = 1; # eg. 'MIE1-Doc2'
  901. $isWriting{"MIE$n"} = 1; # eg. 'MIE1'
  902. # determine if we are deleting this group
  903. if (%{$$et{DEL_GROUP}}) {
  904. $delGroup = 1 if $$et{DEL_GROUP}{MIE} or
  905. $$et{DEL_GROUP}{$grp} or
  906. $$et{DEL_GROUP}{$grp1} or
  907. $$et{DEL_GROUP}{"MIE$n"};
  908. }
  909. # prepare lookups and lists for writing
  910. my $newTags = $et->GetNewTagInfoHash($tagTablePtr);
  911. my ($addDirs, $editDirs) = $et->GetAddDirHash($tagTablePtr, $dirName);
  912. my @editTags = sort keys %$newTags, keys %$editDirs;
  913. $verbose and print $out $raf ? 'Writing' : 'Creating', " $grp1:\n";
  914. # loop through elements in MIE group
  915. MieElement: for (;;) {
  916. my ($format, $tagLen, $valLen, $units, $oldHdr, $buff);
  917. my $lastTag = $tag;
  918. if ($raf) {
  919. # read first 4 bytes of element header
  920. my $n = $raf->Read($oldHdr, 4);
  921. if ($n != 4) {
  922. last if $n or defined $sync;
  923. undef $raf; # all done reading
  924. $ok = 1;
  925. }
  926. }
  927. if ($raf) {
  928. ($sync, $format, $tagLen, $valLen) = unpack('aC3', $oldHdr);
  929. $sync eq '~' or $msg = 'Invalid sync byte', last;
  930. # read tag name
  931. if ($tagLen) {
  932. $raf->Read($tag, $tagLen) == $tagLen or last;
  933. $oldHdr .= $tag; # add tag to element header
  934. $et->Warn("MIE tag '$tag' out of sequence") if $tag lt $lastTag;
  935. # separate units from tag name if they exist
  936. $units = $1 if $tag =~ s/\((.*)\)$//;
  937. } else {
  938. $tag = '';
  939. }
  940. # get multi-byte value length if necessary
  941. if ($valLen > 252) {
  942. # calculate number of bytes in extended DataLength
  943. my $n = 1 << (256 - $valLen);
  944. $raf->Read($buff, $n) == $n or last;
  945. $oldHdr .= $buff; # add to old header
  946. my $fmt = 'int' . ($n * 8) . 'u';
  947. $valLen = ReadValue(\$buff, 0, $fmt, 1, $n);
  948. if ($valLen > 0x7fffffff) {
  949. $msg = "Can't write $tag (DataLength > 2GB not yet supported)";
  950. last;
  951. }
  952. }
  953. # don't rewrite free bytes or information in deleted groups
  954. if ($format eq 0x80 or ($delGroup and $tagLen and ($format & 0xf0) != 0x10)) {
  955. $raf->Seek($valLen, 1) or $msg = 'Seek error', last;
  956. if ($verbose > 1) {
  957. my $free = ($format eq 0x80) ? ' free' : '';
  958. print $out " - $grp1:$tag ($valLen$free bytes)\n";
  959. }
  960. ++$$et{CHANGED} if $delGroup;
  961. next;
  962. }
  963. } else {
  964. # no more elements to read
  965. $tagLen = $valLen = 0;
  966. $tag = '';
  967. }
  968. #
  969. # write necessary new tags and process directories
  970. #
  971. while (@editTags) {
  972. last if $tagLen and $editTags[0] gt $tag;
  973. # we are writing the new tag now
  974. my ($newVal, $writable, $oldVal, $newFormat, $compress);
  975. my $newTag = shift @editTags;
  976. my $newInfo = $$editDirs{$newTag};
  977. if ($newInfo) {
  978. # create the new subdirectory or rewrite existing non-MIE directory
  979. my $subTablePtr = GetTagTable($newInfo->{SubDirectory}->{TagTable});
  980. unless ($subTablePtr) {
  981. $et->Warn("No tag table for $newTag $$newInfo{Name}");
  982. next;
  983. }
  984. my %subdirInfo;
  985. my $isMieGroup = ($$subTablePtr{WRITE_PROC} and
  986. $$subTablePtr{WRITE_PROC} eq \&ProcessMIE);
  987. if ($newTag eq $tag) {
  988. # make sure that either both or neither old and new tags are MIE groups
  989. if ($isMieGroup xor ($format & 0xf3) == 0x10) {
  990. $et->Warn("Tag '$tag' not expected type");
  991. next; # don't write our new tag
  992. }
  993. # uncompress existing directory into $oldVal since we are editing it
  994. if ($format & 0x04) {
  995. last unless HasZlib($et, 'edit');
  996. $raf->Read($oldVal, $valLen) == $valLen or last MieElement;
  997. my $stat;
  998. my $inflate = Compress::Zlib::inflateInit();
  999. $inflate and ($oldVal, $stat) = $inflate->inflate($oldVal);
  1000. unless ($inflate and $stat == Compress::Zlib::Z_STREAM_END()) {
  1001. $msg = "Error inflating $tag";
  1002. last MieElement;
  1003. }
  1004. $compress = 1;
  1005. $valLen = length $oldVal; # uncompressed value length
  1006. }
  1007. } else {
  1008. # don't create this directory unless necessary
  1009. next unless $$addDirs{$newTag};
  1010. }
  1011. if ($isMieGroup) {
  1012. my $hdr;
  1013. if ($newTag eq $tag) {
  1014. # rewrite existing directory later unless it was compressed
  1015. last unless $compress;
  1016. # rewrite directory to '$newVal'
  1017. $newVal = '';
  1018. %subdirInfo = (
  1019. OutFile => \$newVal,
  1020. RAF => new File::RandomAccess(\$oldVal),
  1021. );
  1022. } elsif ($optCompress and not $$dirInfo{IsCompressed}) {
  1023. # write to memory so we can compress the new MIE group
  1024. $compress = 1;
  1025. %subdirInfo = (
  1026. OutFile => \$newVal,
  1027. );
  1028. } else {
  1029. $hdr = '~' . MIEGroupFormat(1) . chr(length($newTag)) .
  1030. "\0" . $newTag;
  1031. %subdirInfo = (
  1032. OutFile => $outfile,
  1033. ToWrite => $toWrite . $hdr,
  1034. );
  1035. }
  1036. $subdirInfo{DirName} = $newInfo->{SubDirectory}->{DirName} || $newTag;
  1037. $subdirInfo{Parent} = $dirName;
  1038. # don't compress elements of an already compressed group
  1039. $subdirInfo{IsCompressed} = $$dirInfo{IsCompressed} || $compress;
  1040. $msg = WriteMIEGroup($et, \%subdirInfo, $subTablePtr);
  1041. last MieElement if $msg;
  1042. # message is defined but empty if nothing was written
  1043. if (defined $msg) {
  1044. undef $msg; # not a problem if nothing was written
  1045. next;
  1046. } elsif (not $compress) {
  1047. # group was written already
  1048. $toWrite = '';
  1049. next;
  1050. } elsif (length($newVal) <= 4) { # terminator only?
  1051. $verbose and print $out "Deleted compressed $grp1 (empty)\n";
  1052. next MieElement if $newTag eq $tag; # deleting the directory
  1053. next; # not creating the new directory
  1054. }
  1055. $writable = 'undef';
  1056. $newFormat = MIEGroupFormat();
  1057. } else {
  1058. if ($newTag eq $tag) {
  1059. unless ($compress) {
  1060. # read and edit existing directory
  1061. $raf->Read($oldVal, $valLen) == $valLen or last MieElement;
  1062. }
  1063. %subdirInfo = (
  1064. DataPt => \$oldVal,
  1065. DataLen => $valLen,
  1066. DirName => $$newInfo{Name},
  1067. DataPos => $$dirInfo{IsCompressed} ? undef : $raf->Tell() - $valLen,
  1068. DirStart=> 0,
  1069. DirLen => $valLen,
  1070. );
  1071. # write Compact subdirectories if we will compress the data
  1072. if (($compress or $optCompress or $$dirInfo{IsCompressed}) and
  1073. eval { require Compress::Zlib })
  1074. {
  1075. $subdirInfo{Compact} = 1;
  1076. }
  1077. }
  1078. $subdirInfo{Parent} = $dirName;
  1079. my $writeProc = $newInfo->{SubDirectory}->{WriteProc};
  1080. # reset processed lookup to avoid errors in case of multiple EXIF blocks
  1081. $$et{PROCESSED} = { };
  1082. $newVal = $et->WriteDirectory(\%subdirInfo, $subTablePtr, $writeProc);
  1083. if (defined $newVal) {
  1084. if ($newVal eq '') {
  1085. next MieElement if $newTag eq $tag; # deleting the directory
  1086. next; # not creating the new directory
  1087. }
  1088. } else {
  1089. next unless defined $oldVal;
  1090. $newVal = $oldVal; # just copy over the old directory
  1091. }
  1092. $writable = 'undef';
  1093. $newFormat = 0x00; # all other directories are 'undef' format
  1094. }
  1095. } else {
  1096. # get the new tag information
  1097. $newInfo = $$newTags{$newTag};
  1098. my $nvHash = $et->GetNewValueHash($newInfo);
  1099. my @newVals;
  1100. # write information only to specified group
  1101. my $writeGroup = $$nvHash{WriteGroup};
  1102. last unless $isWriting{$writeGroup};
  1103. # if tag existed, must decide if we want to overwrite the value
  1104. if ($newTag eq $tag) {
  1105. my $isOverwriting;
  1106. my $isList = $$newInfo{List};
  1107. if ($isList) {
  1108. last if $$nvHash{CreateOnly};
  1109. $isOverwriting = -1; # force processing list elements individually
  1110. } else {
  1111. $isOverwriting = $et->IsOverwriting($nvHash);
  1112. last unless $isOverwriting;
  1113. }
  1114. my ($val, $cmpVal);
  1115. if ($isOverwriting < 0 or $verbose > 1) {
  1116. # check to be sure we can uncompress the value if necessary
  1117. HasZlib($et, 'edit') or last if $format & 0x04;
  1118. # read the old value
  1119. $raf->Read($oldVal, $valLen) == $valLen or last MieElement;
  1120. # uncompress if necessary
  1121. if ($format & 0x04) {
  1122. my $stat;
  1123. my $inflate = Compress::Zlib::inflateInit();
  1124. # must save original compressed value in case we decide
  1125. # not to overwrite it later
  1126. $cmpVal = $oldVal;
  1127. $inflate and ($oldVal, $stat) = $inflate->inflate($oldVal);
  1128. unless ($inflate and $stat == Compress::Zlib::Z_STREAM_END()) {
  1129. $msg = "Error inflating $tag";
  1130. last MieElement;
  1131. }
  1132. $valLen = length $oldVal; # update value length
  1133. }
  1134. # convert according to specified format
  1135. my $formatStr = $mieFormat{$format & 0xfb} || 'undef';
  1136. $val = ReadMIEValue(\$oldVal, 0, $formatStr, undef, $valLen);
  1137. if ($isOverwriting < 0 and defined $val) {
  1138. # handle list values individually
  1139. if ($isList) {
  1140. my (@vals, $v);
  1141. if ($formatStr =~ /_list$/) {
  1142. @vals = split "\0", $val;
  1143. } else {
  1144. @vals = $val;
  1145. }
  1146. # keep any list items that we aren't overwriting
  1147. foreach $v (@vals) {
  1148. next if $et->IsOverwriting($nvHash, $v);
  1149. push @newVals, $v;
  1150. }
  1151. } else {
  1152. # test to see if we really want to overwrite the value
  1153. $isOverwriting = $et->IsOverwriting($nvHash, $val);
  1154. }
  1155. }
  1156. }
  1157. if ($isOverwriting) {
  1158. # skip the old value if we didn't read it already
  1159. unless (defined $oldVal) {
  1160. $raf->Seek($valLen, 1) or $msg = 'Seek error';
  1161. }
  1162. if ($verbose > 1) {
  1163. $val .= "($units)" if defined $units;
  1164. $et->VerboseValue("- $grp1:$$newInfo{Name}", $val);
  1165. }
  1166. $deletedTag = $tag; # remember that we deleted this tag
  1167. ++$$et{CHANGED}; # we deleted the old value
  1168. } else {
  1169. if (defined $oldVal) {
  1170. # write original compressed value
  1171. $oldVal = $cmpVal if defined $cmpVal;
  1172. } else {
  1173. $raf->Read($oldVal, $valLen) == $valLen or last MieElement;
  1174. }
  1175. # write the old value now
  1176. Write($outfile, $toWrite, $oldHdr, $oldVal) or $err = 1;
  1177. $toWrite = '';
  1178. next MieElement;
  1179. }
  1180. unless (@newVals) {
  1181. # unshift the new tag info to write it later
  1182. unshift @editTags, $newTag;
  1183. next MieElement; # get next element from file
  1184. }
  1185. } else {
  1186. # write new value if creating, or if List and list existed, or
  1187. # if tag was previously deleted
  1188. next unless $$nvHash{IsCreating} or
  1189. (($newTag eq $lastTag and ($$newInfo{List} or $deletedTag eq $lastTag)
  1190. and not $$nvHash{EditOnly}));
  1191. }
  1192. # get the new value to write (undef to delete)
  1193. push @newVals, $et->GetNewValue($nvHash);
  1194. next unless @newVals;
  1195. $writable = $$newInfo{Writable} || $$tagTablePtr{WRITABLE};
  1196. if ($writable eq 'string') {
  1197. # join multiple values into a single string
  1198. $newVal = join "\0", @newVals;
  1199. # write string as UTF-8,16 or 32 if value contains valid UTF-8 codes
  1200. require Image::ExifTool::XMP;
  1201. my $isUTF8 = Image::ExifTool::XMP::IsUTF8(\$newVal);
  1202. if ($isUTF8 > 0) {
  1203. $writable = 'utf8';
  1204. # write UTF-16 or UTF-32 if it is more compact
  1205. my $to = $isUTF8 > 1 ? 'UCS4' : 'UCS2';
  1206. my $tmp = Image::ExifTool::Decode(undef,$newVal,'UTF8',undef,$to);
  1207. if (length $tmp < length $newVal) {
  1208. $newVal = $tmp;
  1209. $writable = ($isUTF8 > 1) ? 'utf32' : 'utf16';
  1210. }
  1211. }
  1212. # write as a list if we have multiple values
  1213. $writable .= '_list' if @newVals > 1;
  1214. } else {
  1215. # should only be one element in the list
  1216. $newVal = shift @newVals;
  1217. }
  1218. $newFormat = $mieCode{$writable};
  1219. unless (defined $newFormat) {
  1220. $msg = "Bad format '$writable' for $$newInfo{Name}";
  1221. next MieElement;
  1222. }
  1223. }
  1224. # write the new or edited element
  1225. while (defined $newFormat) {
  1226. my $valPt = \$newVal;
  1227. # remove units from value and add to tag name if supported by this tag
  1228. if ($$newInfo{Units}) {
  1229. my $val2;
  1230. if ($$valPt =~ /(.*)\((.*)\)$/) {
  1231. $val2 = $1;
  1232. $newTag .= "($2)";
  1233. } else {
  1234. $val2 = $$valPt;
  1235. # add default units
  1236. my $ustr = '(' . $newInfo->{Units}->[0] . ')';
  1237. $newTag .= $ustr;
  1238. $$valPt .= $ustr;
  1239. }
  1240. $valPt = \$val2;
  1241. }
  1242. # convert value if necessary
  1243. if ($writable !~ /^(utf|string|undef)/) {
  1244. my $val3 = WriteValue($$valPt, $writable, $$newInfo{Count});
  1245. defined $val3 or $et->Warn("Error writing $newTag"), last;
  1246. $valPt = \$val3;
  1247. }
  1248. my $len = length $$valPt;
  1249. # compress value before writing if required
  1250. if (($compress or $optCompress) and not $$dirInfo{IsCompressed} and
  1251. HasZlib($et, 'write'))
  1252. {
  1253. my $deflate = Compress::Zlib::deflateInit();
  1254. my $val4;
  1255. if ($deflate) {
  1256. $val4 = $deflate->deflate($$valPt);
  1257. $val4 .= $deflate->flush() if defined $val4;
  1258. }
  1259. if (defined $val4) {
  1260. my $len4 = length $val4;
  1261. my $saved = $len - $len4;
  1262. # only use compressed data if it is smaller
  1263. if ($saved > 0) {
  1264. $verbose and print $out " [$newTag compression saved $saved bytes]\n";
  1265. $newFormat |= 0x04; # set compressed bit
  1266. $len = $len4; # set length
  1267. $valPt = \$val4; # set value pointer
  1268. } elsif ($verbose) {
  1269. print $out " [$newTag compression saved $saved bytes -- written uncompressed]\n";
  1270. }
  1271. } else {
  1272. $et->Warn("Error deflating $newTag (written uncompressed)");
  1273. }
  1274. }
  1275. # calculate the DataLength code
  1276. my $extLen;
  1277. if ($len < 253) {
  1278. $extLen = '';
  1279. } elsif ($len < 65536) {
  1280. $extLen = Set16u($len);
  1281. $len = 255;
  1282. } elsif ($len <= 0x7fffffff) {
  1283. $extLen = Set32u($len);
  1284. $len = 254;
  1285. } else {
  1286. $et->Warn("Can't write $newTag (DataLength > 2GB not yet suppported)");
  1287. last; # don't write this tag
  1288. }
  1289. # write this element (with leading MIE group element if not done already)
  1290. my $hdr = $toWrite . '~' . chr($newFormat) . chr(length $newTag);
  1291. Write($outfile, $hdr, chr($len), $newTag, $extLen, $$valPt) or $err = 1;
  1292. $toWrite = '';
  1293. # we changed a tag unless just editing a subdirectory
  1294. unless ($$editDirs{$newTag}) {
  1295. $et->VerboseValue("+ $grp1:$$newInfo{Name}", $newVal);
  1296. ++$$et{CHANGED};
  1297. }
  1298. last; # didn't want to loop anyway
  1299. }
  1300. next MieElement if defined $oldVal;
  1301. }
  1302. #
  1303. # rewrite existing element or descend into uncompressed MIE group
  1304. #
  1305. # all done this MIE group if we reached the terminator element
  1306. unless ($tagLen) {
  1307. # skip over existing terminator data (if any)
  1308. last if $valLen and not $raf->Seek($valLen, 1);
  1309. $ok = 1;
  1310. # write group terminator if necessary
  1311. unless ($toWrite) {
  1312. # write end-of-group terminator element
  1313. my $term = "~\0\0\0";
  1314. unless ($$dirInfo{Parent}) {
  1315. # write extended terminator for file-level group
  1316. my $len = ref $outfile eq 'SCALAR' ? length($$outfile) : tell $outfile;
  1317. $len += 10; # include length of terminator itself
  1318. if ($len and $len <= 0x7fffffff) {
  1319. $term = "~\0\0\x06" . Set32u($len) . MIEGroupFormat(1) . "\x04";
  1320. }
  1321. }
  1322. Write($outfile, $term) or $err = 1;
  1323. }
  1324. last;
  1325. }
  1326. # descend into existing uncompressed MIE group
  1327. if ($format == 0x10 or $format == 0x18) {
  1328. my ($subTablePtr, $dirName);
  1329. my $tagInfo = $et->GetTagInfo($tagTablePtr, $tag);
  1330. if ($tagInfo and $$tagInfo{SubDirectory}) {
  1331. $dirName = $tagInfo->{SubDirectory}->{DirName};
  1332. my $subTable = $tagInfo->{SubDirectory}->{TagTable};
  1333. $subTablePtr = $subTable ? GetTagTable($subTable) : $tagTablePtr;
  1334. } else {
  1335. $subTablePtr = GetTagTable('Image::ExifTool::MIE::Unknown');
  1336. }
  1337. my $hdr = '~' . chr($format) . chr(length $tag) . "\0" . $tag;
  1338. my %subdirInfo = (
  1339. DirName => $dirName || $tag,
  1340. RAF => $raf,
  1341. ToWrite => $toWrite . $hdr,
  1342. OutFile => $outfile,
  1343. Parent => $dirName,
  1344. IsCompressed => $$dirInfo{IsCompressed},
  1345. );
  1346. my $oldOrder = GetByteOrder();
  1347. SetByteOrder($format & 0x08 ? 'II' : 'MM');
  1348. $msg = WriteMIEGroup($et, \%subdirInfo, $subTablePtr);
  1349. SetByteOrder($oldOrder);
  1350. last if $msg;
  1351. if (defined $msg) {
  1352. undef $msg; # no problem if nothing written
  1353. } else {
  1354. $toWrite = '';
  1355. }
  1356. next;
  1357. }
  1358. # just copy existing element
  1359. my $oldVal;
  1360. $raf->Read($oldVal, $valLen) == $valLen or last;
  1361. if ($toWrite) {
  1362. Write($outfile, $toWrite) or $err = 1;
  1363. $toWrite = '';
  1364. }
  1365. Write($outfile, $oldHdr, $oldVal) or $err = 1;
  1366. }
  1367. # return error message
  1368. if ($err) {
  1369. $msg = 'Error writing file';
  1370. } elsif (not $ok and not $msg) {
  1371. $msg = 'Unexpected end of file';
  1372. } elsif (not $msg and $toWrite) {
  1373. $msg = ''; # flag for nothing written
  1374. $verbose and print $out "Deleted $grp1 (empty)\n";
  1375. }
  1376. return $msg;
  1377. }
  1378. #------------------------------------------------------------------------------
  1379. # Process MIE directory
  1380. # Inputs: 0) ExifTool object reference, 1) DirInfo reference, 2) tag table ref
  1381. # Returns: undef on success, or error message if there was a problem
  1382. # Notes: file pointer is positioned at the MIE end on entry
  1383. sub ProcessMIEGroup($$$)
  1384. {
  1385. my ($et, $dirInfo, $tagTablePtr) = @_;
  1386. my $raf = $$dirInfo{RAF};
  1387. my $verbose = $et->Options('Verbose');
  1388. my $out = $et->Options('TextOut');
  1389. my $notUTF8 = ($$et{OPTIONS}{Charset} ne 'UTF8');
  1390. my ($msg, $buff, $ok, $oldIndent, $mime);
  1391. my $lastTag = '';
  1392. # get group 1 names: $grp doesn't have numbers (eg. 'MIE-Doc'),
  1393. # and $grp1 does (eg. 'MIE1-Doc1')
  1394. my $cnt = $$et{MIE_COUNT};
  1395. my $grp1 = $tagTablePtr->{GROUPS}->{1};
  1396. my $n = $$cnt{'MIE-Main'} || 0;
  1397. if ($grp1 eq 'MIE-Main') {
  1398. $$cnt{$grp1} = ++$n;
  1399. $grp1 =~ s/MIE-/MIE$n-/ if $n > 1;
  1400. } else {
  1401. $grp1 =~ s/MIE-/MIE$n-/ if $n > 1;
  1402. $$cnt{$grp1} = ($$cnt{$grp1} || 0) + 1;
  1403. $grp1 .= $$cnt{$grp1} if $$cnt{$grp1} > 1;
  1404. }
  1405. # set group1 name for all tags extracted from this group
  1406. $$et{SET_GROUP1} = $grp1;
  1407. if ($verbose) {
  1408. $oldIndent = $$et{INDENT};
  1409. $$et{INDENT} .= '| ';
  1410. $et->VerboseDir($grp1);
  1411. }
  1412. my $wasCompressed = $$dirInfo{WasCompressed};
  1413. # process all MIE elements
  1414. for (;;) {
  1415. $raf->Read($buff, 4) == 4 or last;
  1416. my ($sync, $format, $tagLen, $valLen) = unpack('aC3', $buff);
  1417. $sync eq '~' or $msg = 'Invalid sync byte', last;
  1418. # read tag name
  1419. my ($tag, $units);
  1420. if ($tagLen) {
  1421. $raf->Read($tag, $tagLen) == $tagLen or last;
  1422. $et->Warn("MIE tag '$tag' out of sequence") if $tag lt $lastTag;
  1423. $lastTag = $tag;
  1424. # separate units from tag name if they exist
  1425. $units = $1 if $tag =~ s/\((.*)\)$//;
  1426. } else {
  1427. $tag = '';
  1428. }
  1429. # get multi-byte value length if necessary
  1430. if ($valLen > 252) {
  1431. my $n = 1 << (256 - $valLen);
  1432. $raf->Read($buff, $n) == $n or last;
  1433. my $fmt = 'int' . ($n * 8) . 'u';
  1434. $valLen = ReadValue(\$buff, 0, $fmt, 1, $n);
  1435. if ($valLen > 0x7fffffff) {
  1436. $msg = "Can't read $tag (DataLength > 2GB not yet supported)";
  1437. last;
  1438. }
  1439. }
  1440. # all done if we reached the group terminator
  1441. unless ($tagLen) {
  1442. # skip over terminator data block
  1443. $ok = 1 unless $valLen and not $raf->Seek($valLen, 1);
  1444. last;
  1445. }
  1446. # get tag information hash unless this is free space
  1447. my ($tagInfo, $value);
  1448. while ($format != 0x80) {
  1449. $tagInfo = $et->GetTagInfo($tagTablePtr, $tag);
  1450. last if $tagInfo;
  1451. # extract tags with locale code
  1452. if ($tag =~ /\W/) {
  1453. if ($tag =~ /^(\w+)-([a-z]{2}_[A-Z]{2})$/) {
  1454. my ($baseTag, $langCode) = ($1, $2);
  1455. $tagInfo = $et->GetTagInfo($tagTablePtr, $baseTag);
  1456. $tagInfo = GetLangInfo($tagInfo, $langCode) if $tagInfo;
  1457. last if $tagInfo;
  1458. } else {
  1459. $et->Warn('Invalid MIE tag name');
  1460. last;
  1461. }
  1462. }
  1463. # extract unknown tags if specified
  1464. $tagInfo = {
  1465. Name => $tag,
  1466. Writable => 0,
  1467. PrintConv => 'length($val) > 60 ? substr($val,0,55) . "[...]" : $val',
  1468. };
  1469. AddTagToTable($tagTablePtr, $tag, $tagInfo);
  1470. last;
  1471. }
  1472. # read value and uncompress if necessary
  1473. my $formatStr = $mieFormat{$format & 0xfb} || 'undef';
  1474. if ($tagInfo or ($formatStr eq 'MIE' and $format & 0x04)) {
  1475. $raf->Read($value, $valLen) == $valLen or last;
  1476. if ($format & 0x04) {
  1477. if ($verbose) {
  1478. print $out "$$et{INDENT}\[Tag '$tag' $valLen bytes compressed]\n";
  1479. }
  1480. next unless HasZlib($et, 'decode');
  1481. my $stat;
  1482. my $inflate = Compress::Zlib::inflateInit();
  1483. $inflate and ($value, $stat) = $inflate->inflate($value);
  1484. unless ($inflate and $stat == Compress::Zlib::Z_STREAM_END()) {
  1485. $et->Warn("Error inflating $tag");
  1486. next;
  1487. }
  1488. $valLen = length $value;
  1489. $wasCompressed = 1;
  1490. }
  1491. }
  1492. # process this tag
  1493. if ($formatStr eq 'MIE') {
  1494. # process MIE directory
  1495. my ($subTablePtr, $dirName);
  1496. if ($tagInfo and $$tagInfo{SubDirectory}) {
  1497. $dirName = $tagInfo->{SubDirectory}->{DirName};
  1498. my $subTable = $tagInfo->{SubDirectory}->{TagTable};
  1499. $subTablePtr = $subTable ? GetTagTable($subTable) : $tagTablePtr;
  1500. } else {
  1501. $subTablePtr = GetTagTable('Image::ExifTool::MIE::Unknown');
  1502. }
  1503. if ($verbose) {
  1504. my $order = ', byte order ' . GetByteOrder();
  1505. $et->VerboseInfo($tag, $tagInfo, Size => $valLen, Extra => $order);
  1506. }
  1507. my %subdirInfo = (
  1508. DirName => $dirName || $tag,
  1509. RAF => $raf,
  1510. Parent => $$dirInfo{DirName},
  1511. WasCompressed => $wasCompressed,
  1512. );
  1513. # read from uncompressed data instead if necessary
  1514. $subdirInfo{RAF} = new File::RandomAccess(\$value) if $valLen;
  1515. my $oldOrder = GetByteOrder();
  1516. SetByteOrder($format & 0x08 ? 'II' : 'MM');
  1517. $msg = ProcessMIEGroup($et, \%subdirInfo, $subTablePtr);
  1518. SetByteOrder($oldOrder);
  1519. $$et{SET_GROUP1} = $grp1; # restore this group1 name
  1520. last if $msg;
  1521. } else {
  1522. # process MIE data format types
  1523. if ($tagInfo) {
  1524. my $rational;
  1525. # extract tag value
  1526. my $val = ReadMIEValue(\$value, 0, $formatStr, undef, $valLen, \$rational);
  1527. unless (defined $val) {
  1528. $et->Warn("Error reading $tag value");
  1529. $val = '<err>';
  1530. }
  1531. # save type or mime type
  1532. $mime = $val if $tag eq '0Type' or $tag eq '2MIME';
  1533. if ($verbose) {
  1534. my $count;
  1535. my $s = Image::ExifTool::FormatSize($formatStr);
  1536. if ($s and $formatStr !~ /^(utf|string|undef)/) {
  1537. $count = $valLen / $s;
  1538. }
  1539. $et->VerboseInfo($lastTag, $tagInfo,
  1540. DataPt => \$value,
  1541. DataPos => $raf->Tell() - $valLen,
  1542. Size => $valLen,
  1543. Format => $formatStr,
  1544. Value => $val,
  1545. Count => $count,
  1546. );
  1547. }
  1548. if ($$tagInfo{SubDirectory}) {
  1549. my $subTablePtr = GetTagTable($tagInfo->{SubDirectory}->{TagTable});
  1550. my %subdirInfo = (
  1551. DirName => $$tagInfo{Name},
  1552. DataPt => \$value,
  1553. DataLen => $valLen,
  1554. DirStart=> 0,
  1555. DirLen => $valLen,
  1556. Parent => $$dirInfo{DirName},
  1557. WasCompressed => $wasCompressed,
  1558. );
  1559. # set DataPos and Base for uncompressed information only
  1560. unless ($wasCompressed) {
  1561. $subdirInfo{DataPos} = 0; # (relative to Base)
  1562. $subdirInfo{Base} = $raf->Tell() - $valLen;
  1563. }
  1564. # reset PROCESSED lookup for each MIE directory
  1565. # (there is no possibility of double-processing a MIE directory)
  1566. $$et{PROCESSED} = { };
  1567. my $processProc = $tagInfo->{SubDirectory}->{ProcessProc};
  1568. delete $$et{SET_GROUP1};
  1569. delete $$et{NO_LIST};
  1570. $et->ProcessDirectory(\%subdirInfo, $subTablePtr, $processProc);
  1571. $$et{SET_GROUP1} = $grp1;
  1572. $$et{NO_LIST} = 1;
  1573. } else {
  1574. # convert to specified character set if necessary
  1575. if ($notUTF8 and $formatStr =~ /^(utf|string)/) {
  1576. $val = $et->Decode($val, 'UTF8');
  1577. }
  1578. if ($formatStr =~ /_list$/) {
  1579. # split list value into separate strings
  1580. my @vals = split "\0", $val;
  1581. $val = \@vals;
  1582. }
  1583. if (defined $units) {
  1584. $val = "@$val" if ref $val; # convert string list to number list
  1585. # add units to value if specified
  1586. $val .= "($units)" if defined $units;
  1587. }
  1588. my $key = $et->FoundTag($tagInfo, $val);
  1589. $$et{RATIONAL}{$key} = $rational if defined $rational and defined $key;
  1590. }
  1591. } else {
  1592. # skip over unknown information or free bytes
  1593. $raf->Seek($valLen, 1) or $msg = 'Seek error', last;
  1594. $verbose and $et->VerboseInfo($tag, undef, Size => $valLen);
  1595. }
  1596. }
  1597. }
  1598. # modify MIME type if necessary
  1599. $mime and not $$dirInfo{Parent} and $et->ModifyMimeType($mime);
  1600. $ok or $msg or $msg = 'Unexpected end of file';
  1601. $verbose and $$et{INDENT} = $oldIndent;
  1602. return $msg;
  1603. }
  1604. #------------------------------------------------------------------------------
  1605. # Read/write a MIE file
  1606. # Inputs: 0) ExifTool object reference, 1) DirInfo reference
  1607. # Returns: 1 on success, 0 if this wasn't a valid MIE file, or -1 on write error
  1608. # - process as a trailer if "Trailer" flag set in dirInfo
  1609. sub ProcessMIE($$)
  1610. {
  1611. my ($et, $dirInfo) = @_;
  1612. return 1 unless defined $et;
  1613. my $raf = $$dirInfo{RAF};
  1614. my $outfile = $$dirInfo{OutFile};
  1615. my ($buff, $err, $msg, $pos, $end, $isCreating);
  1616. my $numDocs = 0;
  1617. #
  1618. # process as a trailer (from end of file) if specified
  1619. #
  1620. if ($$dirInfo{Trailer}) {
  1621. my $offset = $$dirInfo{Offset} || 0; # offset from end of file
  1622. $raf->Seek(-10 - $offset, 2) or return 0;
  1623. for (;;) {
  1624. # read and validate last 10 bytes
  1625. $raf->Read($buff, 10) == 10 or last;
  1626. last unless $buff =~ /~\0\0\x06.{4}(\x10|\x18)(\x04)$/s or
  1627. $buff =~ /(\x10|\x18)(\x08)$/s;
  1628. SetByteOrder($1 eq "\x10" ? 'MM' : 'II');
  1629. my $len = ($2 eq "\x04") ? Get32u(\$buff, 4) : Get64u(\$buff, 0);
  1630. my $curPos = $raf->Tell() or last;
  1631. last if $len < 12 or $len > $curPos;
  1632. # validate element header if 8-byte offset was used
  1633. if ($2 eq "\x08") {
  1634. last if $len < 14;
  1635. $raf->Seek($curPos - 14, 0) and $raf->Read($buff, 4) or last;
  1636. last unless $buff eq "~\0\0\x0a";
  1637. }
  1638. # looks like a good group, so remember start position
  1639. $pos = $curPos - $len;
  1640. $end = $curPos unless $end;
  1641. # seek to 10 bytes from end of previous group
  1642. $raf->Seek($pos - 10, 0) or last;
  1643. }
  1644. # seek to start of first MIE group
  1645. return 0 unless defined $pos and $raf->Seek($pos, 0);
  1646. # update DataPos and DirLen for ProcessTrailers()
  1647. $$dirInfo{DataPos} = $pos;
  1648. $$dirInfo{DirLen} = $end - $pos;
  1649. if ($outfile and $$et{DEL_GROUP}{MIE}) {
  1650. # delete the trailer
  1651. $et->VPrint(0," Deleting MIE trailer\n");
  1652. ++$$et{CHANGED};
  1653. return 1;
  1654. } elsif ($et->Options('Verbose') or $$et{HTML_DUMP}) {
  1655. $et->DumpTrailer($dirInfo);
  1656. }
  1657. }
  1658. #
  1659. # loop through all documents in MIE file
  1660. #
  1661. for (;;) {
  1662. # look for "0MIE" group element
  1663. my $num = $raf->Read($buff, 8);
  1664. if ($num == 8) {
  1665. # verify file identifier
  1666. if ($buff =~ /^~(\x10|\x18)\x04(.)0MIE/s) {
  1667. SetByteOrder($1 eq "\x10" ? 'MM' : 'II');
  1668. my $len = ord($2);
  1669. # skip extended DataLength if it exists
  1670. if ($len > 252 and not $raf->Seek(1 << (256 - $len), 1)) {
  1671. $msg = 'Seek error';
  1672. last;
  1673. }
  1674. } else {
  1675. return 0 unless $numDocs; # not a MIE file
  1676. if ($buff =~ /^~/) {
  1677. $msg = 'Non-standard file-level MIE element';
  1678. } else {
  1679. $msg = 'Invalid MIE file-level data';
  1680. }
  1681. }
  1682. } elsif ($numDocs) {
  1683. last unless $num; # OK, all done with file
  1684. $msg = 'Truncated MIE element header';
  1685. } else {
  1686. return 0 if $num or not $outfile;
  1687. # we have the ability to create a MIE file from scratch
  1688. $buff = ''; # start from nothing
  1689. # set byte order according to preferences
  1690. $et->SetPreferredByteOrder();
  1691. $isCreating = 1;
  1692. }
  1693. if ($msg) {
  1694. last if $$dirInfo{Trailer}; # allow other trailers after MIE
  1695. if ($outfile) {
  1696. $et->Error($msg);
  1697. } else {
  1698. $et->Warn($msg);
  1699. }
  1700. last;
  1701. }
  1702. # this is a new MIE document -- increment document count
  1703. unless ($numDocs) {
  1704. # this is a valid MIE file (unless a trailer on another file)
  1705. $et->SetFileType();
  1706. $$et{NO_LIST} = 1; # handle lists ourself
  1707. $$et{MIE_COUNT} = { };
  1708. undef $hasZlib;
  1709. }
  1710. ++$numDocs;
  1711. # process the MIE groups recursively, beginning with the main MIE group
  1712. my $tagTablePtr = GetTagTable('Image::ExifTool::MIE::Main');
  1713. my %subdirInfo = (
  1714. DirName => 'MIE',
  1715. RAF => $raf,
  1716. OutFile => $outfile,
  1717. # don't define Parent so WriteMIEGroup() writes extended terminator
  1718. );
  1719. if ($outfile) {
  1720. # generate lookup for MIE format codes if not done already
  1721. unless (%mieCode) {
  1722. foreach (keys %mieFormat) {
  1723. $mieCode{$mieFormat{$_}} = $_;
  1724. }
  1725. }
  1726. # update %mieMap with user-defined MIE groups
  1727. UpdateMieMap() unless $doneMieMap;
  1728. # initialize write directories, with MIE tags taking priority
  1729. # (note that this may re-initialize directories when writing trailer
  1730. # to another type of image, but this is OK because we are done writing
  1731. # the other format by the time we start writing the trailer)
  1732. $et->InitWriteDirs(\%mieMap, 'MIE');
  1733. $subdirInfo{ToWrite} = '~' . MIEGroupFormat(1) . "\x04\xfe0MIE\0\0\0\0";
  1734. $msg = WriteMIEGroup($et, \%subdirInfo, $tagTablePtr);
  1735. if ($msg) {
  1736. $et->Error($msg);
  1737. $err = 1;
  1738. last;
  1739. } elsif (defined $msg and $isCreating) {
  1740. last;
  1741. }
  1742. } else {
  1743. $msg = ProcessMIEGroup($et, \%subdirInfo, $tagTablePtr);
  1744. if ($msg) {
  1745. $et->Warn($msg);
  1746. last;
  1747. }
  1748. }
  1749. }
  1750. delete $$et{NO_LIST};
  1751. delete $$et{MIE_COUNT};
  1752. delete $$et{SET_GROUP1};
  1753. return $err ? -1 : 1;
  1754. }
  1755. 1; # end
  1756. __END__
  1757. =head1 NAME
  1758. Image::ExifTool::MIE - Read/write MIE meta information
  1759. =head1 SYNOPSIS
  1760. This module is used by Image::ExifTool
  1761. =head1 DESCRIPTION
  1762. This module contains routines required by Image::ExifTool to read and write
  1763. information in MIE files.
  1764. =head1 WHAT IS MIE?
  1765. MIE stands for "Meta Information Encapsulation". The MIE format is an
  1766. extensible, dedicated meta information format which supports storage of
  1767. binary as well as textual meta information. MIE can be used to encapsulate
  1768. meta information from many sources and bundle it together with any type of
  1769. file.
  1770. =head2 Features
  1771. Below is very subjective score card comparing the features of a number of
  1772. common file and meta information formats, and comparing them to MIE. The
  1773. following features are rated for each format with a score of 0 to 10:
  1774. 1) Extensible (can incorporate user-defined information).
  1775. 2) Meaningful tag ID's (hint to meaning of unknown information).
  1776. 3) Sequential read/write ability (streamable).
  1777. 4) Hierarchical information structure.
  1778. 5) Easy to implement reader/writer/editor.
  1779. 6) Order of information well defined.
  1780. 7) Large data lengths supported: >64kB (+5) and >4GB (+5).
  1781. 8) Localized text strings.
  1782. 9) Multiple documents in a single file.
  1783. 10) Compact format doesn't squander disk space or bandwidth.
  1784. 11) Compressed meta information supported.
  1785. 12) Relocatable data elements (ie. no fixed offsets).
  1786. 13) Binary meta information (+7) with variable byte order (+3).
  1787. 14) Mandatory tags not required (an unnecessary complication).
  1788. 15) Append information to end of file without editing.
  1789. Feature number Total
  1790. Format 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Score
  1791. ------ --------------------------------------------- -----
  1792. MIE 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 150
  1793. PDF 10 10 0 10 0 0 10 0 10 10 10 0 7 10 10 97
  1794. PNG 10 10 10 0 8 0 5 10 0 10 10 10 0 10 0 93
  1795. XMP 10 10 10 10 2 0 10 10 10 0 0 10 0 10 0 92
  1796. AIFF 0 5 10 10 10 0 5 0 0 10 0 10 7 10 0 77
  1797. RIFF 0 5 10 10 10 0 5 0 0 10 0 10 7 10 0 77
  1798. JPEG 10 0 10 0 10 0 0 0 0 10 0 10 7 10 0 67
  1799. EPS 10 10 10 0 0 0 10 0 10 0 0 5 0 10 0 65
  1800. CIFF 0 0 0 10 10 0 5 0 0 10 0 10 10 10 0 65
  1801. TIFF 0 0 0 10 5 10 5 0 10 10 0 0 10 0 0 60
  1802. EXIF 0 0 0 10 5 10 0 0 0 10 0 0 10 0 0 45
  1803. IPTC 0 0 10 0 8 0 0 0 0 10 0 10 7 0 0 45
  1804. By design, MIE ranks highest by a significant margin. Other formats with
  1805. reasonable scores are PDF, PNG and XMP, but each has significant weak
  1806. points. What may be surprising is that TIFF, EXIF and IPTC rank so low.
  1807. As well as scoring high in all these features, the MIE format has the unique
  1808. ability to encapsulate any other type of file, and provides a non-invasive
  1809. method of adding meta information to a file. The meta information is
  1810. logically separated from the original file data, which is extremely
  1811. important because meta information is routinely lost when files are edited.
  1812. Also, the MIE format supports multiple files by simple concatenation,
  1813. enabling all kinds of wonderful features such as linear databases, edit
  1814. histories or non-intrusive file updates. This ability can also be leveraged
  1815. to allow MIE-format trailers to be added to some other file types.
  1816. =head1 MIE 1.1 FORMAT SPECIFICATION (2007-01-21)
  1817. =head2 File Structure
  1818. A MIE file consists of a series of MIE elements. A MIE element may contain
  1819. either data or a group of MIE elements, providing a hierarchical format for
  1820. storing data. Each MIE element is identified by a human-readable tag name,
  1821. and may store data from zero to 2^64-1 bytes in length.
  1822. =head2 File Signature
  1823. The first element in the MIE file must be an uncompressed MIE group element
  1824. with a tag name of "0MIE". This restriction allows the first 8 bytes of a
  1825. MIE file to be used to identify a MIE format file. The following table
  1826. lists the two possible initial byte sequences for a MIE-format file (the
  1827. first for big-endian, and the second for little-endian byte ordering):
  1828. Byte Number: 0 1 2 3 4 5 6 7
  1829. C Characters: ~ \x10 \x04 ? 0 M I E
  1830. or ~ \x18 \x04 ? 0 M I E
  1831. Hexadecimal: 7e 10 04 ? 30 4d 49 45
  1832. or 7e 18 04 ? 30 4d 49 45
  1833. Decimal: 126 16 4 ? 48 77 73 69
  1834. or 126 24 4 ? 48 77 73 69
  1835. Note that byte 1 may have one of the two possible values (0x10 or 0x18), and
  1836. byte 3 may have any value (0x00 to 0xff).
  1837. =head2 Element Structure
  1838. 1 byte SyncByte = 0x7e (decimal 126, character '~')
  1839. 1 byte FormatCode (see below)
  1840. 1 byte TagLength (T)
  1841. 1 byte DataLength (gives D if DataLength < 253)
  1842. T bytes TagName (T given by TagLength)
  1843. 2 bytes DataLength2 [exists only if DataLength == 255 (0xff)]
  1844. 4 bytes DataLength4 [exists only if DataLength == 254 (0xfe)]
  1845. 8 bytes DataLength8 [exists only if DataLength == 253 (0xfd)]
  1846. D bytes DataBlock (D given by DataLength)
  1847. The minimum element length is 4 bytes (for a group terminator). The maximum
  1848. DataBlock size is 2^64-1 bytes. TagLength and DataLength are unsigned
  1849. integers, and the byte ordering for multi-byte DataLength fields is
  1850. specified by the containing MIE group element. The SyncByte is byte
  1851. aligned, so no padding is added to align on an N-byte boundary.
  1852. =head3 FormatCode
  1853. The format code is a bitmask that defines the format of the data:
  1854. 7654 3210
  1855. ++++ ---- FormatType
  1856. ---- +--- TypeModifier
  1857. ---- -+-- Compressed
  1858. ---- --++ FormatSize
  1859. =over 4
  1860. =item FormatType (bitmask 0xf0):
  1861. 0x00 - other (or unknown) data
  1862. 0x10 - MIE group
  1863. 0x20 - text string
  1864. 0x30 - list of null-separated text strings
  1865. 0x40 - integer
  1866. 0x50 - rational
  1867. 0x60 - fixed point
  1868. 0x70 - floating point
  1869. 0x80 - free space
  1870. =item TypeModifier (bitmask 0x08):
  1871. Modifies the meaning of certain FormatTypes (0x00-0x60):
  1872. 0x08 - other data sensitive to MIE group byte order
  1873. 0x18 - MIE group with little-endian byte ordering
  1874. 0x28 - UTF encoded text string
  1875. 0x38 - UTF encoded text string list
  1876. 0x48 - signed integer
  1877. 0x58 - signed rational (denominator is always unsigned)
  1878. 0x68 - signed fixed-point
  1879. =item Compressed (bitmask 0x04):
  1880. If this bit is set, the data block is compressed using Zlib deflate. An
  1881. entire MIE group may be compressed, with the exception of file-level groups.
  1882. =item FormatSize (bitmask 0x03):
  1883. Gives the byte size of each data element:
  1884. 0x00 - 8 bits (1 byte)
  1885. 0x01 - 16 bits (2 bytes)
  1886. 0x02 - 32 bits (4 bytes)
  1887. 0x03 - 64 bits (8 bytes)
  1888. The number of bytes in a single value for this format is given by
  1889. 2**FormatSize (or 1 << FormatSize). The number of values is the data length
  1890. divided by this number of bytes. It is an error if the data length is not
  1891. an even multiple of the format size in bytes.
  1892. =back
  1893. The following is a list of all currently defined MIE FormatCode values for
  1894. uncompressed data (add 0x04 to each value for compressed data):
  1895. 0x00 - other data (insensitive to MIE group byte order) (1)
  1896. 0x01 - other 16-bit data (may be byte swapped)
  1897. 0x02 - other 32-bit data (may be byte swapped)
  1898. 0x03 - other 64-bit data (may be byte swapped)
  1899. 0x08 - other data (sensitive to MIE group byte order) (1)
  1900. 0x10 - MIE group with big-endian values (1)
  1901. 0x18 - MIE group with little-endian values (1)
  1902. 0x20 - ASCII (ISO 8859-1) string (2,3)
  1903. 0x28 - UTF-8 string (2,3,4)
  1904. 0x29 - UTF-16 string (2,3,4)
  1905. 0x2a - UTF-32 string (2,3,4)
  1906. 0x30 - ASCII (ISO 8859-1) string list (3,5)
  1907. 0x38 - UTF-8 string list (3,4,5)
  1908. 0x39 - UTF-16 string list (3,4,5)
  1909. 0x3a - UTF-32 string list (3,4,5)
  1910. 0x40 - unsigned 8-bit integer
  1911. 0x41 - unsigned 16-bit integer
  1912. 0x42 - unsigned 32-bit integer
  1913. 0x43 - unsigned 64-bit integer (6)
  1914. 0x48 - signed 8-bit integer
  1915. 0x49 - signed 16-bit integer
  1916. 0x4a - signed 32-bit integer
  1917. 0x4b - signed 64-bit integer (6)
  1918. 0x52 - unsigned 32-bit rational (16-bit numerator then denominator) (7)
  1919. 0x53 - unsigned 64-bit rational (32-bit numerator then denominator) (7)
  1920. 0x5a - signed 32-bit rational (denominator is unsigned) (7)
  1921. 0x5b - signed 64-bit rational (denominator is unsigned) (7)
  1922. 0x61 - unsigned 16-bit fixed-point (high 8 bits is integer part) (8)
  1923. 0x62 - unsigned 32-bit fixed-point (high 16 bits is integer part) (8)
  1924. 0x69 - signed 16-bit fixed-point (high 8 bits is signed integer) (8)
  1925. 0x6a - signed 32-bit fixed-point (high 16 bits is signed integer) (8)
  1926. 0x72 - 32-bit IEEE float (not recommended for portability reasons)
  1927. 0x73 - 64-bit IEEE double (not recommended for portability reasons) (6)
  1928. 0x80 - free space (value data does not contain useful information)
  1929. Notes:
  1930. =over 4
  1931. =item 1.
  1932. The byte ordering specified by the MIE group TypeModifier applies to the MIE
  1933. group element as well as all elements within the group. Data for all
  1934. FormatCodes except 0x08 (other data, sensitive to byte order) may be
  1935. transferred between MIE groups with different byte order by byte swapping
  1936. the uncompressed data according to the specified data format. The following
  1937. list illustrates the byte-swapping pattern, based on FormatSize, for all
  1938. format types except rational (FormatType 0x50).
  1939. FormatSize Change in Byte Sequence
  1940. -------------- -----------------------------------
  1941. 0x00 (8 bits) 0 1 2 3 4 5 6 7 --> 0 1 2 3 4 5 6 7 (no change)
  1942. 0x01 (16 bits) 0 1 2 3 4 5 6 7 --> 1 0 3 2 5 4 7 6
  1943. 0x02 (32 bits) 0 1 2 3 4 5 6 7 --> 3 2 1 0 7 6 5 4
  1944. 0x03 (64 bits) 0 1 2 3 4 5 6 7 --> 7 6 5 4 3 2 1 0
  1945. Rational values consist of two integers, so they are swapped as the next
  1946. lower FormatSize. For example, a 32-bit rational (FormatSize 0x02, and
  1947. FormatCode 0x52 or 0x5a) is swapped as two 16-bit values (ie. as if it had
  1948. FormatSize 0x01).
  1949. =item 2.
  1950. The TagName of a string element may have an 6-character suffix to indicate a
  1951. specific locale. (eg. "Title-en_US", or "Keywords-de_DE").
  1952. =item 3.
  1953. Text strings are not normally null terminated, however they may be padded
  1954. with one or more null characters to the end of the data block to allow
  1955. strings to be edited within fixed-length data blocks. Newlines in the text
  1956. are indicated by a single LF (0x0a) character.
  1957. =item 4.
  1958. UTF strings must not begin with a byte order mark (BOM) since the byte order
  1959. and byte size are specified by the MIE format. If a BOM is found, it should
  1960. be treated as a zero-width non-breaking space.
  1961. =item 5.
  1962. A list of text strings separated by null characters. These lists must not
  1963. be null padded or null terminated, since this would be interpreted as
  1964. additional zero-length strings. For ASCII and UTF-8 strings, the null
  1965. character is a single zero (0x00) byte. For UTF-16 or UTF-32 strings, the
  1966. null character is 2 or 4 zero bytes respectively.
  1967. =item 6.
  1968. 64-bit integers and doubles are subject to the specified byte ordering for
  1969. both 32-bit words and bytes within these words. For instance, the high
  1970. order byte is always the first byte if big-endian, and the eighth byte if
  1971. little-endian. This means that some swapping is always necessary for these
  1972. values on systems where the byte order differs from the word order (eg. some
  1973. ARM systems), regardless of the endian-ness of the stored values.
  1974. =item 7.
  1975. Rational values are treated as two separate integers. The numerator always
  1976. comes first regardless of the byte ordering. In a signed rational value,
  1977. only the numerator is signed. The denominator of all rational values is
  1978. unsigned (eg. a signed 64-bit rational of 0x80000000/0x80000000 evaluates to
  1979. -1, not +1).
  1980. =item 8.
  1981. 32-bit fixed point values are converted to floating point by treating them
  1982. as an integer and dividing by an appropriate value. eg)
  1983. 16-bit fixed value = 16-bit integer value / 256.0
  1984. 32-bit fixed value = 32-bit integer value / 65536.0
  1985. =back
  1986. =head3 TagLength
  1987. Gives the length of the TagName string. Any value between 0 and 255 is
  1988. valid, but the TagLength of 0 is valid only for the MIE group terminator.
  1989. =head3 DataLength
  1990. DataLength is an unsigned byte that gives the number of bytes in the data
  1991. block. A value between 0 and 252 gives the data length directly, and
  1992. numbers from 253 to 255 are reserved for extended DataLength codes. Codes
  1993. of 255, 254 and 253 indicate that the element contains an additional 2, 4 or
  1994. 8 byte unsigned integer representing the data length.
  1995. 0-252 - length of data block
  1996. 255 (0xff) - use DataLength2
  1997. 254 (0xfe) - use DataLength4
  1998. 253 (0xfd) - use DataLength8
  1999. A DataLength of zero is valid for any element except a compressed MIE group.
  2000. A zero DataLength for an uncompressed MIE group indicates that the group
  2001. length is unknown. For other elements, a zero length indicates there is no
  2002. associated data. A terminator element must have a DataLength of 0, 6 or 10,
  2003. and may not use an extended DataLength.
  2004. =head3 TagName
  2005. The TagName string is 0 to 255 bytes long, and is composed of the ASCII
  2006. characters A-Z, a-z, 0-9 and underline ('_'). Also, a dash ('-') is used to
  2007. separate the language/country code in the TagName of a localized text
  2008. string, and a units string (possibly containing other ASCII characters) may
  2009. be appear in brackets at the end of the TagName. The TagName string is NOT
  2010. null terminated. A MIE element with a tag string of zero length is reserved
  2011. for the group terminator.
  2012. MIE elements are sorted alphabetically by TagName within each group.
  2013. Multiple elements with the same TagName are allowed, even within the same
  2014. group.
  2015. TagNames should be meaningful. Case is significant. Words should be
  2016. lowercase with an uppercase first character, and acronyms should be all
  2017. upper case. The underline ("_") is provided to allow separation of two
  2018. acronyms or two numbers, but it shouldn't be used unless necessary. No
  2019. separation is necessary between an acronym and a word (eg. "ISOSetting").
  2020. All TagNames should start with an uppercase letter. An exception to this
  2021. rule allows tags to begin with a digit (0-9) if they must come before other
  2022. tags in the sort order, or a lowercase letter (a-z) if they must come after.
  2023. For instance, the '0Type' element begins with a digit so it comes before,
  2024. and the 'data' element begins with a lowercase letter so that it comes after
  2025. meta information tags in the main "0MIE" group.
  2026. Tag names for localized text strings have an 6-character suffix with the
  2027. following format: The first character is a dash ('-'), followed by a
  2028. 2-character lower case ISO 639-1 language code, then an underline ('_'), and
  2029. ending with a 2-character upper case ISO 3166-1 alpha 2 country code. (eg.
  2030. "-en_US", "-en_GB", "-de_DE" or "-fr_FR". Note that "GB", and not "UK" is
  2031. the code for Great Britain, although "UK" should be recognized for
  2032. compatibility reasons.) The suffix is included when sorting the tags
  2033. alphabetically, so the default locale (with no tag-name suffix) always comes
  2034. first. If the country is unknown or not applicable, a country code of "XX"
  2035. should be used.
  2036. Tags with numerical values may allow units of measurement to be specified.
  2037. The units string is stored in brackets at the end of the tag name, and is
  2038. composed of zero or more ASCII characters in the range 0x21 to 0x7d,
  2039. excluding the bracket characters 0x28 and 0x29. (eg. "Resolution(/cm)" or
  2040. "SpecificHeat(J/kg.K)".) See L<Image::ExifTool::MIEUnits> for details. Unit
  2041. strings are not localized, and may not be used in combination with localized
  2042. text strings.
  2043. Sets of tags which would require a common prefix should be added in a
  2044. separate MIE group instead of adding the prefix to all tag names. For
  2045. example, instead of these TagName's:
  2046. ExternalFlashType
  2047. ExternalFlashSerialNumber
  2048. ExternalFlashFired
  2049. one would instead designate a separate "ExternalFlash" MIE group to contain
  2050. the following elements:
  2051. Type
  2052. SerialNumber
  2053. Fired
  2054. =head3 DataLength2/4/8
  2055. These extended DataLength fields exist only if DataLength is 255, 254 or
  2056. 253, and are respectively 2, 4 or 8 byte unsigned integers giving the data
  2057. block length. One of these values must be used if the data block is larger
  2058. than 252 bytes, but they may be used if desired for smaller blocks too
  2059. (although this may add a few unnecessary bytes to the MIE element).
  2060. =head3 DataBlock
  2061. The data value for the MIE element. The format of the data is given by the
  2062. FormatCode. For MIE group elements, the data includes all contained
  2063. elements and the group terminator.
  2064. =head2 MIE groups
  2065. All MIE data elements must be contained within a group. A group begins with
  2066. a MIE group element, and ends with a group terminator. Groups may be nested
  2067. in a hierarchy to arbitrary depth.
  2068. A MIE group element is identified by a format code of 0x10 (big endian byte
  2069. ordering) or 0x18 (little endian). The group terminator is distinguished by
  2070. a zero TagLength (it is the only element allowed to have a zero TagLength),
  2071. and has a FormatCode of 0x00.
  2072. The MIE group element is permitted to have a zero DataLength only if the
  2073. data is uncompressed. This special value indicates that the group length is
  2074. unknown (otherwise the minimum value for DataLength is 4, corresponding the
  2075. the minimum group size which includes a terminator of at least 4 bytes). If
  2076. DataLength is zero, all elements in the group must be parsed until the group
  2077. terminator is found. If non-zero, DataLength includes the length of all
  2078. elements contained within the group, including the group terminator. Use of
  2079. a non-zero DataLength is encouraged because it allows readers quickly skip
  2080. over entire MIE groups. For compressed groups DataLength must be non-zero,
  2081. and is the length of the compressed group data (which includes the
  2082. compressed group terminator).
  2083. =head3 Group Terminator
  2084. The group terminator has a FormatCode and TagLength of zero. The terminator
  2085. DataLength must be 0, 6 or 10 bytes, and extended DataLength codes may not
  2086. be used. With a zero DataLength, the byte sequence for a terminator is "7e
  2087. 00 00 00" (hex). With a DataLength of 6 or 10 bytes, the terminator data
  2088. block contains information about the length and byte ordering of the
  2089. preceding group. This additional information is recommended for file-level
  2090. groups, and is used in multi-document MIE files and MIE trailers to allow
  2091. the file to be scanned backwards from the end. (This may also allow some
  2092. documents to be recovered if part of the file is corrupted.) The structure
  2093. of this optional terminator data block is as follows:
  2094. 4 or 8 bytes GroupLength (unsigned integer)
  2095. 1 byte ByteOrder (0x10 or 0x18, same as MIE group)
  2096. 1 byte GroupLengthSize (0x04 or 0x08)
  2097. The ByteOrder and GroupLengthSize values give the byte ordering and size of
  2098. the GroupLength integer. The GroupLength value is the total length of the
  2099. entire MIE group ending with this terminator, including the opening MIE
  2100. group element and the terminator itself.
  2101. =head3 File-level MIE groups
  2102. File-level MIE groups may NOT be compressed.
  2103. All elements in a MIE file are contained within a special group with a
  2104. TagName of "0MIE". The purpose of the "OMIE" group is to provide a unique
  2105. signature at the start of the file, and to encapsulate information allowing
  2106. files to be easily combined. The "0MIE" group must be terminated like any
  2107. other group, but it is recommended that the terminator of a file-level group
  2108. include the optional data block (defined above) to provide information about
  2109. the group length and byte order.
  2110. It is valid to have more than one "0MIE" group at the file level, allowing
  2111. multiple documents in a single MIE file. Furthermore, the MIE structure
  2112. enables multi-document files to be generated by simply concatenating two or
  2113. more MIE files.
  2114. =head2 Scanning Backwards through a MIE File
  2115. The steps below give an algorithm to quickly locate the last document in a
  2116. MIE file:
  2117. =over 4
  2118. =item 1.
  2119. Read the last 10 bytes of the file. (Note that a valid MIE file may be as
  2120. short as 12 bytes long, but a file this length contains only an an empty MIE
  2121. group.)
  2122. =item 2.
  2123. If the last byte of the file is zero, then it is not possible to scan
  2124. backward through the file, so the file must be scanned from the beginning.
  2125. Otherwise, proceed to the next step.
  2126. =item 3.
  2127. If the last byte is 4 or 8, the terminator contains information about the
  2128. byte ordering and length of the group. Otherwise, stop here because this
  2129. isn't a valid MIE file.
  2130. =item 4.
  2131. The next-to-last byte must be either 0x10 indicating big-endian byte
  2132. ordering or 0x18 for little-endian ordering, otherwise this isn't a valid
  2133. MIE file.
  2134. =item 5.
  2135. The value of the preceding 4 or 8 bytes gives the length of the complete
  2136. file-level MIE group (GroupLength). This length includes both the leading
  2137. MIE group element and the terminator element itself. The value is an
  2138. unsigned integer with a byte length given in step 3), and a byte order from
  2139. step 4). From the current file position (at the end of the data read in
  2140. step 1), seek backward by this number of bytes to find the start of the MIE
  2141. group element for this document.
  2142. =back
  2143. This algorithm may be repeated again beginning at this point in the file to
  2144. locate the next-to-last document, etc.
  2145. The table below lists all 5 valid patterns for the last 14 bytes of a
  2146. file-level MIE group, with all numbers in hex. The comments indicate the
  2147. length and byte ordering of GroupLength (xx) if available:
  2148. ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? 7e 00 00 00 - (no GroupLength)
  2149. ?? ?? ?? ?? 7e 00 00 06 xx xx xx xx 10 04 - 4 bytes, big endian
  2150. ?? ?? ?? ?? 7e 00 00 06 xx xx xx xx 18 04 - 4 bytes, little endian
  2151. 7e 00 00 0a xx xx xx xx xx xx xx xx 10 08 - 8 bytes, big endian
  2152. 7e 00 00 0a xx xx xx xx xx xx xx xx 18 08 - 8 bytes, little endian
  2153. =head2 Trailer Signature
  2154. The MIE format may be used for trailer information appended to other types
  2155. of files. When this is done, a signature must appear at the end of the main
  2156. MIE group to uniquely identify the MIE format trailer. To achieve this, a
  2157. "zmie" trailer signature is written as the last element in the main "0MIE"
  2158. group. This element has a FormatCode of 0, a TagLength of 4, a DataLength
  2159. of 0, and a TagName of "zmie". With this signature, the hex byte sequence
  2160. "7e 00 04 00 7a 6d 69 65" appears immediately before the final group
  2161. terminator, and the last 22 bytes of the trailer correspond to one of the
  2162. following 4 patterns (where the trailer length is given by "xx", as above):
  2163. ?? ?? ?? ?? 7e 00 04 00 7a 6d 69 65 7e 00 00 06 xx xx xx xx 10 04
  2164. ?? ?? ?? ?? 7e 00 04 00 7a 6d 69 65 7e 00 00 06 xx xx xx xx 18 04
  2165. 7e 00 04 00 7a 6d 69 65 7e 00 00 0a xx xx xx xx xx xx xx xx 10 08
  2166. 7e 00 04 00 7a 6d 69 65 7e 00 00 0a xx xx xx xx xx xx xx xx 18 08
  2167. Note that the zero-DataLength terminator may not be used here because the
  2168. trailer length must be known for seeking backwards from the end of the file.
  2169. Multiple trailers may be appended to the same file using this technique.
  2170. =head2 MIE Data Values
  2171. MIE data values for a given tag are usually not restricted to a specific
  2172. FormatCode. Any value may be represented in any appropriate format,
  2173. including numbers represented in string (ASCII or UTF) form.
  2174. It is preferred that closely related values with the same format are written
  2175. to a single tag instead of using multiple tags. This improves localization
  2176. of like values and decreases MIE element overhead. For instance, instead of
  2177. separate ImageWidth and ImageHeight tags, a single ImageSize tag is defined.
  2178. Tags which may take on a discrete set of values should have meaningful
  2179. values if possible. This improves the extensibility of the format and
  2180. allows a more reasonable interpretation of unrecognized values.
  2181. =head3 Numerical Representation
  2182. Integer and floating point numbers may be represented in binary or string
  2183. form. In string form, integers are a series of digits with an optional
  2184. leading sign (eg. "[+|-]DDDDDD"), and multiple values are separated by a
  2185. single space character (eg. "23 128 -32"). Floating point numbers are
  2186. similar but may also contain a decimal point and/or a signed exponent with a
  2187. leading 'e' character (eg. "[+|-]DD[.DDDDDD][e(+|-)EEE]"). The string "inf"
  2188. is used to represent infinity. One advantage of numerical strings is that
  2189. they can have an arbitrarily high precision because the possible number of
  2190. significant digits is virtually unlimited.
  2191. Note that numerical values may have associated units of measurement which
  2192. are specified in the L</TagName> string.
  2193. =head3 Date/Time Format
  2194. All MIE dates are strings in the form "YYYY:mm:dd HH:MM:SS.ss+HH:MM". The
  2195. fractional seconds (".ss") are optional, and if included may contain any
  2196. number of significant digits (unlike all other fields which are a fixed
  2197. number of digits and must be padded with leading zeros if necessary). The
  2198. timezone ("+HH:MM" or "-HH:MM") is recommended but not required. If not
  2199. given, the local system timezone is assumed.
  2200. =head2 MIME Type
  2201. The basic MIME type for a MIE file is "application/x-mie", however the
  2202. specific MIME type depends on the type of subfile, and is obtained by adding
  2203. "x-mie-" to the MIME type of the subfile. For example, with a subfile of
  2204. type "image/jpeg", the MIE file MIME type is "image/x-mie-jpeg". But note
  2205. that the "x-" is not duplicated if the subfile MIME type already starts with
  2206. "x-". So a subfile with MIME type "image/x-raw" is contained within a MIE
  2207. file of type "image/x-mie-raw", not "image/x-mie-x-raw". In the case of
  2208. multiple documents in a MIE file, the MIME type is taken from the first
  2209. document. Regardless of the subfile type, all MIE-format files should have
  2210. a filename extension of ".MIE".
  2211. =head2 Levels of Support
  2212. Basic MIE reader/writer applications may choose not to provide support for
  2213. some advanced features of the MIE format. Features which may not be
  2214. supported by all software are:
  2215. =over 4
  2216. =item Compression
  2217. Software not supporting compression must ignore compressed elements and
  2218. groups, but should be able to process the remaining information.
  2219. =item Large data lengths
  2220. Some software may limit the maximum size of a MIE group or element.
  2221. Historically, a limit of 2GB may be imposed by some systems. However,
  2222. 8-byte data lengths should be supported by all applications provided the
  2223. value doesn't exceed the system limit. (eg. For systems with a 2GB limit,
  2224. 8-byte data lengths should be supported if the upper 17 bits are all zero.)
  2225. If a data length above the system limit is encountered, it may be necessary
  2226. for the application to stop processing if it can not seek to the next
  2227. element in the file.
  2228. =back
  2229. =head1 EXAMPLES
  2230. This section gives examples for working with MIE information using ExifTool.
  2231. =head2 Encapsulating Information with Data in a MIE File
  2232. The following command encapsulates any file recognized by ExifTool inside a
  2233. MIE file, and initializes MIE tags from information within the file:
  2234. exiftool -o new.mie -tagsfromfile FILE '-mie:all<all' \
  2235. '-subfilename<filename' '-subfiletype<filetype' \
  2236. '-subfilemimetype<mimetype' '-subfiledata<=FILE'
  2237. where C<FILE> is the name of the file.
  2238. For unrecognized files, this command may be used:
  2239. exiftool -o new.mie -subfilename=FILE -subfiletype=TYPE \
  2240. -subfilemimetype=MIME '-subfiledata<=FILE'
  2241. where C<TYPE> and C<MIME> represent the source file type and MIME type
  2242. respectively.
  2243. =head2 Adding a MIE Trailer to a File
  2244. The MIE format may also be used to store information in a trailer appended
  2245. to another type of file. Beware that trailers may not be compatible with
  2246. all file formats, but JPEG and TIFF are two formats where additional trailer
  2247. information doesn't create any problems for normal parsing of the file.
  2248. Also note that this technique has the disadvantage that trailer information
  2249. is commonly lost if the file is subsequently edited by other software.
  2250. Creating a MIE trailer with ExifTool is a two-step process since ExifTool
  2251. can't currently be used to add a MIE trailer directly. The example below
  2252. illustrates the steps for adding a MIE trailer with a small preview image
  2253. (C<small.jpg>) to a destination JPEG image (C<dst.jpg>).
  2254. Step 1) Create a MIE file with a TrailerSignature containing the desired
  2255. information:
  2256. exiftool -o new.mie -trailersignature=1 -tagsfromfile small.jpg \
  2257. '-previewimagetype<filetype' '-previewimagesize<imagesize' \
  2258. '-previewimagename<filename' '-previewimage<=small.jpg'
  2259. Step 2) Append the MIE information to another file. In Unix, this can be
  2260. done with the 'cat' command:
  2261. cat new.mie >> dst.jpg
  2262. Once added, ExifTool may be used to edit or delete a MIE trailer in a JPEG
  2263. or TIFF image.
  2264. =head2 Multiple MIE Documents in a Single File
  2265. The MIE specification allows multiple MIE documents (or trailers) to exist
  2266. in a single file. A file like this may be created by simply concatenating
  2267. MIE documents. ExifTool may be used to access information in a specific
  2268. document by adding a copy number to the MIE group name. For example:
  2269. # write the Author tag in the second MIE document
  2270. exiftool -mie2:author=phil test.mie
  2271. # delete the first MIE document from a file
  2272. exiftool -mie1:all= test.mie
  2273. =head2 Units of Measurement
  2274. Some MIE tags allow values to be specified in different units of
  2275. measurement. In the MIE file format these units are combined with the tag
  2276. name, but when using ExifTool they are specified in brackets after the
  2277. value:
  2278. exiftool -mie:gpsaltitude='7500(ft)' test.mie
  2279. If no units are provided, the default units are written.
  2280. =head2 Localized Text
  2281. Localized text values are accessed by adding a language/country code to the
  2282. tag name. For example:
  2283. exiftool -comment-en_us='this is a comment' test.mie
  2284. =head1 REVISIONS
  2285. 2010-04-05 - Fixed "Format Size" Note 7 to give the correct number of bits
  2286. in the example rational value
  2287. 2007-01-21 - Specified LF character (0x0a) for text newline sequence
  2288. 2007-01-19 - Specified ISO 8859-1 character set for extended ASCII codes
  2289. 2007-01-01 - Improved wording of Step 5 for scanning backwards in MIE file
  2290. 2006-12-30 - Added EXAMPLES section and note about UTF BOM
  2291. 2006-12-20 - MIE 1.1: Changed meaning of TypeModifier bit (0x08) for
  2292. unknown data (FormatType 0x00), and documented byte swapping
  2293. 2006-12-14 - MIE 1.0: Added Data Values and Numerical Representations
  2294. sections, and added ability to specify units in tag names
  2295. 2006-11-09 - Added Levels of Support section
  2296. 2006-11-03 - Added Trailer Signature
  2297. 2005-11-18 - Original specification created
  2298. =head1 AUTHOR
  2299. Copyright 2003-2016, Phil Harvey (phil at owl.phy.queensu.ca)
  2300. This library is free software; you can redistribute it and/or modify it
  2301. under the same terms as Perl itself. The MIE format itself is also
  2302. copyright Phil Harvey, and is covered by the same free-use license.
  2303. =head1 REFERENCES
  2304. =over 4
  2305. =item L<http://owl.phy.queensu.ca/~phil/exiftool/MIE1.1-20070121.pdf>
  2306. =back
  2307. =head1 SEE ALSO
  2308. L<Image::ExifTool::TagNames/MIE Tags>, L<Image::ExifTool::MIEUnits>,
  2309. L<Image::ExifTool(3pm)|Image::ExifTool>
  2310. =cut