-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathencode.go
More file actions
92 lines (77 loc) · 1.94 KB
/
encode.go
File metadata and controls
92 lines (77 loc) · 1.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package turbojpeg
/*
#cgo CFLAGS: -I${SRCDIR}/include -I/usr/local/include -I/usr/include -I/opt/libjpeg-turbo/include
#cgo LDFLAGS: -L${SRCDIR}/lib -L/usr/local/lib -L/usr/lib -L/opt/libjpeg-turbo/lib64 -L/opt/libjpeg-turbo/lib -lturbojpeg -lm -ldl
#include <stdint.h>
#include <stdlib.h>
#include "encode.h"
*/
import "C"
import (
"image"
"io"
"runtime"
"sync/atomic"
"unsafe"
"github.com/octu0/cgobytepool"
"github.com/pkg/errors"
)
type Encoder struct {
pool cgobytepool.Pool
handle unsafe.Pointer // tjhandle
closed int32
}
func (e *Encoder) EncodeRGBA(out io.Writer, img *image.RGBA, quality int) (int, error) {
ctx := cgobytepool.CgoHandle(e.pool)
width, height := img.Rect.Dx(), img.Rect.Dy()
r := unsafe.Pointer(C.encode_jpeg(
unsafe.Pointer(&ctx),
(C.tjhandle)(e.handle),
(*C.uchar)(unsafe.Pointer(&img.Pix[0])),
C.int(width),
C.int(height),
C.int(img.Stride),
C.int(PixelFormatRGBA),
C.int(Subsampling420),
C.int(quality),
))
if r == nil {
ctx.Delete()
return 0, errors.Errorf("failed to call tjCompress2()")
}
result := (*C.jpeg_encode_result_t)(r)
defer func() {
defer ctx.Delete()
C.free_jpeg_encode_result(unsafe.Pointer(&ctx), result)
}()
return out.Write(cgobytepool.GoBytes(unsafe.Pointer(result.data), int(result.data_size)))
}
func (e *Encoder) Close() {
if atomic.CompareAndSwapInt32(&e.closed, 0, 1) {
runtime.SetFinalizer(e, nil)
C.tjDestroy((C.tjhandle)(e.handle))
}
}
func finalizeEncoder(e *Encoder) {
e.Close()
}
func CreateEncoder() (*Encoder, error) {
e, err := CreateEncoderWithPool(defaultCgoBytePool)
if err != nil {
return nil, errors.WithStack(err)
}
return e, nil
}
func CreateEncoderWithPool(p cgobytepool.Pool) (*Encoder, error) {
h := unsafe.Pointer(C.tjInitCompress())
if h == nil {
return nil, errors.Errorf("failed to call tjInitCompress()")
}
e := &Encoder{
pool: p,
handle: h,
closed: 0,
}
runtime.SetFinalizer(e, finalizeEncoder)
return e, nil
}