|
| 1 | +VERSION 1.0 CLASS |
| 2 | +BEGIN |
| 3 | + MultiUse = -1 'True |
| 4 | + Persistable = 0 'NotPersistable |
| 5 | + DataBindingBehavior = 0 'vbNone |
| 6 | + DataSourceBehavior = 0 'vbNone |
| 7 | + MTSTransactionMode = 0 'NotAnMTSObject |
| 8 | +END |
| 9 | +Attribute VB_Name = "pdWBMP" |
| 10 | +Attribute VB_GlobalNameSpace = False |
| 11 | +Attribute VB_Creatable = True |
| 12 | +Attribute VB_PredeclaredId = False |
| 13 | +Attribute VB_Exposed = False |
| 14 | +'*************************************************************************** |
| 15 | +'PhotoDemon Wireless Application Protocol Bitmap (WBMP) Decoder |
| 16 | +'Copyright 2024-2024 by Tanner Helland |
| 17 | +'Created: 19/March/24 |
| 18 | +'Last updated: 19/March/24 |
| 19 | +'Last update: initial build, heavily derived from PD's just-written XBM parser |
| 20 | +' |
| 21 | +'The WBMP file format has been around since the late 90s. You can find a copy of the latest spec revision |
| 22 | +' here: https://www.wapforum.org/what/technical/SPEC-WAESpec-19990524.pdf |
| 23 | +' |
| 24 | +'PhotoDemon originally handed WBMP support off to the 3rd-party FreeImage library, but ongoing issues with |
| 25 | +' FreeImage reliability eventually prompted me to write my own WBMP decoder. (This was done shortly after |
| 26 | +' writing a similar decoder for the XBM format, which is another ancient monochrome-only image format; |
| 27 | +' this decoder is based roughly on the code for that one.) |
| 28 | +' |
| 29 | +'PD's WBMP decoder is small and lightweight, covering all known variants of the format. Encoding support |
| 30 | +' is *not* planned at present, but this may be revisited (as always) if users complain. |
| 31 | +' |
| 32 | +'Unless otherwise noted, all source code in this file is shared under a simplified BSD license. |
| 33 | +' Full license details are available in the LICENSE.md file, or at https://photodemon.org/license/ |
| 34 | +' |
| 35 | +'*************************************************************************** |
| 36 | + |
| 37 | +Option Explicit |
| 38 | + |
| 39 | +'To aid debugging, you can activate "verbose" output; this dumps additional diagnostic information |
| 40 | +' to PD's primary debug log. |
| 41 | +Private Const WBMP_DEBUG_VERBOSE As Boolean = True |
| 42 | + |
| 43 | +'Image width/height, in pixels, after a file has been validated. |
| 44 | +' (Calling "IsFileWBMP" is enough to populate these.) |
| 45 | +Private m_Width As Long, m_Height As Long |
| 46 | + |
| 47 | +'Byte-by-byte access is provided, as always, by a pdStream instance. |
| 48 | +Private m_Stream As pdStream |
| 49 | + |
| 50 | +'The last filename loaded. The contents of the filename will be stored in m_FileAsString, below. |
| 51 | +Private m_OpenFilename As String |
| 52 | + |
| 53 | +'WBMP files use a very small header with no magic numbers, so we check a few key fields (including width/height) |
| 54 | +' when attempting to validate. |
| 55 | +Friend Function IsFileWBMP(ByRef srcFilename As String, Optional ByVal requireValidFileExtension As Boolean = True, Optional ByVal closeStreamWhenDone As Boolean = True) As Boolean |
| 56 | + |
| 57 | + Const FUNC_NAME As String = "IsFileWBMP" |
| 58 | + |
| 59 | + IsFileWBMP = False |
| 60 | + On Error GoTo BadWBMPFile |
| 61 | + |
| 62 | + m_OpenFilename = vbNullString |
| 63 | + m_Width = 0: m_Height = 0 |
| 64 | + |
| 65 | + Dim potentialMatch As Boolean |
| 66 | + potentialMatch = Files.FileExists(srcFilename) |
| 67 | + |
| 68 | + 'Check extension too, as requested. |
| 69 | + If (potentialMatch And requireValidFileExtension) Then |
| 70 | + potentialMatch = Strings.StringsEqual(Files.FileGetExtension(srcFilename), "wbmp", True) Or Strings.StringsEqual(Files.FileGetExtension(srcFilename), "wbm", True) |
| 71 | + End If |
| 72 | + |
| 73 | + 'If any of the failsafe checks failed, exit immediately |
| 74 | + If (Not potentialMatch) Then |
| 75 | + Exit Function |
| 76 | + ElseIf WBMP_DEBUG_VERBOSE Then |
| 77 | + PDDebug.LogAction "File might be WBMP. Opening image and attempting to validate..." |
| 78 | + End If |
| 79 | + |
| 80 | + 'WBMP files use an extremely simple header comprised of a series of VLQs |
| 81 | + ' (Wiki description of VLQs here: https://en.wikipedia.org/wiki/Variable-length_quantity) |
| 82 | + ' |
| 83 | + 'We want to read enough of the header to validate width/height. (It's only a few bytes!) |
| 84 | + |
| 85 | + 'Open a stream on the target file |
| 86 | + If (m_Stream Is Nothing) Then Set m_Stream = New pdStream |
| 87 | + If m_Stream.StartStream(PD_SM_FileMemoryMapped, PD_SA_ReadOnly, srcFilename, optimizeAccess:=OptimizeSequentialAccess) Then |
| 88 | + |
| 89 | + m_OpenFilename = srcFilename |
| 90 | + |
| 91 | + 'First byte is technically a VLQ, but per the spec, the only valid definition (from the working group) |
| 92 | + ' is 0. |
| 93 | + If (m_Stream.ReadByte() <> 0) Then Exit Function |
| 94 | + |
| 95 | + 'This is followed by a fixed header field and a variable number of optional extension header fields... |
| 96 | + ' ...but again, the only valid value the fixed header is 0. |
| 97 | + If (m_Stream.ReadByte() <> 0) Then Exit Function |
| 98 | + |
| 99 | + 'Finally we arrive at width and height, which are both encoded as VLQs |
| 100 | + m_Width = ReadVLQ(m_Stream) |
| 101 | + m_Height = ReadVLQ(m_Stream) |
| 102 | + |
| 103 | + '/Couldn't start stream; file may be locked or inaccessible |
| 104 | + Else |
| 105 | + GoTo BadWBMPFile |
| 106 | + End If |
| 107 | + |
| 108 | + 'After all that, ensure we have valid, non-zero width/height |
| 109 | + If (m_Width > 0) And (m_Height > 0) Then |
| 110 | + IsFileWBMP = True |
| 111 | + If WBMP_DEBUG_VERBOSE Then PDDebug.LogAction "File validates as WBMP!" |
| 112 | + End If |
| 113 | + |
| 114 | + 'Close the file stream before exiting |
| 115 | + If (Not m_Stream Is Nothing) And closeStreamWhenDone Then m_Stream.StopStream True |
| 116 | + |
| 117 | + Exit Function |
| 118 | + |
| 119 | +'On any parse error, this function jumps to this branch and simply closes the underlying file, then exits |
| 120 | +BadWBMPFile: |
| 121 | + |
| 122 | + Set m_Stream = Nothing |
| 123 | + InternalError FUNC_NAME, "critical parse failure" |
| 124 | + IsFileWBMP = False |
| 125 | + |
| 126 | +End Function |
| 127 | + |
| 128 | +'Validate and load a candidate WBMP file |
| 129 | +Friend Function LoadWBMP_FromFile(ByRef srcFile As String, ByRef dstImage As pdImage, ByRef dstDIB As pdDIB) As Boolean |
| 130 | + |
| 131 | + On Error GoTo BadWBMPFile |
| 132 | + |
| 133 | + Const FUNC_NAME As String = "LoadWBMP_FromFile" |
| 134 | + LoadWBMP_FromFile = False |
| 135 | + |
| 136 | + 'Validate the file and leave it open if validated successfully |
| 137 | + If Me.IsFileWBMP(srcFile, False, False) Then |
| 138 | + |
| 139 | + 'If validation passed, the width and height (if any) will be stored in m_width and m_height. |
| 140 | + If (m_Width <= 0) Or (m_Height <= 0) Then |
| 141 | + InternalError FUNC_NAME, "bad dimensions: " & m_Width & "x" & m_Height |
| 142 | + Set m_Stream = Nothing |
| 143 | + Exit Function |
| 144 | + End If |
| 145 | + |
| 146 | + If WBMP_DEBUG_VERBOSE Then |
| 147 | + PDDebug.LogAction "WBMP dimensions: " & m_Width & "x" & m_Height |
| 148 | + PDDebug.LogAction "Starting to parse pixel data..." |
| 149 | + End If |
| 150 | + |
| 151 | + 'We left the stream open after validation, so the stream pointer already points at pixel data! |
| 152 | + |
| 153 | + 'Prep image buffer; we'll dump intensity values straight into it. |
| 154 | + Set dstDIB = New pdDIB |
| 155 | + If dstDIB.CreateBlank(m_Width, m_Height, 32, vbWhite, 255) Then |
| 156 | + |
| 157 | + 'There's not a performance-friendly way to mask flags in VB, so let's just use a byte array for clarity |
| 158 | + Dim bitFlags(0 To 7) As Byte |
| 159 | + bitFlags(0) = 1 |
| 160 | + bitFlags(1) = 2 |
| 161 | + bitFlags(2) = 4 |
| 162 | + bitFlags(3) = 8 |
| 163 | + bitFlags(4) = 16 |
| 164 | + bitFlags(5) = 32 |
| 165 | + bitFlags(6) = 64 |
| 166 | + bitFlags(7) = 128 |
| 167 | + |
| 168 | + 'To avoid having to pull pixels out one-by-one (which is slow), |
| 169 | + ' grab the whole source data chunk as a local byte array. |
| 170 | + Dim srcPixels() As Byte, idxSrcByte As Long |
| 171 | + m_Stream.ReadBytes srcPixels, -1, True |
| 172 | + m_Stream.StopStream True |
| 173 | + |
| 174 | + 'We know how many pixels we should be addressing (based on the underlying width/height) |
| 175 | + Dim totalNumPixels As Long, numPixelsScanline As Long, curByte As Byte |
| 176 | + totalNumPixels = m_Width * m_Height |
| 177 | + |
| 178 | + 'Scanlines must be null-padded to end on byte boundaries. |
| 179 | + Dim maxPixelsScanline As Long |
| 180 | + maxPixelsScanline = Int((m_Width + 7) \ 8) * 8 |
| 181 | + |
| 182 | + 'Valiate the width/height against the size of the pixel data |
| 183 | + If (((maxPixelsScanline \ 8) * m_Height) > UBound(srcPixels)) Then |
| 184 | + InternalError FUNC_NAME, "not enough pixel data", True |
| 185 | + Exit Function |
| 186 | + End If |
| 187 | + |
| 188 | + 'We'll need to track an index into the source data; it'll be updated "as we go" |
| 189 | + idxSrcByte = 0 |
| 190 | + |
| 191 | + 'Wrap an array around the destination DIB. (This is unsafe, and must be manually |
| 192 | + ' freed before this function xits.) |
| 193 | + Dim imgPixels() As Long, imgSA As SafeArray1D |
| 194 | + dstDIB.WrapLongArrayAroundDIB_1D imgPixels, imgSA |
| 195 | + |
| 196 | + 'Start iterating bytes and converting bits to monochrome colors! |
| 197 | + Dim x As Long |
| 198 | + Do While (x < totalNumPixels) |
| 199 | + |
| 200 | + 'We don't need to validate these reads, as we already asserted source size in a previous step |
| 201 | + curByte = srcPixels(idxSrcByte) |
| 202 | + |
| 203 | + 'Parse each bit in turn |
| 204 | + Dim i As Long |
| 205 | + For i = 7 To 0 Step -1 |
| 206 | + |
| 207 | + 'Ignore empty bytes at the end of the image |
| 208 | + If (x < totalNumPixels) Then |
| 209 | + |
| 210 | + 'Ignore empty bytes at the end of each scanline |
| 211 | + If (numPixelsScanline < m_Width) Then |
| 212 | + |
| 213 | + 'Draw black bits into the image |
| 214 | + If ((curByte And bitFlags(i)) = 0) Then imgPixels(x) = &HFF000000 |
| 215 | + |
| 216 | + 'Increment pixel pointer |
| 217 | + x = x + 1 |
| 218 | + |
| 219 | + End If |
| 220 | + |
| 221 | + End If |
| 222 | + |
| 223 | + 'Keep track of how many pixels we've copied *on this scanline* |
| 224 | + numPixelsScanline = numPixelsScanline + 1 |
| 225 | + |
| 226 | + Next i |
| 227 | + |
| 228 | + 'If we've reached the end of a scanline, reset the scanline pixel counter |
| 229 | + If (numPixelsScanline >= maxPixelsScanline) Then numPixelsScanline = 0 |
| 230 | + |
| 231 | + 'Advance to the next byte |
| 232 | + idxSrcByte = idxSrcByte + 1 |
| 233 | + |
| 234 | + Loop |
| 235 | + |
| 236 | + 'Release our unsafe array wrapper |
| 237 | + dstDIB.UnwrapLongArrayFromDIB imgPixels |
| 238 | + |
| 239 | + 'File was loaded successfully! |
| 240 | + LoadWBMP_FromFile = True |
| 241 | + |
| 242 | + 'The returned data is always premultiplied |
| 243 | + If LoadWBMP_FromFile Then dstDIB.SetInitialAlphaPremultiplicationState True |
| 244 | + |
| 245 | + Else |
| 246 | + InternalError FUNC_NAME, "out of memory" |
| 247 | + Set m_Stream = Nothing |
| 248 | + Exit Function |
| 249 | + End If |
| 250 | + |
| 251 | + '/File is not WBMP; silently ignore it |
| 252 | + End If |
| 253 | + |
| 254 | + Exit Function |
| 255 | + |
| 256 | +BadWBMPFile: |
| 257 | + InternalError FUNC_NAME, "abandoned load due to critical error" |
| 258 | + LoadWBMP_FromFile = False |
| 259 | + |
| 260 | +End Function |
| 261 | + |
| 262 | +'Decode a "variable-length quantity" entry inside the target stream, starting at the current stream location. |
| 263 | +' VLQs are a way to encode 128-bit entries in a variable-length stream, by using the first bit of each byte |
| 264 | +' to indicate that additional bytes follow. You then keep reading bytes one-at-a-time, shifting each one |
| 265 | +' 7-bits left, until you arrive at a byte with a 0 in the first bit space. |
| 266 | +Private Function ReadVLQ(ByRef srcStream As pdStream) As Long |
| 267 | + |
| 268 | + Const FUNC_NAME As String = "ReadVLQ" |
| 269 | + |
| 270 | + On Error GoTo BadVLQ |
| 271 | + |
| 272 | + Dim numBytesPulled As Long |
| 273 | + ReadVLQ = 0: numBytesPulled = 0 |
| 274 | + |
| 275 | + 'Pull the next byte in, but stop if... |
| 276 | + ' 1) the end of stream is reached (otherwise we could loop eternally!) |
| 277 | + ' 2) too many bytes have been read |
| 278 | + Do While (srcStream.GetPosition < srcStream.GetStreamSize()) And (numBytesPulled < 5) |
| 279 | + |
| 280 | + Dim nextByte As Byte |
| 281 | + nextByte = srcStream.ReadByte() |
| 282 | + |
| 283 | + 'Add this byte to the running VLQ entry (but make sure to strip the flag bit) |
| 284 | + ReadVLQ = ReadVLQ Or (nextByte And &H7F) |
| 285 | + |
| 286 | + 'Check the flag bit and stop looping if this is the last entry |
| 287 | + If ((nextByte And &H80) = &H0) Then Exit Do |
| 288 | + |
| 289 | + 'Shift existing numerical data by 2^7 (remember - we're reading 128 bits at a time) |
| 290 | + ReadVLQ = ReadVLQ * 128 |
| 291 | + |
| 292 | + 'Track how many bytes we've pulled out, because this function can only hold up to 4-bytes at a time |
| 293 | + numBytesPulled = numBytesPulled + 1 |
| 294 | + |
| 295 | + Loop |
| 296 | + |
| 297 | + 'Auto-return whatever we've calculated so far |
| 298 | + Exit Function |
| 299 | + |
| 300 | +BadVLQ: |
| 301 | + ReadVLQ = 0 |
| 302 | + InternalError FUNC_NAME, "bad VLQ entry" |
| 303 | + |
| 304 | +End Function |
| 305 | + |
| 306 | +Private Sub InternalError(ByRef funcName As String, ByRef errDescription As String, Optional ByVal writeDebugLog As Boolean = True) |
| 307 | + If UserPrefs.GenerateDebugLogs Then |
| 308 | + If writeDebugLog Then PDDebug.LogAction "pdWBMP." & funcName & "() reported an error: " & errDescription |
| 309 | + Else |
| 310 | + Debug.Print "pdWBMP." & funcName & "() reported an error: " & errDescription |
| 311 | + End If |
| 312 | +End Sub |
| 313 | + |
| 314 | +'The underlying stream would auto-free naturally, but I like being tidy |
| 315 | +Private Sub Class_Terminate() |
| 316 | + If (Not m_Stream Is Nothing) Then |
| 317 | + If m_Stream.IsOpen Then m_Stream.StopStream True |
| 318 | + End If |
| 319 | +End Sub |
0 commit comments