Repository navigation
Description
I assume that the code for Flip16,32,64 bits in sound.cpp is not efficient (or doesn't do what it should do): https://github.com/jamulussoftware/jamulus/blob/main/src/sound/asio/sound.cpp#L1168
I made some heuristic tests on what the function Flip16Bits outputs (Disclaimer: I haven't fully understood what the code exactly does) and it seems that all it does is a left shift by one. Thus, at least Flip16Bits can be simplified (and I assume it's the same for the other code).
By the function name, it could do a bitwise invert which it doesn't. Also it doesn't seem to flip the whole word around.
What confuses me most, is that the if statement doesn't flip anything. So it might well be a bug.
The following code outputs "ok", which I consider as proof that the function Flip16Bits can be implemented as leftshift by 1 only.
#include <cassert>
#include <cstdint>
#include <iostream>
#include <bitset>
using namespace std;
int32_t Flip32Bits(int32_t iIn) {
uint32_t iMask = ( static_cast<uint32_t> ( 1 ) << 31 );
int32_t iOut = 0;
for ( unsigned int i = 0; i < 32; i++ )
{
// copy current bit to correct position
iOut |= ( iIn & iMask ) ? 1 : 0;
// shift out value and mask by one bit
iOut <<= 1;
iMask >>= 1;
}
return iOut;
}
int32_t Flip32BitHist(int32_t iIn) {
return (iIn<<1);
}
int16_t Flip16Bits ( const int16_t iIn )
{
uint16_t iMask = ( 1 << 15 );
int16_t iOut = 0;
for ( unsigned int i = 0; i < 16; i++ )
{
// copy current bit to correct position
iOut |= ( iIn & iMask ) ? 1 : 0;
// shift out value and mask by one bit
iOut <<= 1;
iMask >>= 1;
}
return iOut;
}
int16_t Flip16BitsHist(const int16_t iIn) {
int16_t iOut = (iIn<< 1);
return iOut;
}
int64_t Flip64Bits ( const int64_t iIn )
{
uint64_t iMask = ( static_cast<uint64_t> ( 1 ) << 63 );
int64_t iOut = 0;
for ( unsigned int i = 0; i < 64; i++ )
{
// copy current bit to correct position
iOut |= ( iIn & iMask ) ? 1 : 0;
// shift out value and mask by one bit
iOut <<= 1;
iMask >>= 1;
}
return iOut;
}
int64_t Flip64BitHist(int64_t iIn) {
return (iIn << 1);
}
int main(int argc, char** argv) {
for (uint16_t check = 0;check<=(uint16_t)-1;check++) {
cout << bitset<16> (check) << endl;
//cout << b1 << endl;
//cout << bitset<16>(Flip16BitsHist(check)) << endl;
//cout << bitset<16>(Flip16Bits(check)) << endl << endl;
assert(Flip16BitsHist(check) == Flip16Bits(check));
//assert(Flip32Bits(check) == Flip32BitHist(check));
//assert(Flip64Bits(check) == Flip64BitHist(check));
//cout << check;
if (check == (uint16_t)-1) {// not so elegant termination!
break;
}
}
cout << "ok";
}
The other functions can't be tested this way as uint64_t is just too large to get an answer, thus analysis of the code is needed.
(I might run the 32 bit over night)
Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsTriage
Activity
[-]Improve performance of FlipNBits in sound.cpp[/-][+]Improve performance/correctness of FlipNBits in sound.cpp[/+]ann0see commentedon Jan 15, 2023
@corrados as you are probably most familiar with the Windows sound code: what should the FlipNBits functions do?
ann0see commentedon Jan 16, 2023
The 32 Bit code also seems to be equivalent.
The following program returns ok:
corrados commentedon Jan 16, 2023
As you can see in the code: "
// NOT YET TESTED" -> There are a lot of switch branches which are not tested. You need to have the correct hardware to test the code. I have written these functions to convert the ASIO formats in the Jamulus sample format but only a subset was actually tested by myself (i.e., the branches which my hardware has used).That's not good :-). These "FlipBits" functions were created to convert MSB <-> LSB format. If that does not work correctly, it should be fixed.
Maybe it makes sense to take a look at the implementation in Portaudio. They must have some similar code and I assume that these conversion functions are all tested.
ann0see commentedon Jan 17, 2023
As I probably don't have the hardware, I can't test either.
Ok. Thanks for the information. Does it swap endianness? Or can you give an example?
1100 0100 --> 1000 1000 (currently)
Do you want a reversal like:
1010 0001 -> 1000 0101
?
hoffie commentedon Jan 17, 2023
When considering changing them for solely performance reasons it might also make sense to validate whether the compiler doesn't already perform such optimizations.
corrados commentedon Jan 17, 2023
Yes, that was the intention.
ann0see commentedon Jan 17, 2023
Probably it's possible, but I think the code is invalid right now.
ann0see commentedon Jan 17, 2023
Found https://www.geeksforgeeks.org/c-program-to-rotate-bits-of-a-number/Probably https://www.geeksforgeeks.org/write-an-efficient-c-program-to-reverse-bits-of-a-number/ is what we search for.
softins commentedon Jan 17, 2023
I haven't yet studied the original code in Jamulus for reversing the order of bits, and don't know what impact it has on performance, but if the fastest performance would be beneficial, I would suggest using a lookup table of reversed bytes, with code such as the following:
Disclaimer: not tested.
ann0see commentedon Jan 25, 2023
Hmm. Agree. The lookup table approach is probably the fastest? We should verify that it actually does what we expect with a device.
True. If we find a way around turning the bits around, we could rewrite this part, sure.
softins commentedon Feb 11, 2024
I have just for the first time studied the existing flip bits code, and also run some tests, comparing the results with my lookup table functions above.
Yes, that is what it is actually doing, but not what it is intended to do, I'm sure. It appears that the intention is by shifting and masking to reverse the order of the bits. Any ASIO driver that returns MSB data needing to be reversed will not currently work with Jamulus at all. I don't know if there have been any such drivers in practice.
Here is the 16-bit function.
There are two main problems with this code:
iOutis being done after adding in the new bit, but should have been done before adding it. This means that after adding the last bit, the output value is still shifted once more. This is why the output is just the input shifted left by one bit.It would be straightforward to fix both of those problems to make the function work correctly:
And similarly for the 32-bit and 64-bit functions.
I'm not familiar with ASIO, but the question remains in my mind whether "MSB" data from ASIO actually needs the bits reversed, or just the bytes swapped, like network addresses do.
If indeed it is bit reversal that is needed, the existing functions, when corrected as above, are still very inefficient, with lots of looping and shifting. They should be replaced with the lookup table functions. I could raise a PR to do this soon.
softins commentedon Feb 11, 2024
I found a PDF for the ASIO SDK here.
mcfnord commentedon Jul 19, 2026
Root cause (per the request in #3804): your suspicion is right, and it goes further — there are two distinct defects here, verified by analysis plus an exhaustive test.
1. The implementation is broken exactly as you measured, for all three widths. The loop body is
— the shift comes after the OR on every iteration, including the last. So the bit captured on iteration k gets shifted (N−k) more times: the input MSB (captured first) is shifted out of the word entirely, and every input bit j lands at position j+1. Net effect:
FlipNBits(x) == x << 1for N = 16, 32, and 64 — not a bit reversal, not an invert, just a left shift that destroys the sign bit. No need to run the 64-bit case overnight: the argument above is width-independent, and I verified it empirically with the verbatim functions from sound.cpp#L1245-L1299 — exhaustive over all 2¹⁶ and all 2³² inputs, plus structured patterns and 10⁸ random values for 64-bit: all equalx << 1.2. Even a corrected bit reversal would still be the wrong operation. Every call site is an
ASIOST*MSBsample-format case — MSB here means big-endian byte order (ASIO SDK). The correct conversion is a byte swap (qFromBigEndian/__builtin_bswap16/32/64), not a whole-word bit reversal: bit-reversing a big-endian sample does not produce the little-endian value. TheASIOSTInt24MSBpath builds further on the wrong model ("because the bits are flipped, we do not have to perform the shift by 8 bits", #L868-L871).Why it has never bitten: every one of these branches is marked
NOT YET TESTEDand executes only for big-endian ASIO formats, which effectively don't occur on x86 Windows hardware — so the code is latent. If such a device ever appeared, audio would be corrupted (the current<<1alone is sign corruption at any hot signal, before the endianness error even matters).Correct fix shape: replace all three functions with byte swaps, and fix the Int24MSB paths to byte-swap the 3-byte sample and shift properly. Alternatively, since the branches are untested and likely unreachable in practice, they could return an "unsupported sample format" error instead — that's a maintainer call.