I have the following function that I just can't get right. I am working on it again and again, and somehow something always turns out wrong.
I have encoded some audio data. The audio data is encoded in "frames" of 3 bytes each.
For example like this:
Frame #1
0
1
2
Frame #2
3
4
5
Frame #3
6
7
8
Now when I want to decode some audio (let's say from byte position 4 with the length of 3 bytes, I first have to calculate in which frame this audio would be found and how many frames I have to decode and what the offset in the decoded frame is.
In this case, I would have to read frame #2 and #3, and the offset would be 1.
I have tried to set up the following void:
int g_iByteSize1FrameDecoded = 3;
void CalcFrames(unsigned long uByteStart,unsigned long uByteCount,unsigned long &uStartFrame,unsigned long &uFramesToRead,unsigned long& uOffset)
{
////calculate in which decoded frame the byte from uByteStart would be found in
uStartFrame = ((uByteStart) / g_iByteSize1FrameDecoded) + 1;
unsigned long iEndFrame = ((uByteStart + uByteCount) / g_iByteSize1FrameDecoded) + 1;
uFramesToRead = (iEndFrame - uStartFrame + 1);
uOffset = (uByteStart) % g_iByteSize1FrameDecoded;
}
But it just doesn't work, something ALWAYS goes wrong... rounding, the math itself...
Could somebody with some math skills perhaps have a look where my error(s) could be?
Byte i is in frame i / 3 at offset i % 3:
void CalcFrames(unsigned long uByteStart,unsigned long uByteCount,unsigned long &uStartFrame,unsigned long &uFramesToRead,unsigned long& uOffset) {
uStartFrame = uByteStart / g_iByteSize1FrameDecoded + 1;
uOffset = uByteStart % g_iByteSize1FrameDecoded;
unsigned long lastFrame = (uByteStart + uByteCount - 1) / g_iByteSize1FrameDecoded + 1;
uFramesToRead = lastFrame - uStartFrame + 1;
}
I'm dubious about your decision to count frames and bytes starting from 1 rather than 0, but perhaps it works better for the rest of your code - I don't know.
As far as CalcFrames
goes, I can only see an issue with uOffset
. The calculation should be:
uOffset = (uByteStart % g_iByteSize1FrameDecoded) - 1;
For your example, the offset of byte 5 from the start of the frame is 1 byte. Your original calculation simply does 5 % 3 which is 2, hence the need to additionally subtract 1.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.