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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
|
#include <qpdf/Pl_PNGFilter.hh>
#include <stdexcept>
#include <string.h>
DLL_EXPORT
Pl_PNGFilter::Pl_PNGFilter(char const* identifier, Pipeline* next,
action_e action, unsigned int columns,
unsigned int bytes_per_pixel) :
Pipeline(identifier, next),
action(action),
columns(columns),
cur_row(0),
prev_row(0),
buf1(0),
buf2(0),
pos(0)
{
this->buf1 = new unsigned char[columns + 1];
this->buf2 = new unsigned char[columns + 1];
this->cur_row = buf1;
// number of bytes per incoming row
this->incoming = (action == a_encode ? columns : columns + 1);
}
DLL_EXPORT
Pl_PNGFilter::~Pl_PNGFilter()
{
delete [] buf1;
delete [] buf2;
}
DLL_EXPORT
void
Pl_PNGFilter::write(unsigned char* data, int len)
{
int left = this->incoming - this->pos;
unsigned int offset = 0;
while (len >= left)
{
// finish off current row
memcpy(this->cur_row + this->pos, data + offset, left);
offset += left;
len -= left;
processRow();
// Swap rows
unsigned char* t = this->prev_row;
this->prev_row = this->cur_row;
this->cur_row = t ? t : this->buf2;
memset(this->cur_row, 0, this->columns + 1);
left = this->incoming;
this->pos = 0;
}
if (len)
{
memcpy(this->cur_row + this->pos, data + offset, len);
}
this->pos += len;
}
void
Pl_PNGFilter::processRow()
{
if (this->action == a_encode)
{
encodeRow();
}
else
{
decodeRow();
}
}
void
Pl_PNGFilter::decodeRow()
{
int filter = (int) this->cur_row[0];
if (this->prev_row)
{
switch (filter)
{
case 0: // none
break;
case 1: // sub
throw std::logic_error("sub filter not implemented");
break;
case 2: // up
for (unsigned int i = 1; i <= this->columns; ++i)
{
this->cur_row[i] += this->prev_row[i];
}
break;
case 3: // average
throw std::logic_error("average filter not implemented");
break;
case 4: // Paeth
throw std::logic_error("Paeth filter not implemented");
break;
default:
// ignore
break;
}
}
getNext()->write(this->cur_row + 1, this->columns);
}
void
Pl_PNGFilter::encodeRow()
{
// For now, hard-code to using UP filter.
unsigned char ch = 2;
getNext()->write(&ch, 1);
if (this->prev_row)
{
for (unsigned int i = 0; i < this->columns; ++i)
{
ch = this->cur_row[i] - this->prev_row[i];
getNext()->write(&ch, 1);
}
}
else
{
getNext()->write(this->cur_row, this->columns);
}
}
DLL_EXPORT
void
Pl_PNGFilter::finish()
{
if (this->pos)
{
// write partial row
processRow();
}
this->prev_row = 0;
this->cur_row = buf1;
this->pos = 0;
memset(this->cur_row, 0, this->columns + 1);
getNext()->finish();
}
|