image.codec\meta\xmp_meta.mbt

93.9% · 170 / 181 points · 350 lines

Background color reports the state of each line. Underlined characters mark exact instrumented byte offsets; hover them to inspect the visit count.

  1. 1///|
  2. 2/// # XMP 元数据 meta/xmp_meta
  3. 3///
  4. 4/// 编解码工具模块
  5. 5/// 编解码工具模块 Codec utility module
  6. 6// v249.0.0 XMP 元数据解析与写入
  7. 7// XMP 基于 XML,嵌入在 JPEG APP1 段中(以 "http://ns.adobe.com/xap/1.0/\0" 开头)
  8. 8// 纯 MoonBit 实现,无外部 XML 库依赖
  9. 9
  10. 10///|
  11. 11/// XMP 元数据(常用字段)
  12. 12#derive(Eq, Default, @debug.Debug)
  13. 13pub(all) struct XmpInfo {
  14. 14 creator : String
  15. 15 title : String
  16. 16 description : String
  17. 17 subject : String
  18. 18 keywords : String
  19. 19 rights : String
  20. 20 create_date : String
  21. 21 modify_date : String
  22. 22 software : String
  23. 23 rating : Int32
  24. 24 raw_xml : String
  25. 25}
  26. 26
  27. 27///|
  28. 28pub extend XmpInfo with Eq::{not_equal, equal}
  29. 29
  30. 30///|
  31. 31pub extend XmpInfo with Default::{default}
  32. 32
  33. 33///|
  34. 34pub extend XmpInfo with @debug.Debug::{to_repr}
  35. 35
  36. 36///|
  37. 37/// XMP 命名空间 URI XMP namespace URI
  38. 38fn xmp_namespace_uri() -> String {
  39. 39● "http://ns.adobe.com/xap/1.0/"
  40. 40}
  41. 41
  42. 42///|
  43. 43/// 从字节中提取 ASCII 字符串(到 \0 或指定长度)
  44. 44fn xmp_extract_string(data : Bytes, start : Int32, max_len : Int32) -> String {
  45. 45● let chars : Array[Byte] = []
  46. 46● let len = data.length()
  47. 47 for i in 0..<max_len {
  48. 48● if start + i >= len {
  49. 49○ break
  50. 50 }
  51. 51 let b = data[start + i]
  52. 52 if b == b'\x00' {
  53. 53● break
  54. 54 }
  55. 55● chars.push(b)
  56. 56 }
  57. 57● @encoding/utf8.decode(Bytes::from_array(chars)[:]) catch {
  58. 58● _ => ""
  59. 59 }
  60. 60}
  61. 61
  62. 62///|
  63. 63/// 在字符串中查找子串,返回起始位置或 -1
  64. 64fn xmp_str_find(haystack : String, needle : String) -> Int32 {
  65. 65● let h = haystack.to_array()
  66. 66● let n = needle.to_array()
  67. 67● let hlen = h.length()
  68. 68● let nlen = n.length()
  69. 69 if nlen == 0 {
  70. 70○ return 0
  71. 71 }
  72. 72 if nlen > hlen {
  73. 73● return -1
  74. 74 }
  75. 75 let end = hlen - nlen
  76. 76 for i in 0..<=end {
  77. 77● let mut found = true
  78. 78 for j in 0..<nlen {
  79. 79● if h[i + j] != n[j] {
  80. 80● found = false
  81. 81 break
  82. 82 }
  83. 83 }
  84. 84 if found {
  85. 85● return i
  86. 86 }
  87. 87 }
  88. 88 -1
  89. 89}
  90. 90
  91. 91///|
  92. 92/// 在 XML 中提取标签内容(简单解析,非完整 XML 解析器)
  93. 93fn xmp_extract_tag(xml : String, tag : String) -> String {
  94. 94● let open_tag = "<" + tag + ">"
  95. 95 let close_tag = "</" + tag + ">"
  96. 96● let open_idx = xmp_str_find(xml, open_tag)
  97. 97 if open_idx < 0 {
  98. 98● return ""
  99. 99 }
  100. 100● let content_start = open_idx + open_tag.length()
  101. 101● let close_idx = xmp_str_find(xml[content_start:].to_owned(), close_tag)
  102. 102 if close_idx < 0 {
  103. 103○ return ""
  104. 104 }
  105. 105● xml[content_start:content_start + close_idx].to_owned()
  106. 106}
  107. 107
  108. 108///|
  109. 109/// 在 XML 中提取属性值
  110. 110fn xmp_extract_attr(xml : String, tag : String, attr : String) -> String {
  111. 111● let search = tag + " " + attr + "=\""
  112. 112● let idx = xmp_str_find(xml, search)
  113. 113 if idx < 0 {
  114. 114● return ""
  115. 115 }
  116. 116○ let val_start = idx + search.length()
  117. 117○ let rest = xml[val_start:].to_owned()
  118. 118○ let end = xmp_str_find(rest, "\"")
  119. 119 if end < 0 {
  120. 120○ return ""
  121. 121 }
  122. 122○ rest[:end].to_owned()
  123. 123}
  124. 124
  125. 125///|
  126. 126/// 简单整数解析(支持正负号)
  127. 127fn xmp_parse_int(s : String) -> Int32? {
  128. 128● if s.length() == 0 {
  129. 129● return None
  130. 130 }
  131. 131● let chars = s.to_array()
  132. 132 let mut idx = 0
  133. 133 let mut neg = false
  134. 134● if chars[0].to_int() == 0x2D {
  135. 135● neg = true
  136. 136 idx = 1
  137. 137● } else if chars[0].to_int() == 0x2B {
  138. 138● idx = 1
  139. 139 }
  140. 140● if idx >= chars.length() {
  141. 141○ return None
  142. 142 }
  143. 143 let mut result = 0
  144. 144● while idx < chars.length() {
  145. 145● let c = chars[idx].to_int()
  146. 146 if c < 0x30 || c > 0x39 {
  147. 147● return None
  148. 148 }
  149. 149 result = result * 10 + (c - 0x30)
  150. 150 idx += 1
  151. 151 }
  152. 152 if neg {
  153. 153● Some(-result)
  154. 154 } else {
  155. 155● Some(result)
  156. 156 }
  157. 157}
  158. 158
  159. 159///|
  160. 160/// 从 JPEG 字节流读取 XMP 元数据
  161. 161/// 返回 None 如果不含 XMP 数据
  162. 162pub fn read_xmp_from_bytes(data : Bytes) -> XmpInfo? {
  163. 163● let len = data.length()
  164. 164● if len < 4 || data[0].to_int() != 0xFF || data[1].to_int() != 0xD8 {
  165. 165● return None
  166. 166 }
  167. 167 // 查找 APP1 marker with XMP namespace
  168. 168 let mut pos = 2
  169. 169 let mut xmp_start = -1
  170. 170 let mut xmp_len = 0
  171. 171 while pos < len - 1 {
  172. 172● if data[pos].to_int() == 0xFF && data[pos + 1].to_int() == 0xE1 {
  173. 173● let seg_len = data[pos + 2].to_int() * 256 + data[pos + 3].to_int() - 2
  174. 174 let ns_start = pos + 4
  175. 175● let ns = xmp_extract_string(data, ns_start, 29)
  176. 176● if ns == xmp_namespace_uri() {
  177. 177● xmp_start = ns_start + 29
  178. 178 xmp_len = seg_len - 29
  179. 179 break
  180. 180 }
  181. 181 pos += 2 + seg_len + 2
  182. 182● } else if data[pos].to_int() == 0xFF {
  183. 183● let marker = data[pos + 1].to_int()
  184. 184 if marker == 0xDA || marker == 0xD9 {
  185. 185● break
  186. 186 }
  187. 187● let seg_len = data[pos + 2].to_int() * 256 + data[pos + 3].to_int()
  188. 188 pos += 2 + seg_len
  189. 189 } else {
  190. 190● pos += 1
  191. 191 }
  192. 192 }
  193. 193 if xmp_start < 0 || xmp_start + xmp_len > len {
  194. 194● return None
  195. 195 }
  196. 196● let xml = xmp_extract_string(data, xmp_start, xmp_len)
  197. 197● let creator = xmp_extract_tag(xml, "dc:creator")
  198. 198● let title = xmp_extract_tag(xml, "dc:title")
  199. 199● let description = xmp_extract_tag(xml, "dc:description")
  200. 200● let subject = xmp_extract_tag(xml, "dc:subject")
  201. 201● let keywords = xmp_extract_tag(xml, "lr:hierarchicalSubject")
  202. 202● let rights = xmp_extract_tag(xml, "dc:rights")
  203. 203● let create_date = xmp_extract_attr(xml, "xmp:CreateDate", "xmp:CreateDate")
  204. 204● let modify_date = xmp_extract_attr(xml, "xmp:ModifyDate", "xmp:ModifyDate")
  205. 205● let software = xmp_extract_tag(xml, "xmp:CreatorTool")
  206. 206● let rating_str = xmp_extract_tag(xml, "xmp:Rating")
  207. 207● let rating = match xmp_parse_int(rating_str) {
  208. 208● Some(n) => n
  209. 209● None => 0
  210. 210 }
  211. 211 Some(XmpInfo::{
  212. 212 creator,
  213. 213 title,
  214. 214 description,
  215. 215 subject,
  216. 216 keywords,
  217. 217 rights,
  218. 218 create_date,
  219. 219 modify_date,
  220. 220 software,
  221. 221 rating,
  222. 222 raw_xml: xml,
  223. 223 })
  224. 224}
  225. 225
  226. 226///|
  227. 227/// 构造 XMP APP1 段数据(不含 FF E1 前缀和长度)
  228. 228pub fn create_xmp_segment(info : XmpInfo) -> Bytes {
  229. 229● let ns = xmp_namespace_uri()
  230. 230 let xml_parts : Array[String] = []
  231. 231● xml_parts.push("<?xpacket begin='' id='W5M0MpCehiHzreSzNTczkc9d'?>")
  232. 232● xml_parts.push("<x:xmpmeta xmlns:x='adobe:ns:meta/'>")
  233. 233● xml_parts.push(
  234. 234 "<rdf:RDF xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'>",
  235. 235 )
  236. 236● xml_parts.push("<rdf:Description rdf:about=''")
  237. 237● if info.creator.length() > 0 {
  238. 238● xml_parts.push(" xmlns:dc='http://purl.org/dc/elements/1.1/'")
  239. 239 }
  240. 240● if info.software.length() > 0 {
  241. 241● xml_parts.push(" xmlns:xmp='http://ns.adobe.com/xap/1.0/'>")
  242. 242 } else {
  243. 243● xml_parts.push(">")
  244. 244 }
  245. 245● if info.title.length() > 0 {
  246. 246● xml_parts.push("<dc:title>" + info.title + "</dc:title>")
  247. 247 }
  248. 248● if info.creator.length() > 0 {
  249. 249● xml_parts.push("<dc:creator>" + info.creator + "</dc:creator>")
  250. 250 }
  251. 251● if info.description.length() > 0 {
  252. 252● xml_parts.push("<dc:description>" + info.description + "</dc:description>")
  253. 253 }
  254. 254● if info.rights.length() > 0 {
  255. 255● xml_parts.push("<dc:rights>" + info.rights + "</dc:rights>")
  256. 256 }
  257. 257● if info.software.length() > 0 {
  258. 258● xml_parts.push("<xmp:CreatorTool>" + info.software + "</xmp:CreatorTool>")
  259. 259 }
  260. 260 if info.rating > 0 {
  261. 261● xml_parts.push("<xmp:Rating>" + info.rating.to_string() + "</xmp:Rating>")
  262. 262 }
  263. 263● xml_parts.push("</rdf:Description>")
  264. 264● xml_parts.push("</rdf:RDF>")
  265. 265● xml_parts.push("</x:xmpmeta>")
  266. 266● xml_parts.push("<?xpacket end='w'?>")
  267. 267 let mut xml = ""
  268. 268 for part in xml_parts {
  269. 269● xml = xml + part
  270. 270 }
  271. 271 let out : Array[Byte] = []
  272. 272● for c in ns.to_array() {
  273. 273● let code = c.to_int()
  274. 274 if code < 128 {
  275. 275● out.push(code.to_byte())
  276. 276 } else {
  277. 277○ out.push(b'?')
  278. 278 }
  279. 279 }
  280. 280● out.push(b'\x00')
  281. 281● for c in xml.to_array() {
  282. 282● let code = c.to_int()
  283. 283 if code < 128 {
  284. 284● out.push(code.to_byte())
  285. 285 } else {
  286. 286● out.push(b'?')
  287. 287 }
  288. 288 }
  289. 289● Bytes::from_array(out)
  290. 290}
  291. 291
  292. 292///|
  293. 293/// 将 XMP 写入 JPEG(在 SOI 后插入 APP1,已有则替换)
  294. 294pub fn write_xmp_to_bytes(
  295. 295 info : XmpInfo,
  296. 296 jpeg_data : Bytes,
  297. 297) -> Bytes raise @types.LoadError {
  298. 298● let len = jpeg_data.length()
  299. 299● if len < 4 || jpeg_data[0].to_int() != 0xFF || jpeg_data[1].to_int() != 0xD8 {
  300. 300● raise @types.LoadError::EncodeFailed("输入不是有效 JPEG")
  301. 301 }
  302. 302● let xmp_payload = create_xmp_segment(info)
  303. 303● let xmp_seg_len = xmp_payload.length() + 2
  304. 304 let xmp_seg : Array[Byte] = [
  305. 305 0xFF,
  306. 306 0xE1,
  307. 307● (xmp_seg_len >> 8).to_byte(),
  308. 308● (xmp_seg_len & 0xFF).to_byte(),
  309. 309 ]
  310. 310 for b in xmp_payload {
  311. 311● xmp_seg.push(b)
  312. 312 }
  313. 313 // 查找并跳过已有 XMP APP1
  314. 314 let mut pos = 2
  315. 315 let mut insert_pos = 2
  316. 316 while pos < len - 1 {
  317. 317● if jpeg_data[pos].to_int() == 0xFF && jpeg_data[pos + 1].to_int() == 0xE1 {
  318. 318● let seg_len = jpeg_data[pos + 2].to_int() * 256 +
  319. 319● jpeg_data[pos + 3].to_int()
  320. 320● let ns = xmp_extract_string(jpeg_data, pos + 4, 29)
  321. 321● if ns == xmp_namespace_uri() {
  322. 322● insert_pos = pos
  323. 323 break
  324. 324 }
  325. 325 pos += 2 + seg_len
  326. 326● } else if jpeg_data[pos].to_int() == 0xFF {
  327. 327● let marker = jpeg_data[pos + 1].to_int()
  328. 328 if marker == 0xDA || marker == 0xD9 {
  329. 329● insert_pos = pos
  330. 330 break
  331. 331 }
  332. 332● let seg_len = jpeg_data[pos + 2].to_int() * 256 +
  333. 333● jpeg_data[pos + 3].to_int()
  334. 334 pos += 2 + seg_len
  335. 335 } else {
  336. 336● pos += 1
  337. 337 }
  338. 338 }
  339. 339 let out : Array[Byte] = []
  340. 340 for i in 0..<insert_pos {
  341. 341● out.push(jpeg_data[i])
  342. 342 }
  343. 343 for b in xmp_seg {
  344. 344● out.push(b)
  345. 345 }
  346. 346 for i in insert_pos..<len {
  347. 347● out.push(jpeg_data[i])
  348. 348 }
  349. 349● Bytes::from_array(out)
  350. 350}