function.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  1. package pdfrender
  2. import (
  3. "math"
  4. )
  5. /*
  6. function.go
  7. PDF functions (ISO 32000 7.10): sampled (type 0), exponential (type 2),
  8. stitching (type 3) and PostScript calculator (type 4). They drive tint
  9. transforms of Separation / DeviceN colours and the colour of shadings.
  10. */
  11. type pdfFunction interface {
  12. eval(in []float64) []float64
  13. }
  14. type funcBase struct {
  15. domain []float64
  16. rng []float64
  17. }
  18. func clamp(v, lo, hi float64) float64 {
  19. if v < lo {
  20. return lo
  21. }
  22. if v > hi {
  23. return hi
  24. }
  25. if math.IsNaN(v) {
  26. return lo
  27. }
  28. return v
  29. }
  30. func (f *funcBase) clipIn(in []float64) []float64 {
  31. out := make([]float64, len(in))
  32. for i, v := range in {
  33. if 2*i+1 < len(f.domain) {
  34. v = clamp(v, f.domain[2*i], f.domain[2*i+1])
  35. }
  36. out[i] = v
  37. }
  38. return out
  39. }
  40. func (f *funcBase) clipOut(out []float64) []float64 {
  41. for i := range out {
  42. if 2*i+1 < len(f.rng) {
  43. out[i] = clamp(out[i], f.rng[2*i], f.rng[2*i+1])
  44. }
  45. }
  46. return out
  47. }
  48. // loadFunction parses a function object, or an array of 1 output functions
  49. // combined into one
  50. func (d *Document) loadFunction(o Object, depth int) pdfFunction {
  51. if depth > 8 {
  52. return nil
  53. }
  54. o = d.resolve(o)
  55. if arr, ok := o.(Array); ok {
  56. var fs []pdfFunction
  57. for _, e := range arr {
  58. f := d.loadFunction(e, depth+1)
  59. if f == nil {
  60. return nil
  61. }
  62. fs = append(fs, f)
  63. }
  64. if len(fs) == 0 {
  65. return nil
  66. }
  67. return &funcArray{fs: fs}
  68. }
  69. dict := d.dict(o)
  70. if dict == nil {
  71. return nil
  72. }
  73. base := funcBase{domain: d.numbers(dict["Domain"]), rng: d.numbers(dict["Range"])}
  74. switch d.integer(dict["FunctionType"], -1) {
  75. case 0:
  76. s := d.stream(o)
  77. if s == nil {
  78. return nil
  79. }
  80. return d.loadSampled(s, base)
  81. case 2:
  82. f := &funcExp{funcBase: base, c0: d.numbers(dict["C0"]), c1: d.numbers(dict["C1"]), n: d.num(dict["N"], 1)}
  83. if len(f.c0) == 0 {
  84. f.c0 = []float64{0}
  85. }
  86. if len(f.c1) == 0 {
  87. f.c1 = []float64{1}
  88. }
  89. return f
  90. case 3:
  91. f := &funcStitch{funcBase: base, bounds: d.numbers(dict["Bounds"]), encode: d.numbers(dict["Encode"])}
  92. for _, e := range d.array(dict["Functions"]) {
  93. sub := d.loadFunction(e, depth+1)
  94. if sub == nil {
  95. return nil
  96. }
  97. f.fs = append(f.fs, sub)
  98. }
  99. if len(f.fs) == 0 || len(f.bounds) != len(f.fs)-1 {
  100. return nil
  101. }
  102. return f
  103. case 4:
  104. s := d.stream(o)
  105. if s == nil {
  106. return nil
  107. }
  108. data, err := d.decodeStream(s, 1<<20)
  109. if err != nil {
  110. return nil
  111. }
  112. prog := parsePostScript(data)
  113. if prog == nil {
  114. return nil
  115. }
  116. return &funcPS{funcBase: base, prog: prog}
  117. }
  118. return nil
  119. }
  120. type funcArray struct {
  121. fs []pdfFunction
  122. }
  123. func (f *funcArray) eval(in []float64) []float64 {
  124. out := make([]float64, 0, len(f.fs))
  125. for _, sub := range f.fs {
  126. r := sub.eval(in)
  127. if len(r) > 0 {
  128. out = append(out, r[0])
  129. } else {
  130. out = append(out, 0)
  131. }
  132. }
  133. return out
  134. }
  135. type funcExp struct {
  136. funcBase
  137. c0, c1 []float64
  138. n float64
  139. }
  140. func (f *funcExp) eval(in []float64) []float64 {
  141. x := 0.0
  142. if len(in) > 0 {
  143. x = f.clipIn(in[:1])[0]
  144. }
  145. n := len(f.c0)
  146. if len(f.c1) < n {
  147. n = len(f.c1)
  148. }
  149. out := make([]float64, n)
  150. xn := math.Pow(x, f.n)
  151. if math.IsNaN(xn) || math.IsInf(xn, 0) {
  152. xn = 0
  153. }
  154. for i := 0; i < n; i++ {
  155. out[i] = f.c0[i] + xn*(f.c1[i]-f.c0[i])
  156. }
  157. return f.clipOut(out)
  158. }
  159. type funcStitch struct {
  160. funcBase
  161. fs []pdfFunction
  162. bounds []float64
  163. encode []float64
  164. }
  165. func (f *funcStitch) eval(in []float64) []float64 {
  166. x := 0.0
  167. if len(in) > 0 {
  168. x = f.clipIn(in[:1])[0]
  169. }
  170. lo, hi := 0.0, 1.0
  171. if len(f.domain) >= 2 {
  172. lo, hi = f.domain[0], f.domain[1]
  173. }
  174. k := 0
  175. for k < len(f.bounds) && x >= f.bounds[k] {
  176. k++
  177. }
  178. b0, b1 := lo, hi
  179. if k > 0 {
  180. b0 = f.bounds[k-1]
  181. }
  182. if k < len(f.bounds) {
  183. b1 = f.bounds[k]
  184. }
  185. e0, e1 := 0.0, 1.0
  186. if 2*k+1 < len(f.encode) {
  187. e0, e1 = f.encode[2*k], f.encode[2*k+1]
  188. }
  189. t := e0
  190. if b1 != b0 {
  191. t = e0 + (x-b0)*(e1-e0)/(b1-b0)
  192. }
  193. return f.clipOut(f.fs[k].eval([]float64{t}))
  194. }
  195. type funcSampled struct {
  196. funcBase
  197. size []int
  198. bps int
  199. encode []float64
  200. decode []float64
  201. samples []float64 //Normalised to 0..1
  202. nOut int
  203. }
  204. func (d *Document) loadSampled(s *Stream, base funcBase) pdfFunction {
  205. dict := s.Dict
  206. sizes := d.numbers(dict["Size"])
  207. m := len(base.domain) / 2
  208. n := len(base.rng) / 2
  209. if m < 1 || m > 4 || n < 1 || n > 32 || len(sizes) < m {
  210. return nil
  211. }
  212. f := &funcSampled{funcBase: base, bps: d.integer(dict["BitsPerSample"], 8), nOut: n}
  213. total := int64(n)
  214. for i := 0; i < m; i++ {
  215. sz := int(sizes[i])
  216. if sz < 1 || sz > 1<<16 {
  217. return nil
  218. }
  219. f.size = append(f.size, sz)
  220. total *= int64(sz)
  221. if total > 1<<22 {
  222. return nil
  223. }
  224. }
  225. switch f.bps {
  226. case 1, 2, 4, 8, 12, 16, 24, 32:
  227. default:
  228. return nil
  229. }
  230. f.encode = d.numbers(dict["Encode"])
  231. if len(f.encode) < 2*m {
  232. f.encode = nil
  233. for i := 0; i < m; i++ {
  234. f.encode = append(f.encode, 0, float64(f.size[i]-1))
  235. }
  236. }
  237. f.decode = d.numbers(dict["Decode"])
  238. if len(f.decode) < 2*n {
  239. f.decode = base.rng
  240. }
  241. data, err := d.decodeStream(s, 64<<20)
  242. if err != nil {
  243. return nil
  244. }
  245. maxV := math.Pow(2, float64(f.bps)) - 1
  246. f.samples = make([]float64, total)
  247. br := bitReader{data: data}
  248. for i := range f.samples {
  249. v, ok := br.read(f.bps)
  250. if !ok {
  251. break
  252. }
  253. f.samples[i] = float64(v) / maxV
  254. }
  255. return f
  256. }
  257. func (f *funcSampled) eval(in []float64) []float64 {
  258. m := len(f.size)
  259. x := make([]float64, m)
  260. for i := 0; i < m; i++ {
  261. v := 0.0
  262. if i < len(in) {
  263. v = in[i]
  264. }
  265. d0, d1 := f.domain[2*i], f.domain[2*i+1]
  266. v = clamp(v, math.Min(d0, d1), math.Max(d0, d1))
  267. e := f.encode[2*i]
  268. if d1 != d0 {
  269. e = f.encode[2*i] + (v-d0)*(f.encode[2*i+1]-f.encode[2*i])/(d1-d0)
  270. }
  271. x[i] = clamp(e, 0, float64(f.size[i]-1))
  272. }
  273. out := make([]float64, f.nOut)
  274. //Multilinear interpolation over the 2^m corners
  275. corners := 1 << m
  276. for c := 0; c < corners; c++ {
  277. w := 1.0
  278. idx := 0
  279. stride := 1
  280. for i := 0; i < m; i++ {
  281. lo := math.Floor(x[i])
  282. frac := x[i] - lo
  283. pos := int(lo)
  284. if c&(1<<i) != 0 {
  285. if pos+1 < f.size[i] {
  286. pos++
  287. }
  288. w *= frac
  289. } else {
  290. w *= 1 - frac
  291. }
  292. idx += pos * stride
  293. stride *= f.size[i]
  294. }
  295. if w == 0 {
  296. continue
  297. }
  298. for j := 0; j < f.nOut; j++ {
  299. k := idx*f.nOut + j
  300. if k < len(f.samples) {
  301. out[j] += w * f.samples[k]
  302. }
  303. }
  304. }
  305. for j := range out {
  306. if 2*j+1 < len(f.decode) {
  307. out[j] = f.decode[2*j] + out[j]*(f.decode[2*j+1]-f.decode[2*j])
  308. }
  309. }
  310. return f.clipOut(out)
  311. }
  312. type bitReader struct {
  313. data []byte
  314. pos int //bit position
  315. }
  316. func (b *bitReader) read(n int) (uint32, bool) {
  317. var v uint32
  318. for i := 0; i < n; i++ {
  319. byteIdx := b.pos >> 3
  320. if byteIdx >= len(b.data) {
  321. return v, false
  322. }
  323. bit := (b.data[byteIdx] >> (7 - uint(b.pos&7))) & 1
  324. v = v<<1 | uint32(bit)
  325. b.pos++
  326. }
  327. return v, true
  328. }
  329. func (b *bitReader) alignByte() {
  330. b.pos = (b.pos + 7) &^ 7
  331. }
  332. /*
  333. PostScript calculator functions
  334. */
  335. type psOp struct {
  336. op string
  337. num float64
  338. ifT []psOp
  339. ifF []psOp
  340. isNum bool
  341. }
  342. type funcPS struct {
  343. funcBase
  344. prog []psOp
  345. }
  346. func parsePostScript(data []byte) []psOp {
  347. l := &lexer{buf: data}
  348. t := l.next()
  349. if t.kind != tokBraceOpen {
  350. return nil
  351. }
  352. prog, ok := parsePSBlock(l, 0)
  353. if !ok {
  354. return nil
  355. }
  356. return prog
  357. }
  358. func parsePSBlock(l *lexer, depth int) ([]psOp, bool) {
  359. if depth > 32 {
  360. return nil, false
  361. }
  362. var ops []psOp
  363. var pending [][]psOp
  364. for {
  365. t := l.next()
  366. switch t.kind {
  367. case tokEOF:
  368. return nil, false
  369. case tokBraceClose:
  370. return ops, true
  371. case tokBraceOpen:
  372. blk, ok := parsePSBlock(l, depth+1)
  373. if !ok {
  374. return nil, false
  375. }
  376. pending = append(pending, blk)
  377. case tokInt:
  378. ops = append(ops, psOp{isNum: true, num: float64(t.i)})
  379. case tokReal:
  380. ops = append(ops, psOp{isNum: true, num: t.f})
  381. case tokKeyword:
  382. switch t.s {
  383. case "if":
  384. if len(pending) < 1 {
  385. return nil, false
  386. }
  387. ops = append(ops, psOp{op: "if", ifT: pending[len(pending)-1]})
  388. pending = pending[:len(pending)-1]
  389. case "ifelse":
  390. if len(pending) < 2 {
  391. return nil, false
  392. }
  393. ops = append(ops, psOp{op: "ifelse", ifT: pending[len(pending)-2], ifF: pending[len(pending)-1]})
  394. pending = pending[:len(pending)-2]
  395. default:
  396. ops = append(ops, psOp{op: t.s})
  397. }
  398. }
  399. }
  400. }
  401. func (f *funcPS) eval(in []float64) []float64 {
  402. st := &psStack{}
  403. for _, v := range f.clipIn(in) {
  404. st.push(v)
  405. }
  406. steps := 0
  407. st.run(f.prog, &steps)
  408. n := len(f.rng) / 2
  409. out := make([]float64, n)
  410. for i := n - 1; i >= 0; i-- {
  411. out[i] = st.pop()
  412. }
  413. return f.clipOut(out)
  414. }
  415. type psStack struct {
  416. v []float64
  417. }
  418. func (s *psStack) push(x float64) {
  419. if len(s.v) < 100 {
  420. s.v = append(s.v, x)
  421. }
  422. }
  423. func (s *psStack) pop() float64 {
  424. if len(s.v) == 0 {
  425. return 0
  426. }
  427. x := s.v[len(s.v)-1]
  428. s.v = s.v[:len(s.v)-1]
  429. return x
  430. }
  431. func boolNum(b bool) float64 {
  432. if b {
  433. return 1
  434. }
  435. return 0
  436. }
  437. func (s *psStack) run(prog []psOp, steps *int) {
  438. for _, op := range prog {
  439. *steps++
  440. if *steps > 10000 {
  441. return
  442. }
  443. if op.isNum {
  444. s.push(op.num)
  445. continue
  446. }
  447. switch op.op {
  448. case "add":
  449. b, a := s.pop(), s.pop()
  450. s.push(a + b)
  451. case "sub":
  452. b, a := s.pop(), s.pop()
  453. s.push(a - b)
  454. case "mul":
  455. b, a := s.pop(), s.pop()
  456. s.push(a * b)
  457. case "div":
  458. b, a := s.pop(), s.pop()
  459. if b == 0 {
  460. s.push(0)
  461. } else {
  462. s.push(a / b)
  463. }
  464. case "idiv":
  465. b, a := int64(s.pop()), int64(s.pop())
  466. if b == 0 {
  467. s.push(0)
  468. } else {
  469. s.push(float64(a / b))
  470. }
  471. case "mod":
  472. b, a := int64(s.pop()), int64(s.pop())
  473. if b == 0 {
  474. s.push(0)
  475. } else {
  476. s.push(float64(a % b))
  477. }
  478. case "neg":
  479. s.push(-s.pop())
  480. case "abs":
  481. s.push(math.Abs(s.pop()))
  482. case "ceiling":
  483. s.push(math.Ceil(s.pop()))
  484. case "floor":
  485. s.push(math.Floor(s.pop()))
  486. case "round":
  487. s.push(math.Floor(s.pop() + 0.5))
  488. case "truncate", "cvi":
  489. s.push(math.Trunc(s.pop()))
  490. case "cvr":
  491. case "sqrt":
  492. s.push(math.Sqrt(math.Max(0, s.pop())))
  493. case "sin":
  494. s.push(math.Sin(s.pop() * math.Pi / 180))
  495. case "cos":
  496. s.push(math.Cos(s.pop() * math.Pi / 180))
  497. case "atan":
  498. den, num := s.pop(), s.pop()
  499. a := math.Atan2(num, den) * 180 / math.Pi
  500. if a < 0 {
  501. a += 360
  502. }
  503. s.push(a)
  504. case "exp":
  505. e, b := s.pop(), s.pop()
  506. s.push(math.Pow(b, e))
  507. case "ln":
  508. s.push(math.Log(math.Max(1e-30, s.pop())))
  509. case "log":
  510. s.push(math.Log10(math.Max(1e-30, s.pop())))
  511. case "eq":
  512. b, a := s.pop(), s.pop()
  513. s.push(boolNum(a == b))
  514. case "ne":
  515. b, a := s.pop(), s.pop()
  516. s.push(boolNum(a != b))
  517. case "gt":
  518. b, a := s.pop(), s.pop()
  519. s.push(boolNum(a > b))
  520. case "ge":
  521. b, a := s.pop(), s.pop()
  522. s.push(boolNum(a >= b))
  523. case "lt":
  524. b, a := s.pop(), s.pop()
  525. s.push(boolNum(a < b))
  526. case "le":
  527. b, a := s.pop(), s.pop()
  528. s.push(boolNum(a <= b))
  529. case "and":
  530. b, a := int64(s.pop()), int64(s.pop())
  531. s.push(float64(a & b))
  532. case "or":
  533. b, a := int64(s.pop()), int64(s.pop())
  534. s.push(float64(a | b))
  535. case "xor":
  536. b, a := int64(s.pop()), int64(s.pop())
  537. s.push(float64(a ^ b))
  538. case "not":
  539. a := s.pop()
  540. if a == 0 || a == 1 {
  541. s.push(1 - a)
  542. } else {
  543. s.push(float64(^int64(a)))
  544. }
  545. case "bitshift":
  546. sh, a := int64(s.pop()), int64(s.pop())
  547. if sh > 0 && sh < 63 {
  548. s.push(float64(a << uint(sh)))
  549. } else if sh < 0 && sh > -63 {
  550. s.push(float64(a >> uint(-sh)))
  551. } else {
  552. s.push(float64(a))
  553. }
  554. case "true":
  555. s.push(1)
  556. case "false":
  557. s.push(0)
  558. case "pop":
  559. s.pop()
  560. case "dup":
  561. a := s.pop()
  562. s.push(a)
  563. s.push(a)
  564. case "exch":
  565. b, a := s.pop(), s.pop()
  566. s.push(b)
  567. s.push(a)
  568. case "copy":
  569. n := int(s.pop())
  570. if n > 0 && n <= len(s.v) {
  571. s.v = append(s.v, s.v[len(s.v)-n:]...)
  572. if len(s.v) > 100 {
  573. s.v = s.v[:100]
  574. }
  575. }
  576. case "index":
  577. n := int(s.pop())
  578. if n >= 0 && n < len(s.v) {
  579. s.push(s.v[len(s.v)-1-n])
  580. } else {
  581. s.push(0)
  582. }
  583. case "roll":
  584. j, n := int(s.pop()), int(s.pop())
  585. if n > 0 && n <= len(s.v) {
  586. part := s.v[len(s.v)-n:]
  587. j = ((j % n) + n) % n
  588. tmp := append(append([]float64{}, part[n-j:]...), part[:n-j]...)
  589. copy(part, tmp)
  590. }
  591. case "if":
  592. if s.pop() != 0 {
  593. s.run(op.ifT, steps)
  594. }
  595. case "ifelse":
  596. if s.pop() != 0 {
  597. s.run(op.ifT, steps)
  598. } else {
  599. s.run(op.ifF, steps)
  600. }
  601. }
  602. }
  603. }