we received a bug report for the copy of CharLS that is part of the DCMTK:
I took a look at this file and I think that this is indeed a bug in CharLS.
The attached patch creates an EncoderStrategy instance and writes bits to it. This triggers the same assertion as the original test image. (Ignore my changes to encoderstrategy.h, that's just the debug output that I looked at for figuring this out):
encoderstrategy.h:95: void EncoderStrategy::AppendToBitStream(LONG, LONG): Assertion `bitpos >=0' failed.
My analsysis of what is going on is part of the patch, so be sure to read the comments. :-)
I tried to come up with a patch that fixes this. This is the following part of the diff:
- if (bitpos >= 0)
- if (bitpos > 0)
The idea here is that when 32 bits of input were read, we can Flush().
This should even fix a similar issue, where we have bitpos == 1 and add 31 input bits, so one bit gets added to valcurrent. If Flush() only writes out 30 bits, all the 30 bits of input left can go into the buffer.